Compare commits

...

20 Commits

Author SHA1 Message Date
H3CoF6
6f6ce1144b 补全一些onebot action实现 2 (#24)
* feat: implement get profile like

* feat: implement get at all remain

* feat: implement get undirectional friends

* feat: implement set self long nick

* feat: implement set input status

* feat: implement EN 2 ZH

* feat: implement get mini app ark

* feat: implement click inline button

* feat: implement set and send group sign

* feat: implement set qq avatar

* feat: group notice with pic and delete notice implement

* fix(group-notice): POST api and fix new bkn logic
2026-05-10 10:14:41 +08:00
DrSmoothl
bec23c4dbb [merge] promote SDK changes 2026-05-10 01:29:57 +08:00
DrSmoothl
c343021318 feat: add SnowLuma TypeScript SDK 2026-05-10 01:26:35 +08:00
DrSmoothl
9ab4128799 Implement video message upload 2026-05-09 23:06:55 +08:00
手瓜一十雪
95df5234fb Support forced group member cache refresh
Add a `force` flag to member cache refresh logic so events that affect the bot itself trigger an immediate refresh. When the event userUin matches the bot's UIN, `triggerMemberCacheRefresh` sets `force = true` and forwards it to `fetchGroupMemberList`. `fetchGroupMemberList` now accepts an optional `force` parameter (default false) and bypasses the TTL cache when `force` is true, ensuring up-to-date member data after join/leave events.
2026-05-09 19:54:20 +08:00
手瓜一十雪
a7b3809a12 Only track hook states for running PIDs
Stop exposing and retaining hook state for PIDs that are not currently running. listProcesses() no longer returns orphaned states; live-pipe handling ignores PIDs not present in the current process list. When a process is not running its state is immediately torn down (tearDownClient called) and removed, and bridgeManager.onPidDisconnected is notified if the state was logged in. Also reorganized runningSet creation so it can be reused for these checks.
2026-05-09 19:38:52 +08:00
手瓜一十雪
c39b3f5c4e Add PTT (voice) upload support with FFmpeg addon
Introduce NT SILK-based voice (PTT) upload pipeline and native FFmpeg addon wrapper.

- Add ffmpeg-addon wrapper (packages/core/src/bridge/highway/ffmpeg-addon.ts) to load platform/arch .node binaries, detect SILK files, and convert inputs to NT SILK via the native addon. Provides encodeSilk, isSilkFile and default temp dir helpers.
- Implement ptt-upload pipeline (packages/core/src/bridge/highway/ptt-upload.ts) to: resolve/fetch audio bytes, convert to NT SILK if needed, send OIDB upload request, perform highway HTTP upload when required, and produce Encodable MsgInfo bytes for commonElem.
- Wire record element support into element-builder: uploadPttMsgInfo is used to build a commonElem for 'record' sends; when SendContext is absent, record sends are skipped with a warning (graceful no-bridge path).
- Update message parsing to accept record segments from data.file, data.url or data.path and drop empty sources.
- Enable canSendRecord in OneBot instance context.
- Add tests covering record parsing and the graceful send path (packages/core/tests/message-parser.test.ts).
- Include prebuilt native ffmpeg addon binaries under packages/runtime/native/ffmpeg and update vite config to validate & copy the ffmpeg addon into the dist layout.

These changes enable sending voice messages by converting/encoding sources to the expected NT SILK format and uploading them through the existing highway/NTV2 flows.
2026-05-09 19:32:13 +08:00
手瓜一十雪
2af273b9e2 Simplify WebUI logs and adjust hook reconnect
Translate and consolidate verbose WebUI log messages to shorter English variants (dev mode, initial credentials, forced password change, password update, port fallback, and listening message). Remove a startup log emitted in core index.ts. In HookManager, preserve an existing state.method when detecting an already-injected PID (only set to 'reconnect' if not present) and remove a redundant injection success log to reduce noise.
2026-05-09 16:36:03 +08:00
手瓜一十雪
144e0fdd59 Add BridgeEventBus and network manager
Introduce a typed per-kind BridgeEventBus and migrate away from the legacy single-callback firehose. Bridge now exposes `events` and emits via the bus; BridgeManager/OneBotManager no longer wire a global event callback. Add a focused onebot event pipeline (event-pipeline.ts) that subscribes per-kind handlers on instance construction. Replace the in-memory MediaCache with a persistent MediaStore and update all lookups accordingly. Replace the old Http/Ws/HttpPost transport implementations with a unified OneBotNetworkManager and pluggable adapters (server/client/post), and update OneBotInstance to install and manage adapters from config. Remove several legacy files (http-transport, http-post-transport, ws-transport, media-cache) and update imports across the codebase. Also add tests for the bridge event bus, event pipeline, network manager, and rename media tests to reflect MediaStore usage. The bus dispatches handlers in parallel and reports handler errors via an onError hook to avoid one faulty listener blocking others.
2026-05-09 16:30:06 +08:00
手瓜一十雪
1565749105 Add MediaCache and media segment sink
Introduce an in-memory MediaCache to index recently seen image and record segments and wire a MediaSegmentSink into EventConverter to populate it. OneBotInstance now constructs MediaCache and registers a sink to remember image/record metadata; instance-context exposes get_image/get_record lookup handlers that consult the cache (and re-resolve record URLs via bridge OIDB when needed). ApiHandler actions get_image/get_record now accept file_id fallback and use the new context lookups. Removed the old findMediaInStore stub and added comprehensive tests for the cache and sink behavior.
2026-05-09 15:33:13 +08:00
手瓜一十雪
e53a8a01b7 Revert "[merge] dev & ci: default promote-dev-to-main merge strategy to squash"
This reverts commit 3afbcfaae5.
2026-05-09 15:08:41 +08:00
手瓜一十雪
3afbcfaae5 [merge] dev & ci: default promote-dev-to-main merge strategy to squash
Switch default merge_method from 'merge' to 'squash' so dev->main PRs collapse the dev branch's incremental commits into one squash commit on main, keeping main's history linear and release-tag-friendly. Affects: workflow_dispatch input default, decide-step initial value + workflow_dispatch fallback, both push-trigger branches (tag + commit-msg), and the case-statement fallback in the auto-merge step. CONTRIBUTING.md updated to reflect the new default.
2026-05-09 15:06:54 +08:00
手瓜一十雪
c3b328f91d [merge] dev 2026-05-09 15:01:46 +08:00
手瓜一十雪
7942c47808 [merge] dev 2026-05-09 14:58:37 +08:00
手瓜一十雪
46d93e715a ci: use chore.* tag pattern + commit-msg prefix matching for promote workflow
- Tag trigger switched from v* to chore.* so the promote workflow no longer collides with release.yml's v* tag handling. v* tags now drive only the release build; chore.* tags drive only dev->main promotion.

- Commit-message detection on dev is now prefix-only: '^[merge]' or '^chore(release):' (case-insensitive). 'fix: stuff [merge]' no longer triggers; the marker must be at the start of the message.

- CONTRIBUTING.md updated: prefix examples, chore.* tag examples, and an explicit 'all required status checks must pass' branch-protection setup that lists the dev-build typecheck/build matrix as required.
2026-05-09 14:57:06 +08:00
手瓜一十雪
a9027a8610 ci: add promote dev->main workflow + branching docs
Adds .github/workflows/promote-dev-to-main.yml which uses the SnowLuma Bot GitHub App to open (or refresh) a PR from dev into main. Triggered by [merge] or chore(release): commit-msg markers on dev, by v* tag pushes, or via manual workflow_dispatch. Auto-merge is enabled when triggered.

Adds CONTRIBUTING.md describing the dev/main branch model, the promote workflow, the required SNOWLUMA_BOT_APP_ID / SNOWLUMA_BOT_PRIVATE_KEY secrets, and the GitHub branch protection setup needed to forbid direct pushes to main.
2026-05-09 14:43:44 +08:00
手瓜一十雪
5853dc63ff Lookup workflow by name/id and set default repo
Update release workflows to fallback to 'SnowLuma/SnowLuma.Docker.Framework' when RELEASE_REPOSITORY is unset and to resolve the target workflow by name, path, or id. Replace the simple workflow_id string with logic that paginates listRepoWorkflows, finds the matching workflow, validates it exists, and passes workflow.id to createWorkflowDispatch. Improve error messages and logging to include workflow name and id.
2026-05-09 11:23:50 +08:00
手瓜一十雪
ca14cb5437 Replace DOCKER_RELEASE_TOKEN with SNOWLUMA_TOKEN
Update GitHub Actions release workflows to use the SNOWLUMA_TOKEN secret instead of DOCKER_RELEASE_TOKEN. Changed the github-token input in .github/workflows/release.yml and .github/workflows/dispatch-docker-release.yml for the docker release steps.
2026-05-09 11:17:02 +08:00
手瓜一十雪
a978d27f3a Add manual Docker rebuild dispatcher
Introduce a manual re-dispatch workflow and wire automatic dispatch from releases to the Docker workflow. dispatch-docker-release.yml was converted to a workflow_dispatch-based "Re-dispatch Docker Release" that accepts snowluma_tag, docker_image_override and platforms_override inputs and forwards them (plus source repository) to the downstream docker-image.yml in the Docker release repo. release.yml gains a dispatch-docker job that runs after the release job and uses a PAT to invoke the same downstream workflow for newly published tags. These changes let maintainers rebuild Docker images for existing tags (e.g. to fix Dockerfile issues or rotate credentials) without re-tagging, and ensure the downstream dispatch runs under the configured token.
2026-05-09 11:07:59 +08:00
手瓜一十雪
5a5b9d13d1 Use workflow_dispatch to trigger Docker workflow
Switch the release dispatch to call actions.createWorkflowDispatch instead of repos.createDispatchEvent because the target repo only listens for workflow_dispatch on its docker workflow. Add env vars DOCKER_PLATFORMS, DOCKER_WORKFLOW and DOCKER_REF (with sensible defaults) and pass image, tag, push and platforms as inputs. Update log output to include workflow, ref, image, tag and platforms.
2026-05-09 10:47:29 +08:00
96 changed files with 9506 additions and 1213 deletions

View File

@@ -1,9 +1,27 @@
name: Dispatch Docker Release
name: Re-dispatch Docker Release
# Manual-only re-dispatcher for SnowLuma.Docker.Framework's docker-image.yml.
#
# The normal flow is automatic: release.yml's `dispatch-docker` job fires
# after a tag-triggered release is published. This workflow exists for
# rebuilding an existing release's Docker image without re-tagging — for
# example after fixing the Dockerfile, rotating a Docker Hub credential,
# or backfilling an older tag.
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
snowluma_tag:
description: 'SnowLuma release tag to rebuild (e.g. v0.5.0)'
required: true
docker_image_override:
description: 'Override Docker image name (defaults to vars.DOCKER_IMAGE)'
required: false
default: ''
platforms_override:
description: 'Override platforms (defaults to vars.DOCKER_PLATFORMS or linux/amd64,linux/arm64)'
required: false
default: ''
permissions:
contents: read
@@ -13,35 +31,48 @@ jobs:
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Dispatch Docker release request
- name: Dispatch Docker rebuild
uses: actions/github-script@v8
env:
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
DOCKER_REF: ${{ vars.DOCKER_REF }}
SNOWLUMA_TAG: ${{ inputs.snowluma_tag }}
IMAGE_OVERRIDE: ${{ inputs.docker_image_override }}
PLATFORMS_OVERRIDE: ${{ inputs.platforms_override }}
with:
github-token: ${{ secrets.DOCKER_RELEASE_TOKEN }}
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
script: |
const target = process.env.RELEASE_REPOSITORY;
if (!target || !target.includes('/')) {
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
}
const [owner, repo] = target.split('/');
const refName = context.ref.replace('refs/tags/', '');
const image = process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
const tag = process.env.SNOWLUMA_TAG;
if (!tag) throw new Error('snowluma_tag input is required.');
await github.rest.repos.createDispatchEvent({
const [owner, repo] = target.split('/');
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
const image = process.env.IMAGE_OVERRIDE || process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
const platforms = process.env.PLATFORMS_OVERRIDE || process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
const ref = process.env.DOCKER_REF || 'main';
await github.rest.actions.createWorkflowDispatch({
owner,
repo,
event_type: 'snowluma-tag-release',
client_payload: {
snowluma_repository: context.repo.owner + '/' + context.repo.repo,
snowluma_ref: context.ref,
snowluma_ref_name: refName,
snowluma_sha: context.sha,
docker_image: image,
docker_tag: refName,
workflow_id: workflowId,
ref,
inputs: {
image,
tag,
push: 'true',
platforms,
snowluma_tag: tag,
snowluma_repository: sourceRepo,
},
});
core.info(`Dispatched Docker release for ${context.ref} to ${target}.`);
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);

View File

@@ -0,0 +1,245 @@
name: Promote Dev to Main
on:
push:
branches: [dev]
tags: ['chore.*']
workflow_dispatch:
inputs:
auto_merge:
description: Enable auto-merge on the resulting PR
type: choice
options: ['true', 'false']
default: 'true'
merge_method:
description: Merge strategy when auto-merging
type: choice
options: ['merge', 'squash', 'rebase']
default: 'merge'
permissions:
contents: read
concurrency:
group: promote-dev-to-main
cancel-in-progress: false
jobs:
decide:
runs-on: ubuntu-latest
outputs:
run: ${{ steps.check.outputs.run }}
auto_merge: ${{ steps.check.outputs.auto_merge }}
merge_method: ${{ steps.check.outputs.merge_method }}
reason: ${{ steps.check.outputs.reason }}
steps:
- name: Decide whether to promote
id: check
env:
EVENT_NAME: ${{ github.event_name }}
REF: ${{ github.ref }}
REF_TYPE: ${{ github.ref_type }}
HEAD_COMMIT_MSG: ${{ github.event.head_commit.message }}
INPUT_AUTO_MERGE: ${{ inputs.auto_merge }}
INPUT_MERGE_METHOD: ${{ inputs.merge_method }}
run: |
set -euo pipefail
run='false'
auto_merge='true'
merge_method='merge'
reason=''
case "${EVENT_NAME}" in
workflow_dispatch)
run='true'
auto_merge="${INPUT_AUTO_MERGE:-true}"
merge_method="${INPUT_MERGE_METHOD:-merge}"
reason='Manual workflow_dispatch'
;;
push)
if [ "${REF_TYPE}" = 'tag' ]; then
run='true'
merge_method='merge'
reason="Tag push: ${REF}"
elif [ "${REF}" = 'refs/heads/dev' ]; then
msg="${HEAD_COMMIT_MSG:-}"
if printf '%s' "${msg}" | grep -qiE '^\[merge\]|^chore\(release\):'; then
run='true'
merge_method='merge'
reason='Commit message prefix on dev ([merge] or chore(release):)'
else
reason='Commit on dev without [merge] / chore(release): prefix'
fi
else
reason="Push event on unhandled ref: ${REF}"
fi
;;
*)
reason="Unhandled event: ${EVENT_NAME}"
;;
esac
{
echo "run=${run}"
echo "auto_merge=${auto_merge}"
echo "merge_method=${merge_method}"
echo "reason=${reason}"
} >> "${GITHUB_OUTPUT}"
{
echo "## Promote decision"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Event | \`${EVENT_NAME}\` |"
echo "| Ref | \`${REF}\` |"
echo "| Run | \`${run}\` |"
echo "| Auto-merge | \`${auto_merge}\` |"
echo "| Merge method | \`${merge_method}\` |"
echo "| Reason | ${reason} |"
} >> "${GITHUB_STEP_SUMMARY}"
promote:
needs: decide
if: needs.decide.outputs.run == 'true'
runs-on: ubuntu-latest
steps:
- name: Validate GitHub App credentials
env:
APP_ID: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
PRIVATE_KEY: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
run: |
if [ -z "${APP_ID}" ] || [ -z "${PRIVATE_KEY}" ]; then
echo 'Missing SNOWLUMA_BOT_APP_ID and/or SNOWLUMA_BOT_PRIVATE_KEY secrets.' >&2
echo 'Configure the same GitHub App used by the nnphook native PR flow.' >&2
exit 1
fi
- name: Mint GitHub App installation token
id: app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
private-key: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: ${{ github.event.repository.name }}
- name: Resolve bot identity
id: bot
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
run: |
set -euo pipefail
bot_login="${APP_SLUG}[bot]"
bot_id="$(gh api "/users/${bot_login}" --jq .id)"
bot_email="${bot_id}+${bot_login}@users.noreply.github.com"
{
echo "login=${bot_login}"
echo "id=${bot_id}"
echo "email=${bot_email}"
} >> "${GITHUB_OUTPUT}"
echo "Resolved bot: ${bot_login} <${bot_email}>"
- name: Checkout main
uses: actions/checkout@v6
with:
ref: main
fetch-depth: 0
token: ${{ steps.app-token.outputs.token }}
- name: Compare dev to main
id: diff
run: |
set -euo pipefail
git fetch origin dev:dev
ahead="$(git rev-list --count main..dev)"
behind="$(git rev-list --count dev..main)"
dev_sha="$(git rev-parse dev)"
dev_short="$(git rev-parse --short dev)"
{
echo "ahead=${ahead}"
echo "behind=${behind}"
echo "dev_sha=${dev_sha}"
echo "dev_short=${dev_short}"
} >> "${GITHUB_OUTPUT}"
if [ "${ahead}" = '0' ]; then
echo "skip=true" >> "${GITHUB_OUTPUT}"
echo "::notice::dev has no commits ahead of main; nothing to promote."
else
echo "skip=false" >> "${GITHUB_OUTPUT}"
echo "dev is ${ahead} ahead, ${behind} behind main."
fi
- name: Ensure automation label exists
if: steps.diff.outputs.skip != 'true'
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
run: |
gh label create automation --color 0E8A16 --description 'Automated bot PRs' 2>/dev/null || true
- name: Create or update Pull Request
id: pr
if: steps.diff.outputs.skip != 'true'
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
DEV_SHA: ${{ steps.diff.outputs.dev_sha }}
DEV_SHORT: ${{ steps.diff.outputs.dev_short }}
AHEAD: ${{ steps.diff.outputs.ahead }}
BEHIND: ${{ steps.diff.outputs.behind }}
REASON: ${{ needs.decide.outputs.reason }}
REF: ${{ github.ref }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
title="chore: promote dev → main (${DEV_SHORT})"
{
echo "Automated promotion of \`dev\` into \`main\`."
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Source | \`dev\` @ \`${DEV_SHA}\` |"
echo "| Trigger ref | \`${REF}\` |"
echo "| Trigger reason | ${REASON} |"
echo "| Workflow run | ${RUN_URL} |"
echo "| Ahead / Behind | ${AHEAD} / ${BEHIND} |"
echo
echo "Created by SnowLuma Bot."
} > pr-body.md
existing="$(gh pr list --base main --head dev --state open --json number --jq '.[0].number' 2>/dev/null || true)"
if [ -n "${existing}" ]; then
gh pr edit "${existing}" --title "${title}" --body-file pr-body.md
pr_number="${existing}"
echo "Updated existing PR #${pr_number}"
else
url="$(gh pr create --base main --head dev --title "${title}" --body-file pr-body.md --label automation)"
pr_number="${url##*/}"
echo "Opened new PR #${pr_number} (${url})"
fi
echo "number=${pr_number}" >> "${GITHUB_OUTPUT}"
{
echo "## Promote PR"
echo
echo "- Number: #${pr_number}"
echo "- Source: \`dev@${DEV_SHORT}\`"
echo "- Ahead/Behind: ${AHEAD}/${BEHIND}"
} >> "${GITHUB_STEP_SUMMARY}"
- name: Enable auto-merge
if: steps.diff.outputs.skip != 'true' && needs.decide.outputs.auto_merge == 'true'
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
PR_NUMBER: ${{ steps.pr.outputs.number }}
MERGE_METHOD: ${{ needs.decide.outputs.merge_method }}
run: |
set -euo pipefail
method_flag='--merge'
case "${MERGE_METHOD}" in
squash) method_flag='--squash' ;;
rebase) method_flag='--rebase' ;;
*) method_flag='--merge' ;;
esac
gh pr merge "${PR_NUMBER}" --auto ${method_flag}
echo "::notice::Auto-merge enabled on PR #${PR_NUMBER} with strategy: ${MERGE_METHOD}"

View File

@@ -157,3 +157,58 @@ jobs:
overwrite_files: true
draft: false
prerelease: ${{ contains(github.ref_name, '-') }}
# Triggers the Docker image build on SnowLuma.Docker.Framework once the
# GitHub Release (and its per-arch tarballs) is published, so the Docker
# workflow can pull the matching `SnowLuma-<tag>-linux-<arch>-lite.tar.gz`
# asset and bake it into the container.
#
# Chained as a job dependency rather than via `on: release: published`
# because workflows triggered by GITHUB_TOKEN cannot fire downstream
# workflow events (GitHub anti-loop safeguard). Doing it as `needs: release`
# keeps the dispatch under our PAT.
dispatch-docker:
needs: release
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Trigger Docker.Framework workflow_dispatch
uses: actions/github-script@v8
env:
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
DOCKER_REF: ${{ vars.DOCKER_REF }}
with:
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
script: |
const target = process.env.RELEASE_REPOSITORY;
if (!target || !target.includes('/')) {
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
}
const [owner, repo] = target.split('/');
const tag = context.ref.replace('refs/tags/', '');
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
const image = process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
const platforms = process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
const ref = process.env.DOCKER_REF || 'main';
await github.rest.actions.createWorkflowDispatch({
owner,
repo,
workflow_id: workflowId,
ref,
inputs: {
image,
tag,
push: 'true',
platforms,
snowluma_tag: tag,
snowluma_repository: sourceRepo,
},
});
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);

106
.github/workflows/sdk-npm-publish.yml vendored Normal file
View File

@@ -0,0 +1,106 @@
name: Publish SDK to npm
on:
push:
branches: [main]
paths:
- 'packages/sdk/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
- 'tsconfig.base.json'
workflow_dispatch:
permissions:
contents: read
id-token: write
concurrency:
group: sdk-npm-publish-${{ github.ref }}
cancel-in-progress: false
jobs:
publish:
name: Build, test, and publish SDK
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Type check SDK
run: pnpm --filter @snowluma/sdk typecheck
- name: Test SDK
run: pnpm --filter @snowluma/sdk test
- name: Build SDK
run: pnpm --filter @snowluma/sdk build
- name: Check npm package version
id: npm
working-directory: packages/sdk
shell: bash
run: |
set -euo pipefail
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
{
echo "package_name=${package_name}"
echo "package_version=${package_version}"
} >> "${GITHUB_OUTPUT}"
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
echo "already_published=true" >> "${GITHUB_OUTPUT}"
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
else
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
- name: Publish SDK to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/sdk
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
shell: bash
run: |
{
echo "## SDK npm publish"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
} >> "${GITHUB_STEP_SUMMARY}"

106
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,106 @@
# 贡献指南
## 分支模型
SnowLuma 使用 **`main` + `dev`** 双分支模型:
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先提交到 `dev`。
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
## 把 `dev` 合并到 `main`
新增工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。三种触发方式:
无论使用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
### 1. 提交信息前缀(推荐日常使用)
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
> 注意:是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
### 2. 推送 `chore.*` Tag
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发本工作流。这是和发布 tag 解耦的「合并触发 tag」:
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
- `v*` → 仅触发 `release.yml`(构建发布产物)
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已经过完所有检查的 `main` HEAD 构建。
### 3. 手动触发
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
工作流会按照当前 `dev` 与 `main` 的差异开 / 更新 PR。
## 启用 `main` 分支保护(必做)
仓库管理员需要在 GitHub 上为 `main` 配置一条规则集(Repository Rules)或经典分支保护,至少满足:
1. **Settings → Rules → Rulesets**(推荐)或 **Settings → Branches → Branch protection rules**。
2. 选择 `main` 作为目标分支。
3. 勾选:
- **Restrict deletions** — 禁止删除 `main`。
- **Require a pull request before merging** — 所有合并必须走 PR。
- **Block force pushes** — 禁止强推。
- **Require status checks to pass before merging(必勾)** — 把以下来自 `dev-build.yml` 的 check 全部加为 required:
- `typecheck`
- `build (win-x64)`
- `build (linux-x64)`
- `build (linux-arm64)`
- **Require branches to be up to date before merging** — 保证 PR 合并前已 rebase 过最新 `main`。
4. 在 **Bypass list / Allow specified actors to bypass** 中加入 `SnowLuma Bot` GitHub App。这样 `gh pr merge --auto` 才能在所有 required check 通过后由机器人自动完成合并;否则 PR 会一直卡在 auto-merge 等待人工 review。
5. **不要**把任何用户加入 push 白名单,确保「禁止向 `main` 直接提交」的约束生效。第一次设置完后,连仓库管理员也只能通过 PR 改 `main`。
效果:任何对 `dev` 的推送都会先在 `dev-build.yml` 上跑 typecheck + 三个架构的 build;只有全部成功,promote 工作流的 `--auto` 合并才会真正发生。失败时 PR 会保留在 open 状态,修复后再次推到 `dev` 即可重新触发检查。
## 必需的 Secrets
`promote-dev-to-main.yml` 复用 `SnowLumaNative/build-native.yml` 同一个 GitHub App。请确认 SnowLuma 仓库(或 organization)级别已经配置:
- `SNOWLUMA_BOT_APP_ID` — 数字类型的 App ID。
- `SNOWLUMA_BOT_PRIVATE_KEY` — 该 App 的 PEM 私钥。
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
## 本地工作流速查
```bash
# 切到 dev 开发
git checkout dev
git pull
# 写代码 / 跑测试
pnpm install
pnpm typecheck
pnpm -s --filter @snowluma/core test
# 普通提交(不会触发 promote)
git commit -m "fix: something"
git push
# 把 dev 合入 main(三选一)
# 方式 A:commit-msg 前缀
git commit -m "chore(release): v1.7.0" # 或 "[merge] fix: hotfix"
git push # → 触发 promote-dev-to-main
# 方式 B:chore.* 合并 tag(与发布 tag 解耦)
git tag chore.merge-20240509 # 或 chore.promote-v1.7.0 等
git push origin chore.merge-20240509 # → 触发 promote-dev-to-main
# 方式 C:在 Actions 页面手动 Run workflow
# 合并完成后,发布版本(在 main 上打 v* tag)
git checkout main && git pull
git tag v1.7.0
git push origin v1.7.0 # → 仅触发 release.yml
```

View File

@@ -3,7 +3,7 @@
## 关于项目
项目处于开发初期,仅支持部分功能,持续高速迭代中,仅支持有头。
项目处于开发初期,仅支持部分功能,高速迭代中,随时可能出现破坏性更新。
## 鸣谢
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto

View File

@@ -6,8 +6,9 @@
"type": "module",
"scripts": {
"build": "pnpm --filter @snowluma/core build",
"build:sdk": "pnpm --filter @snowluma/sdk build",
"build:webui": "pnpm --filter webui build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter webui build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
"dev": "pnpm --filter @snowluma/core dev",
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
"dev:web": "pnpm --filter webui dev",
@@ -32,4 +33,4 @@
"engines": {
"node": ">=22"
}
}
}

View File

@@ -47,6 +47,24 @@ import {
SetStatusReqSchema,
SetStatusRespSchema,
OidbSetProfileSchema,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
Oidb0x8a7RespSchema,
Oidb0x8a7ReqSchema,
Oidb0xe17RespSchema,
Oidb0xe17ReqSchema,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
MiniAppShareReqSchema,
MiniAppShareRespSchema,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
} from './proto/oidb-action';
import { FileUploadExtSchema } from './proto/highway';
import {
@@ -1358,4 +1376,359 @@ export async function setProfile(
req,
OidbSetProfileSchema
);
}
}
export async function getProfileLike(
bridge: Bridge,
userId?: number,
start: number = 0,
limit: number = 10
) {
// const isSelf = !userId || userId === bridge.qqInfo.uin;
// const targetUid = isSelf
// ? bridge.qqInfo.uid
// : await bridge.getUidByUinV2(userId!);
const isSelf = !userId
const targetUid = isSelf
? await resolveSelfUid(bridge)
: await resolveUserUid(bridge, userId)
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
targetUid: targetUid,
basic: 1,
vote: 1,
favorite: 1,
start: start,
limit: limit,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x7ed_12',
0x7ED,
12,
req,
Oidb0x7edReqSchema,
Oidb0x7edRespSchema
);
const data = result?.userLikeInfos?.[0];
if (!data) {
throw new Error('get profile like info empty');
}
return {
uid: data.uid,
time: Number(data.time),
favoriteInfo: {
total_count: data.favoriteInfo?.totalCount || 0,
last_time: Number(data.favoriteInfo?.lastTime || 0),
today_count: data.favoriteInfo?.newCount || 0,
userInfos: []
},
voteInfo: {
total_count: data.voteInfo?.totalCount || 0,
new_count: data.voteInfo?.newCount || 0,
new_nearby_count: 0,
last_visit_time: Number(data.voteInfo?.lastTime || 0),
userInfos: []
}
};
}
export async function getGroupAtAllRemain(
bridge: Bridge,
groupId: number
) {
const req = {
basic1: 1,
basic2: 2,
basic3: 1,
uin: BigInt(bridge.qqInfo.uin),
groupId: BigInt(groupId),
type: 0,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x8a7_0',
0x8A7,
0,
req,
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema
);
if (!result) {
throw new Error('get group at all remain result empty');
}
return {
can_at_all: !!result.canAtAll,
remain_at_all_count_for_group: Number(result.groupRemain || 0), // 【修改点】:防止底层库将 uint32 也返回成 BigInt 导致无法被 JSON 序列化
remain_at_all_count_for_uin: Number(result.uinRemain || 0) // 【修改点】:同上
};
}
export async function getUnidirectionalFriendList(
bridge: Bridge
) {
const reqObj = {
uint64_uin: String(bridge.qqInfo.uin),
uint64_top: 0,
uint32_req_num: 99,
bytes_cookies: ""
};
const req = {
jsonBody: JSON.stringify(reqObj)
};
const result = await sendOidbAndDecode<any>(
bridge,
'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
0xE17,
0,
req,
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema
);
if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty');
}
const parsed = JSON.parse(result.jsonBody);
return parsed.rpt_block_list || [];
}
export async function setSelfLongNick(
bridge: Bridge,
longNick: string
) {
const req = {
uin: BigInt(bridge.qqInfo.uin),
profile: {
tag: 102,
value: String(longNick)
}
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112a_2',
0x112A,
2,
req,
Oidb0x112aReqSchema,
Oidb0x112aRespSchema
);
}
export async function setInputStatus(
bridge: Bridge,
userId: number,
eventType: number
) {
const targetUid = await resolveUserUid(bridge, userId);
if (!targetUid) {
throw new Error('target uid not found');
}
const req = {
reqBody: {
uid: targetUid,
chatType: 0,
eventType: eventType
}
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xcd4_1',
0xCD4,
1,
req,
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema
);
}
export async function translateEn2Zh(
bridge: Bridge,
words: string[]
) {
const req = {
translateReq: {
srcLang: 'en',
dstLang: 'zh',
words: words
},
tag10: 1,
tag12: 1
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x990_2',
0x990,
2,
req,
Oidb0x990ReqSchema,
Oidb0x990RespSchema
);
const resp = result?.translateResp;
if (!resp) {
throw new Error('translate response empty');
}
return resp.dstWords || [];
}
export async function getMiniAppArk(
bridge: Bridge,
type: string,
title: string,
desc: string,
picUrl: string,
jumpUrl: string
) {
let appid = "1109937557"; // 默认 bili
let iconUrl = "http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg";
if (type === 'weibo') {
appid = "1109224783";
iconUrl = "http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg";
} else if (type !== 'bili') {
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
}
const request = protoEncode({
sdkVersion: "V1_PC_MINISDK_99.99.99_1_APP_A",
body: {
appid,
title,
desc,
picUrl,
jumpUrl,
iconUrl
}
}, MiniAppShareReqSchema);
const result = await bridge.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
if (!result.success || !result.responseData) {
throw new Error(result.errorMessage || 'get mini app ark failed');
}
const decoded = protoDecode(result.responseData, MiniAppShareRespSchema);
const jsonStr = decoded?.body?.jsonStr;
if (!jsonStr) {
throw new Error('mini app share json empty');
}
const parsed = JSON.parse(jsonStr);
return {
data: {
ver: parsed.ver,
prompt: parsed.prompt,
config: parsed.config,
app: parsed.appName,
view: parsed.appView,
meta: parsed.metaData,
miniappShareOrigin: 3,
miniappOpenRefer: "10002"
}
};
}
export async function clickInlineKeyboardButton(
bridge: Bridge,
groupId: number,
botAppid: number,
buttonId: string,
callbackData: string,
msgSeq: number
) {
const req = {
botAppid: BigInt(botAppid),
msgSeq: BigInt(msgSeq),
buttonId: String(buttonId),
callbackData: String(callbackData || ''),
unknown7: 0,
groupId: BigInt(groupId),
unknown9: 1,
};
const result = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0x112e_1',
0x112E,
1,
req,
Oidb0x112eReqSchema,
Oidb0x112eRespSchema
);
if (!result) {
throw new Error('click inline keyboard button result empty');
}
return {
result: Number(result.result || 0),
errMsg: result.errMsg || '',
status: 0,
promptText: result.promptText || '',
promptType: 0,
promptIcon: 0
};
}
export async function sendGroupSign(
bridge: Bridge,
groupId: number
) {
const req = {
signInInfo: {
uin: String(bridge.qqInfo.uin),
groupId: String(groupId),
version: "9.0.90"
}
};
await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xEB7_1',
0xEB7,
1,
req,
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema
);
}
export async function setAvatar(
bridge: Bridge,
source: string,
): Promise<void> {
const loaded = await loadBinarySource(source, 'avatar');
if (!loaded.bytes.length) throw new Error('avatar file is empty');
const hashes = computeHashes(loaded.bytes);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
}

View File

@@ -67,6 +67,16 @@ import {
fetchGroupFileCount as fetchGroupFileCount_,
setOnlineStatus as setOnlineStatus_,
setProfile as setProfile_,
getProfileLike as getProfileLike_,
getGroupAtAllRemain as getGroupAtAllRemain_,
getUnidirectionalFriendList as getUnidirectionalFriendList_,
setSelfLongNick as setSelfLongNick_,
setInputStatus as setInputStatus_,
translateEn2Zh as translateEn2Zh_,
getMiniAppArk as getMiniAppArk_,
clickInlineKeyboardButton as clickInlineKeyboardButton_,
sendGroupSign as sendGroupSign_,
setAvatar as setAvatar_,
} from './bridge-actions';
import {
getGroupHonorInfo as getGroupHonorInfo_,
@@ -75,14 +85,14 @@ import {
getGroupEssenceAll as getGroupEssenceAll_,
sendGroupNotice as sendGroupNotice_,
getGroupNotice as getGroupNotice_,
deleteGroupNoticeByFid as deleteGroupNotice_,
getCookiesStr as getCookiesStr_,
getCsrfToken as getCsrfToken_,
getCredentials as getCredentials_,
} from './web-actions';
import type { GroupFilesResult } from './bridge-actions';
import type { MediaIndexNode } from './bridge-actions';
export type BridgeEventCallback = (event: QQEventVariant) => void;
import { BridgeEventBus } from './event-bus';
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
@@ -116,7 +126,12 @@ export class Bridge {
private qqInfo_: QQInfo;
private pids_ = new Set<number>();
private eventCallback_: BridgeEventCallback | null = null;
/**
* Per-kind event subscription. Replaces the legacy single-callback
* firehose: downstream consumers now register exactly the kinds they
* care about and `emitEvent` fans out in parallel.
*/
readonly events = new BridgeEventBus();
private cmdHandlers_ = new Map<string, CmdParser[]>();
private packetClient_: PacketSender | null = null;
private memberRefreshTasks_ = new Map<number, Promise<void>>();
@@ -155,10 +170,6 @@ export class Bridge {
this.cmdHandlers_.set(cmd, arr);
}
setEventCallback(cb: BridgeEventCallback): void {
this.eventCallback_ = cb;
}
handlesCmd(cmd: string): boolean {
return this.cmdHandlers_.has(cmd);
}
@@ -199,20 +210,20 @@ export class Bridge {
}
private emitEvent(event: QQEventVariant): void {
if (this.eventCallback_) {
try { this.eventCallback_(event); } catch (e) {
log.error('event callback error: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
// own onError hook so one bad listener never blocks the others.
void this.events.emit(event);
}
private triggerMemberCacheRefresh(event: QQEventVariant): void {
let groupId = 0;
let reason = '';
let refreshGroupList = false;
switch (event.kind) {
case 'group_member_join':
groupId = event.groupId;
reason = 'group_member_join';
refreshGroupList = event.userUin === Number(this.qqInfo_.uin);
break;
case 'group_member_leave':
groupId = event.groupId;
@@ -231,10 +242,12 @@ export class Bridge {
const task = (async () => {
try {
if (!this.qqInfo_.findGroup(groupId)) {
if (refreshGroupList) {
try { await this.fetchGroupList(); } catch { /* ignore */ }
}
await this.fetchGroupMemberList(groupId);
if (this.qqInfo_.findGroup(groupId)) {
await this.fetchGroupMemberList(groupId);
}
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
@@ -490,8 +503,15 @@ export class Bridge {
return getGroupNotice_(this, groupId);
}
async deleteGroupNotice(groupId: number, fid: string): Promise<boolean> {
return deleteGroupNotice_(this, groupId, fid);
}
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
async getGroupAtAllRemain(groupId: number) {
return getGroupAtAllRemain_(this, groupId);
}
// extend
async setOnlineStatus(status: number, extStatus: number = 0, batteryStatus: number = 100): Promise<void> {
return setOnlineStatus_(this, status, extStatus, batteryStatus);
@@ -502,7 +522,33 @@ export class Bridge {
async getCookiesStr(domain: string): Promise<string> { return getCookiesStr_(this, domain); }
async getCsrfToken(): Promise<number> { return getCsrfToken_(this); }
async getCredentials(domain: string) { return getCredentials_(this, domain); }
async getProfileLike(userId?: number, start?: number, limit?: number) {
return getProfileLike_(this, userId, start, limit);
}
async getUnidirectionalFriendList() {
return getUnidirectionalFriendList_(this);
}
async setSelfLongNick(longNick: string) {
return setSelfLongNick_(this, longNick);
}
async setInputStatus(userId: number, eventType: number) {
return setInputStatus_(this, userId, eventType);
}
async translateEn2Zh(words: string[]) {
return translateEn2Zh_(this, words);
}
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) {
return getMiniAppArk_(this, type, title, desc, picUrl, jumpUrl);
}
async clickInlineKeyboardButton(groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) {
return clickInlineKeyboardButton_(this, groupId, botAppid, buttonId, callbackData, msgSeq);
}
async sendGroupSign(groupId: number) {
return sendGroupSign_(this, groupId);
}
async setAvatar(source: string): Promise<void> {
return setAvatar_(this, source);
}
}
// --- Module-level helper functions ---

View File

@@ -14,6 +14,8 @@ import {
MarkdownDataSchema,
} from '../proto/action';
import { uploadImageMsgInfo } from '../highway/image-upload';
import { uploadPttMsgInfo } from '../highway/ptt-upload';
import { uploadVideoMsgInfo } from '../highway/video-upload';
type ProtoElem = Partial<ProtoDecoded<typeof ElemSchema>>;
@@ -151,10 +153,46 @@ async function makeImageElem(ctx: SendContext, element: MessageElement): Promise
};
}
async function makePttElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private record target uid is missing');
}
const msgInfo = await uploadPttMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: 22,
} as any,
};
}
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private video target uid is missing');
}
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: 21,
} as any,
};
}
/**
* Build proto Elem objects from an array of MessageElements.
* Supports: text, face, at, reply, json, xml, markdown, image.
* Image elements trigger highway upload via the SendContext.
* Supports: text, face, at, reply, json, xml, markdown, image, record, video, forward.
* Image, record and video elements trigger NTV2 highway upload via the SendContext.
*/
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
const result: ProtoElem[] = [];
@@ -202,8 +240,19 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
break;
case 'record':
if (ctx) {
result.push(await makePttElem(ctx, elem));
} else {
console.warn('[ElemBuilder] record send requires SendContext');
}
break;
case 'video':
console.warn(`[ElemBuilder] ${elem.type} send not yet implemented`);
if (ctx) {
result.push(await makeVideoElem(ctx, elem));
} else {
console.warn('[ElemBuilder] video send requires SendContext');
}
break;
default:

View File

@@ -0,0 +1,130 @@
// Typed, per-kind pub/sub for bridge-level events.
//
// Replaces the single-callback firehose where every consumer received every
// event variant and had to switch on `event.kind`. Now each downstream
// concern (OneBot dispatch, member cache refresh, etc.) registers exactly
// the kinds it cares about, much closer to NapCat's per-listener pattern.
//
// `emit` is fire-and-forget: subscribers can be sync or async; async
// rejections are surfaced via `Promise.allSettled` and reported through the
// optional `onError` hook so one buggy handler never starves the others.
import type { QQEventVariant } from './events';
import { createLogger } from '../utils/logger';
type EventKind = QQEventVariant['kind'];
type EventOf<K extends EventKind> = Extract<QQEventVariant, { kind: K }>;
export type EventHandler<K extends EventKind> = (event: EventOf<K>) => void | Promise<void>;
export type AnyEventHandler = (event: QQEventVariant) => void | Promise<void>;
export interface EventBusOptions {
/** Logger label for handler failures. Defaults to `Bridge.Events`. */
loggerName?: string;
/** Override the default error reporter (e.g. for tests). */
onError?: (kind: EventKind | '*', err: unknown) => void;
}
const DEFAULT_LOGGER = createLogger('Bridge.Events');
export class BridgeEventBus {
// Per-kind subscribers are stored as `Set<unknown>` so the container
// doesn't carry a contravariant function type that fights TS variance
// rules. The runtime invariant is straightforward: handlers stored under
// key `K` only ever see `EventOf<K>` events, which is what the single
// narrowing cast at the dispatch site below relies on.
private readonly handlers = new Map<EventKind, Set<unknown>>();
private readonly anyHandlers = new Set<AnyEventHandler>();
private readonly onError: (kind: EventKind | '*', err: unknown) => void;
constructor(opts: EventBusOptions = {}) {
if (opts.onError) {
this.onError = opts.onError;
} else {
const log = opts.loggerName ? createLogger(opts.loggerName) : DEFAULT_LOGGER;
this.onError = (kind, err) => {
log.error(
'event handler error [%s]: %s',
kind,
err instanceof Error ? (err.stack ?? err.message) : String(err),
);
};
}
}
/** Subscribe to one kind. Returns an unsubscribe function. */
on<K extends EventKind>(kind: K, handler: EventHandler<K>): () => void {
let set = this.handlers.get(kind);
if (!set) {
set = new Set();
this.handlers.set(kind, set);
}
set.add(handler);
return () => {
this.handlers.get(kind)?.delete(handler);
};
}
/** Subscribe to every kind (low-volume callers like loggers). */
onAny(handler: AnyEventHandler): () => void {
this.anyHandlers.add(handler);
return () => {
this.anyHandlers.delete(handler);
};
}
off<K extends EventKind>(kind: K, handler: EventHandler<K>): void {
this.handlers.get(kind)?.delete(handler);
}
has(kind: EventKind): boolean {
return (this.handlers.get(kind)?.size ?? 0) + this.anyHandlers.size > 0;
}
/** Drop every subscriber. Mostly useful for tests. */
clear(): void {
this.handlers.clear();
this.anyHandlers.clear();
}
/**
* Dispatch an event in parallel to every subscriber for its kind plus every
* onAny handler. Rejections are isolated per-handler — one bad subscriber
* never blocks the others, and the returned promise resolves once every
* subscriber settles.
*/
async emit<K extends EventKind>(event: EventOf<K>): Promise<void> {
const kindHandlers = this.handlers.get(event.kind);
if ((!kindHandlers || kindHandlers.size === 0) && this.anyHandlers.size === 0) {
return;
}
const tasks: Promise<unknown>[] = [];
if (kindHandlers) {
for (const handler of kindHandlers) {
// Single narrowing cast — the only place we re-assert that handlers
// stored under `event.kind` accept `EventOf<event.kind>` events.
const typed = handler as EventHandler<K>;
tasks.push(invoke(this.onError, event.kind, () => typed(event)));
}
}
for (const handler of this.anyHandlers) {
tasks.push(invoke(this.onError, '*', () => handler(event)));
}
await Promise.allSettled(tasks);
}
}
async function invoke(
onError: (kind: EventKind | '*', err: unknown) => void,
kind: EventKind | '*',
fn: () => unknown,
): Promise<void> {
try {
const ret = fn();
if (ret && typeof (ret as Promise<unknown>).then === 'function') {
await ret;
}
} catch (err) {
onError(kind, err);
}
}

View File

@@ -18,6 +18,7 @@ export interface MessageElement {
replyTime?: number; // For reply: original message timestamp
replyRandom?: number; // For reply: original message random/msgId
url?: string;
thumbUrl?: string;
subType?: number;
duration?: number;
width?: number;

View File

@@ -0,0 +1,161 @@
// FFmpeg native addon wrapper — port of NapCat's FFmpegAddonAdapter.
// No fallback: throws if the addon isn't available on this platform/arch.
//
// The addon is shipped under `native/ffmpeg/ffmpegAddon.<platform>.<arch>.node`
// to match the layout used by the upstream NapCat build so the binaries
// can be dropped in as-is.
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface FFmpegVideoInfo {
width: number;
height: number;
duration: number;
format: string;
videoCodec: string;
image: Buffer;
}
interface FFmpegNativeAddon {
convertFile(inputFile: string, outputFile: string, format: string): Promise<{ success: boolean }>;
getVideoInfo(filePath: string, format?: 'bmp' | 'bmp24'): Promise<FFmpegVideoInfo>;
getDuration(filePath: string): Promise<number>;
convertToNTSilkTct(inputPath: string, outputPath: string): Promise<void>;
decodeAudioToPCM(filePath: string, pcmPath: string, sampleRate?: number): Promise<{ result: boolean; sampleRate: number }>;
decodeAudioToFmt(filePath: string, pcmPath: string, format: string): Promise<{ channels: number; sampleRate: number; format: string }>;
}
let cachedAddon: FFmpegNativeAddon | null = null;
let cachedLoadError: string | null = null;
function addonFileName(): string {
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
}
function addonSearchDirs(): string[] {
// Mirrors the hook injector's resolution strategy so the addon is found
// regardless of whether we're running from:
// 1. A released zip (dist/native/ffmpeg/<file>.node), where __dirname is
// the dist root.
// 2. The bundled build (repoRoot/dist/native/ffmpeg/<file>.node).
// 3. `tsx` dev mode (packages/runtime/native/ffmpeg/<file>.node), where
// __dirname is `packages/core/src/bridge/highway` — four levels deep
// under `packages/`. Note: the hook injector lives at
// `packages/core/src/hook` so it only needs 3 `..`; we need 4.
return [
path.resolve(__dirname, 'native', 'ffmpeg'),
path.resolve(__dirname, '..', '..', '..', '..', 'runtime', 'native', 'ffmpeg'),
path.resolve(process.cwd(), 'dist', 'native', 'ffmpeg'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native', 'ffmpeg'),
];
}
function resolveAddonPath(): string | null {
const fileName = addonFileName();
for (const dir of addonSearchDirs()) {
const full = path.join(dir, fileName);
if (fs.existsSync(full)) return full;
}
return null;
}
/**
* Load the ffmpegAddon once and return a cached instance.
* Throws on first-use failure; subsequent calls replay the same error message
* so callers don't silently fall back.
*/
export function getFFmpegAddon(): FFmpegNativeAddon {
if (cachedAddon) return cachedAddon;
if (cachedLoadError) throw new Error(cachedLoadError);
const addonPath = resolveAddonPath();
if (!addonPath) {
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
throw new Error(cachedLoadError);
}
try {
const mod = { exports: {} as Record<string, unknown> };
process.dlopen(mod, addonPath);
cachedAddon = mod.exports as unknown as FFmpegNativeAddon;
return cachedAddon;
} catch (error) {
cachedLoadError = `failed to load ffmpegAddon (${addonPath}): ${error instanceof Error ? error.message : String(error)}`;
throw new Error(cachedLoadError);
}
}
/**
* Check whether `filePath` is already an NT SILK container. The addon can
* read any input directly so the only reason we peek at the header is to
* skip the conversion (and the temp file) when the caller already fed us
* a ready-to-upload silk file.
*/
export function isSilkFile(filePath: string): boolean {
try {
const fd = fs.openSync(filePath, 'r');
try {
const buf = Buffer.alloc(10);
fs.readSync(fd, buf, 0, 10, 0);
const header = buf.toString();
return header.includes('#!SILK') || header.includes('\x02#!SILK');
} finally {
fs.closeSync(fd);
}
} catch {
return false;
}
}
export interface EncodeSilkResult {
/** Absolute path to the silk file ready for highway upload. */
path: string;
/** Voice duration in whole seconds (>= 1). */
duration: number;
/** `true` if we wrote a new silk file and the caller should unlink it. */
converted: boolean;
}
/**
* Convert `inputFile` to NT SILK when necessary and return the output path
* + duration. The caller is responsible for unlinking the returned path
* when `converted === true`.
*/
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
const addon = getFFmpegAddon();
// Already silk — trust the file, just measure duration via the addon.
if (isSilkFile(inputFile)) {
let duration = 1;
try {
duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
} catch {
// getDuration on a silk file occasionally fails on certain encodings;
// the upload path only needs a rough, non-zero value, so fall back
// to the size-based heuristic used by NapCat's audio.ts.
const stat = fs.statSync(inputFile);
duration = Math.max(1, Math.floor(stat.size / 1024 / 3));
}
return { path: inputFile, duration, converted: false };
}
fs.mkdirSync(tempDir, { recursive: true });
const outPath = path.join(tempDir, crypto.randomUUID());
await addon.convertToNTSilkTct(inputFile, outPath);
if (!fs.existsSync(outPath)) {
throw new Error('convertToNTSilkTct produced no output file');
}
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
return { path: outPath, duration, converted: true };
}
/** Default location for temporary silk files. */
export function defaultPttTempDir(): string {
return path.join(os.tmpdir(), 'snowluma-ptt');
}

View File

@@ -94,12 +94,16 @@ function makeHighwayHead(
}
export function buildHighwayExtend(
uKey: string, msgInfo: any, ipv4s: any[], sha1: Uint8Array,
uKey: string,
msgInfo: any,
ipv4s: any[],
sha1: Uint8Array | Uint8Array[],
fileIndex = 0,
): Uint8Array {
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
const first = msgInfoBody[0];
const selected = msgInfoBody[fileIndex] ?? msgInfoBody[0];
const networkIpv4s: any[] = [];
for (const ipv4 of ipv4s ?? []) {
const ip = ipv4.outIp ?? 0;
@@ -110,14 +114,14 @@ export function buildHighwayExtend(
}
return protoEncode({
fileUuid: first?.index?.fileUuid ?? '',
fileUuid: selected?.index?.fileUuid ?? '',
uKey,
network: { ipv4s: networkIpv4s },
msgInfoBody: msgInfoBody.map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
})),
blockSize: HIGHWAY_BLOCK_SIZE,
hash: { fileSha1: [sha1] },
hash: { fileSha1: Array.isArray(sha1) ? sha1 : [sha1] },
}, NTV2RichMediaHighwayExtSchema);
}

View File

@@ -0,0 +1,274 @@
// Voice (PTT) upload pipeline:
// 1. resolve / fetch the source audio bytes,
// 2. convert to NT SILK via the ffmpegAddon (skip if already silk),
// 3. NTV2 OIDB upload request — 0x126E (group) / 0x126D (private),
// 4. highway HTTP upload — commandId 1008 (group) / 1007 (private),
// 5. return the encoded `MsgInfo` bytes ready for the commonElem.
//
// Port of NapCat's `UploadGroupPtt` / `UploadPrivatePtt` transformer + the
// `uploadGroupPtt` / `uploadC2CPtt` paths in `PacketHighwayContext`.
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { protoEncode, protoDecode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import {
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
EncodableMediaMsgInfoSchema,
} from '../proto/highway';
import { loadBinarySource, computeHashes } from './utils';
import {
fetchHighwaySession,
uploadHighwayHttp,
buildHighwayExtend,
} from './highway-client';
import { encodeSilk, defaultPttTempDir } from './ffmpeg-addon';
import { createLogger } from '../../utils/logger';
const log = createLogger('Ptt');
export const PRIVATE_PTT_CMD_ID = 1007;
export const GROUP_PTT_CMD_ID = 1008;
interface PttPayload {
/** Silk bytes that get uploaded to highway. */
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
fileName: string;
/** Whole seconds, >= 1. */
duration: number;
/** Cleanup hooks invoked once the OIDB request + highway upload finish. */
cleanups: Array<() => void>;
}
/**
* Decide whether `source` looks like a local filesystem path. The shape
* matches the heuristics used inside `loadBinarySource`: we only reuse the
* caller-supplied path verbatim for things the addon can read directly.
*/
function asLocalFilePath(source: string): string | null {
if (!source) return null;
if (source.startsWith('base64://')) return null;
if (source.startsWith('http://') || source.startsWith('https://')) return null;
let filePath = source;
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
return filePath;
}
async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPayload> {
const source = element.url || element.fileId || '';
if (!source) throw new Error('record source is empty');
const cleanups: Array<() => void> = [];
// Run all queued cleanups; callable both on the success path (via the
// returned `cleanups` array) and the failure path (try/catch below).
const runCleanups = () => {
while (cleanups.length > 0) {
const fn = cleanups.pop();
if (!fn) continue;
try { fn(); } catch { /* best-effort */ }
}
};
fs.mkdirSync(tempDir, { recursive: true });
try {
// Resolve the on-disk path the addon should read. Anything that isn't
// already a local file (base64, HTTP) gets staged into the temp dir.
let inputPath: string;
const local = asLocalFilePath(source);
if (local && fs.existsSync(local)) {
inputPath = local;
} else {
const loaded = await loadBinarySource(source, 'record');
inputPath = path.join(tempDir, `snowluma-ptt-in-${crypto.randomUUID()}`);
fs.writeFileSync(inputPath, Buffer.from(loaded.bytes));
cleanups.push(() => { try { fs.unlinkSync(inputPath); } catch { /* ignore */ } });
}
const silk = await encodeSilk(inputPath, tempDir);
if (silk.converted) {
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
}
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
if (silkBytes.length === 0) throw new Error('silk file is empty after conversion');
const hashes = computeHashes(silkBytes);
return {
bytes: silkBytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: `${hashes.md5Hex}.amr`,
duration: silk.duration,
cleanups: [...cleanups],
};
} catch (err) {
runCleanups();
throw err;
}
}
function makeClientRandomId(): bigint {
// Same trick NapCat uses: 8 random bytes, masked into the positive int64
// range so it survives proto signed-int64 encoding without surprises.
const buf = crypto.randomBytes(8);
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
}
async function startPttUpload(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
ptt: PttPayload,
): Promise<any> {
const body: any = {
reqHead: {
// NapCat uses requestId=1 for group / 4 for c2c. Mirror it.
common: { requestId: isGroup ? 1 : 4, command: 100 },
scene: {
requestType: 2,
businessType: 3,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
},
client: { agentType: 2 },
},
upload: {
uploadInfo: [{
fileInfo: {
fileSize: ptt.bytes.length,
fileHash: ptt.md5Hex,
fileSha1: ptt.sha1Hex,
fileName: ptt.fileName,
// type=3 voice, voiceFormat=1 (silk).
type: { type: 3, picFormat: 0, videoFormat: 0, voiceFormat: 1 },
width: 0,
height: 0,
time: ptt.duration,
original: 0,
},
subFileType: 0,
}],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: makeClientRandomId(),
compatQmsgSceneType: isGroup ? 2 : 1,
extBizInfo: {
// NapCat fills in a placeholder textSummary so the legacy compat
// QMsg path still has something to render. Mirror it.
pic: { textSummary: 'Nya~' },
video: { bytesPbReserve: new Uint8Array(0) },
ptt: {
bytesReserve: new Uint8Array([0x08, 0x00, 0x38, 0x00]),
bytesPbReserve: new Uint8Array(0),
// `bytesGeneralFlags` differs between group / c2c voice. Lifted
// verbatim from NapCat (UploadGroupPtt.ts / UploadPrivatePtt.ts).
bytesGeneralFlags: isGroup
? new Uint8Array([0x9a, 0x01, 0x07, 0xaa, 0x03, 0x04, 0x08, 0x08, 0x12, 0x00])
: new Uint8Array([0x9a, 0x01, 0x0b, 0xaa, 0x03, 0x08, 0x08, 0x04, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00]),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
};
const oidbCmd = isGroup ? 0x126E : 0x126D;
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x126e_100' : 'OidbSvcTrpcTcp.0x126d_100';
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'ptt upload request failed');
}
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
if (!resp) throw new Error('failed to decode ptt upload response');
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error('ptt upload response body missing');
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? 'ptt upload failed');
}
return uploadBody.upload;
}
function finalizePttMsgInfo(upload: any): Uint8Array {
if (!upload?.msgInfo) throw new Error('ptt upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) extBizInfo.pic = upload.msgInfo.extBizInfo.pic;
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
}
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
}
/**
* Upload a voice clip and return the encoded `MsgInfo` bytes that go inside
* a `commonElem { serviceType: 48, businessType: 22 }`.
*/
export async function uploadPttMsgInfo(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const tempDir = defaultPttTempDir();
const ptt = await loadPtt(element, tempDir);
try {
const upload = await startPttUpload(bridge, isGroup, targetIdOrUid, ptt);
// Highway upload only happens when the server didn't fast-path the file
// (uKey present == "we want the bytes"). Otherwise we just embed the
// returned MsgInfo and trust the dedupe.
const uKey = upload?.uKey ?? '';
if (uKey && upload?.msgInfo) {
log.debug('highway upload: bytes=%d md5=%s scene=%s', ptt.bytes.length, ptt.md5Hex, isGroup ? 'group' : 'c2c');
const session = await fetchHighwaySession(bridge);
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], ptt.sha1);
const commandId = isGroup ? GROUP_PTT_CMD_ID : PRIVATE_PTT_CMD_ID;
await uploadHighwayHttp(bridge, session, commandId, ptt.bytes, ptt.md5, extend);
} else {
log.debug('ptt fast-uploaded (server already has md5=%s)', ptt.md5Hex);
}
return finalizePttMsgInfo(upload);
} finally {
for (const fn of ptt.cleanups) {
try { fn(); } catch { /* best-effort cleanup */ }
}
}
}

View File

@@ -0,0 +1,531 @@
// Video upload pipeline:
// 1. resolve / fetch the source video and optional thumbnail,
// 2. generate a thumbnail via ffmpegAddon when needed,
// 3. NTV2 OIDB upload request - 0x11EA (group) / 0x11E9 (private),
// 4. highway HTTP upload for video + thumbnail,
// 5. return the encoded `MsgInfo` bytes ready for the commonElem.
//
// Port of NapCat's UploadGroupVideo / UploadPrivateVideo transformers and
// the uploadGroupVideo / uploadC2CVideo paths in PacketHighwayContext.
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { protoEncode, protoDecode } from '../../protobuf/decode';
import { makeOidbBaseSchema } from '../proto/oidb';
import {
NTV2UploadRichMediaReqSchema,
NTV2UploadRichMediaRespSchema,
EncodableMediaMsgInfoSchema,
} from '../proto/highway';
import {
loadBinarySource,
computeHashes,
detectImageFormat,
} from './utils';
import {
fetchHighwaySession,
uploadHighwayHttp,
buildHighwayExtend,
} from './highway-client';
import { getFFmpegAddon } from './ffmpeg-addon';
import { createLogger } from '../../utils/logger';
const log = createLogger('Video');
export const PRIVATE_VIDEO_CMD_ID = 1001;
export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
export const GROUP_VIDEO_CMD_ID = 1005;
export const GROUP_VIDEO_THUMB_CMD_ID = 1006;
const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024;
const FALLBACK_THUMB = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
'base64',
);
interface VideoPayload {
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
sha1Blocks: Uint8Array[];
md5Hex: string;
sha1Hex: string;
fileName: string;
filePath: string;
width: number;
height: number;
duration: number;
thumb: ThumbPayload;
cleanups: Array<() => void>;
}
interface ThumbPayload {
bytes: Uint8Array;
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
width: number;
height: number;
}
class Sha1StreamState {
readonly blockSize = 64;
private readonly padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]);
private readonly state = new Uint32Array(5);
private readonly count = new Uint32Array(2);
private readonly buffer = Buffer.allocUnsafe(this.blockSize);
private readonly w = new Uint32Array(80);
constructor() {
this.reset();
}
private reset(): void {
this.state[0] = 0x67452301;
this.state[1] = 0xEFCDAB89;
this.state[2] = 0x98BADCFE;
this.state[3] = 0x10325476;
this.state[4] = 0xC3D2E1F0;
this.count[0] = 0;
this.count[1] = 0;
this.buffer.fill(0);
}
private rotateLeft(value: number, offset: number): number {
return ((value << offset) | (value >>> (32 - offset))) >>> 0;
}
private transform(chunk: Uint8Array, offset: number): void {
const view = new DataView(chunk.buffer, chunk.byteOffset + offset, this.blockSize);
for (let i = 0; i < 16; i++) {
this.w[i] = view.getUint32(i * 4, false);
}
for (let i = 16; i < 80; i++) {
this.w[i] = this.rotateLeft(this.w[i - 3] ^ this.w[i - 8] ^ this.w[i - 14] ^ this.w[i - 16], 1);
}
let a = this.state[0];
let b = this.state[1];
let c = this.state[2];
let d = this.state[3];
let e = this.state[4];
for (let i = 0; i < 80; i++) {
let temp: number;
if (i < 20) {
temp = ((b & c) | (~b & d)) + 0x5A827999;
} else if (i < 40) {
temp = (b ^ c ^ d) + 0x6ED9EBA1;
} else if (i < 60) {
temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC;
} else {
temp = (b ^ c ^ d) + 0xCA62C1D6;
}
temp += (this.rotateLeft(a, 5) + e + this.w[i]) >>> 0;
e = d;
d = c;
c = this.rotateLeft(b, 30);
b = a;
a = temp >>> 0;
}
this.state[0] = (this.state[0] + a) >>> 0;
this.state[1] = (this.state[1] + b) >>> 0;
this.state[2] = (this.state[2] + c) >>> 0;
this.state[3] = (this.state[3] + d) >>> 0;
this.state[4] = (this.state[4] + e) >>> 0;
}
update(data: Uint8Array): void {
let index = (this.count[0] >>> 3) & 0x3F;
const dataLen = data.length;
this.count[0] = (this.count[0] + (dataLen << 3)) >>> 0;
if (this.count[0] < (dataLen << 3)) this.count[1] = (this.count[1] + 1) >>> 0;
this.count[1] = (this.count[1] + (dataLen >>> 29)) >>> 0;
const partLen = this.blockSize - index;
let i = 0;
if (dataLen >= partLen) {
this.buffer.set(data.subarray(0, partLen), index);
this.transform(this.buffer, 0);
for (i = partLen; i + this.blockSize <= dataLen; i += this.blockSize) {
this.transform(data, i);
}
index = 0;
}
if (i < dataLen) {
this.buffer.set(data.subarray(i, dataLen), index);
}
}
hash(bigEndian = true): Uint8Array {
const digest = Buffer.allocUnsafe(20);
for (let i = 0; i < 5; i++) {
if (bigEndian) digest.writeUInt32BE(this.state[i], i * 4);
else digest.writeUInt32LE(this.state[i], i * 4);
}
return new Uint8Array(digest);
}
final(): Uint8Array {
const bits = Buffer.allocUnsafe(8);
bits.writeUInt32BE(this.count[1], 0);
bits.writeUInt32BE(this.count[0], 4);
const index = (this.count[0] >>> 3) & 0x3F;
const padLen = index < 56 ? 56 - index : 120 - index;
this.update(this.padding.subarray(0, padLen));
this.update(bits);
return this.hash(true);
}
}
function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] {
const sha1 = new Sha1StreamState();
const blocks: Uint8Array[] = [];
let bytesRead = 0;
let offset = 0;
while (offset + sha1.blockSize <= bytes.length) {
const block = bytes.subarray(offset, offset + sha1.blockSize);
sha1.update(block);
offset += sha1.blockSize;
bytesRead += sha1.blockSize;
if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) {
blocks.push(sha1.hash(false));
}
}
if (offset < bytes.length) sha1.update(bytes.subarray(offset));
blocks.push(sha1.final());
return blocks;
}
function asLocalFilePath(source: string): string | null {
if (!source) return null;
if (source.startsWith('base64://')) return null;
if (source.startsWith('http://') || source.startsWith('https://')) return null;
let filePath = source;
if (filePath.startsWith('file://')) filePath = filePath.slice(7);
if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
return filePath;
}
function defaultVideoTempDir(): string {
return path.join(os.tmpdir(), 'snowluma-video');
}
function sourceExtension(fileName: string, source: string): string {
const fromName = path.extname(fileName);
if (fromName) return fromName;
const local = asLocalFilePath(source);
const fromSource = local ? path.extname(local) : '';
return fromSource || '.mp4';
}
function makeClientRandomId(): bigint {
const buf = crypto.randomBytes(8);
return buf.readBigUInt64BE() & 0x7FFFFFFFFFFFFFFFn;
}
async function stageVideoSource(element: MessageElement, tempDir: string, cleanups: Array<() => void>): Promise<{
bytes: Uint8Array;
filePath: string;
fileName: string;
}> {
const source = element.url || element.fileId || '';
if (!source) throw new Error('video source is empty');
const local = asLocalFilePath(source);
if (local && fs.existsSync(local)) {
return {
bytes: new Uint8Array(fs.readFileSync(local)),
filePath: local,
fileName: element.fileName || path.basename(local),
};
}
const loaded = await loadBinarySource(source, 'video');
const fileName = element.fileName || loaded.fileName || '';
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
cleanups.push(() => { try { fs.unlinkSync(stagedPath); } catch { /* ignore */ } });
return {
bytes: loaded.bytes,
filePath: stagedPath,
fileName,
};
}
async function loadThumb(element: MessageElement, videoPath: string): Promise<{
thumb: ThumbPayload;
width: number;
height: number;
duration: number;
}> {
let width = element.width ?? 0;
let height = element.height ?? 0;
let duration = element.duration ?? 0;
let thumbBytes: Uint8Array | null = null;
if (element.thumbUrl) {
try {
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
} catch (err) {
log.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
}
}
if (!thumbBytes) {
try {
const info = await getFFmpegAddon().getVideoInfo(videoPath);
width = width || info.width || 0;
height = height || info.height || 0;
duration = duration || Math.max(1, Math.round(info.duration || 0));
if (info.image && info.image.length > 0) {
thumbBytes = new Uint8Array(info.image);
}
} catch (err) {
log.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
}
}
if (!thumbBytes) {
thumbBytes = new Uint8Array(FALLBACK_THUMB);
}
const fmt = detectImageFormat(thumbBytes);
width = width || fmt.width || 1;
height = height || fmt.height || 1;
duration = duration || 1;
const hashes = computeHashes(thumbBytes);
return {
width,
height,
duration,
thumb: {
bytes: thumbBytes,
md5: hashes.md5,
sha1: hashes.sha1,
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
width,
height,
},
};
}
async function loadVideo(element: MessageElement): Promise<VideoPayload> {
const tempDir = defaultVideoTempDir();
const cleanups: Array<() => void> = [];
fs.mkdirSync(tempDir, { recursive: true });
try {
const staged = await stageVideoSource(element, tempDir, cleanups);
if (staged.bytes.length === 0) throw new Error('video file is empty');
if (staged.bytes.length > MAX_VIDEO_SIZE) {
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB`);
}
const hashes = computeHashes(staged.bytes);
const { thumb, width, height, duration } = await loadThumb(element, staged.filePath);
return {
bytes: staged.bytes,
md5: hashes.md5,
sha1: hashes.sha1,
sha1Blocks: computeVideoSha1Blocks(staged.bytes),
md5Hex: hashes.md5Hex,
sha1Hex: hashes.sha1Hex,
fileName: staged.fileName || `${hashes.md5Hex}.mp4`,
filePath: staged.filePath,
width,
height,
duration,
thumb,
cleanups: [...cleanups],
};
} catch (err) {
for (const fn of cleanups.reverse()) {
try { fn(); } catch { /* best-effort cleanup */ }
}
throw err;
}
}
async function startVideoUpload(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
video: VideoPayload,
): Promise<any> {
const body: any = {
reqHead: {
common: { requestId: 3, command: 100 },
scene: {
requestType: 2,
businessType: 2,
sceneType: isGroup ? 2 : 1,
...(isGroup
? { group: { groupUin: Number(targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(targetIdOrUid) } }),
},
client: { agentType: 2 },
},
upload: {
uploadInfo: [
{
fileInfo: {
fileSize: video.bytes.length,
fileHash: video.md5Hex,
fileSha1: video.sha1Hex,
fileName: 'nya.mp4',
type: { type: 2, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
height: 0,
width: 0,
time: 0,
original: 0,
},
subFileType: 0,
},
{
fileInfo: {
fileSize: video.thumb.bytes.length,
fileHash: video.thumb.md5Hex,
fileSha1: video.thumb.sha1Hex,
fileName: 'nya.jpg',
type: { type: 1, picFormat: 0, videoFormat: 0, voiceFormat: 0 },
height: video.thumb.height,
width: video.thumb.width,
time: 0,
original: 0,
},
subFileType: 100,
},
],
tryFastUploadCompleted: true,
srvSendMsg: false,
clientRandomId: makeClientRandomId(),
compatQmsgSceneType: 2,
extBizInfo: {
pic: { bizType: 0, textSummary: 'Nya~' },
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
ptt: {
bytesPbReserve: new Uint8Array(0),
bytesReserve: new Uint8Array(0),
bytesGeneralFlags: new Uint8Array(0),
},
},
clientSeq: 0,
noNeedCompatMsg: false,
},
};
const oidbCmd = isGroup ? 0x11EA : 0x11E9;
const serviceCmd = isGroup ? 'OidbSvcTrpcTcp.0x11ea_100' : 'OidbSvcTrpcTcp.0x11e9_100';
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema);
const request = protoEncode({
command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1,
}, baseSchema);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'video upload request failed');
}
const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const resp: any = protoDecode(result.responseData, respBaseSchema);
if (!resp) throw new Error('failed to decode video upload response');
if (resp.errorCode && resp.errorCode !== 0) {
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
if (!uploadBody) throw new Error('video upload response body missing');
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
throw new Error(uploadBody.respHead.message ?? 'video upload failed');
}
return uploadBody.upload;
}
function finalizeVideoMsgInfo(upload: any): Uint8Array {
if (!upload?.msgInfo) throw new Error('video upload response missing msgInfo');
const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({
index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum,
}));
const extBizInfo: any = {};
if (upload.msgInfo.extBizInfo?.pic) extBizInfo.pic = upload.msgInfo.extBizInfo.pic;
if (upload.msgInfo.extBizInfo?.video) extBizInfo.video = upload.msgInfo.extBizInfo.video;
if (upload.msgInfo.extBizInfo?.ptt) extBizInfo.ptt = upload.msgInfo.extBizInfo.ptt;
if (upload.msgInfo.extBizInfo?.busiType !== undefined) {
extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType;
}
return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema);
}
/**
* Upload a video and return the encoded `MsgInfo` bytes that go inside
* a `commonElem { serviceType: 48, businessType: 21 }`.
*/
export async function uploadVideoMsgInfo(
bridge: Bridge,
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const video = await loadVideo(element);
try {
const upload = await startVideoUpload(bridge, isGroup, targetIdOrUid, video);
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
const getSession = async () => {
session ??= await fetchHighwaySession(bridge);
return session;
};
const uKey = upload?.uKey ?? '';
if (uKey && upload?.msgInfo) {
log.debug('highway video upload: bytes=%d md5=%s scene=%s', video.bytes.length, video.md5Hex, isGroup ? 'group' : 'c2c');
const extend = buildHighwayExtend(uKey, upload.msgInfo, upload.ipv4s ?? [], video.sha1Blocks, 0);
const commandId = isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID;
await uploadHighwayHttp(bridge, await getSession(), commandId, video.bytes, video.md5, extend);
} else {
log.debug('video fast-uploaded (server already has md5=%s)', video.md5Hex);
}
const subFile = upload?.subFileInfos?.[0];
if (subFile?.uKey && upload?.msgInfo) {
log.debug('highway video thumb upload: bytes=%d md5=%s scene=%s', video.thumb.bytes.length, video.thumb.md5Hex, isGroup ? 'group' : 'c2c');
const extend = buildHighwayExtend(subFile.uKey, upload.msgInfo, subFile.ipv4s ?? [], video.thumb.sha1, 1);
const commandId = isGroup ? GROUP_VIDEO_THUMB_CMD_ID : PRIVATE_VIDEO_THUMB_CMD_ID;
await uploadHighwayHttp(bridge, await getSession(), commandId, video.thumb.bytes, video.thumb.md5, extend);
} else {
log.debug('video thumb fast-uploaded (server already has md5=%s)', video.thumb.md5Hex);
}
return finalizeVideoMsgInfo(upload);
} finally {
for (const fn of video.cleanups) {
try { fn(); } catch { /* best-effort cleanup */ }
}
}
}

