@theokit/gateway-line 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.
@@ -0,0 +1,226 @@
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, LineMessageEvent } from '@theokit/gateway';
2
+ import { Express } from 'express';
3
+
4
+ /**
5
+ * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.
6
+ */
7
+ interface LineSdkClient {
8
+ replyMessage(replyToken: string, messages: Array<{
9
+ type: "text";
10
+ text: string;
11
+ }>): Promise<unknown>;
12
+ pushMessage(to: string, messages: Array<{
13
+ type: "text";
14
+ text: string;
15
+ }>): Promise<unknown>;
16
+ }
17
+
18
+ /**
19
+ * Public option types + internal LINE webhook event shapes.
20
+ *
21
+ * Only the subset we actually read from `@line/bot-sdk` is declared
22
+ * here; we keep peer-dep types out of the public surface so consumers
23
+ * can install the LINE SDK at any compatible version.
24
+ *
25
+ * @public
26
+ */
27
+ interface LineAdapterOptions {
28
+ /** From LINE Developers Console → Messaging API → Channel secret. */
29
+ readonly channelSecret: string;
30
+ /** From LINE Developers Console → Messaging API → Channel access token (long-lived). */
31
+ readonly channelAccessToken: string;
32
+ /**
33
+ * Bot's own LINE user id (`Uxxx...`). When set + `requireMention: true`,
34
+ * the adapter checks `botUserId in event.message.mentionees`.
35
+ * When unset, the mention guard is disabled.
36
+ */
37
+ readonly botUserId?: string;
38
+ /** Default `true`. Set `false` to bypass mention enforcement. */
39
+ readonly requireMention?: boolean;
40
+ }
41
+ /**
42
+ * LINE webhook source object (subset). The 3 source types from the API:
43
+ * `user` (1:1), `group` (multi-user persistent), `room` (multi-user ephemeral).
44
+ *
45
+ * @public
46
+ */
47
+ interface LineSource {
48
+ readonly type: "user" | "group" | "room" | (string & {});
49
+ readonly userId?: string;
50
+ readonly groupId?: string;
51
+ readonly roomId?: string;
52
+ }
53
+ /**
54
+ * LINE webhook event (subset we read). Real events from `@line/bot-sdk`
55
+ * carry more fields (`timestamp`, `webhookEventId`, etc.) — preserved
56
+ * via `event.line.raw`.
57
+ *
58
+ * @public
59
+ */
60
+ interface LineWebhookEvent {
61
+ readonly type: "message" | "follow" | "unfollow" | "join" | "leave" | "postback" | "beacon" | "accountLink" | "things" | (string & {});
62
+ readonly timestamp?: number;
63
+ readonly source?: LineSource;
64
+ readonly replyToken?: string;
65
+ readonly message?: LineMessage;
66
+ readonly webhookEventId?: string;
67
+ }
68
+ /**
69
+ * Minimal LINE message shape (text only in v0.1).
70
+ *
71
+ * @public
72
+ */
73
+ interface LineMessage {
74
+ readonly type: "text" | "image" | "audio" | "video" | "sticker" | "location" | (string & {});
75
+ readonly id?: string;
76
+ readonly text?: string;
77
+ readonly mentionees?: ReadonlyArray<{
78
+ readonly index: number;
79
+ readonly length: number;
80
+ readonly userId?: string;
81
+ }>;
82
+ }
83
+ /** Webhook request envelope `{ destination, events: [...] }`. */
84
+ interface LineWebhookEnvelope {
85
+ readonly destination?: string;
86
+ readonly events: ReadonlyArray<LineWebhookEvent>;
87
+ }
88
+
89
+ /**
90
+ * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.
91
+ * ADRs D405-D412.
92
+ *
93
+ * @public
94
+ */
95
+
96
+ declare class LineAdapter extends BasePlatformAdapter {
97
+ readonly platform: "line";
98
+ private readonly opts;
99
+ private readonly replyCache;
100
+ private client;
101
+ private inboundHandler;
102
+ private connected;
103
+ constructor(opts: LineAdapterOptions);
104
+ connect(): Promise<boolean>;
105
+ disconnect(): Promise<void>;
106
+ sendMessage(out: OutboundMessage): Promise<SendResult>;
107
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
108
+ /** Escape hatch: caller drives Flex/Carousel/etc directly. */
109
+ getClient(): LineSdkClient | undefined;
110
+ /**
111
+ * Webhook entrypoint — called by `createWebhookServer` AFTER signature
112
+ * validation. Iterates LINE's batch envelope and dispatches each event.
113
+ */
114
+ dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void>;
115
+ private dispatchSingleEvent;
116
+ private passesMentionGuard;
117
+ /** Expose channel secret for the webhook server (signature middleware). */
118
+ getChannelSecret(): string;
119
+ /** Used by tests to seed the reply cache (no other path exposes raw cache). */
120
+ _cacheReplyToken(userId: string, token: string): void;
121
+ }
122
+
123
+ /**
124
+ * Typed errors for `@theokit/gateway-line`.
125
+ */
126
+ /** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
127
+ interface ConfigurationErrorOptions {
128
+ readonly code: string;
129
+ readonly message?: string;
130
+ readonly detail?: string;
131
+ }
132
+ declare class ConfigurationError extends Error {
133
+ readonly name = "ConfigurationError";
134
+ readonly code: string;
135
+ readonly detail: string | undefined;
136
+ constructor(opts: ConfigurationErrorOptions);
137
+ }
138
+ declare class SDKNotInstalledError extends ConfigurationError {
139
+ constructor(pkgName: string);
140
+ }
141
+
142
+ /**
143
+ * Inbound normalization: LINE webhook event → LineMessageEvent.
144
+ *
145
+ * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`
146
+ * events of `text` type are dispatched in v0.1; other types (`follow`,
147
+ * `unfollow`, `postback`, image/audio/sticker messages, etc.) return
148
+ * `undefined` so `adapter.dispatchEvent` skips them silently.
149
+ *
150
+ * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.
151
+ */
152
+
153
+ declare function mapSourceType(sourceType: string): "dm" | "group" | "thread";
154
+ declare function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined;
155
+
156
+ /**
157
+ * Reply-token LRU cache (D407).
158
+ *
159
+ * `put(userId, token)` — store with 60s TTL.
160
+ * `take(userId)` — atomic one-shot consume; second call returns undefined.
161
+ * `evictExpired()` — periodic GC; called internally before each take.
162
+ *
163
+ * Capacity 1000; oldest dropped when full.
164
+ */
165
+ declare class ReplyTokenCache {
166
+ private readonly cache;
167
+ private readonly ttlMs;
168
+ private readonly capacity;
169
+ constructor(opts?: {
170
+ ttlMs?: number;
171
+ capacity?: number;
172
+ });
173
+ put(userId: string, token: string): void;
174
+ take(userId: string): string | undefined;
175
+ size(): number;
176
+ clear(): void;
177
+ private evictOldest;
178
+ }
179
+
180
+ /**
181
+ * LINE HMAC-SHA256 signature verification (D408).
182
+ *
183
+ * Per LINE Developers docs:
184
+ * signature = base64(hmac_sha256(channelSecret, rawBody))
185
+ *
186
+ * Carried in header `X-Line-Signature`.
187
+ *
188
+ * Always uses `crypto.timingSafeEqual` to prevent timing attacks.
189
+ */
190
+ declare function computeLineSignature(channelSecret: string, rawBody: string): string;
191
+ declare function verifyLineSignature(channelSecret: string, rawBody: string, signatureHeader: string | undefined): boolean;
192
+
193
+ /**
194
+ * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).
195
+ *
196
+ * LINE limits text messages to 5000 chars. We segment with `Intl.Segmenter`
197
+ * so emoji, regional indicators, and combining sequences are never
198
+ * severed.
199
+ */
200
+ declare function splitForLine(text: string, limit?: number): string[];
201
+
202
+ /**
203
+ * Express webhook server for LINE inbound.
204
+ *
205
+ * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE
206
+ * parsing/dispatch — 401 on missing or invalid (D408).
207
+ *
208
+ * @public
209
+ */
210
+
211
+ interface WebhookServerOptions {
212
+ readonly adapter: LineAdapter;
213
+ /** Mount path; default `/line`. */
214
+ readonly path?: string;
215
+ /** Port to listen on when creating own Express app. Default 3000. */
216
+ readonly port?: number;
217
+ /** Inject an existing Express app. */
218
+ readonly app?: Express;
219
+ }
220
+ interface WebhookServer {
221
+ start(): Promise<void>;
222
+ stop(): Promise<void>;
223
+ }
224
+ declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
225
+
226
+ export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineEventToMessageEvent, mapSourceType, splitForLine, verifyLineSignature };
@@ -0,0 +1,226 @@
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, LineMessageEvent } from '@theokit/gateway';
2
+ import { Express } from 'express';
3
+
4
+ /**
5
+ * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.
6
+ */
7
+ interface LineSdkClient {
8
+ replyMessage(replyToken: string, messages: Array<{
9
+ type: "text";
10
+ text: string;
11
+ }>): Promise<unknown>;
12
+ pushMessage(to: string, messages: Array<{
13
+ type: "text";
14
+ text: string;
15
+ }>): Promise<unknown>;
16
+ }
17
+
18
+ /**
19
+ * Public option types + internal LINE webhook event shapes.
20
+ *
21
+ * Only the subset we actually read from `@line/bot-sdk` is declared
22
+ * here; we keep peer-dep types out of the public surface so consumers
23
+ * can install the LINE SDK at any compatible version.
24
+ *
25
+ * @public
26
+ */
27
+ interface LineAdapterOptions {
28
+ /** From LINE Developers Console → Messaging API → Channel secret. */
29
+ readonly channelSecret: string;
30
+ /** From LINE Developers Console → Messaging API → Channel access token (long-lived). */
31
+ readonly channelAccessToken: string;
32
+ /**
33
+ * Bot's own LINE user id (`Uxxx...`). When set + `requireMention: true`,
34
+ * the adapter checks `botUserId in event.message.mentionees`.
35
+ * When unset, the mention guard is disabled.
36
+ */
37
+ readonly botUserId?: string;
38
+ /** Default `true`. Set `false` to bypass mention enforcement. */
39
+ readonly requireMention?: boolean;
40
+ }
41
+ /**
42
+ * LINE webhook source object (subset). The 3 source types from the API:
43
+ * `user` (1:1), `group` (multi-user persistent), `room` (multi-user ephemeral).
44
+ *
45
+ * @public
46
+ */
47
+ interface LineSource {
48
+ readonly type: "user" | "group" | "room" | (string & {});
49
+ readonly userId?: string;
50
+ readonly groupId?: string;
51
+ readonly roomId?: string;
52
+ }
53
+ /**
54
+ * LINE webhook event (subset we read). Real events from `@line/bot-sdk`
55
+ * carry more fields (`timestamp`, `webhookEventId`, etc.) — preserved
56
+ * via `event.line.raw`.
57
+ *
58
+ * @public
59
+ */
60
+ interface LineWebhookEvent {
61
+ readonly type: "message" | "follow" | "unfollow" | "join" | "leave" | "postback" | "beacon" | "accountLink" | "things" | (string & {});
62
+ readonly timestamp?: number;
63
+ readonly source?: LineSource;
64
+ readonly replyToken?: string;
65
+ readonly message?: LineMessage;
66
+ readonly webhookEventId?: string;
67
+ }
68
+ /**
69
+ * Minimal LINE message shape (text only in v0.1).
70
+ *
71
+ * @public
72
+ */
73
+ interface LineMessage {
74
+ readonly type: "text" | "image" | "audio" | "video" | "sticker" | "location" | (string & {});
75
+ readonly id?: string;
76
+ readonly text?: string;
77
+ readonly mentionees?: ReadonlyArray<{
78
+ readonly index: number;
79
+ readonly length: number;
80
+ readonly userId?: string;
81
+ }>;
82
+ }
83
+ /** Webhook request envelope `{ destination, events: [...] }`. */
84
+ interface LineWebhookEnvelope {
85
+ readonly destination?: string;
86
+ readonly events: ReadonlyArray<LineWebhookEvent>;
87
+ }
88
+
89
+ /**
90
+ * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.
91
+ * ADRs D405-D412.
92
+ *
93
+ * @public
94
+ */
95
+
96
+ declare class LineAdapter extends BasePlatformAdapter {
97
+ readonly platform: "line";
98
+ private readonly opts;
99
+ private readonly replyCache;
100
+ private client;
101
+ private inboundHandler;
102
+ private connected;
103
+ constructor(opts: LineAdapterOptions);
104
+ connect(): Promise<boolean>;
105
+ disconnect(): Promise<void>;
106
+ sendMessage(out: OutboundMessage): Promise<SendResult>;
107
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
108
+ /** Escape hatch: caller drives Flex/Carousel/etc directly. */
109
+ getClient(): LineSdkClient | undefined;
110
+ /**
111
+ * Webhook entrypoint — called by `createWebhookServer` AFTER signature
112
+ * validation. Iterates LINE's batch envelope and dispatches each event.
113
+ */
114
+ dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void>;
115
+ private dispatchSingleEvent;
116
+ private passesMentionGuard;
117
+ /** Expose channel secret for the webhook server (signature middleware). */
118
+ getChannelSecret(): string;
119
+ /** Used by tests to seed the reply cache (no other path exposes raw cache). */
120
+ _cacheReplyToken(userId: string, token: string): void;
121
+ }
122
+
123
+ /**
124
+ * Typed errors for `@theokit/gateway-line`.
125
+ */
126
+ /** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */
127
+ interface ConfigurationErrorOptions {
128
+ readonly code: string;
129
+ readonly message?: string;
130
+ readonly detail?: string;
131
+ }
132
+ declare class ConfigurationError extends Error {
133
+ readonly name = "ConfigurationError";
134
+ readonly code: string;
135
+ readonly detail: string | undefined;
136
+ constructor(opts: ConfigurationErrorOptions);
137
+ }
138
+ declare class SDKNotInstalledError extends ConfigurationError {
139
+ constructor(pkgName: string);
140
+ }
141
+
142
+ /**
143
+ * Inbound normalization: LINE webhook event → LineMessageEvent.
144
+ *
145
+ * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`
146
+ * events of `text` type are dispatched in v0.1; other types (`follow`,
147
+ * `unfollow`, `postback`, image/audio/sticker messages, etc.) return
148
+ * `undefined` so `adapter.dispatchEvent` skips them silently.
149
+ *
150
+ * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.
151
+ */
152
+
153
+ declare function mapSourceType(sourceType: string): "dm" | "group" | "thread";
154
+ declare function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined;
155
+
156
+ /**
157
+ * Reply-token LRU cache (D407).
158
+ *
159
+ * `put(userId, token)` — store with 60s TTL.
160
+ * `take(userId)` — atomic one-shot consume; second call returns undefined.
161
+ * `evictExpired()` — periodic GC; called internally before each take.
162
+ *
163
+ * Capacity 1000; oldest dropped when full.
164
+ */
165
+ declare class ReplyTokenCache {
166
+ private readonly cache;
167
+ private readonly ttlMs;
168
+ private readonly capacity;
169
+ constructor(opts?: {
170
+ ttlMs?: number;
171
+ capacity?: number;
172
+ });
173
+ put(userId: string, token: string): void;
174
+ take(userId: string): string | undefined;
175
+ size(): number;
176
+ clear(): void;
177
+ private evictOldest;
178
+ }
179
+
180
+ /**
181
+ * LINE HMAC-SHA256 signature verification (D408).
182
+ *
183
+ * Per LINE Developers docs:
184
+ * signature = base64(hmac_sha256(channelSecret, rawBody))
185
+ *
186
+ * Carried in header `X-Line-Signature`.
187
+ *
188
+ * Always uses `crypto.timingSafeEqual` to prevent timing attacks.
189
+ */
190
+ declare function computeLineSignature(channelSecret: string, rawBody: string): string;
191
+ declare function verifyLineSignature(channelSecret: string, rawBody: string, signatureHeader: string | undefined): boolean;
192
+
193
+ /**
194
+ * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).
195
+ *
196
+ * LINE limits text messages to 5000 chars. We segment with `Intl.Segmenter`
197
+ * so emoji, regional indicators, and combining sequences are never
198
+ * severed.
199
+ */
200
+ declare function splitForLine(text: string, limit?: number): string[];
201
+
202
+ /**
203
+ * Express webhook server for LINE inbound.
204
+ *
205
+ * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE
206
+ * parsing/dispatch — 401 on missing or invalid (D408).
207
+ *
208
+ * @public
209
+ */
210
+
211
+ interface WebhookServerOptions {
212
+ readonly adapter: LineAdapter;
213
+ /** Mount path; default `/line`. */
214
+ readonly path?: string;
215
+ /** Port to listen on when creating own Express app. Default 3000. */
216
+ readonly port?: number;
217
+ /** Inject an existing Express app. */
218
+ readonly app?: Express;
219
+ }
220
+ interface WebhookServer {
221
+ start(): Promise<void>;
222
+ stop(): Promise<void>;
223
+ }
224
+ declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
225
+
226
+ export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineEventToMessageEvent, mapSourceType, splitForLine, verifyLineSignature };