@im-more/dsh-line 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/cordis.patch.yml +12 -0
- package/lib/index.js +1701 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +55 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +169 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +47 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +77 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +60 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +321 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +47 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +112 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +17 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +24 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +17 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +16 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/media.d.ts +19 -0
- package/lib/types/media.d.ts.map +1 -0
- package/lib/types/media.js +55 -0
- package/lib/types/media.js.map +1 -0
- package/lib/types/modes/shared.d.ts +126 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +316 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/modes/text.d.ts +13 -0
- package/lib/types/modes/text.d.ts.map +1 -0
- package/lib/types/modes/text.js +143 -0
- package/lib/types/modes/text.js.map +1 -0
- package/lib/types/request.d.ts +49 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +162 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/send.d.ts +43 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +74 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/signature.d.ts +19 -0
- package/lib/types/signature.d.ts.map +1 -0
- package/lib/types/signature.js +30 -0
- package/lib/types/signature.js.map +1 -0
- package/lib/types/transport/media.d.ts +62 -0
- package/lib/types/transport/media.d.ts.map +1 -0
- package/lib/types/transport/media.js +104 -0
- package/lib/types/transport/media.js.map +1 -0
- package/lib/types/transport/webhook.d.ts +62 -0
- package/lib/types/transport/webhook.d.ts.map +1 -0
- package/lib/types/transport/webhook.js +208 -0
- package/lib/types/transport/webhook.js.map +1 -0
- package/lib/types/types/definition.d.ts +1006 -0
- package/lib/types/types/definition.d.ts.map +1 -0
- package/lib/types/types/definition.js +2 -0
- package/lib/types/types/definition.js.map +1 -0
- package/lib/types/types/index.d.ts +542 -0
- package/lib/types/types/index.d.ts.map +1 -0
- package/lib/types/types/index.js +4 -0
- package/lib/types/types/index.js.map +1 -0
- package/lib/types/types/internal.d.ts +8 -0
- package/lib/types/types/internal.d.ts.map +1 -0
- package/lib/types/types/internal.js +234 -0
- package/lib/types/types/internal.js.map +1 -0
- package/lib/types/types/request.d.ts +341 -0
- package/lib/types/types/request.d.ts.map +1 -0
- package/lib/types/types/request.js +2 -0
- package/lib/types/types/request.js.map +1 -0
- package/package.json +61 -3
- package/src/bot.ts +229 -0
- package/src/config.ts +113 -0
- package/src/decode.ts +418 -0
- package/src/errors.ts +138 -0
- package/src/identity.ts +28 -0
- package/src/index.ts +60 -0
- package/src/media.ts +66 -0
- package/src/modes/shared.ts +408 -0
- package/src/modes/text.ts +177 -0
- package/src/request.ts +215 -0
- package/src/send.ts +104 -0
- package/src/signature.ts +32 -0
- package/src/transport/media.ts +117 -0
- package/src/transport/webhook.ts +266 -0
- package/src/types/.eslintrc.yml +2 -0
- package/src/types/definition.ts +1008 -0
- package/src/types/index.ts +593 -0
- package/src/types/internal.ts +233 -0
- package/src/types/request.ts +341 -0
- package/README.md +0 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,1701 @@
|
|
|
1
|
+
import { Adapter, ElementRegistry, PlatformError } from "@deepseek-ai/cordis-plugin-im-core";
|
|
2
|
+
import z from "@deepseek-ai/schemastery";
|
|
3
|
+
import { h, isPhrasingContainer, normalize } from "@deepseek-ai/satori-element";
|
|
4
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
5
|
+
// \0rolldown/runtime.js
|
|
6
|
+
var __defProp = Object.defineProperty;
|
|
7
|
+
var __exportAll = (all, no_symbols) => {
|
|
8
|
+
let target = {};
|
|
9
|
+
for (var name in all) __defProp(target, name, {
|
|
10
|
+
get: all[name],
|
|
11
|
+
enumerable: true
|
|
12
|
+
});
|
|
13
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
14
|
+
return target;
|
|
15
|
+
};
|
|
16
|
+
// lib/types/errors.js
|
|
17
|
+
/**
|
|
18
|
+
* One failed LINE Messaging API call.
|
|
19
|
+
*
|
|
20
|
+
* LINE answers a refusal in one of two JSON envelopes — `{ message, details[] }` for a business refusal and
|
|
21
|
+
* `{ error, error_description }` for a token or request-format refusal — or with a page no proxy should produce.
|
|
22
|
+
*/
|
|
23
|
+
var LineApiError = class extends Error {
|
|
24
|
+
status;
|
|
25
|
+
platformMessage;
|
|
26
|
+
error;
|
|
27
|
+
details;
|
|
28
|
+
bodyText;
|
|
29
|
+
nonJson;
|
|
30
|
+
constructor(message, init = {}) {
|
|
31
|
+
super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
|
|
32
|
+
this.name = "LineApiError";
|
|
33
|
+
this.status = init.status;
|
|
34
|
+
this.platformMessage = init.platformMessage;
|
|
35
|
+
this.error = init.error;
|
|
36
|
+
this.details = init.details ?? [];
|
|
37
|
+
this.bodyText = init.bodyText;
|
|
38
|
+
this.nonJson = init.nonJson ?? false;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/** Whether a caught value is an abort error, including the `DOMException` a signal produces. */
|
|
42
|
+
function isAbortError(error) {
|
|
43
|
+
return (error instanceof Error || error instanceof DOMException) && error.name === "AbortError";
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Map any failure onto the core platform taxonomy.
|
|
47
|
+
*
|
|
48
|
+
* A LINE refusal is a request-level answer: the platform rejects the whole request or sends all of it, so every 4xx
|
|
49
|
+
* means nothing was published. Transport failures, answers whose body is not JSON and 5xx leave the outcome unknown.
|
|
50
|
+
*
|
|
51
|
+
* @param error - the caught failure.
|
|
52
|
+
* @returns the classified platform error.
|
|
53
|
+
*/
|
|
54
|
+
function classifyLineError(error) {
|
|
55
|
+
if (error instanceof PlatformError) return error;
|
|
56
|
+
if (error instanceof LineApiError) {
|
|
57
|
+
const status = error.status;
|
|
58
|
+
const init = {
|
|
59
|
+
...status === void 0 ? {} : { code: status },
|
|
60
|
+
cause: error
|
|
61
|
+
};
|
|
62
|
+
if (status === void 0 || error.nonJson) return new PlatformError("retryable", error.message, {
|
|
63
|
+
...init,
|
|
64
|
+
published: "unknown"
|
|
65
|
+
});
|
|
66
|
+
if (status === 429) return new PlatformError("rate-limit", error.message, {
|
|
67
|
+
...init,
|
|
68
|
+
published: "no"
|
|
69
|
+
});
|
|
70
|
+
if (status === 401 || status === 403) return new PlatformError("permission", error.message, {
|
|
71
|
+
...init,
|
|
72
|
+
published: "no"
|
|
73
|
+
});
|
|
74
|
+
if (status === 404 || status === 410) return new PlatformError("not-found", error.message, {
|
|
75
|
+
...init,
|
|
76
|
+
published: "no"
|
|
77
|
+
});
|
|
78
|
+
if (status === 409) return new PlatformError("fatal", error.message, {
|
|
79
|
+
...init,
|
|
80
|
+
published: "unknown"
|
|
81
|
+
});
|
|
82
|
+
if (status === 413) return new PlatformError("limit", error.message, {
|
|
83
|
+
...init,
|
|
84
|
+
published: "no"
|
|
85
|
+
});
|
|
86
|
+
if (status >= 500) return new PlatformError("retryable", error.message, {
|
|
87
|
+
...init,
|
|
88
|
+
published: "unknown"
|
|
89
|
+
});
|
|
90
|
+
return new PlatformError("invalid", error.message, {
|
|
91
|
+
...init,
|
|
92
|
+
published: "no"
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
if (isAbortError(error)) return new PlatformError("fatal", error.message, {
|
|
96
|
+
published: "unknown",
|
|
97
|
+
cause: error
|
|
98
|
+
});
|
|
99
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
100
|
+
return new PlatformError("retryable", `line: request failed: ${message}`, {
|
|
101
|
+
published: "unknown",
|
|
102
|
+
cause: error
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
// lib/types/request.js
|
|
106
|
+
/**
|
|
107
|
+
* The transport every LINE REST call shares: API root, bearer authentication, JSON unwrapping, the failure
|
|
108
|
+
* `errors.ts` classifies, and content download.
|
|
109
|
+
*
|
|
110
|
+
* The typed method surface lives on `Internal`; the generated route table calls {@link invoke}, so the migrated layer
|
|
111
|
+
* and the hand-written calls (identity, push, members, content download) cannot diverge in authentication or failure
|
|
112
|
+
* handling.
|
|
113
|
+
*/
|
|
114
|
+
/** Root of the messaging API: every method except content download and the two audience uploads. */
|
|
115
|
+
const LINE_API_ORIGIN = "https://api.line.me";
|
|
116
|
+
/** Root of the content API, which serves the bytes of an inbound message. */
|
|
117
|
+
const LINE_DATA_ORIGIN = "https://api-data.line.me";
|
|
118
|
+
/** How much of a body that carried no JSON is kept in the error and the log; enough to recognise a gateway page. */
|
|
119
|
+
const BODY_PREFIX_BYTES = 512;
|
|
120
|
+
/** Message of any caught value, for a log line. */
|
|
121
|
+
function messageOf$4(error) {
|
|
122
|
+
return error instanceof Error ? error.message : String(error);
|
|
123
|
+
}
|
|
124
|
+
/** Whether a failed `ctx.http` call was the caller's cancellation rather than a transport failure. */
|
|
125
|
+
function isCancellation(cause, signal) {
|
|
126
|
+
if (signal?.aborted === true) return true;
|
|
127
|
+
if ((cause instanceof Error || cause instanceof DOMException) && cause.name === "AbortError") return true;
|
|
128
|
+
return signal?.reason !== void 0 && cause === signal.reason;
|
|
129
|
+
}
|
|
130
|
+
/** A cancelled request rejects with the signal's reason, so the classifier sees the cancellation itself. */
|
|
131
|
+
function cancellation(cause, signal) {
|
|
132
|
+
return signal?.aborted === true ? signal.reason : cause;
|
|
133
|
+
}
|
|
134
|
+
/** One JSON object, when the value is a plain object. */
|
|
135
|
+
function asRecord(value) {
|
|
136
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
137
|
+
}
|
|
138
|
+
/** The `details` array of a business refusal, keeping only the fields a log or a caller can name. */
|
|
139
|
+
function detailsOf(value) {
|
|
140
|
+
if (!Array.isArray(value)) return [];
|
|
141
|
+
const out = [];
|
|
142
|
+
for (const item of value) {
|
|
143
|
+
const record = asRecord(item);
|
|
144
|
+
if (record === void 0) continue;
|
|
145
|
+
out.push({
|
|
146
|
+
...typeof record.property === "string" ? { property: record.property } : {},
|
|
147
|
+
...typeof record.message === "string" ? { message: record.message } : {}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
/** The field names a business refusal names, for the error message. */
|
|
153
|
+
function propertiesOf(details) {
|
|
154
|
+
const names = details.map((detail) => detail.property).filter((name) => name !== void 0 && name !== "");
|
|
155
|
+
return names.length === 0 ? "" : ` (${names.join(", ")})`;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Call one messaging API endpoint.
|
|
159
|
+
*
|
|
160
|
+
* @param request - the adapter whose credentials and context the call uses.
|
|
161
|
+
* @param method - HTTP method.
|
|
162
|
+
* @param path - endpoint path under {@link LINE_API_ORIGIN}.
|
|
163
|
+
* @param config - body, query parameters and cancellation of the call.
|
|
164
|
+
* @returns the unwrapped JSON answer.
|
|
165
|
+
* @throws LineApiError when the platform refused the call or did not answer with JSON.
|
|
166
|
+
*/
|
|
167
|
+
async function invoke(request, method, path, config = {}) {
|
|
168
|
+
let response;
|
|
169
|
+
try {
|
|
170
|
+
response = await request.ctx.http(`${LINE_API_ORIGIN}${path}`, {
|
|
171
|
+
method,
|
|
172
|
+
headers: { authorization: `Bearer ${request.config.token}` },
|
|
173
|
+
...config.data === void 0 ? {} : { data: config.data },
|
|
174
|
+
...config.params === void 0 ? {} : { params: config.params },
|
|
175
|
+
...config.signal === void 0 ? {} : { signal: config.signal }
|
|
176
|
+
});
|
|
177
|
+
} catch (cause) {
|
|
178
|
+
if (isCancellation(cause, config.signal)) throw cancellation(cause, config.signal);
|
|
179
|
+
throw new LineApiError(`line: ${method} ${path} request failed: ${messageOf$4(cause)}`, { cause });
|
|
180
|
+
}
|
|
181
|
+
let text;
|
|
182
|
+
try {
|
|
183
|
+
text = await response.text();
|
|
184
|
+
} catch (cause) {
|
|
185
|
+
if (isCancellation(cause, config.signal)) throw cancellation(cause, config.signal);
|
|
186
|
+
throw new LineApiError(`line: ${method} ${path} answered ${response.status} but its body could not be read`, {
|
|
187
|
+
status: response.status,
|
|
188
|
+
cause
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
let body;
|
|
192
|
+
let nonJson = false;
|
|
193
|
+
if (text !== "") try {
|
|
194
|
+
body = JSON.parse(text);
|
|
195
|
+
} catch {
|
|
196
|
+
nonJson = true;
|
|
197
|
+
}
|
|
198
|
+
const record = asRecord(body);
|
|
199
|
+
const platformMessage = typeof record?.message === "string" ? record.message : typeof record?.error_description === "string" ? record.error_description : void 0;
|
|
200
|
+
const error = typeof record?.error === "string" ? record.error : void 0;
|
|
201
|
+
const details = detailsOf(record?.details);
|
|
202
|
+
if (response.status < 200 || response.status >= 300 || nonJson) {
|
|
203
|
+
const suffix = (platformMessage === void 0 ? "" : `: ${platformMessage}`) + propertiesOf(details);
|
|
204
|
+
throw new LineApiError(`line: ${method} ${path} answered ${response.status}${suffix}`, {
|
|
205
|
+
status: response.status,
|
|
206
|
+
...platformMessage === void 0 ? {} : { platformMessage },
|
|
207
|
+
...error === void 0 ? {} : { error },
|
|
208
|
+
...details.length === 0 ? {} : { details },
|
|
209
|
+
...text === "" ? {} : { bodyText: text.slice(0, BODY_PREFIX_BYTES) },
|
|
210
|
+
nonJson
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return body;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Download the bytes of one inbound message from the content API.
|
|
217
|
+
*
|
|
218
|
+
* The answer is returned as it arrived, whatever its status: the caller maps `200`/`202`/`404`/`410` to the inbound
|
|
219
|
+
* media contract. A request that never got an answer rejects.
|
|
220
|
+
*
|
|
221
|
+
* @param request - the adapter whose credentials and context the download uses.
|
|
222
|
+
* @param messageId - platform message id the bytes belong to.
|
|
223
|
+
* @param signal - cancellation.
|
|
224
|
+
* @returns the content API answer.
|
|
225
|
+
*/
|
|
226
|
+
async function downloadContent(request, messageId, signal) {
|
|
227
|
+
try {
|
|
228
|
+
return await request.ctx.http(`${LINE_DATA_ORIGIN}/v2/bot/message/${encodeURIComponent(messageId)}/content`, {
|
|
229
|
+
headers: { authorization: `Bearer ${request.config.token}` },
|
|
230
|
+
...signal === void 0 ? {} : { signal }
|
|
231
|
+
});
|
|
232
|
+
} catch (cause) {
|
|
233
|
+
if (isCancellation(cause, signal)) throw cancellation(cause, signal);
|
|
234
|
+
throw cause;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
// lib/types/types/internal.js
|
|
238
|
+
var Internal = class Internal {
|
|
239
|
+
request;
|
|
240
|
+
constructor(request) {
|
|
241
|
+
this.request = request;
|
|
242
|
+
}
|
|
243
|
+
static define(routes) {
|
|
244
|
+
const methods = Internal.prototype;
|
|
245
|
+
for (const path in routes) for (const key in routes[path]) {
|
|
246
|
+
const method = key;
|
|
247
|
+
const group = routes[path][method];
|
|
248
|
+
if (group === void 0) continue;
|
|
249
|
+
const names = Array.isArray(group) ? group : [group];
|
|
250
|
+
for (const name of names) methods[name] = async function(...args) {
|
|
251
|
+
const raw = args.join(", ");
|
|
252
|
+
const url = path.replace(/\{([^}]+)\}/g, () => {
|
|
253
|
+
if (!args.length) throw new Error(`too few arguments for ${path}, received ${raw}`);
|
|
254
|
+
return args.shift();
|
|
255
|
+
});
|
|
256
|
+
const config = {};
|
|
257
|
+
if (args.length === 1) {
|
|
258
|
+
if (method === "GET" || method === "DELETE") config.params = args[0];
|
|
259
|
+
else config.data = args[0];
|
|
260
|
+
} else if (args.length === 2 && method !== "GET" && method !== "DELETE") {
|
|
261
|
+
config.data = args[0];
|
|
262
|
+
config.params = args[1];
|
|
263
|
+
} else if (args.length > 1) throw new Error(`too many arguments for ${path}, received ${raw}`);
|
|
264
|
+
return await invoke(this.request, method, url, config);
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
Internal.define({
|
|
270
|
+
"/v2/bot/channel/webhook/endpoint": {
|
|
271
|
+
GET: "getWebhookEndpoint",
|
|
272
|
+
PUT: "setWebhookEndpoint"
|
|
273
|
+
},
|
|
274
|
+
"/v2/bot/channel/webhook/test": { POST: "testWebhookEndpoint" },
|
|
275
|
+
"/v2/bot/message/{messageId}/content": { GET: "getMessageContent" },
|
|
276
|
+
"/v2/bot/message/{messageId}/content/preview": { GET: "getMessageContentPreview" },
|
|
277
|
+
"/v2/bot/message/{messageId}/content/transcoding": { GET: "getMessageContentTranscodingByMessageId" },
|
|
278
|
+
"/v2/bot/message/reply": { POST: "replyMessage" },
|
|
279
|
+
"/v2/bot/message/push": { POST: "pushMessage" },
|
|
280
|
+
"/v2/bot/message/multicast": { POST: "multicast" },
|
|
281
|
+
"/v2/bot/message/narrowcast": { POST: "narrowcast" },
|
|
282
|
+
"/v2/bot/message/progress/narrowcast": { GET: "getNarrowcastProgress" },
|
|
283
|
+
"/v2/bot/message/broadcast": { POST: "broadcast" },
|
|
284
|
+
"/v2/bot/message/quota": { GET: "getMessageQuota" },
|
|
285
|
+
"/v2/bot/message/quota/consumption": { GET: "getMessageQuotaConsumption" },
|
|
286
|
+
"/v2/bot/message/delivery/reply": { GET: "getNumberOfSentReplyMessages" },
|
|
287
|
+
"/v2/bot/message/delivery/push": { GET: "getNumberOfSentPushMessages" },
|
|
288
|
+
"/v2/bot/message/delivery/multicast": { GET: "getNumberOfSentMulticastMessages" },
|
|
289
|
+
"/v2/bot/message/delivery/broadcast": { GET: "getNumberOfSentBroadcastMessages" },
|
|
290
|
+
"/v2/bot/message/validate/reply": { POST: "validateReply" },
|
|
291
|
+
"/v2/bot/message/validate/push": { POST: "validatePush" },
|
|
292
|
+
"/v2/bot/message/validate/multicast": { POST: "validateMulticast" },
|
|
293
|
+
"/v2/bot/message/validate/narrowcast": { POST: "validateNarrowcast" },
|
|
294
|
+
"/v2/bot/message/validate/broadcast": { POST: "validateBroadcast" },
|
|
295
|
+
"/v2/bot/message/aggregation/info": { GET: "getAggregationUnitUsage" },
|
|
296
|
+
"/v2/bot/message/aggregation/list": { GET: "getAggregationUnitNameList" },
|
|
297
|
+
"/v2/bot/profile/{userId}": { GET: "getProfile" },
|
|
298
|
+
"/v2/bot/followers/ids": { GET: "getFollowers" },
|
|
299
|
+
"/v2/bot/info": { GET: "getBotInfo" },
|
|
300
|
+
"/v2/bot/group/{groupId}/member/{userId}": { GET: "getGroupMemberProfile" },
|
|
301
|
+
"/v2/bot/room/{roomId}/member/{userId}": { GET: "getRoomMemberProfile" },
|
|
302
|
+
"/v2/bot/group/{groupId}/members/ids": { GET: "getGroupMembersIds" },
|
|
303
|
+
"/v2/bot/room/{roomId}/members/ids": { GET: "getRoomMembersIds" },
|
|
304
|
+
"/v2/bot/group/{groupId}/leave": { POST: "leaveGroup" },
|
|
305
|
+
"/v2/bot/room/{roomId}/leave": { POST: "leaveRoom" },
|
|
306
|
+
"/v2/bot/group/{groupId}/summary": { GET: "getGroupSummary" },
|
|
307
|
+
"/v2/bot/group/{groupId}/members/count": { GET: "getGroupMemberCount" },
|
|
308
|
+
"/v2/bot/room/{roomId}/members/count": { GET: "getRoomMemberCount" },
|
|
309
|
+
"/v2/bot/richmenu": { POST: "createRichMenu" },
|
|
310
|
+
"/v2/bot/richmenu/validate": { POST: "validateRichMenuObject" },
|
|
311
|
+
"/v2/bot/richmenu/{richMenuId}/content": {
|
|
312
|
+
GET: "getRichMenuImage",
|
|
313
|
+
POST: "setRichMenuImage"
|
|
314
|
+
},
|
|
315
|
+
"/v2/bot/richmenu/{richMenuId}": {
|
|
316
|
+
GET: "getRichMenu",
|
|
317
|
+
DELETE: "deleteRichMenu"
|
|
318
|
+
},
|
|
319
|
+
"/v2/bot/richmenu/list": { GET: "getRichMenuList" },
|
|
320
|
+
"/v2/bot/user/all/richmenu/{richMenuId}": { POST: "setDefaultRichMenu" },
|
|
321
|
+
"/v2/bot/user/all/richmenu": {
|
|
322
|
+
GET: "getDefaultRichMenuId",
|
|
323
|
+
DELETE: "cancelDefaultRichMenu"
|
|
324
|
+
},
|
|
325
|
+
"/v2/bot/richmenu/alias": { POST: "createRichMenuAlias" },
|
|
326
|
+
"/v2/bot/richmenu/alias/{richMenuAliasId}": {
|
|
327
|
+
GET: "getRichMenuAlias",
|
|
328
|
+
POST: "updateRichMenuAlias",
|
|
329
|
+
DELETE: "deleteRichMenuAlias"
|
|
330
|
+
},
|
|
331
|
+
"/v2/bot/richmenu/alias/list": { GET: "getRichMenuAliasList" },
|
|
332
|
+
"/v2/bot/user/{userId}/richmenu": {
|
|
333
|
+
GET: "getRichMenuIdOfUser",
|
|
334
|
+
DELETE: "unlinkRichMenuIdFromUser"
|
|
335
|
+
},
|
|
336
|
+
"/v2/bot/user/{userId}/richmenu/{richMenuId}": { POST: "linkRichMenuIdToUser" },
|
|
337
|
+
"/v2/bot/richmenu/bulk/link": { POST: "linkRichMenuIdToUsers" },
|
|
338
|
+
"/v2/bot/richmenu/bulk/unlink": { POST: "unlinkRichMenuIdFromUsers" },
|
|
339
|
+
"/v2/bot/richmenu/batch": { POST: "richMenuBatch" },
|
|
340
|
+
"/v2/bot/richmenu/validate/batch": { POST: "validateRichMenuBatchRequest" },
|
|
341
|
+
"/v2/bot/richmenu/progress/batch": { GET: "getRichMenuBatchProgress" },
|
|
342
|
+
"/v2/bot/user/{userId}/linkToken": { POST: "issueLinkToken" },
|
|
343
|
+
"/v2/bot/message/markAsRead": { POST: "markMessagesAsRead" },
|
|
344
|
+
"/bot/pnp/push": { POST: "pushMessagesByPhone" },
|
|
345
|
+
"/bot/ad/multicast/phone": { POST: "audienceMatch" },
|
|
346
|
+
"/v2/bot/message/delivery/pnp": { GET: "getPNPMessageStatistics" },
|
|
347
|
+
"/v2/bot/message/delivery/ad_phone": { GET: "getAdPhoneMessageStatistics" }
|
|
348
|
+
});
|
|
349
|
+
// lib/types/types/index.js
|
|
350
|
+
var types_exports = /* @__PURE__ */ __exportAll({ Internal: () => Internal });
|
|
351
|
+
// lib/types/config.js
|
|
352
|
+
/** Validated LINE adapter configuration. */
|
|
353
|
+
const Config = z.object({
|
|
354
|
+
token: z.string().role("secret").required(),
|
|
355
|
+
secret: z.string().role("secret").required(),
|
|
356
|
+
selfId: z.string().required(),
|
|
357
|
+
publicUrl: z.string().role("url").required(),
|
|
358
|
+
webhook: z.object({ path: z.string().default("/line") }).default({}),
|
|
359
|
+
media: z.object({ path: z.string().default("/line-media") }).default({})
|
|
360
|
+
});
|
|
361
|
+
/**
|
|
362
|
+
* Normalize a route path: absolute, no trailing slash.
|
|
363
|
+
*
|
|
364
|
+
* @param path - a configured path.
|
|
365
|
+
* @returns the pathname to register on the web server.
|
|
366
|
+
*/
|
|
367
|
+
function routePath(path) {
|
|
368
|
+
const withSlash = path.startsWith("/") ? path : `/${path}`;
|
|
369
|
+
return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* The public base URL without its trailing slashes.
|
|
373
|
+
*
|
|
374
|
+
* @param publicUrl - the configured `publicUrl`.
|
|
375
|
+
* @returns the base every public URL is prefixed with.
|
|
376
|
+
*/
|
|
377
|
+
function publicBase(publicUrl) {
|
|
378
|
+
return publicUrl.replace(/\/+$/, "");
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* The configuration the adapter cannot work from, as far as it can tell locally.
|
|
382
|
+
*
|
|
383
|
+
* LINE has only the webhook transport, so a profile without a public HTTPS base can neither receive an event nor let
|
|
384
|
+
* LINE fetch outbound media. The check runs when the bot starts, not on the first callback.
|
|
385
|
+
*
|
|
386
|
+
* @param config - the validated configuration.
|
|
387
|
+
* @returns the configuration error, or undefined when the configuration is usable.
|
|
388
|
+
*/
|
|
389
|
+
function configError(config) {
|
|
390
|
+
if (config.token === "") return /* @__PURE__ */ new Error("line: token is required (the channel access token of the Messaging API channel)");
|
|
391
|
+
if (config.secret === "") return /* @__PURE__ */ new Error("line: secret is required (the channel secret; it verifies every webhook)");
|
|
392
|
+
if (config.selfId === "") return /* @__PURE__ */ new Error("line: selfId is required (the bot's own user id: \"U\" + 32 hex, read from the console Basic settings)");
|
|
393
|
+
if (config.publicUrl === "") return /* @__PURE__ */ new Error("line: publicUrl is required (LINE only delivers webhooks, and it fetches outbound media from this base)");
|
|
394
|
+
let origin;
|
|
395
|
+
try {
|
|
396
|
+
origin = new URL(config.publicUrl);
|
|
397
|
+
} catch {
|
|
398
|
+
return /* @__PURE__ */ new Error(`line: publicUrl must be an absolute URL, got "${config.publicUrl}"`);
|
|
399
|
+
}
|
|
400
|
+
if (origin.protocol !== "https:") return /* @__PURE__ */ new Error(`line: publicUrl must be an https URL, got "${config.publicUrl}" (LINE refuses a plain-HTTP webhook and fetches media over https)`);
|
|
401
|
+
const webhook = routePath(config.webhook.path);
|
|
402
|
+
if (webhook === routePath(config.media.path)) return /* @__PURE__ */ new Error(`line: webhook.path and media.path must differ, both are "${webhook}"`);
|
|
403
|
+
}
|
|
404
|
+
// lib/types/identity.js
|
|
405
|
+
/** Failure to confirm the configured bot identity. */
|
|
406
|
+
var LineIdentityError = class extends Error {
|
|
407
|
+
constructor(message) {
|
|
408
|
+
super(message);
|
|
409
|
+
this.name = "LineIdentityError";
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
/**
|
|
413
|
+
* Verify a `getBotInfo` answer against the configured `selfId`.
|
|
414
|
+
*
|
|
415
|
+
* `bot.id` is fixed at construction, so the channel must be identified from configuration; this call proves the
|
|
416
|
+
* token belongs to that channel instead of discovering the id from it.
|
|
417
|
+
*
|
|
418
|
+
* @param selfId - the configured bot user id.
|
|
419
|
+
* @param info - the `GET /v2/bot/info` answer.
|
|
420
|
+
* @returns the platform user id, which is `selfId`.
|
|
421
|
+
*/
|
|
422
|
+
function verifyIdentity(selfId, info) {
|
|
423
|
+
if (info.userId !== selfId) throw new LineIdentityError(`line: selfId is ${selfId} but getBotInfo returned ${info.userId}`);
|
|
424
|
+
return info.userId;
|
|
425
|
+
}
|
|
426
|
+
// lib/types/media.js
|
|
427
|
+
/**
|
|
428
|
+
* Inbound media: the `satori:` route behind an image, video, audio or file element.
|
|
429
|
+
*
|
|
430
|
+
* LINE serves the bytes of a received message from its content API, with the channel's own credentials, and deletes
|
|
431
|
+
* them after a while. The route therefore downloads on demand instead of baking a URL into the stored message.
|
|
432
|
+
*/
|
|
433
|
+
/** Message of any caught value, for a log line. */
|
|
434
|
+
function messageOf$3(error) {
|
|
435
|
+
return error instanceof Error ? error.message : String(error);
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Serve the bytes of one inbound message.
|
|
439
|
+
*
|
|
440
|
+
* The content API answers `202` while a large video or audio is still being transcoded, `404` for an unknown id and
|
|
441
|
+
* `410` for a message the user unsent; the host treats the first as "not available yet" and the second pair as "gone".
|
|
442
|
+
*
|
|
443
|
+
* @param bot - the receiving adapter.
|
|
444
|
+
* @param messageId - platform message id of the media.
|
|
445
|
+
* @returns the bytes, or the status the host reads as unavailable.
|
|
446
|
+
*/
|
|
447
|
+
async function serveMessageContent(bot, messageId) {
|
|
448
|
+
let response;
|
|
449
|
+
try {
|
|
450
|
+
response = await downloadContent(bot.request, messageId);
|
|
451
|
+
} catch (error) {
|
|
452
|
+
bot.ctx.logger.warn("line: media %s could not be downloaded: %s", messageId, messageOf$3(error));
|
|
453
|
+
return new Response(null, { status: 502 });
|
|
454
|
+
}
|
|
455
|
+
switch (response.status) {
|
|
456
|
+
case 200: {
|
|
457
|
+
const headers = new Headers();
|
|
458
|
+
const mime = response.headers.get("content-type");
|
|
459
|
+
if (mime !== null) headers.set("content-type", mime);
|
|
460
|
+
const cacheControl = response.headers.get("cache-control");
|
|
461
|
+
if (cacheControl !== null) headers.set("cache-control", cacheControl);
|
|
462
|
+
return new Response(response.body, {
|
|
463
|
+
status: 200,
|
|
464
|
+
headers
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
case 202:
|
|
468
|
+
bot.ctx.logger.warn("line: media %s is still being transcoded", messageId);
|
|
469
|
+
return new Response(null, { status: 503 });
|
|
470
|
+
case 404:
|
|
471
|
+
case 410: return new Response(null, { status: 404 });
|
|
472
|
+
default:
|
|
473
|
+
bot.ctx.logger.warn("line: media %s answered %s", messageId, String(response.status));
|
|
474
|
+
return new Response(null, { status: 502 });
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
// lib/types/decode.js
|
|
478
|
+
/**
|
|
479
|
+
* Inbound decoding: one LINE webhook event becomes an intake `Session` (`message`), a button interaction, or an
|
|
480
|
+
* unsent-message notification.
|
|
481
|
+
*
|
|
482
|
+
* LINE gives the content away exactly once — there is no API that reads a message back — so the webhook payload, its
|
|
483
|
+
* UTF-16 indices included, is the only source of text, mentions, quotes and media.
|
|
484
|
+
*/
|
|
485
|
+
/** The `chat.id` of a source: `user:`, `group:` or `room:` plus the platform id. */
|
|
486
|
+
function chatIdOf(source) {
|
|
487
|
+
switch (source.type) {
|
|
488
|
+
case "user": return `user:${source.userId}`;
|
|
489
|
+
case "group": return `group:${source.groupId}`;
|
|
490
|
+
case "room": return `room:${source.roomId}`;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
/** The `ChatRef` of a source; a room is a group in the DSH vocabulary. */
|
|
494
|
+
function chatRefOf(source) {
|
|
495
|
+
return {
|
|
496
|
+
id: chatIdOf(source),
|
|
497
|
+
type: source.type === "user" ? "direct" : "group"
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Split a `chat.id` back into the platform conversation.
|
|
502
|
+
*
|
|
503
|
+
* @param chatId - a `chat.id` this adapter wrote, or one a profile configured by hand.
|
|
504
|
+
* @returns the conversation kind and its platform id.
|
|
505
|
+
* @throws PlatformError `invalid` when the id carries no known prefix.
|
|
506
|
+
*/
|
|
507
|
+
function parseChatId(chatId) {
|
|
508
|
+
const index = chatId.indexOf(":");
|
|
509
|
+
const kind = index === -1 ? "" : chatId.slice(0, index);
|
|
510
|
+
if (kind !== "user" && kind !== "group" && kind !== "room") throw new PlatformError("invalid", `line: chat id "${chatId}" carries no user:/group:/room: prefix`, { published: "no" });
|
|
511
|
+
return {
|
|
512
|
+
kind,
|
|
513
|
+
id: chatId.slice(index + 1)
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* The `pushMessage` recipient of a `chat.id`.
|
|
518
|
+
*
|
|
519
|
+
* @param chatId - a `chat.id` this adapter wrote.
|
|
520
|
+
* @returns the `to` value of a push request.
|
|
521
|
+
* @throws PlatformError `invalid` when the id carries no known prefix.
|
|
522
|
+
*/
|
|
523
|
+
function chatTargetOf(chatId) {
|
|
524
|
+
return parseChatId(chatId).id;
|
|
525
|
+
}
|
|
526
|
+
/** The sender of a source; LINE omits the user id of an unconverted user, which collapses to `anonymous`. */
|
|
527
|
+
function senderOf(source) {
|
|
528
|
+
return { id: source.type === "user" ? source.userId : source.userId ?? "anonymous" };
|
|
529
|
+
}
|
|
530
|
+
/** A mention's visible name, without the leading `@` the payload carries. */
|
|
531
|
+
function mentionName(slice) {
|
|
532
|
+
return slice.startsWith("@") ? slice.slice(1) : slice;
|
|
533
|
+
}
|
|
534
|
+
/** One UTF-16 slice of a text message; LINE indices count UTF-16 code units. */
|
|
535
|
+
function sliceOf(text, index, length) {
|
|
536
|
+
return text.slice(index, index + length);
|
|
537
|
+
}
|
|
538
|
+
/** The element nodes of one text message, slicing the body at its emoji and mention spans. */
|
|
539
|
+
function textNodes(message) {
|
|
540
|
+
const text = message.text;
|
|
541
|
+
const spans = [...(message.emojis ?? []).map((emoji) => ({
|
|
542
|
+
kind: "emoji",
|
|
543
|
+
index: emoji.index,
|
|
544
|
+
length: emoji.length,
|
|
545
|
+
emoji
|
|
546
|
+
})), ...(message.mention?.mentionees ?? []).map((mention) => ({
|
|
547
|
+
kind: "mention",
|
|
548
|
+
index: mention.index,
|
|
549
|
+
length: mention.length,
|
|
550
|
+
mention
|
|
551
|
+
}))].filter((span) => span.index >= 0 && span.length > 0 && span.index + span.length <= text.length).sort((a, b) => a.index - b.index);
|
|
552
|
+
const nodes = [];
|
|
553
|
+
let cursor = 0;
|
|
554
|
+
for (const span of spans) {
|
|
555
|
+
if (span.index < cursor) continue;
|
|
556
|
+
if (span.index > cursor) nodes.push(text.slice(cursor, span.index));
|
|
557
|
+
if (span.kind === "emoji") nodes.push(h("emoji", { id: `e:${span.emoji.productId}:${span.emoji.emojiId}` }));
|
|
558
|
+
else if (span.mention.type === "all") nodes.push(h("at", { type: "all" }));
|
|
559
|
+
else if (span.mention.userId === void 0) nodes.push(sliceOf(text, span.index, span.length));
|
|
560
|
+
else nodes.push(h("at", {
|
|
561
|
+
type: "user",
|
|
562
|
+
id: span.mention.userId,
|
|
563
|
+
name: mentionName(sliceOf(text, span.index, span.length))
|
|
564
|
+
}));
|
|
565
|
+
cursor = span.index + span.length;
|
|
566
|
+
}
|
|
567
|
+
if (cursor < text.length) nodes.push(text.slice(cursor));
|
|
568
|
+
return nodes;
|
|
569
|
+
}
|
|
570
|
+
/** The source of an inbound media element: LINE's own content API, or the URL a third party provided. */
|
|
571
|
+
function contentSource(bot, messageId, provider) {
|
|
572
|
+
if (provider?.type === "external") return provider.originalContentUrl;
|
|
573
|
+
return bot.getInternalUrl(`/assets/${encodeURIComponent(messageId)}`);
|
|
574
|
+
}
|
|
575
|
+
/** The elements of one message of the seven platform types. */
|
|
576
|
+
function messageNodes(bot, message) {
|
|
577
|
+
switch (message.type) {
|
|
578
|
+
case "text": return textNodes(message);
|
|
579
|
+
case "image": return [h("img", { src: contentSource(bot, message.id, message.contentProvider) })];
|
|
580
|
+
case "video": return [h("video", {
|
|
581
|
+
src: contentSource(bot, message.id, message.contentProvider),
|
|
582
|
+
...message.duration === void 0 ? {} : { duration: message.duration }
|
|
583
|
+
})];
|
|
584
|
+
case "audio": return [h("audio", {
|
|
585
|
+
src: contentSource(bot, message.id, message.contentProvider),
|
|
586
|
+
duration: message.duration
|
|
587
|
+
})];
|
|
588
|
+
case "file": {
|
|
589
|
+
const size = Number(message.fileSize);
|
|
590
|
+
return [h("file", {
|
|
591
|
+
src: bot.getInternalUrl(`/assets/${encodeURIComponent(message.id)}`),
|
|
592
|
+
name: message.fileName,
|
|
593
|
+
...Number.isFinite(size) ? { size } : {}
|
|
594
|
+
})];
|
|
595
|
+
}
|
|
596
|
+
case "location": {
|
|
597
|
+
const lines = [
|
|
598
|
+
message.title,
|
|
599
|
+
message.address,
|
|
600
|
+
`${message.latitude}, ${message.longitude}`
|
|
601
|
+
].filter((line) => line !== "");
|
|
602
|
+
return [h("p", lines.join("\n"))];
|
|
603
|
+
}
|
|
604
|
+
case "sticker": return [h("emoji", { id: `s:${message.packageId}:${message.stickerId}` })];
|
|
605
|
+
default: return [];
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
/** Mention flags and mentioned users of one message. */
|
|
609
|
+
function mentionsOf(bot, message) {
|
|
610
|
+
if (message.type !== "text") return {
|
|
611
|
+
self: false,
|
|
612
|
+
all: false,
|
|
613
|
+
users: []
|
|
614
|
+
};
|
|
615
|
+
const text = message.text;
|
|
616
|
+
const mentionees = message.mention?.mentionees ?? [];
|
|
617
|
+
const users = [];
|
|
618
|
+
for (const mention of mentionees) {
|
|
619
|
+
if (mention.type !== "user" || mention.userId === void 0) continue;
|
|
620
|
+
users.push({
|
|
621
|
+
id: mention.userId,
|
|
622
|
+
name: mentionName(sliceOf(text, mention.index, mention.length))
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
const all = mentionees.some((mention) => mention.type === "all");
|
|
626
|
+
const declaresSelf = mentionees.some((mention) => mention.isSelf !== void 0);
|
|
627
|
+
return {
|
|
628
|
+
self: mentionees.some((mention) => mention.isSelf === true) || !declaresSelf && mentionees.some((mention) => mention.type === "user" && mention.userId === bot.selfId),
|
|
629
|
+
all,
|
|
630
|
+
users
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
/** The quote token of a message, which only the four quotable types carry. */
|
|
634
|
+
function quoteTokenOf$1(message) {
|
|
635
|
+
switch (message.type) {
|
|
636
|
+
case "text":
|
|
637
|
+
case "image":
|
|
638
|
+
case "video":
|
|
639
|
+
case "sticker": return message.quoteToken;
|
|
640
|
+
default: return;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
/** The quote an inbound message answers, when the platform names it. */
|
|
644
|
+
function quoteOf(message) {
|
|
645
|
+
return message.type === "text" && message.quotedMessageId !== void 0 ? { id: message.quotedMessageId } : void 0;
|
|
646
|
+
}
|
|
647
|
+
/** Decode one message event into the normalized inbound message. */
|
|
648
|
+
function decodeMessage(bot, event) {
|
|
649
|
+
const source = event.source;
|
|
650
|
+
const message = event.message;
|
|
651
|
+
const referrer = {
|
|
652
|
+
messageId: message.id,
|
|
653
|
+
timestamp: event.timestamp,
|
|
654
|
+
mode: event.mode,
|
|
655
|
+
...quoteTokenOf$1(message) === void 0 ? {} : { quoteToken: quoteTokenOf$1(message) },
|
|
656
|
+
...event.replyToken === void 0 ? {} : { replyToken: event.replyToken }
|
|
657
|
+
};
|
|
658
|
+
const nodes = messageNodes(bot, message);
|
|
659
|
+
const content = normalize(nodes.length > 0 ? nodes : [h("raw", {
|
|
660
|
+
platform: "line",
|
|
661
|
+
type: "message",
|
|
662
|
+
data: message
|
|
663
|
+
})]);
|
|
664
|
+
const quote = quoteOf(message);
|
|
665
|
+
return {
|
|
666
|
+
id: message.id,
|
|
667
|
+
chat: chatRefOf(source),
|
|
668
|
+
sender: senderOf(source),
|
|
669
|
+
content,
|
|
670
|
+
...quote === void 0 ? {} : { quote },
|
|
671
|
+
mentions: mentionsOf(bot, message),
|
|
672
|
+
time: event.timestamp,
|
|
673
|
+
referrer,
|
|
674
|
+
raw: event
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
/** Decode the button context of a postback, which names no platform message of its own. */
|
|
678
|
+
function decodePostback(bot, event) {
|
|
679
|
+
const chat = chatRefOf(event.source);
|
|
680
|
+
const referrer = {
|
|
681
|
+
timestamp: event.timestamp,
|
|
682
|
+
mode: event.mode,
|
|
683
|
+
replyToken: event.replyToken
|
|
684
|
+
};
|
|
685
|
+
const button = {
|
|
686
|
+
id: event.postback.data,
|
|
687
|
+
data: event.postback.data,
|
|
688
|
+
referrer,
|
|
689
|
+
time: event.timestamp,
|
|
690
|
+
bot,
|
|
691
|
+
user: senderOf(event.source),
|
|
692
|
+
chat
|
|
693
|
+
};
|
|
694
|
+
return bot.session({
|
|
695
|
+
type: "interaction/button",
|
|
696
|
+
id: event.webhookEventId,
|
|
697
|
+
timestamp: event.timestamp,
|
|
698
|
+
button,
|
|
699
|
+
raw: event
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* Decode one webhook event.
|
|
704
|
+
*
|
|
705
|
+
* Events the DSH contract has no consumer for (follows, joins, member changes, beacons, edits, deliveries …) are
|
|
706
|
+
* dropped with a debug line: the model has no `friend-*`/`guild-*` event to receive them.
|
|
707
|
+
*
|
|
708
|
+
* @param bot - the receiving adapter.
|
|
709
|
+
* @param event - one event of the webhook body.
|
|
710
|
+
* @returns the session to publish, or undefined for an ignored event.
|
|
711
|
+
*/
|
|
712
|
+
function decodeEvent(bot, event) {
|
|
713
|
+
if (event.mode === "standby") {
|
|
714
|
+
bot.ctx.logger.debug("line: skipping standby event %s", event.webhookEventId);
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
if (event.deliveryContext?.isRedelivery === true) bot.ctx.logger.debug("line: handling redelivered event %s", event.webhookEventId);
|
|
718
|
+
switch (event.type) {
|
|
719
|
+
case "message": {
|
|
720
|
+
const message = decodeMessage(bot, event);
|
|
721
|
+
return bot.session({
|
|
722
|
+
type: "message",
|
|
723
|
+
id: message.id,
|
|
724
|
+
timestamp: message.time,
|
|
725
|
+
message,
|
|
726
|
+
raw: event
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
case "unsend": return bot.session({
|
|
730
|
+
type: "message-deleted",
|
|
731
|
+
id: event.webhookEventId,
|
|
732
|
+
timestamp: event.timestamp,
|
|
733
|
+
deleted: {
|
|
734
|
+
id: event.unsend.messageId,
|
|
735
|
+
chat: chatRefOf(event.source)
|
|
736
|
+
},
|
|
737
|
+
raw: event
|
|
738
|
+
});
|
|
739
|
+
case "postback": return decodePostback(bot, event);
|
|
740
|
+
default:
|
|
741
|
+
bot.ctx.logger.debug("line: ignoring a %s event", event.type);
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
// lib/types/modes/shared.js
|
|
746
|
+
/**
|
|
747
|
+
* Shared types and the draft machinery of the single `text` mode.
|
|
748
|
+
*
|
|
749
|
+
* A LINE message object is the only outbound representation the platform programs against, and one request carries at
|
|
750
|
+
* most five of them. A draft is therefore one request: up to five message objects plus the quick reply items of the
|
|
751
|
+
* last one, because the platform shows only the last message object's quick reply.
|
|
752
|
+
*/
|
|
753
|
+
/** The platform's documented bounds. */
|
|
754
|
+
const LINE_LIMITS = {
|
|
755
|
+
/** One text message object: 5,000 UTF-16 code units. */
|
|
756
|
+
text: 5e3,
|
|
757
|
+
/** Message objects one push accepts. */
|
|
758
|
+
messages: 5,
|
|
759
|
+
/** Quick reply items one message accepts. */
|
|
760
|
+
quickReplies: 13,
|
|
761
|
+
/** Request body size (`413 Payload Too Large`). */
|
|
762
|
+
payloadBytes: 2097152
|
|
763
|
+
};
|
|
764
|
+
/**
|
|
765
|
+
* The length allowance of one media key that is not the source itself.
|
|
766
|
+
*
|
|
767
|
+
* A non-HTTPS source is staged and the request carries `<publicUrl><media.path>/<token>` instead of it, so measuring the
|
|
768
|
+
* source would refuse a `data:` URL of megabytes that actually spends a few dozen bytes of the request body.
|
|
769
|
+
*/
|
|
770
|
+
const STAGED_URL_ALLOWANCE = "https://line-media.invalid/0000000000000000000000";
|
|
771
|
+
/** Report inline media that moves out of its text run into a message object of its own. */
|
|
772
|
+
function reportMovedMedia(el, ctx) {
|
|
773
|
+
const parent = ctx.ancestors[ctx.ancestors.length - 1];
|
|
774
|
+
if (parent !== void 0 && isPhrasingContainer(parent.type)) ctx.report.moved.push({
|
|
775
|
+
tag: el.type,
|
|
776
|
+
reason: "line-media-split",
|
|
777
|
+
path: ctx.stableId(el)
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* The latest paragraph, line or space boundary at or before `limit`.
|
|
782
|
+
*
|
|
783
|
+
* The whitespace that ends the boundary stays in the chunk, so concatenating the chunks reproduces the input.
|
|
784
|
+
*
|
|
785
|
+
* @param text - the text to cut.
|
|
786
|
+
* @param limit - the maximum chunk length in UTF-16 code units.
|
|
787
|
+
* @returns the cut index including the boundary whitespace, or -1 for none.
|
|
788
|
+
*/
|
|
789
|
+
function boundaryCut(text, limit) {
|
|
790
|
+
const window = text.slice(0, limit);
|
|
791
|
+
const paragraph = window.lastIndexOf("\n\n");
|
|
792
|
+
if (paragraph >= 0) return paragraph + 2;
|
|
793
|
+
const line = window.lastIndexOf("\n");
|
|
794
|
+
if (line >= 0) return line + 1;
|
|
795
|
+
const space = window.lastIndexOf(" ");
|
|
796
|
+
if (space >= 0) return space + 1;
|
|
797
|
+
return -1;
|
|
798
|
+
}
|
|
799
|
+
/** Move a cut left by one unit when it would fall inside a surrogate pair. */
|
|
800
|
+
function avoidSplitPair(text, cut) {
|
|
801
|
+
if (cut <= 0 || cut >= text.length) return cut;
|
|
802
|
+
const before = text.charCodeAt(cut - 1);
|
|
803
|
+
const after = text.charCodeAt(cut);
|
|
804
|
+
return before >= 55296 && before <= 56319 && after >= 56320 && after <= 57343 ? cut - 1 : cut;
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Cut text into chunks a text message object accepts.
|
|
808
|
+
*
|
|
809
|
+
* Point cuts prefer a paragraph break, then a line break, then a space, then a code-unit boundary that does not split a
|
|
810
|
+
* surrogate pair. The chunks concatenate back to the input.
|
|
811
|
+
*
|
|
812
|
+
* @param text - the text of one block.
|
|
813
|
+
* @param limit - the maximum chunk length in UTF-16 code units.
|
|
814
|
+
* @returns one or more chunks.
|
|
815
|
+
*/
|
|
816
|
+
function splitText(text, limit) {
|
|
817
|
+
if (text.length <= limit) return [text];
|
|
818
|
+
const chunks = [];
|
|
819
|
+
let rest = text;
|
|
820
|
+
while (rest.length > limit) {
|
|
821
|
+
let cut = boundaryCut(rest, limit);
|
|
822
|
+
if (cut <= 0) cut = Math.max(1, limit);
|
|
823
|
+
cut = Math.max(1, avoidSplitPair(rest, cut));
|
|
824
|
+
chunks.push(rest.slice(0, cut));
|
|
825
|
+
rest = rest.slice(cut);
|
|
826
|
+
}
|
|
827
|
+
if (rest !== "") chunks.push(rest);
|
|
828
|
+
return chunks;
|
|
829
|
+
}
|
|
830
|
+
/** One message object of a draft, with resource keys resolved by the caller. */
|
|
831
|
+
function messageOf$2(block, keyOf) {
|
|
832
|
+
switch (block.type) {
|
|
833
|
+
case "text": return {
|
|
834
|
+
type: "text",
|
|
835
|
+
text: block.text
|
|
836
|
+
};
|
|
837
|
+
case "image": {
|
|
838
|
+
const url = keyOf(block.ref);
|
|
839
|
+
return {
|
|
840
|
+
type: "image",
|
|
841
|
+
originalContentUrl: url,
|
|
842
|
+
previewImageUrl: url
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
case "video": return {
|
|
846
|
+
type: "video",
|
|
847
|
+
originalContentUrl: keyOf(block.ref),
|
|
848
|
+
previewImageUrl: keyOf(block.poster)
|
|
849
|
+
};
|
|
850
|
+
case "audio": return {
|
|
851
|
+
type: "audio",
|
|
852
|
+
originalContentUrl: keyOf(block.ref),
|
|
853
|
+
duration: block.duration
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
/** One LINE action object of a quick reply item. */
|
|
858
|
+
function actionOf(action) {
|
|
859
|
+
switch (action.type) {
|
|
860
|
+
case "postback": return {
|
|
861
|
+
type: "postback",
|
|
862
|
+
label: action.label,
|
|
863
|
+
data: action.data
|
|
864
|
+
};
|
|
865
|
+
case "uri": return {
|
|
866
|
+
type: "uri",
|
|
867
|
+
label: action.label,
|
|
868
|
+
uri: action.uri
|
|
869
|
+
};
|
|
870
|
+
case "message": return {
|
|
871
|
+
type: "message",
|
|
872
|
+
label: action.label,
|
|
873
|
+
text: action.text
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
/** Copy one message object with its quote token. */
|
|
878
|
+
function quoteMessage(message, quoteToken) {
|
|
879
|
+
return {
|
|
880
|
+
...message,
|
|
881
|
+
quoteToken
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
/** One quick reply item around a collected button. */
|
|
885
|
+
function quickReplyItemOf(action) {
|
|
886
|
+
return {
|
|
887
|
+
type: "action",
|
|
888
|
+
action: actionOf(action)
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
* The message objects of one draft.
|
|
893
|
+
*
|
|
894
|
+
* A draft without blocks exists only to carry a quick reply (content that is nothing but buttons), so it gets a text
|
|
895
|
+
* message the quick reply can ride on.
|
|
896
|
+
*/
|
|
897
|
+
function messagesOf(draft, keyOf) {
|
|
898
|
+
const messages = (draft.blocks.length > 0 ? draft.blocks : [{
|
|
899
|
+
type: "text",
|
|
900
|
+
text: ""
|
|
901
|
+
}]).map((block) => messageOf$2(block, keyOf));
|
|
902
|
+
if (draft.actions.length > 0) {
|
|
903
|
+
const last = messages[messages.length - 1];
|
|
904
|
+
messages[messages.length - 1] = {
|
|
905
|
+
...last,
|
|
906
|
+
quickReply: { items: draft.actions.map(quickReplyItemOf) }
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
return messages;
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Fold a node stream into requests.
|
|
913
|
+
*
|
|
914
|
+
* @param nodes - rendered nodes, in document order.
|
|
915
|
+
* @returns one draft per request, in send order; never empty.
|
|
916
|
+
*/
|
|
917
|
+
function assembleDraft(nodes) {
|
|
918
|
+
const blocks = [];
|
|
919
|
+
const actions = [];
|
|
920
|
+
let buffer = "";
|
|
921
|
+
const flushText = () => {
|
|
922
|
+
const text = buffer.trim();
|
|
923
|
+
buffer = "";
|
|
924
|
+
if (text === "") return;
|
|
925
|
+
for (const chunk of splitText(text, LINE_LIMITS.text)) blocks.push({
|
|
926
|
+
type: "text",
|
|
927
|
+
text: chunk
|
|
928
|
+
});
|
|
929
|
+
};
|
|
930
|
+
for (const node of nodes) switch (node.type) {
|
|
931
|
+
case "text":
|
|
932
|
+
buffer += node.text;
|
|
933
|
+
break;
|
|
934
|
+
case "media":
|
|
935
|
+
flushText();
|
|
936
|
+
blocks.push(node.block);
|
|
937
|
+
break;
|
|
938
|
+
case "button": actions.push(node.action);
|
|
939
|
+
}
|
|
940
|
+
flushText();
|
|
941
|
+
const drafts = [];
|
|
942
|
+
for (let index = 0; index < blocks.length; index += LINE_LIMITS.messages) drafts.push({
|
|
943
|
+
blocks: blocks.slice(index, index + LINE_LIMITS.messages),
|
|
944
|
+
actions: []
|
|
945
|
+
});
|
|
946
|
+
if (drafts.length === 0) drafts.push({
|
|
947
|
+
blocks: [],
|
|
948
|
+
actions: []
|
|
949
|
+
});
|
|
950
|
+
if (actions.length > 0) drafts[drafts.length - 1].actions = actions;
|
|
951
|
+
return drafts;
|
|
952
|
+
}
|
|
953
|
+
/** The referrer this adapter wrote, when the target still carries it. */
|
|
954
|
+
function isLineReferrer(value) {
|
|
955
|
+
return typeof value === "object" && value !== null && "timestamp" in value && "mode" in value;
|
|
956
|
+
}
|
|
957
|
+
/** One resolved resource key of a prepared draft. */
|
|
958
|
+
function resolvedKey(prepared, ref) {
|
|
959
|
+
const resolved = prepared.resolved.get(ref);
|
|
960
|
+
if (resolved === void 0) throw new Error("line: media was not prepared before serialize");
|
|
961
|
+
return resolved.key;
|
|
962
|
+
}
|
|
963
|
+
/** The quote token of this request, when the request answers the message the token belongs to. */
|
|
964
|
+
function quoteTokenOf(ctx) {
|
|
965
|
+
if (ctx.index !== 0 || ctx.quote === void 0) return void 0;
|
|
966
|
+
const referrer = ctx.target.referrer;
|
|
967
|
+
if (!isLineReferrer(referrer)) return void 0;
|
|
968
|
+
if (referrer.messageId !== ctx.quote) return void 0;
|
|
969
|
+
return referrer.quoteToken;
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* Build the exact push body of one prepared draft.
|
|
973
|
+
*
|
|
974
|
+
* @param prepared - the draft with its resource keys resolved.
|
|
975
|
+
* @param ctx - the send context: target, part index and quoted message.
|
|
976
|
+
* @returns the request body.
|
|
977
|
+
* @throws PlatformError `invalid` when the target chat id carries no known prefix.
|
|
978
|
+
*/
|
|
979
|
+
function serializeDraft(prepared, ctx) {
|
|
980
|
+
const messages = messagesOf(prepared.draft, (ref) => resolvedKey(prepared, ref));
|
|
981
|
+
const quoteToken = quoteTokenOf(ctx);
|
|
982
|
+
if (quoteToken !== void 0) {
|
|
983
|
+
const first = messages[0];
|
|
984
|
+
if (first.type === "text" || first.type === "image" || first.type === "video" || first.type === "sticker") messages[0] = quoteMessage(first, quoteToken);
|
|
985
|
+
else ctx.bot.ctx.logger.debug("line: the first message object is an %s, which cannot carry a quote token", first.type);
|
|
986
|
+
}
|
|
987
|
+
return {
|
|
988
|
+
to: chatTargetOf(ctx.target.chat.id),
|
|
989
|
+
messages
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Hard platform limits of one draft, checked before any request.
|
|
994
|
+
*
|
|
995
|
+
* Text splitting and per-request grouping already keep the draft inside the text, object-count and quick-reply bounds;
|
|
996
|
+
* the checks stay as a regression guard and as the only place a caller learns about a request body that outgrew the
|
|
997
|
+
* 2 MB limit (long media URLs).
|
|
998
|
+
*
|
|
999
|
+
* @param draft - the assembled draft.
|
|
1000
|
+
* @returns every violation the platform would refuse.
|
|
1001
|
+
*/
|
|
1002
|
+
function checkDraft(draft) {
|
|
1003
|
+
const violations = [];
|
|
1004
|
+
for (const block of draft.blocks) {
|
|
1005
|
+
if (block.type !== "text") continue;
|
|
1006
|
+
const length = block.text.length;
|
|
1007
|
+
if (length <= LINE_LIMITS.text) continue;
|
|
1008
|
+
violations.push({
|
|
1009
|
+
kind: "size",
|
|
1010
|
+
key: "limit.text.chars",
|
|
1011
|
+
limit: LINE_LIMITS.text,
|
|
1012
|
+
actual: length,
|
|
1013
|
+
message: `LINE text accepts ${LINE_LIMITS.text} UTF-16 code units, got ${length}`
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
if (draft.actions.length > LINE_LIMITS.quickReplies) violations.push({
|
|
1017
|
+
kind: "size",
|
|
1018
|
+
key: "limit.buttons.rows",
|
|
1019
|
+
limit: LINE_LIMITS.quickReplies,
|
|
1020
|
+
actual: draft.actions.length,
|
|
1021
|
+
message: `LINE quick reply accepts ${LINE_LIMITS.quickReplies} items, got ${draft.actions.length}`
|
|
1022
|
+
});
|
|
1023
|
+
const bytes = Buffer.byteLength(JSON.stringify(messagesOf(draft, (ref) => /^https:\/\//i.test(ref.src) ? ref.src : STAGED_URL_ALLOWANCE)), "utf8");
|
|
1024
|
+
if (bytes > LINE_LIMITS.payloadBytes) violations.push({
|
|
1025
|
+
kind: "size",
|
|
1026
|
+
key: "limit.payload.bytes",
|
|
1027
|
+
limit: LINE_LIMITS.payloadBytes,
|
|
1028
|
+
actual: bytes,
|
|
1029
|
+
message: `LINE accepts a ${LINE_LIMITS.payloadBytes}-byte request body, got ${bytes}`
|
|
1030
|
+
});
|
|
1031
|
+
return violations;
|
|
1032
|
+
}
|
|
1033
|
+
// lib/types/modes/text.js
|
|
1034
|
+
/**
|
|
1035
|
+
* `text` mode: LINE message objects, which is the only outbound representation the Messaging API programs against.
|
|
1036
|
+
*
|
|
1037
|
+
* Text is sent verbatim — a LINE text message has no markup, so nothing is escaped. Images, videos and audio become
|
|
1038
|
+
* message objects of their own; a video without a poster and an audio without a duration cannot be expressed (both
|
|
1039
|
+
* fields are required by the platform), so they become a link the LINE client can open. Buttons become quick reply
|
|
1040
|
+
* items. Everything else takes the core fallback and is reported as degraded.
|
|
1041
|
+
*/
|
|
1042
|
+
/** The link text a media element the platform cannot send as its kind degrades to. */
|
|
1043
|
+
function linkText(name, src) {
|
|
1044
|
+
return name === void 0 || name === "" ? src : `${name}: ${src}`;
|
|
1045
|
+
}
|
|
1046
|
+
/** The text run of rendered children and the media that cannot stay inside it. */
|
|
1047
|
+
function textRun(nodes) {
|
|
1048
|
+
let text = "";
|
|
1049
|
+
const rest = [];
|
|
1050
|
+
for (const node of nodes) if (node.type === "text") text += node.text;
|
|
1051
|
+
else rest.push(node);
|
|
1052
|
+
return {
|
|
1053
|
+
text,
|
|
1054
|
+
nodes: rest
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
/** One image message object, reported as moved when it stood inside a phrasing container. */
|
|
1058
|
+
function imageNode(el, ctx) {
|
|
1059
|
+
reportMovedMedia(el, ctx);
|
|
1060
|
+
return {
|
|
1061
|
+
type: "media",
|
|
1062
|
+
block: {
|
|
1063
|
+
type: "image",
|
|
1064
|
+
ref: ctx.resource("image", el.attrs.src, {})
|
|
1065
|
+
}
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
/** One video message object; without a poster the platform refuses the object, so the video becomes a link. */
|
|
1069
|
+
function videoNode(el, ctx) {
|
|
1070
|
+
const { src, poster, name } = el.attrs;
|
|
1071
|
+
if (poster === void 0) {
|
|
1072
|
+
ctx.report.dropped.push({
|
|
1073
|
+
what: `video:${name ?? src}`,
|
|
1074
|
+
reason: "line-video-poster"
|
|
1075
|
+
});
|
|
1076
|
+
return {
|
|
1077
|
+
type: "text",
|
|
1078
|
+
text: linkText(name, src)
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
reportMovedMedia(el, ctx);
|
|
1082
|
+
return {
|
|
1083
|
+
type: "media",
|
|
1084
|
+
block: {
|
|
1085
|
+
type: "video",
|
|
1086
|
+
ref: ctx.resource("video", src, name === void 0 ? {} : { name }),
|
|
1087
|
+
poster: ctx.resource("image", poster, {})
|
|
1088
|
+
}
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
/** One audio message object; the platform requires the duration, so an audio without one becomes a link. */
|
|
1092
|
+
function audioNode(el, ctx) {
|
|
1093
|
+
const { src, name, duration } = el.attrs;
|
|
1094
|
+
if (duration === void 0) {
|
|
1095
|
+
ctx.report.dropped.push({
|
|
1096
|
+
what: `audio:${name ?? src}`,
|
|
1097
|
+
reason: "line-audio-duration"
|
|
1098
|
+
});
|
|
1099
|
+
return {
|
|
1100
|
+
type: "text",
|
|
1101
|
+
text: linkText(name, src)
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
reportMovedMedia(el, ctx);
|
|
1105
|
+
return {
|
|
1106
|
+
type: "media",
|
|
1107
|
+
block: {
|
|
1108
|
+
type: "audio",
|
|
1109
|
+
ref: ctx.resource("audio", src, {
|
|
1110
|
+
...name === void 0 ? {} : { name },
|
|
1111
|
+
duration
|
|
1112
|
+
}),
|
|
1113
|
+
duration
|
|
1114
|
+
}
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
/** The quick reply action of one button, by its type. */
|
|
1118
|
+
function buttonAction(el, ctx) {
|
|
1119
|
+
const label = ctx.text(el.children).trim();
|
|
1120
|
+
switch (el.attrs.type) {
|
|
1121
|
+
case "link": return {
|
|
1122
|
+
type: "uri",
|
|
1123
|
+
label: label === "" ? el.attrs.href : label,
|
|
1124
|
+
uri: el.attrs.href
|
|
1125
|
+
};
|
|
1126
|
+
case "input": return {
|
|
1127
|
+
type: "message",
|
|
1128
|
+
label: label === "" ? el.attrs.text : label,
|
|
1129
|
+
text: el.attrs.text
|
|
1130
|
+
};
|
|
1131
|
+
case "action":
|
|
1132
|
+
case "submit": return {
|
|
1133
|
+
type: "postback",
|
|
1134
|
+
label: label === "" ? el.attrs.id : label,
|
|
1135
|
+
data: el.attrs.id
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
/** Build the `text` mode. */
|
|
1140
|
+
function createTextMode() {
|
|
1141
|
+
return {
|
|
1142
|
+
id: "text",
|
|
1143
|
+
elements: new ElementRegistry().register("text", (el) => ({
|
|
1144
|
+
type: "text",
|
|
1145
|
+
text: el.attrs.content
|
|
1146
|
+
})).register("br", () => ({
|
|
1147
|
+
type: "text",
|
|
1148
|
+
text: "\n"
|
|
1149
|
+
})).register("p", (el, ctx) => [...ctx.render(el.children), {
|
|
1150
|
+
type: "text",
|
|
1151
|
+
text: "\n\n"
|
|
1152
|
+
}]).register("a", (el, ctx) => {
|
|
1153
|
+
const run = textRun(ctx.render(el.children));
|
|
1154
|
+
return [{
|
|
1155
|
+
type: "text",
|
|
1156
|
+
text: run.text.includes(el.attrs.href) ? run.text : run.text.trim() === "" ? el.attrs.href : `${run.text} (${el.attrs.href})`
|
|
1157
|
+
}, ...run.nodes];
|
|
1158
|
+
}).register("img", (el, ctx) => imageNode(el, ctx), { variants: ["inline"] }).register("video", (el, ctx) => videoNode(el, ctx)).register("audio", (el, ctx) => audioNode(el, ctx)).register("button", (el, ctx) => ({
|
|
1159
|
+
type: "button",
|
|
1160
|
+
action: buttonAction(el, ctx)
|
|
1161
|
+
}), { variants: [
|
|
1162
|
+
"action",
|
|
1163
|
+
"link",
|
|
1164
|
+
"input",
|
|
1165
|
+
"submit",
|
|
1166
|
+
"theme",
|
|
1167
|
+
"inline"
|
|
1168
|
+
] }).register("button-group", (el, ctx) => ctx.render(el.children)),
|
|
1169
|
+
limits: {
|
|
1170
|
+
"limit.text.chars": LINE_LIMITS.text,
|
|
1171
|
+
"limit.buttons.rows": LINE_LIMITS.quickReplies,
|
|
1172
|
+
"limit.payload.bytes": LINE_LIMITS.payloadBytes
|
|
1173
|
+
},
|
|
1174
|
+
assemble: (nodes) => assembleDraft(nodes),
|
|
1175
|
+
serialize: (prepared, ctx) => serializeDraft(prepared, ctx),
|
|
1176
|
+
check: (draft) => checkDraft(draft)
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
// lib/types/send.js
|
|
1180
|
+
/**
|
|
1181
|
+
* Outbound: one push request per draft, and the member pages `im_members` reads.
|
|
1182
|
+
*
|
|
1183
|
+
* LINE has no reply API the DSH pipeline could use — a reply token lives one minute and is single-use, while a turn may
|
|
1184
|
+
* run for minutes — so every send is a push. The reply token is still kept in the inbound referrer for a plugin that
|
|
1185
|
+
* calls `bot.internal.replyMessage` itself.
|
|
1186
|
+
*/
|
|
1187
|
+
/**
|
|
1188
|
+
* Send one serialized payload and report the parts the platform created.
|
|
1189
|
+
*
|
|
1190
|
+
* A refused push is a request-level failure: LINE has no partial send, and it documents that a request answered with an
|
|
1191
|
+
* error sent nothing.
|
|
1192
|
+
*
|
|
1193
|
+
* @param deps - the adapter's API surface.
|
|
1194
|
+
* @param payload - one push body.
|
|
1195
|
+
* @param _target - the chat the payload goes to; the recipient already rides `payload.to`.
|
|
1196
|
+
* @param _ctx - the core send context; this adapter keeps no per-part state.
|
|
1197
|
+
* @returns the published part; its `aliases` are the remaining message ids of the same request.
|
|
1198
|
+
* @throws PlatformError `invalid` when the answer carries no `sentMessages`, with an unknown outcome.
|
|
1199
|
+
*/
|
|
1200
|
+
async function sendPayload(deps, payload, _target, _ctx) {
|
|
1201
|
+
const sent = (await deps.internal.pushMessage({
|
|
1202
|
+
to: payload.to,
|
|
1203
|
+
messages: payload.messages
|
|
1204
|
+
})).sentMessages ?? [];
|
|
1205
|
+
const [head, ...rest] = sent;
|
|
1206
|
+
if (head === void 0) throw new PlatformError("invalid", "line: pushMessage answered without sentMessages", { published: "unknown" });
|
|
1207
|
+
return {
|
|
1208
|
+
id: head.id,
|
|
1209
|
+
kind: "message",
|
|
1210
|
+
time: Date.now(),
|
|
1211
|
+
...rest.length === 0 ? {} : { aliases: rest.map((message) => message.id) },
|
|
1212
|
+
raw: {
|
|
1213
|
+
ids: sent.map((message) => message.id),
|
|
1214
|
+
quoteTokens: sent.map((message) => message.quoteToken)
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* One page of the members of a chat.
|
|
1220
|
+
*
|
|
1221
|
+
* A group or a room lists its member ids through the platform; a direct chat's only member is the peer, which the
|
|
1222
|
+
* `chat.id` already names. Names are not filled in: the platform wants one profile request per member, and that
|
|
1223
|
+
* request is refused for a user who has not agreed to the Official Accounts Terms of Use.
|
|
1224
|
+
*
|
|
1225
|
+
* @param deps - the adapter's API surface.
|
|
1226
|
+
* @param chat - the chat to list.
|
|
1227
|
+
* @param cursor - the previous page's `next` token, valid for 24 hours.
|
|
1228
|
+
* @param _limit - unused; the platform fixes the page size at 100 and the host truncates the answer.
|
|
1229
|
+
* @returns one page of member ids.
|
|
1230
|
+
*/
|
|
1231
|
+
async function members(deps, chat, cursor, _limit) {
|
|
1232
|
+
const address = parseChatId(chat.id);
|
|
1233
|
+
if (address.kind === "user") return { data: [{ id: address.id }] };
|
|
1234
|
+
const query = cursor === void 0 ? void 0 : { start: cursor };
|
|
1235
|
+
const answer = address.kind === "group" ? await deps.internal.getGroupMembersIds(address.id, query) : await deps.internal.getRoomMembersIds(address.id, query);
|
|
1236
|
+
return {
|
|
1237
|
+
data: answer.memberIds.map((id) => ({ id })),
|
|
1238
|
+
...answer.next === void 0 ? {} : { next: answer.next }
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
// lib/types/transport/media.js
|
|
1242
|
+
/**
|
|
1243
|
+
* Outbound media: the public route LINE fetches staged bytes from.
|
|
1244
|
+
*
|
|
1245
|
+
* The Messaging API has no endpoint that uploads message media; an image, video or audio message carries only HTTPS URLs
|
|
1246
|
+
* that the LINE servers fetch themselves. The adapter therefore stages the bytes of every non-HTTPS source in memory
|
|
1247
|
+
* and serves them from an anonymous, unguessable URL for the lifetime of the process.
|
|
1248
|
+
*/
|
|
1249
|
+
/**
|
|
1250
|
+
* Staged bytes by opaque token.
|
|
1251
|
+
*
|
|
1252
|
+
* Entries live until the process exits: the platform may fetch a URL minutes after a send, and the W1 rule forbids
|
|
1253
|
+
* inventing a TTL or a byte cap the platform does not document. The `prepare` cache means the same media is staged
|
|
1254
|
+
* once, not once per send.
|
|
1255
|
+
*/
|
|
1256
|
+
var MediaStaging = class {
|
|
1257
|
+
base;
|
|
1258
|
+
prefix;
|
|
1259
|
+
entries = /* @__PURE__ */ new Map();
|
|
1260
|
+
constructor(base, prefix) {
|
|
1261
|
+
this.base = base;
|
|
1262
|
+
this.prefix = prefix;
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Stage one attachment.
|
|
1266
|
+
*
|
|
1267
|
+
* @param media - the bytes, their MIME type and name.
|
|
1268
|
+
* @returns the public URL LINE fetches the bytes from.
|
|
1269
|
+
*/
|
|
1270
|
+
stage(media) {
|
|
1271
|
+
const token = randomBytes(16).toString("base64url");
|
|
1272
|
+
this.entries.set(token, media);
|
|
1273
|
+
return `${this.base}${this.prefix}/${token}`;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Read staged bytes back.
|
|
1277
|
+
*
|
|
1278
|
+
* @param token - the last path segment of a URL returned by {@link stage}.
|
|
1279
|
+
* @returns the staged attachment, or undefined for an unknown token.
|
|
1280
|
+
*/
|
|
1281
|
+
get(token) {
|
|
1282
|
+
return this.entries.get(token);
|
|
1283
|
+
}
|
|
1284
|
+
/** The number of attachments currently staged, for tests and diagnostics. */
|
|
1285
|
+
get size() {
|
|
1286
|
+
return this.entries.size;
|
|
1287
|
+
}
|
|
1288
|
+
};
|
|
1289
|
+
/**
|
|
1290
|
+
* The public media route.
|
|
1291
|
+
*
|
|
1292
|
+
* It is registered as a `prefix` resource, so the web server hands it a Fetch `Request` and takes the `Response` back;
|
|
1293
|
+
* the route is anonymous because LINE's servers carry no DSH peer credential.
|
|
1294
|
+
*/
|
|
1295
|
+
var LineMediaRoute = class {
|
|
1296
|
+
bot;
|
|
1297
|
+
webServer;
|
|
1298
|
+
dispose;
|
|
1299
|
+
constructor(bot, webServer) {
|
|
1300
|
+
this.bot = bot;
|
|
1301
|
+
this.webServer = webServer;
|
|
1302
|
+
}
|
|
1303
|
+
/** Register the prefix route. */
|
|
1304
|
+
start() {
|
|
1305
|
+
const path = routePath(this.bot.config.media.path);
|
|
1306
|
+
this.dispose = this.webServer.register({
|
|
1307
|
+
kind: "prefix",
|
|
1308
|
+
path,
|
|
1309
|
+
auth: "anonymous",
|
|
1310
|
+
resource: (request) => this.serve(request)
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
/** Release the route. */
|
|
1314
|
+
stop() {
|
|
1315
|
+
this.dispose?.();
|
|
1316
|
+
this.dispose = void 0;
|
|
1317
|
+
}
|
|
1318
|
+
async serve(request) {
|
|
1319
|
+
const prefix = `${routePath(this.bot.config.media.path)}/`;
|
|
1320
|
+
const { pathname } = new URL(request.url);
|
|
1321
|
+
if (!pathname.startsWith(prefix)) return new Response(null, { status: 404 });
|
|
1322
|
+
const segment = pathname.slice(prefix.length);
|
|
1323
|
+
let token;
|
|
1324
|
+
try {
|
|
1325
|
+
token = decodeURIComponent(segment);
|
|
1326
|
+
} catch {
|
|
1327
|
+
return new Response(null, { status: 404 });
|
|
1328
|
+
}
|
|
1329
|
+
const media = this.bot.staging.get(token);
|
|
1330
|
+
if (media === void 0) return new Response(null, { status: 404 });
|
|
1331
|
+
const headers = new Headers();
|
|
1332
|
+
headers.set("content-type", media.mime ?? "application/octet-stream");
|
|
1333
|
+
headers.set("content-length", String(media.data.byteLength));
|
|
1334
|
+
return new Response(media.data, {
|
|
1335
|
+
status: 200,
|
|
1336
|
+
headers
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
};
|
|
1340
|
+
// lib/types/signature.js
|
|
1341
|
+
/**
|
|
1342
|
+
* The `x-line-signature` value of one webhook request.
|
|
1343
|
+
*
|
|
1344
|
+
* LINE signs the request body exactly as it arrived, keyed by the channel secret.
|
|
1345
|
+
*
|
|
1346
|
+
* @param secret - the channel secret.
|
|
1347
|
+
* @param body - the raw request body, before any decoding.
|
|
1348
|
+
* @returns base64 of `HMAC-SHA256(secret, body)`.
|
|
1349
|
+
*/
|
|
1350
|
+
function signatureOf(secret, body) {
|
|
1351
|
+
return createHmac("sha256", secret).update(body).digest("base64");
|
|
1352
|
+
}
|
|
1353
|
+
/**
|
|
1354
|
+
* Compare a received signature with the computed one without leaking where they differ.
|
|
1355
|
+
*
|
|
1356
|
+
* @param expected - the signature computed from the body.
|
|
1357
|
+
* @param received - the header value, if the request carried one.
|
|
1358
|
+
* @returns whether the header matches.
|
|
1359
|
+
*/
|
|
1360
|
+
function matchesSignature(expected, received) {
|
|
1361
|
+
if (received === void 0) return false;
|
|
1362
|
+
const left = Buffer.from(expected, "utf8");
|
|
1363
|
+
const right = Buffer.from(received, "utf8");
|
|
1364
|
+
if (left.length !== right.length) return false;
|
|
1365
|
+
return timingSafeEqual(left, right);
|
|
1366
|
+
}
|
|
1367
|
+
// lib/types/transport/webhook.js
|
|
1368
|
+
/**
|
|
1369
|
+
* The webhook transport.
|
|
1370
|
+
*
|
|
1371
|
+
* LINE has no long connection, polling or gateway: the only inbound path is an HTTPS POST to a URL configured in the
|
|
1372
|
+
* console. The route is registered on the profile's `webServer`, which owns the listener and the public address; the
|
|
1373
|
+
* adapter keeps the handler anonymous and authenticates every request with the channel secret.
|
|
1374
|
+
*
|
|
1375
|
+
* The handler answers `200` only after intake stored the events, so a retrying platform can resend a failed delivery,
|
|
1376
|
+
* and it answers every refusal before any work is done.
|
|
1377
|
+
*/
|
|
1378
|
+
/** Header LINE signs the request with. */
|
|
1379
|
+
const SIGNATURE_HEADER = "x-line-signature";
|
|
1380
|
+
/** Message of any caught value, for a log line. */
|
|
1381
|
+
function messageOf$1(error) {
|
|
1382
|
+
return error instanceof Error ? error.message : String(error);
|
|
1383
|
+
}
|
|
1384
|
+
/** One header of an inbound request, when it arrived exactly once. */
|
|
1385
|
+
function headerOf(request, name) {
|
|
1386
|
+
const value = request.headers[name];
|
|
1387
|
+
return typeof value === "string" ? value : void 0;
|
|
1388
|
+
}
|
|
1389
|
+
/** Read a request body to its end. LINE publishes no body-size limit, so the adapter imposes none. */
|
|
1390
|
+
async function readBody(request) {
|
|
1391
|
+
const chunks = [];
|
|
1392
|
+
for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
1393
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
1394
|
+
}
|
|
1395
|
+
/** Write one bodiless answer. */
|
|
1396
|
+
function writeStatus(response, status, headers = {}) {
|
|
1397
|
+
response.writeHead(status, headers);
|
|
1398
|
+
response.end();
|
|
1399
|
+
}
|
|
1400
|
+
/** One event source, when the payload names a conversation kind this adapter knows. */
|
|
1401
|
+
function isEventSource(value) {
|
|
1402
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1403
|
+
const record = value;
|
|
1404
|
+
switch (record.type) {
|
|
1405
|
+
case "user": return typeof record.userId === "string";
|
|
1406
|
+
case "group": return typeof record.groupId === "string";
|
|
1407
|
+
case "room": return typeof record.roomId === "string";
|
|
1408
|
+
default: return false;
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
/** One event envelope, as far as decoding needs it: a type, a channel mode, a time and a source. */
|
|
1412
|
+
function isWebhookEvent(value) {
|
|
1413
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1414
|
+
const record = value;
|
|
1415
|
+
return typeof record.type === "string" && (record.mode === "active" || record.mode === "standby") && typeof record.timestamp === "number" && isEventSource(record.source);
|
|
1416
|
+
}
|
|
1417
|
+
/**
|
|
1418
|
+
* The parsed webhook body, when its envelope is complete.
|
|
1419
|
+
*
|
|
1420
|
+
* @param value - the parsed JSON value.
|
|
1421
|
+
* @returns the typed body, or undefined when the value is not a webhook body.
|
|
1422
|
+
*/
|
|
1423
|
+
function parseWebhookBody(value) {
|
|
1424
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
1425
|
+
const record = value;
|
|
1426
|
+
if (typeof record.destination !== "string") return void 0;
|
|
1427
|
+
if (!Array.isArray(record.events)) return void 0;
|
|
1428
|
+
const events = [];
|
|
1429
|
+
for (const item of record.events) {
|
|
1430
|
+
if (!isWebhookEvent(item)) return void 0;
|
|
1431
|
+
events.push(item);
|
|
1432
|
+
}
|
|
1433
|
+
return {
|
|
1434
|
+
destination: record.destination,
|
|
1435
|
+
events
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* The webhook route.
|
|
1440
|
+
*
|
|
1441
|
+
* `start` registers the route and `announce` points the channel at it, so the media route of the same connect is in
|
|
1442
|
+
* place before the channel starts delivering anything.
|
|
1443
|
+
*/
|
|
1444
|
+
var LineWebhook = class {
|
|
1445
|
+
bot;
|
|
1446
|
+
webServer;
|
|
1447
|
+
dispose;
|
|
1448
|
+
constructor(bot, webServer) {
|
|
1449
|
+
this.bot = bot;
|
|
1450
|
+
this.webServer = webServer;
|
|
1451
|
+
}
|
|
1452
|
+
/** Register the route. */
|
|
1453
|
+
start() {
|
|
1454
|
+
const path = routePath(this.bot.config.webhook.path);
|
|
1455
|
+
this.dispose = this.webServer.register({
|
|
1456
|
+
kind: "exact",
|
|
1457
|
+
path,
|
|
1458
|
+
auth: "anonymous",
|
|
1459
|
+
handler: (request, response) => this.handle(request, response)
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Point the channel at the registered route and read the endpoint state back.
|
|
1464
|
+
*
|
|
1465
|
+
* A profile that cannot receive anything fails at connect with an actionable message instead of silently getting no
|
|
1466
|
+
* events; the route is released on that failure so a half-configured connect leaves nothing behind.
|
|
1467
|
+
*/
|
|
1468
|
+
async announce() {
|
|
1469
|
+
try {
|
|
1470
|
+
await this.bot.internal.setWebhookEndpoint({ endpoint: `${publicBase(this.bot.config.publicUrl)}${routePath(this.bot.config.webhook.path)}` });
|
|
1471
|
+
} catch (error) {
|
|
1472
|
+
this.stop();
|
|
1473
|
+
this.bot.ctx.logger.error("line: setWebhookEndpoint failed: %s", messageOf$1(error));
|
|
1474
|
+
throw error;
|
|
1475
|
+
}
|
|
1476
|
+
await this.readBackEndpoint();
|
|
1477
|
+
}
|
|
1478
|
+
/** Release the route. The channel keeps its endpoint: clearing it would point LINE at a 404. */
|
|
1479
|
+
stop() {
|
|
1480
|
+
this.dispose?.();
|
|
1481
|
+
this.dispose = void 0;
|
|
1482
|
+
}
|
|
1483
|
+
/**
|
|
1484
|
+
* Read the endpoint state back after registering it.
|
|
1485
|
+
*
|
|
1486
|
+
* A channel whose "Use webhook" switch is off answers `active: false`; the console takes up to a minute to apply the
|
|
1487
|
+
* new endpoint, so this only warns and never fails the connect.
|
|
1488
|
+
*/
|
|
1489
|
+
async readBackEndpoint() {
|
|
1490
|
+
try {
|
|
1491
|
+
if (!(await this.bot.internal.getWebhookEndpoint()).active) this.bot.ctx.logger.warn("line: the webhook endpoint is not active; turn on \"Use webhook\" in the LINE console");
|
|
1492
|
+
} catch (error) {
|
|
1493
|
+
this.bot.ctx.logger.warn("line: the webhook endpoint could not be read back: %s", messageOf$1(error));
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
async handle(request, response) {
|
|
1497
|
+
try {
|
|
1498
|
+
if (request.method !== "POST") {
|
|
1499
|
+
writeStatus(response, 405, { allow: "POST" });
|
|
1500
|
+
return;
|
|
1501
|
+
}
|
|
1502
|
+
const received = headerOf(request, SIGNATURE_HEADER);
|
|
1503
|
+
if (received === void 0) {
|
|
1504
|
+
writeStatus(response, 401);
|
|
1505
|
+
return;
|
|
1506
|
+
}
|
|
1507
|
+
const body = await readBody(request);
|
|
1508
|
+
if (!matchesSignature(signatureOf(this.bot.config.secret, body), received)) {
|
|
1509
|
+
writeStatus(response, 401);
|
|
1510
|
+
return;
|
|
1511
|
+
}
|
|
1512
|
+
let parsed;
|
|
1513
|
+
try {
|
|
1514
|
+
parsed = JSON.parse(body);
|
|
1515
|
+
} catch (error) {
|
|
1516
|
+
this.bot.ctx.logger.warn("line: cannot parse a webhook request: %s", messageOf$1(error));
|
|
1517
|
+
writeStatus(response, 400);
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1520
|
+
const payload = parseWebhookBody(parsed);
|
|
1521
|
+
if (payload === void 0) {
|
|
1522
|
+
writeStatus(response, 400);
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
if (payload.destination !== this.bot.selfId) {
|
|
1526
|
+
writeStatus(response, 403);
|
|
1527
|
+
return;
|
|
1528
|
+
}
|
|
1529
|
+
if (payload.events.length === 0) {
|
|
1530
|
+
writeStatus(response, 200);
|
|
1531
|
+
return;
|
|
1532
|
+
}
|
|
1533
|
+
for (const event of payload.events) {
|
|
1534
|
+
const session = decodeEvent(this.bot, event);
|
|
1535
|
+
if (session !== void 0) await this.bot.receive(session);
|
|
1536
|
+
}
|
|
1537
|
+
writeStatus(response, 200);
|
|
1538
|
+
} catch (error) {
|
|
1539
|
+
this.bot.ctx.logger.warn("line: webhook delivery failed: %s", messageOf$1(error));
|
|
1540
|
+
if (!response.headersSent) writeStatus(response, 500);
|
|
1541
|
+
else response.end();
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
};
|
|
1545
|
+
// lib/types/bot.js
|
|
1546
|
+
/** Message of any caught value, for a log line. */
|
|
1547
|
+
function messageOf(error) {
|
|
1548
|
+
return error instanceof Error ? error.message : String(error);
|
|
1549
|
+
}
|
|
1550
|
+
/** Whether a resource source is a public HTTPS URL LINE can fetch itself. */
|
|
1551
|
+
function isHttpsSource(src) {
|
|
1552
|
+
try {
|
|
1553
|
+
return new URL(src).protocol === "https:";
|
|
1554
|
+
} catch {
|
|
1555
|
+
return false;
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* LINE Messaging API adapter.
|
|
1560
|
+
*
|
|
1561
|
+
* The channel is identified by configuration (`selfId`), confirmed with `getBotInfo` on connect. The webhook is the
|
|
1562
|
+
* only transport, `text` is the only mode, and every send is a push: a reply token lives one minute and is single-use,
|
|
1563
|
+
* while a turn may run for minutes. Outbound media is staged in memory and served from a public route, because the
|
|
1564
|
+
* platform accepts media only as HTTPS URLs it fetches itself.
|
|
1565
|
+
*/
|
|
1566
|
+
var LineBot = class extends Adapter {
|
|
1567
|
+
/** The adapter needs the Satori service and the isolated `http` service. */
|
|
1568
|
+
static inject = ["satori", "http"];
|
|
1569
|
+
/** The Loader applies this schema to a profile row's `config` before the constructor runs. */
|
|
1570
|
+
static Config = Config;
|
|
1571
|
+
modes = { text: createTextMode() };
|
|
1572
|
+
modeOrder = ["text"];
|
|
1573
|
+
/** Endpoints shared by the API client and the content download. */
|
|
1574
|
+
request;
|
|
1575
|
+
/** Full typed Messaging API surface registered by the vendored declarations. */
|
|
1576
|
+
internal;
|
|
1577
|
+
/** Outbound media bytes, served from the public media route. */
|
|
1578
|
+
staging;
|
|
1579
|
+
webhook;
|
|
1580
|
+
mediaRoute;
|
|
1581
|
+
constructor(ctx, config) {
|
|
1582
|
+
super(ctx, config, {
|
|
1583
|
+
id: `line:${config.selfId}`,
|
|
1584
|
+
platform: "line",
|
|
1585
|
+
adapter: "line"
|
|
1586
|
+
});
|
|
1587
|
+
this.selfId = config.selfId;
|
|
1588
|
+
this.request = {
|
|
1589
|
+
ctx,
|
|
1590
|
+
config
|
|
1591
|
+
};
|
|
1592
|
+
this.internal = new Internal(this.request);
|
|
1593
|
+
this.staging = new MediaStaging(publicBase(config.publicUrl), routePath(config.media.path));
|
|
1594
|
+
this.defineInternalRoute("/assets/:messageId", async ({ params }) => serveMessageContent(this, params.messageId));
|
|
1595
|
+
}
|
|
1596
|
+
async connect() {
|
|
1597
|
+
const invalid = configError(this.config);
|
|
1598
|
+
if (invalid !== void 0) {
|
|
1599
|
+
this.ctx.logger.error("line: connect failed: %s", invalid.message);
|
|
1600
|
+
throw invalid;
|
|
1601
|
+
}
|
|
1602
|
+
const webServer = this.ctx.get("webServer");
|
|
1603
|
+
if (webServer === void 0) {
|
|
1604
|
+
const error = /* @__PURE__ */ new Error("line: this adapter needs a profile-provided webServer; LINE has only the webhook transport, so add a webServer row to the profile and make publicUrl reachable from the internet");
|
|
1605
|
+
this.ctx.logger.error(error.message);
|
|
1606
|
+
throw error;
|
|
1607
|
+
}
|
|
1608
|
+
try {
|
|
1609
|
+
const info = await this.internal.getBotInfo();
|
|
1610
|
+
this.selfId = verifyIdentity(this.config.selfId, info);
|
|
1611
|
+
this.user = {
|
|
1612
|
+
id: info.userId,
|
|
1613
|
+
name: info.displayName,
|
|
1614
|
+
isBot: true
|
|
1615
|
+
};
|
|
1616
|
+
const webhook = new LineWebhook(this, webServer);
|
|
1617
|
+
const mediaRoute = new LineMediaRoute(this, webServer);
|
|
1618
|
+
webhook.start();
|
|
1619
|
+
try {
|
|
1620
|
+
mediaRoute.start();
|
|
1621
|
+
} catch (error) {
|
|
1622
|
+
webhook.stop();
|
|
1623
|
+
throw error;
|
|
1624
|
+
}
|
|
1625
|
+
try {
|
|
1626
|
+
await webhook.announce();
|
|
1627
|
+
} catch (error) {
|
|
1628
|
+
mediaRoute.stop();
|
|
1629
|
+
throw error;
|
|
1630
|
+
}
|
|
1631
|
+
this.webhook = webhook;
|
|
1632
|
+
this.mediaRoute = mediaRoute;
|
|
1633
|
+
this.online();
|
|
1634
|
+
} catch (error) {
|
|
1635
|
+
this.ctx.logger.error("line: connect failed: %s", messageOf(error));
|
|
1636
|
+
throw error;
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
async disconnect() {
|
|
1640
|
+
const webhook = this.webhook;
|
|
1641
|
+
const mediaRoute = this.mediaRoute;
|
|
1642
|
+
this.webhook = void 0;
|
|
1643
|
+
this.mediaRoute = void 0;
|
|
1644
|
+
webhook?.stop();
|
|
1645
|
+
mediaRoute?.stop();
|
|
1646
|
+
}
|
|
1647
|
+
/**
|
|
1648
|
+
* Turn one outbound attachment into the key a message object carries.
|
|
1649
|
+
*
|
|
1650
|
+
* A public HTTPS source is passed through untouched: LINE fetches it, so the bytes never enter this process. Every
|
|
1651
|
+
* other source (`data:`, `base64:`, `satori:`, `file:`, plain HTTP) is fetched and staged on the public media route.
|
|
1652
|
+
*/
|
|
1653
|
+
async upload(ref, _scope, ctx) {
|
|
1654
|
+
if (isHttpsSource(ref.src)) return {
|
|
1655
|
+
key: ref.src,
|
|
1656
|
+
extra: {
|
|
1657
|
+
name: ref.meta.name,
|
|
1658
|
+
mime: ref.meta.mime
|
|
1659
|
+
}
|
|
1660
|
+
};
|
|
1661
|
+
let fetched;
|
|
1662
|
+
try {
|
|
1663
|
+
fetched = await ctx.fetch(ref.src, ctx.signal);
|
|
1664
|
+
} catch (error) {
|
|
1665
|
+
if (ctx.signal.aborted) throw error;
|
|
1666
|
+
throw new PlatformError("invalid", `line: media source ${ref.src} could not be read: ${messageOf(error)}`, {
|
|
1667
|
+
published: "no",
|
|
1668
|
+
cause: error
|
|
1669
|
+
});
|
|
1670
|
+
}
|
|
1671
|
+
const mime = ref.meta.mime ?? fetched.mime;
|
|
1672
|
+
const name = ref.meta.name ?? fetched.name;
|
|
1673
|
+
return {
|
|
1674
|
+
key: this.staging.stage({
|
|
1675
|
+
data: fetched.data,
|
|
1676
|
+
...mime === void 0 ? {} : { mime },
|
|
1677
|
+
...name === void 0 ? {} : { name }
|
|
1678
|
+
}),
|
|
1679
|
+
extra: {
|
|
1680
|
+
...name === void 0 ? {} : { name },
|
|
1681
|
+
...mime === void 0 ? {} : { mime },
|
|
1682
|
+
size: fetched.data.byteLength
|
|
1683
|
+
}
|
|
1684
|
+
};
|
|
1685
|
+
}
|
|
1686
|
+
resourceScope(_target, _kind) {
|
|
1687
|
+
return this.id;
|
|
1688
|
+
}
|
|
1689
|
+
async sendPayload(payload, target, ctx) {
|
|
1690
|
+
return await sendPayload({ internal: this.internal }, payload, target, ctx);
|
|
1691
|
+
}
|
|
1692
|
+
async members(chat, cursor, limit) {
|
|
1693
|
+
return await members({ internal: this.internal }, chat, cursor, limit);
|
|
1694
|
+
}
|
|
1695
|
+
classify(error) {
|
|
1696
|
+
return classifyLineError(error);
|
|
1697
|
+
}
|
|
1698
|
+
};
|
|
1699
|
+
export { Config, Internal, LINE_API_ORIGIN, LINE_DATA_ORIGIN, LINE_LIMITS, types_exports as Line, LineApiError, LineBot, LineBot as default, LineIdentityError, LineMediaRoute, LineWebhook, MediaStaging, chatIdOf, chatRefOf, chatTargetOf, classifyLineError, configError, decodeEvent, downloadContent, invoke, matchesSignature, members, parseChatId, publicBase, routePath, sendPayload, serveMessageContent, signatureOf, verifyIdentity };
|
|
1700
|
+
|
|
1701
|
+
//# sourceMappingURL=index.js.map
|