View File

@@ -4,7 +4,6 @@
import type { NtqqHandler } from '../protocol/ntqq-handler';
import type { PacketInfo } from '../protocol/types';
import type { QQEventVariant } from './events';
import { Bridge } from './bridge';
import { QQInfo } from './qq-info';
import type { PacketSender } from '../protocol/packet-sender';
@@ -12,7 +11,6 @@ import { createLogger } from '../utils/logger';
export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string) => void;
export type BridgeEventCallback = (uin: string, event: QQEventVariant) => void;
interface QQSession {
qqInfo: QQInfo;
@@ -28,11 +26,9 @@ export class BridgeManager {
private onSessionStarted_: SessionStartedCallback | null = null;
private onSessionClosed_: SessionClosedCallback | null = null;
private onBridgeEvent_: BridgeEventCallback | null = null;
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
setEventCallback(cb: BridgeEventCallback): void { this.onBridgeEvent_ = cb; }
bind(ntqq: NtqqHandler): void {
ntqq.registerCmdAll((pkt: PacketInfo) => this.onPacket(pkt));
@@ -115,11 +111,9 @@ export class BridgeManager {
session = { qqInfo, bridge };
this.sessions_.set(uin, session);
// Wire event callback
bridge.setEventCallback((event) => {
if (this.onBridgeEvent_) this.onBridgeEvent_(uin, event);
});
// Each downstream consumer (e.g. OneBotInstance) subscribes to
// `bridge.events` directly via the per-kind bus — there is no longer a
// generic firehose to wire here.
return { session, created: true };
}

View File

@@ -862,4 +862,160 @@ export const OidbSetProfileSchema = {
uin: { field: 1, type: 'uint64' as const },
stringProfiles: { field: 2, type: 'repeated_message' as const, schema: OidbProfileStringItemSchema },
intProfiles: { field: 3, type: 'repeated_message' as const, schema: OidbProfileIntItemSchema },
} satisfies ProtoSchema;
} satisfies ProtoSchema;
export const Oidb0x7edInteractionSchema = {
totalCount: { field: 1, type: 'uint32' as const },
newCount: { field: 2, type: 'uint32' as const },
todayCount: { field: 3, type: 'uint32' as const },
lastTime: { field: 4, type: 'uint64' as const },
// userInfos: { field: 7, type: 'repeated_message' ... } // 我没有这个字段,期待未来补全
} satisfies ProtoSchema;
export const Oidb0x7edUserLikeInfoSchema = {
uid: { field: 1, type: 'string' as const },
time: { field: 2, type: 'uint64' as const },
favoriteInfo: { field: 3, type: 'message' as const, schema: Oidb0x7edInteractionSchema },
voteInfo: { field: 4, type: 'message' as const, schema: Oidb0x7edInteractionSchema },
} satisfies ProtoSchema;
export const Oidb0x7edReqSchema = {
targetUid: { field: 1, type: 'string' as const },
basic: { field: 2, type: 'uint32' as const },
vote: { field: 3, type: 'uint32' as const },
favorite: { field: 4, type: 'uint32' as const },
start: { field: 12, type: 'uint32' as const },
limit: { field: 103, type: 'uint32' as const }, // 0xB8 0x06
} satisfies ProtoSchema;
export const Oidb0x7edRespSchema = {
userLikeInfos: { field: 1, type: 'repeated_message' as const, schema: Oidb0x7edUserLikeInfoSchema },
} satisfies ProtoSchema;
export const Oidb0x8a7ReqSchema = {
basic1: { field: 1, type: 'uint32' as const },
basic2: { field: 2, type: 'uint32' as const },
basic3: { field: 3, type: 'uint32' as const },
uin: { field: 4, type: 'uint64' as const },
groupId: { field: 5, type: 'uint64' as const },
type: { field: 12, type: 'uint32' as const },
} satisfies ProtoSchema;
export const Oidb0x8a7RespSchema = {
uinRemain: { field: 2, type: 'uint32' as const },
groupRemain: { field: 3, type: 'uint32' as const },
msg: { field: 4, type: 'string' as const },
canAtAll: { field: 6, type: 'bool' as const },
} satisfies ProtoSchema;
export const Oidb0xe17ReqSchema = {
jsonBody: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const Oidb0xe17RespSchema = {
jsonBody: { field: 4, type: 'string' as const },
} satisfies ProtoSchema;
export const Oidb0x112aProfileInfoSchema = {
tag: { field: 1, type: 'uint32' as const },
value: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const Oidb0x112aReqSchema = {
uin: { field: 1, type: 'uint64' as const },
profile: { field: 2, type: 'message' as const, schema: Oidb0x112aProfileInfoSchema },
} satisfies ProtoSchema;
export const Oidb0x112aRespSchema = {} satisfies ProtoSchema;
export const Oidb0xcd4ReqBodySchema = {
uid: { field: 1, type: 'string' as const },
chatType: { field: 2, type: 'uint32' as const }, // 默认为 0
eventType: { field: 3, type: 'uint32' as const }, // 输入状态 1 等
} satisfies ProtoSchema;
export const Oidb0xcd4ReqSchema = {
reqBody: { field: 1, type: 'message' as const, schema: Oidb0xcd4ReqBodySchema },
} satisfies ProtoSchema;
export const Oidb0xcd4RespSchema = {} satisfies ProtoSchema;
export const Oidb0x990TranslateReqSchema = {
srcLang: { field: 1, type: 'string' as const },
dstLang: { field: 2, type: 'string' as const },
words: { field: 3, type: 'repeated_string' as const },
} satisfies ProtoSchema;
export const Oidb0x990ReqSchema = {
translateReq: { field: 2, type: 'message' as const, schema: Oidb0x990TranslateReqSchema },
tag10: { field: 10, type: 'uint32' as const },
tag12: { field: 12, type: 'uint32' as const },
} satisfies ProtoSchema;
export const Oidb0x990TranslateRespSchema = {
errorCode: { field: 1, type: 'uint32' as const },
errorMsg: { field: 2, type: 'string' as const },
srcLang: { field: 3, type: 'string' as const },
dstLang: { field: 4, type: 'string' as const },
srcWords: { field: 5, type: 'repeated_string' as const },
dstWords: { field: 6, type: 'repeated_string' as const },
} satisfies ProtoSchema;
export const Oidb0x990RespSchema = {
translateResp: { field: 2, type: 'message' as const, schema: Oidb0x990TranslateRespSchema }
} satisfies ProtoSchema;
export const MiniAppShareReqBodySchema = {
appid: { field: 2, type: 'string' as const },
title: { field: 3, type: 'string' as const },
desc: { field: 4, type: 'string' as const },
picUrl: { field: 9, type: 'string' as const },
jumpUrl: { field: 11, type: 'string' as const },
iconUrl: { field: 12, type: 'string' as const },
} satisfies ProtoSchema;
export const MiniAppShareReqSchema = {
sdkVersion: { field: 2, type: 'string' as const },
body: { field: 4, type: 'message' as const, schema: MiniAppShareReqBodySchema },
} satisfies ProtoSchema;
export const MiniAppShareRespBodySchema = {
jsonStr: { field: 2, type: 'string' as const },
} satisfies ProtoSchema;
export const MiniAppShareRespSchema = {
status: { field: 2, type: 'uint32' as const },
msg: { field: 3, type: 'string' as const },
body: { field: 4, type: 'message' as const, schema: MiniAppShareRespBodySchema },
} satisfies ProtoSchema;
export const Oidb0x112eReqSchema = {
botAppid: { field: 3, type: 'uint64' as const },
msgSeq: { field: 4, type: 'uint64' as const },
buttonId: { field: 5, type: 'string' as const },
callbackData: { field: 6, type: 'string' as const },
unknown7: { field: 7, type: 'uint32' as const },
groupId: { field: 8, type: 'uint64' as const },
unknown9: { field: 9, type: 'uint32' as const },
} satisfies ProtoSchema;
export const Oidb0x112eRespSchema = {
result: { field: 3, type: 'uint32' as const },
promptText: { field: 4, type: 'string' as const },
errMsg: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
export const Oidb0xeb7SignInInfoSchema = {
uin: { field: 1, type: 'string' as const },
groupId: { field: 2, type: 'string' as const },
version: { field: 3, type: 'string' as const },
} satisfies ProtoSchema;
export const Oidb0xeb7ReqSchema = {
signInInfo: { field: 2, type: 'message' as const, schema: Oidb0xeb7SignInInfoSchema },
} satisfies ProtoSchema;
export const Oidb0xeb7RespSchema = {} satisfies ProtoSchema;

View File

@@ -12,7 +12,7 @@ import {
import { RequestUtil } from './web/request-util';
import { getHonorListWebAPI, WebHonorType } from './web/group-honor';
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from './web/group-essence';
import { setGroupNoticeWebAPI, getGroupNoticeWebAPI } from './web/group-notice';
import { setGroupNoticeWebAPI, getGroupNoticeWebAPI, uploadGroupNoticeImage, deleteGroupNotice } from './web/group-notice';
export async function forceFetchClientKey(bridge: Bridge) {
const resp = await sendOidbAndDecode<any>(
@@ -189,15 +189,25 @@ export async function sendGroupNotice(
let imgWidth = 540;
let imgHeight = 300;
if (options?.image) {
let imageBuffer: Buffer;
// 暂时不知道怎么实现,后面有空再看看
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
const response = await fetch(options.image);
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
imageBuffer = Buffer.from(await response.arrayBuffer());
} else {
const { readFileSync } = await import('fs');
imageBuffer = readFileSync(options.image);
}
// if (options?.image) {
// const picInfo = await bridge.uploadGroupBulletinPic(groupCode, options.image);
// picId = picInfo.id;
// imgWidth = picInfo.width;
// imgHeight = picInfo.height;
// }
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
if (picInfo) {
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
@@ -261,6 +271,12 @@ export async function getGroupNotice(bridge: Bridge, groupId: number) {
return retNotices;
}
export async function deleteGroupNoticeByFid(bridge: Bridge, groupId: number, fid: string): Promise<boolean> {
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNotice(cookieObject, groupCode, fid);
}
/**
* 提取的公共算法:根据 skey/p_skey 计算 bkn (也就是 token / csrf_token)
*/

View File

@@ -1,4 +1,7 @@
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
import { RequestUtil, cookieToString } from './request-util';
import https from 'node:https';
// import { readFileSync } from 'node:fs';
// import * as console from "node:console";
export interface SetNoticeRetSuccess {
ec?: number;
@@ -6,6 +9,12 @@ export interface SetNoticeRetSuccess {
[key: string]: any;
}
export interface UploadImageRetSuccess {
ec?: number;
id?: string;
[key: string]: any;
}
export interface WebApiGroupNoticeFeed {
fid: string;
u: number;
@@ -26,6 +35,14 @@ export interface WebApiGroupNoticeRet {
[key: string]: any;
}
export function calculateBkn(key: string): string {
let hash = 5381;
for (let i = 0; i < key.length; i++) {
const code = key.charCodeAt(i);
hash = hash + (hash << 5) + code;
}
return (hash & 0x7FFFFFFF).toString();
}
/**
* 发送群公告 Web API
@@ -44,33 +61,54 @@ export async function setGroupNoticeWebAPI(
imgHeight: number = 300
): Promise<SetNoticeRetSuccess | undefined> {
try {
// 分别获取 skey 和 p_skey
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey);
//
// console.log(skey)
// console.log(pskey)
//
// console.log(urlBkn);
// console.log(bodyBkn)
const settings = JSON.stringify({
is_show_edit_card: isShowEditCard,
tip_window_type: tipWindowType,
confirm_required: confirmRequired,
});
const externalParam = {
pic: picId,
imgWidth: imgWidth.toString(),
imgHeight: imgHeight.toString(),
};
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?${new URLSearchParams({
bkn: getBknFromCookie(cookieObject),
const bodyParams: Record<string, string> = {
qid: groupCode,
bkn: bodyBkn,
text: content,
pinned: pinned.toString(),
type: type.toString(),
settings,
...(picId === '' ? {} : externalParam),
}).toString()}`;
};
if (picId !== '') {
bodyParams.pic = picId;
bodyParams.imgWidth = imgWidth.toString();
bodyParams.imgHeight = imgHeight.toString();
}
// 注意这里:URL 必须使用 skey 算出来的 bkn
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
const body = new URLSearchParams(bodyParams).toString();
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST', // 注意这里必须是 POST
'',
{ Cookie: cookieToString(cookieObject) }
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret;
} catch (e) {
@@ -78,35 +116,151 @@ export async function setGroupNoticeWebAPI(
}
}
/**
* 获取群公告列表 Web API
*/
export async function getGroupNoticeWebAPI(
cookieObject: Record<string, string>,
groupCode: string
groupCode: string,
start: number = -1, // -1 表示第一页
count: number = 20 // 抓包中是 10,你可以根据需要调整
): Promise<WebApiGroupNoticeRet | undefined> {
const bkn = getBknFromCookie(cookieObject);
const params = new URLSearchParams({
bkn: bkn,
qid: groupCode,
ft: '23',
ni: '1',
i: '1',
log_read: '1',
platform: '1',
s: '-1',
}).toString();
const url = `https://web.qun.qq.com/cgi-bin/announce/get_t_list?${params}&n=20`;
try {
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
const bodyParams = new URLSearchParams({
qid: groupCode,
bkn: bodyBkn, // Body 中传入 p_skey 计算结果
ft: '23',
s: start.toString(), // 分页游标
n: count.toString(), // 获取数量
i: '1',
ni: '1'
}).toString();
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
url,
'GET',
'',
{ Cookie: cookieToString(cookieObject) }
'POST',
bodyParams,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
},
true,
false
);
// console.log(JSON.stringify(ret, null, 2));
return ret?.ec === 0 ? ret : undefined;
} catch {
return undefined;
}
}
/**
* 上传群公告图片 Web API
*/
export async function uploadGroupNoticeImage(
cookieObject: Record<string, string>,
imageBuffer: Buffer
): Promise<{ id: string; width: number; height: number } | undefined> {
try {
const bkn = calculateBkn(cookieObject['skey']);
const boundary = `-----------------------------${Date.now()}`;
const parts: Buffer[] = [];
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
parts.push(imageBuffer);
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
const body = Buffer.concat(parts);
const url = 'https://web.qun.qq.com/cgi-bin/announce/upload_img';
const options = {
hostname: 'web.qun.qq.com',
path: '/cgi-bin/announce/upload_img',
method: 'POST',
headers: {
'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': body.length,
'Cookie': cookieToString(cookieObject),
},
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
try {
const result = JSON.parse(data) as UploadImageRetSuccess;
if (result.ec === 0 && result.id) {
const unescapedIdStr = result.id.replace(/&quot;/g, '"');
const idObj = JSON.parse(unescapedIdStr);
resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
} else {
resolve(undefined);
}
} catch {
resolve(undefined);
}
});
});
req.on('error', () => resolve(undefined));
req.write(body);
req.end();
});
} catch {
return undefined;
}
}
/**
* 删除群公告 Web API
*/
export async function deleteGroupNotice(
cookieObject: Record<string, string>,
groupCode: string,
fid: string
): Promise<boolean> {
try {
const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
const params = new URLSearchParams({
bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
fid: fid,
qid: groupCode,
}).toString();
// 注意这里:URL 拼接 urlBkn
const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
params,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret?.ec === 0;
} catch {
return false;
}
}

View File

@@ -76,9 +76,7 @@ export class HookManager {
async listProcesses(): Promise<HookProcessInfo[]> {
const processes = listHookProcesses();
const seen = new Set<number>();
for (const proc of processes) {
seen.add(proc.pid);
const state = this.ensureState(proc.pid);
state.name = proc.name || state.name;
state.path = proc.path || state.path;
@@ -87,11 +85,6 @@ export class HookManager {
for (const proc of processes) {
result.push(this.toPublicInfo(this.ensureState(proc.pid)));
}
for (const state of this.states.values()) {
if (!seen.has(state.pid) && (state.injected || state.client)) {
result.push(this.toPublicInfo(state));
}
}
return result.sort((a, b) => a.pid - b.pid);
}
@@ -165,13 +158,12 @@ export class HookManager {
const livePipes = await QqHookClient.listLivePipes();
if (livePipes.has(pid)) {
state.injected = true;
state.method = 'reconnect';
state.method = state.method || 'reconnect';
log.info('PID=%d already has SnowLuma pipe; will reconnect via watcher', pid);
} else {
state.injectResult = injectHookProcess(pid);
state.injected = true;
state.method = state.injectResult.method;
log.info('SnowLuma loaded into PID=%d via %s', pid, state.method);
}
}
state.status = state.connected
@@ -317,6 +309,7 @@ export class HookManager {
try {
const livePipes = await QqHookClient.listLivePipes();
const processes = listHookProcesses();
const runningSet = new Set(processes.map(p => p.pid));
// Refresh metadata + ensure a state entry exists for each known PID.
for (const proc of processes) {
@@ -326,6 +319,7 @@ export class HookManager {
}
// Auto-detect hooks that survived a SnowLuma restart or failed unload.
for (const pid of livePipes) {
if (!runningSet.has(pid)) continue;
const state = this.ensureState(pid);
if (!state.injected) {
state.injected = true;
@@ -335,14 +329,15 @@ export class HookManager {
}
}
const runningSet = new Set(processes.map(p => p.pid));
const tasks: Promise<unknown>[] = [];
for (const state of [...this.states.values()]) {
const alivePipe = livePipes.has(state.pid);
const aliveProc = runningSet.has(state.pid);
// Reap stale state entries that have nothing left to do.
if (!aliveProc && !alivePipe && !state.injected && !state.client) {
if (!aliveProc) {
const wasLoggedIn = state.loggedIn;
this.tearDownClient(state);
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(state.pid);
this.states.delete(state.pid);
continue;
}

View File

@@ -25,7 +25,6 @@ async function main() {
process.env.SNOWLUMA_DEV_WEBUI === '1'
) {
try {
log.info('WebUI is enabled, starting...');
const { initWebUI } = await import('./webui/server');
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager);
} catch (err) {

View File

@@ -239,16 +239,13 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and content are required');
}
if (image) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented: image upload for group notice is not supported yet');
}
if (!ctx.sendGroupNotice) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const options = {
image: image || undefined,
pinned: params.pinned !== undefined ? Number(params.pinned) : 0,
type: params.type !== undefined ? Number(params.type) : 1,
confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1,
@@ -277,8 +274,28 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
}
});
h.registerAction('_del_group_notice', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('_del_group_notice', async (params) => {
const groupId = asNumber(params.group_id);
const fid = asString(params.fid) || asString(params.notice_id);
if (!groupId || !fid) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and fid/notice_id are required');
}
if (!ctx.deleteGroupNotice) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const success = await ctx.deleteGroupNotice(groupId, fid);
if (success) {
return okResponse();
} else {
return failedResponse(RETCODE.ACTION_FAILED, 'delete failed');
}
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
// --- Forward messages ---
@@ -392,22 +409,20 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
// --- Media ---
h.registerAction('get_image', async (params) => {
const file = asString(params.file);
const file = asString(params.file) || asString(params.file_id);
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
const imageInfo = findMediaInStore('image', file, ctx);
if (imageInfo) {
return okResponse(imageInfo as unknown as import('../types').JsonValue);
}
if (!ctx.getImageInfo) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const info = await ctx.getImageInfo(file);
if (info) return okResponse(info);
return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache');
});
h.registerAction('get_record', async (params) => {
const file = asString(params.file);
const file = asString(params.file) || asString(params.file_id);
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
const recordInfo = findMediaInStore('record', file, ctx);
if (recordInfo) {
return okResponse(recordInfo as unknown as import('../types').JsonValue);
}
if (!ctx.getRecordInfo) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
const info = await ctx.getRecordInfo(file);
if (info) return okResponse(info);
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
});
@@ -463,7 +478,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const context = params.context as import('../types').JsonObject | undefined;
const operation = params.operation as Record<string, unknown> | undefined;
if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required');
const { executeQuickOperation } = await import('../http-post-transport');
const { executeQuickOperation } = await import('../network/quick-operation');
await executeQuickOperation(context, operation, h);
return okResponse();
});
@@ -607,12 +622,26 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
// todo 我的建议是引入数据库api 纯协议我不知道这种api怎么实现,ntQQ在实现这个方法的时候只进行了数据库查询,完全没碰网络
h.registerAction('get_recent_contact', async () => {
return okResponse([]);
});
h.registerAction('get_profile_like', async () => {
return okResponse({});
h.registerAction('get_profile_like', async (params) => {
const userId = asNumber(params.user_id);
const start = asNumber(params.start) || 0;
const count = asNumber(params.count) || 10;
if (!ctx.getProfileLike) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getProfileLike(userId, start, count);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_friends_with_category', async () => {
@@ -624,6 +653,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
// --- Additional NapCat-compatible stubs ---
///napcat 似乎也用不了??,暂时不管了
h.registerAction('get_online_clients', async () => {
return okResponse({ clients: [] });
});
@@ -640,16 +670,55 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('get_group_at_all_remain', async () => {
return okResponse({ can_at_all: false, remain_at_all_count_for_group: 0, remain_at_all_count_for_uin: 0 });
h.registerAction('get_group_at_all_remain', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id');
}
if (!ctx.getGroupAtAllRemain) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getGroupAtAllRemain(groupId);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_unidirectional_friend_list', async () => {
return okResponse([]);
if (!ctx.getUnidirectionalFriendList) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getUnidirectionalFriendList();
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('set_self_longnick', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('set_self_longnick', async (params) => {
const longNick = params.longNick || params.long_nick;
if (typeof longNick !== 'string') {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick');
}
if (!ctx.setSelfLongNick) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setSelfLongNick(longNick);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_collection_list', async () => {
@@ -660,16 +729,66 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
h.registerAction('set_qq_avatar', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('set_qq_avatar', async (params) => {
const file = asString(params.file);
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
if (!ctx.setAvatar) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setAvatar(file);
return okResponse();
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('set_input_status', async () => {
return okResponse();
h.registerAction('set_input_status', async (params) => {
const userId = asNumber(params.user_id);
const eventType = asNumber(params.event_type);
if (!userId) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid user_id');
}
// event_type 有可能是 0 (取消输入状态),所以这里严格判断 undefined 或 isNaN
if (eventType === undefined || isNaN(eventType)) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid event_type');
}
if (!ctx.setInputStatus) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.setInputStatus(userId, eventType);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('translate_en2zh', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('translate_en2zh', async (params) => {
const rawWords = params.words;
if (!Array.isArray(rawWords)) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array');
}
const words = rawWords.map(w => String(w));
if (!ctx.translateEn2Zh) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const translated = await ctx.translateEn2Zh(words);
return okResponse({ words: translated });
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('get_clientkey', async () => {
@@ -683,21 +802,81 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse(clientKeyInfo);
});
h.registerAction('get_mini_app_ark', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('get_mini_app_ark', async (params) => {
const type = params.type || 'bili';
const title = params.title || '';
const desc = params.desc || '';
const picUrl = params.picUrl || params.pic_url || '';
const jumpUrl = params.jumpUrl || params.jump_url || '';
if (!ctx.getMiniAppArk) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.getMiniAppArk(
String(type),
String(title),
String(desc),
String(picUrl),
String(jumpUrl)
);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('click_inline_keyboard_button', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
h.registerAction('click_inline_keyboard_button', async (params) => {
const groupId = asNumber(params.group_id);
const botAppid = asNumber(params.bot_appid);
const buttonId = params.button_id;
const callbackData = params.callback_data || '';
const msgSeq = asNumber(params.msg_seq);
if (!groupId || !botAppid || !buttonId || !msgSeq) {
return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters');
}
if (!ctx.clickInlineKeyboardButton) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
const data = await ctx.clickInlineKeyboardButton(
groupId,
botAppid,
String(buttonId),
String(callbackData),
msgSeq
);
return okResponse(data);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
});
h.registerAction('set_group_sign', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
const handleGroupSign = async (params: any) => {
const groupId = asNumber(params.group_id);
h.registerAction('send_group_sign', async () => {
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
});
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id');
}
if (!ctx.sendGroupSign) {
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
}
try {
await ctx.sendGroupSign(groupId);
return okResponse({});
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, String(e));
}
};
h.registerAction('set_group_sign', handleGroupSign);
h.registerAction('send_group_sign', handleGroupSign);
h.registerAction('get_group_info_ex', async (params) => {
const groupId = asNumber(params.group_id);
@@ -736,23 +915,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
});
}
/**
* Search through cached message segments to find a media element (image/record)
* that matches the given file identifier.
*/
function findMediaInStore(
mediaType: 'image' | 'record',
file: string,
ctx: ApiActionContext,
): Record<string, unknown> | null {
// The file param can match a file id, a URL, or a filename stored in segments.
// We don't have a reverse index, so this is best-effort from stored events.
// Most callers will pass the `file` field from a received message segment.
// Just return the info if we can look it up from any recent cached message.
// This is a known limitation — full implementation would require a media cache.
return null;
}
/**
* Parse download_file headers parameter into a Record.
*/

View File

@@ -55,6 +55,7 @@ export interface ApiActionContext {
setGroupName?: (groupId: number, name: string) => Promise<void>;
setGroupLeave?: (groupId: number) => Promise<void>;
setGroupSpecialTitle?: (groupId: number, userId: number, title: string) => Promise<void>;
getGroupAtAllRemain?: (groupId: number) => Promise<any>;
// Group file
uploadGroupFile?: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
uploadPrivateFile?: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
@@ -78,6 +79,13 @@ export interface ApiActionContext {
forceFetchClientKey? : () => Promise<{clientKey: string, keyIndex: string, expireTime: string}>;
setOnlineStatus?: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile?: (nickname?: string, personalNote?: string) => Promise<void>;
getUnidirectionalFriendList?: () => Promise<any>;
setSelfLongNick?: (longNick: string) => Promise<void>;
setInputStatus?: (userId: number, eventType: number) => Promise<void>;
translateEn2Zh?: (words: string[]) => Promise<string[]>;
getMiniAppArk?: (type: string, title: string, desc: string, picUrl: string, jumpUrl: string) => Promise<any>;
clickInlineKeyboardButton?: (groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number) => Promise<any>;
sendGroupSign?: (groupId: number) => Promise<void>;
// New context methods
setGroupReaction?: (groupId: number, sequence: number, code: string, isSet: boolean) => Promise<void>;
handleDeleteFriend?: (userId: number, block?: boolean) => Promise<void>;
@@ -96,15 +104,22 @@ export interface ApiActionContext {
setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
markGroupMsgAsRead?: (groupId: number, sequence: number) => Promise<void>;
markPrivateMsgAsRead?: (userId: number, sequence: number) => Promise<void>;
getProfileLike?: (userId?: number, start?: number, limit?: number) => Promise<any>;
// Web
getGroupHonorInfo?: (groupId: number, type: WebHonorType | string) => Promise<any>;
getGroupEssence?: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
getGroupEssenceAll?: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
sendGroupNotice?: (groupId: number, content: string, options?: any) => Promise<any>;
getGroupNotice?: (groupId: number) => Promise<any[]>;
deleteGroupNotice?: (groupId: number, fid: string) => Promise<boolean>;
getCookiesStr?: (domain: string) => Promise<string>;
getCsrfToken?: () => Promise<number>;
getCredentials?: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
// Media lookup (populated from previously dispatched message segments)
getImageInfo?: (file: string) => Promise<JsonObject | null>;
getRecordInfo?: (file: string) => Promise<JsonObject | null>;
// Avatar
setAvatar?: (source: string) => Promise<void>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;

View File

@@ -5,11 +5,24 @@ import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from './message-id';
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
/**
* Side-channel callback invoked every time an image/record segment is
* produced, so that callers can keep a lookup index (e.g. for `get_image` /
* `get_record`) without having to re-scan the persisted message store.
*/
export type MediaSegmentSink = (
mediaType: 'image' | 'record',
element: MessageElement,
data: JsonObject,
isGroup: boolean,
sessionId: number,
) => void;
export class EventConverter {
private imageUrlResolver_: ImageUrlResolver | null = null;
private mediaUrlResolver_: MediaUrlResolver | null = null;
private messageIdResolver_: MessageIdResolver | null = null;
private mediaSegmentSink_: MediaSegmentSink | null = null;
setImageUrlResolver(resolver: ImageUrlResolver): void {
this.imageUrlResolver_ = resolver;
@@ -23,6 +36,10 @@ export class EventConverter {
this.messageIdResolver_ = resolver;
}
setMediaSegmentSink(sink: MediaSegmentSink): void {
this.mediaSegmentSink_ = sink;
}
async convert(instanceUin: string, event: QQEventVariant): Promise<JsonObject | null> {
const selfId = parseSelfId(instanceUin);
@@ -32,7 +49,7 @@ export class EventConverter {
const isSelf = event.senderUin === selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_, this.mediaSegmentSink_);
return {
time: event.time,
self_id: selfId,
@@ -59,7 +76,7 @@ export class EventConverter {
const isSelf = event.senderUin === selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_, this.mediaSegmentSink_);
return {
time: event.time,
self_id: selfId,
@@ -90,7 +107,7 @@ export class EventConverter {
const isSelf = event.senderUin === selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_, this.mediaSegmentSink_);
return {
time: event.time,
self_id: selfId,
@@ -320,10 +337,11 @@ async function elementsToJson(
resolver?: ImageUrlResolver | null,
mediaResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSink?: MediaSegmentSink | null,
): Promise<JsonArray> {
const result: JsonArray = [];
for (const element of elements) {
result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver));
result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver, mediaSink));
}
return result;
}
@@ -335,8 +353,9 @@ export async function elementsToOneBotSegments(
resolver?: ImageUrlResolver | null,
mediaResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSink?: MediaSegmentSink | null,
): Promise<JsonArray> {
return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver);
return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver, mediaSink);
}
async function elementToSegment(
@@ -346,6 +365,7 @@ async function elementToSegment(
resolver?: ImageUrlResolver | null,
mediaResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSink?: MediaSegmentSink | null,
): Promise<JsonObject> {
if (element.type === 'text') {
return { type: 'text', data: { text: element.text ?? '' } };
@@ -357,13 +377,12 @@ async function elementToSegment(
if (element.type === 'image') {
const url = resolver ? resolver(element, isGroup) : (element.imageUrl ?? '');
return {
type: 'image',
data: {
url,
file: element.fileId ?? '',
},
const data: JsonObject = {
url,
file: element.fileId ?? '',
};
if (mediaSink) mediaSink('image', element, data, isGroup, sessionId);
return { type: 'image', data };
}
if (element.type === 'at') {
@@ -380,13 +399,12 @@ async function elementToSegment(
if (element.type === 'record') {
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
return {
type: 'record',
data: {
file: element.fileName ?? element.fileId ?? '',
url,
},
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (mediaSink) mediaSink('record', element, data, isGroup, sessionId);
return { type: 'record', data };
}
if (element.type === 'video') {

View File

@@ -0,0 +1,113 @@
// Per-kind bridge → OneBot event handlers.
//
// Replaces the legacy single-firehose `OneBotInstance.onBridgeEvent` switch.
// Every bridge event kind gets a small async handler bound to a shared
// `OneBotInstanceContext`; subscribers register on `ctx.bridge.events` so
// multiple unrelated downstream concerns (meta caching, OB11 conversion,
// dispatch) compose cleanly without one giant switch statement.
import type { OneBotInstanceContext } from './instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { QQEventVariant } from '../bridge/events';
/**
* Subscribe every `OneBotInstanceContext`-aware handler onto the bridge
* event bus. Returns a disposer that removes every subscription registered
* here in one shot — useful for tests and for tearing down a session.
*/
export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
const disposers: Array<() => void> = [];
// Every kind that maps onto an OB11 message event also seeds the
// message-meta cache; we do that synchronously before async conversion so
// reply / quote lookups for that message id work even if the converter
// takes a beat to finish (e.g. while resolving image URLs).
disposers.push(
ctx.bridge.events.on('group_message', async (event) => {
cacheGroupMessageMeta(ctx, event);
await convertAndDispatch(ctx, event);
}),
);
disposers.push(
ctx.bridge.events.on('friend_message', async (event) => {
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, event.msgId);
await convertAndDispatch(ctx, event);
}),
);
disposers.push(
ctx.bridge.events.on('temp_message', async (event) => {
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
await convertAndDispatch(ctx, event);
}),
);
// Notice / request / non-message events: no meta caching needed, just
// convert and dispatch.
for (const kind of NOTICE_KINDS) {
disposers.push(
ctx.bridge.events.on(kind, async (event) => {
await convertAndDispatch(ctx, event);
}),
);
}
return () => {
for (const dispose of disposers) {
try { dispose(); } catch { /* ignore */ }
}
};
}
const NOTICE_KINDS = [
'group_member_join',
'group_member_leave',
'group_mute',
'group_admin',
'friend_recall',
'group_recall',
'friend_request',
'group_invite',
'friend_poke',
'group_poke',
'group_essence',
'group_file_upload',
'friend_add',
] as const satisfies readonly QQEventVariant['kind'][];
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
const converted = await ctx.eventConverter.convert(ctx.uin, event);
if (!converted) return;
ctx.dispatchEvent(converted);
}
function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEventVariant, { kind: 'group_message' }>): void {
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
ctx.cacheMessageMeta(messageId, {
isGroup: true,
targetId: event.groupId,
sequence: event.msgSeq,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: event.msgId,
timestamp: event.time,
});
}
function cachePrivateMessageMeta(
ctx: OneBotInstanceContext,
senderUin: number,
msgSeq: number,
timestamp: number,
random: number,
): void {
const messageId = hashMessageIdInt32(msgSeq, senderUin, PRIVATE_MESSAGE_EVENT);
ctx.cacheMessageMeta(messageId, {
isGroup: false,
targetId: senderUin,
sequence: msgSeq,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random,
timestamp,
});
}

View File

@@ -1,230 +0,0 @@
import type { HttpClientNetwork, JsonObject, OneBotConfig } from './types';
import { createLogger } from '../utils/logger';
import {
buildDispatchPayload,
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from './event-filter';
export interface HttpPostTransportContext {
uin: string;
api: import('./api-handler').ApiHandler;
}
const log = createLogger('OneBot.POST');
const DEFAULT_TIMEOUT_MS = 5000;
interface ResolvedClient {
network: HttpClientNetwork;
options: EventReportOptions;
}
export class HttpPostTransport {
private readonly context: HttpPostTransportContext;
private clients = new Map<string, ResolvedClient>();
private stopped = false;
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
this.clients = resolveClients(config);
this.context = context;
}
start(): void {
this.stopped = false;
if (this.clients.size > 0) {
log.info('configured %d HTTP POST adapter(s): %s', this.clients.size, [...this.clients.keys()].join(', '));
}
}
reloadConfig(config: OneBotConfig): void {
this.clients = resolveClients(config);
log.info('reloaded %d HTTP POST adapter(s)', this.clients.size);
}
stop(): void {
this.stopped = true;
}
/**
* Forward one canonical event to every active HTTP push client.
*
* The instance pre-builds the {@link DispatchPayload} so this method only
* picks the right pre-serialized variant per client (zero extra
* `JSON.stringify` calls). The raw `event` is still kept around because the
* quick-operation handler reads structured fields from it.
*/
publishEvent(event: JsonObject, payload?: DispatchPayload): void {
if (this.stopped || this.clients.size === 0) return;
const dispatch = payload ?? buildDispatchPayload(event);
for (const client of this.clients.values()) {
const json = pickDispatchJson(dispatch, client.options);
if (json === null) continue;
void this.postEvent(client.network, json, event);
}
}
private async postEvent(network: HttpClientNetwork, payload: string, event: JsonObject): Promise<void> {
if (this.stopped) return;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'User-Agent': 'OneBot',
'X-Self-ID': this.context.uin,
};
if (network.accessToken) {
headers['X-Signature'] = await computeHmacSha1(network.accessToken, payload);
}
const timeoutMs = network.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const response = await fetch(network.url, {
method: 'POST',
headers,
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
// OneBot v11: if the response has a JSON body, it's a quick operation
if (response.ok) {
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/json')) {
const body = await response.text();
if (body.trim()) {
await this.handleQuickOperation(event, body);
}
}
} else {
log.warn('[%s] POST %s returned %d', network.name, network.url, response.status);
}
} catch (error) {
if (!this.stopped) {
log.warn('[%s] POST %s failed: %s', network.name, network.url, error instanceof Error ? error.message : String(error));
}
}
}
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
try {
const operation = JSON.parse(responseBody) as Record<string, unknown>;
if (!operation || typeof operation !== 'object') return;
await executeQuickOperation(event, operation, this.context.api);
} catch (error) {
log.warn('quick operation failed: %s', error instanceof Error ? error.message : String(error));
}
}
}
function resolveClients(config: OneBotConfig): Map<string, ResolvedClient> {
const out = new Map<string, ResolvedClient>();
for (const network of config.networks.httpClients) {
if (network.enabled === false) continue;
if (!network.url) continue;
out.set(network.name, {
network,
options: resolveReportOptions(network),
});
}
return out;
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
}
/**
* Execute a quick operation based on the event type and the response body.
* This implements the .handle_quick_operation hidden API behavior.
* See: https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md
*/
export async function executeQuickOperation(
event: JsonObject,
operation: Record<string, unknown>,
api: import('./api-handler').ApiHandler,
): Promise<void> {
const postType = event.post_type as string;
if (postType === 'message') {
// Quick reply
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
const messageType = event.message_type as string;
const autoEscape = !!operation.auto_escape;
if (messageType === 'group') {
const params: JsonObject = {
group_id: event.group_id as number,
message: operation.reply as import('./types').JsonValue,
auto_escape: autoEscape,
};
// at_sender defaults to true for group messages
if (operation.at_sender !== false && event.user_id) {
// Prepend an @ segment
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
if (typeof operation.reply === 'string') {
params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as import('./types').JsonValue;
params.auto_escape = false;
} else if (Array.isArray(operation.reply)) {
params.message = [atSegment, ...(operation.reply as unknown[])] as import('./types').JsonValue;
}
}
await api.handle('send_group_msg', params);
} else if (messageType === 'private') {
await api.handle('send_private_msg', {
user_id: event.user_id as number,
message: operation.reply as import('./types').JsonValue,
auto_escape: autoEscape,
});
}
}
// Quick delete
if (operation.delete) {
await api.handle('delete_msg', { message_id: event.message_id as number });
}
// Quick ban (group only)
if (operation.ban && event.message_type === 'group') {
const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
await api.handle('set_group_ban', {
group_id: event.group_id as number,
user_id: event.user_id as number,
duration: duration as import('./types').JsonValue,
});
}
// Quick kick (group only)
if (operation.kick && event.message_type === 'group') {
await api.handle('set_group_kick', {
group_id: event.group_id as number,
user_id: event.user_id as number,
reject_add_request: !!operation.reject_add_request as unknown as import('./types').JsonValue,
});
}
}
if (postType === 'request') {
if (operation.approve !== undefined) {
const requestType = event.request_type as string;
if (requestType === 'friend') {
await api.handle('set_friend_add_request', {
flag: event.flag as string,
approve: operation.approve as import('./types').JsonValue,
remark: (operation.remark ?? '') as import('./types').JsonValue,
});
} else if (requestType === 'group') {
await api.handle('set_group_add_request', {
flag: event.flag as string,
sub_type: event.sub_type as string,
approve: operation.approve as import('./types').JsonValue,
reason: (operation.reason ?? '') as import('./types').JsonValue,
});
}
}
}
}

View File

@@ -1,232 +0,0 @@
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from 'http';
import type { ApiHandler } from './api-handler';
import type { HttpServerNetwork, OneBotConfig } from './types';
import { createLogger } from '../utils/logger';
export interface HttpTransportContext {
api: ApiHandler;
}
const log = createLogger('OneBot.HTTP');
interface RunningServer {
server: Server;
signature: string;
network: HttpServerNetwork;
}
export class HttpTransport {
private readonly context: HttpTransportContext;
private readonly servers = new Map<string, RunningServer>();
private networks: HttpServerNetwork[] = [];
constructor(config: OneBotConfig, context: HttpTransportContext) {
this.networks = activeNetworks(config);
this.context = context;
}
start(): void {
for (const network of this.networks) this.startEndpoint(network);
}
reloadConfig(config: OneBotConfig): void {
const nextNetworks = activeNetworks(config);
const nextByName = new Map(nextNetworks.map((n) => [n.name, n] as const));
// Stop adapters that no longer exist or whose binding/auth changed.
for (const [name, running] of [...this.servers]) {
const next = nextByName.get(name);
if (!next || httpServerSignature(next) !== running.signature) {
running.server.close();
this.servers.delete(name);
log.info('stopped [%s]', name);
}
}
// (Re)start adapters that aren't running yet.
for (const network of nextNetworks) {
if (!this.servers.has(network.name)) {
this.startEndpoint(network);
}
}
this.networks = nextNetworks;
}
stop(): void {
for (const { server } of this.servers.values()) {
server.close();
}
this.servers.clear();
}
private startEndpoint(network: HttpServerNetwork): void {
const expectedPath = normalizePath(network.path ?? '/');
const endpointToken = network.accessToken ?? '';
const server = createServer((req, res) => {
void this.handleRequest(expectedPath, endpointToken, req, res);
});
server.on('listening', () => {
log.success('[%s] listening %s:%d%s', network.name, network.host ?? '0.0.0.0', network.port, expectedPath);
});
server.on('error', (error) => {
log.warn('[%s] server error: %s', network.name, error instanceof Error ? error.message : String(error));
});
server.listen(network.port, network.host ?? '0.0.0.0');
this.servers.set(network.name, { server, signature: httpServerSignature(network), network });
}
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
const incomingPath = parsedUrl.pathname;
// Determine the expected prefix (e.g., "/" or "/api/")
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
let action = '';
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
action = ''; // No action in URL (legacy body mode)
} else if (incomingPath.startsWith(ep)) {
action = incomingPath.substring(ep.length); // Extract action from URL
} else {
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
return;
}
if (!isAuthorized(req, accessToken)) {
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
return;
}
if (req.method === 'GET' && !action) {
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
return;
}
try {
let params: Record<string, unknown> = {};
let echo: unknown;
if (req.method === 'GET') {
parsedUrl.searchParams.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
} else if (req.method === 'POST') {
const bodyContent = await readRequestBody(req);
if (bodyContent.trim()) {
try {
const parsedBody = JSON.parse(bodyContent);
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
// Legacy format: { action: "...", params: {...} } vs standard raw params
if (parsedBody.action && !action) {
action = String(parsedBody.action);
}
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
params = parsedBody.params as Record<string, unknown>;
} else {
params = parsedBody as Record<string, unknown>;
}
echo = parsedBody.echo;
}
} catch {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
return;
}
}
} else {
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
return;
}
if (!action) {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
return;
}
// Handle the API call
const response = await this.context.api.handle(action, params as import('./types').JsonObject);
if (echo !== undefined) {
response.echo = echo as import('./types').JsonValue;
}
writeJson(res, 200, response);
} catch (error) {
const wording = error instanceof Error ? error.message : 'internal error';
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
}
}
}
function normalizePath(pathValue: string): string {
const path = pathValue.trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
}
function httpServerSignature(network: HttpServerNetwork): string {
return `${network.host ?? '0.0.0.0'}:${network.port}${normalizePath(network.path ?? '/')}#${network.accessToken ?? ''}`;
}
function activeNetworks(config: OneBotConfig): HttpServerNetwork[] {
return config.networks.httpServers.filter((n) => n.enabled !== false);
}
function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
// 1. Header auth
const rawAuth = request.headers.authorization;
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
if (auth === `Bearer ${token}`) return true;
// 2. Query string auth
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
if (url.searchParams.get('access_token') === token) {
return true;
}
} catch {}
return false;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
req.on('data', (chunk: Buffer) => {
total += chunk.length;
if (total > maxBytes) {
reject(new Error('request body too large'));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => {
resolve(Buffer.concat(chunks).toString('utf8'));
});
req.on('error', reject);
});
}
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
}

View File

@@ -2,27 +2,56 @@ import type { Bridge } from '../bridge/bridge';
import type { ForwardNodePayload, MessageElement } from '../bridge/events';
import type { QQInfo } from '../bridge/qq-info';
import type { ApiActionContext, MessageSendResult } from './api-handler';
import type { EventConverter } from './event-converter';
import { elementsToOneBotSegments } from './event-converter';
import { MessageStore } from './message-store';
import { parseMessage } from './message-parser';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { JsonObject, JsonValue, MessageMeta } from './types';
import type { MediaStore } from './media-store';
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig } from './types';
import { createLogger } from '../utils/logger';
import {WebHonorType} from "@/bridge/web/group-honor";
const log = createLogger('OneBot');
export interface InstanceRef {
/**
* Single shared context bag that flows through every OneBot instance-internal
* subsystem: API builder and the per-kind event pipeline.
*
* Only fields that are actually read through this bag live here — the api
* handler and network manager are owned by `OneBotInstance` directly because
* nothing reads them via ctx, and including them here would force a
* chicken-and-egg `late-bound` field dance during construction.
*
* `dispatchEvent` is the indirection used by the event pipeline to hand a
* converted OneBot event back to the instance for caching + adapter fan-out;
* it lets the pipeline stay decoupled from the network manager.
*/
export interface OneBotInstanceContext {
/** Self UIN as string (matches what's on disk and on the wire). */
uin: string;
/** Self UIN parsed once, used in event payloads. */
selfId: number;
qqInfo: QQInfo;
bridge: Bridge;
messageStore: MessageStore;
mediaStore: MediaStore;
eventConverter: EventConverter;
config: OneBotConfig;
musicSignUrl?: string;
/** Persist meta about a message id; safe to call any number of times. */
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
/** Hand a fully-converted OneBot event to the network manager + caches. */
dispatchEvent(event: JsonObject): void;
}
export function buildApiContext(ref: InstanceRef): ApiActionContext {
const { bridge, qqInfo, messageStore } = ref;
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const { bridge, qqInfo, messageStore, mediaStore } = ref;
return {
getLoginInfo: () => getLoginInfo(ref),
@@ -30,7 +59,7 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
getMessage: (messageId) => messageStore.findEvent(messageId),
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
canSendImage: () => true,
canSendRecord: () => false,
canSendRecord: () => true,
sendPrivateMessage: (userId, message, autoEscape) => handleSendPrivate(ref, userId, message, autoEscape),
sendGroupMessage: (groupId, message, autoEscape) => handleSendGroup(ref, groupId, message, autoEscape),
deleteMessage: (messageId, meta) => handleDeleteMessage(bridge, meta),
@@ -50,6 +79,7 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
setGroupName: (groupId, name) => bridge.setGroupName(groupId, name),
setGroupLeave: (groupId) => bridge.leaveGroup(groupId),
setGroupSpecialTitle: (groupId, userId, title) => bridge.setGroupSpecialTitle(groupId, userId, title),
getGroupAtAllRemain: (groupId) => bridge.getGroupAtAllRemain(groupId),
// Group file
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.uploadGroupFile(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
@@ -76,6 +106,14 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
sendGroupPoke: (groupId, userId) => bridge.sendPoke(true, groupId, userId),
setEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => handleSetEssence(bridge, messageStore, messageId, false),
getProfileLike: (userId?: number, start: number = 0, limit: number = 10) => bridge.getProfileLike(userId, start, limit),
getUnidirectionalFriendList: () => bridge.getUnidirectionalFriendList(),
setSelfLongNick: (longNick) => bridge.setSelfLongNick(longNick),
setInputStatus: (userId, eventType) => bridge.setInputStatus(userId, eventType),
translateEn2Zh: (words) => bridge.translateEn2Zh(words),
getMiniAppArk: (type, title, desc, picUrl, jumpUrl) => bridge.getMiniAppArk(type, title, desc, picUrl, jumpUrl),
clickInlineKeyboardButton: (groupId, botAppid, buttonId, callbackData, msgSeq) => bridge.clickInlineKeyboardButton(groupId, botAppid, buttonId, callbackData, msgSeq),
sendGroupSign: (groupId) => bridge.sendGroupSign(groupId),
// New extended
setGroupReaction: (groupId, sequence, code, isSet) => bridge.setGroupReaction(groupId, sequence, code, isSet),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
@@ -132,15 +170,70 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
getGroupEssenceAll: (groupId: number) => bridge.getGroupEssenceAll(groupId),
sendGroupNotice: (groupId: number, content: string, options?: any) => bridge.sendGroupNotice(groupId, content, options),
getGroupNotice: (groupId: number) => bridge.getGroupNotice(groupId),
deleteGroupNotice: (groupId: number, fid: string) => bridge.deleteGroupNotice(groupId, fid),
getCookiesStr: (domain: string) => bridge.getCookiesStr(domain),
getCsrfToken: () => bridge.getCsrfToken(),
getCredentials: (domain: string) => bridge.getCredentials(domain),
// Media lookup
getImageInfo: (file) => handleGetImageInfo(mediaStore, file),
getRecordInfo: (file) => handleGetRecordInfo(bridge, mediaStore, file),
// Avatar
setAvatar: (source: string) => bridge.setAvatar(source),
};
}
// --- Media lookup ---
async function handleGetImageInfo(
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaStore.findImage(file);
if (!cached) return null;
const url = cached.url || cached.imageUrl || '';
return {
file: url || cached.file,
url,
file_size: String(cached.fileSize ?? 0),
file_name: cached.fileName || cached.file,
};
}
async function handleGetRecordInfo(
bridge: Bridge,
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaStore.findRecord(file);
if (!cached) return null;
// Re-resolve via OIDB if the cached URL is missing or empty.
// Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid.
let url = cached.url;
if (!url && cached.mediaNode) {
try {
url = cached.isGroup
? await bridge.fetchGroupPttUrlByNode(cached.sessionId, cached.mediaNode)
: await bridge.fetchPrivatePttUrlByNode(cached.mediaNode);
if (url) {
mediaStore.updateRecordUrl(file, url);
}
} catch (err) {
log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err));
}
}
return {
file: url || cached.file,
url: url || '',
file_size: String(cached.fileSize ?? 0),
file_name: cached.fileName || cached.file,
};
}
// --- Login info ---
function getLoginInfo(ref: InstanceRef): { userId: number; nickname: string } {
function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0;
const nickname = ref.qqInfo.nickname || ref.uin;
return { userId, nickname };
@@ -496,7 +589,7 @@ function logSentMessage(isGroup: boolean, targetId: number, elements: MessageEle
// --- Send message ---
async function handleSendPrivate(
ref: InstanceRef,
ref: OneBotInstanceContext,
userId: number,
message: JsonValue,
autoEscape: boolean,
@@ -542,7 +635,7 @@ async function handleSendPrivate(
}
async function handleSendGroup(
ref: InstanceRef,
ref: OneBotInstanceContext,
groupId: number,
message: JsonValue,
autoEscape: boolean,
@@ -588,7 +681,7 @@ async function handleSendGroup(
}
async function handleSendGroupForward(
ref: InstanceRef,
ref: OneBotInstanceContext,
groupId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
@@ -611,7 +704,7 @@ async function handleSendGroupForward(
}
async function handleSendPrivateForward(
ref: InstanceRef,
ref: OneBotInstanceContext,
userId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
@@ -634,7 +727,7 @@ async function handleSendPrivateForward(
}
async function handleUploadForward(
ref: InstanceRef,
ref: OneBotInstanceContext,
messages: JsonValue,
): Promise<{ forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
@@ -643,7 +736,7 @@ async function handleUploadForward(
}
async function handleGetForward(
ref: InstanceRef,
ref: OneBotInstanceContext,
resId: string,
): Promise<JsonObject[]> {
const nodes = await ref.bridge.fetchForwardNodes(resId);
@@ -663,7 +756,7 @@ async function handleGetForward(
return results;
}
async function parseForwardNodes(ref: InstanceRef, messages: JsonValue): Promise<ForwardNodePayload[]> {
async function parseForwardNodes(ref: OneBotInstanceContext, messages: JsonValue): Promise<ForwardNodePayload[]> {
if (!Array.isArray(messages)) {
throw new Error('forward messages must be an array');
}

View File

@@ -1,18 +1,23 @@
import path from 'path';
import type { QQEventVariant } from '../bridge/events';
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import { ApiHandler } from './api-handler';
import { EventConverter } from './event-converter';
import { MessageStore } from './message-store';
import { MediaStore } from './media-store';
import { RKeyCache } from './instance-rkey';
import { buildApiContext } from './instance-context';
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
import { registerEventPipeline } from './event-pipeline';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import { HttpTransport } from './http-transport';
import { HttpPostTransport } from './http-post-transport';
import { WsTransport } from './ws-transport';
import { buildDispatchPayload } from './event-filter';
import type { JsonObject, MessageMeta, OneBotConfig, NetworkBase } from './types';
import {
OneBotNetworkManager,
WsServerAdapter,
WsClientAdapter,
HttpServerAdapter,
HttpPostAdapter,
type NetworkAdapterContext,
} from './network';
import { createLogger } from '../utils/logger';
const log = createLogger('Event');
@@ -25,10 +30,11 @@ export class OneBotInstance {
private readonly apiHandler: ApiHandler;
private readonly eventConverter: EventConverter;
private readonly messageStore: MessageStore;
private readonly httpTransport: HttpTransport;
private readonly httpPostTransport: HttpPostTransport;
private readonly wsTransport: WsTransport;
private readonly mediaStore: MediaStore;
private readonly networkManager: OneBotNetworkManager;
private readonly rkeyCache: RKeyCache;
private readonly ctx: OneBotInstanceContext;
private disposeEventPipeline: (() => void) | null = null;
private readonly pids = new Set<number>();
private online = true;
@@ -42,6 +48,7 @@ export class OneBotInstance {
this.eventConverter = new EventConverter();
this.rkeyCache = new RKeyCache();
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
this.eventConverter.setImageUrlResolver((element, isGroup) =>
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup));
this.eventConverter.setMediaUrlResolver(async (element, isGroup, sessionId) => {
@@ -70,69 +77,83 @@ export class OneBotInstance {
// Then apply RKey if needed
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
});
this.eventConverter.setMediaSegmentSink((mediaType, element, data, isGroup, sessionId) => {
const url = typeof data.url === 'string' ? data.url : '';
const file = typeof data.file === 'string' ? data.file : '';
if (mediaType === 'image') {
this.mediaStore.rememberImage({
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileId ?? '',
subType: element.subType ?? 0,
summary: element.summary ?? '',
imageUrl: element.imageUrl ?? '',
isGroup,
sessionId,
});
return;
}
this.mediaStore.rememberRecord({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
});
});
this.eventConverter.setMessageIdResolver((isGroup, sessionId, sequence, eventName) =>
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)));
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
const context = buildApiContext({
// Shared instance context. Only carries fields that are actually read
// through it — api handler and network manager stay as direct fields on
// the instance because nothing reads them via ctx.
const ctx: OneBotInstanceContext = {
uin: this.uin,
selfId: parseInt(this.uin, 10) || 0,
qqInfo: this.qqInfo,
bridge: this.bridge,
messageStore: this.messageStore,
mediaStore: this.mediaStore,
eventConverter: this.eventConverter,
config,
musicSignUrl: config.musicSignUrl,
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
});
this.apiHandler = new ApiHandler(context);
dispatchEvent: (event) => this.dispatchEvent(event),
};
this.ctx = ctx;
this.httpTransport = new HttpTransport(config, {
api: this.apiHandler,
});
this.apiHandler = new ApiHandler(buildApiContext(ctx));
this.networkManager = new OneBotNetworkManager();
this.installAdaptersFromConfig(config);
void this.networkManager.openAll();
this.httpPostTransport = new HttpPostTransport(config, {
uin: this.uin,
api: this.apiHandler,
});
this.wsTransport = new WsTransport(config, {
uin: this.uin,
api: this.apiHandler,
buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType),
buildHeartbeatEvent: () => this.makeHeartbeatEvent(),
});
this.httpTransport.start();
this.httpPostTransport.start();
this.wsTransport.start();
this.startHeartbeat();
this.rkeyCache.warmUp(this.bridge, this.uin);
// Per-kind subscription on the typed event bus. Each bridge event kind
// gets its own focused handler in `event-pipeline`; the firehose is gone.
this.disposeEventPipeline = registerEventPipeline(ctx);
}
reloadConfig(config: OneBotConfig): void {
this.httpTransport.reloadConfig(config);
this.httpPostTransport.reloadConfig(config);
this.wsTransport.reloadConfig(config);
void this.applyConfigDiff(config);
}
dispose(): void {
this.online = false;
this.stopHeartbeat();
this.httpTransport.stop();
this.httpPostTransport.stop();
this.wsTransport.stop();
this.disposeEventPipeline?.();
this.disposeEventPipeline = null;
void this.networkManager.closeAll();
this.messageStore.close();
}
onBridgeEvent(event: QQEventVariant): void {
this.cacheMessageMetaFromBridgeEvent(event);
void this.dispatchBridgeEventAsync(event);
}
private async dispatchBridgeEventAsync(event: QQEventVariant): Promise<void> {
const converted = await this.eventConverter.convert(this.uin, event);
if (!converted) return;
this.dispatchEvent(converted);
this.mediaStore.close();
}
addPid(pid: number): void {
@@ -158,11 +179,87 @@ export class OneBotInstance {
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.logReceivedMessage(event);
// Produce one canonical event, serialize the two format variants once,
// then let each adapter pick its slot at zero allocation cost.
const payload = buildDispatchPayload(event);
this.wsTransport.publishEvent(event, payload);
this.httpPostTransport.publishEvent(event, payload);
// NetworkManager builds the dispatch payload once and fans out to every
// active adapter in parallel via Promise.allSettled.
void this.networkManager.emitEvent(event);
}
private buildNetworkContext(): NetworkAdapterContext {
return {
uin: this.uin,
api: this.apiHandler,
buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType),
buildHeartbeatEvent: () => this.makeHeartbeatEvent(),
};
}
private installAdaptersFromConfig(config: OneBotConfig): void {
const ctx = this.buildNetworkContext();
for (const net of config.networks.httpServers) {
if (net.enabled === false) continue;
this.networkManager.register(new HttpServerAdapter(net.name, net, ctx));
}
for (const net of config.networks.httpClients) {
if (net.enabled === false || !net.url) continue;
this.networkManager.register(new HttpPostAdapter(net.name, net, ctx));
}
for (const net of config.networks.wsServers) {
if (net.enabled === false) continue;
this.networkManager.register(new WsServerAdapter(net.name, net, ctx));
}
for (const net of config.networks.wsClients) {
if (net.enabled === false || !net.url) continue;
this.networkManager.register(new WsClientAdapter(net.name, net, ctx));
}
}
private async applyConfigDiff(next: OneBotConfig): Promise<void> {
const ctx = this.buildNetworkContext();
const desired = new Map<string, NetworkBase>();
const factories = new Map<string, () => void>();
for (const net of next.networks.httpServers) {
desired.set(net.name, net);
factories.set(net.name, () => this.networkManager.register(new HttpServerAdapter(net.name, net, ctx)));
}
for (const net of next.networks.httpClients) {
desired.set(net.name, net);
factories.set(net.name, () => this.networkManager.register(new HttpPostAdapter(net.name, net, ctx)));
}
for (const net of next.networks.wsServers) {
desired.set(net.name, net);
factories.set(net.name, () => this.networkManager.register(new WsServerAdapter(net.name, net, ctx)));
}
for (const net of next.networks.wsClients) {
desired.set(net.name, net);
factories.set(net.name, () => this.networkManager.register(new WsClientAdapter(net.name, net, ctx)));
}
// Close adapters whose entry has been removed entirely.
for (const adapter of this.networkManager.list()) {
if (!desired.has(adapter.name)) {
await this.networkManager.closeOne(adapter.name);
}
}
// Reload existing adapters in place; spin up new ones the manager hasn't
// seen before.
for (const [name, net] of desired) {
const existing = this.networkManager.get(name);
if (existing) {
try {
await existing.reload(net as never);
} catch (err) {
log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
}
} else if (net.enabled !== false) {
const factory = factories.get(name);
if (factory) {
factory();
await this.networkManager.get(name)?.open();
}
}
}
}
private logReceivedMessage(event: JsonObject): void {
@@ -239,49 +336,6 @@ export class OneBotInstance {
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
}
private cacheMessageMetaFromBridgeEvent(event: QQEventVariant): void {
if (event.kind === 'group_message') {
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
this.cacheMessageMeta(messageId, {
isGroup: true,
targetId: event.groupId,
sequence: event.msgSeq,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: event.msgId,
timestamp: event.time,
});
return;
}
if (event.kind === 'friend_message') {
const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT);
this.cacheMessageMeta(messageId, {
isGroup: false,
targetId: event.senderUin,
sequence: event.msgSeq,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: event.msgId,
timestamp: event.time,
});
return;
}
if (event.kind === 'temp_message') {
const messageId = hashMessageIdInt32(event.msgSeq, event.senderUin, PRIVATE_MESSAGE_EVENT);
this.cacheMessageMeta(messageId, {
isGroup: false,
targetId: event.senderUin,
sequence: event.msgSeq,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: event.time,
});
}
}
private cacheMessageMeta(messageId: number, meta: MessageMeta): void {
if (!Number.isInteger(messageId) || messageId === 0) return;
this.messageStore.storeMeta(messageId, meta);

View File

@@ -1,4 +1,3 @@
import type { QQEventVariant } from '../bridge/events';
import type { Bridge } from '../bridge/bridge';
import type { QQInfo } from '../bridge/qq-info';
import type { BridgeManager } from '../bridge/manager';
@@ -21,9 +20,8 @@ export class OneBotManager {
this.onSessionClosed(uin);
});
bridgeManager.setEventCallback((uin, event) => {
this.onBridgeEvent(uin, event);
});
// Per-kind subscriptions to `bridge.events` happen inside
// `OneBotInstance` itself; no global firehose to wire here.
}
getInstance(uin: string): OneBotInstance | null {
@@ -80,12 +78,6 @@ export class OneBotManager {
log.info('session closed: UIN=%s', uin);
}
private onBridgeEvent(uin: string, event: QQEventVariant): void {
const instance = this.instances.get(uin);
if (!instance) return;
instance.onBridgeEvent(event);
}
}
async function warmUpBridgeState(uin: string, qqInfo: QQInfo, bridge: Bridge): Promise<void> {

View File

@@ -0,0 +1,267 @@
// Persistent media metadata store.
//
// The `get_image` / `get_record` actions need to map a `data.file` (or related
// identifier) we previously emitted in a message segment back to the URL,
// size, name, and any OIDB media-node info needed to re-resolve a stale URL.
//
// Earlier this lived in an in-memory `MediaCache`, which meant the lookup
// table was lost on every restart. This implementation persists everything
// alongside the message store so OneBot consumers can always resolve the
// media that produced any segment ever stored, even after the bot restarts.
//
// Schema overview (single SQLite file per UIN, e.g. `data/<uin>/media.db`):
// media_entries(type, primary_key, data JSON, last_seen) -- one row per logical media item
// media_keys(type, key, primary_key) -- secondary index for every alias
//
// `rememberImage` / `rememberRecord` upsert exactly one entry row plus one
// alias row per identifier (file / fileName / fileId / url). The alias rows
// always point to the canonical entry so URL refreshes propagate to every
// alias automatically.
import fs from 'fs';
import path from 'path';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import type { MessageElement } from '../bridge/events';
export interface CachedImage {
/** Primary `data.file` value as exposed in the OneBot segment. */
file: string;
/** Last known resolved URL (may be empty if resolution failed). */
url: string;
fileSize: number;
fileName: string;
subType: number;
summary: string;
/** Conversation the media originated from. */
isGroup: boolean;
sessionId: number;
/** Original imageUrl from the MessageElement, used for RKey re-appending. */
imageUrl: string;
}
export interface CachedRecord {
/** Primary `data.file` value as exposed in the OneBot segment. */
file: string;
/** Raw fileId from the MessageElement (typically the fileUuid). */
fileId: string;
/** Last known resolved URL (may be empty if resolution failed). */
url: string;
fileSize: number;
fileName: string;
duration: number;
fileHash: string;
/** OIDB media node used to re-fetch the URL via getPtt*UrlByNode. */
mediaNode?: MessageElement['mediaNode'];
/** Conversation the media originated from (group vs private path). */
isGroup: boolean;
sessionId: number;
}
const TYPE_IMAGE = 'image';
const TYPE_RECORD = 'record';
const DEFAULT_KEEP_ENTRIES = 4096;
export class MediaStore {
private readonly db: DatabaseSync;
private readonly maxEntriesPerType: number;
// Prepared statements (pay the parsing cost once at startup).
private readonly upsertEntry: StatementSync;
private readonly upsertKey: StatementSync;
private readonly findEntryByKey: StatementSync;
private readonly findEntryByPrimary: StatementSync;
private readonly evictByType: StatementSync;
private readonly purgeOrphanKeys: StatementSync;
private readonly countByType: StatementSync;
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
this.upsertEntry = this.db.prepare(
`INSERT INTO media_entries (type, primary_key, data, last_seen)
VALUES (?, ?, ?, ?)
ON CONFLICT(type, primary_key) DO UPDATE SET
data = excluded.data,
last_seen = excluded.last_seen`,
);
this.upsertKey = this.db.prepare(
`INSERT INTO media_keys (type, key, primary_key)
VALUES (?, ?, ?)
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key`,
);
this.findEntryByKey = this.db.prepare(
`SELECT e.data FROM media_entries e
JOIN media_keys k ON k.type = e.type AND k.primary_key = e.primary_key
WHERE k.type = ? AND k.key = ?
LIMIT 1`,
);
this.findEntryByPrimary = this.db.prepare(
`SELECT data FROM media_entries WHERE type = ? AND primary_key = ?`,
);
this.evictByType = this.db.prepare(
// `rowid DESC` makes the tiebreaker match insertion order (newest first)
// so reproducible inserts within the same `last_seen` second still get
// the most recent rows retained, regardless of how the lexicographic
// sort would have ordered the synthetic primary_key.
`DELETE FROM media_entries WHERE type = ? AND rowid IN (
SELECT rowid FROM media_entries
WHERE type = ?
ORDER BY last_seen DESC, rowid DESC
LIMIT -1 OFFSET ?
)`,
);
this.purgeOrphanKeys = this.db.prepare(
`DELETE FROM media_keys WHERE type = ? AND primary_key NOT IN (
SELECT primary_key FROM media_entries WHERE type = ?
)`,
);
this.countByType = this.db.prepare(
`SELECT COUNT(*) AS n FROM media_entries WHERE type = ?`,
);
}
close(): void {
this.db.close();
}
rememberImage(info: CachedImage): void {
const primaryKey = pickPrimary([info.file, info.fileName]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_IMAGE, primaryKey, info, [info.file, info.fileName, info.url]);
}
rememberRecord(info: CachedRecord): void {
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_RECORD, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
}
findImage(key: string): CachedImage | null {
return this.findByAnyKey<CachedImage>(TYPE_IMAGE, key);
}
findRecord(key: string): CachedRecord | null {
return this.findByAnyKey<CachedRecord>(TYPE_RECORD, key);
}
updateImageUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findImage(key);
if (!cached || cached.url === url) return;
this.rememberImage({ ...cached, url });
}
updateRecordUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findRecord(key);
if (!cached || cached.url === url) return;
this.rememberRecord({ ...cached, url });
}
/** Snapshot count of distinct entries per type; mostly used by tests. */
size(): { images: number; records: number } {
const img = this.countByType.get(TYPE_IMAGE) as { n: number } | undefined;
const rec = this.countByType.get(TYPE_RECORD) as { n: number } | undefined;
return { images: img?.n ?? 0, records: rec?.n ?? 0 };
}
// --- internals ---
private initSchema(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS media_entries (
type TEXT NOT NULL,
primary_key TEXT NOT NULL,
data TEXT NOT NULL,
last_seen INTEGER NOT NULL,
PRIMARY KEY (type, primary_key)
);
CREATE INDEX IF NOT EXISTS idx_media_entries_lastseen
ON media_entries(type, last_seen DESC);
CREATE TABLE IF NOT EXISTS media_keys (
type TEXT NOT NULL,
key TEXT NOT NULL,
primary_key TEXT NOT NULL,
PRIMARY KEY (type, key)
);
CREATE INDEX IF NOT EXISTS idx_media_keys_primary
ON media_keys(type, primary_key);
`);
}
private upsertWithAliases<T>(
type: string,
primaryKey: string,
info: T,
aliases: (string | undefined)[],
): void {
const data = JSON.stringify(info);
const lastSeen = Math.floor(Date.now() / 1000);
// Run the writes in a transaction so concurrent readers always see a
// consistent (entry, keys) pair.
this.db.exec('BEGIN');
try {
this.upsertEntry.run(type, primaryKey, data, lastSeen);
const seen = new Set<string>();
for (const raw of aliases) {
if (!raw) continue;
if (seen.has(raw)) continue;
seen.add(raw);
this.upsertKey.run(type, raw, primaryKey);
}
this.db.exec('COMMIT');
} catch (err) {
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
throw err;
}
// Eager eviction. The DELETE is a no-op when row count <= cap so
// there is no measurable cost while we are below the limit.
this.evictOldEntries(type);
}
private findByAnyKey<T>(type: string, key: string): T | null {
if (!key) return null;
const row = this.findEntryByKey.get(type, key) as { data: string } | undefined;
if (row?.data) return safeParse<T>(row.data);
// Fall back to looking up by primary_key directly so callers that pass
// the canonical identifier still hit (e.g. when the alias index is yet
// to be built for that key in this session).
const fallback = this.findEntryByPrimary.get(type, key) as { data: string } | undefined;
return fallback?.data ? safeParse<T>(fallback.data) : null;
}
private evictOldEntries(type: string): void {
try {
this.evictByType.run(type, type, this.maxEntriesPerType);
this.purgeOrphanKeys.run(type, type);
} catch {
// Best-effort eviction; don't propagate.
}
}
}
function pickPrimary(candidates: (string | undefined)[]): string {
for (const c of candidates) {
if (c && c.length > 0) return c;
}
return '';
}
function safeParse<T>(json: string): T | null {
try {
return JSON.parse(json) as T;
} catch {
return null;
}
}

View File

@@ -150,15 +150,20 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
};
}
case 'record': {
const source = String(data.file ?? data.url ?? data.path ?? '');
if (!source) return null;
return {
type: 'record',
url: String(data.file ?? data.url ?? ''),
url: source,
};
}
case 'video': {
const source = String(data.file ?? data.url ?? data.path ?? '');
if (!source) return null;
return {
type: 'video',
url: String(data.file ?? data.url ?? ''),
url: source,
thumbUrl: data.thumb ? String(data.thumb) : undefined,
};
}
case 'json': {

View File

@@ -0,0 +1,65 @@
// Base abstractions for OneBot network adapters.
//
// Modeled on NapCat's `IOB11NetworkAdapter` so each entry under
// `config.networks.{httpServers,httpClients,wsServers,wsClients}` becomes
// exactly one adapter instance, identified by `name`. The previous design
// rolled multiple servers/clients into a single transport class; the
// per-entry split makes hot-reload, lifecycle, and event isolation much
// simpler to reason about.
import type { ApiHandler } from '../api-handler';
import type { JsonObject, NetworkBase } from '../types';
import type { DispatchPayload } from '../event-filter';
export interface NetworkAdapterContext {
/** Self UIN as string — written into outbound headers. */
uin: string;
/** Shared API dispatcher used by request/response style adapters. */
api: ApiHandler;
/** Build a lifecycle event payload (connect/enable/disable). */
buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject;
/** Build a heartbeat event payload. */
buildHeartbeatEvent(): JsonObject;
}
export enum NetworkReloadType {
/** Configuration unchanged or only soft fields updated. */
Normal = 0,
/** Underlying socket/listener restarted in place. */
Reopened = 1,
/** Was running, now closed. */
Closed = 2,
/** Was idle, now opened. */
Opened = 3,
}
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
readonly name: string;
protected config: C;
protected readonly ctx: NetworkAdapterContext;
protected isEnabled = false;
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
this.name = name;
// Defensive copy so reload diffs never mutate the caller's object.
this.config = structuredClone(config);
this.ctx = ctx;
}
/** Whether the adapter is currently accepting/relaying events. */
get isActive(): boolean { return this.isEnabled; }
/** Snapshot of the active config (read-only). */
get currentConfig(): Readonly<C> { return this.config; }
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
/**
* Receive one fully-shaped OneBot event for forwarding. Adapters that
* don't push events (e.g. HTTP request-response servers) override with a
* no-op.
*/
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
}

View File

@@ -0,0 +1,136 @@
// Outbound HTTP webhook adapter — one instance per `httpClients[]` entry.
//
// Forwards every event to the configured URL via HTTP POST and interprets
// any JSON response body as a OneBot v11 quick-operation.
import type { HttpClientNetwork, JsonObject } from '../types';
import {
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import { createLogger } from '../../utils/logger';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
const log = createLogger('OneBot.POST');
const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
this.signature_ = bindingSignature(config);
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.config.enabled === false) return;
if (!this.config.url) return;
this.isEnabled = true;
}
close(): void {
this.isEnabled = false;
}
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
const newSig = bindingSignature(next);
const sigChanged = newSig !== this.signature_;
this.signature_ = newSig;
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled) return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
void this.postEvent(json, event);
}
private async postEvent(payload: string, event: JsonObject): Promise<void> {
if (!this.isEnabled) return;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'User-Agent': 'OneBot',
'X-Self-ID': this.ctx.uin,
};
if (this.config.accessToken) {
headers['X-Signature'] = await computeHmacSha1(this.config.accessToken, payload);
}
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const response = await fetch(this.config.url, {
method: 'POST',
headers,
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
if (response.ok) {
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/json')) {
const body = await response.text();
if (body.trim()) {
await this.handleQuickOperation(event, body);
}
}
} else {
log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
}
} catch (error) {
if (this.isEnabled) {
log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
}
}
}
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
try {
const operation = JSON.parse(responseBody) as Record<string, unknown>;
if (!operation || typeof operation !== 'object') return;
await executeQuickOperation(event, operation, this.ctx.api);
} catch (error) {
log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
}
}
}
function bindingSignature(net: HttpClientNetwork): string {
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
}

View File

@@ -0,0 +1,203 @@
// Inbound HTTP API server — one instance per `httpServers[]` entry.
//
// Pure request/response: incoming POST/GET maps to `ApiHandler.handle`,
// the response body is JSON-serialized back. `onEvent` is a deliberate
// no-op since this transport never pushes events.
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from 'http';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import type { DispatchPayload } from '../event-filter';
import { createLogger } from '../../utils/logger';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
const log = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
override get isActive(): boolean {
// HTTP server never receives events — `isActive` purely tracks the
// bound listener so the network manager can skip dispatch cleanly.
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
this.startServer();
this.isEnabled = true;
}
close(): void {
if (!this.isEnabled && !this.server) return;
this.isEnabled = false;
this.server?.close();
this.server = null;
}
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
// HTTP server only acts on inbound requests; it doesn't push events.
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
private startServer(): void {
const expectedPath = normalizePath(this.config.path ?? '/');
const accessToken = this.config.accessToken ?? '';
const server = createServer((req, res) => {
void this.handleRequest(expectedPath, accessToken, req, res);
});
this.server = server;
server.on('listening', () => {
log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
expectedPath,
);
});
server.on('error', (err) => {
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
}
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
const incomingPath = parsedUrl.pathname;
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
let action = '';
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
action = '';
} else if (incomingPath.startsWith(ep)) {
action = incomingPath.substring(ep.length);
} else {
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
return;
}
if (!isAuthorized(req, accessToken)) {
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
return;
}
if (req.method === 'GET' && !action) {
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
return;
}
try {
let params: Record<string, unknown> = {};
let echo: unknown;
if (req.method === 'GET') {
parsedUrl.searchParams.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
} else if (req.method === 'POST') {
const bodyContent = await readRequestBody(req);
if (bodyContent.trim()) {
try {
const parsedBody = JSON.parse(bodyContent);
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
if (parsedBody.action && !action) action = String(parsedBody.action);
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
params = parsedBody.params as Record<string, unknown>;
} else {
params = parsedBody as Record<string, unknown>;
}
echo = parsedBody.echo;
}
} catch {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
return;
}
}
} else {
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
return;
}
if (!action) {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
return;
}
const response = await this.ctx.api.handle(action, params as JsonObject);
if (echo !== undefined) {
response.echo = echo as JsonValue;
}
writeJson(res, 200, response);
} catch (error) {
const wording = error instanceof Error ? error.message : 'internal error';
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
}
}
}
function bindingSignature(net: HttpServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}#${net.accessToken ?? ''}`;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
req.on('data', (chunk: Buffer) => {
total += chunk.length;
if (total > maxBytes) {
reject(new Error('request body too large'));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
}

View File

@@ -0,0 +1,9 @@
// Public surface for the OneBot network package.
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
export { OneBotNetworkManager } from './network-manager';
export { WsServerAdapter } from './ws-server-adapter';
export { WsClientAdapter } from './ws-client-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export { HttpPostAdapter } from './http-post-adapter';
export { executeQuickOperation } from './quick-operation';

View File

@@ -0,0 +1,105 @@
// OneBot network manager.
//
// Mirrors NapCat's `OB11NetworkManager`: holds a `Map<name, adapter>`, fans
// events out to every active adapter in parallel, and provides primitives
// the OneBot instance uses to register, hot-reload, and tear adapters down.
import type { JsonObject, NetworkBase } from '../types';
import { buildDispatchPayload } from '../event-filter';
import { IOneBotNetworkAdapter } from './adapter';
import { createLogger } from '../../utils/logger';
const log = createLogger('OneBot.Network');
type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
export class OneBotNetworkManager {
private readonly adapters = new Map<string, AnyAdapter>();
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
const existing = this.adapters.get(adapter.name);
if (existing) {
// Replacing an adapter under the same name — close the previous one
// before storing the new instance to keep ports/sockets clean.
log.info('replacing adapter [%s]', adapter.name);
void Promise.resolve(existing.close()).catch(() => { /* best-effort */ });
}
this.adapters.set(adapter.name, adapter as AnyAdapter);
}
has(name: string): boolean { return this.adapters.has(name); }
get(name: string): AnyAdapter | null {
return this.adapters.get(name) ?? null;
}
list(): AnyAdapter[] { return [...this.adapters.values()]; }
hasActiveAdapters(): boolean {
for (const a of this.adapters.values()) if (a.isActive) return true;
return false;
}
async openAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.open();
} catch (err) {
log.error('adapter [%s] open failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
}
async closeAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
this.adapters.clear();
}
async closeOne(name: string): Promise<void> {
const adapter = this.adapters.get(name);
if (!adapter) return;
this.adapters.delete(name);
try {
await adapter.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', adapter.name, errMessage(err));
}
}
/**
* Dispatch one canonical OneBot event to every active adapter in parallel.
* The dispatch payload is built once so each adapter pays only the cost
* of picking the right pre-serialized variant.
*
* Errors thrown inside an adapter are isolated — one bad adapter never
* blocks the others.
*/
async emitEvent(event: JsonObject): Promise<void> {
if (!this.hasActiveAdapters()) return;
const payload = buildDispatchPayload(event);
const tasks: Promise<unknown>[] = [];
for (const adapter of this.adapters.values()) {
if (!adapter.isActive) continue;
tasks.push(
Promise.resolve()
.then(() => adapter.onEvent(event, payload))
.catch((err) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(err));
}),
);
}
await Promise.allSettled(tasks);
}
}
function errMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}

View File

@@ -0,0 +1,89 @@
// OneBot v11 hidden API: `.handle_quick_operation`.
//
// When an HTTP POST event report receives a JSON body in response, that body
// is interpreted as a "quick operation" — short-cuts to common follow-up
// API calls (reply, recall, ban, kick, approve/reject). Spec:
// https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md
import type { ApiHandler } from '../api-handler';
import type { JsonObject, JsonValue } from '../types';
export async function executeQuickOperation(
event: JsonObject,
operation: Record<string, unknown>,
api: ApiHandler,
): Promise<void> {
const postType = event.post_type as string;
if (postType === 'message') {
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
const messageType = event.message_type as string;
const autoEscape = !!operation.auto_escape;
if (messageType === 'group') {
const params: JsonObject = {
group_id: event.group_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
};
if (operation.at_sender !== false && event.user_id) {
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
if (typeof operation.reply === 'string') {
params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as JsonValue;
params.auto_escape = false;
} else if (Array.isArray(operation.reply)) {
params.message = [atSegment, ...(operation.reply as unknown[])] as JsonValue;
}
}
await api.handle('send_group_msg', params);
} else if (messageType === 'private') {
await api.handle('send_private_msg', {
user_id: event.user_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
});
}
}
if (operation.delete) {
await api.handle('delete_msg', { message_id: event.message_id as number });
}
if (operation.ban && event.message_type === 'group') {
const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
await api.handle('set_group_ban', {
group_id: event.group_id as number,
user_id: event.user_id as number,
duration: duration as JsonValue,
});
}
if (operation.kick && event.message_type === 'group') {
await api.handle('set_group_kick', {
group_id: event.group_id as number,
user_id: event.user_id as number,
reject_add_request: !!operation.reject_add_request,
});
}
}
if (postType === 'request') {
if (operation.approve !== undefined) {
const requestType = event.request_type as string;
if (requestType === 'friend') {
await api.handle('set_friend_add_request', {
flag: event.flag as string,
approve: operation.approve as JsonValue,
remark: (operation.remark ?? '') as JsonValue,
});
} else if (requestType === 'group') {
await api.handle('set_group_add_request', {
flag: event.flag as string,
sub_type: event.sub_type as string,
approve: operation.approve as JsonValue,
reason: (operation.reason ?? '') as JsonValue,
});
}
}
}
}

View File

@@ -0,0 +1,59 @@
// Helpers shared between OneBot network adapters.
import type { IncomingMessage } from 'http';
import type { WebSocket } from '@snowluma/websocket';
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
export function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
const rawAuth = request.headers.authorization;
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
if (auth === `Bearer ${token}`) return true;
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
if (url.searchParams.get('access_token') === token) return true;
} catch { /* ignore malformed URLs */ }
return false;
}
/** Convert anything ws can hand us into a UTF-8 string. */
export function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
if (typeof raw === 'string') return raw;
if (Buffer.isBuffer(raw)) return raw.toString('utf8');
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
if (ArrayBuffer.isView(raw)) {
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
}
/** Best-effort send: drops payload if the socket isn't OPEN, reports send errors. */
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
if (socket.readyState !== 1 /* WebSocket.OPEN */) return;
socket.send(payload, (error?: Error | null) => {
if (error && onError) onError(error);
});
}
/** Best-effort close, treats already-closed sockets as a no-op. */
export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return;
socket.close(code, reason);
}
/** Normalize an HTTP/WS path to a comparable form (strip trailing slash, default to "/"). */
export function normalizePath(pathValue: string | undefined): string {
const path = (pathValue ?? '/').trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
}
/** Parse the `pathname` from a (potentially relative) WebSocket request URL. */
export function parseRequestPath(urlValue: string): string {
try {
return new URL(urlValue, 'ws://127.0.0.1').pathname;
} catch {
return '/';
}
}

View File

@@ -0,0 +1,177 @@
// Reverse (client) WebSocket adapter — one instance per `wsClients[]` entry.
//
// Connects out to a remote OneBot endpoint, manages reconnects, forwards
// pushed events on `onEvent`, and dispatches incoming API messages to the
// shared ApiHandler.
import { WebSocket } from '@snowluma/websocket';
import type { WsClientNetwork, WsRole, JsonObject } from '../types';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import { createLogger } from '../../utils/logger';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
const log = createLogger('OneBot.WS-Client');
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private socket: WebSocket | null = null;
private reconnectTimer: NodeJS.Timeout | null = null;
private options: EventReportOptions;
private role: WsRole;
private explicitlyClosed = false;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
this.role = config.role ?? 'Universal';
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
if (!this.config.url) return;
this.explicitlyClosed = false;
this.isEnabled = true;
this.connect();
}
close(): void {
this.explicitlyClosed = true;
this.isEnabled = false;
this.cancelReconnect();
if (this.socket) {
safeClose(this.socket);
this.socket = null;
}
}
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
this.role = next.role ?? 'Universal';
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || !this.socket) return;
if (this.role !== 'Event' && this.role !== 'Universal') return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
safeSend(this.socket, json);
}
private connect(): void {
if (this.explicitlyClosed) return;
if (!this.config.url) return;
if (this.socket) return;
const headers: Record<string, string> = {
'User-Agent': 'OneBot/11',
'X-Self-ID': this.ctx.uin,
'X-Client-Role': this.role,
};
if (this.config.accessToken) {
headers.Authorization = `Bearer ${this.config.accessToken}`;
}
const socket = new WebSocket(this.config.url, { headers });
this.socket = socket;
socket.on('open', () => {
log.info('[%s] connected %s', this.name, this.config.url);
this.sendBootstrapMetaEvents(socket);
});
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, raw);
});
socket.on('close', () => {
this.socket = null;
if (this.explicitlyClosed || !this.isEnabled) return;
this.scheduleReconnect();
});
socket.on('error', (err: Error) => {
log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
});
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
if (this.explicitlyClosed) return;
const interval = Math.max(1000, this.config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS);
const timer = setTimeout(() => {
this.reconnectTimer = null;
if (this.explicitlyClosed || !this.isEnabled) return;
this.connect();
}, interval);
timer.unref?.();
this.reconnectTimer = timer;
}
private cancelReconnect(): void {
if (!this.reconnectTimer) return;
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
private async handleApiMessage(socket: WebSocket, raw: Buffer | string): Promise<void> {
if (this.role !== 'Api' && this.role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
if (this.role !== 'Event' && this.role !== 'Universal') return;
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
function bindingSignature(net: WsClientNetwork): string {
return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`;
}

View File

@@ -0,0 +1,187 @@
// Forward (server) WebSocket adapter — one instance per `wsServers[]` entry.
//
// Each adapter owns its own `WebSocketServer`, accepts inbound forward
// connections (api / event / universal roles), and pushes events to all live
// event-receiving sockets when `onEvent` fires.
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import type { WsRole, WsServerNetwork, JsonObject } from '../types';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import { createLogger } from '../../utils/logger';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, parseRequestPath, rawDataToString, safeClose, safeSend, normalizePath } from './utils';
const log = createLogger('OneBot.WS-Server');
interface ForwardConn {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
}
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
this.startServer();
this.isEnabled = true;
}
close(): void {
if (!this.isEnabled && this.connections.size === 0 && !this.wss) return;
// Final lifecycle broadcast before tearing down so attached event clients
// see the disable transition.
const lifecycle = this.ctx.buildLifecycleEvent('disable');
for (const conn of this.connections.values()) {
if (conn.role === 'Api') continue;
const shaped = shapeEventForAdapter(lifecycle, conn.options);
if (!shaped) continue;
safeSend(conn.socket, JSON.stringify(shaped));
}
this.isEnabled = false;
for (const ws of [...this.connections.keys()]) safeClose(ws);
this.connections.clear();
this.wss?.close();
this.wss = null;
}
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
for (const conn of this.connections.values()) conn.options = this.options;
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || this.connections.size === 0) return;
for (const conn of this.connections.values()) {
if (conn.role !== 'Event' && conn.role !== 'Universal') continue;
const json = pickDispatchJson(payload, conn.options);
if (json === null) continue;
safeSend(conn.socket, json);
}
}
private startServer(): void {
const wss = new WebSocketServer({
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
path: this.config.path ?? '/',
});
this.wss = wss;
wss.on('listening', () => {
log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
this.config.path ?? '/',
);
});
wss.on('error', (err: Error) => {
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
}
private onConnection(socket: WebSocket, request: IncomingMessage): void {
if (!isAuthorized(request, this.config.accessToken ?? '')) {
safeClose(socket, 1008, 'invalid access token');
return;
}
const role = this.config.role ?? classifyForwardRole(request);
const conn: ForwardConn = { socket, role, options: this.options };
this.connections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
});
socket.on('close', () => this.connections.delete(socket));
socket.on('error', (err: Error) => {
log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
});
if (role === 'Event' || role === 'Universal') {
this.sendBootstrapMetaEvents(socket);
}
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
if (role !== 'Api' && role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
function classifyForwardRole(request: IncomingMessage): WsRole {
const path = parseRequestPath(request.url ?? '/');
if (path.endsWith('/api')) return 'Api';
if (path.endsWith('/event')) return 'Event';
return 'Universal';
}
function bindingSignature(net: WsServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path)}#${net.role ?? 'auto'}#${net.accessToken ?? ''}`;
}

View File

@@ -33,7 +33,7 @@ export type NetworkKind = 'httpServers' | 'httpClients' | 'wsServers' | 'wsClien
* The `name` is a free-form identifier scoped to the adapter's array; it is
* used for hot-reload bookkeeping and as a label in logs / WebUI.
*/
interface NetworkBase {
export interface NetworkBase {
name: string;
/** When `false`, the adapter is configured but inactive. Defaults to `true`. */
enabled?: boolean;

View File

@@ -1,424 +0,0 @@
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import type { ApiHandler } from './api-handler';
import type { JsonObject, OneBotConfig, WsClientNetwork, WsRole, WsServerNetwork } from './types';
import { createLogger } from '../utils/logger';
import {
buildDispatchPayload,
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from './event-filter';
interface ForwardConnection {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
serverName: string;
}
interface ReverseConnection {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
endpointUrl: string;
reconnectIntervalMs: number;
name: string;
}
interface RunningWsServer {
wss: WebSocketServer;
signature: string;
network: WsServerNetwork;
options: EventReportOptions;
}
interface RunningWsClient {
network: WsClientNetwork;
signature: string;
options: EventReportOptions;
}
export interface WsTransportContext {
uin: string;
api: ApiHandler;
buildLifecycleEvent: (subType: 'connect' | 'enable' | 'disable') => JsonObject;
buildHeartbeatEvent: () => JsonObject;
}
const log = createLogger('OneBot.WS');
export class WsTransport {
private readonly context: WsTransportContext;
private readonly servers = new Map<string, RunningWsServer>();
private readonly clientStates = new Map<string, RunningWsClient>();
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
private readonly reverseConnections = new Map<string, ReverseConnection>();
private readonly reconnectTimers = new Map<string, NodeJS.Timeout>();
private serverNetworks: WsServerNetwork[] = [];
private clientNetworks: WsClientNetwork[] = [];
private stopped = false;
constructor(config: OneBotConfig, context: WsTransportContext) {
this.serverNetworks = activeServers(config);
this.clientNetworks = activeClients(config);
this.context = context;
for (const network of this.clientNetworks) {
this.clientStates.set(network.name, {
network,
signature: wsClientSignature(network),
options: resolveReportOptions(network),
});
}
}
start(): void {
this.stopped = false;
for (const network of this.serverNetworks) this.startServerEndpoint(network);
for (const network of this.clientNetworks) this.startClientEndpoint(network.name);
}
reloadConfig(config: OneBotConfig): void {
const nextServers = activeServers(config);
const nextClients = activeClients(config);
const nextServerByName = new Map(nextServers.map((n) => [n.name, n] as const));
const nextClientByName = new Map(nextClients.map((n) => [n.name, n] as const));
// --- WS Servers ---
for (const [name, running] of [...this.servers]) {
const next = nextServerByName.get(name);
if (!next || wsServerSignature(next) !== running.signature) {
running.wss.close();
this.servers.delete(name);
// Drop forward connections that belonged to the closed adapter.
for (const [socket, conn] of [...this.forwardConnections]) {
if (conn.serverName === name) {
safeClose(socket);
this.forwardConnections.delete(socket);
}
}
log.info('stopped forward server [%s]', name);
} else {
// Same binding — refresh options so reload picks up format changes.
running.network = next;
running.options = resolveReportOptions(next);
for (const conn of this.forwardConnections.values()) {
if (conn.serverName === name) conn.options = running.options;
}
}
}
for (const network of nextServers) {
if (!this.servers.has(network.name)) this.startServerEndpoint(network);
}
// --- WS Clients (reverse) ---
for (const [name, state] of [...this.clientStates]) {
const next = nextClientByName.get(name);
const sig = next ? wsClientSignature(next) : null;
if (!next || sig !== state.signature) {
const conn = this.reverseConnections.get(name);
if (conn) {
safeClose(conn.socket);
this.reverseConnections.delete(name);
}
const timer = this.reconnectTimers.get(name);
if (timer) {
clearTimeout(timer);
this.reconnectTimers.delete(name);
}
this.clientStates.delete(name);
log.info('stopped reverse client [%s]', name);
} else {
state.network = next;
state.options = resolveReportOptions(next);
const conn = this.reverseConnections.get(name);
if (conn) conn.options = state.options;
}
}
for (const network of nextClients) {
if (!this.clientStates.has(network.name)) {
this.clientStates.set(network.name, {
network,
signature: wsClientSignature(network),
options: resolveReportOptions(network),
});
if (!this.stopped) this.startClientEndpoint(network.name);
}
}
this.serverNetworks = nextServers;
this.clientNetworks = nextClients;
}
stop(): void {
// Final lifecycle broadcast before we mark ourselves stopped.
this.publishEvent(this.context.buildLifecycleEvent('disable'));
this.stopped = true;
for (const timer of this.reconnectTimers.values()) {
clearTimeout(timer);
}
this.reconnectTimers.clear();
for (const socket of this.forwardConnections.keys()) {
safeClose(socket);
}
this.forwardConnections.clear();
for (const conn of this.reverseConnections.values()) {
safeClose(conn.socket);
}
this.reverseConnections.clear();
for (const { wss } of this.servers.values()) {
wss.close();
}
this.servers.clear();
this.clientStates.clear();
}
/**
* Fan out one canonical event to every event-receiving WS connection.
*
* The instance pre-builds the {@link DispatchPayload} (two JSON variants at
* most) so each connection is served with a single O(1) pick + send rather
* than re-shaping or re-serializing the event itself. The raw `event` is
* accepted so ad-hoc callers (e.g. `stop()`) can dispatch without allocating
* a payload at the call site.
*/
publishEvent(event: JsonObject, payload?: DispatchPayload): void {
const dispatch = payload ?? buildDispatchPayload(event);
for (const conn of this.forwardConnections.values()) {
if (conn.role !== 'Event' && conn.role !== 'Universal') continue;
const json = pickDispatchJson(dispatch, conn.options);
if (json === null) continue;
safeSend(conn.socket, json);
}
for (const conn of this.reverseConnections.values()) {
if (conn.role !== 'Event' && conn.role !== 'Universal') continue;
const json = pickDispatchJson(dispatch, conn.options);
if (json === null) continue;
safeSend(conn.socket, json);
}
}
private startServerEndpoint(network: WsServerNetwork): void {
const wss = new WebSocketServer({
host: network.host ?? '0.0.0.0',
port: network.port,
path: network.path ?? '/',
});
const running: RunningWsServer = {
wss,
signature: wsServerSignature(network),
network,
options: resolveReportOptions(network),
};
this.servers.set(network.name, running);
wss.on('listening', () => {
log.success('[%s] listening %s:%d%s', network.name, network.host ?? '0.0.0.0', network.port, network.path ?? '/');
});
wss.on('connection', (socket, request) => {
if (!isAuthorized(request, running.network.accessToken ?? '')) {
safeClose(socket, 1008, 'invalid access token');
return;
}
const role = running.network.role ?? classifyForwardRole(request);
const conn: ForwardConnection = {
socket,
role,
options: running.options,
serverName: running.network.name,
};
this.forwardConnections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
});
socket.on('close', () => {
this.forwardConnections.delete(socket);
});
socket.on('error', (error: Error) => {
log.warn('[%s] forward socket error: %s', running.network.name, error instanceof Error ? error.message : String(error));
});
this.sendBootstrapMetaEvents(socket, role, conn.options);
});
wss.on('error', (error: Error) => {
log.warn('[%s] server error: %s', network.name, error instanceof Error ? error.message : String(error));
});
}
private startClientEndpoint(name: string): void {
const state = this.clientStates.get(name);
if (!state || this.stopped) return;
if (this.reverseConnections.has(name) || this.reconnectTimers.has(name)) return;
const network = state.network;
const role = network.role ?? 'Universal';
const headers: Record<string, string> = {
'User-Agent': 'OneBot/11',
'X-Self-ID': this.context.uin,
'X-Client-Role': role,
};
if (network.accessToken) headers.Authorization = `Bearer ${network.accessToken}`;
const socket = new WebSocket(network.url, { headers });
const conn: ReverseConnection = {
socket,
role,
options: state.options,
endpointUrl: network.url,
reconnectIntervalMs: Math.max(1000, network.reconnectIntervalMs ?? 5000),
name,
};
this.reverseConnections.set(name, conn);
socket.on('open', () => {
log.info('[%s] reverse connected %s', name, network.url);
this.sendBootstrapMetaEvents(socket, role, state.options);
});
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
});
socket.on('close', () => {
this.reverseConnections.delete(name);
if (this.stopped) return;
if (!this.clientStates.has(name)) return;
if (this.reconnectTimers.has(name)) return;
const timer = setTimeout(() => {
this.reconnectTimers.delete(name);
if (this.stopped || !this.clientStates.has(name)) return;
this.startClientEndpoint(name);
}, conn.reconnectIntervalMs);
timer.unref?.();
this.reconnectTimers.set(name, timer);
});
socket.on('error', (error: Error) => {
log.warn('[%s] reverse error %s: %s', name, network.url, error instanceof Error ? error.message : String(error));
});
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
if (role !== 'Api' && role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.context.api.processRequest(text);
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket, role: WsRole, options: EventReportOptions): void {
if (role !== 'Event' && role !== 'Universal') return;
const events = [
this.context.buildLifecycleEvent('connect'),
this.context.buildLifecycleEvent('enable'),
this.context.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
function classifyForwardRole(request: IncomingMessage): WsRole {
const path = parseRequestPath(request.url ?? '/');
if (path.endsWith('/api')) return 'Api';
if (path.endsWith('/event')) return 'Event';
return 'Universal';
}
function parseRequestPath(urlValue: string): string {
try {
return new URL(urlValue, 'ws://127.0.0.1').pathname;
} catch {
return '/';
}
}
function normalizeWsPath(pathValue: string | undefined): string {
const path = (pathValue ?? '/').trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
}
function activeServers(config: OneBotConfig): WsServerNetwork[] {
return config.networks.wsServers.filter((n) => n.enabled !== false);
}
function activeClients(config: OneBotConfig): WsClientNetwork[] {
return config.networks.wsClients.filter((n) => n.enabled !== false && !!n.url);
}
function wsServerSignature(network: WsServerNetwork): string {
return `${network.host ?? '0.0.0.0'}:${network.port}${normalizeWsPath(network.path)}#${network.role ?? 'auto'}#${network.accessToken ?? ''}`;
}
function wsClientSignature(network: WsClientNetwork): string {
const role = network.role ?? 'Universal';
const reconnectIntervalMs = Math.max(1000, network.reconnectIntervalMs ?? 5000);
return `${network.url}#${role}#${reconnectIntervalMs}#${network.accessToken ?? ''}`;
}
function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
// 1. Header auth
const rawAuth = request.headers.authorization;
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
if (auth === `Bearer ${token}`) return true;
// 2. Query string auth
try {
const url = new URL(request.url ?? '/', 'ws://127.0.0.1');
if (url.searchParams.get('access_token') === token) {
return true;
}
} catch { }
return false;
}
function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
if (typeof raw === 'string') return raw;
if (Buffer.isBuffer(raw)) return raw.toString('utf8');
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
if (ArrayBuffer.isView(raw)) {
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
}
function safeSend(socket: WebSocket, payload: string): void {
if (socket.readyState !== WebSocket.OPEN) return;
socket.send(payload, (error?: Error | null) => {
if (error) {
log.warn('send error: %s', error instanceof Error ? error.message : String(error));
}
});
}
function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) return;
socket.close(code, reason);
}

View File

@@ -78,21 +78,13 @@ export async function initWebUI(
const auth = WebuiAuth.load();
const initialPassword = auth.takeInitialPassword();
if (auth.isDevMode()) {
log.warn('=========================================');
log.warn('WebUI 已进入开发模式 (SNOWLUMA_DEV_MODE=1)');
log.warn('固定密码: %s', WebuiAuth.devPassword);
log.warn('config/webui.json 不会被读写,强制改密流程已跳过');
log.warn('请勿在生产环境启用此模式');
log.warn('=========================================');
log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword);
log.warn('dev mode skips config/webui.json and password rotation');
} else if (initialPassword) {
log.info('=========================================');
log.info('WebUI 安全认证(首次启动,已生成临时密码)');
log.info('默认用户: admin');
log.info('临时密码: %s', initialPassword);
log.info('请使用该密码登录后立即设置强密码(≥10 位、含大小写、特殊符号、不含空格)');
log.info('=========================================');
log.info('initial credentials: user=admin password=%s', initialPassword);
log.info('password change required after first login');
} else if (auth.mustChangePassword()) {
log.warn('WebUI 仍未完成强制改密,登录后须立即修改密码。');
log.warn('password change is still required');
}
const app = new Hono();
@@ -216,7 +208,7 @@ export async function initWebUI(
sessionTokens.delete(tok);
}
}
log.info('WebUI 密码已更新(强制改密流程完成)');
log.info('password updated');
return c.json({ success: true });
});
@@ -458,12 +450,12 @@ export async function initWebUI(
const finalPort = await findAvailablePort(desiredPort);
if (finalPort !== desiredPort) {
log.warn('端口 %d 已被占用,已自动改用 %d', desiredPort, finalPort);
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
}
await new Promise<void>((resolve) => {
serve({ fetch: app.fetch, port: finalPort }, (info) => {
log.info(`WebUI 服务监听 http://localhost:${info.port}`);
log.info(`listening http://localhost:${info.port}`);
resolve();
});
});

View File

@@ -0,0 +1,135 @@
import { describe, expect, it, vi } from 'vitest';
import { BridgeEventBus } from '../src/bridge/event-bus';
import type { FriendMessage, GroupMessage } from '../src/bridge/events';
function makeFriendMessage(): FriendMessage {
return {
kind: 'friend_message',
time: 1700000000,
selfUin: 10001,
senderUin: 22222,
senderNick: 'peer',
msgSeq: 1,
msgId: 1,
elements: [{ type: 'text', text: 'hi' }],
};
}
function makeGroupMessage(): GroupMessage {
return {
kind: 'group_message',
time: 1700000000,
selfUin: 10001,
groupId: 99999,
senderUin: 22222,
senderNick: 'peer',
senderCard: '',
senderRole: 'member',
msgSeq: 2,
msgId: 2,
elements: [{ type: 'text', text: 'hi' }],
};
}
describe('BridgeEventBus', () => {
it('routes events only to subscribers of the matching kind', async () => {
const bus = new BridgeEventBus();
const friend = vi.fn();
const group = vi.fn();
bus.on('friend_message', friend);
bus.on('group_message', group);
await bus.emit(makeFriendMessage());
await bus.emit(makeGroupMessage());
expect(friend).toHaveBeenCalledTimes(1);
expect(group).toHaveBeenCalledTimes(1);
});
it('runs every subscriber in parallel for one kind', async () => {
const bus = new BridgeEventBus();
const order: string[] = [];
bus.on('friend_message', async () => {
await new Promise((r) => setTimeout(r, 20));
order.push('slow');
});
bus.on('friend_message', () => {
order.push('fast');
});
await bus.emit(makeFriendMessage());
// The synchronous handler must finish before the async one — proves we
// don't serialize handlers across the kind.
expect(order).toEqual(['fast', 'slow']);
});
it('isolates handler errors and reports them via onError', async () => {
const seen: Array<{ kind: string; err: unknown }> = [];
const bus = new BridgeEventBus({ onError: (kind, err) => seen.push({ kind, err }) });
const ok = vi.fn();
bus.on('friend_message', () => {
throw new Error('boom');
});
bus.on('friend_message', ok);
await bus.emit(makeFriendMessage());
expect(ok).toHaveBeenCalledTimes(1);
expect(seen).toHaveLength(1);
expect(seen[0].kind).toBe('friend_message');
expect((seen[0].err as Error).message).toBe('boom');
});
it('supports unsubscribe via the returned disposer', async () => {
const bus = new BridgeEventBus();
const handler = vi.fn();
const off = bus.on('friend_message', handler);
await bus.emit(makeFriendMessage());
expect(handler).toHaveBeenCalledTimes(1);
off();
await bus.emit(makeFriendMessage());
expect(handler).toHaveBeenCalledTimes(1);
});
it('supports onAny and isolates its errors separately', async () => {
const seen: Array<{ kind: string; err: unknown }> = [];
const bus = new BridgeEventBus({ onError: (kind, err) => seen.push({ kind, err }) });
const tap = vi.fn();
bus.onAny(tap);
bus.onAny(() => { throw new Error('any-fail'); });
await bus.emit(makeFriendMessage());
await bus.emit(makeGroupMessage());
expect(tap).toHaveBeenCalledTimes(2);
expect(seen).toHaveLength(2);
expect(seen.every((s) => s.kind === '*')).toBe(true);
});
it('reports has() based on per-kind + onAny subscriptions', () => {
const bus = new BridgeEventBus();
expect(bus.has('friend_message')).toBe(false);
const off = bus.on('friend_message', () => {});
expect(bus.has('friend_message')).toBe(true);
off();
expect(bus.has('friend_message')).toBe(false);
bus.onAny(() => {});
expect(bus.has('friend_message')).toBe(true);
});
it('clear() drops every subscriber', async () => {
const bus = new BridgeEventBus();
const handler = vi.fn();
bus.on('friend_message', handler);
bus.onAny(handler);
bus.clear();
await bus.emit(makeFriendMessage());
expect(handler).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,193 @@
import { describe, expect, it, vi } from 'vitest';
import { BridgeEventBus } from '../src/bridge/event-bus';
import { EventConverter } from '../src/onebot/event-converter';
import { registerEventPipeline } from '../src/onebot/event-pipeline';
import type { OneBotInstanceContext } from '../src/onebot/instance-context';
import type {
FriendMessage,
GroupMessage,
GroupMemberJoin,
TempMessage,
QQEventVariant,
} from '../src/bridge/events';
import type { JsonObject, MessageMeta } from '../src/onebot/types';
const SELF_UIN = '10001';
const SELF_ID = 10001;
const PEER_UIN = 22222;
const GROUP_ID = 99999;
interface FakeBridge {
events: BridgeEventBus;
}
function makeFriendMessage(): FriendMessage {
return {
kind: 'friend_message',
time: 1700000000,
selfUin: SELF_ID,
senderUin: PEER_UIN,
senderNick: 'peer',
msgSeq: 11,
msgId: 555,
elements: [{ type: 'text', text: 'hi' }],
};
}
function makeGroupMessage(): GroupMessage {
return {
kind: 'group_message',
time: 1700000000,
selfUin: SELF_ID,
groupId: GROUP_ID,
senderUin: PEER_UIN,
senderNick: 'peer',
senderCard: '',
senderRole: 'member',
msgSeq: 22,
msgId: 777,
elements: [{ type: 'text', text: 'group' }],
};
}
function makeTempMessage(): TempMessage {
return {
kind: 'temp_message',
time: 1700000000,
selfUin: SELF_ID,
senderUin: PEER_UIN,
groupId: GROUP_ID,
senderNick: 'peer',
msgSeq: 33,
elements: [{ type: 'text', text: 'temp' }],
};
}
function makeMemberJoin(): GroupMemberJoin {
return {
kind: 'group_member_join',
time: 1700000000,
selfUin: SELF_ID,
groupId: GROUP_ID,
userUin: PEER_UIN,
operatorUin: PEER_UIN,
};
}
function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
ctx: OneBotInstanceContext;
bus: BridgeEventBus;
metaCalls: Array<{ id: number; meta: MessageMeta }>;
dispatchCalls: JsonObject[];
} {
const bus = new BridgeEventBus();
const fakeBridge: FakeBridge = { events: bus };
const eventConverter = new EventConverter();
const metaCalls: Array<{ id: number; meta: MessageMeta }> = [];
const dispatchCalls: JsonObject[] = [];
const ctx: OneBotInstanceContext = {
uin: SELF_UIN,
selfId: SELF_ID,
qqInfo: {} as never,
bridge: fakeBridge as never,
messageStore: {} as never,
mediaStore: {} as never,
eventConverter,
config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never,
cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); },
dispatchEvent: (event) => { dispatchCalls.push(event); },
...extra,
};
return { ctx, bus, metaCalls, dispatchCalls };
}
describe('registerEventPipeline', () => {
it('caches meta and dispatches a converted event for friend_message', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeFriendMessage());
expect(metaCalls).toHaveLength(1);
expect(metaCalls[0].meta.isGroup).toBe(false);
expect(metaCalls[0].meta.targetId).toBe(PEER_UIN);
expect(metaCalls[0].meta.sequence).toBe(11);
expect(metaCalls[0].meta.random).toBe(555);
expect(dispatchCalls).toHaveLength(1);
expect(dispatchCalls[0].post_type).toBe('message');
expect(dispatchCalls[0].message_type).toBe('private');
});
it('caches meta and dispatches for group_message', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeGroupMessage());
expect(metaCalls[0].meta.isGroup).toBe(true);
expect(metaCalls[0].meta.targetId).toBe(GROUP_ID);
expect(dispatchCalls[0].message_type).toBe('group');
});
it('caches meta with random=0 for temp_message and dispatches as private+sub_type=group', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeTempMessage());
expect(metaCalls[0].meta.isGroup).toBe(false);
expect(metaCalls[0].meta.random).toBe(0);
expect(dispatchCalls[0].message_type).toBe('private');
expect(dispatchCalls[0].sub_type).toBe('group');
});
it('dispatches notice events without seeding meta', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeMemberJoin());
expect(metaCalls).toHaveLength(0);
expect(dispatchCalls).toHaveLength(1);
expect(dispatchCalls[0].notice_type).toBe('group_increase');
});
it('returns a disposer that fully unsubscribes', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
const dispose = registerEventPipeline(ctx);
await bus.emit(makeFriendMessage());
expect(dispatchCalls).toHaveLength(1);
dispose();
await bus.emit(makeFriendMessage());
// No new calls after dispose.
expect(dispatchCalls).toHaveLength(1);
expect(metaCalls).toHaveLength(1);
});
it('dispatches a separate event for every kind in parallel', async () => {
const { ctx, bus, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
const events: QQEventVariant[] = [makeFriendMessage(), makeGroupMessage(), makeMemberJoin(), makeTempMessage()];
await Promise.all(events.map((e) => bus.emit(e)));
expect(dispatchCalls).toHaveLength(events.length);
});
it('skips dispatch for kinds without a converter mapping (no crash)', async () => {
// Stub `convert` on a real EventConverter instance so the type stays
// honest -- no structural casts.
const stubbed = new EventConverter();
stubbed.convert = vi.fn().mockResolvedValue(null);
const { ctx, bus, dispatchCalls } = makeContext({ eventConverter: stubbed });
registerEventPipeline(ctx);
await bus.emit(makeFriendMessage());
expect(dispatchCalls).toHaveLength(0);
});
});

View File

@@ -0,0 +1,306 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import fs from 'fs';
import path from 'path';
import { MediaStore } from '../src/onebot/media-store';
import { EventConverter } from '../src/onebot/event-converter';
import type { GroupMessage, FriendMessage, MessageElement } from '../src/bridge/events';
const SELF_UIN = '10001';
const SELF_ID = 10001;
const PEER_UIN = 22222;
const GROUP_ID = 99999;
function imageElement(overrides: Partial<MessageElement> = {}): MessageElement {
return {
type: 'image',
fileId: 'abc.png',
fileSize: 4242,
imageUrl: 'https://example.com/abc.png',
...overrides,
};
}
function recordElement(overrides: Partial<MessageElement> = {}): MessageElement {
return {
type: 'record',
fileId: 'uuid-base64-fake',
fileName: 'silk_test.amr',
fileSize: 1024,
duration: 3,
fileHash: 'deadbeef',
mediaNode: { fileUuid: 'uuid-base64-fake', storeId: 1 },
...overrides,
};
}
function makeGroupMessage(elements: MessageElement[]): GroupMessage {
return {
kind: 'group_message',
time: 1700000000,
selfUin: SELF_ID,
groupId: GROUP_ID,
senderUin: PEER_UIN,
senderNick: 'peer',
senderCard: '',
senderRole: 'member',
msgSeq: 1,
msgId: 1,
elements,
};
}
function makeFriendMessage(elements: MessageElement[]): FriendMessage {
return {
kind: 'friend_message',
time: 1700000000,
selfUin: SELF_ID,
senderUin: PEER_UIN,
senderNick: 'peer',
msgSeq: 1,
msgId: 1,
elements,
};
}
function tempDbPath(label: string): string {
return path.join('data', 'test', `media-${label}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
}
describe('MediaStore basic semantics', () => {
const dbs: string[] = [];
beforeEach(() => {
dbs.length = 0;
});
afterEach(() => {
for (const dbPath of dbs) {
for (const ext of ['', '-wal', '-shm']) {
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
}
}
});
function open(label: string, max?: number): MediaStore {
const dbPath = tempDbPath(label);
dbs.push(dbPath);
return max !== undefined ? new MediaStore(dbPath, max) : new MediaStore(dbPath);
}
it('indexes images by file, fileName, and url', () => {
const store = open('img-keys');
store.rememberImage({
file: 'abc.png',
url: 'https://example.com/abc.png',
fileSize: 4242,
fileName: 'abc.png',
subType: 0,
summary: '',
imageUrl: 'https://example.com/abc.png',
isGroup: true,
sessionId: GROUP_ID,
});
expect(store.findImage('abc.png')?.fileSize).toBe(4242);
expect(store.findImage('https://example.com/abc.png')?.url).toBe('https://example.com/abc.png');
expect(store.findImage('missing.png')).toBeNull();
expect(store.findImage('')).toBeNull();
store.close();
});
it('indexes records by file, fileName, fileId, and url', () => {
const store = open('rec-keys');
store.rememberRecord({
file: 'silk_test.amr',
fileId: 'uuid-base64-fake',
url: 'https://example.com/voice.amr',
fileSize: 1024,
fileName: 'silk_test.amr',
duration: 3,
fileHash: 'deadbeef',
mediaNode: { fileUuid: 'uuid-base64-fake' },
isGroup: false,
sessionId: PEER_UIN,
});
expect(store.findRecord('silk_test.amr')?.duration).toBe(3);
expect(store.findRecord('uuid-base64-fake')?.fileId).toBe('uuid-base64-fake');
expect(store.findRecord('https://example.com/voice.amr')?.url).toBe('https://example.com/voice.amr');
expect(store.findRecord('nope')).toBeNull();
store.close();
});
it('updates URLs in place across all alias keys', () => {
const store = open('url-update');
store.rememberRecord({
file: 'silk_test.amr',
fileId: 'uuid-base64-fake',
url: '',
fileSize: 1024,
fileName: 'silk_test.amr',
duration: 3,
fileHash: '',
mediaNode: { fileUuid: 'uuid-base64-fake' },
isGroup: false,
sessionId: PEER_UIN,
});
store.updateRecordUrl('silk_test.amr', 'https://refreshed.example.com/voice.amr');
expect(store.findRecord('silk_test.amr')?.url).toBe('https://refreshed.example.com/voice.amr');
expect(store.findRecord('uuid-base64-fake')?.url).toBe('https://refreshed.example.com/voice.amr');
store.close();
});
it('survives close+reopen against the same db path', () => {
const dbPath = tempDbPath('persist');
dbs.push(dbPath);
{
const store = new MediaStore(dbPath);
store.rememberImage({
file: 'abc.png',
url: 'https://example.com/abc.png',
fileSize: 99,
fileName: 'abc.png',
subType: 0,
summary: '',
imageUrl: 'https://example.com/abc.png',
isGroup: true,
sessionId: GROUP_ID,
});
store.close();
}
{
const store = new MediaStore(dbPath);
const found = store.findImage('abc.png');
expect(found).not.toBeNull();
expect(found!.fileSize).toBe(99);
// Alias index must also persist.
expect(store.findImage('https://example.com/abc.png')?.fileSize).toBe(99);
store.close();
}
});
it('evicts old entries beyond the configured cap', () => {
// EVICT_EVERY_N_REMEMBERS = 64 inside the store; we exercise the eviction
// path by writing well past the cap so it triggers at least once.
const cap = 80;
const store = open('evict', cap);
for (let i = 0; i < 200; i++) {
store.rememberImage({
file: `file-${i}.png`,
url: `https://example.com/${i}.png`,
fileSize: i,
fileName: `file-${i}.png`,
subType: 0,
summary: '',
imageUrl: '',
isGroup: true,
sessionId: GROUP_ID,
});
}
const { images } = store.size();
expect(images).toBeLessThanOrEqual(cap);
// Most recent entries should still be present.
expect(store.findImage('file-199.png')?.fileSize).toBe(199);
store.close();
});
});
describe('EventConverter media segment sink → MediaStore wiring', () => {
const dbs: string[] = [];
afterEach(() => {
for (const dbPath of dbs) {
for (const ext of ['', '-wal', '-shm']) {
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
}
}
dbs.length = 0;
});
it('emits sink invocations for image segments with the right context', async () => {
const conv = new EventConverter();
const sinkCalls: Array<{ type: string; isGroup: boolean; sessionId: number; file: string }> = [];
conv.setMediaSegmentSink((type, _element, data, isGroup, sessionId) => {
sinkCalls.push({ type, isGroup, sessionId, file: String(data.file ?? '') });
});
await conv.convert(SELF_UIN, makeGroupMessage([imageElement()]));
await conv.convert(SELF_UIN, makeFriendMessage([recordElement()]));
expect(sinkCalls).toEqual([
{ type: 'image', isGroup: true, sessionId: GROUP_ID, file: 'abc.png' },
{ type: 'record', isGroup: false, sessionId: PEER_UIN, file: 'silk_test.amr' },
]);
});
it('lets the sink populate a MediaStore that get_image-style lookups can use', async () => {
const dbPath = tempDbPath('sink');
dbs.push(dbPath);
const store = new MediaStore(dbPath);
const conv = new EventConverter();
conv.setImageUrlResolver((element) => element.imageUrl ?? '');
conv.setMediaUrlResolver(async (element) => element.url ?? '');
conv.setMediaSegmentSink((type, element, data, isGroup, sessionId) => {
const url = typeof data.url === 'string' ? data.url : '';
const file = typeof data.file === 'string' ? data.file : '';
if (type === 'image') {
store.rememberImage({
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileId ?? '',
subType: element.subType ?? 0,
summary: element.summary ?? '',
imageUrl: element.imageUrl ?? '',
isGroup,
sessionId,
});
} else {
store.rememberRecord({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
});
}
});
await conv.convert(SELF_UIN, makeGroupMessage([imageElement()]));
await conv.convert(SELF_UIN, makeFriendMessage([recordElement()]));
const img = store.findImage('abc.png');
expect(img).not.toBeNull();
expect(img!.url).toBe('https://example.com/abc.png');
expect(img!.fileSize).toBe(4242);
expect(img!.isGroup).toBe(true);
expect(img!.sessionId).toBe(GROUP_ID);
const rec = store.findRecord('silk_test.amr');
expect(rec).not.toBeNull();
expect(rec!.fileId).toBe('uuid-base64-fake');
expect(rec!.duration).toBe(3);
expect(rec!.isGroup).toBe(false);
expect(rec!.sessionId).toBe(PEER_UIN);
// Alias lookup by fileUuid still works.
expect(store.findRecord('uuid-base64-fake')?.fileName).toBe('silk_test.amr');
store.close();
});
it('does not invoke the sink when no media segments are present', async () => {
const conv = new EventConverter();
let calls = 0;
conv.setMediaSegmentSink(() => { calls++; });
await conv.convert(SELF_UIN, makeGroupMessage([{ type: 'text', text: 'hello' }]));
expect(calls).toBe(0);
});
});

View File

@@ -1,8 +1,13 @@
import { describe, it, expect } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { describe, it, expect, vi } from 'vitest';
import { parseMessage } from '../src/onebot/message-parser';
import { buildSendElems } from '../src/bridge/builders/element-builder';
import { MentionExtraSendSchema } from '../src/bridge/proto/action';
import { protoDecode } from '../src/protobuf/decode';
import { makeOidbBaseSchema } from '../src/bridge/proto/oidb';
import { NTV2UploadRichMediaRespSchema } from '../src/bridge/proto/highway';
import { protoDecode, protoEncode } from '../src/protobuf/decode';
describe('parseMessage', () => {
describe('plain text', () => {
@@ -87,6 +92,46 @@ describe('parseMessage', () => {
expect(result[0].url).toBe('https://example.com/img.png');
});
it('parses record segment from data.file', async () => {
const result = await parseMessage(
[{ type: 'record', data: { file: 'file:///tmp/voice.amr' } }] as any,
false,
);
expect(result).toEqual([{ type: 'record', url: 'file:///tmp/voice.amr' }]);
});
it('parses video segment from data.path and preserves thumb', async () => {
const result = await parseMessage(
[{ type: 'video', data: { path: '/tmp/clip.mp4', thumb: '/tmp/clip.png' } }] as any,
false,
);
expect(result).toEqual([{ type: 'video', url: '/tmp/clip.mp4', thumbUrl: '/tmp/clip.png' }]);
});
it('drops video segment with empty source', async () => {
const result = await parseMessage(
[{ type: 'video', data: {} }] as any,
false,
);
expect(result).toEqual([]);
});
it('parses record segment from data.path (NapCat parity)', async () => {
const result = await parseMessage(
[{ type: 'record', data: { path: 'C:\\voices\\hi.silk' } }] as any,
false,
);
expect(result).toEqual([{ type: 'record', url: 'C:\\voices\\hi.silk' }]);
});
it('drops record segment with empty source', async () => {
const result = await parseMessage(
[{ type: 'record', data: {} }] as any,
false,
);
expect(result).toEqual([]);
});
it('parses at segment', async () => {
const result = await parseMessage(
[{ type: 'at', data: { qq: 12345 } }] as any,
@@ -144,6 +189,95 @@ describe('parseMessage', () => {
expect(protoElems[0].text?.str).toBe('@User ');
});
it('skips record send when SendContext is absent (graceful no-bridge path)', async () => {
// Without a SendContext, buildSendElems can't run highway upload —
// it should warn and drop the element instead of throwing into the
// ffmpegAddon (which would explode for callers that don't actually
// need to send).
const elements = await parseMessage(
[
{ type: 'text', data: { text: 'hi ' } },
{ type: 'record', data: { file: '/tmp/x.silk' } },
] as any,
false,
);
const protoElems = await buildSendElems(elements);
// Only the leading text should make it through.
expect(protoElems).toHaveLength(1);
expect(protoElems[0].text?.str).toBe('hi ');
});
it('skips video send when SendContext is absent (graceful no-bridge path)', async () => {
const elements = await parseMessage(
[
{ type: 'text', data: { text: 'hi ' } },
{ type: 'video', data: { file: '/tmp/x.mp4' } },
] as any,
false,
);
const protoElems = await buildSendElems(elements);
expect(protoElems).toHaveLength(1);
expect(protoElems[0].text?.str).toBe('hi ');
});
it('builds video commonElem through NTV2 fast-upload response', async () => {
const videoPath = path.join(os.tmpdir(), `snowluma-video-test-${process.pid}-${Date.now()}.mp4`);
fs.writeFileSync(videoPath, Buffer.from([0, 1, 2, 3]));
const respSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
const responseData = protoEncode({
command: 0x11EA,
subCommand: 100,
errorCode: 0,
body: {
respHead: { retCode: 0, message: '' },
upload: {
uKey: '',
msgInfo: {
msgInfoBody: [
{ index: { fileUuid: 'video-uuid' }, fileExist: true },
{ index: { fileUuid: 'thumb-uuid' }, fileExist: true },
],
extBizInfo: {
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
},
},
subFileInfos: [{ uKey: '' }],
},
},
errorMsg: '',
reserved: 1,
}, respSchema);
const bridge = {
qqInfo: { uin: '10000' },
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData,
})),
} as any;
try {
const protoElems = await buildSendElems([{
type: 'video',
url: videoPath,
thumbUrl: 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
}], { bridge, groupId: 123456 });
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
expect(bridge.sendRawPacket).toHaveBeenCalledWith('OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array));
expect(protoElems).toHaveLength(1);
expect(protoElems[0].commonElem?.serviceType).toBe(48);
expect(protoElems[0].commonElem?.businessType).toBe(21);
expect(protoElems[0].commonElem?.pbElem).toBeInstanceOf(Uint8Array);
} finally {
try { fs.unlinkSync(videoPath); } catch { /* ignore */ }
}
});
it('parses multiple segments', async () => {
const result = await parseMessage(
[

View File

@@ -0,0 +1,180 @@
import { describe, expect, it } from 'vitest';
import { IOneBotNetworkAdapter, NetworkReloadType, OneBotNetworkManager } from '../src/onebot/network';
import type { NetworkAdapterContext } from '../src/onebot/network';
import type { JsonObject, NetworkBase } from '../src/onebot/types';
import type { DispatchPayload } from '../src/onebot/event-filter';
interface FakeNetworkConfig extends NetworkBase {
// Allows tests to influence behavior via config:
failOnEvent?: boolean;
}
class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
events: JsonObject[] = [];
opens = 0;
closes = 0;
reloads = 0;
// Last dispatch payload object identity, to assert it was reused per emit.
lastPayloads: DispatchPayload[] = [];
open(): void {
this.opens++;
if (this.config.enabled !== false) this.isEnabled = true;
}
close(): void {
this.closes++;
this.isEnabled = false;
}
reload(next: FakeNetworkConfig): NetworkReloadType {
this.reloads++;
this.config = structuredClone(next);
if (next.enabled === false && this.isEnabled) {
this.close();
return NetworkReloadType.Closed;
}
if (next.enabled !== false && !this.isEnabled) {
this.open();
return NetworkReloadType.Opened;
}
return NetworkReloadType.Normal;
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
this.events.push(event);
this.lastPayloads.push(payload);
if (this.config.failOnEvent) throw new Error('boom');
}
}
const NULL_CTX: NetworkAdapterContext = {
uin: '10001',
api: { handle: async () => ({ status: 'failed', retcode: 0, data: null }), processRequest: async () => '' } as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
};
function makeAdapter(name: string, partial: Partial<FakeNetworkConfig> = {}): FakeAdapter {
const config: FakeNetworkConfig = {
name,
enabled: true,
messageFormat: 'array',
reportSelfMessage: false,
...partial,
};
return new FakeAdapter(name, config, NULL_CTX);
}
const SAMPLE_EVENT: JsonObject = {
time: 1,
self_id: 10001,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 1,
user_id: 22222,
message: [{ type: 'text', data: { text: 'hi' } }],
raw_message: 'hi',
font: 0,
sender: { user_id: 22222, nickname: 'peer', sex: 'unknown', age: 0 },
};
describe('OneBotNetworkManager', () => {
it('opens and emits to every active adapter in parallel', async () => {
const mgr = new OneBotNetworkManager();
const a = makeAdapter('a');
const b = makeAdapter('b');
mgr.register(a);
mgr.register(b);
await mgr.openAll();
expect(a.opens).toBe(1);
expect(b.opens).toBe(1);
await mgr.emitEvent(SAMPLE_EVENT);
expect(a.events).toEqual([SAMPLE_EVENT]);
expect(b.events).toEqual([SAMPLE_EVENT]);
// Both adapters should receive the same payload reference (built once).
expect(a.lastPayloads[0]).toBe(b.lastPayloads[0]);
});
it('skips inactive adapters during emit', async () => {
const mgr = new OneBotNetworkManager();
const active = makeAdapter('active');
const idle = makeAdapter('idle', { enabled: false });
mgr.register(active);
mgr.register(idle);
await mgr.openAll();
await mgr.emitEvent(SAMPLE_EVENT);
expect(active.events).toHaveLength(1);
expect(idle.events).toHaveLength(0);
});
it('isolates adapter errors so one bad adapter does not block others', async () => {
const mgr = new OneBotNetworkManager();
const ok = makeAdapter('ok');
const bad = makeAdapter('bad', { failOnEvent: true });
mgr.register(ok);
mgr.register(bad);
await mgr.openAll();
await mgr.emitEvent(SAMPLE_EVENT);
// The good adapter still saw the event.
expect(ok.events).toHaveLength(1);
// The bad adapter logged the throw but didn't crash the manager.
expect(bad.events).toHaveLength(1);
});
it('replaces an existing adapter under the same name and closes the old one', async () => {
const mgr = new OneBotNetworkManager();
const first = makeAdapter('dup');
mgr.register(first);
await mgr.openAll();
const second = makeAdapter('dup');
mgr.register(second);
expect(mgr.get('dup')).toBe(second);
expect(first.closes).toBe(1);
});
it('closeOne shuts down a single adapter and removes it', async () => {
const mgr = new OneBotNetworkManager();
const a = makeAdapter('a');
const b = makeAdapter('b');
mgr.register(a);
mgr.register(b);
await mgr.openAll();
await mgr.closeOne('a');
expect(mgr.has('a')).toBe(false);
expect(a.closes).toBe(1);
expect(b.closes).toBe(0);
expect(mgr.hasActiveAdapters()).toBe(true);
});
it('closeAll clears every adapter', async () => {
const mgr = new OneBotNetworkManager();
const a = makeAdapter('a');
const b = makeAdapter('b');
mgr.register(a);
mgr.register(b);
await mgr.openAll();
await mgr.closeAll();
expect(mgr.list()).toHaveLength(0);
expect(a.closes).toBe(1);
expect(b.closes).toBe(1);
});
it('hasActiveAdapters reflects current state', async () => {
const mgr = new OneBotNetworkManager();
expect(mgr.hasActiveAdapters()).toBe(false);
const a = makeAdapter('a');
mgr.register(a);
expect(mgr.hasActiveAdapters()).toBe(false);
await mgr.openAll();
expect(mgr.hasActiveAdapters()).toBe(true);
await mgr.closeAll();
expect(mgr.hasActiveAdapters()).toBe(false);
});
});

View File

@@ -26,7 +26,7 @@ const nativeSrc = toPosix(nativeDir);
// Target selection: `SNOWLUMA_TARGET=<platform>-<arch>` overrides the host
// detection, enabling cross-target packaging on CI.
const targetTriple = process.env.SNOWLUMA_TARGET ?? `${process.platform}-${process.arch}`;
const targetPlatform = targetTriple.split('-')[0];
const [targetPlatform, targetArch] = targetTriple.split('-');
// Runtime scaffolding files copied into dist/. The NTQQ hook is Windows-only,
// so its launcher/shell script differ per target.
@@ -47,12 +47,22 @@ const nativeFiles = [
: []),
];
// FFmpeg native addon ported from NapCat. Uses NapCat's
// `<platform>.<arch>` naming so the prebuilt binaries can be vendored
// as-is without renaming. Lives under `native/ffmpeg/` to keep it
// separate from the SnowLuma flat-naming addons above.
const ffmpegAddonFile = `ffmpegAddon.${targetPlatform}.${targetArch}.node`;
const ffmpegSrcDir = path.resolve(nativeDir, 'ffmpeg');
// Fail fast if any expected native binary is missing from packages/runtime/native/.
// vite-plugin-cp only emits a warning on missing source files; we want a hard
// error so CI can't accidentally ship an incomplete archive.
const missingNatives = nativeFiles.filter(
(f) => !fs.existsSync(path.join(nativeDir, f)),
);
if (!fs.existsSync(path.join(ffmpegSrcDir, ffmpegAddonFile))) {
missingNatives.push(`ffmpeg/${ffmpegAddonFile}`);
}
if (missingNatives.length > 0) {
throw new Error(
`Missing native binaries for target ${targetTriple}:\n` +
@@ -73,6 +83,11 @@ const BaseConfigPlugin: PluginOption[] = [
dest: path.join(distDir, 'native'),
flatten: true,
})),
{
src: `${toPosix(ffmpegSrcDir)}/${ffmpegAddonFile}`,
dest: path.join(distDir, 'native', 'ffmpeg'),
flatten: true,
},
]
})
];

View File

@@ -0,0 +1,8 @@
# Changelog
## 0.1.0
- Initial SnowLuma TypeScript SDK package.
- Added HTTP and WebSocket clients for OneBot APIs.
- Added event middleware, command matching, request context helpers, and message chain builders.
- Added structured SDK error classes and per-request `AbortSignal` support.

259
packages/sdk/README.md Normal file
View File

@@ -0,0 +1,259 @@
# @snowluma/sdk
SnowLuma 的 TypeScript SDK,提供 OneBot HTTP / WebSocket 客户端、事件中间件、命令匹配和消息链式构造器。
## 导航
- [安装](#安装)
- [快速开始](#快速开始)
- [HTTP Client](#http-client)
- [WebSocket Client](#websocket-client)
- [事件中间件与命令](#事件中间件与命令)
- [Raw Action](#raw-action)
- [Message Builder](#message-builder)
- [请求控制](#请求控制)
- [错误处理](#错误处理)
- [测试建议](#测试建议)
- [子路径导入](#子路径导入)
- [Action 同步](#action-同步)
- [项目结构](#项目结构)
- [版本策略](#版本策略)
## 安装
在本 monorepo 内直接通过 workspace 引用:
```bash
pnpm add @snowluma/sdk --workspace
```
发布到 npm 后可直接安装:
```bash
pnpm add @snowluma/sdk
```
## 快速开始
```ts
import { SnowLumaHttpClient, text } from '@snowluma/sdk';
const bot = new SnowLumaHttpClient({
baseUrl: 'http://127.0.0.1:3000/',
accessToken: process.env.SNOWLUMA_TOKEN,
});
const login = await bot.getLoginInfo();
await bot.sendGroupMessage(123456, text(`Hello from ${login.nickname}`).at('all'));
```
SnowLuma 的 OneBot HTTP / WebSocket 端口和 `accessToken` 来自 `config/onebot_<uin>.json`。
## HTTP Client
```ts
import { SnowLumaHttpClient, message, text } from '@snowluma/sdk';
const bot = new SnowLumaHttpClient({
baseUrl: 'http://127.0.0.1:3000/',
accessToken: process.env.SNOWLUMA_TOKEN,
requestTimeoutMs: 30_000,
});
await bot.sendPrivateMessage(10001, text('pong'));
await bot.sendGroupMessage(123456, [
message.text('Hello'),
message.at('all'),
]);
```
## WebSocket Client
WebSocket 客户端会用 `echo` 关联 API 响应,并把无 `echo` 的包作为事件分发。
```ts
import { SnowLumaWebSocketClient, text } from '@snowluma/sdk';
const bot = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
accessToken: process.env.SNOWLUMA_TOKEN,
reconnect: true,
});
bot.onGroupMessage(async (event, ctx) => {
if (event.raw_message === '/ping') {
await ctx.reply(text('pong').at(event.user_id));
}
});
bot.onRequest('friend', async (_event, ctx) => {
await ctx.approve();
});
await bot.connect();
await bot.sendPrivateMessage(10001, text('ready'));
```
## 事件中间件与命令
```ts
bot.use(async (event, ctx, next) => {
console.log(event.post_type);
await next();
});
bot.command('echo', async (_event, ctx, match) => {
await ctx.reply(text(match.rest || 'empty'));
});
bot.when(
(event) => event.post_type === 'notice',
async (event) => console.log(event),
);
```
事件上下文内置快捷操作:
- `ctx.reply(message)`:按私聊/群聊自动回复。
- `ctx.approve()` / `ctx.reject(reason)`:处理好友或群请求。
- `ctx.quickOperation(operation)`:调用 `.handle_quick_operation`。
- `ctx.stopPropagation()`:停止后续中间件和普通 `onEvent` 分发。
## Raw Action
高频接口提供 camelCase 方法;其它 SnowLuma action 可以用 `raw` 或 `rawResponse`:
```ts
const data = await bot.raw('get_group_file_system_info', {
group_id: 123456,
});
const response = await bot.rawResponse('get_status');
```
`raw` 会在 SnowLuma 返回 `status: "failed"` 或非零 `retcode` 时抛出 `SnowLumaApiError`;`rawResponse` 会保留完整响应。
## Message Builder
```ts
import { fromCQString, message, text, toCQString } from '@snowluma/sdk';
const segments = [
message.reply(42),
message.text('收到 '),
message.image('https://example.com/a.png'),
];
const chained = text('收到 ')
.at(10001)
.image('https://example.com/a.png');
const cq = toCQString(segments);
const chainedCq = toCQString(chained);
const parsed = fromCQString('hi[CQ:at,qq=all]');
```
链式入口返回 `MessageChain`,可以直接传给发送接口,也可以用 `build()` / `toSegments()` 转成 OneBot segment 数组:
```ts
await bot.sendGroupMessage(123456, text('hi').at(10001).image('/tmp/a.png'));
const segments = text('hi').at('all').build();
await text('hi').atAll().br().face(14).sendToGroup(bot, 123456);
```
`reply()` 在一条链中只能出现一次;TypeScript 会阻止 `text('a').reply(1).reply(2)`,运行时也会做同样检查。
已内置常用段:`text`、`br`、`face`、`at`、`atAll`、`reply`、`image`、`record`、`video`、`json`、`xml`、`poke`、`forward`、`node`、`share`、`music`、`location`、`contact` 和 `raw`。
## 请求控制
每次请求都支持覆盖 `echo`、超时和 `AbortSignal`:
```ts
const controller = new AbortController();
const status = bot.getStatus({
echo: 'healthcheck',
timeoutMs: 5_000,
signal: controller.signal,
});
controller.abort();
await status;
```
`timeoutMs: 0` 表示关闭该请求的超时控制。
## 错误处理
SDK 暴露统一错误基类和更具体的错误类型:
- `SnowLumaApiError`:OneBot 响应失败或 `retcode !== 0`。
- `SnowLumaAuthError`:鉴权相关 retcode,例如 `1401`、`401`、`403`。
- `SnowLumaTransportError`:连接、解析、超时、取消等传输层错误基类。
- `SnowLumaConnectionError`:HTTP fetch / WebSocket 连接或发送失败。
- `SnowLumaParseError`:响应不是合法 JSON 或不符合 OneBot 响应结构。
- `SnowLumaTimeoutError`:请求超过 `timeoutMs`。
- `SnowLumaAbortError`:调用方通过 `AbortSignal` 主动取消。
```ts
import {
SnowLumaApiError,
SnowLumaAuthError,
SnowLumaTimeoutError,
} from '@snowluma/sdk';
try {
await bot.getStatus({ timeoutMs: 1000 });
} catch (error) {
if (error instanceof SnowLumaAuthError) {
throw new Error('SnowLuma access token is invalid');
}
if (error instanceof SnowLumaTimeoutError) {
console.warn(`SnowLuma did not respond in ${error.timeoutMs}ms`);
}
if (error instanceof SnowLumaApiError) {
console.warn(error.retcode, error.wording);
}
}
```
## 测试建议
- SDK 自身使用 Vitest 覆盖消息构造、事件上下文、WebSocket 响应关联、错误模型和取消逻辑。
- 对接真实 SnowLuma 时建议使用单独测试账号和测试群,避免把自动化消息发到生产环境。
- 集成测试里优先显式设置 `echo` 和较短 `timeoutMs`,这样失败时更容易定位是哪一次 action。
- 发布前运行 `pnpm --filter @snowluma/sdk typecheck`、`pnpm --filter @snowluma/sdk test`、`pnpm --filter @snowluma/sdk build`。
## 子路径导入
```ts
import { SnowLumaHttpClient } from '@snowluma/sdk/client';
import { text } from '@snowluma/sdk/messages';
import { isMessageEvent } from '@snowluma/sdk/events';
import { SnowLumaApiError } from '@snowluma/sdk/errors';
```
根入口 `@snowluma/sdk` 仍导出正式公开 API;不再保留旧的根级兼容 barrel 或别名 API。
## Action 同步
SDK 导出 `SNOWLUMA_ACTIONS` 和 `isSnowLumaAction()`。测试会扫描 `packages/core/src/onebot/actions/*.ts` 的 `registerAction()`,确保 SDK action 列表没有落后。
## 项目结构
```text
src/
client/ HTTP / WebSocket client 与 API facade
events/ 事件上下文、类型守卫、中间件和命令匹配
messages/ segment 工厂、MessageChain、CQ 编解码
types/ JSON、消息、事件、action 参数和返回类型
internal/ SDK 内部工具
```
## 版本策略
当前包版本为 `0.1.0`。版本规则、发布检查清单和破坏性变更边界见 [VERSIONING.md](./VERSIONING.md)。

View File

@@ -0,0 +1,43 @@
# @snowluma/sdk Versioning
The SDK follows SemVer for its public package surface:
- Exported runtime values and classes from `@snowluma/sdk`.
- Exported types from `@snowluma/sdk` and `@snowluma/sdk/types`.
- Supported subpath exports: `client`, `messages`, `events`, `errors`, `actions`, and `types`.
- Runtime behavior of typed client helpers, message builders, event helpers, and SDK error classes.
## Current 0.x Policy
While the SDK is below `1.0.0`, breaking changes should use a minor release and include a migration note. Patch releases should remain bug fixes only.
Examples:
- `0.1.1`: bug fix, doc fix, type refinement that does not break consumers.
- `0.2.0`: new client helper, new event helper, new action typing, or documented breaking change before 1.0.
- `1.0.0`: first stable release where breaking changes move to major versions.
## After 1.0
- Major: removes or changes a public export, changes runtime behavior incompatibly, changes supported Node version, or changes package subpaths.
- Minor: adds new public API, supports new SnowLuma actions, adds optional parameters, or adds error subclasses.
- Patch: fixes bugs, improves docs, narrows implementation details without breaking public types, or updates action metadata without changing call signatures.
## Release Checklist
1. Update `packages/sdk/package.json` version.
2. Update `packages/sdk/CHANGELOG.md`.
3. Run `pnpm --filter @snowluma/sdk typecheck`.
4. Run `pnpm --filter @snowluma/sdk test`.
5. Run `pnpm --filter @snowluma/sdk build`.
6. Run `pnpm --filter @snowluma/sdk pack --dry-run` to inspect published files.
## Automated npm Publish
`.github/workflows/sdk-npm-publish.yml` publishes `@snowluma/sdk` when SDK-related files reach `main`, including the automated `dev` to `main` promotion flow. The publish job uses the GitHub Environment named `SnowLuma` and expects an environment secret named `NPM_TOKEN`.
If the package version already exists on npm, the workflow skips publishing that run. Bump `packages/sdk/package.json` before merging SDK changes that should create a new npm release.
## Action Compatibility
SnowLuma action coverage is synchronized from `packages/core/src/onebot/actions/*.ts`. Adding an action type is a minor change unless it changes an existing method signature or return type.

95
packages/sdk/package.json Normal file
View File

@@ -0,0 +1,95 @@
{
"name": "@snowluma/sdk",
"author": {
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "0.1.0",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
"onebot",
"onebot11",
"qq",
"bot",
"sdk"
],
"homepage": "https://github.com/SnowLuma/SnowLuma#readme",
"bugs": {
"url": "https://github.com/SnowLuma/SnowLuma/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/SnowLuma/SnowLuma.git",
"directory": "packages/sdk"
},
"license": "UNLICENSED",
"type": "module",
"sideEffects": false,
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./client": {
"types": "./dist/client/index.d.ts",
"import": "./dist/client/index.js"
},
"./messages": {
"types": "./dist/messages/index.d.ts",
"import": "./dist/messages/index.js"
},
"./events": {
"types": "./dist/events/index.d.ts",
"import": "./dist/events/index.js"
},
"./types": {
"types": "./dist/types/index.d.ts",
"import": "./dist/types/index.js"
},
"./errors": {
"types": "./dist/errors.d.ts",
"import": "./dist/errors.js"
},
"./actions": {
"types": "./dist/actions.d.ts",
"import": "./dist/actions.js"
},
"./package.json": "./package.json"
},
"files": [
"dist/actions.*",
"dist/client",
"dist/emitter.*",
"dist/errors.*",
"dist/events",
"dist/index.*",
"dist/internal",
"dist/messages",
"dist/types",
"README.md",
"CHANGELOG.md",
"VERSIONING.md"
],
"scripts": {
"clean": "node -e \"const fs = require('node:fs'); fs.rmSync('dist', { recursive: true, force: true })\"",
"prebuild": "pnpm run clean",
"build": "tsc -p tsconfig.json",
"prepack": "pnpm run build",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"publishConfig": {
"access": "public"
},
"engines": {
"node": ">=22"
},
"devDependencies": {
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vitest": "^4.1.4"
}
}

126
packages/sdk/src/actions.ts Normal file
View File

@@ -0,0 +1,126 @@
import type { SnowLumaActionMap } from './types/index';
export const SNOWLUMA_ACTIONS = [
'get_login_info',
'get_status',
'get_version_info',
'can_send_image',
'can_send_record',
'send_msg',
'send_private_msg',
'send_group_msg',
'get_msg',
'delete_msg',
'get_friend_list',
'get_stranger_info',
'delete_friend',
'get_group_list',
'get_group_info',
'get_group_member_list',
'get_group_member_info',
'get_group_honor_info',
'get_group_system_msg',
'set_group_kick',
'set_group_ban',
'set_group_whole_ban',
'set_group_admin',
'set_group_card',
'set_group_name',
'set_group_leave',
'set_group_special_title',
'set_group_anonymous',
'set_group_anonymous_ban',
'set_group_portrait',
'upload_group_file',
'upload_private_file',
'get_group_file_url',
'get_group_root_files',
'get_group_files_by_folder',
'delete_group_file',
'move_group_file',
'create_group_file_folder',
'delete_group_file_folder',
'rename_group_file_folder',
'get_private_file_url',
'set_friend_add_request',
'set_group_add_request',
'send_like',
'friend_poke',
'group_poke',
'send_poke',
'set_essence_msg',
'delete_essence_msg',
'get_essence_msg_list',
'set_group_reaction',
'get_group_msg_history',
'get_friend_msg_history',
'mark_group_msg_as_read',
'mark_private_msg_as_read',
'mark_msg_as_read',
'get_rkey',
'ocr_image',
'.ocr_image',
'_send_group_notice',
'_get_group_notice',
'_del_group_notice',
'upload_forward_msg',
'upload_foward_msg',
'send_forward_msg',
'send_group_forward_msg',
'send_private_forward_msg',
'get_forward_msg',
'get_image',
'get_record',
'get_cookies',
'get_csrf_token',
'get_credentials',
'set_restart',
'clean_cache',
'.handle_quick_operation',
'set_friend_remark',
'set_msg_emoji_like',
'_mark_all_as_read',
'get_group_file_system_info',
'check_url_safely',
'download_file',
'set_qq_profile',
'set_online_status',
'get_group_ignored_notifies',
'get_group_shut_list',
'forward_friend_single_msg',
'forward_group_single_msg',
'get_recent_contact',
'get_profile_like',
'get_friends_with_category',
'get_online_clients',
'_get_model_show',
'_set_model_show',
'.get_word_slices',
'get_group_at_all_remain',
'get_unidirectional_friend_list',
'set_self_longnick',
'get_collection_list',
'create_collection',
'set_qq_avatar',
'set_input_status',
'translate_en2zh',
'get_clientkey',
'get_mini_app_ark',
'click_inline_keyboard_button',
'set_group_sign',
'send_group_sign',
'get_group_info_ex',
'get_group_detail_info',
'trans_group_file',
'rename_group_file',
'get_file',
'.send_packet',
] as const satisfies readonly (keyof SnowLumaActionMap)[];
export type SnowLumaKnownAction = typeof SNOWLUMA_ACTIONS[number];
const ACTION_SET = new Set<string>(SNOWLUMA_ACTIONS);
export function isSnowLumaAction(action: string): action is SnowLumaKnownAction {
return ACTION_SET.has(action);
}

View File

@@ -0,0 +1,470 @@
import { createSnowLumaApiError } from '../errors';
import { normalizeMessage } from '../messages/index';
import type {
ActionParams,
ActionResult,
ApiResponse,
DomainParams,
DownloadFileParams,
ForwardMessageParams,
GetForwardMsgParams,
GetFriendMessageHistoryParams,
GetGroupHonorInfoParams,
GetGroupMessageHistoryParams,
GetMediaParams,
JsonObject,
JsonValue,
OutgoingMessage,
PrivateForwardMessageParams,
RequestOptions,
SendMsgParams,
SetGroupReactionParams,
SnowLumaAction,
} from '../types/index';
/**
* Base class for SnowLuma API clients.
*
* Concrete transports implement request(); this facade adds typed OneBot actions,
* message normalization, and failed-response error handling.
*/
export abstract class SnowLumaApiClient {
/** Sends a raw OneBot action and returns the complete API response. */
abstract request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>>;
/** Sends a OneBot action and returns data, throwing SnowLumaApiError on failed responses. */
async call<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ActionResult<TAction>> {
const response = await this.request(action, params, options);
if (response.status !== 'ok' || response.retcode !== 0) {
throw createSnowLumaApiError(response);
}
return response.data;
}
getLoginInfo(options?: RequestOptions) {
return this.call('get_login_info', {}, options);
}
getStatus(options?: RequestOptions) {
return this.call('get_status', {}, options);
}
getVersionInfo(options?: RequestOptions) {
return this.call('get_version_info', {}, options);
}
canSendImage(options?: RequestOptions) {
return this.call('can_send_image', {}, options);
}
canSendRecord(options?: RequestOptions) {
return this.call('can_send_record', {}, options);
}
sendMsg(params: Omit<SendMsgParams, 'message'> & { message: OutgoingMessage }, options?: RequestOptions) {
return this.call('send_msg', { ...params, message: normalizeMessage(params.message) as JsonValue }, options);
}
sendPrivateMessage(userId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }) {
return this.call('send_private_msg', {
user_id: userId,
message: normalizeMessage(message) as JsonValue,
auto_escape: options?.autoEscape,
}, options);
}
sendGroupMessage(groupId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }) {
return this.call('send_group_msg', {
group_id: groupId,
message: normalizeMessage(message) as JsonValue,
auto_escape: options?.autoEscape,
}, options);
}
getMessage(messageId: number, options?: RequestOptions) {
return this.call('get_msg', { message_id: messageId }, options);
}
deleteMessage(messageId: number, options?: RequestOptions) {
return this.call('delete_msg', { message_id: messageId }, options);
}
getFriendList(options?: RequestOptions) {
return this.call('get_friend_list', {}, options);
}
getStrangerInfo(userId: number, options?: RequestOptions) {
return this.call('get_stranger_info', { user_id: userId }, options);
}
deleteFriend(userId: number, options?: RequestOptions & { block?: boolean }) {
return this.call('delete_friend', { user_id: userId, block: options?.block }, options);
}
getGroupList(options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_list', { no_cache: options?.noCache }, options);
}
getGroupInfo(groupId: number, options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_info', { group_id: groupId, no_cache: options?.noCache }, options);
}
getGroupMemberList(groupId: number, options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_member_list', { group_id: groupId, no_cache: options?.noCache }, options);
}
getGroupMemberInfo(groupId: number, userId: number, options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_member_info', {
group_id: groupId,
user_id: userId,
no_cache: options?.noCache,
}, options);
}
getGroupHonorInfo(params: GetGroupHonorInfoParams, options?: RequestOptions) {
return this.call('get_group_honor_info', params, options);
}
getGroupSystemMessages(options?: RequestOptions) {
return this.call('get_group_system_msg', {}, options);
}
setGroupKick(groupId: number, userId: number, options?: RequestOptions & { rejectAddRequest?: boolean }) {
return this.call('set_group_kick', {
group_id: groupId,
user_id: userId,
reject_add_request: options?.rejectAddRequest,
}, options);
}
setGroupBan(groupId: number, userId: number, duration?: number, options?: RequestOptions) {
return this.call('set_group_ban', { group_id: groupId, user_id: userId, duration }, options);
}
setGroupWholeBan(groupId: number, enable = true, options?: RequestOptions) {
return this.call('set_group_whole_ban', { group_id: groupId, enable }, options);
}
setGroupAdmin(groupId: number, userId: number, enable = true, options?: RequestOptions) {
return this.call('set_group_admin', { group_id: groupId, user_id: userId, enable }, options);
}
setGroupCard(groupId: number, userId: number, card = '', options?: RequestOptions) {
return this.call('set_group_card', { group_id: groupId, user_id: userId, card }, options);
}
setGroupName(groupId: number, name: string, options?: RequestOptions) {
return this.call('set_group_name', { group_id: groupId, group_name: name }, options);
}
setGroupLeave(groupId: number, options?: RequestOptions) {
return this.call('set_group_leave', { group_id: groupId }, options);
}
setGroupSpecialTitle(groupId: number, userId: number, title = '', options?: RequestOptions) {
return this.call('set_group_special_title', {
group_id: groupId,
user_id: userId,
special_title: title,
}, options);
}
uploadGroupFile(groupId: number, file: string, options: RequestOptions & {
name?: string;
folder?: string;
folderId?: string;
uploadFile?: boolean;
} = {}) {
return this.call('upload_group_file', {
group_id: groupId,
file,
name: options.name,
folder: options.folder,
folder_id: options.folderId,
upload_file: options.uploadFile,
}, options);
}
uploadPrivateFile(userId: number, file: string, options: RequestOptions & {
name?: string;
uploadFile?: boolean;
} = {}) {
return this.call('upload_private_file', {
user_id: userId,
file,
name: options.name,
upload_file: options.uploadFile,
}, options);
}
getGroupFileUrl(groupId: number, fileId: string, options?: RequestOptions & { busid?: number }) {
return this.call('get_group_file_url', { group_id: groupId, file_id: fileId, busid: options?.busid }, options);
}
getGroupRootFiles(groupId: number, options?: RequestOptions) {
return this.call('get_group_root_files', { group_id: groupId }, options);
}
getGroupFilesByFolder(groupId: number, folderId = '/', options?: RequestOptions) {
return this.call('get_group_files_by_folder', { group_id: groupId, folder_id: folderId }, options);
}
deleteGroupFile(groupId: number, fileId: string, options?: RequestOptions) {
return this.call('delete_group_file', { group_id: groupId, file_id: fileId }, options);
}
moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string, options?: RequestOptions) {
return this.call('move_group_file', {
group_id: groupId,
file_id: fileId,
parent_directory: parentDirectory,
target_directory: targetDirectory,
}, options);
}
createGroupFileFolder(groupId: number, name: string, parentId = '/', options?: RequestOptions) {
return this.call('create_group_file_folder', { group_id: groupId, name, parent_id: parentId }, options);
}
deleteGroupFileFolder(groupId: number, folderId: string, options?: RequestOptions) {
return this.call('delete_group_file_folder', { group_id: groupId, folder_id: folderId }, options);
}
renameGroupFileFolder(groupId: number, folderId: string, newName: string, options?: RequestOptions) {
return this.call('rename_group_file_folder', {
group_id: groupId,
folder_id: folderId,
new_folder_name: newName,
}, options);
}
getPrivateFileUrl(userId: number, fileId: string, fileHash: string, options?: RequestOptions) {
return this.call('get_private_file_url', { user_id: userId, file_id: fileId, file_hash: fileHash }, options);
}
setFriendAddRequest(flag: string, approve = true, options?: RequestOptions) {
return this.call('set_friend_add_request', { flag, approve }, options);
}
setGroupAddRequest(flag: string, params: RequestOptions & {
subType?: string;
type?: string;
approve?: boolean;
reason?: string;
} = {}) {
return this.call('set_group_add_request', {
flag,
sub_type: params.subType,
type: params.type,
approve: params.approve,
reason: params.reason,
}, params);
}
sendLike(userId: number, times = 1, options?: RequestOptions) {
return this.call('send_like', { user_id: userId, times }, options);
}
friendPoke(userId: number, options?: RequestOptions & { targetId?: number }) {
return this.call('friend_poke', { user_id: userId, target_id: options?.targetId }, options);
}
groupPoke(groupId: number, userId: number, options?: RequestOptions) {
return this.call('group_poke', { group_id: groupId, user_id: userId }, options);
}
sendPoke(userId: number, options?: RequestOptions & { groupId?: number }) {
return this.call('send_poke', { user_id: userId, group_id: options?.groupId }, options);
}
setEssenceMessage(messageId: number, options?: RequestOptions) {
return this.call('set_essence_msg', { message_id: messageId }, options);
}
deleteEssenceMessage(messageId: number, options?: RequestOptions) {
return this.call('delete_essence_msg', { message_id: messageId }, options);
}
getEssenceMessageList(groupId: number, options?: RequestOptions) {
return this.call('get_essence_msg_list', { group_id: groupId }, options);
}
setGroupReaction(params: SetGroupReactionParams, options?: RequestOptions) {
return this.call('set_group_reaction', params, options);
}
getGroupMessageHistory(params: GetGroupMessageHistoryParams, options?: RequestOptions) {
return this.call('get_group_msg_history', params, options);
}
getFriendMessageHistory(params: GetFriendMessageHistoryParams, options?: RequestOptions) {
return this.call('get_friend_msg_history', params, options);
}
markGroupMessageAsRead(messageId: number, groupId?: number, options?: RequestOptions) {
return this.call('mark_group_msg_as_read', { message_id: messageId, group_id: groupId }, options);
}
markPrivateMessageAsRead(messageId: number, userId?: number, options?: RequestOptions) {
return this.call('mark_private_msg_as_read', { message_id: messageId, user_id: userId }, options);
}
markMessageAsRead(messageId: number, targetId?: number, options?: RequestOptions) {
return this.call('mark_msg_as_read', { message_id: messageId, target_id: targetId }, options);
}
getRKey(options?: RequestOptions) {
return this.call('get_rkey', {}, options);
}
sendGroupNotice(groupId: number, content: string, options: RequestOptions & {
image?: string;
pinned?: number;
type?: number;
confirmRequired?: number;
} = {}) {
return this.call('_send_group_notice', {
group_id: groupId,
content,
image: options.image,
pinned: options.pinned,
type: options.type,
confirm_required: options.confirmRequired,
}, options);
}
getGroupNotice(groupId: number, options?: RequestOptions) {
return this.call('_get_group_notice', { group_id: groupId }, options);
}
uploadForwardMessage(params: ForwardMessageParams, options?: RequestOptions) {
return this.call('upload_forward_msg', params, options);
}
sendForwardMessage(params: ForwardMessageParams, options?: RequestOptions) {
return this.call('send_forward_msg', params, options);
}
sendGroupForwardMessage(groupId: number, messages: OutgoingMessage, options?: RequestOptions) {
return this.call('send_group_forward_msg', {
group_id: groupId,
messages: normalizeMessage(messages) as JsonValue,
}, options);
}
sendPrivateForwardMessage(userId: number, messages: OutgoingMessage, options?: RequestOptions) {
return this.call('send_private_forward_msg', {
user_id: userId,
messages: normalizeMessage(messages) as JsonValue,
}, options);
}
getForwardMessage(params: GetForwardMsgParams, options?: RequestOptions) {
return this.call('get_forward_msg', params, options);
}
getImage(params: GetMediaParams, options?: RequestOptions) {
return this.call('get_image', params, options);
}
getRecord(params: GetMediaParams, options?: RequestOptions) {
return this.call('get_record', params, options);
}
getCookies(params: DomainParams = {}, options?: RequestOptions) {
return this.call('get_cookies', params, options);
}
getCsrfToken(options?: RequestOptions) {
return this.call('get_csrf_token', {}, options);
}
getCredentials(params: DomainParams = {}, options?: RequestOptions) {
return this.call('get_credentials', params, options);
}
cleanCache(options?: RequestOptions) {
return this.call('clean_cache', {}, options);
}
setFriendRemark(userId: number, remark: string, options?: RequestOptions) {
return this.call('set_friend_remark', { user_id: userId, remark }, options);
}
setMsgEmojiLike(messageId: number, emojiId: string, set = true, options?: RequestOptions) {
return this.call('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId, set }, options);
}
markAllAsRead(options?: RequestOptions) {
return this.call('_mark_all_as_read', {}, options);
}
getGroupFileSystemInfo(groupId: number, options?: RequestOptions) {
return this.call('get_group_file_system_info', { group_id: groupId }, options);
}
checkUrlSafely(options?: RequestOptions) {
return this.call('check_url_safely', {}, options);
}
downloadFile(params: DownloadFileParams, options?: RequestOptions) {
return this.call('download_file', params, options);
}
setQqProfile(params: { nickname?: string; personalNote?: string }, options?: RequestOptions) {
return this.call('set_qq_profile', {
nickname: params.nickname,
personal_note: params.personalNote,
}, options);
}
setOnlineStatus(status: number, params: RequestOptions & { extStatus?: number; batteryStatus?: number } = {}) {
return this.call('set_online_status', {
status,
ext_status: params.extStatus,
battery_status: params.batteryStatus,
}, params);
}
getClientKey(options?: RequestOptions) {
return this.call('get_clientkey', {}, options);
}
getGroupInfoEx(groupId: number, options?: RequestOptions) {
return this.call('get_group_info_ex', { group_id: groupId }, options);
}
getGroupDetailInfo(groupId: number, options?: RequestOptions) {
return this.call('get_group_detail_info', { group_id: groupId }, options);
}
/** Calls any registered SnowLuma action and returns the response data. */
raw<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
) {
return this.call(action, params, options);
}
/** Calls any registered SnowLuma action and preserves the full OneBot response envelope. */
rawResponse<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
) {
return this.request(action, params, options);
}
}
export function toJsonObject(value: JsonObject | undefined): JsonObject {
return value ?? {};
}

View File

@@ -0,0 +1,115 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError,
} from '../errors';
import { SnowLumaApiClient, toJsonObject } from './api-client';
import { createRequestAbortState, isAbortError } from '../internal/abort';
import { assertApiResponse } from '../internal/json';
import type {
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
RequestOptions,
SnowLumaAction,
SnowLumaClientOptions,
} from '../types/index';
/** Options for the HTTP transport client. */
export interface SnowLumaHttpClientOptions extends SnowLumaClientOptions {
/** OneBot HTTP endpoint. Defaults to http://127.0.0.1:3000/. */
baseUrl?: string;
/** Custom fetch implementation for tests or non-standard runtimes. */
fetch?: typeof fetch;
/** Extra headers sent with every request. Authorization is managed by accessToken. */
headers?: Record<string, string>;
}
/** OneBot HTTP client for SnowLuma. */
export class SnowLumaHttpClient extends SnowLumaApiClient {
readonly baseUrl: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
private readonly fetchImpl: typeof fetch;
private readonly headers: Record<string, string>;
constructor(options: SnowLumaHttpClientOptions = {}) {
super();
this.baseUrl = options.baseUrl ?? 'http://127.0.0.1:3000/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.fetchImpl = options.fetch ?? globalThis.fetch;
this.headers = options.headers ?? {};
if (!this.fetchImpl) {
throw new SnowLumaConnectionError('No fetch implementation is available');
}
}
/** Sends one OneBot action over HTTP and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const abort = createRequestAbortState(timeoutMs, options?.signal);
try {
const response = await this.fetchImpl(this.baseUrl, {
method: 'POST',
headers: this.createHeaders(),
body: JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo: options?.echo,
}),
signal: abort.signal,
});
const text = await response.text();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch (error) {
throw new SnowLumaParseError(`SnowLuma returned non-JSON HTTP ${response.status}`, { cause: error });
}
const apiResponse = assertApiResponse(parsed) as ApiResponse<ActionResult<TAction>>;
return apiResponse;
} catch (error) {
if (error instanceof SnowLumaTransportError) throw error;
if (isAbortError(error) || abort.signal.aborted) {
if (abort.isTimedOut()) {
throw new SnowLumaTimeoutError(`SnowLuma request timed out after ${timeoutMs}ms`, timeoutMs, { cause: error });
}
if (abort.isExternallyAborted()) {
throw new SnowLumaAbortError('SnowLuma request aborted', { cause: error });
}
}
throw new SnowLumaConnectionError('SnowLuma HTTP request failed', { cause: error });
} finally {
abort.cleanup();
}
}
private createHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
...this.headers,
};
if (this.accessToken) {
headers.Authorization = `Bearer ${this.accessToken}`;
}
return headers;
}
}
export function createHttpClient(options?: SnowLumaHttpClientOptions): SnowLumaHttpClient {
return new SnowLumaHttpClient(options);
}

View File

@@ -0,0 +1,12 @@
export { SnowLumaApiClient } from './api-client';
export { SnowLumaHttpClient, createHttpClient } from './http-client';
export { SnowLumaWebSocketClient, createWebSocketClient } from './websocket-client';
export type { SnowLumaHttpClientOptions } from './http-client';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './websocket-client';

View File

@@ -0,0 +1,421 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
} from '../errors';
import { Emitter } from '../emitter';
import {
createEventContext,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
matchCommand,
noticeType,
requestType,
type CommandHandler,
type CommandOptions,
type EventHandler,
type EventMiddleware,
type EventPredicate,
} from '../events/index';
import { SnowLumaApiClient, toJsonObject } from './api-client';
import { raceWithAbort, throwIfAborted } from '../internal/abort';
import { appendAccessToken, assertApiResponse, createEcho, echoKey, isJsonObject } from '../internal/json';
import {
addSocketListener,
closeInfo,
normalizeReconnect,
rawToString,
unwrapEventPayload,
unwrapMessagePayload,
WEBSOCKET_CLOSED,
WEBSOCKET_OPEN,
} from './websocket-utils';
import type {
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
JsonValue,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotRequestEvent,
RequestOptions,
SnowLumaAction,
SnowLumaEvent,
WsRole,
} from '../types/index';
import type {
PendingRequest,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketConstructor,
WebSocketLike,
} from './websocket-types';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './websocket-types';
/** OneBot WebSocket client for SnowLuma APIs and realtime events. */
export class SnowLumaWebSocketClient extends SnowLumaApiClient {
readonly url: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
readonly role: WsRole;
private readonly protocols?: string | string[];
private readonly WebSocketCtor: WebSocketConstructor;
private readonly reconnect: ReconnectOptions | null;
private readonly emitter = new Emitter<SnowLumaWebSocketEvents>();
private readonly pending = new Map<string, PendingRequest>();
private readonly middlewares: EventMiddleware[] = [];
private socket: WebSocketLike | null = null;
private connectPromise: Promise<void> | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempts = 0;
private closedByUser = false;
constructor(options: SnowLumaWebSocketClientOptions = {}) {
super();
this.url = options.url ?? 'ws://127.0.0.1:3001/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.role = options.role ?? 'Universal';
this.protocols = options.protocols;
this.WebSocketCtor = options.webSocket ?? globalThis.WebSocket as unknown as WebSocketConstructor;
this.reconnect = normalizeReconnect(options.reconnect);
if (!this.WebSocketCtor) {
throw new SnowLumaConnectionError('No WebSocket implementation is available');
}
}
/** True when the underlying WebSocket is currently open. */
get isConnected(): boolean {
return this.socket?.readyState === WEBSOCKET_OPEN;
}
/** Subscribes to low-level client events. Returns an unsubscribe function. */
on<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.on(event, listener);
}
/** Subscribes to one low-level client event, then automatically unsubscribes. */
once<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.once(event, listener);
}
/** Removes a previously registered low-level client event listener. */
off<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): void {
this.emitter.off(event, listener);
}
/** Subscribes to every SnowLuma event packet. */
onEvent(listener: (event: SnowLumaEvent) => void): () => void {
return this.on('event', listener);
}
/** Adds event middleware to the dispatch pipeline. */
use(middleware: EventMiddleware): () => void {
this.middlewares.push(middleware);
return () => {
const index = this.middlewares.indexOf(middleware);
if (index >= 0) this.middlewares.splice(index, 1);
};
}
/** Runs a handler when a type guard or predicate matches an event. */
when<TEvent extends SnowLumaEvent>(
predicate: EventPredicate<TEvent>,
handler: EventHandler<TEvent>,
): () => void {
return this.use(async (event, context, next) => {
if (predicate(event)) {
await handler(event, context as never);
}
if (!context.stopped) await next();
});
}
onMessage(handler: EventHandler<OneBotMessageEvent>): () => void {
return this.when(isMessageEvent, handler);
}
onPrivateMessage(handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'private' }>>): () => void {
return this.when(isPrivateMessageEvent, handler);
}
onGroupMessage(handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'group' }>>): () => void {
return this.when(isGroupMessageEvent, handler);
}
onNotice(handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(type: string, handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(typeOrHandler: string | EventHandler<OneBotNoticeEvent>, handler?: EventHandler<OneBotNoticeEvent>): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) throw new TypeError('onNotice(type, handler) requires a handler');
return this.when(noticeType(typeOrHandler), handler);
}
return this.when(isNoticeEvent, typeOrHandler);
}
onRequest(handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(type: string, handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(typeOrHandler: string | EventHandler<OneBotRequestEvent>, handler?: EventHandler<OneBotRequestEvent>): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) throw new TypeError('onRequest(type, handler) requires a handler');
return this.when(requestType(typeOrHandler), handler);
}
return this.when(isRequestEvent, typeOrHandler);
}
onMetaEvent(handler: EventHandler<OneBotMetaEvent>): () => void {
return this.when(isMetaEvent, handler);
}
command(
command: string | RegExp,
handler: CommandHandler,
options?: CommandOptions,
): () => void {
return this.onMessage(async (event, context) => {
const matched = matchCommand(event, command, options);
if (!matched) return;
await handler(event, Object.assign(context, { command: matched }), matched);
});
}
/** Connects to SnowLuma's OneBot WebSocket endpoint. */
async connect(): Promise<void> {
if (this.isConnected) return;
if (this.connectPromise) return this.connectPromise;
this.closedByUser = false;
this.connectPromise = new Promise((resolve, reject) => {
const url = appendAccessToken(this.url, this.accessToken);
const socket = new this.WebSocketCtor(url, this.protocols);
this.socket = socket;
const cleanup = [
addSocketListener(socket, 'open', () => {
cleanup.forEach((off) => off());
this.bindSocket(socket);
this.reconnectAttempts = 0;
this.connectPromise = null;
this.emitter.emit('open', undefined);
resolve();
}),
addSocketListener(socket, 'error', (error) => {
this.emitter.emit('error', unwrapEventPayload(error));
}),
addSocketListener(socket, 'close', (...args) => {
cleanup.forEach((off) => off());
this.connectPromise = null;
this.socket = null;
reject(new SnowLumaConnectionError('SnowLuma WebSocket closed before opening'));
this.handleClose(args);
}),
];
});
return this.connectPromise;
}
/** Closes the socket and rejects all pending API requests. */
close(code = 1000, reason = 'normal'): void {
this.closedByUser = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket client closed'));
if (this.socket && this.socket.readyState !== WEBSOCKET_CLOSED) {
this.socket.close(code, reason);
}
this.socket = null;
this.connectPromise = null;
}
/** Sends one OneBot action over WebSocket and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
throwIfAborted(options?.signal);
await raceWithAbort(this.connect(), options?.signal, 'SnowLuma WebSocket request aborted before connection opened');
throwIfAborted(options?.signal);
const socket = this.socket;
if (!socket || socket.readyState !== WEBSOCKET_OPEN) {
throw new SnowLumaConnectionError('SnowLuma WebSocket is not open');
}
const echo = options?.echo ?? createEcho();
const key = echoKey(echo);
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const promise = new Promise<ApiResponse>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | null = null;
let abortListener: (() => void) | undefined;
const cleanup = (): void => {
if (timer) clearTimeout(timer);
if (abortListener) options?.signal?.removeEventListener('abort', abortListener);
};
timer = timeoutMs > 0
? setTimeout(() => {
this.pending.delete(key);
cleanup();
reject(new SnowLumaTimeoutError(`SnowLuma WebSocket request timed out after ${timeoutMs}ms`, timeoutMs));
}, timeoutMs)
: null;
abortListener = () => {
this.pending.delete(key);
cleanup();
reject(new SnowLumaAbortError('SnowLuma WebSocket request aborted', { cause: options?.signal?.reason }));
};
options?.signal?.addEventListener('abort', abortListener, { once: true });
this.pending.set(key, { resolve, reject, timer, cleanup });
});
try {
socket.send(JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo,
}));
} catch (error) {
const pending = this.pending.get(key);
pending?.cleanup?.();
this.pending.delete(key);
throw new SnowLumaConnectionError('Failed to send SnowLuma WebSocket request', { cause: error });
}
return promise as Promise<ApiResponse<ActionResult<TAction>>>;
}
private bindSocket(socket: WebSocketLike): void {
addSocketListener(socket, 'message', (...args) => this.handleMessage(args));
addSocketListener(socket, 'error', (error) => this.emitter.emit('error', unwrapEventPayload(error)));
addSocketListener(socket, 'close', (...args) => this.handleClose(args));
}
private handleMessage(args: unknown[]): void {
const raw = unwrapMessagePayload(args[0]);
this.emitter.emit('raw', raw);
let parsed: unknown;
try {
parsed = JSON.parse(rawToString(raw));
} catch (error) {
this.emitter.emit('error', new SnowLumaParseError('SnowLuma WebSocket returned non-JSON message', { cause: error }));
return;
}
if (isJsonObject(parsed) && parsed.echo !== undefined) {
const key = echoKey(parsed.echo as JsonValue);
const pending = this.pending.get(key);
if (pending) {
this.pending.delete(key);
pending.cleanup?.();
try {
const response = assertApiResponse(parsed);
pending.resolve(response);
this.emitter.emit('response', response);
} catch (error) {
pending.reject(new SnowLumaParseError('SnowLuma WebSocket response is invalid', { cause: error }));
}
return;
}
}
if (isJsonObject(parsed) && typeof parsed.post_type === 'string') {
void this.dispatchEvent(parsed as SnowLumaEvent).catch((error) => {
this.emitter.emit('error', error);
});
}
}
private async dispatchEvent(event: SnowLumaEvent): Promise<void> {
const context = createEventContext(event, this);
let index = -1;
const next = async (): Promise<void> => {
index += 1;
const middleware = this.middlewares[index];
if (!middleware || context.stopped) return;
await middleware(event, context, next);
};
await next();
if (!context.stopped && index >= this.middlewares.length - 1) {
this.emitter.emit('event', event);
}
}
private handleClose(args: unknown[]): void {
const info = closeInfo(args);
this.socket = null;
this.connectPromise = null;
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket closed'));
this.emitter.emit('close', info);
if (!this.closedByUser && this.reconnect) {
this.scheduleReconnect();
}
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
const reconnect = this.reconnect;
if (!reconnect) return;
const retries = reconnect.retries ?? Number.POSITIVE_INFINITY;
if (this.reconnectAttempts >= retries) return;
const minDelay = reconnect.minDelayMs ?? 1000;
const maxDelay = reconnect.maxDelayMs ?? 30_000;
const delay = Math.min(maxDelay, minDelay * 2 ** this.reconnectAttempts);
this.reconnectAttempts += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
void this.connect().catch((error) => {
this.emitter.emit('error', error);
if (!this.closedByUser) this.scheduleReconnect();
});
}, delay);
}
private rejectPending(error: Error): void {
for (const pending of this.pending.values()) {
pending.cleanup?.();
pending.reject(error);
}
this.pending.clear();
}
}
export function createWebSocketClient(options?: SnowLumaWebSocketClientOptions): SnowLumaWebSocketClient {
return new SnowLumaWebSocketClient(options);
}

View File

@@ -0,0 +1,64 @@
import type {
ApiResponse,
SnowLumaClientOptions,
SnowLumaEvent,
WsRole,
} from '../types/index';
export interface WebSocketLike {
readyState: number;
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
removeEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
on?: (event: string, listener: (...args: unknown[]) => void) => void;
off?: (event: string, listener: (...args: unknown[]) => void) => void;
removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
}
export type WebSocketConstructor = new (url: string, protocols?: string | string[]) => WebSocketLike;
/** Reconnect policy for the WebSocket client. */
export interface ReconnectOptions {
/** Maximum reconnect attempts. Omit for unlimited retries. */
retries?: number;
/** Initial reconnect delay in milliseconds. Defaults to 1000. */
minDelayMs?: number;
/** Maximum reconnect delay in milliseconds. Defaults to 30000. */
maxDelayMs?: number;
}
/** Options for the WebSocket transport client. */
export interface SnowLumaWebSocketClientOptions extends SnowLumaClientOptions {
/** OneBot WebSocket endpoint. Defaults to ws://127.0.0.1:3001/. */
url?: string;
/** OneBot WebSocket role advertised by the client. */
role?: WsRole;
/** Optional WebSocket protocols argument. */
protocols?: string | string[];
/** Custom WebSocket constructor for Node runtimes or tests. */
webSocket?: WebSocketConstructor;
/** Enables or configures automatic reconnect after unexpected close. */
reconnect?: boolean | ReconnectOptions;
}
export interface WebSocketCloseInfo {
code?: number;
reason?: string;
}
export interface SnowLumaWebSocketEvents {
open: undefined;
close: WebSocketCloseInfo;
error: unknown;
event: SnowLumaEvent;
response: ApiResponse;
raw: unknown;
}
export interface PendingRequest {
resolve: (response: ApiResponse) => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout> | null;
cleanup?: () => void;
}

View File

@@ -0,0 +1,77 @@
import { isJsonObject } from '../internal/json';
import type {
ReconnectOptions,
WebSocketCloseInfo,
WebSocketLike,
} from './websocket-types';
export const WEBSOCKET_OPEN = 1;
export const WEBSOCKET_CLOSED = 3;
export function normalizeReconnect(value: boolean | ReconnectOptions | undefined): ReconnectOptions | null {
if (!value) return null;
if (value === true) return {};
return value;
}
export function addSocketListener(
socket: WebSocketLike,
event: string,
listener: (...args: unknown[]) => void,
): () => void {
if (socket.addEventListener) {
socket.addEventListener(event, listener);
return () => socket.removeEventListener?.(event, listener);
}
if (socket.on) {
socket.on(event, listener);
return () => {
if (socket.off) socket.off(event, listener);
else socket.removeListener?.(event, listener);
};
}
return () => undefined;
}
export function unwrapMessagePayload(value: unknown): unknown {
if (isJsonObject(value) && 'data' in value) {
return value.data;
}
return value;
}
export function unwrapEventPayload(value: unknown): unknown {
if (isJsonObject(value) && 'error' in value) {
return value.error;
}
return value;
}
export function rawToString(value: unknown): string {
if (typeof value === 'string') return value;
if (value instanceof ArrayBuffer) return new TextDecoder().decode(value);
if (ArrayBuffer.isView(value)) {
return new TextDecoder().decode(value);
}
if (value instanceof Blob) {
throw new Error('Blob WebSocket messages are not supported synchronously');
}
if (value && typeof value === 'object' && 'toString' in value && typeof value.toString === 'function') {
return value.toString();
}
return String(value);
}
export function closeInfo(args: unknown[]): WebSocketCloseInfo {
const first = args[0];
if (isJsonObject(first)) {
return {
code: typeof first.code === 'number' ? first.code : undefined,
reason: typeof first.reason === 'string' ? first.reason : undefined,
};
}
return {
code: typeof args[0] === 'number' ? args[0] : undefined,
reason: typeof args[1] === 'string' ? args[1] : undefined,
};
}

View File

@@ -0,0 +1,39 @@
type Listener<TPayload> = (payload: TPayload) => void;
export class Emitter<TEvents extends object> {
private readonly listeners = new Map<keyof TEvents, Set<Listener<never>>>();
on<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): () => void {
let set = this.listeners.get(event);
if (!set) {
set = new Set();
this.listeners.set(event, set);
}
set.add(listener as Listener<never>);
return () => this.off(event, listener);
}
once<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): () => void {
const off = this.on(event, (payload) => {
off();
listener(payload);
});
return off;
}
off<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): void {
this.listeners.get(event)?.delete(listener as Listener<never>);
}
emit<TKey extends keyof TEvents>(event: TKey, payload: TEvents[TKey]): void {
const set = this.listeners.get(event);
if (!set) return;
for (const listener of [...set]) {
listener(payload as never);
}
}
clear(): void {
this.listeners.clear();
}
}

View File

@@ -0,0 +1,83 @@
import type { ApiResponse } from './types/index';
/** Base error for every exception intentionally thrown by the SnowLuma SDK. */
export class SnowLumaError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaError';
}
}
/** Transport-layer failures before a valid OneBot API response is available. */
export class SnowLumaTransportError extends SnowLumaError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaTransportError';
}
}
/** The request was cancelled by the caller's AbortSignal. */
export class SnowLumaAbortError extends SnowLumaTransportError {
constructor(message = 'SnowLuma request aborted', options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaAbortError';
}
}
/** The request exceeded the configured timeout. */
export class SnowLumaTimeoutError extends SnowLumaTransportError {
readonly timeoutMs: number;
constructor(message: string, timeoutMs: number, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaTimeoutError';
this.timeoutMs = timeoutMs;
}
}
/** The SDK could not establish or keep a connection to SnowLuma. */
export class SnowLumaConnectionError extends SnowLumaTransportError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaConnectionError';
}
}
/** SnowLuma returned a payload that could not be parsed as the expected protocol shape. */
export class SnowLumaParseError extends SnowLumaTransportError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaParseError';
}
}
/** A OneBot API response with status failed or a non-zero retcode. */
export class SnowLumaApiError<TData = unknown> extends SnowLumaError {
readonly response: ApiResponse<TData>;
readonly retcode: number;
readonly wording?: string;
constructor(response: ApiResponse<TData>) {
super(response.wording || `SnowLuma API failed with retcode ${response.retcode}`);
this.name = 'SnowLumaApiError';
this.response = response;
this.retcode = response.retcode;
this.wording = response.wording;
}
}
/** Authentication or authorization failure returned by SnowLuma. */
export class SnowLumaAuthError<TData = unknown> extends SnowLumaApiError<TData> {
constructor(response: ApiResponse<TData>) {
super(response);
this.name = 'SnowLumaAuthError';
}
}
export function createSnowLumaApiError<TData>(response: ApiResponse<TData>): SnowLumaApiError<TData> {
return isAuthFailure(response) ? new SnowLumaAuthError(response) : new SnowLumaApiError(response);
}
function isAuthFailure(response: ApiResponse<unknown>): boolean {
return response.retcode === 1401 || response.retcode === 401 || response.retcode === 403;
}

View File

@@ -0,0 +1,55 @@
import type { OneBotMessageEvent } from '../types/index';
import type { CommandMatch, CommandOptions } from './types';
export function matchCommand(
event: OneBotMessageEvent,
command: string | RegExp,
options: CommandOptions = {},
): CommandMatch | null {
const trim = options.trim ?? true;
const raw = trim ? event.raw_message.trim() : event.raw_message;
const prefixes = normalizePrefixes(options.prefixes ?? '/');
for (const prefix of prefixes) {
if (prefix && !raw.startsWith(prefix)) continue;
const text = prefix ? raw.slice(prefix.length).trimStart() : raw;
if (!text) continue;
if (command instanceof RegExp) {
const match = text.match(command);
if (!match || match.index !== 0) continue;
const matchedText = match[0] ?? '';
const rest = text.slice(matchedText.length).trim();
return {
command: matchedText,
text,
args: rest ? rest.split(/\s+/) : [],
rest,
prefix,
match,
};
}
const [head = '', ...args] = text.split(/\s+/);
const matches = options.caseSensitive
? head === command
: head.toLowerCase() === command.toLowerCase();
if (!matches) continue;
return {
command: head,
text,
args,
rest: text.slice(head.length).trim(),
prefix,
match: null,
};
}
return null;
}
function normalizePrefixes(prefixes: string | string[]): string[] {
return Array.isArray(prefixes) ? prefixes : [prefixes];
}

View File

@@ -0,0 +1,73 @@
import type { SnowLumaApiClient } from '../client/api-client';
import type { SnowLumaEvent } from '../types/index';
import { isGroupMessageEvent, isPrivateMessageEvent, isRequestEvent } from './guards';
import type { SnowLumaEventContext } from './types';
/** Creates the helper context object used by WebSocket event handlers. */
export function createEventContext<TEvent extends SnowLumaEvent>(
event: TEvent,
client: SnowLumaApiClient,
): SnowLumaEventContext<TEvent> {
let stopped = false;
const context: SnowLumaEventContext<TEvent> = {
event,
client,
get stopped() {
return stopped;
},
stopPropagation() {
stopped = true;
},
async reply(message, options) {
if (isGroupMessageEvent(event)) {
return client.sendGroupMessage(event.group_id, message, options);
}
if (isPrivateMessageEvent(event)) {
return client.sendPrivateMessage(event.user_id, message, options);
}
throw new Error('reply() is only available for message events');
},
async approve(options) {
if (!isRequestEvent(event)) {
throw new Error('approve() is only available for request events');
}
if (event.request_type === 'friend') {
return client.setFriendAddRequest(event.flag, true, options);
}
if (event.request_type === 'group') {
return client.setGroupAddRequest(event.flag, {
...options,
subType: options?.subType ?? event.sub_type,
approve: true,
});
}
throw new Error(`approve() does not support request_type=${event.request_type}`);
},
async reject(reason, options) {
if (!isRequestEvent(event)) {
throw new Error('reject() is only available for request events');
}
if (event.request_type === 'friend') {
return client.setFriendAddRequest(event.flag, false, options);
}
if (event.request_type === 'group') {
return client.setGroupAddRequest(event.flag, {
...options,
subType: options?.subType ?? event.sub_type,
approve: false,
reason: reason ?? options?.reason,
});
}
throw new Error(`reject() does not support request_type=${event.request_type}`);
},
async quickOperation(operation, options) {
return client.raw('.handle_quick_operation', {
context: event,
operation,
}, options);
},
};
return context;
}

View File

@@ -0,0 +1,43 @@
import type {
OneBotGroupMessageEvent,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotPrivateMessageEvent,
OneBotRequestEvent,
SnowLumaEvent,
} from '../types/index';
import type { EventPredicate } from './types';
export function isMessageEvent(event: SnowLumaEvent): event is OneBotMessageEvent {
return (event.post_type === 'message' || event.post_type === 'message_sent')
&& (event.message_type === 'private' || event.message_type === 'group');
}
export function isPrivateMessageEvent(event: SnowLumaEvent): event is OneBotPrivateMessageEvent {
return isMessageEvent(event) && event.message_type === 'private';
}
export function isGroupMessageEvent(event: SnowLumaEvent): event is OneBotGroupMessageEvent {
return isMessageEvent(event) && event.message_type === 'group';
}
export function isNoticeEvent(event: SnowLumaEvent): event is OneBotNoticeEvent {
return event.post_type === 'notice' && typeof event.notice_type === 'string';
}
export function isRequestEvent(event: SnowLumaEvent): event is OneBotRequestEvent {
return event.post_type === 'request' && typeof event.request_type === 'string' && typeof event.flag === 'string';
}
export function isMetaEvent(event: SnowLumaEvent): event is OneBotMetaEvent {
return event.post_type === 'meta_event' && typeof event.meta_event_type === 'string';
}
export function noticeType(type: string): EventPredicate<OneBotNoticeEvent> {
return (event): event is OneBotNoticeEvent => isNoticeEvent(event) && event.notice_type === type;
}
export function requestType(type: string): EventPredicate<OneBotRequestEvent> {
return (event): event is OneBotRequestEvent => isRequestEvent(event) && event.request_type === type;
}

View File

@@ -0,0 +1,4 @@
export * from './types';
export * from './guards';
export * from './context';
export * from './command';

View File

@@ -0,0 +1,73 @@
import type { SnowLumaApiClient } from '../client/api-client';
import type {
JsonObject,
OneBotMessageEvent,
OutgoingMessage,
RequestOptions,
SnowLumaEvent,
} from '../types/index';
export type MaybePromise<T = void> = T | Promise<T>;
export type EventNext = () => Promise<void>;
/** Type guard or predicate used by client.when(). */
export type EventPredicate<TEvent extends SnowLumaEvent = SnowLumaEvent> = (event: SnowLumaEvent) => event is TEvent;
/** Handler for one narrowed SnowLuma event. */
export type EventHandler<TEvent extends SnowLumaEvent = SnowLumaEvent> = (
event: TEvent,
context: SnowLumaEventContext<TEvent>,
) => MaybePromise;
/** Middleware in the WebSocket event dispatch pipeline. */
export type EventMiddleware = (
event: SnowLumaEvent,
context: SnowLumaEventContext,
next: EventNext,
) => MaybePromise;
/** Options for accepting or rejecting OneBot request events. */
export interface RequestDecisionOptions extends RequestOptions {
reason?: string;
subType?: string;
}
/** Convenience context passed to event middleware and handlers. */
export interface SnowLumaEventContext<TEvent extends SnowLumaEvent = SnowLumaEvent> {
readonly event: TEvent;
readonly client: SnowLumaApiClient;
readonly stopped: boolean;
/** Prevents subsequent middleware and final onEvent listeners from running. */
stopPropagation(): void;
/** Replies to private or group message events with the correct API. */
reply(message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
/** Approves a friend or group request event. */
approve(options?: RequestDecisionOptions): Promise<unknown>;
/** Rejects a friend or group request event. */
reject(reason?: string, options?: RequestDecisionOptions): Promise<unknown>;
/** Sends OneBot .handle_quick_operation with the current event as context. */
quickOperation(operation: JsonObject, options?: RequestOptions): Promise<unknown>;
}
/** Command matching options for WebSocketClient.command(). */
export interface CommandOptions {
prefixes?: string | string[];
trim?: boolean;
caseSensitive?: boolean;
}
/** Parsed command information passed to command handlers. */
export interface CommandMatch {
command: string;
text: string;
args: string[];
rest: string;
prefix: string;
match: RegExpMatchArray | null;
}
export type CommandHandler<TEvent extends OneBotMessageEvent = OneBotMessageEvent> = (
event: TEvent,
context: SnowLumaEventContext<TEvent> & { command: CommandMatch },
match: CommandMatch,
) => MaybePromise;

88
packages/sdk/src/index.ts Normal file
View File

@@ -0,0 +1,88 @@
export { SNOWLUMA_ACTIONS, isSnowLumaAction } from './actions';
export { SnowLumaApiClient } from './client/api-client';
export { SnowLumaHttpClient, createHttpClient } from './client/http-client';
export { SnowLumaWebSocketClient, createWebSocketClient } from './client/websocket-client';
export {
SnowLumaAbortError,
SnowLumaApiError,
SnowLumaAuthError,
SnowLumaConnectionError,
SnowLumaError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError,
createSnowLumaApiError,
} from './errors';
export {
MessageChain,
at,
atAll,
br,
chain,
contact,
escapeCqParam,
escapeCqText,
face,
forward,
image,
json,
location,
message,
music,
node,
normalizeMessage,
parseSegments,
poke,
raw,
record,
reply,
share,
text,
toCQString,
video,
xml,
fromCQString,
} from './messages/index';
export {
createEventContext,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
matchCommand,
noticeType,
requestType,
} from './events/index';
export type {
SnowLumaKnownAction,
} from './actions';
export type {
SnowLumaHttpClientOptions,
} from './client/http-client';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './client/websocket-client';
export type {
CommandHandler,
CommandMatch,
CommandOptions,
EventHandler,
EventMiddleware,
EventNext,
EventPredicate,
MaybePromise,
RequestDecisionOptions,
SnowLumaEventContext,
} from './events/index';
export type * from './types/index';

View File

@@ -0,0 +1,82 @@
import { SnowLumaAbortError } from '../errors';
export interface RequestAbortState {
signal: AbortSignal;
cleanup(): void;
isTimedOut(): boolean;
isExternallyAborted(): boolean;
}
export function createRequestAbortState(
timeoutMs: number,
externalSignal?: AbortSignal,
): RequestAbortState {
const controller = new AbortController();
let timedOut = false;
let externallyAborted = false;
const onExternalAbort = (): void => {
externallyAborted = true;
controller.abort(externalSignal?.reason);
};
if (externalSignal?.aborted) {
onExternalAbort();
} else {
externalSignal?.addEventListener('abort', onExternalAbort, { once: true });
}
const timer = timeoutMs > 0
? setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs)
: null;
return {
signal: controller.signal,
cleanup() {
if (timer) clearTimeout(timer);
externalSignal?.removeEventListener('abort', onExternalAbort);
},
isTimedOut() {
return timedOut;
},
isExternallyAborted() {
return externallyAborted || externalSignal?.aborted === true;
},
};
}
export function throwIfAborted(signal?: AbortSignal, message = 'SnowLuma request aborted'): void {
if (signal?.aborted) {
throw new SnowLumaAbortError(message, { cause: signal.reason });
}
}
export function isAbortError(error: unknown): boolean {
return typeof error === 'object'
&& error !== null
&& 'name' in error
&& (error as { name?: unknown }).name === 'AbortError';
}
export function raceWithAbort<T>(
promise: Promise<T>,
signal?: AbortSignal,
message = 'SnowLuma request aborted',
): Promise<T> {
if (!signal) return promise;
throwIfAborted(signal, message);
return new Promise<T>((resolve, reject) => {
const onAbort = (): void => {
reject(new SnowLumaAbortError(message, { cause: signal.reason }));
};
signal.addEventListener('abort', onAbort, { once: true });
promise.then(resolve, reject).finally(() => {
signal.removeEventListener('abort', onAbort);
});
});
}

View File

@@ -0,0 +1,64 @@
import type { ApiResponse, JsonObject, JsonValue } from '../types/index';
export function isJsonObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function asJsonValue(value: unknown): JsonValue {
if (value === null) return null;
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return value;
}
if (Array.isArray(value)) return value.map(asJsonValue);
if (isJsonObject(value)) {
const out: JsonObject = {};
for (const [key, item] of Object.entries(value)) {
if (item === undefined) continue;
out[key] = asJsonValue(item);
}
return out;
}
return String(value);
}
export function assertApiResponse(value: unknown): ApiResponse {
if (!isJsonObject(value)) {
throw new Error('response is not a JSON object');
}
const status = value.status === 'ok' ? 'ok' : value.status === 'failed' ? 'failed' : null;
if (!status) {
throw new Error('response status is missing or invalid');
}
const retcode = typeof value.retcode === 'number' && Number.isFinite(value.retcode)
? value.retcode
: status === 'ok' ? 0 : -1;
return {
status,
retcode,
data: asJsonValue(value.data ?? null),
echo: value.echo === undefined ? undefined : asJsonValue(value.echo),
wording: typeof value.wording === 'string' ? value.wording : undefined,
};
}
export function createEcho(): string {
const random = Math.random().toString(36).slice(2);
return `snowluma-sdk:${Date.now().toString(36)}:${random}`;
}
export function echoKey(value: JsonValue | undefined): string {
if (value === undefined) return '';
return JSON.stringify(value);
}
export function appendAccessToken(urlValue: string, accessToken?: string): string {
if (!accessToken) return urlValue;
const url = new URL(urlValue);
if (!url.searchParams.has('access_token')) {
url.searchParams.set('access_token', accessToken);
}
return url.toString();
}

