@theokit/gateway 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +56 -0
- package/dist/index.cjs +188 -31
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +127 -10
- package/dist/index.d.ts +127 -10
- package/dist/index.js +186 -32
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -378,6 +378,81 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
|
|
|
378
378
|
}
|
|
379
379
|
};
|
|
380
380
|
|
|
381
|
+
// src/adapter/send-error.ts
|
|
382
|
+
function parseRetryAfter(value, now) {
|
|
383
|
+
if (value == null) return void 0;
|
|
384
|
+
const v = value.trim();
|
|
385
|
+
if (/^\d+$/.test(v)) return Number(v) * 1e3;
|
|
386
|
+
if (!/[A-Za-z]/.test(v)) return void 0;
|
|
387
|
+
const at = Date.parse(v);
|
|
388
|
+
if (Number.isNaN(at)) return void 0;
|
|
389
|
+
return Math.max(0, at - now);
|
|
390
|
+
}
|
|
391
|
+
var STATUS_CODES = {
|
|
392
|
+
429: "rate_limit",
|
|
393
|
+
401: "auth_failed",
|
|
394
|
+
403: "permission_denied",
|
|
395
|
+
408: "timeout"
|
|
396
|
+
};
|
|
397
|
+
function codeForStatus(status) {
|
|
398
|
+
return STATUS_CODES[status] ?? (status >= 500 ? "server_error" : "platform_error");
|
|
399
|
+
}
|
|
400
|
+
function sendErrorFromHttp(status, message, options) {
|
|
401
|
+
if (!Number.isInteger(status) || status < 100 || status > 599) {
|
|
402
|
+
throw new RangeError(`status must be an integer in 100..599, got ${String(status)}`);
|
|
403
|
+
}
|
|
404
|
+
const code = codeForStatus(status);
|
|
405
|
+
const retryAfterMs = status === 429 ? parseRetryAfter(options?.retryAfter, (options?.now ?? Date.now)()) : void 0;
|
|
406
|
+
return {
|
|
407
|
+
ok: false,
|
|
408
|
+
error: {
|
|
409
|
+
code,
|
|
410
|
+
message,
|
|
411
|
+
...retryAfterMs !== void 0 ? { retryAfterMs } : {},
|
|
412
|
+
...options?.platformCode !== void 0 ? { platformCode: options.platformCode } : {}
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// src/auth/token-cache.ts
|
|
418
|
+
function createTokenCache(options) {
|
|
419
|
+
const marginMs = options.marginMs ?? 6e4;
|
|
420
|
+
const defaultTtlS = options.defaultTtlS ?? 7200;
|
|
421
|
+
const now = options.now ?? Date.now;
|
|
422
|
+
let cached;
|
|
423
|
+
let pending;
|
|
424
|
+
let generation = 0;
|
|
425
|
+
const refresh = (signal) => {
|
|
426
|
+
const started = generation;
|
|
427
|
+
const run = (async () => {
|
|
428
|
+
const fetched = await options.fetchToken(signal);
|
|
429
|
+
const ttl = fetched.expiresInS !== void 0 && fetched.expiresInS > 0 ? fetched.expiresInS : defaultTtlS;
|
|
430
|
+
if (started === generation) {
|
|
431
|
+
cached = { value: fetched.value, expiresAt: now() + ttl * 1e3 };
|
|
432
|
+
}
|
|
433
|
+
return fetched.value;
|
|
434
|
+
})();
|
|
435
|
+
const tracked = run.finally(() => {
|
|
436
|
+
if (pending === tracked) pending = void 0;
|
|
437
|
+
});
|
|
438
|
+
pending = tracked;
|
|
439
|
+
return tracked;
|
|
440
|
+
};
|
|
441
|
+
return {
|
|
442
|
+
get(opts) {
|
|
443
|
+
if (opts?.force !== true && cached !== void 0 && cached.expiresAt - marginMs > now()) {
|
|
444
|
+
return Promise.resolve(cached.value);
|
|
445
|
+
}
|
|
446
|
+
return pending ?? refresh(opts?.signal);
|
|
447
|
+
},
|
|
448
|
+
clear() {
|
|
449
|
+
generation += 1;
|
|
450
|
+
cached = void 0;
|
|
451
|
+
pending = void 0;
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
|
|
381
456
|
// src/text/seen-ids.ts
|
|
382
457
|
var DEFAULT_LIMIT = 1e3;
|
|
383
458
|
var SeenIds = class {
|
|
@@ -427,7 +502,6 @@ function decodeEntities(s) {
|
|
|
427
502
|
|
|
428
503
|
// src/adapter/weixin-base.ts
|
|
429
504
|
var REQUEST_TIMEOUT_MS = 3e4;
|
|
430
|
-
var TOKEN_MARGIN_MS = 6e4;
|
|
431
505
|
var defaultFetch = async (url, init) => {
|
|
432
506
|
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
433
507
|
return { status: res.status, text: () => res.text() };
|
|
@@ -442,12 +516,13 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
442
516
|
cfg;
|
|
443
517
|
doFetch;
|
|
444
518
|
connected = false;
|
|
445
|
-
|
|
519
|
+
tokens;
|
|
446
520
|
seen = new SeenIds();
|
|
447
521
|
constructor(cfg) {
|
|
448
522
|
super();
|
|
449
523
|
this.cfg = cfg;
|
|
450
524
|
this.doFetch = cfg.fetch ?? defaultFetch;
|
|
525
|
+
this.tokens = createTokenCache({ fetchToken: () => this.requestToken() });
|
|
451
526
|
}
|
|
452
527
|
async connect() {
|
|
453
528
|
if (this.connected) return true;
|
|
@@ -463,7 +538,7 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
463
538
|
}
|
|
464
539
|
async disconnect() {
|
|
465
540
|
this.connected = false;
|
|
466
|
-
this.
|
|
541
|
+
this.tokens.clear();
|
|
467
542
|
}
|
|
468
543
|
/** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
|
|
469
544
|
async sendText(out) {
|
|
@@ -525,21 +600,19 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
525
600
|
if (outcome === "no_handler") return { status: 503, body: "", reason: "no handler subscribed" };
|
|
526
601
|
return weixinAck(outcome);
|
|
527
602
|
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
}
|
|
603
|
+
token(force) {
|
|
604
|
+
return this.tokens.get({ force });
|
|
605
|
+
}
|
|
606
|
+
async requestToken() {
|
|
533
607
|
const body = await this.call("GET", this.tokenPath());
|
|
534
608
|
if (body.errcode !== void 0 && body.errcode !== 0) {
|
|
535
609
|
throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);
|
|
536
610
|
}
|
|
537
611
|
if (!body.access_token) throw new Error("token answer has no access_token");
|
|
538
|
-
|
|
612
|
+
return {
|
|
539
613
|
value: body.access_token,
|
|
540
|
-
|
|
614
|
+
...body.expires_in === void 0 ? {} : { expiresInS: body.expires_in }
|
|
541
615
|
};
|
|
542
|
-
return body.access_token;
|
|
543
616
|
}
|
|
544
617
|
async call(method, path, payload) {
|
|
545
618
|
const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {
|
|
@@ -1248,6 +1321,56 @@ var HookExecutor = class {
|
|
|
1248
1321
|
}
|
|
1249
1322
|
};
|
|
1250
1323
|
|
|
1324
|
+
// src/runner/reconnect-backoff.ts
|
|
1325
|
+
function checkNonNegativeFinite(name, value) {
|
|
1326
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
1327
|
+
throw new RangeError(`${name} must be a finite number >= 0, got ${value}`);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
var ReconnectBackoff = class {
|
|
1331
|
+
initialDelayMs;
|
|
1332
|
+
maxDelayMs;
|
|
1333
|
+
factor;
|
|
1334
|
+
maxAttempts;
|
|
1335
|
+
stableAfterMs;
|
|
1336
|
+
now;
|
|
1337
|
+
attempts = 0;
|
|
1338
|
+
openedAt;
|
|
1339
|
+
constructor(options = {}) {
|
|
1340
|
+
this.initialDelayMs = options.initialDelayMs ?? 1e3;
|
|
1341
|
+
this.maxDelayMs = options.maxDelayMs ?? 6e4;
|
|
1342
|
+
this.factor = options.factor ?? 2;
|
|
1343
|
+
this.maxAttempts = options.maxAttempts;
|
|
1344
|
+
this.stableAfterMs = options.stableAfterMs ?? 6e4;
|
|
1345
|
+
this.now = options.now ?? Date.now;
|
|
1346
|
+
checkNonNegativeFinite("initialDelayMs", this.initialDelayMs);
|
|
1347
|
+
checkNonNegativeFinite("maxDelayMs", this.maxDelayMs);
|
|
1348
|
+
if (!(this.factor >= 1) || !Number.isFinite(this.factor)) {
|
|
1349
|
+
throw new RangeError(`factor must be a finite number >= 1, got ${this.factor}`);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
/** Call when the connection opens. */
|
|
1353
|
+
opened() {
|
|
1354
|
+
this.openedAt = this.now();
|
|
1355
|
+
}
|
|
1356
|
+
/** Delay before the next attempt; `undefined` once `maxAttempts` is spent. Resets first if the last connection was stable. */
|
|
1357
|
+
nextDelayMs() {
|
|
1358
|
+
if (this.openedAt !== void 0) {
|
|
1359
|
+
if (this.now() - this.openedAt >= this.stableAfterMs) this.attempts = 0;
|
|
1360
|
+
this.openedAt = void 0;
|
|
1361
|
+
}
|
|
1362
|
+
if (this.maxAttempts !== void 0 && this.attempts >= this.maxAttempts) return void 0;
|
|
1363
|
+
const delay = Math.min(this.initialDelayMs * this.factor ** this.attempts, this.maxDelayMs);
|
|
1364
|
+
this.attempts += 1;
|
|
1365
|
+
return delay;
|
|
1366
|
+
}
|
|
1367
|
+
/** Back to the initial delay. */
|
|
1368
|
+
reset() {
|
|
1369
|
+
this.attempts = 0;
|
|
1370
|
+
this.openedAt = void 0;
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
|
|
1251
1374
|
// src/runner/gateway-runner.ts
|
|
1252
1375
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
1253
1376
|
var TYPING_RENEW_MS = 4e3;
|
|
@@ -1399,27 +1522,28 @@ var GatewayRunner = class {
|
|
|
1399
1522
|
connected: result.connected.map((a) => a.platform),
|
|
1400
1523
|
failed: result.failed
|
|
1401
1524
|
};
|
|
1402
|
-
for (const adapter of result.retryable)
|
|
1525
|
+
for (const adapter of result.retryable) {
|
|
1526
|
+
const policy = this.opts.reconnect;
|
|
1527
|
+
if (policy === void 0) break;
|
|
1528
|
+
this.scheduleReconnect(adapter, 1, new ReconnectBackoff(policy));
|
|
1529
|
+
}
|
|
1403
1530
|
return this.startResult;
|
|
1404
1531
|
}
|
|
1405
1532
|
/** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
|
|
1406
|
-
scheduleReconnect(adapter, attempt) {
|
|
1533
|
+
scheduleReconnect(adapter, attempt, backoff) {
|
|
1407
1534
|
const policy = this.opts.reconnect;
|
|
1408
1535
|
if (policy === void 0 || this.stopped) return;
|
|
1409
|
-
|
|
1536
|
+
const delay = backoff.nextDelayMs();
|
|
1537
|
+
if (delay === void 0) {
|
|
1410
1538
|
process.stderr.write(
|
|
1411
1539
|
`[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
|
|
1412
1540
|
`
|
|
1413
1541
|
);
|
|
1414
1542
|
return;
|
|
1415
1543
|
}
|
|
1416
|
-
const delay = Math.min(
|
|
1417
|
-
(policy.initialDelayMs ?? 1e3) * (policy.factor ?? 2) ** (attempt - 1),
|
|
1418
|
-
policy.maxDelayMs ?? 6e4
|
|
1419
|
-
);
|
|
1420
1544
|
const timer = setTimeout(() => {
|
|
1421
1545
|
this.retryTimers.delete(timer);
|
|
1422
|
-
void this.reconnectOnce(adapter, attempt);
|
|
1546
|
+
void this.reconnectOnce(adapter, attempt, backoff);
|
|
1423
1547
|
}, delay);
|
|
1424
1548
|
timer.unref();
|
|
1425
1549
|
this.retryTimers.add(timer);
|
|
@@ -1429,7 +1553,7 @@ var GatewayRunner = class {
|
|
|
1429
1553
|
);
|
|
1430
1554
|
this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
|
|
1431
1555
|
}
|
|
1432
|
-
async reconnectOnce(adapter, attempt) {
|
|
1556
|
+
async reconnectOnce(adapter, attempt, backoff) {
|
|
1433
1557
|
if (this.stopped) return;
|
|
1434
1558
|
try {
|
|
1435
1559
|
if (await adapter.connect()) {
|
|
@@ -1475,7 +1599,7 @@ var GatewayRunner = class {
|
|
|
1475
1599
|
`
|
|
1476
1600
|
);
|
|
1477
1601
|
}
|
|
1478
|
-
this.scheduleReconnect(adapter, attempt + 1);
|
|
1602
|
+
this.scheduleReconnect(adapter, attempt + 1, backoff);
|
|
1479
1603
|
}
|
|
1480
1604
|
/**
|
|
1481
1605
|
* All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
|
|
@@ -2145,30 +2269,60 @@ function lineEndFrom(text, cut, bound) {
|
|
|
2145
2269
|
while (at < text.length && at <= bound && !isLineEnd2(text[at])) at += 1;
|
|
2146
2270
|
return at;
|
|
2147
2271
|
}
|
|
2148
|
-
function
|
|
2272
|
+
function advance(text, from, count, codepoint) {
|
|
2273
|
+
if (!codepoint) return Math.min(from + count, text.length);
|
|
2274
|
+
let at = from;
|
|
2275
|
+
for (let left = count; left > 0 && at < text.length; left -= 1) {
|
|
2276
|
+
at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
|
|
2277
|
+
}
|
|
2278
|
+
return at;
|
|
2279
|
+
}
|
|
2280
|
+
function rowSafeCut2(text, partStart, cut, partLimit, codepoint) {
|
|
2149
2281
|
const lineStart = lineStartBefore(text, cut, partStart);
|
|
2150
2282
|
if (lineStart <= partStart || lineStart === cut) return cut;
|
|
2151
2283
|
if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
|
|
2152
|
-
const
|
|
2153
|
-
return
|
|
2284
|
+
const bound = advance(text, lineStart, partLimit, codepoint);
|
|
2285
|
+
return lineEndFrom(text, cut, bound) <= bound ? lineStart : cut;
|
|
2154
2286
|
}
|
|
2155
|
-
function graphemeCut(segments, start,
|
|
2156
|
-
const
|
|
2157
|
-
|
|
2158
|
-
if (segment === void 0 || segment.index >= cut) return cut;
|
|
2287
|
+
function graphemeCut(segments, start, limitCut) {
|
|
2288
|
+
const segment = segments.containing(limitCut);
|
|
2289
|
+
if (segment === void 0 || segment.index >= limitCut) return limitCut;
|
|
2159
2290
|
return segment.index > start ? segment.index : segment.index + segment.segment.length;
|
|
2160
2291
|
}
|
|
2161
|
-
function
|
|
2292
|
+
function readUnit(partLimit, options) {
|
|
2293
|
+
const unit = options.unit ?? "utf16";
|
|
2294
|
+
if (unit !== "utf16" && unit !== "codepoint") {
|
|
2295
|
+
throw new RangeError(
|
|
2296
|
+
`splitKeepingRows: unit must be "utf16" or "codepoint", got ${String(unit)}`
|
|
2297
|
+
);
|
|
2298
|
+
}
|
|
2299
|
+
if (unit === "codepoint" && !(Number.isInteger(partLimit) && partLimit > 0)) {
|
|
2300
|
+
throw new RangeError(
|
|
2301
|
+
`splitKeepingRows: partLimit must be a positive integer, got ${partLimit}`
|
|
2302
|
+
);
|
|
2303
|
+
}
|
|
2304
|
+
return unit === "codepoint";
|
|
2305
|
+
}
|
|
2306
|
+
function splitKeepingRows(text, partLimit, options = {}) {
|
|
2307
|
+
const codepoint = readUnit(partLimit, options);
|
|
2162
2308
|
const segments = new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text);
|
|
2163
2309
|
const parts = [];
|
|
2164
2310
|
let start = 0;
|
|
2165
|
-
|
|
2166
|
-
|
|
2311
|
+
let limitCut = advance(text, start, partLimit, codepoint);
|
|
2312
|
+
while (limitCut < text.length) {
|
|
2313
|
+
const grapheme = graphemeCut(segments, start, limitCut);
|
|
2314
|
+
if (codepoint && grapheme > limitCut) {
|
|
2315
|
+
throw new RangeError(
|
|
2316
|
+
`splitKeepingRows: a grapheme at offset ${start} is longer than ${partLimit} code points`
|
|
2317
|
+
);
|
|
2318
|
+
}
|
|
2319
|
+
const cut = rowSafeCut2(text, start, grapheme, partLimit, codepoint);
|
|
2167
2320
|
if (cut <= start) {
|
|
2168
2321
|
throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);
|
|
2169
2322
|
}
|
|
2170
2323
|
parts.push(text.slice(start, cut));
|
|
2171
2324
|
start = cut;
|
|
2325
|
+
limitCut = advance(text, start, partLimit, codepoint);
|
|
2172
2326
|
}
|
|
2173
2327
|
if (start < text.length) parts.push(text.slice(start));
|
|
2174
2328
|
return parts;
|
|
@@ -2431,6 +2585,6 @@ async function dispatch(webhook, adapter, request) {
|
|
|
2431
2585
|
return runDefault(webhook, adapter, request);
|
|
2432
2586
|
}
|
|
2433
2587
|
|
|
2434
|
-
export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
|
|
2588
|
+
export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, ReconnectBackoff, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createTokenCache, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, sendErrorFromHttp, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
|
|
2435
2589
|
//# sourceMappingURL=index.js.map
|
|
2436
2590
|
//# sourceMappingURL=index.js.map
|