Phase 2 of the 4-package split (RoadMap #3). Moves ~35 files — events / event-bus / identity-service / packet-pipeline / element- builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* + the bridge-side formatters — out of `packages/core/src/bridge/` into the new `@snowluma/bridge` workspace package. Everything that translates QQ wire bytes ↔ typed events/elements now lives there. Why --- - `packages/core/src/bridge/` was actually two layers: a low-level "protocol decoder + I/O" set (msg-push, highway, packet-pipeline, identity, element-builder) AND the Api-class host (bridge.ts + apis/*). The Api layer can't move without the protocol layer moving first, but the two had grown into one directory. - Bridge-internal consumers (highway uploaders, OIDB envelope helper, element-builder, msg-push parsers) only ever needed `bridge.identity` + `bridge.sendRawPacket` + the upload-metadata cache. Splitting them out lets that minimal surface live in the bridge package as `BridgeContext` while the api-layer's extended context (with `apis: ApiHub`) stays in @snowluma/core. What stays in @snowluma/core (apis layer): - bridge.ts ── the god-class that composes the protocol building blocks + mounts apis - bridge-interface.ts ── public façade for OneBot consumers - manager.ts ── per-uin BridgeManager hub - apis/* ── the 13 typed Api classes - bridge-context.ts (NEW) ── extends @snowluma/bridge's slim BridgeContext with `apis: ApiHub` so the 13 Api classes keep their typed `this.ctx.apis.X.method()` access. Layout ------ Moved via `git mv` (history preserved): events / event-bus / identity-service / packet-pipeline / element-builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* → @snowluma/bridge/<sub> utils/event-format.ts → @snowluma/bridge/format.ts (the last one renamed because the destination directory only has bridge-related files; `format.ts` reads cleaner than `event-format`. Listed as a rename in git's `RM` output — content unchanged.) Layering fixes (functionality preserved, just type signatures) -------------------------------------------------------------- - `element-builder.SendContext.bridge` → typed as `BridgeContext` instead of `Bridge`. Reads only `bridge.identity` and the upload-cache (both on BridgeContext); the concrete `Bridge` instance still passes via free upcast. - `bridge-oidb.runOidb` signature widened from `Bridge` to `BridgeContext` — same reason. - `highway/{highway-client,pipeline,image-upload,ptt-upload, video-upload}.ts` — same. - `format.ts::formatReply` parameter typed as a new local `ReplyEventLookup` structural type (`{ findEvent(id): JsonObject | null }`) instead of `MessageStore` from @snowluma/onebot. The OneBot `MessageStore` is a structural superset; consumers pass it through unchanged. - JSON value types moved to a new `@snowluma/common/json` subpath (consumed by format.ts) — `onebot/types.ts` re-exports them so external `import { JsonValue } from '<…>/onebot/types'` paths keep working. - `UploadedFileMeta` interface moved from `core/src/bridge/bridge.ts` into `@snowluma/bridge/bridge-context.ts` — element-builder + the forward-builder both read the upload cache through BridgeContext, so the type has to live in @snowluma/bridge. `bridge.ts` keeps its re-export for back-compat. Changes ------- - New package `packages/bridge/` (package.json with per-file subpath exports mirroring legacy `core/src/bridge/<x>` layout 1:1, tsconfig.json, typecheck script). - 35 `.ts` files moved via `git mv` (3 files counted by git as RM — rename + modify because Bridge → BridgeContext type swap). - 150+ import sites rewritten across `packages/core/src` and `packages/core/tests`: `'../bridge/<x>'`, `'../../bridge/<x>'`, `'../src/bridge/<x>'`, `'@/bridge/web/<x>'`, and vitest `vi.mock(...)` literals all collapse to `@snowluma/bridge/<x>`. - `@snowluma/core` depends on `@snowluma/bridge` (workspace:*). - `@snowluma/bridge` depends on `@snowluma/common`, `@snowluma/proto-defs`, `@snowluma/proton`. - `packages/core/src/utils/` directory removed (empty). Verification ------------ - Full workspace `pnpm -r typecheck`: all 10 projects clean. - core test suite: 552 passed / 552 total (pre-existing websocket-darwin-arm64.node addon failure unchanged — same baseline as the previous refactor commits). - Vite build (with stubbed native binary): clean — 143 modules, 2.84 MB bundle / 224 KB gzip, identical envelope to the pre-split build. Phase 3 (next): OneBot + WebUI move into @snowluma/onebot. The runnable `index.ts` stays in @snowluma/core as the application entry, importing `OneBotManager` from `@snowluma/onebot`.
102 lines
3.7 KiB
TypeScript
102 lines
3.7 KiB
TypeScript
import fs from 'fs';
|
|
import os from 'os';
|
|
import path from 'path';
|
|
import { pathToFileURL } from 'url';
|
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
import { loadBinarySource, resolveLocalFilePath } from '@snowluma/bridge/highway/utils';
|
|
|
|
describe('highway source paths', () => {
|
|
it('normalizes file URLs with an extra leading slash on POSIX', () => {
|
|
if (process.platform === 'win32') return;
|
|
expect(resolveLocalFilePath('file:////AstrBot/data/plugin/cache/BV-test.mp4'))
|
|
.toBe('/AstrBot/data/plugin/cache/BV-test.mp4');
|
|
});
|
|
|
|
it('loads encoded file URLs from the local filesystem', async () => {
|
|
const filePath = path.join(os.tmpdir(), `snowluma video ${process.pid}-${Date.now()}.txt`);
|
|
fs.writeFileSync(filePath, 'ok');
|
|
|
|
try {
|
|
const source = pathToFileURL(filePath).href;
|
|
const loaded = await loadBinarySource(source, 'test file');
|
|
expect(Buffer.from(loaded.bytes).toString('utf8')).toBe('ok');
|
|
expect(loaded.fileName).toBe(path.basename(filePath));
|
|
} finally {
|
|
try { fs.unlinkSync(filePath); } catch { /* ignore */ }
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('loadBinarySource maxBytes enforcement', () => {
|
|
const originalFetch = globalThis.fetch;
|
|
afterEach(() => {
|
|
globalThis.fetch = originalFetch;
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
it('rejects HTTP downloads larger than maxBytes via streaming, even without Content-Length', async () => {
|
|
// Streamed chunk-encoded response: no Content-Length, totals > cap.
|
|
const chunkSize = 4 * 1024;
|
|
const totalChunks = 16;
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
start(controller) {
|
|
for (let i = 0; i < totalChunks; i++) controller.enqueue(new Uint8Array(chunkSize));
|
|
controller.close();
|
|
},
|
|
});
|
|
globalThis.fetch = vi.fn(async () => new Response(stream, {
|
|
status: 200,
|
|
headers: { /* no content-length */ },
|
|
})) as typeof fetch;
|
|
|
|
// Cap below total: 16*4096 = 65536, cap 32 KiB → should throw mid-stream.
|
|
await expect(
|
|
loadBinarySource('https://example.test/big.bin', 'test', 32 * 1024),
|
|
).rejects.toThrow(/too large/);
|
|
});
|
|
|
|
it('rejects HTTP downloads when Content-Length already exceeds maxBytes', async () => {
|
|
globalThis.fetch = vi.fn(async () => new Response(new Uint8Array(0), {
|
|
status: 200,
|
|
headers: { 'content-length': String(10 * 1024 * 1024) },
|
|
})) as typeof fetch;
|
|
|
|
await expect(
|
|
loadBinarySource('https://example.test/big.bin', 'test', 1024),
|
|
).rejects.toThrow(/too large: 10485760/);
|
|
});
|
|
|
|
it('accepts a streamed download that fits inside maxBytes', async () => {
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
start(controller) {
|
|
controller.enqueue(new Uint8Array([1, 2, 3]));
|
|
controller.enqueue(new Uint8Array([4, 5]));
|
|
controller.close();
|
|
},
|
|
});
|
|
globalThis.fetch = vi.fn(async () => new Response(stream, { status: 200 })) as typeof fetch;
|
|
|
|
const loaded = await loadBinarySource('https://example.test/small.bin', 'test', 1024);
|
|
expect(Array.from(loaded.bytes)).toEqual([1, 2, 3, 4, 5]);
|
|
});
|
|
|
|
it('rejects oversized local files via fs.stat before reading them', async () => {
|
|
const filePath = path.join(os.tmpdir(), `snowluma-binary-cap-${process.pid}-${Date.now()}.bin`);
|
|
fs.writeFileSync(filePath, Buffer.alloc(128));
|
|
try {
|
|
await expect(
|
|
loadBinarySource(filePath, 'test', 64),
|
|
).rejects.toThrow(/too large: 128 > 64/);
|
|
} finally {
|
|
try { fs.unlinkSync(filePath); } catch { /* ignore */ }
|
|
}
|
|
});
|
|
|
|
it('rejects oversized base64 payloads', async () => {
|
|
const big = Buffer.alloc(128).toString('base64');
|
|
await expect(
|
|
loadBinarySource(`base64://${big}`, 'test', 64),
|
|
).rejects.toThrow(/too large: 128 > 64/);
|
|
});
|
|
});
|