View File

@@ -0,0 +1,306 @@
import { segments } from './segments';
import { segmentsToCQString } from './cq-format';
import type {
AnyMessageSegment,
ContactSegment,
ImageSegment,
JsonObject,
LocationSegment,
MessageChainLike,
MessageSegment,
MusicSegment,
OutgoingMessage,
RecordSegment,
RequestOptions,
ShareSegment,
VideoSegment,
XmlSegment,
} from '../types/index';
export interface MessageChainSender {
sendGroupMessage(groupId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
sendPrivateMessage(userId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
}
const SINGLE_USE_TYPES = new Set(['reply']);
/**
* Immutable fluent builder for OneBot message segments.
*
* The generic state tracks single-use segments such as reply(), so TypeScript
* can reject duplicate reply segments in normal chained calls.
*/
export class MessageChain<THasReply extends boolean = false> implements MessageChainLike {
private readonly replyStateBrand?: THasReply;
private constructor(
private readonly items: AnyMessageSegment[] = [],
private readonly used: ReadonlySet<string> = new Set(),
) {}
static empty(): MessageChain<false> {
return new MessageChain<false>();
}
/** Number of segments currently in the chain. */
get length(): number {
return this.items.length;
}
/** True when no segment has been appended. */
get isEmpty(): boolean {
return this.items.length === 0;
}
/** Appends a text segment. */
text(text = ''): MessageChain<THasReply> {
return this.addSegment(segments.text(text));
}
/** Appends a newline text segment. */
br(): MessageChain<THasReply> {
return this.text('\n');
}
face(id: number | string): MessageChain<THasReply> {
return this.addSegment(segments.face(id));
}
/** Mentions a user or everyone in a group. */
at(qq: number | 'all', options: { name?: string; uid?: string } = {}): MessageChain<THasReply> {
return this.addSegment(segments.at(qq, options));
}
atAll(): MessageChain<THasReply> {
return this.at('all');
}
/** Adds a reply segment. A chain can contain at most one reply segment. */
reply(this: MessageChain<false>, id: number | string): MessageChain<true> {
return this.addSegment(segments.reply(id), 'reply') as MessageChain<true>;
}
/** Appends an image segment from a URL, local path, file id, or base64 URI. */
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.image(file, options));
}
record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.record(file, options));
}
video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.video(file, options));
}
json(data: string | JsonObject): MessageChain<THasReply> {
return this.addSegment(segments.json(data));
}
xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.xml(data, options));
}
poke(type: number | string, id?: number | string): MessageChain<THasReply> {
return this.addSegment(segments.poke(type, id));
}
forward(id: string): MessageChain<THasReply> {
return this.addSegment(segments.forward(id));
}
node(userId: number, nickname: string, content: OutgoingMessage): MessageChain<THasReply> {
return this.addSegment(segments.node(userId, nickname, content));
}
share(options: ShareSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.share(options));
}
music(options: MusicSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.music(options));
}
location(options: LocationSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.location(options));
}
contact(type: ContactSegment['data']['type'], id: number | string): MessageChain<THasReply> {
return this.addSegment(segments.contact(type, id));
}
raw<TType extends string, TData extends JsonObject>(type: TType, data: TData): MessageChain<THasReply> {
return this.addSegment(segments.raw(type, data), type);
}
/** Appends another outgoing message while preserving single-use segment checks. */
append(messageInput: OutgoingMessage): MessageChain<THasReply> {
let next: MessageChain<THasReply> = this;
const normalized = normalizeMessage(messageInput);
if (typeof normalized === 'string') {
return next.text(normalized);
}
for (const segment of normalized) {
next = next.addFromSegment(segment);
}
return next;
}
/** Returns a fresh segment array suitable for OneBot array message format. */
build(): AnyMessageSegment[] {
return this.toSegments();
}
toArray(): AnyMessageSegment[] {
return this.toSegments();
}
toSegments(): AnyMessageSegment[] {
return [...this.items];
}
toJSON(): AnyMessageSegment[] {
return this.toSegments();
}
toString(): string {
return segmentsToCQString(this.items);
}
/** Sends this chain to a group through a compatible SnowLuma client. */
sendToGroup(
client: MessageChainSender,
groupId: number,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown> {
return client.sendGroupMessage(groupId, this, options);
}
/** Sends this chain to a private chat through a compatible SnowLuma client. */
sendToPrivate(
client: MessageChainSender,
userId: number,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown> {
return client.sendPrivateMessage(userId, this, options);
}
[Symbol.iterator](): IterableIterator<AnyMessageSegment> {
return this.items[Symbol.iterator]();
}
private addFromSegment(segment: AnyMessageSegment): MessageChain<THasReply> {
return this.addSegment(segment, segment.type);
}
private addSegment<TNextReply extends boolean = THasReply>(
segment: AnyMessageSegment,
singleUseType?: string,
): MessageChain<TNextReply> {
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType) && this.used.has(singleUseType)) {
throw new Error(`Message segment "${singleUseType}" can only appear once in a chain`);
}
const nextUsed = new Set(this.used);
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType)) {
nextUsed.add(singleUseType);
}
return new MessageChain<TNextReply>([...this.items, segment], nextUsed);
}
}
export function chain(): MessageChain<false> {
return MessageChain.empty();
}
/** Starts a message chain with a text segment. */
export function text(value = ''): MessageChain<false> {
return chain().text(value);
}
export function br(): MessageChain<false> {
return chain().br();
}
export function face(id: number | string): MessageChain<false> {
return chain().face(id);
}
export function at(qq: number | 'all', options: { name?: string; uid?: string } = {}): MessageChain<false> {
return chain().at(qq, options);
}
export function atAll(): MessageChain<false> {
return chain().atAll();
}
export function reply(id: number | string): MessageChain<true> {
return chain().reply(id);
}
/** Starts a message chain with an image segment. */
export function image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().image(file, options);
}
export function record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().record(file, options);
}
export function video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().video(file, options);
}
export function json(data: string | JsonObject): MessageChain<false> {
return chain().json(data);
}
export function xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): MessageChain<false> {
return chain().xml(data, options);
}
export function poke(type: number | string, id?: number | string): MessageChain<false> {
return chain().poke(type, id);
}
export function forward(id: string): MessageChain<false> {
return chain().forward(id);
}
export function node(userId: number, nickname: string, content: OutgoingMessage): MessageChain<false> {
return chain().node(userId, nickname, content);
}
export function share(options: ShareSegment['data']): MessageChain<false> {
return chain().share(options);
}
export function music(options: MusicSegment['data']): MessageChain<false> {
return chain().music(options);
}
export function location(options: LocationSegment['data']): MessageChain<false> {
return chain().location(options);
}
export function contact(type: ContactSegment['data']['type'], id: number | string): MessageChain<false> {
return chain().contact(type, id);
}
export function raw<TType extends string, TData extends JsonObject>(type: TType, data: TData): MessageChain<false> {
return chain().raw(type, data);
}
/** Normalizes a string, segment, segment array, or MessageChain into OneBot output. */
export function normalizeMessage(input: OutgoingMessage): string | AnyMessageSegment[] {
if (typeof input === 'string') return input;
if (isMessageChainLike(input)) return input.toSegments();
return Array.isArray(input) ? input : [input];
}
function isMessageChainLike(value: unknown): value is MessageChainLike {
return typeof value === 'object'
&& value !== null
&& 'toSegments' in value
&& typeof value.toSegments === 'function';
}

