loopzero-gateway-zalo-personal 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +4 -2
- package/dist/index.cjs +32 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +33 -5
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# loopzero-gateway-zalo-personal
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 414ebff: Deliver an inbound voice message (zca-js `msgType` `chat.voice`) with empty text and `event.audio`, typed `audio/mp4`. The recording is read on demand from the `href` zca-js reports, over HTTPS only and with no credential, up to 20 MiB within 30 s, and a failed read rejects with `InboundAudioReadError` naming a reason code, never the URL. Zalo reports no duration, so `durationSeconds` is 0. The `loopzero-gateway` peer floor is now 0.2.0.
|
|
8
|
+
|
|
3
9
|
## 0.3.1
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -34,8 +34,10 @@ await runner.start();
|
|
|
34
34
|
|
|
35
35
|
## Behaviour
|
|
36
36
|
|
|
37
|
-
- Inbound: direct (`channel.type` `dm`) and group text messages from others
|
|
38
|
-
|
|
37
|
+
- Inbound: direct (`channel.type` `dm`) and group text messages from others. A voice message
|
|
38
|
+
arrives with empty text and `event.audio` (`audio/mp4`), downloaded from its URL over HTTPS
|
|
39
|
+
only when `audio.read()` is called, up to 20 MiB. The account's own messages, repeats and
|
|
40
|
+
other non-text messages are dropped.
|
|
39
41
|
- Outbound: text only, in a direct chat or group by `channel.type`; markdown loses its markers; a
|
|
40
42
|
reply over 2000 characters goes as several messages. Attachments are refused with
|
|
41
43
|
`attachments_unsupported`.
|
package/dist/index.cjs
CHANGED
|
@@ -3,6 +3,27 @@
|
|
|
3
3
|
var loopzeroGateway = require('loopzero-gateway');
|
|
4
4
|
|
|
5
5
|
// src/adapter.ts
|
|
6
|
+
var VOICE_MESSAGE_TYPE = "chat.voice";
|
|
7
|
+
var ZALO_VOICE_MEDIA_TYPE = "audio/mp4";
|
|
8
|
+
function deferZaloVoice(msgType, content, fetchMedia) {
|
|
9
|
+
if (msgType !== VOICE_MESSAGE_TYPE || typeof content !== "object" || content === null) {
|
|
10
|
+
return void 0;
|
|
11
|
+
}
|
|
12
|
+
const href = content.href;
|
|
13
|
+
if (typeof href !== "string" || href.length === 0) return void 0;
|
|
14
|
+
return loopzeroGateway.deferInboundAudio({
|
|
15
|
+
platform: "zalo_personal",
|
|
16
|
+
mediaType: ZALO_VOICE_MEDIA_TYPE,
|
|
17
|
+
request: async (signal) => isHttps(href) ? fetchMedia(href, { signal }) : { reason: "insecure_url" }
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
function isHttps(url) {
|
|
21
|
+
try {
|
|
22
|
+
return new URL(url).protocol === "https:";
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
6
27
|
|
|
7
28
|
// src/refuse-attachments.ts
|
|
8
29
|
function refuseAttachments(out) {
|
|
@@ -196,7 +217,7 @@ var ZaloPersonalAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
|
196
217
|
}
|
|
197
218
|
onMessage(message) {
|
|
198
219
|
if (message.isSelf === true) return;
|
|
199
|
-
const event = toMessageEvent(message);
|
|
220
|
+
const event = toMessageEvent(message, this.opts.__fetch ?? fetch);
|
|
200
221
|
if (event === void 0) return;
|
|
201
222
|
if (!this.seen.add(event.id)) return;
|
|
202
223
|
void this.runHandler(this.handler, event).catch((err) => {
|
|
@@ -205,14 +226,15 @@ var ZaloPersonalAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
|
205
226
|
});
|
|
206
227
|
}
|
|
207
228
|
};
|
|
208
|
-
function toMessageEvent(message) {
|
|
229
|
+
function toMessageEvent(message, fetchMedia) {
|
|
209
230
|
const data = message.data;
|
|
210
231
|
const msgId = data?.msgId;
|
|
211
232
|
const from = data?.uidFrom;
|
|
212
233
|
if (typeof msgId !== "string" && typeof msgId !== "number" || typeof from !== "string" && typeof from !== "number" || typeof message.threadId !== "string") {
|
|
213
234
|
return void 0;
|
|
214
235
|
}
|
|
215
|
-
|
|
236
|
+
const content = contentOf(data, fetchMedia);
|
|
237
|
+
if (content === void 0) return void 0;
|
|
216
238
|
const group = message.type === THREAD_GROUP;
|
|
217
239
|
const name = typeof data.dName === "string" ? data.dName : "";
|
|
218
240
|
return {
|
|
@@ -220,8 +242,9 @@ function toMessageEvent(message) {
|
|
|
220
242
|
platform: "zalo_personal",
|
|
221
243
|
sender: { id: String(from), username: name },
|
|
222
244
|
channel: { id: message.threadId, type: group ? "group" : "dm" },
|
|
223
|
-
text:
|
|
245
|
+
text: content.text,
|
|
224
246
|
receivedAt: Date.now(),
|
|
247
|
+
...content.audio !== void 0 ? { audio: content.audio } : {},
|
|
225
248
|
zalo_personal: {
|
|
226
249
|
messageId: String(msgId),
|
|
227
250
|
threadId: message.threadId,
|
|
@@ -231,6 +254,11 @@ function toMessageEvent(message) {
|
|
|
231
254
|
}
|
|
232
255
|
};
|
|
233
256
|
}
|
|
257
|
+
function contentOf(data, fetchMedia) {
|
|
258
|
+
if (typeof data.content === "string") return { text: data.content };
|
|
259
|
+
const audio = deferZaloVoice(data.msgType, data.content, fetchMedia);
|
|
260
|
+
return audio === void 0 ? void 0 : { text: "", audio };
|
|
261
|
+
}
|
|
234
262
|
async function withTimeout(ms, work) {
|
|
235
263
|
let timer;
|
|
236
264
|
const deadline = new Promise((resolve) => {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/channel.ts"],"names":["chunkByGrapheme","B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ChB,IAAA,KAAS,EAAA,IACT,OAAO,SAAA,KAAc,QAAA,IACrB,cAAc,EAAA,EACd;AACA,IAAA,MAAM,OAAA,CAAQ,eAAe,oBAAoB,CAAA;AAAA,EACnD;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAU;AACnC;AAEA,SAAS,aAAa,MAAA,EAA4C;AAChE,EAAA,oBAAA,CAAqB,MAAA,EAAQ,EAAE,KAAA,EAAO,YAAA,EAAc,CAAA;AACpD,EAAA,MAAM,QAAQ,OAAA,CAAQ,YAAA;AAAA,IACpB,MAAA;AAAA,IACA;AAAA,GACF;AACA,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,gBAAgB,MAAM,CAAA;AAAA,IACnC,GAAI,KAAA,KAAU,MAAA,GAAY,EAAC,GAAI,EAAE,KAAA;AAAM,GACzC;AACF;AAWA,IAAM,MAAA,GAAqC;AAAA,EACzC;AAAA,IACE,GAAA,EAAK,aAAA;AAAA,IACL,QAAA,EAAU,IAAA;AAAA,IACV,MAAA,EAAQ,IAAA;AAAA,IACR,GAAA,EAAK,2BAAA;AAAA,IACL,WAAA,EACE;AAAA,GACJ;AAAA,EACA;AAAA,IACE,GAAA,EAAK,OAAA;AAAA,IACL,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EAAa;AAAA;AAEjB,CAAA;AAWO,IAAM,mBAAA,GAAsB;AAAA,EACjC,QAAA,EAAU,eAAA;AAAA,EACV,SAAA,EAAW,QAAA;AAAA,EACX,cAAA,EAAgB,eAAA;AAAA,EAChB,MAAA,EAAQ,MAAA;AAAA,EACR,OAAO,MAAA,EAAqC;AAC1C,IAAA,OAAO,IAAI,mBAAA,CAAoB,YAAA,CAAa,MAAM,CAAC,CAAA;AAAA,EACrD;AACF","file":"index.cjs","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `loopzero-gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"loopzero-gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"zalo_personal adapter cannot send attachments\",\n },\n };\n}\n","/**\n * Cut outbound text into Zalo messages.\n *\n * @public\n */\n\nimport { chunkByGrapheme } from \"loopzero-gateway\";\n\n/** The most characters one Zalo message carries. */\nexport const ZALO_PERSONAL_MESSAGE_LIMIT = 2000;\n\n/**\n * Split `text` into messages of at most 2000 characters, never inside a grapheme, in order.\n *\n * @returns the parts; empty for an empty text\n * @public\n */\nexport function splitForZaloPersonal(text: string): string[] {\n if (text.length === 0) return [];\n return chunkByGrapheme(text, { limit: ZALO_PERSONAL_MESSAGE_LIMIT }).filter(\n (part) => part.length > 0,\n );\n}\n","/**\n * `ZaloPersonalAdapter` — `BasePlatformAdapter` over a personal Zalo account, through the\n * unofficial `zca-js` web session.\n *\n * @public\n */\n\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n channelRendering,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n SeenIds,\n type SendResult,\n} from \"loopzero-gateway\";\n\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { splitForZaloPersonal, ZALO_PERSONAL_MESSAGE_LIMIT } from \"./split.js\";\nimport type {\n ZaloApi,\n ZaloListenerMessage,\n ZaloLogin,\n ZaloPersonalAdapterOptions,\n} from \"./types.js\";\n\nconst LABEL = \"gateway-zalo-personal\";\nconst CONNECT_TIMEOUT_MS = 30_000;\nconst SEND_TIMEOUT_MS = 30_000;\nconst THREAD_USER = 0;\nconst THREAD_GROUP = 1;\n\n/** The default login: `zca-js`, imported when first needed so it stays the consumer's install. */\nconst defaultLogin: ZaloLogin = async (credentials) => {\n const specifier = \"zca-js\";\n let mod: { Zalo?: new () => { login(c: unknown): Promise<ZaloApi> } };\n try {\n mod = (await import(specifier)) as typeof mod;\n } catch {\n throw new Error(\"the `zca-js` package is not installed; add it to use this adapter\");\n }\n if (mod.Zalo === undefined) throw new Error(\"`zca-js` does not export `Zalo`\");\n return new mod.Zalo().login(credentials);\n};\n\n/**\n * Zalo Personal adapter for one personal account.\n *\n * `connect()` logs in and starts the listener; it answers `true` once the listener is started and\n * `false`, never a throw, on a refused login, a missing `zca-js` or after 30000 ms. A direct or\n * group message from someone else becomes one `ZaloPersonalMessageEvent` (repeats by message id\n * are dropped). A reply longer than 2000 characters goes as several messages, in order.\n *\n * This is an unofficial client of a personal account: Zalo may restrict an account that automates.\n *\n * @public\n */\nexport class ZaloPersonalAdapter extends BasePlatformAdapter {\n readonly platform = \"zalo_personal\" as const;\n\n /** The platform facts; `maxMessageChars` is the splitter\\'s limit. */\n override get capabilities(): AdapterCapabilities {\n return { ...super.capabilities, maxMessageChars: ZALO_PERSONAL_MESSAGE_LIMIT };\n }\n private readonly opts: ZaloPersonalAdapterOptions;\n private handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private api: ZaloApi | undefined;\n private connected = false;\n private connecting: Promise<boolean> | undefined;\n /** Bumped by `disconnect()`, so a connect it overtook does not report connected. */\n private generation = 0;\n private readonly seen = new SeenIds();\n private warnedAboutHtml = false;\n\n /** @throws Error when `credentials` lacks an imei or a user agent */\n constructor(opts: ZaloPersonalAdapterOptions) {\n super();\n const c = opts.credentials;\n if (!c || typeof c.imei !== \"string\" || c.imei === \"\" || typeof c.userAgent !== \"string\") {\n throw new Error(`${LABEL}: credentials must hold a cookie, an imei and a userAgent`);\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n const attempt = this.open().finally(() => {\n if (this.connecting === attempt) this.connecting = undefined;\n });\n this.connecting = attempt;\n return attempt;\n }\n\n async disconnect(): Promise<void> {\n this.generation += 1;\n this.connected = false;\n this.connecting = undefined;\n this.stopListener();\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // Replace, not stack.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n /** Deliver an event that arrived out of band, through `runHandler`. */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n const api = this.api;\n if (!this.connected || api === undefined) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"ZaloPersonalAdapter.connect() has not succeeded\",\n },\n };\n }\n if (out.channel.id === \"\") {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: \"channel.id must be a thread id\" },\n };\n }\n const type = out.channel.type === \"group\" ? THREAD_GROUP : THREAD_USER;\n const parts = splitForZaloPersonal(this.textFor(out));\n const answer = await withTimeout(SEND_TIMEOUT_MS, async () => {\n let messageId = \"\";\n for (const text of parts) {\n const sent = await api.sendMessage({ msg: text }, out.channel.id, type);\n const id = sent?.message?.msgId;\n messageId = id === undefined || id === null ? messageId : String(id);\n }\n return messageId;\n }).catch((err: unknown) => ({ failure: messageOf(err) }));\n if (answer === \"timeout\") {\n return {\n ok: false,\n error: { code: \"timeout\", message: `Zalo did not answer within ${SEND_TIMEOUT_MS} ms` },\n };\n }\n if (typeof answer === \"object\") {\n return { ok: false, error: { code: \"zalo_send_failed\", message: answer.failure } };\n }\n return { ok: true, messageId: answer };\n }\n\n /** The text to send: markdown loses its markers, html goes as is with one warning. */\n private textFor(out: OutboundMessage): string {\n if (out.format === \"markdown\") return channelRendering(this.platform).translate(out.text);\n if (out.format === \"html\" && !this.warnedAboutHtml) {\n this.warnedAboutHtml = true;\n process.stderr.write(\n `[${LABEL}] format=\"html\" was declared and Zalo is plain text; sending the text unchanged. Logged once.\\n`,\n );\n }\n return out.text;\n }\n\n private async open(): Promise<boolean> {\n const generation = this.generation;\n const login = this.opts.login ?? defaultLogin;\n const result = await withTimeout(CONNECT_TIMEOUT_MS, async () => {\n const api = await login(this.opts.credentials);\n if (generation !== this.generation) return false;\n api.listener.on(\"message\", (message) => this.onMessage(message));\n api.listener.on(\"error\", (err) =>\n process.stderr.write(`[${LABEL}] listener error: ${messageOf(err)}\\n`),\n );\n api.listener.on(\"closed\", (code, reason) => {\n if (api === this.api) this.connected = false;\n process.stderr.write(`[${LABEL}] listener closed: ${code} ${reason}\\n`);\n });\n api.listener.start();\n this.api = api;\n return true;\n }).catch((err: unknown) => {\n process.stderr.write(`[${LABEL}] connect failed: ${messageOf(err)}\\n`);\n return false as const;\n });\n if (result === true && generation === this.generation) {\n this.connected = true;\n return true;\n }\n if (result === \"timeout\") {\n process.stderr.write(\n `[${LABEL}] connect failed: no answer within ${CONNECT_TIMEOUT_MS} ms\\n`,\n );\n }\n if (generation === this.generation) this.stopListener();\n return false;\n }\n\n private stopListener(): void {\n const api = this.api;\n this.api = undefined;\n try {\n api?.listener.stop();\n } catch (err) {\n process.stderr.write(`[${LABEL}] listener stop failed: ${messageOf(err)}\\n`);\n }\n }\n\n private onMessage(message: ZaloListenerMessage): void {\n if (message.isSelf === true) return;\n const event = toMessageEvent(message);\n if (event === undefined) return;\n if (!this.seen.add(event.id)) return;\n void this.runHandler(this.handler, event).catch((err: unknown) => {\n process.stderr.write(`[${LABEL}] handler threw: ${messageOf(err)}\\n`);\n });\n }\n}\n\nfunction toMessageEvent(message: ZaloListenerMessage): GatewayMessageEvent | undefined {\n const data = message.data;\n const msgId = data?.msgId;\n const from = data?.uidFrom;\n if (\n (typeof msgId !== \"string\" && typeof msgId !== \"number\") ||\n (typeof from !== \"string\" && typeof from !== \"number\") ||\n typeof message.threadId !== \"string\"\n ) {\n return undefined;\n }\n // Only plain text: a sticker, an image or a card has an object for content.\n if (typeof data.content !== \"string\") return undefined;\n const group = message.type === THREAD_GROUP;\n const name = typeof data.dName === \"string\" ? data.dName : \"\";\n return {\n id: String(msgId),\n platform: \"zalo_personal\",\n sender: { id: String(from), username: name },\n channel: { id: message.threadId, type: group ? \"group\" : \"dm\" },\n text: data.content,\n receivedAt: Date.now(),\n zalo_personal: {\n messageId: String(msgId),\n threadId: message.threadId,\n threadType: group ? \"group\" : \"user\",\n senderUid: String(from),\n raw: message,\n },\n };\n}\n\n/** Run `work`; `\"timeout\"` once `ms` passes first. */\nasync function withTimeout<T>(ms: number, work: () => Promise<T>): Promise<T | \"timeout\"> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), ms);\n });\n try {\n return await Promise.race([work(), deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","/**\n * `zaloPersonalChannel` — the Zalo personal channel described as data, with env bindings.\n *\n * Typed locally on purpose (as `telegramChannel` is): a published `.d.ts` naming a core type an\n * older peer lacks would break a consumer on that floor. The object is structurally a\n * `ChannelDescriptor`.\n */\n\nimport { channelConfigReaders } from \"loopzero-gateway\";\n\nimport { ZaloPersonalAdapter } from \"./adapter.js\";\nimport type { ZaloCredentials, ZaloPersonalAdapterOptions } from \"./types.js\";\n\nconst PREFIX = \"gateway-zalo-personal\";\n\ntype Config = Readonly<Record<string, unknown>>;\n\nconst readers = channelConfigReaders(PREFIX);\nconst { invalid } = readers;\n\n/**\n * The shared readers treat `null` (and `\"\"`) as absent. A value the caller supplied must not fall\n * back to a default silently: `null` is refused for every key, `\"\"` for those that are not strings.\n */\nfunction refuseSuppliedAbsent(config: Config, keys: Readonly<Record<string, string>>): void {\n for (const [key, expected] of Object.entries(keys)) {\n const value = config[key];\n if (value === null || (value === \"\" && expected !== \"a string\")) throw invalid(key, expected);\n }\n}\n\nconst EXPECTED_CREDENTIALS = \"an object with a cookie, an imei and a userAgent, or its JSON text\";\n\n/** The credentials as an object, or the JSON text of one (what an environment variable gives). */\nfunction readCredentials(config: Config): ZaloCredentials {\n let value = config.credentials;\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch {\n throw invalid(\"credentials\", \"valid JSON text of the web session\");\n }\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw invalid(\"credentials\", EXPECTED_CREDENTIALS);\n }\n const c = value as Record<string, unknown>;\n const { cookie, imei, userAgent } = c;\n if (\n cookie === undefined ||\n cookie === null ||\n typeof imei !== \"string\" ||\n imei === \"\" ||\n typeof userAgent !== \"string\" ||\n userAgent === \"\"\n ) {\n throw invalid(\"credentials\", EXPECTED_CREDENTIALS);\n }\n return { cookie, imei, userAgent };\n}\n\nfunction buildOptions(config: Config): ZaloPersonalAdapterOptions {\n refuseSuppliedAbsent(config, { login: \"a function\" });\n const login = readers.readFunction<NonNullable<ZaloPersonalAdapterOptions[\"login\"]>>(\n config,\n \"login\",\n );\n return {\n credentials: readCredentials(config),\n ...(login === undefined ? {} : { login }),\n };\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n readonly env?: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"credentials\",\n required: true,\n secret: true,\n env: \"ZALO_PERSONAL_CREDENTIALS\",\n description:\n \"The account's web session ({ cookie, imei, userAgent }): an object, or its JSON text.\",\n },\n {\n key: \"login\",\n required: false,\n secret: false,\n description: \"Programmatic only: replaces the zca-js login.\",\n },\n];\n\n/**\n * The Zalo personal channel: the adapter opens its own listener in `connect()`.\n *\n * `create` validates each value, then builds the adapter; it makes no network call. A wrongly typed\n * value or credentials that are not valid JSON throw a `GatewayConfigurationError` coded\n * `invalid_config` with the prefix `gateway-zalo-personal`.\n *\n * @public\n */\nexport const zaloPersonalChannel = {\n platform: \"zalo_personal\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Config): ZaloPersonalAdapter {\n return new ZaloPersonalAdapter(buildOptions(config));\n },\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/read-audio.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/channel.ts"],"names":["deferInboundAudio","chunkByGrapheme","BasePlatformAdapter","SeenIds","channelRendering","channelConfigReaders"],"mappings":";;;;;AAoBA,IAAM,kBAAA,GAAqB,YAAA;AAG3B,IAAM,qBAAA,GAAwB,WAAA;AAavB,SAAS,cAAA,CACd,OAAA,EACA,OAAA,EACA,UAAA,EAC0B;AAC1B,EAAA,IAAI,YAAY,kBAAA,IAAsB,OAAO,OAAA,KAAY,QAAA,IAAY,YAAY,IAAA,EAAM;AACrF,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,OAAQ,OAAA,CAA+B,IAAA;AAC7C,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,CAAK,MAAA,KAAW,GAAG,OAAO,MAAA;AAC1D,EAAA,OAAOA,iCAAA,CAAkB;AAAA,IACvB,QAAA,EAAU,eAAA;AAAA,IACV,SAAA,EAAW,qBAAA;AAAA,IACX,OAAA,EAAS,OAAO,MAAA,KACd,OAAA,CAAQ,IAAI,CAAA,GAAI,UAAA,CAAW,IAAA,EAAM,EAAE,MAAA,EAAQ,CAAA,GAAI,EAAE,QAAQ,cAAA;AAAe,GAC3E,CAAA;AACH;AAEA,SAAS,QAAQ,GAAA,E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AAAA,IACL,QAAA,EAAU,IAAA;AAAA,IACV,MAAA,EAAQ,IAAA;AAAA,IACR,GAAA,EAAK,2BAAA;AAAA,IACL,WAAA,EACE;AAAA,GACJ;AAAA,EACA;AAAA,IACE,GAAA,EAAK,OAAA;AAAA,IACL,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EAAa;AAAA;AAEjB,CAAA;AAWO,IAAM,mBAAA,GAAsB;AAAA,EACjC,QAAA,EAAU,eAAA;AAAA,EACV,SAAA,EAAW,QAAA;AAAA,EACX,cAAA,EAAgB,eAAA;AAAA,EAChB,MAAA,EAAQ,MAAA;AAAA,EACR,OAAO,MAAA,EAAqC;AAC1C,IAAA,OAAO,IAAI,mBAAA,CAAoB,YAAA,CAAa,MAAM,CAAC,CAAA;AAAA,EACrD;AACF","file":"index.cjs","sourcesContent":["/**\n * The audio of an inbound Zalo voice message, read on demand as `event.audio` (row H-2).\n *\n * `zca-js` reports a voice message with `data.msgType` `\"chat.voice\"` and an attachment object as\n * `data.content`, whose `href` is the URL of the recording (`TMessage` and `TAttachmentContent`\n * in `dist/models/Message.d.ts`, and `getClientMessageType` in `dist/utils.js`, of zca-js 2.4.0,\n * https://github.com/RFS-ADRENO/zca-js, read 2026-12-03). The library's own `sendVoice` sends a\n * voice message by passing its URL as `m4aUrl`, so the recording is M4A (AAC in an MP4\n * container), whose registered media type is `audio/mp4`. The message reports no duration and no\n * size, so `durationSeconds` is 0 and the size is counted while the bytes arrive.\n *\n * The URL is fetched over HTTPS only and with no credential: the session cookie never leaves\n * `zca-js`. The read goes through `deferInboundAudio`: nothing is requested until `read()`, at\n * most 20 MiB within 30 s, and a failure rejects with `InboundAudioReadError` naming a reason\n * code, never the URL.\n */\n\nimport { deferInboundAudio, type InboundAudio } from \"loopzero-gateway\";\n\n/** The `msgType` zca-js gives a voice message. */\nconst VOICE_MESSAGE_TYPE = \"chat.voice\";\n\n/** The media type of a Zalo voice message: M4A, as zca-js's `sendVoice` names it. */\nconst ZALO_VOICE_MEDIA_TYPE = \"audio/mp4\";\n\n/**\n * The `fetch` an inbound voice message is read with.\n *\n * @internal\n */\nexport type ZaloMediaFetch = (url: string, init: RequestInit) => Promise<Response>;\n\n/**\n * The deferred audio of a message whose `msgType` is `chat.voice` and whose content names an\n * `href`, or `undefined` for anything else.\n */\nexport function deferZaloVoice(\n msgType: unknown,\n content: unknown,\n fetchMedia: ZaloMediaFetch,\n): InboundAudio | undefined {\n if (msgType !== VOICE_MESSAGE_TYPE || typeof content !== \"object\" || content === null) {\n return undefined;\n }\n const href = (content as { href?: unknown }).href;\n if (typeof href !== \"string\" || href.length === 0) return undefined;\n return deferInboundAudio({\n platform: \"zalo_personal\",\n mediaType: ZALO_VOICE_MEDIA_TYPE,\n request: async (signal) =>\n isHttps(href) ? fetchMedia(href, { signal }) : { reason: \"insecure_url\" },\n });\n}\n\nfunction isHttps(url: string): boolean {\n try {\n return new URL(url).protocol === \"https:\";\n } catch {\n // An unparseable URL is not an https one; the caller refuses it with a reason code.\n return false;\n }\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `loopzero-gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"loopzero-gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"zalo_personal adapter cannot send attachments\",\n },\n };\n}\n","/**\n * Cut outbound text into Zalo messages.\n *\n * @public\n */\n\nimport { chunkByGrapheme } from \"loopzero-gateway\";\n\n/** The most characters one Zalo message carries. */\nexport const ZALO_PERSONAL_MESSAGE_LIMIT = 2000;\n\n/**\n * Split `text` into messages of at most 2000 characters, never inside a grapheme, in order.\n *\n * @returns the parts; empty for an empty text\n * @public\n */\nexport function splitForZaloPersonal(text: string): string[] {\n if (text.length === 0) return [];\n return chunkByGrapheme(text, { limit: ZALO_PERSONAL_MESSAGE_LIMIT }).filter(\n (part) => part.length > 0,\n );\n}\n","/**\n * `ZaloPersonalAdapter` — `BasePlatformAdapter` over a personal Zalo account, through the\n * unofficial `zca-js` web session.\n *\n * @public\n */\n\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n channelRendering,\n type MessageEvent as GatewayMessageEvent,\n type InboundAudio,\n type OutboundMessage,\n SeenIds,\n type SendResult,\n} from \"loopzero-gateway\";\n\nimport { deferZaloVoice, type ZaloMediaFetch } from \"./read-audio.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { splitForZaloPersonal, ZALO_PERSONAL_MESSAGE_LIMIT } from \"./split.js\";\nimport type {\n ZaloApi,\n ZaloListenerMessage,\n ZaloLogin,\n ZaloPersonalAdapterOptions,\n} from \"./types.js\";\n\nconst LABEL = \"gateway-zalo-personal\";\nconst CONNECT_TIMEOUT_MS = 30_000;\nconst SEND_TIMEOUT_MS = 30_000;\nconst THREAD_USER = 0;\nconst THREAD_GROUP = 1;\n\n/** The default login: `zca-js`, imported when first needed so it stays the consumer's install. */\nconst defaultLogin: ZaloLogin = async (credentials) => {\n const specifier = \"zca-js\";\n let mod: { Zalo?: new () => { login(c: unknown): Promise<ZaloApi> } };\n try {\n mod = (await import(specifier)) as typeof mod;\n } catch {\n throw new Error(\"the `zca-js` package is not installed; add it to use this adapter\");\n }\n if (mod.Zalo === undefined) throw new Error(\"`zca-js` does not export `Zalo`\");\n return new mod.Zalo().login(credentials);\n};\n\n/**\n * Zalo Personal adapter for one personal account.\n *\n * `connect()` logs in and starts the listener; it answers `true` once the listener is started and\n * `false`, never a throw, on a refused login, a missing `zca-js` or after 30000 ms. A direct or\n * group message from someone else becomes one `ZaloPersonalMessageEvent` (repeats by message id\n * are dropped): a text message with its text, a voice message with empty text and `event.audio`,\n * read from the recording's URL only when `audio.read()` is called. A reply longer than 2000 characters goes as several messages, in order.\n *\n * This is an unofficial client of a personal account: Zalo may restrict an account that automates.\n *\n * @public\n */\nexport class ZaloPersonalAdapter extends BasePlatformAdapter {\n readonly platform = \"zalo_personal\" as const;\n\n /** The platform facts; `maxMessageChars` is the splitter\\'s limit. */\n override get capabilities(): AdapterCapabilities {\n return { ...super.capabilities, maxMessageChars: ZALO_PERSONAL_MESSAGE_LIMIT };\n }\n private readonly opts: ZaloPersonalAdapterOptions;\n private handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private api: ZaloApi | undefined;\n private connected = false;\n private connecting: Promise<boolean> | undefined;\n /** Bumped by `disconnect()`, so a connect it overtook does not report connected. */\n private generation = 0;\n private readonly seen = new SeenIds();\n private warnedAboutHtml = false;\n\n /** @throws Error when `credentials` lacks an imei or a user agent */\n constructor(opts: ZaloPersonalAdapterOptions) {\n super();\n const c = opts.credentials;\n if (!c || typeof c.imei !== \"string\" || c.imei === \"\" || typeof c.userAgent !== \"string\") {\n throw new Error(`${LABEL}: credentials must hold a cookie, an imei and a userAgent`);\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n const attempt = this.open().finally(() => {\n if (this.connecting === attempt) this.connecting = undefined;\n });\n this.connecting = attempt;\n return attempt;\n }\n\n async disconnect(): Promise<void> {\n this.generation += 1;\n this.connected = false;\n this.connecting = undefined;\n this.stopListener();\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // Replace, not stack.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n /** Deliver an event that arrived out of band, through `runHandler`. */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n const api = this.api;\n if (!this.connected || api === undefined) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"ZaloPersonalAdapter.connect() has not succeeded\",\n },\n };\n }\n if (out.channel.id === \"\") {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: \"channel.id must be a thread id\" },\n };\n }\n const type = out.channel.type === \"group\" ? THREAD_GROUP : THREAD_USER;\n const parts = splitForZaloPersonal(this.textFor(out));\n const answer = await withTimeout(SEND_TIMEOUT_MS, async () => {\n let messageId = \"\";\n for (const text of parts) {\n const sent = await api.sendMessage({ msg: text }, out.channel.id, type);\n const id = sent?.message?.msgId;\n messageId = id === undefined || id === null ? messageId : String(id);\n }\n return messageId;\n }).catch((err: unknown) => ({ failure: messageOf(err) }));\n if (answer === \"timeout\") {\n return {\n ok: false,\n error: { code: \"timeout\", message: `Zalo did not answer within ${SEND_TIMEOUT_MS} ms` },\n };\n }\n if (typeof answer === \"object\") {\n return { ok: false, error: { code: \"zalo_send_failed\", message: answer.failure } };\n }\n return { ok: true, messageId: answer };\n }\n\n /** The text to send: markdown loses its markers, html goes as is with one warning. */\n private textFor(out: OutboundMessage): string {\n if (out.format === \"markdown\") return channelRendering(this.platform).translate(out.text);\n if (out.format === \"html\" && !this.warnedAboutHtml) {\n this.warnedAboutHtml = true;\n process.stderr.write(\n `[${LABEL}] format=\"html\" was declared and Zalo is plain text; sending the text unchanged. Logged once.\\n`,\n );\n }\n return out.text;\n }\n\n private async open(): Promise<boolean> {\n const generation = this.generation;\n const login = this.opts.login ?? defaultLogin;\n const result = await withTimeout(CONNECT_TIMEOUT_MS, async () => {\n const api = await login(this.opts.credentials);\n if (generation !== this.generation) return false;\n api.listener.on(\"message\", (message) => this.onMessage(message));\n api.listener.on(\"error\", (err) =>\n process.stderr.write(`[${LABEL}] listener error: ${messageOf(err)}\\n`),\n );\n api.listener.on(\"closed\", (code, reason) => {\n if (api === this.api) this.connected = false;\n process.stderr.write(`[${LABEL}] listener closed: ${code} ${reason}\\n`);\n });\n api.listener.start();\n this.api = api;\n return true;\n }).catch((err: unknown) => {\n process.stderr.write(`[${LABEL}] connect failed: ${messageOf(err)}\\n`);\n return false as const;\n });\n if (result === true && generation === this.generation) {\n this.connected = true;\n return true;\n }\n if (result === \"timeout\") {\n process.stderr.write(\n `[${LABEL}] connect failed: no answer within ${CONNECT_TIMEOUT_MS} ms\\n`,\n );\n }\n if (generation === this.generation) this.stopListener();\n return false;\n }\n\n private stopListener(): void {\n const api = this.api;\n this.api = undefined;\n try {\n api?.listener.stop();\n } catch (err) {\n process.stderr.write(`[${LABEL}] listener stop failed: ${messageOf(err)}\\n`);\n }\n }\n\n private onMessage(message: ZaloListenerMessage): void {\n if (message.isSelf === true) return;\n const event = toMessageEvent(message, this.opts.__fetch ?? fetch);\n if (event === undefined) return;\n if (!this.seen.add(event.id)) return;\n void this.runHandler(this.handler, event).catch((err: unknown) => {\n process.stderr.write(`[${LABEL}] handler threw: ${messageOf(err)}\\n`);\n });\n }\n}\n\nfunction toMessageEvent(\n message: ZaloListenerMessage,\n fetchMedia: ZaloMediaFetch,\n): GatewayMessageEvent | undefined {\n const data = message.data;\n const msgId = data?.msgId;\n const from = data?.uidFrom;\n if (\n (typeof msgId !== \"string\" && typeof msgId !== \"number\") ||\n (typeof from !== \"string\" && typeof from !== \"number\") ||\n typeof message.threadId !== \"string\"\n ) {\n return undefined;\n }\n const content = contentOf(data, fetchMedia);\n if (content === undefined) return undefined;\n const group = message.type === THREAD_GROUP;\n const name = typeof data.dName === \"string\" ? data.dName : \"\";\n return {\n id: String(msgId),\n platform: \"zalo_personal\",\n sender: { id: String(from), username: name },\n channel: { id: message.threadId, type: group ? \"group\" : \"dm\" },\n text: content.text,\n receivedAt: Date.now(),\n ...(content.audio !== undefined ? { audio: content.audio } : {}),\n zalo_personal: {\n messageId: String(msgId),\n threadId: message.threadId,\n threadType: group ? \"group\" : \"user\",\n senderUid: String(from),\n raw: message,\n },\n };\n}\n\n/**\n * The text of a plain-text message, or empty text and the audio of a voice message (row H-2);\n * `undefined` for a sticker, an image, a card or anything else whose content is an object.\n */\nfunction contentOf(\n data: ZaloListenerMessage[\"data\"],\n fetchMedia: ZaloMediaFetch,\n): { text: string; audio?: InboundAudio } | undefined {\n if (typeof data.content === \"string\") return { text: data.content };\n const audio = deferZaloVoice(data.msgType, data.content, fetchMedia);\n return audio === undefined ? undefined : { text: \"\", audio };\n}\n\n/** Run `work`; `\"timeout\"` once `ms` passes first. */\nasync function withTimeout<T>(ms: number, work: () => Promise<T>): Promise<T | \"timeout\"> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), ms);\n });\n try {\n return await Promise.race([work(), deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","/**\n * `zaloPersonalChannel` — the Zalo personal channel described as data, with env bindings.\n *\n * Typed locally on purpose (as `telegramChannel` is): a published `.d.ts` naming a core type an\n * older peer lacks would break a consumer on that floor. The object is structurally a\n * `ChannelDescriptor`.\n */\n\nimport { channelConfigReaders } from \"loopzero-gateway\";\n\nimport { ZaloPersonalAdapter } from \"./adapter.js\";\nimport type { ZaloCredentials, ZaloPersonalAdapterOptions } from \"./types.js\";\n\nconst PREFIX = \"gateway-zalo-personal\";\n\ntype Config = Readonly<Record<string, unknown>>;\n\nconst readers = channelConfigReaders(PREFIX);\nconst { invalid } = readers;\n\n/**\n * The shared readers treat `null` (and `\"\"`) as absent. A value the caller supplied must not fall\n * back to a default silently: `null` is refused for every key, `\"\"` for those that are not strings.\n */\nfunction refuseSuppliedAbsent(config: Config, keys: Readonly<Record<string, string>>): void {\n for (const [key, expected] of Object.entries(keys)) {\n const value = config[key];\n if (value === null || (value === \"\" && expected !== \"a string\")) throw invalid(key, expected);\n }\n}\n\nconst EXPECTED_CREDENTIALS = \"an object with a cookie, an imei and a userAgent, or its JSON text\";\n\n/** The credentials as an object, or the JSON text of one (what an environment variable gives). */\nfunction readCredentials(config: Config): ZaloCredentials {\n let value = config.credentials;\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch {\n throw invalid(\"credentials\", \"valid JSON text of the web session\");\n }\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw invalid(\"credentials\", EXPECTED_CREDENTIALS);\n }\n const c = value as Record<string, unknown>;\n const { cookie, imei, userAgent } = c;\n if (\n cookie === undefined ||\n cookie === null ||\n typeof imei !== \"string\" ||\n imei === \"\" ||\n typeof userAgent !== \"string\" ||\n userAgent === \"\"\n ) {\n throw invalid(\"credentials\", EXPECTED_CREDENTIALS);\n }\n return { cookie, imei, userAgent };\n}\n\nfunction buildOptions(config: Config): ZaloPersonalAdapterOptions {\n refuseSuppliedAbsent(config, { login: \"a function\" });\n const login = readers.readFunction<NonNullable<ZaloPersonalAdapterOptions[\"login\"]>>(\n config,\n \"login\",\n );\n return {\n credentials: readCredentials(config),\n ...(login === undefined ? {} : { login }),\n };\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n readonly env?: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"credentials\",\n required: true,\n secret: true,\n env: \"ZALO_PERSONAL_CREDENTIALS\",\n description:\n \"The account's web session ({ cookie, imei, userAgent }): an object, or its JSON text.\",\n },\n {\n key: \"login\",\n required: false,\n secret: false,\n description: \"Programmatic only: replaces the zca-js login.\",\n },\n];\n\n/**\n * The Zalo personal channel: the adapter opens its own listener in `connect()`.\n *\n * `create` validates each value, then builds the adapter; it makes no network call. A wrongly typed\n * value or credentials that are not valid JSON throw a `GatewayConfigurationError` coded\n * `invalid_config` with the prefix `gateway-zalo-personal`.\n *\n * @public\n */\nexport const zaloPersonalChannel = {\n platform: \"zalo_personal\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Config): ZaloPersonalAdapter {\n return new ZaloPersonalAdapter(buildOptions(config));\n },\n};\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -33,6 +33,9 @@ interface ZaloListenerMessage {
|
|
|
33
33
|
readonly msgId?: unknown;
|
|
34
34
|
readonly uidFrom?: unknown;
|
|
35
35
|
readonly dName?: unknown;
|
|
36
|
+
/** `"webchat"` for text, `"chat.voice"` for a voice message, and so on. */
|
|
37
|
+
readonly msgType?: unknown;
|
|
38
|
+
/** A string for text; an object for an attachment, whose `href` is a voice message's URL. */
|
|
36
39
|
readonly content?: unknown;
|
|
37
40
|
};
|
|
38
41
|
}
|
|
@@ -93,7 +96,8 @@ interface ZaloPersonalAdapterOptions {
|
|
|
93
96
|
* `connect()` logs in and starts the listener; it answers `true` once the listener is started and
|
|
94
97
|
* `false`, never a throw, on a refused login, a missing `zca-js` or after 30000 ms. A direct or
|
|
95
98
|
* group message from someone else becomes one `ZaloPersonalMessageEvent` (repeats by message id
|
|
96
|
-
* are dropped)
|
|
99
|
+
* are dropped): a text message with its text, a voice message with empty text and `event.audio`,
|
|
100
|
+
* read from the recording's URL only when `audio.read()` is called. A reply longer than 2000 characters goes as several messages, in order.
|
|
97
101
|
*
|
|
98
102
|
* This is an unofficial client of a personal account: Zalo may restrict an account that automates.
|
|
99
103
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -33,6 +33,9 @@ interface ZaloListenerMessage {
|
|
|
33
33
|
readonly msgId?: unknown;
|
|
34
34
|
readonly uidFrom?: unknown;
|
|
35
35
|
readonly dName?: unknown;
|
|
36
|
+
/** `"webchat"` for text, `"chat.voice"` for a voice message, and so on. */
|
|
37
|
+
readonly msgType?: unknown;
|
|
38
|
+
/** A string for text; an object for an attachment, whose `href` is a voice message's URL. */
|
|
36
39
|
readonly content?: unknown;
|
|
37
40
|
};
|
|
38
41
|
}
|
|
@@ -93,7 +96,8 @@ interface ZaloPersonalAdapterOptions {
|
|
|
93
96
|
* `connect()` logs in and starts the listener; it answers `true` once the listener is started and
|
|
94
97
|
* `false`, never a throw, on a refused login, a missing `zca-js` or after 30000 ms. A direct or
|
|
95
98
|
* group message from someone else becomes one `ZaloPersonalMessageEvent` (repeats by message id
|
|
96
|
-
* are dropped)
|
|
99
|
+
* are dropped): a text message with its text, a voice message with empty text and `event.audio`,
|
|
100
|
+
* read from the recording's URL only when `audio.read()` is called. A reply longer than 2000 characters goes as several messages, in order.
|
|
97
101
|
*
|
|
98
102
|
* This is an unofficial client of a personal account: Zalo may restrict an account that automates.
|
|
99
103
|
*
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
|
-
import { channelConfigReaders, chunkByGrapheme, BasePlatformAdapter, SeenIds, channelRendering } from 'loopzero-gateway';
|
|
1
|
+
import { channelConfigReaders, chunkByGrapheme, BasePlatformAdapter, SeenIds, channelRendering, deferInboundAudio } from 'loopzero-gateway';
|
|
2
2
|
|
|
3
3
|
// src/adapter.ts
|
|
4
|
+
var VOICE_MESSAGE_TYPE = "chat.voice";
|
|
5
|
+
var ZALO_VOICE_MEDIA_TYPE = "audio/mp4";
|
|
6
|
+
function deferZaloVoice(msgType, content, fetchMedia) {
|
|
7
|
+
if (msgType !== VOICE_MESSAGE_TYPE || typeof content !== "object" || content === null) {
|
|
8
|
+
return void 0;
|
|
9
|
+
}
|
|
10
|
+
const href = content.href;
|
|
11
|
+
if (typeof href !== "string" || href.length === 0) return void 0;
|
|
12
|
+
return deferInboundAudio({
|
|
13
|
+
platform: "zalo_personal",
|
|
14
|
+
mediaType: ZALO_VOICE_MEDIA_TYPE,
|
|
15
|
+
request: async (signal) => isHttps(href) ? fetchMedia(href, { signal }) : { reason: "insecure_url" }
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
function isHttps(url) {
|
|
19
|
+
try {
|
|
20
|
+
return new URL(url).protocol === "https:";
|
|
21
|
+
} catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
4
25
|
|
|
5
26
|
// src/refuse-attachments.ts
|
|
6
27
|
function refuseAttachments(out) {
|
|
@@ -194,7 +215,7 @@ var ZaloPersonalAdapter = class extends BasePlatformAdapter {
|
|
|
194
215
|
}
|
|
195
216
|
onMessage(message) {
|
|
196
217
|
if (message.isSelf === true) return;
|
|
197
|
-
const event = toMessageEvent(message);
|
|
218
|
+
const event = toMessageEvent(message, this.opts.__fetch ?? fetch);
|
|
198
219
|
if (event === void 0) return;
|
|
199
220
|
if (!this.seen.add(event.id)) return;
|
|
200
221
|
void this.runHandler(this.handler, event).catch((err) => {
|
|
@@ -203,14 +224,15 @@ var ZaloPersonalAdapter = class extends BasePlatformAdapter {
|
|
|
203
224
|
});
|
|
204
225
|
}
|
|
205
226
|
};
|
|
206
|
-
function toMessageEvent(message) {
|
|
227
|
+
function toMessageEvent(message, fetchMedia) {
|
|
207
228
|
const data = message.data;
|
|
208
229
|
const msgId = data?.msgId;
|
|
209
230
|
const from = data?.uidFrom;
|
|
210
231
|
if (typeof msgId !== "string" && typeof msgId !== "number" || typeof from !== "string" && typeof from !== "number" || typeof message.threadId !== "string") {
|
|
211
232
|
return void 0;
|
|
212
233
|
}
|
|
213
|
-
|
|
234
|
+
const content = contentOf(data, fetchMedia);
|
|
235
|
+
if (content === void 0) return void 0;
|
|
214
236
|
const group = message.type === THREAD_GROUP;
|
|
215
237
|
const name = typeof data.dName === "string" ? data.dName : "";
|
|
216
238
|
return {
|
|
@@ -218,8 +240,9 @@ function toMessageEvent(message) {
|
|
|
218
240
|
platform: "zalo_personal",
|
|
219
241
|
sender: { id: String(from), username: name },
|
|
220
242
|
channel: { id: message.threadId, type: group ? "group" : "dm" },
|
|
221
|
-
text:
|
|
243
|
+
text: content.text,
|
|
222
244
|
receivedAt: Date.now(),
|
|
245
|
+
...content.audio !== void 0 ? { audio: content.audio } : {},
|
|
223
246
|
zalo_personal: {
|
|
224
247
|
messageId: String(msgId),
|
|
225
248
|
threadId: message.threadId,
|
|
@@ -229,6 +252,11 @@ function toMessageEvent(message) {
|
|
|
229
252
|
}
|
|
230
253
|
};
|
|
231
254
|
}
|
|
255
|
+
function contentOf(data, fetchMedia) {
|
|
256
|
+
if (typeof data.content === "string") return { text: data.content };
|
|
257
|
+
const audio = deferZaloVoice(data.msgType, data.content, fetchMedia);
|
|
258
|
+
return audio === void 0 ? void 0 : { text: "", audio };
|
|
259
|
+
}
|
|
232
260
|
async function withTimeout(ms, work) {
|
|
233
261
|
let timer;
|
|
234
262
|
const deadline = new Promise((resolve) => {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/channel.ts"],"names":[],"mappings":";;;;;AAmBO,SAAS,kBAAkB,GAAA,EAA8C;AAC9E,EAAA,IAAI,IAAI,WAAA,IAAe,IAAA,IAAQ,IAAI,WAAA,CAAY,MAAA,KAAW,GAAG,OAAO,MAAA;AACpE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO;AAAA,MACL,IAAA,EAAM,yBAAA;AAAA,MACN,OAAA,EAAS;AAAA;AACX,GACF;AACF;ACnBO,IAAM,2BAAA,GAA8B;AAQpC,SAAS,qBAAqB,IAAA,EAAwB;AAC3D,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AAC/B,EAAA,OAAO,gBAAgB,IAAA,EAAM,EAAE,KAAA,EAAO,2BAAA,EAA6B,CAAA,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M,MAAA,GAAqC;AAAA,EACzC;AAAA,IACE,GAAA,EAAK,aAAA;AAAA,IACL,QAAA,EAAU,IAAA;AAAA,IACV,MAAA,EAAQ,IAAA;AAAA,IACR,GAAA,EAAK,2BAAA;AAAA,IACL,WAAA,EACE;AAAA,GACJ;AAAA,EACA;AAAA,IACE,GAAA,EAAK,OAAA;AAAA,IACL,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EAAa;AAAA;AAEjB,CAAA;AAWO,IAAM,mBAAA,GAAsB;AAAA,EACjC,QAAA,EAAU,eAAA;AAAA,EACV,SAAA,EAAW,QAAA;AAAA,EACX,cAAA,EAAgB,eAAA;AAAA,EAChB,MAAA,EAAQ,MAAA;AAAA,EACR,OAAO,MAAA,EAAqC;AAC1C,IAAA,OAAO,IAAI,mBAAA,CAAoB,YAAA,CAAa,MAAM,CAAC,CAAA;AAAA,EACrD;AACF","file":"index.js","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `loopzero-gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"loopzero-gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"zalo_personal adapter cannot send attachments\",\n },\n };\n}\n","/**\n * Cut outbound text into Zalo messages.\n *\n * @public\n */\n\nimport { chunkByGrapheme } from \"loopzero-gateway\";\n\n/** The most characters one Zalo message carries. */\nexport const ZALO_PERSONAL_MESSAGE_LIMIT = 2000;\n\n/**\n * Split `text` into messages of at most 2000 characters, never inside a grapheme, in order.\n *\n * @returns the parts; empty for an empty text\n * @public\n */\nexport function splitForZaloPersonal(text: string): string[] {\n if (text.length === 0) return [];\n return chunkByGrapheme(text, { limit: ZALO_PERSONAL_MESSAGE_LIMIT }).filter(\n (part) => part.length > 0,\n );\n}\n","/**\n * `ZaloPersonalAdapter` — `BasePlatformAdapter` over a personal Zalo account, through the\n * unofficial `zca-js` web session.\n *\n * @public\n */\n\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n channelRendering,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n SeenIds,\n type SendResult,\n} from \"loopzero-gateway\";\n\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { splitForZaloPersonal, ZALO_PERSONAL_MESSAGE_LIMIT } from \"./split.js\";\nimport type {\n ZaloApi,\n ZaloListenerMessage,\n ZaloLogin,\n ZaloPersonalAdapterOptions,\n} from \"./types.js\";\n\nconst LABEL = \"gateway-zalo-personal\";\nconst CONNECT_TIMEOUT_MS = 30_000;\nconst SEND_TIMEOUT_MS = 30_000;\nconst THREAD_USER = 0;\nconst THREAD_GROUP = 1;\n\n/** The default login: `zca-js`, imported when first needed so it stays the consumer's install. */\nconst defaultLogin: ZaloLogin = async (credentials) => {\n const specifier = \"zca-js\";\n let mod: { Zalo?: new () => { login(c: unknown): Promise<ZaloApi> } };\n try {\n mod = (await import(specifier)) as typeof mod;\n } catch {\n throw new Error(\"the `zca-js` package is not installed; add it to use this adapter\");\n }\n if (mod.Zalo === undefined) throw new Error(\"`zca-js` does not export `Zalo`\");\n return new mod.Zalo().login(credentials);\n};\n\n/**\n * Zalo Personal adapter for one personal account.\n *\n * `connect()` logs in and starts the listener; it answers `true` once the listener is started and\n * `false`, never a throw, on a refused login, a missing `zca-js` or after 30000 ms. A direct or\n * group message from someone else becomes one `ZaloPersonalMessageEvent` (repeats by message id\n * are dropped). A reply longer than 2000 characters goes as several messages, in order.\n *\n * This is an unofficial client of a personal account: Zalo may restrict an account that automates.\n *\n * @public\n */\nexport class ZaloPersonalAdapter extends BasePlatformAdapter {\n readonly platform = \"zalo_personal\" as const;\n\n /** The platform facts; `maxMessageChars` is the splitter\\'s limit. */\n override get capabilities(): AdapterCapabilities {\n return { ...super.capabilities, maxMessageChars: ZALO_PERSONAL_MESSAGE_LIMIT };\n }\n private readonly opts: ZaloPersonalAdapterOptions;\n private handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private api: ZaloApi | undefined;\n private connected = false;\n private connecting: Promise<boolean> | undefined;\n /** Bumped by `disconnect()`, so a connect it overtook does not report connected. */\n private generation = 0;\n private readonly seen = new SeenIds();\n private warnedAboutHtml = false;\n\n /** @throws Error when `credentials` lacks an imei or a user agent */\n constructor(opts: ZaloPersonalAdapterOptions) {\n super();\n const c = opts.credentials;\n if (!c || typeof c.imei !== \"string\" || c.imei === \"\" || typeof c.userAgent !== \"string\") {\n throw new Error(`${LABEL}: credentials must hold a cookie, an imei and a userAgent`);\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n const attempt = this.open().finally(() => {\n if (this.connecting === attempt) this.connecting = undefined;\n });\n this.connecting = attempt;\n return attempt;\n }\n\n async disconnect(): Promise<void> {\n this.generation += 1;\n this.connected = false;\n this.connecting = undefined;\n this.stopListener();\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // Replace, not stack.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n /** Deliver an event that arrived out of band, through `runHandler`. */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n const api = this.api;\n if (!this.connected || api === undefined) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"ZaloPersonalAdapter.connect() has not succeeded\",\n },\n };\n }\n if (out.channel.id === \"\") {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: \"channel.id must be a thread id\" },\n };\n }\n const type = out.channel.type === \"group\" ? THREAD_GROUP : THREAD_USER;\n const parts = splitForZaloPersonal(this.textFor(out));\n const answer = await withTimeout(SEND_TIMEOUT_MS, async () => {\n let messageId = \"\";\n for (const text of parts) {\n const sent = await api.sendMessage({ msg: text }, out.channel.id, type);\n const id = sent?.message?.msgId;\n messageId = id === undefined || id === null ? messageId : String(id);\n }\n return messageId;\n }).catch((err: unknown) => ({ failure: messageOf(err) }));\n if (answer === \"timeout\") {\n return {\n ok: false,\n error: { code: \"timeout\", message: `Zalo did not answer within ${SEND_TIMEOUT_MS} ms` },\n };\n }\n if (typeof answer === \"object\") {\n return { ok: false, error: { code: \"zalo_send_failed\", message: answer.failure } };\n }\n return { ok: true, messageId: answer };\n }\n\n /** The text to send: markdown loses its markers, html goes as is with one warning. */\n private textFor(out: OutboundMessage): string {\n if (out.format === \"markdown\") return channelRendering(this.platform).translate(out.text);\n if (out.format === \"html\" && !this.warnedAboutHtml) {\n this.warnedAboutHtml = true;\n process.stderr.write(\n `[${LABEL}] format=\"html\" was declared and Zalo is plain text; sending the text unchanged. Logged once.\\n`,\n );\n }\n return out.text;\n }\n\n private async open(): Promise<boolean> {\n const generation = this.generation;\n const login = this.opts.login ?? defaultLogin;\n const result = await withTimeout(CONNECT_TIMEOUT_MS, async () => {\n const api = await login(this.opts.credentials);\n if (generation !== this.generation) return false;\n api.listener.on(\"message\", (message) => this.onMessage(message));\n api.listener.on(\"error\", (err) =>\n process.stderr.write(`[${LABEL}] listener error: ${messageOf(err)}\\n`),\n );\n api.listener.on(\"closed\", (code, reason) => {\n if (api === this.api) this.connected = false;\n process.stderr.write(`[${LABEL}] listener closed: ${code} ${reason}\\n`);\n });\n api.listener.start();\n this.api = api;\n return true;\n }).catch((err: unknown) => {\n process.stderr.write(`[${LABEL}] connect failed: ${messageOf(err)}\\n`);\n return false as const;\n });\n if (result === true && generation === this.generation) {\n this.connected = true;\n return true;\n }\n if (result === \"timeout\") {\n process.stderr.write(\n `[${LABEL}] connect failed: no answer within ${CONNECT_TIMEOUT_MS} ms\\n`,\n );\n }\n if (generation === this.generation) this.stopListener();\n return false;\n }\n\n private stopListener(): void {\n const api = this.api;\n this.api = undefined;\n try {\n api?.listener.stop();\n } catch (err) {\n process.stderr.write(`[${LABEL}] listener stop failed: ${messageOf(err)}\\n`);\n }\n }\n\n private onMessage(message: ZaloListenerMessage): void {\n if (message.isSelf === true) return;\n const event = toMessageEvent(message);\n if (event === undefined) return;\n if (!this.seen.add(event.id)) return;\n void this.runHandler(this.handler, event).catch((err: unknown) => {\n process.stderr.write(`[${LABEL}] handler threw: ${messageOf(err)}\\n`);\n });\n }\n}\n\nfunction toMessageEvent(message: ZaloListenerMessage): GatewayMessageEvent | undefined {\n const data = message.data;\n const msgId = data?.msgId;\n const from = data?.uidFrom;\n if (\n (typeof msgId !== \"string\" && typeof msgId !== \"number\") ||\n (typeof from !== \"string\" && typeof from !== \"number\") ||\n typeof message.threadId !== \"string\"\n ) {\n return undefined;\n }\n // Only plain text: a sticker, an image or a card has an object for content.\n if (typeof data.content !== \"string\") return undefined;\n const group = message.type === THREAD_GROUP;\n const name = typeof data.dName === \"string\" ? data.dName : \"\";\n return {\n id: String(msgId),\n platform: \"zalo_personal\",\n sender: { id: String(from), username: name },\n channel: { id: message.threadId, type: group ? \"group\" : \"dm\" },\n text: data.content,\n receivedAt: Date.now(),\n zalo_personal: {\n messageId: String(msgId),\n threadId: message.threadId,\n threadType: group ? \"group\" : \"user\",\n senderUid: String(from),\n raw: message,\n },\n };\n}\n\n/** Run `work`; `\"timeout\"` once `ms` passes first. */\nasync function withTimeout<T>(ms: number, work: () => Promise<T>): Promise<T | \"timeout\"> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), ms);\n });\n try {\n return await Promise.race([work(), deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","/**\n * `zaloPersonalChannel` — the Zalo personal channel described as data, with env bindings.\n *\n * Typed locally on purpose (as `telegramChannel` is): a published `.d.ts` naming a core type an\n * older peer lacks would break a consumer on that floor. The object is structurally a\n * `ChannelDescriptor`.\n */\n\nimport { channelConfigReaders } from \"loopzero-gateway\";\n\nimport { ZaloPersonalAdapter } from \"./adapter.js\";\nimport type { ZaloCredentials, ZaloPersonalAdapterOptions } from \"./types.js\";\n\nconst PREFIX = \"gateway-zalo-personal\";\n\ntype Config = Readonly<Record<string, unknown>>;\n\nconst readers = channelConfigReaders(PREFIX);\nconst { invalid } = readers;\n\n/**\n * The shared readers treat `null` (and `\"\"`) as absent. A value the caller supplied must not fall\n * back to a default silently: `null` is refused for every key, `\"\"` for those that are not strings.\n */\nfunction refuseSuppliedAbsent(config: Config, keys: Readonly<Record<string, string>>): void {\n for (const [key, expected] of Object.entries(keys)) {\n const value = config[key];\n if (value === null || (value === \"\" && expected !== \"a string\")) throw invalid(key, expected);\n }\n}\n\nconst EXPECTED_CREDENTIALS = \"an object with a cookie, an imei and a userAgent, or its JSON text\";\n\n/** The credentials as an object, or the JSON text of one (what an environment variable gives). */\nfunction readCredentials(config: Config): ZaloCredentials {\n let value = config.credentials;\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch {\n throw invalid(\"credentials\", \"valid JSON text of the web session\");\n }\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw invalid(\"credentials\", EXPECTED_CREDENTIALS);\n }\n const c = value as Record<string, unknown>;\n const { cookie, imei, userAgent } = c;\n if (\n cookie === undefined ||\n cookie === null ||\n typeof imei !== \"string\" ||\n imei === \"\" ||\n typeof userAgent !== \"string\" ||\n userAgent === \"\"\n ) {\n throw invalid(\"credentials\", EXPECTED_CREDENTIALS);\n }\n return { cookie, imei, userAgent };\n}\n\nfunction buildOptions(config: Config): ZaloPersonalAdapterOptions {\n refuseSuppliedAbsent(config, { login: \"a function\" });\n const login = readers.readFunction<NonNullable<ZaloPersonalAdapterOptions[\"login\"]>>(\n config,\n \"login\",\n );\n return {\n credentials: readCredentials(config),\n ...(login === undefined ? {} : { login }),\n };\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n readonly env?: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"credentials\",\n required: true,\n secret: true,\n env: \"ZALO_PERSONAL_CREDENTIALS\",\n description:\n \"The account's web session ({ cookie, imei, userAgent }): an object, or its JSON text.\",\n },\n {\n key: \"login\",\n required: false,\n secret: false,\n description: \"Programmatic only: replaces the zca-js login.\",\n },\n];\n\n/**\n * The Zalo personal channel: the adapter opens its own listener in `connect()`.\n *\n * `create` validates each value, then builds the adapter; it makes no network call. A wrongly typed\n * value or credentials that are not valid JSON throw a `GatewayConfigurationError` coded\n * `invalid_config` with the prefix `gateway-zalo-personal`.\n *\n * @public\n */\nexport const zaloPersonalChannel = {\n platform: \"zalo_personal\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Config): ZaloPersonalAdapter {\n return new ZaloPersonalAdapter(buildOptions(config));\n },\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/read-audio.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts","../src/channel.ts"],"names":[],"mappings":";;;AAoBA,IAAM,kBAAA,GAAqB,YAAA;AAG3B,IAAM,qBAAA,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QAAA,IAChB,IAAA,KAAS,EAAA,IACT,OAAO,SAAA,KAAc,QAAA,IACrB,cAAc,EAAA,EACd;AACA,IAAA,MAAM,OAAA,CAAQ,eAAe,oBAAoB,CAAA;AAAA,EACnD;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAU;AACnC;AAEA,SAAS,aAAa,MAAA,EAA4C;AAChE,EAAA,oBAAA,CAAqB,MAAA,EAAQ,EAAE,KAAA,EAAO,YAAA,EAAc,CAAA;AACpD,EAAA,MAAM,QAAQ,OAAA,CAAQ,YAAA;AAAA,IACpB,MAAA;AAAA,IACA;AAAA,GACF;AACA,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,gBAAgB,MAAM,CAAA;AAAA,IACnC,GAAI,KAAA,KAAU,MAAA,GAAY,EAAC,GAAI,EAAE,KAAA;AAAM,GACzC;AACF;AAWA,IAAM,MAAA,GAAqC;AAAA,EACzC;AAAA,IACE,GAAA,EAAK,aAAA;AAAA,IACL,QAAA,EAAU,IAAA;AAAA,IACV,MAAA,EAAQ,IAAA;AAAA,IACR,GAAA,EAAK,2BAAA;AAAA,IACL,WAAA,EACE;AAAA,GACJ;AAAA,EACA;AAAA,IACE,GAAA,EAAK,OAAA;AAAA,IACL,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EAAa;AAAA;AAEjB,CAAA;AAWO,IAAM,mBAAA,GAAsB;AAAA,EACjC,QAAA,EAAU,eAAA;AAAA,EACV,SAAA,EAAW,QAAA;AAAA,EACX,cAAA,EAAgB,eAAA;AAAA,EAChB,MAAA,EAAQ,MAAA;AAAA,EACR,OAAO,MAAA,EAAqC;AAC1C,IAAA,OAAO,IAAI,mBAAA,CAAoB,YAAA,CAAa,MAAM,CAAC,CAAA;AAAA,EACrD;AACF","file":"index.js","sourcesContent":["/**\n * The audio of an inbound Zalo voice message, read on demand as `event.audio` (row H-2).\n *\n * `zca-js` reports a voice message with `data.msgType` `\"chat.voice\"` and an attachment object as\n * `data.content`, whose `href` is the URL of the recording (`TMessage` and `TAttachmentContent`\n * in `dist/models/Message.d.ts`, and `getClientMessageType` in `dist/utils.js`, of zca-js 2.4.0,\n * https://github.com/RFS-ADRENO/zca-js, read 2026-12-03). The library's own `sendVoice` sends a\n * voice message by passing its URL as `m4aUrl`, so the recording is M4A (AAC in an MP4\n * container), whose registered media type is `audio/mp4`. The message reports no duration and no\n * size, so `durationSeconds` is 0 and the size is counted while the bytes arrive.\n *\n * The URL is fetched over HTTPS only and with no credential: the session cookie never leaves\n * `zca-js`. The read goes through `deferInboundAudio`: nothing is requested until `read()`, at\n * most 20 MiB within 30 s, and a failure rejects with `InboundAudioReadError` naming a reason\n * code, never the URL.\n */\n\nimport { deferInboundAudio, type InboundAudio } from \"loopzero-gateway\";\n\n/** The `msgType` zca-js gives a voice message. */\nconst VOICE_MESSAGE_TYPE = \"chat.voice\";\n\n/** The media type of a Zalo voice message: M4A, as zca-js's `sendVoice` names it. */\nconst ZALO_VOICE_MEDIA_TYPE = \"audio/mp4\";\n\n/**\n * The `fetch` an inbound voice message is read with.\n *\n * @internal\n */\nexport type ZaloMediaFetch = (url: string, init: RequestInit) => Promise<Response>;\n\n/**\n * The deferred audio of a message whose `msgType` is `chat.voice` and whose content names an\n * `href`, or `undefined` for anything else.\n */\nexport function deferZaloVoice(\n msgType: unknown,\n content: unknown,\n fetchMedia: ZaloMediaFetch,\n): InboundAudio | undefined {\n if (msgType !== VOICE_MESSAGE_TYPE || typeof content !== \"object\" || content === null) {\n return undefined;\n }\n const href = (content as { href?: unknown }).href;\n if (typeof href !== \"string\" || href.length === 0) return undefined;\n return deferInboundAudio({\n platform: \"zalo_personal\",\n mediaType: ZALO_VOICE_MEDIA_TYPE,\n request: async (signal) =>\n isHttps(href) ? fetchMedia(href, { signal }) : { reason: \"insecure_url\" },\n });\n}\n\nfunction isHttps(url: string): boolean {\n try {\n return new URL(url).protocol === \"https:\";\n } catch {\n // An unparseable URL is not an https one; the caller refuses it with a reason code.\n return false;\n }\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `loopzero-gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"loopzero-gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"zalo_personal adapter cannot send attachments\",\n },\n };\n}\n","/**\n * Cut outbound text into Zalo messages.\n *\n * @public\n */\n\nimport { chunkByGrapheme } from \"loopzero-gateway\";\n\n/** The most characters one Zalo message carries. */\nexport const ZALO_PERSONAL_MESSAGE_LIMIT = 2000;\n\n/**\n * Split `text` into messages of at most 2000 characters, never inside a grapheme, in order.\n *\n * @returns the parts; empty for an empty text\n * @public\n */\nexport function splitForZaloPersonal(text: string): string[] {\n if (text.length === 0) return [];\n return chunkByGrapheme(text, { limit: ZALO_PERSONAL_MESSAGE_LIMIT }).filter(\n (part) => part.length > 0,\n );\n}\n","/**\n * `ZaloPersonalAdapter` — `BasePlatformAdapter` over a personal Zalo account, through the\n * unofficial `zca-js` web session.\n *\n * @public\n */\n\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n channelRendering,\n type MessageEvent as GatewayMessageEvent,\n type InboundAudio,\n type OutboundMessage,\n SeenIds,\n type SendResult,\n} from \"loopzero-gateway\";\n\nimport { deferZaloVoice, type ZaloMediaFetch } from \"./read-audio.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { splitForZaloPersonal, ZALO_PERSONAL_MESSAGE_LIMIT } from \"./split.js\";\nimport type {\n ZaloApi,\n ZaloListenerMessage,\n ZaloLogin,\n ZaloPersonalAdapterOptions,\n} from \"./types.js\";\n\nconst LABEL = \"gateway-zalo-personal\";\nconst CONNECT_TIMEOUT_MS = 30_000;\nconst SEND_TIMEOUT_MS = 30_000;\nconst THREAD_USER = 0;\nconst THREAD_GROUP = 1;\n\n/** The default login: `zca-js`, imported when first needed so it stays the consumer's install. */\nconst defaultLogin: ZaloLogin = async (credentials) => {\n const specifier = \"zca-js\";\n let mod: { Zalo?: new () => { login(c: unknown): Promise<ZaloApi> } };\n try {\n mod = (await import(specifier)) as typeof mod;\n } catch {\n throw new Error(\"the `zca-js` package is not installed; add it to use this adapter\");\n }\n if (mod.Zalo === undefined) throw new Error(\"`zca-js` does not export `Zalo`\");\n return new mod.Zalo().login(credentials);\n};\n\n/**\n * Zalo Personal adapter for one personal account.\n *\n * `connect()` logs in and starts the listener; it answers `true` once the listener is started and\n * `false`, never a throw, on a refused login, a missing `zca-js` or after 30000 ms. A direct or\n * group message from someone else becomes one `ZaloPersonalMessageEvent` (repeats by message id\n * are dropped): a text message with its text, a voice message with empty text and `event.audio`,\n * read from the recording's URL only when `audio.read()` is called. A reply longer than 2000 characters goes as several messages, in order.\n *\n * This is an unofficial client of a personal account: Zalo may restrict an account that automates.\n *\n * @public\n */\nexport class ZaloPersonalAdapter extends BasePlatformAdapter {\n readonly platform = \"zalo_personal\" as const;\n\n /** The platform facts; `maxMessageChars` is the splitter\\'s limit. */\n override get capabilities(): AdapterCapabilities {\n return { ...super.capabilities, maxMessageChars: ZALO_PERSONAL_MESSAGE_LIMIT };\n }\n private readonly opts: ZaloPersonalAdapterOptions;\n private handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private api: ZaloApi | undefined;\n private connected = false;\n private connecting: Promise<boolean> | undefined;\n /** Bumped by `disconnect()`, so a connect it overtook does not report connected. */\n private generation = 0;\n private readonly seen = new SeenIds();\n private warnedAboutHtml = false;\n\n /** @throws Error when `credentials` lacks an imei or a user agent */\n constructor(opts: ZaloPersonalAdapterOptions) {\n super();\n const c = opts.credentials;\n if (!c || typeof c.imei !== \"string\" || c.imei === \"\" || typeof c.userAgent !== \"string\") {\n throw new Error(`${LABEL}: credentials must hold a cookie, an imei and a userAgent`);\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n const attempt = this.open().finally(() => {\n if (this.connecting === attempt) this.connecting = undefined;\n });\n this.connecting = attempt;\n return attempt;\n }\n\n async disconnect(): Promise<void> {\n this.generation += 1;\n this.connected = false;\n this.connecting = undefined;\n this.stopListener();\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // Replace, not stack.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n /** Deliver an event that arrived out of band, through `runHandler`. */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n const api = this.api;\n if (!this.connected || api === undefined) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"ZaloPersonalAdapter.connect() has not succeeded\",\n },\n };\n }\n if (out.channel.id === \"\") {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: \"channel.id must be a thread id\" },\n };\n }\n const type = out.channel.type === \"group\" ? THREAD_GROUP : THREAD_USER;\n const parts = splitForZaloPersonal(this.textFor(out));\n const answer = await withTimeout(SEND_TIMEOUT_MS, async () => {\n let messageId = \"\";\n for (const text of parts) {\n const sent = await api.sendMessage({ msg: text }, out.channel.id, type);\n const id = sent?.message?.msgId;\n messageId = id === undefined || id === null ? messageId : String(id);\n }\n return messageId;\n }).catch((err: unknown) => ({ failure: messageOf(err) }));\n if (answer === \"timeout\") {\n return {\n ok: false,\n error: { code: \"timeout\", message: `Zalo did not answer within ${SEND_TIMEOUT_MS} ms` },\n };\n }\n if (typeof answer === \"object\") {\n return { ok: false, error: { code: \"zalo_send_failed\", message: answer.failure } };\n }\n return { ok: true, messageId: answer };\n }\n\n /** The text to send: markdown loses its markers, html goes as is with one warning. */\n private textFor(out: OutboundMessage): string {\n if (out.format === \"markdown\") return channelRendering(this.platform).translate(out.text);\n if (out.format === \"html\" && !this.warnedAboutHtml) {\n this.warnedAboutHtml = true;\n process.stderr.write(\n `[${LABEL}] format=\"html\" was declared and Zalo is plain text; sending the text unchanged. Logged once.\\n`,\n );\n }\n return out.text;\n }\n\n private async open(): Promise<boolean> {\n const generation = this.generation;\n const login = this.opts.login ?? defaultLogin;\n const result = await withTimeout(CONNECT_TIMEOUT_MS, async () => {\n const api = await login(this.opts.credentials);\n if (generation !== this.generation) return false;\n api.listener.on(\"message\", (message) => this.onMessage(message));\n api.listener.on(\"error\", (err) =>\n process.stderr.write(`[${LABEL}] listener error: ${messageOf(err)}\\n`),\n );\n api.listener.on(\"closed\", (code, reason) => {\n if (api === this.api) this.connected = false;\n process.stderr.write(`[${LABEL}] listener closed: ${code} ${reason}\\n`);\n });\n api.listener.start();\n this.api = api;\n return true;\n }).catch((err: unknown) => {\n process.stderr.write(`[${LABEL}] connect failed: ${messageOf(err)}\\n`);\n return false as const;\n });\n if (result === true && generation === this.generation) {\n this.connected = true;\n return true;\n }\n if (result === \"timeout\") {\n process.stderr.write(\n `[${LABEL}] connect failed: no answer within ${CONNECT_TIMEOUT_MS} ms\\n`,\n );\n }\n if (generation === this.generation) this.stopListener();\n return false;\n }\n\n private stopListener(): void {\n const api = this.api;\n this.api = undefined;\n try {\n api?.listener.stop();\n } catch (err) {\n process.stderr.write(`[${LABEL}] listener stop failed: ${messageOf(err)}\\n`);\n }\n }\n\n private onMessage(message: ZaloListenerMessage): void {\n if (message.isSelf === true) return;\n const event = toMessageEvent(message, this.opts.__fetch ?? fetch);\n if (event === undefined) return;\n if (!this.seen.add(event.id)) return;\n void this.runHandler(this.handler, event).catch((err: unknown) => {\n process.stderr.write(`[${LABEL}] handler threw: ${messageOf(err)}\\n`);\n });\n }\n}\n\nfunction toMessageEvent(\n message: ZaloListenerMessage,\n fetchMedia: ZaloMediaFetch,\n): GatewayMessageEvent | undefined {\n const data = message.data;\n const msgId = data?.msgId;\n const from = data?.uidFrom;\n if (\n (typeof msgId !== \"string\" && typeof msgId !== \"number\") ||\n (typeof from !== \"string\" && typeof from !== \"number\") ||\n typeof message.threadId !== \"string\"\n ) {\n return undefined;\n }\n const content = contentOf(data, fetchMedia);\n if (content === undefined) return undefined;\n const group = message.type === THREAD_GROUP;\n const name = typeof data.dName === \"string\" ? data.dName : \"\";\n return {\n id: String(msgId),\n platform: \"zalo_personal\",\n sender: { id: String(from), username: name },\n channel: { id: message.threadId, type: group ? \"group\" : \"dm\" },\n text: content.text,\n receivedAt: Date.now(),\n ...(content.audio !== undefined ? { audio: content.audio } : {}),\n zalo_personal: {\n messageId: String(msgId),\n threadId: message.threadId,\n threadType: group ? \"group\" : \"user\",\n senderUid: String(from),\n raw: message,\n },\n };\n}\n\n/**\n * The text of a plain-text message, or empty text and the audio of a voice message (row H-2);\n * `undefined` for a sticker, an image, a card or anything else whose content is an object.\n */\nfunction contentOf(\n data: ZaloListenerMessage[\"data\"],\n fetchMedia: ZaloMediaFetch,\n): { text: string; audio?: InboundAudio } | undefined {\n if (typeof data.content === \"string\") return { text: data.content };\n const audio = deferZaloVoice(data.msgType, data.content, fetchMedia);\n return audio === undefined ? undefined : { text: \"\", audio };\n}\n\n/** Run `work`; `\"timeout\"` once `ms` passes first. */\nasync function withTimeout<T>(ms: number, work: () => Promise<T>): Promise<T | \"timeout\"> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), ms);\n });\n try {\n return await Promise.race([work(), deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","/**\n * `zaloPersonalChannel` — the Zalo personal channel described as data, with env bindings.\n *\n * Typed locally on purpose (as `telegramChannel` is): a published `.d.ts` naming a core type an\n * older peer lacks would break a consumer on that floor. The object is structurally a\n * `ChannelDescriptor`.\n */\n\nimport { channelConfigReaders } from \"loopzero-gateway\";\n\nimport { ZaloPersonalAdapter } from \"./adapter.js\";\nimport type { ZaloCredentials, ZaloPersonalAdapterOptions } from \"./types.js\";\n\nconst PREFIX = \"gateway-zalo-personal\";\n\ntype Config = Readonly<Record<string, unknown>>;\n\nconst readers = channelConfigReaders(PREFIX);\nconst { invalid } = readers;\n\n/**\n * The shared readers treat `null` (and `\"\"`) as absent. A value the caller supplied must not fall\n * back to a default silently: `null` is refused for every key, `\"\"` for those that are not strings.\n */\nfunction refuseSuppliedAbsent(config: Config, keys: Readonly<Record<string, string>>): void {\n for (const [key, expected] of Object.entries(keys)) {\n const value = config[key];\n if (value === null || (value === \"\" && expected !== \"a string\")) throw invalid(key, expected);\n }\n}\n\nconst EXPECTED_CREDENTIALS = \"an object with a cookie, an imei and a userAgent, or its JSON text\";\n\n/** The credentials as an object, or the JSON text of one (what an environment variable gives). */\nfunction readCredentials(config: Config): ZaloCredentials {\n let value = config.credentials;\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch {\n throw invalid(\"credentials\", \"valid JSON text of the web session\");\n }\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw invalid(\"credentials\", EXPECTED_CREDENTIALS);\n }\n const c = value as Record<string, unknown>;\n const { cookie, imei, userAgent } = c;\n if (\n cookie === undefined ||\n cookie === null ||\n typeof imei !== \"string\" ||\n imei === \"\" ||\n typeof userAgent !== \"string\" ||\n userAgent === \"\"\n ) {\n throw invalid(\"credentials\", EXPECTED_CREDENTIALS);\n }\n return { cookie, imei, userAgent };\n}\n\nfunction buildOptions(config: Config): ZaloPersonalAdapterOptions {\n refuseSuppliedAbsent(config, { login: \"a function\" });\n const login = readers.readFunction<NonNullable<ZaloPersonalAdapterOptions[\"login\"]>>(\n config,\n \"login\",\n );\n return {\n credentials: readCredentials(config),\n ...(login === undefined ? {} : { login }),\n };\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n readonly env?: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"credentials\",\n required: true,\n secret: true,\n env: \"ZALO_PERSONAL_CREDENTIALS\",\n description:\n \"The account's web session ({ cookie, imei, userAgent }): an object, or its JSON text.\",\n },\n {\n key: \"login\",\n required: false,\n secret: false,\n description: \"Programmatic only: replaces the zca-js login.\",\n },\n];\n\n/**\n * The Zalo personal channel: the adapter opens its own listener in `connect()`.\n *\n * `create` validates each value, then builds the adapter; it makes no network call. A wrongly typed\n * value or credentials that are not valid JSON throw a `GatewayConfigurationError` coded\n * `invalid_config` with the prefix `gateway-zalo-personal`.\n *\n * @public\n */\nexport const zaloPersonalChannel = {\n platform: \"zalo_personal\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Config): ZaloPersonalAdapter {\n return new ZaloPersonalAdapter(buildOptions(config));\n },\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "loopzero-gateway-zalo-personal",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Zalo Personal platform adapter for loopzero-gateway, over the unofficial zca-js web session (a personal account, not an Official Account).",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -36,13 +36,13 @@
|
|
|
36
36
|
"CHANGELOG.md"
|
|
37
37
|
],
|
|
38
38
|
"peerDependencies": {
|
|
39
|
-
"loopzero-gateway": ">=0.
|
|
39
|
+
"loopzero-gateway": ">=0.2.0 <1.0.0"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"tsup": "^8.5.0",
|
|
43
43
|
"typescript": "5.9.3",
|
|
44
44
|
"vitest": "^4.1.11",
|
|
45
|
-
"loopzero-gateway": "0.
|
|
45
|
+
"loopzero-gateway": "0.2.0"
|
|
46
46
|
},
|
|
47
47
|
"publishConfig": {
|
|
48
48
|
"access": "public",
|