View File

@@ -0,0 +1,29 @@
import type { KnownMessageSegment, MessageSegment } from '../types/index';
export function escapeCqText(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/\[/g, '&#91;')
.replace(/\]/g, '&#93;');
}
export function escapeCqParam(text: string): string {
return escapeCqText(text).replace(/,/g, '&#44;');
}
export function segmentsToCQString(segments: Array<KnownMessageSegment | MessageSegment>): string {
return segments.map(segmentToCq).join('');
}
function segmentToCq(segment: KnownMessageSegment | MessageSegment): string {
if (segment.type === 'text') {
return escapeCqText(String(segment.data.text ?? ''));
}
const params = Object.entries(segment.data)
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${key}=${escapeCqParam(String(value))}`)
.join(',');
return params ? `[CQ:${segment.type},${params}]` : `[CQ:${segment.type}]`;
}

View File

@@ -0,0 +1,105 @@
import { normalizeMessage, chain } from './chain';
import { escapeCqText, segmentsToCQString } from './cq-format';
import { segments } from './segments';
import type { AnyMessageSegment, OutgoingMessage } from '../types/index';
const CQ_REGEX = /\[CQ:([a-zA-Z0-9_.-]+)(?:,([^\]]*))?\]/g;
export function toCQString(input: OutgoingMessage): string {
if (typeof input === 'string') return escapeCqText(input);
const normalized = normalizeMessage(input);
return typeof normalized === 'string'
? escapeCqText(normalized)
: segmentsToCQString(normalized);
}
export function fromCQString(input: string) {
let current = chain();
let lastIndex = 0;
for (const match of input.matchAll(CQ_REGEX)) {
const index = match.index ?? 0;
if (index > lastIndex) {
const textValue = cqUnescape(input.slice(lastIndex, index));
if (textValue) current = current.text(textValue);
}
const segment = segmentFromCq(match[1] ?? '', parseCQParams(match[2] ?? ''));
if (segment) current = current.append(segment);
lastIndex = index + match[0].length;
}
if (lastIndex < input.length) {
const textValue = cqUnescape(input.slice(lastIndex));
if (textValue) current = current.text(textValue);
}
return current;
}
export function parseSegments(input: string): AnyMessageSegment[] {
return fromCQString(input).toSegments();
}
function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
if (!raw) return params;
for (const pair of raw.split(',')) {
const eq = pair.indexOf('=');
if (eq <= 0) continue;
params[pair.slice(0, eq)] = cqUnescapeParam(pair.slice(eq + 1));
}
return params;
}
function cqUnescape(text: string): string {
return text
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&amp;/g, '&');
}
function cqUnescapeParam(text: string): string {
return cqUnescape(text).replace(/&#44;/g, ',');
}
function segmentFromCq(type: string, data: Record<string, string>): AnyMessageSegment | null {
switch (type) {
case 'text':
return segments.text(data.text ?? '');
case 'face':
return segments.face(data.id ?? '0');
case 'at':
if (data.qq === 'all') return segments.at('all');
{
const qq = Number(data.qq);
return Number.isFinite(qq) && qq > 0
? segments.at(qq, { name: data.name, uid: data.uid })
: segments.raw(type, data);
}
case 'reply':
return segments.reply(data.id ?? '0');
case 'image':
return segments.image(data.file ?? data.url ?? '', {
url: data.url,
type: data.type === 'flash' ? 'flash' : undefined,
summary: data.summary,
});
case 'record':
return segments.record(data.file ?? data.url ?? '', { url: data.url });
case 'video':
return segments.video(data.file ?? data.url ?? '', { url: data.url, thumb: data.thumb });
case 'json':
return segments.json(data.data ?? '');
case 'xml':
return segments.xml(data.data ?? '', { id: data.id });
case 'poke':
return segments.poke(data.type ?? data.id ?? '0', data.id);
case 'forward':
return segments.forward(data.id ?? data.res_id ?? data.forward_id ?? '');
default:
return segments.raw(type, data);
}
}

View File

@@ -0,0 +1,33 @@
import { segments } from './segments';
export { MessageChain } from './chain';
export {
at,
atAll,
br,
chain,
contact,
face,
forward,
image,
json,
location,
music,
node,
normalizeMessage,
poke,
raw,
record,
reply,
share,
text,
video,
xml,
} from './chain';
export { escapeCqParam, escapeCqText } from './cq-format';
export { fromCQString, parseSegments, toCQString } from './cq';
export { segments };
export const message = {
...segments,
};

View File

@@ -0,0 +1,100 @@
import type {
AtSegment,
ContactSegment,
FaceSegment,
ForwardSegment,
ImageSegment,
JsonObject,
JsonSegment,
LocationSegment,
MessageSegment,
MusicSegment,
NodeSegment,
OutgoingMessage,
PokeSegment,
RecordSegment,
ReplySegment,
ShareSegment,
TextSegment,
VideoSegment,
XmlSegment,
} from '../types/index';
function seg<TType extends string, TData extends Record<string, unknown>>(type: TType, data: TData): MessageSegment<TType, TData> {
return { type, data };
}
export const segments = {
text(text: string): TextSegment {
return seg('text', { text });
},
face(id: number | string): FaceSegment {
return seg('face', { id: String(id) });
},
at(qq: number | 'all', options: { name?: string; uid?: string } = {}): AtSegment {
const data: AtSegment['data'] = { qq: String(qq) };
if (options.name) data.name = options.name;
if (options.uid) data.uid = options.uid;
return seg('at', data);
},
reply(id: number | string): ReplySegment {
return seg('reply', { id: String(id) });
},
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): ImageSegment {
return seg('image', { file, ...options });
},
record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): RecordSegment {
return seg('record', { file, ...options });
},
video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): VideoSegment {
return seg('video', { file, ...options });
},
json(data: string | JsonObject): JsonSegment {
return seg('json', { data: typeof data === 'string' ? data : JSON.stringify(data) });
},
xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): XmlSegment {
return seg('xml', { data, ...options });
},
poke(type: number | string, id?: number | string): PokeSegment {
const data: PokeSegment['data'] = { type };
if (id !== undefined) data.id = id;
return seg('poke', data);
},
forward(id: string): ForwardSegment {
return seg('forward', { id, res_id: id, forward_id: id });
},
node(userId: number, nickname: string, content: OutgoingMessage): NodeSegment {
return seg('node', { user_id: userId, nickname, content });
},
share(options: ShareSegment['data']): ShareSegment {
return seg('share', options);
},
music(options: MusicSegment['data']): MusicSegment {
return seg('music', options);
},
location(options: LocationSegment['data']): LocationSegment {
return seg('location', options);
},
contact(type: ContactSegment['data']['type'], id: number | string): ContactSegment {
return seg('contact', { type, id });
},
raw<TType extends string, TData extends JsonObject>(type: TType, data: TData): MessageSegment<TType, TData> {
return seg(type, data);
},
};

View File

@@ -0,0 +1,208 @@
import type { JsonArray, JsonObject, JsonValue } from './json';
import type {
CreateGroupFileFolderParams,
DeleteFriendParams,
DeleteGroupFileFolderParams,
DeleteGroupFileParams,
DomainParams,
DownloadFileParams,
ForwardMessageParams,
FriendPokeParams,
GetForwardMsgParams,
GetFriendMessageHistoryParams,
GetGroupFilesParams,
GetGroupFileUrlParams,
GetGroupHonorInfoParams,
GetGroupInfoParams,
GetGroupListParams,
GetGroupMemberInfoParams,
GetGroupMemberListParams,
GetGroupMessageHistoryParams,
GetMediaParams,
GetPrivateFileUrlParams,
GroupForwardMessageParams,
GroupIdParams,
GroupNoticeParams,
GroupPokeParams,
MarkGroupMsgAsReadParams,
MarkMsgAsReadParams,
MarkPrivateMsgAsReadParams,
MessageIdParams,
MoveGroupFileParams,
PrivateForwardMessageParams,
RenameGroupFileFolderParams,
SendGroupMsgParams,
SendLikeParams,
SendMsgParams,
SendPokeParams,
SendPrivateMsgParams,
SetFriendAddRequestParams,
SetFriendRemarkParams,
SetGroupAddRequestParams,
SetGroupAdminParams,
SetGroupBanParams,
SetGroupCardParams,
SetGroupKickParams,
SetGroupNameParams,
SetGroupReactionParams,
SetGroupSpecialTitleParams,
SetGroupWholeBanParams,
SetMsgEmojiLikeParams,
SetOnlineStatusParams,
SetQqProfileParams,
UploadGroupFileParams,
UploadPrivateFileParams,
UserIdParams,
QuickOperationParams,
} from './params';
import type {
CapabilityInfo,
ClientKeyInfo,
CookieInfo,
CredentialsInfo,
CsrfInfo,
DownloadFileResult,
EmptyData,
ForwardMessageResult,
FriendMessageHistory,
GroupAtAllRemainInfo,
GroupFileSystemInfo,
GroupFileUrl,
GroupMessageHistory,
LoginInfo,
MediaInfo,
OnlineClientsInfo,
PrivateFileUrl,
SendMessageResult,
StatusInfo,
UploadForwardResult,
UrlSafetyInfo,
VersionInfo,
} from './results';
export type ActionData = JsonValue;
export interface SnowLumaActionMap {
get_login_info: { params: JsonObject; data: LoginInfo };
get_status: { params: JsonObject; data: StatusInfo };
get_version_info: { params: JsonObject; data: VersionInfo };
can_send_image: { params: JsonObject; data: CapabilityInfo };
can_send_record: { params: JsonObject; data: CapabilityInfo };
send_msg: { params: SendMsgParams; data: SendMessageResult };
send_private_msg: { params: SendPrivateMsgParams; data: SendMessageResult };
send_group_msg: { params: SendGroupMsgParams; data: SendMessageResult };
get_msg: { params: MessageIdParams; data: JsonObject };
delete_msg: { params: MessageIdParams; data: EmptyData };
get_friend_list: { params: JsonObject; data: JsonObject[] };
get_stranger_info: { params: UserIdParams; data: JsonObject };
delete_friend: { params: DeleteFriendParams; data: EmptyData };
get_group_list: { params: GetGroupListParams; data: JsonObject[] };
get_group_info: { params: GetGroupInfoParams; data: JsonObject };
get_group_member_list: { params: GetGroupMemberListParams; data: JsonObject[] };
get_group_member_info: { params: GetGroupMemberInfoParams; data: JsonObject };
get_group_honor_info: { params: GetGroupHonorInfoParams; data: JsonValue };
get_group_system_msg: { params: JsonObject; data: JsonObject[] };
set_group_kick: { params: SetGroupKickParams; data: EmptyData };
set_group_ban: { params: SetGroupBanParams; data: EmptyData };
set_group_whole_ban: { params: SetGroupWholeBanParams; data: EmptyData };
set_group_admin: { params: SetGroupAdminParams; data: EmptyData };
set_group_card: { params: SetGroupCardParams; data: EmptyData };
set_group_name: { params: SetGroupNameParams; data: EmptyData };
set_group_leave: { params: GroupIdParams; data: EmptyData };
set_group_special_title: { params: SetGroupSpecialTitleParams; data: EmptyData };
set_group_anonymous: { params: JsonObject; data: EmptyData };
set_group_anonymous_ban: { params: JsonObject; data: EmptyData };
set_group_portrait: { params: JsonObject; data: EmptyData };
upload_group_file: { params: UploadGroupFileParams; data: { file_id: string | null } };
upload_private_file: { params: UploadPrivateFileParams; data: { file_id: string | null } };
get_group_file_url: { params: GetGroupFileUrlParams; data: GroupFileUrl };
get_group_root_files: { params: GroupIdParams; data: JsonObject };
get_group_files_by_folder: { params: GetGroupFilesParams; data: JsonObject };
delete_group_file: { params: DeleteGroupFileParams; data: EmptyData };
move_group_file: { params: MoveGroupFileParams; data: EmptyData };
create_group_file_folder: { params: CreateGroupFileFolderParams; data: EmptyData };
delete_group_file_folder: { params: DeleteGroupFileFolderParams; data: EmptyData };
rename_group_file_folder: { params: RenameGroupFileFolderParams; data: EmptyData };
get_private_file_url: { params: GetPrivateFileUrlParams; data: PrivateFileUrl };
set_friend_add_request: { params: SetFriendAddRequestParams; data: EmptyData };
set_group_add_request: { params: SetGroupAddRequestParams; data: EmptyData };
send_like: { params: SendLikeParams; data: EmptyData };
friend_poke: { params: FriendPokeParams; data: EmptyData };
group_poke: { params: GroupPokeParams; data: EmptyData };
send_poke: { params: SendPokeParams; data: EmptyData };
set_essence_msg: { params: MessageIdParams; data: EmptyData };
delete_essence_msg: { params: MessageIdParams; data: EmptyData };
get_essence_msg_list: { params: GroupIdParams; data: JsonArray };
set_group_reaction: { params: SetGroupReactionParams; data: EmptyData };
get_group_msg_history: { params: GetGroupMessageHistoryParams; data: GroupMessageHistory };
get_friend_msg_history: { params: GetFriendMessageHistoryParams; data: FriendMessageHistory };
mark_group_msg_as_read: { params: MarkGroupMsgAsReadParams; data: EmptyData };
mark_private_msg_as_read: { params: MarkPrivateMsgAsReadParams; data: EmptyData };
mark_msg_as_read: { params: MarkMsgAsReadParams; data: EmptyData };
get_rkey: { params: JsonObject; data: JsonObject[] };
ocr_image: { params: JsonObject; data: JsonValue };
'.ocr_image': { params: JsonObject; data: JsonValue };
_send_group_notice: { params: GroupNoticeParams; data: EmptyData };
_get_group_notice: { params: GroupIdParams; data: JsonArray };
_del_group_notice: { params: JsonObject; data: EmptyData };
upload_forward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
upload_foward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
send_forward_msg: { params: ForwardMessageParams; data: ForwardMessageResult };
send_group_forward_msg: { params: GroupForwardMessageParams; data: ForwardMessageResult };
send_private_forward_msg: { params: PrivateForwardMessageParams; data: ForwardMessageResult };
get_forward_msg: { params: GetForwardMsgParams; data: { messages: JsonObject[] } };
get_image: { params: GetMediaParams; data: MediaInfo };
get_record: { params: GetMediaParams; data: MediaInfo };
get_cookies: { params: DomainParams; data: CookieInfo };
get_csrf_token: { params: JsonObject; data: CsrfInfo };
get_credentials: { params: DomainParams; data: CredentialsInfo };
set_restart: { params: JsonObject; data: EmptyData };
clean_cache: { params: JsonObject; data: EmptyData };
'.handle_quick_operation': { params: QuickOperationParams; data: EmptyData };
set_friend_remark: { params: SetFriendRemarkParams; data: EmptyData };
set_msg_emoji_like: { params: SetMsgEmojiLikeParams; data: EmptyData };
_mark_all_as_read: { params: JsonObject; data: EmptyData };
get_group_file_system_info: { params: GroupIdParams; data: GroupFileSystemInfo };
check_url_safely: { params: JsonObject; data: UrlSafetyInfo };
download_file: { params: DownloadFileParams; data: DownloadFileResult };
set_qq_profile: { params: SetQqProfileParams; data: EmptyData };
set_online_status: { params: SetOnlineStatusParams; data: EmptyData };
get_group_ignored_notifies: { params: JsonObject; data: JsonArray };
get_group_shut_list: { params: JsonObject; data: JsonArray };
forward_friend_single_msg: { params: JsonObject; data: JsonValue };
forward_group_single_msg: { params: JsonObject; data: JsonValue };
get_recent_contact: { params: JsonObject; data: JsonArray };
get_profile_like: { params: JsonObject; data: JsonObject };
get_friends_with_category: { params: JsonObject; data: JsonObject[] };
get_online_clients: { params: JsonObject; data: OnlineClientsInfo };
_get_model_show: { params: JsonObject; data: { variants: JsonArray } };
_set_model_show: { params: JsonObject; data: EmptyData };
'.get_word_slices': { params: JsonObject; data: JsonValue };
get_group_at_all_remain: { params: JsonObject; data: GroupAtAllRemainInfo };
get_unidirectional_friend_list: { params: JsonObject; data: JsonArray };
set_self_longnick: { params: JsonObject; data: EmptyData };
get_collection_list: { params: JsonObject; data: JsonArray };
create_collection: { params: JsonObject; data: JsonValue };
set_qq_avatar: { params: JsonObject; data: EmptyData };
set_input_status: { params: JsonObject; data: EmptyData };
translate_en2zh: { params: JsonObject; data: JsonValue };
get_clientkey: { params: JsonObject; data: ClientKeyInfo };
get_mini_app_ark: { params: JsonObject; data: JsonValue };
click_inline_keyboard_button: { params: JsonObject; data: JsonValue };
set_group_sign: { params: JsonObject; data: EmptyData };
send_group_sign: { params: JsonObject; data: EmptyData };
get_group_info_ex: { params: GroupIdParams; data: JsonObject };
get_group_detail_info: { params: GroupIdParams; data: JsonObject };
trans_group_file: { params: JsonObject; data: JsonValue };
rename_group_file: { params: JsonObject; data: JsonValue };
get_file: { params: GetMediaParams; data: JsonValue };
'.send_packet': { params: JsonObject; data: JsonValue };
}
export type SnowLumaAction = keyof SnowLumaActionMap | (string & {});
export type ActionParams<TAction extends string> =
TAction extends keyof SnowLumaActionMap ? SnowLumaActionMap[TAction]['params'] : JsonObject;
export type ActionResult<TAction extends string> =
TAction extends keyof SnowLumaActionMap ? SnowLumaActionMap[TAction]['data'] : ActionData;

View File

@@ -0,0 +1,73 @@
import type { JsonObject, JsonValue } from './json';
export interface OneBotBaseEvent extends JsonObject {
time: number;
self_id: number;
post_type: string;
}
export interface OneBotSender extends JsonObject {
user_id: number;
nickname: string;
sex?: string;
age?: number;
card?: string;
role?: string;
}
export interface OneBotPrivateMessageEvent extends OneBotBaseEvent {
post_type: 'message' | 'message_sent';
message_type: 'private';
sub_type: string;
message_id: number;
message_seq?: number;
user_id: number;
message: JsonValue;
raw_message: string;
font: number;
sender: OneBotSender;
}
export interface OneBotGroupMessageEvent extends OneBotBaseEvent {
post_type: 'message' | 'message_sent';
message_type: 'group';
sub_type: string;
message_id: number;
message_seq?: number;
group_id: number;
user_id: number;
message: JsonValue;
raw_message: string;
font: number;
sender: OneBotSender;
anonymous?: JsonValue;
}
export type OneBotMessageEvent = OneBotPrivateMessageEvent | OneBotGroupMessageEvent;
export interface OneBotNoticeEvent extends OneBotBaseEvent {
post_type: 'notice';
notice_type: string;
}
export interface OneBotRequestEvent extends OneBotBaseEvent {
post_type: 'request';
request_type: string;
flag: string;
sub_type?: string;
group_id?: number;
user_id?: number;
comment?: string;
}
export interface OneBotMetaEvent extends OneBotBaseEvent {
post_type: 'meta_event';
meta_event_type: string;
}
export type SnowLumaEvent =
| OneBotMessageEvent
| OneBotNoticeEvent
| OneBotRequestEvent
| OneBotMetaEvent
| OneBotBaseEvent;

View File

@@ -0,0 +1,6 @@
export * from './json';
export * from './messages';
export * from './results';
export * from './params';
export * from './actions';
export * from './events';

View File

@@ -0,0 +1,43 @@
export type JsonPrimitive = string | number | boolean | null;
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
export interface JsonObject {
[key: string]: JsonValue | undefined;
}
export type JsonArray = JsonValue[];
export interface ApiResponse<TData = JsonValue> {
status: 'ok' | 'failed';
retcode: number;
data: TData;
echo?: JsonValue;
wording?: string;
}
export interface OneBotRequest<TParams extends JsonObject = JsonObject> {
action: string;
params?: TParams;
echo?: JsonValue;
}
export type WsRole = 'Api' | 'Event' | 'Universal';
export type MessageFormat = 'array' | 'string';
/** Per-request controls shared by HTTP and WebSocket clients. */
export interface RequestOptions {
/** Echo value used to correlate OneBot request and response packets. */
echo?: JsonValue;
/** Override the client's default timeout for this request. Set to 0 to disable timeout. */
timeoutMs?: number;
/** Cancels the request before a SnowLuma response arrives. */
signal?: AbortSignal;
}
/** Shared options accepted by concrete SnowLuma clients. */
export interface SnowLumaClientOptions {
/** Access token configured in SnowLuma's OneBot settings. */
accessToken?: string;
/** Default timeout for API calls in milliseconds. Defaults to 30000. */
requestTimeoutMs?: number;
}

View File

@@ -0,0 +1,85 @@
import type { JsonObject } from './json';
export interface MessageSegment<
TType extends string = string,
TData extends Record<string, unknown> = JsonObject,
> {
type: TType;
data: TData;
}
export type TextSegment = MessageSegment<'text', { text: string }>;
export type FaceSegment = MessageSegment<'face', { id: string }>;
export type AtSegment = MessageSegment<'at', { qq: string; name?: string; uid?: string }>;
export type ReplySegment = MessageSegment<'reply', { id: string }>;
export type ImageSegment = MessageSegment<'image', {
file: string;
type?: 'flash';
subType?: number;
summary?: string;
url?: string;
}>;
export type RecordSegment = MessageSegment<'record', { file: string; url?: string }>;
export type VideoSegment = MessageSegment<'video', { file: string; url?: string; thumb?: string }>;
export type JsonSegment = MessageSegment<'json', { data: string }>;
export type XmlSegment = MessageSegment<'xml', { data: string; id?: string }>;
export type PokeSegment = MessageSegment<'poke', { type: string | number; id?: string | number }>;
export type ForwardSegment = MessageSegment<'forward', { id: string; res_id?: string; forward_id?: string }>;
export type NodeSegment = MessageSegment<'node', {
user_id: number;
nickname: string;
content: OutgoingMessage;
}>;
export type ShareSegment = MessageSegment<'share', {
url: string;
title: string;
content?: string;
image?: string;
}>;
export type MusicSegment = MessageSegment<'music', {
type: string;
id?: string;
url?: string;
audio?: string;
title?: string;
image?: string;
content?: string;
}>;
export type LocationSegment = MessageSegment<'location', {
lat: string | number;
lon: string | number;
title?: string;
content?: string;
}>;
export type ContactSegment = MessageSegment<'contact', {
type: 'qq' | 'group' | string;
id: string | number;
}>;
export type KnownMessageSegment =
| TextSegment
| FaceSegment
| AtSegment
| ReplySegment
| ImageSegment
| RecordSegment
| VideoSegment
| JsonSegment
| XmlSegment
| PokeSegment
| ForwardSegment
| NodeSegment
| ShareSegment
| MusicSegment
| LocationSegment
| ContactSegment;
export type AnyMessageSegment = KnownMessageSegment | MessageSegment;
export interface MessageChainLike {
readonly length: number;
toSegments(): AnyMessageSegment[];
toJSON(): AnyMessageSegment[];
}
export type OutgoingMessage = string | MessageChainLike | AnyMessageSegment | AnyMessageSegment[];

View File

@@ -0,0 +1,279 @@
import type { JsonObject, JsonValue } from './json';
export interface SendMsgParams extends JsonObject {
message_type?: 'private' | 'group' | string;
user_id?: number;
group_id?: number;
message: JsonValue;
auto_escape?: boolean;
}
export interface SendPrivateMsgParams extends JsonObject {
user_id: number;
message: JsonValue;
auto_escape?: boolean;
}
export interface SendGroupMsgParams extends JsonObject {
group_id: number;
message: JsonValue;
auto_escape?: boolean;
}
export interface MessageIdParams extends JsonObject {
message_id: number;
}
export interface GroupIdParams extends JsonObject {
group_id: number;
}
export interface UserIdParams extends JsonObject {
user_id: number;
}
export interface NoCacheParams extends JsonObject {
no_cache?: boolean;
}
export interface GetGroupListParams extends NoCacheParams {}
export interface GetGroupInfoParams extends GroupIdParams {
no_cache?: boolean;
}
export interface GetGroupMemberListParams extends GroupIdParams {
no_cache?: boolean;
}
export interface GetGroupMemberInfoParams extends GroupIdParams {
user_id: number;
no_cache?: boolean;
}
export interface GetGroupHonorInfoParams extends GroupIdParams {
type?: 'talkative' | 'performer' | 'legend' | 'strong_newbie' | 'emotion' | 'all' | string;
}
export interface DeleteFriendParams extends UserIdParams {
block?: boolean;
}
export interface SetGroupKickParams extends GroupIdParams {
user_id: number;
reject_add_request?: boolean;
}
export interface SetGroupBanParams extends GroupIdParams {
user_id: number;
duration?: number;
}
export interface SetGroupWholeBanParams extends GroupIdParams {
enable?: boolean;
}
export interface SetGroupAdminParams extends GroupIdParams {
user_id: number;
enable?: boolean;
}
export interface SetGroupCardParams extends GroupIdParams {
user_id: number;
card?: string;
}
export interface SetGroupNameParams extends GroupIdParams {
group_name: string;
}
export interface SetGroupSpecialTitleParams extends GroupIdParams {
user_id: number;
special_title?: string;
}
export interface UploadGroupFileParams extends GroupIdParams {
file: string;
name?: string;
folder?: string;
folder_id?: string;
upload_file?: boolean;
}
export interface UploadPrivateFileParams extends UserIdParams {
file: string;
name?: string;
upload_file?: boolean;
}
export interface GetGroupFileUrlParams extends GroupIdParams {
file_id: string;
busid?: number;
}
export interface GetGroupFilesParams extends GroupIdParams {
folder_id?: string;
folder?: string;
}
export interface DeleteGroupFileParams extends GroupIdParams {
file_id: string;
}
export interface MoveGroupFileParams extends GroupIdParams {
file_id: string;
parent_directory: string;
target_directory: string;
}
export interface CreateGroupFileFolderParams extends GroupIdParams {
name: string;
parent_id?: string;
}
export interface DeleteGroupFileFolderParams extends GroupIdParams {
folder_id: string;
}
export interface RenameGroupFileFolderParams extends GroupIdParams {
folder_id: string;
new_folder_name?: string;
name?: string;
}
export interface GetPrivateFileUrlParams extends UserIdParams {
file_id: string;
file_hash: string;
}
export interface SetFriendAddRequestParams extends JsonObject {
flag: string;
approve?: boolean;
}
export interface SetGroupAddRequestParams extends JsonObject {
flag: string;
sub_type?: string;
type?: string;
approve?: boolean;
reason?: string;
}
export interface SendLikeParams extends UserIdParams {
times?: number;
}
export interface FriendPokeParams extends UserIdParams {
target_id?: number;
}
export interface GroupPokeParams extends GroupIdParams {
user_id: number;
}
export interface SendPokeParams extends UserIdParams {
group_id?: number;
}
export interface SetGroupReactionParams extends JsonObject {
message_id: number;
code: string;
group_id?: number;
is_set?: boolean;
}
export interface GetMessageHistoryParams extends JsonObject {
message_id?: number;
count?: number;
}
export interface GetGroupMessageHistoryParams extends GroupIdParams, GetMessageHistoryParams {}
export interface GetFriendMessageHistoryParams extends UserIdParams, GetMessageHistoryParams {}
export interface MarkGroupMsgAsReadParams extends JsonObject {
message_id: number;
group_id?: number;
}
export interface MarkPrivateMsgAsReadParams extends JsonObject {
message_id: number;
user_id?: number;
}
export interface MarkMsgAsReadParams extends JsonObject {
message_id: number;
target_id?: number;
}
export interface GroupNoticeParams extends GroupIdParams {
content: string;
image?: string;
pinned?: number;
type?: number;
confirm_required?: number;
}
export interface ForwardMessageParams extends JsonObject {
message_type?: 'private' | 'group' | string;
user_id?: number;
group_id?: number;
message?: JsonValue;
messages?: JsonValue;
}
export interface GroupForwardMessageParams extends GroupIdParams {
message?: JsonValue;
messages?: JsonValue;
}
export interface PrivateForwardMessageParams extends UserIdParams {
message?: JsonValue;
messages?: JsonValue;
}
export interface GetForwardMsgParams extends JsonObject {
id?: string;
message_id?: number | string;
}
export interface GetMediaParams extends JsonObject {
file?: string;
file_id?: string;
}
export interface DomainParams extends JsonObject {
domain?: string;
}
export interface QuickOperationParams extends JsonObject {
context: JsonObject;
operation: JsonObject;
}
export interface SetFriendRemarkParams extends UserIdParams {
remark: string;
}
export interface SetMsgEmojiLikeParams extends JsonObject {
message_id: number;
emoji_id: string;
set?: boolean;
}
export interface DownloadFileParams extends JsonObject {
url?: string;
base64?: string;
name?: string;
headers?: string | string[];
}
export interface SetQqProfileParams extends JsonObject {
nickname?: string;
personal_note?: string;
}
export interface SetOnlineStatusParams extends JsonObject {
status: number;
ext_status?: number;
battery_status?: number;
}

View File

@@ -0,0 +1,103 @@
import type { JsonArray, JsonObject } from './json';
export interface SendMessageResult {
message_id: number;
}
export interface ForwardMessageResult {
message_id: number;
res_id: string;
forward_id: string;
}
export interface UploadForwardResult {
message_id: number;
res_id: string;
forward_id: string;
group_id?: number;
}
export interface LoginInfo {
user_id: number;
nickname: string;
}
export interface StatusInfo {
online: boolean;
good: boolean;
}
export interface VersionInfo {
app_name: string;
app_version: string;
protocol_version: string;
}
export interface CapabilityInfo {
yes: boolean;
}
export interface GroupFileUrl {
url: string;
}
export interface PrivateFileUrl {
url: string;
}
export interface GroupFileSystemInfo {
file_count: number;
limit_count: number;
used_space: number;
total_space: number;
}
export interface GroupMessageHistory {
messages: JsonObject[];
}
export interface FriendMessageHistory {
messages: JsonObject[];
}
export interface MediaInfo extends JsonObject {}
export interface CookieInfo {
cookies: string;
}
export interface CsrfInfo {
token: number;
}
export interface CredentialsInfo {
cookies: string;
token: number;
csrf_token: number;
}
export interface DownloadFileResult {
file: string;
}
export interface ClientKeyInfo {
clientKey: string;
keyIndex: string;
expireTime: string;
}
export interface OnlineClientsInfo {
clients: JsonArray;
}
export interface UrlSafetyInfo {
level: number;
}
export interface GroupAtAllRemainInfo {
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}
export type EmptyData = null;

View File

@@ -0,0 +1,21 @@
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { SNOWLUMA_ACTIONS } from '../src';
describe('SnowLuma action list', () => {
it('stays in sync with core registerAction calls', () => {
const actionsDir = fileURLToPath(new URL('../../core/src/onebot/actions/', import.meta.url));
const registered = new Set<string>();
for (const file of fs.readdirSync(actionsDir)) {
if (!file.endsWith('.ts')) continue;
const source = fs.readFileSync(new URL(file, `file://${actionsDir}/`), 'utf8');
for (const match of source.matchAll(/registerAction\('([^']+)'/g)) {
registered.add(match[1]!);
}
}
expect([...SNOWLUMA_ACTIONS].sort()).toEqual([...registered].sort());
});
});

View File

@@ -0,0 +1,88 @@
import { describe, expect, it, vi } from 'vitest';
import {
createEventContext,
isGroupMessageEvent,
isPrivateMessageEvent,
matchCommand,
text,
type OneBotPrivateMessageEvent,
type OneBotRequestEvent,
type SnowLumaApiClient,
} from '../src';
const PRIVATE_EVENT: OneBotPrivateMessageEvent = {
time: 1,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
message_seq: 8,
user_id: 10001,
message: [{ type: 'text', data: { text: '/ping a b' } }],
raw_message: '/ping a b',
font: 0,
sender: { user_id: 10001, nickname: 'tester' },
};
function fakeClient(): SnowLumaApiClient {
return {
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 1 }),
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 2 }),
setFriendAddRequest: vi.fn().mockResolvedValue(null),
setGroupAddRequest: vi.fn().mockResolvedValue(null),
raw: vi.fn().mockResolvedValue(null),
} as unknown as SnowLumaApiClient;
}
describe('event helpers', () => {
it('narrows message event types', () => {
expect(isPrivateMessageEvent(PRIVATE_EVENT)).toBe(true);
expect(isGroupMessageEvent(PRIVATE_EVENT)).toBe(false);
});
it('replies to private messages through context', async () => {
const client = fakeClient();
const context = createEventContext(PRIVATE_EVENT, client);
await context.reply(text('pong'));
expect(client.sendPrivateMessage).toHaveBeenCalledWith(10001, text('pong'), undefined);
});
it('approves and rejects request events', async () => {
const client = fakeClient();
const request: OneBotRequestEvent = {
time: 1,
self_id: 10000,
post_type: 'request',
request_type: 'group',
sub_type: 'invite',
flag: 'flag-1',
};
const context = createEventContext(request, client);
await context.approve();
await context.reject('nope');
expect(client.setGroupAddRequest).toHaveBeenNthCalledWith(1, 'flag-1', {
subType: 'invite',
approve: true,
});
expect(client.setGroupAddRequest).toHaveBeenNthCalledWith(2, 'flag-1', {
subType: 'invite',
approve: false,
reason: 'nope',
});
});
it('matches commands with prefixes', () => {
expect(matchCommand(PRIVATE_EVENT, 'ping')).toMatchObject({
command: 'ping',
args: ['a', 'b'],
rest: 'a b',
prefix: '/',
});
expect(matchCommand(PRIVATE_EVENT, 'pong')).toBeNull();
});
});

View File

@@ -0,0 +1,44 @@
import { describe, expect, it, vi } from 'vitest';
import {
SnowLumaAbortError,
SnowLumaAuthError,
SnowLumaHttpClient,
SnowLumaParseError,
} from '../src';
describe('SnowLumaHttpClient', () => {
it('throws SnowLumaAuthError for auth retcodes', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response(JSON.stringify({
status: 'failed',
retcode: 1401,
data: null,
wording: 'unauthorized',
})));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaAuthError);
});
it('throws SnowLumaParseError for non-JSON responses', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response('not json', { status: 200 }));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaParseError);
});
it('supports caller AbortSignal cancellation', async () => {
const fetchImpl = vi.fn((_url: string | URL | Request, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
const signal = init?.signal;
const abort = () => reject(new DOMException('aborted', 'AbortError'));
if (signal?.aborted) abort();
signal?.addEventListener('abort', abort, { once: true });
}));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const controller = new AbortController();
const request = client.getStatus({ signal: controller.signal });
controller.abort();
await expect(request).rejects.toBeInstanceOf(SnowLumaAbortError);
});
});

View File

@@ -0,0 +1,62 @@
import { describe, expect, it, vi } from 'vitest';
import {
atAll,
fromCQString,
message,
parseSegments,
text,
toCQString,
} from '../src';
describe('MessageChain', () => {
it('builds fluent segment chains', () => {
const chain = text('hello').at(10001).br().image('/tmp/a.png');
expect(chain.length).toBe(4);
expect(chain.toSegments()).toEqual([
{ type: 'text', data: { text: 'hello' } },
{ type: 'at', data: { qq: '10001' } },
{ type: 'text', data: { text: '\n' } },
{ type: 'image', data: { file: '/tmp/a.png' } },
]);
});
it('keeps the old segment builder API available', () => {
expect(message.text('hello')).toEqual({ type: 'text', data: { text: 'hello' } });
expect(atAll().toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
});
it('allows reply only once in a chain at runtime', () => {
const chain = text('hello').reply(1);
expect(() => (chain as any).reply(2)).toThrow(/reply/);
expect(() => chain.append(message.reply(2))).toThrow(/reply/);
});
it('appends other messages and converts to CQ string', () => {
const chain = text('hello').append([message.at('all'), message.face(14)]);
expect(toCQString(chain)).toBe('hello[CQ:at,qq=all][CQ:face,id=14]');
});
it('parses CQ strings into chains', () => {
const chain = fromCQString('hi[CQ:at,qq=all][CQ:image,file=a&#44;b]');
expect(chain.toSegments()).toEqual([
{ type: 'text', data: { text: 'hi' } },
{ type: 'at', data: { qq: 'all' } },
{ type: 'image', data: { file: 'a,b', url: undefined, type: undefined, summary: undefined } },
]);
expect(parseSegments('[CQ:reply,id=7]')).toEqual([{ type: 'reply', data: { id: '7' } }]);
});
it('can send itself through a compatible client', async () => {
const client = {
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 1 }),
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 2 }),
};
await text('hi').sendToGroup(client, 123);
await text('yo').sendToPrivate(client, 456);
expect(client.sendGroupMessage).toHaveBeenCalledWith(123, text('hi'), undefined);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(456, text('yo'), undefined);
});
});

View File

@@ -0,0 +1,143 @@
import { describe, expect, it, vi } from 'vitest';
import {
SnowLumaAbortError,
SnowLumaWebSocketClient,
type OneBotPrivateMessageEvent,
} from '../src';
class MockWebSocket {
static instances: MockWebSocket[] = [];
readyState = 0;
sent: string[] = [];
readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>();
constructor(
readonly url: string,
readonly protocols?: string | string[],
) {
MockWebSocket.instances.push(this);
}
addEventListener(event: string, listener: (...args: unknown[]) => void): void {
let listeners = this.listeners.get(event);
if (!listeners) {
listeners = new Set();
this.listeners.set(event, listeners);
}
listeners.add(listener);
}
removeEventListener(event: string, listener: (...args: unknown[]) => void): void {
this.listeners.get(event)?.delete(listener);
}
send(data: string): void {
this.sent.push(data);
}
close(code?: number, reason?: string): void {
this.readyState = 3;
this.emit('close', { code, reason });
}
open(): void {
this.readyState = 1;
this.emit('open');
}
message(data: unknown): void {
this.emit('message', { data });
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) {
listener(...args);
}
}
}
const PRIVATE_EVENT: OneBotPrivateMessageEvent = {
time: 1,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
message_seq: 8,
user_id: 10001,
message: [{ type: 'text', data: { text: '/ping a b' } }],
raw_message: '/ping a b',
font: 0,
sender: { user_id: 10001, nickname: 'tester' },
};
describe('SnowLumaWebSocketClient', () => {
it('matches API responses by echo', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
accessToken: 'token',
webSocket: MockWebSocket,
});
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
expect(socket.url).toContain('access_token=token');
socket.open();
await connecting;
const status = client.getStatus();
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
const request = JSON.parse(socket.sent[0]!) as { echo: string };
socket.message(JSON.stringify({
status: 'ok',
retcode: 0,
data: { online: true, good: true },
echo: request.echo,
}));
await expect(status).resolves.toEqual({ online: true, good: true });
});
it('runs command handlers for matching message events', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
});
const handler = vi.fn();
client.command('ping', handler);
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
socket.message(JSON.stringify(PRIVATE_EVENT));
await vi.waitFor(() => {
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0]![2]).toMatchObject({ args: ['a', 'b'] });
});
});
it('supports caller AbortSignal cancellation for pending requests', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
});
const controller = new AbortController();
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
const request = client.getStatus({ signal: controller.signal });
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
controller.abort();
await expect(request).rejects.toBeInstanceOf(SnowLumaAbortError);
});
});

View File

@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"lib": ["ES2022", "DOM"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

12
pnpm-lock.yaml generated
View File

@@ -66,6 +66,18 @@ importers:
packages/runtime: {}
packages/sdk:
devDependencies:
'@types/node':
specifier: ^24.12.2
version: 24.12.2
typescript:
specifier: 'catalog:'
version: 6.0.2
vitest:
specifier: ^4.1.4
version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
packages/websocket:
devDependencies:
'@types/node':

View File

@@ -5,6 +5,7 @@
"include": [],
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/sdk" },
{ "path": "./packages/webui" }
]
}