Compare commits

..
Author SHA1 Message Date
dependabot[bot] 860217214a Bump eslint from 9.39.4 to 10.7.0
Bumps [eslint](https://github.com/eslint/eslint) from 9.39.4 to 10.7.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/compare/v9.39.4...v10.7.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-version: 10.7.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-15 13:33:48 +00:00
30 changed files with 838 additions and 2304 deletions
+21
View File
@@ -0,0 +1,21 @@
name: 📝 Service Request
description: Request a service or support task
title: '📝 [Service Request]: '
body:
- type: textarea
id: information
attributes:
label: Description
description: Provide all information.
placeholder: 'What happened? What did you expect to happen?'
validations:
required: false
- type: textarea
id: criteria
attributes:
label: Acceptance Criteria
description: What are the expectations?
placeholder: 'How do you want it implemented? How should it be tested?'
validations:
required: false
+21
View File
@@ -0,0 +1,21 @@
name: 👮 Story
description: Describe a user story
title: '👮 [Story]: '
body:
- type: textarea
id: information
attributes:
label: Description
description: Provide all information.
placeholder: 'What happened? What did you expect to happen?'
validations:
required: false
- type: textarea
id: criteria
attributes:
label: Acceptance Criteria
description: What are the expectations?
placeholder: 'How do you want it implemented? How should it be tested?'
validations:
required: false
+11
View File
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: 'npm' # See documentation for possible values
directory: '/' # Location of package manifests
schedule:
interval: 'daily'
@@ -9,7 +9,6 @@ permissions:
env:
VERSION_MAJOR: '1'
VERSION_MINOR: '1'
VERSION_PATCH: ${{ gitea.run_number }}
jobs:
build:
@@ -22,10 +21,10 @@ jobs:
fetch-depth: 0
fetch-tags: true
- name: Use NodeJS 24
- name: Use NodeJS v22.22.3
uses: actions/setup-node@v6
with:
node-version: '24'
node-version: '22.22.3'
registry-url: 'https://registry.npmjs.org'
package-manager-cache: false
@@ -40,7 +39,7 @@ jobs:
id: release_version
run: |
package_version="$(node -p "require('./package.json').version")"
echo "tag=${package_version}" >> "$GITEA_OUTPUT"
echo "tag=${package_version}" >> "$GITHUB_OUTPUT"
- name: Run Build
run: npm run build
@@ -50,29 +49,24 @@ jobs:
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Create Gitea release
- name: Create GitHub release
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_API_URL: ${{ gitea.api_url }}
GITEA_REPOSITORY: ${{ gitea.repository }}
GITEA_SERVER_URL: ${{ gitea.server_url }}
GITEA_SHA: ${{ gitea.sha }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_TAG: v${{ steps.release_version.outputs.tag }}
run: |
git fetch --force --tags
releases_url="${GITEA_API_URL}/repos/${GITEA_REPOSITORY}/releases"
previous_tag="$(curl --fail --silent --show-error --header "Authorization: token ${GITEA_TOKEN}" "${releases_url}?limit=50" | jq -r --arg tag "$RELEASE_TAG" '[.[] | select(.draft == false and .tag_name != $tag)][0].tag_name // empty')"
previous_tag="$(gh api repos/${{ github.repository }}/releases --paginate --jq '.[] | select(.draft == false) | .tag_name' | grep -Fxv "$RELEASE_TAG" | head -n 1 || true)"
if [ -n "$previous_tag" ]; then
if git rev-parse --verify --quiet "${previous_tag}^{commit}" >/dev/null; then
commit_messages="$(git log --reverse --format='- %s' "${previous_tag}..${GITEA_SHA}")"
commit_messages="$(git log --reverse --format='- %s' "${previous_tag}..${GITHUB_SHA}")"
else
commit_messages="$(git log --reverse --format='- %s' "${GITEA_SHA}")"
commit_messages="$(git log --reverse --format='- %s' "${GITHUB_SHA}")"
fi
full_changelog="${GITEA_SERVER_URL}/${GITEA_REPOSITORY}/compare/${previous_tag}...${RELEASE_TAG}"
full_changelog="https://github.com/${{ github.repository }}/compare/${previous_tag}...${RELEASE_TAG}"
else
commit_messages="$(git log --reverse --format='- %s' "${GITEA_SHA}")"
commit_messages="$(git log --reverse --format='- %s' "${GITHUB_SHA}")"
full_changelog=""
fi
@@ -90,13 +84,8 @@ jobs:
fi
} > release-notes.md
jq -n --arg tag "$RELEASE_TAG" --arg target "$GITEA_SHA" --rawfile body release-notes.md \
'{tag_name: $tag, target_commitish: $target, name: $tag, body: $body, draft: false, prerelease: false}' > release.json
release_id="$(curl --silent --header "Authorization: token ${GITEA_TOKEN}" "${releases_url}/tags/${RELEASE_TAG}" | jq -r '.id // empty')"
if [ -n "$release_id" ]; then
curl --fail-with-body --request PATCH --header "Authorization: token ${GITEA_TOKEN}" --header 'Content-Type: application/json' --data @release.json "${releases_url}/${release_id}"
if gh release view "$RELEASE_TAG" >/dev/null 2>&1; then
gh release edit "$RELEASE_TAG" --title "$RELEASE_TAG" --notes-file release-notes.md
else
curl --fail-with-body --request POST --header "Authorization: token ${GITEA_TOKEN}" --header 'Content-Type: application/json' --data @release.json "$releases_url"
gh release create "$RELEASE_TAG" --target "${GITHUB_SHA}" --title "$RELEASE_TAG" --notes-file release-notes.md
fi
@@ -15,10 +15,10 @@ jobs:
- name: Checkout Repository
uses: actions/checkout@v4
- name: use NodeJS 24
- name: use NodeJS v22.22.3
uses: actions/setup-node@v4
with:
node-version: '24'
node-version: '22.22.3'
- name: Install Dependencies
run: npm ci
-106
View File
@@ -1,106 +0,0 @@
name: Redirect contributions to Gitea
on:
issues:
types: [opened, reopened]
pull_request_target:
types: [opened, reopened]
permissions:
issues: write
pull-requests: write
concurrency:
group: migrate-${{ github.event_name }}-${{ github.event.issue.number || github.event.pull_request.number }}
env:
GITEA_API_URL: https://git.lechner-systems.at/api/v1
GITEA_REPOSITORY: FrauJulian/Discord-Audio-Stream
jobs:
migrate-issue:
if: github.event_name == 'issues'
runs-on: ubuntu-latest
steps:
- name: Migrate issue and close
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
set -euo pipefail
number="$(jq -r '.issue.number' "$GITHUB_EVENT_PATH")"
title="$(jq -r '.issue.title' "$GITHUB_EVENT_PATH")"
body="$(jq -r '.issue.body // ""' "$GITHUB_EVENT_PATH")"
author="$(jq -r '.issue.user.login' "$GITHUB_EVENT_PATH")"
source_url="$(jq -r '.issue.html_url' "$GITHUB_EVENT_PATH")"
github_api="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}"
migrated_url="$(
curl --fail --silent --show-error \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Accept: application/vnd.github+json" \
"${github_api}/issues/${number}/comments?per_page=100" |
jq -r '[.[] | select(.user.login == "github-actions[bot]" and (.body | startswith("Migrated to Gitea: ")))] | first | .body // "" | sub("^Migrated to Gitea: "; "")'
)"
if [ -z "$migrated_url" ]; then
migrated_body="${body}
---
Originally opened by @${author} on GitHub: ${source_url}"
jq -n \
--arg title "$title" \
--arg body "$migrated_body" \
'{title: $title, body: $body}' > gitea-request.json
curl --fail-with-body \
--request POST \
--header "Authorization: token ${GITEA_TOKEN}" \
--header "Content-Type: application/json" \
--data @gitea-request.json \
"${GITEA_API_URL}/repos/${GITEA_REPOSITORY}/issues" > gitea-response.json
migrated_url="$(jq -r '.html_url' gitea-response.json)"
jq -n --arg body "Migrated to Gitea: ${migrated_url}" '{body: $body}' > github-comment.json
curl --fail-with-body \
--request POST \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Content-Type: application/json" \
--data @github-comment.json \
"${github_api}/issues/${number}/comments"
fi
curl --fail-with-body \
--request PATCH \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Content-Type: application/json" \
--data '{"state":"closed","state_reason":"not_planned"}' \
"${github_api}/issues/${number}"
redirect-pull-request:
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-latest
steps:
- name: Redirect pull request and close
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
number="$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH")"
github_api="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}"
curl --fail-with-body \
--request POST \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Content-Type: application/json" \
--data '{"body":"Please open the Pull Request on Gitea"}' \
"${github_api}/issues/${number}/comments"
curl --fail-with-body \
--request PATCH \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Content-Type: application/json" \
--data '{"state":"closed"}' \
"${github_api}/pulls/${number}"
+1 -1
View File
@@ -1,4 +1,4 @@
.gitea
.github
.git
.idea
+21 -31
View File
@@ -1,8 +1,8 @@
# Discord Audio Stream
[![npm](https://img.shields.io/npm/dw/discord-audio-stream)](http://npmjs.org/package/discord-audio-stream)
![latest release](https://img.shields.io/gitea/v/release/FrauJulian/Discord-Audio-Stream?gitea_url=https%3A%2F%2Fgit.lechner-systems.at&color=blue)
![Gitea Repo stars](https://img.shields.io/gitea/stars/FrauJulian/Discord-Audio-Stream?gitea_url=https%3A%2F%2Fgit.lechner-systems.at&style=social)
![latest release](https://img.shields.io/badge/dynamic/json?label=release&query=$.name&url=https%3A%2F%2Fapi.github.com%2Frepos%2FFrauJulian%2Fdiscord-audio-stream%2Freleases%2Flatest&color=blue)
![GitHub Repo stars](https://img.shields.io/github/stars/FrauJulian/discord-audio-stream?style=social)
`discord-audio-stream` is a small TypeScript library for managed Discord voice playback through
`@discordjs/voice` and ffmpeg.
@@ -13,19 +13,17 @@ reused.
## Support
Create an [issue](https://git.lechner-systems.at/FrauJulian/Discord-Audio-Stream/issues) on Gitea or contact
Create an [issue](https://github.com/FrauJulian/Discord-Audio-Stream/issues) on GitHub or contact
[`fraujulian`](https://discord.com/users/860206216893693973) on Discord.
## Installation
Node.js `24.x` is required.
Node.js `22.22.3` or newer is required.
```bash
npm install discord-audio-stream @discordjs/voice @discordjs/opus
npm install discord-audio-stream @discordjs/voice prism-media @snazzah/davey opusscript
```
Use `opusscript@^0.0.8` only as a slower JavaScript fallback when `@discordjs/opus` cannot be installed.
`ffmpeg` must be available either on the host PATH or through the optional `ffmpeg-static` package:
```bash
@@ -34,6 +32,13 @@ npm install ffmpeg-static
Use `ffmpeg.mode: 'native'` for PATH-based ffmpeg and `ffmpeg.mode: 'static'` for `ffmpeg-static`.
`libsodium-wrappers` is optional. Install it only when your runtime does not support `aes-256-gcm`:
```bash
node -e "console.log(require('node:crypto').getCiphers().includes('aes-256-gcm'))"
npm install libsodium-wrappers
```
## Basic Usage
```ts
@@ -88,15 +93,6 @@ manager.dispose(); // final cleanup; the manager cannot be reused
`connect()` joins the configured voice channel. `play(source?)` starts playback on an existing connection. Use `start()`
when you want both.
For scoped playback, `AudioManager` supports explicit resource management:
```ts
{
using manager = new AudioManager(options);
await manager.start();
} // disposed automatically
```
## API
```ts
@@ -115,7 +111,6 @@ type AudioManagerOptions = {
source?: { type: 'url'; url: string } | { type: 'file'; path: string };
renewIntervalMs?: number | false;
connectTimeoutMs?: number;
onError?: (error: Error) => void;
volume?: {
enabled?: boolean;
initialPercent?: number;
@@ -125,12 +120,12 @@ type AudioManagerOptions = {
### Defaults
| Option | Default |
| ------------------ | ---------- |
| `ffmpeg.mode` | `'native'` |
| `connectTimeoutMs` | `20_000` |
| `renewIntervalMs` | `false` |
| `volume.enabled` | `false` |
| Option | Default |
| ------------------ | ----------- |
| `ffmpeg.mode` | `'native'` |
| `connectTimeoutMs` | `20_000` |
| `renewIntervalMs` | `5_400_000` |
| `volume.enabled` | `false` |
### Methods
@@ -146,7 +141,6 @@ type AudioManagerOptions = {
| `stop()` | Stops playback, clears renewal, and destroys the voice connection. |
| `setVolume(percent)` | Sets volume from `0` to `100`; requires `volume.enabled: true`. |
| `dispose()` | Idempotently releases timers, ffmpeg, streams, player state, and voice connection. |
| `[Symbol.dispose]()` | Enables automatic cleanup with TypeScript's `using` declaration. |
### State
@@ -181,9 +175,8 @@ Default ffmpeg output is raw Discord-compatible PCM: `s16le`, `48000 Hz`, `2 cha
You can override ffmpeg arguments through `ffmpeg.inputArgs` and `ffmpeg.outputArgs`. When you override them, you are
responsible for keeping the output compatible with `StreamType.Raw`.
Connection renewal is disabled by default because `@discordjs/voice` handles recoverable disconnects. Set
`renewIntervalMs` only when an application has a measured need for periodic restarts. `stop()` and `dispose()` always
clear the renewal timer.
By default, the manager schedules a renewal after `5_400_000 ms` so long-running streams can reconnect periodically.
Set `renewIntervalMs: false` to disable it. `stop()` and `dispose()` always clear the renewal timer.
## Errors
@@ -197,9 +190,6 @@ The package exports these error classes:
Configuration problems, such as a missing source or invalid URL, throw `AudioManagerConfigError`. Invalid lifecycle
operations, such as calling `pause()` while nothing is playing, throw `AudioManagerStateError`.
Use `onError` to observe asynchronous audio player and voice connection errors. The manager cleans up failed playback
and unrecoverable connections before invoking the callback.
## Development
```bash
@@ -214,4 +204,4 @@ npm run build
## Enjoy the package?
Give it a star on [Gitea](https://git.lechner-systems.at/FrauJulian/Discord-Audio-Stream)!
Give it a star on [GitHub](https://github.com/FrauJulian/discord-audio-stream)!
+1 -1
View File
@@ -14,7 +14,7 @@ If a vulnerability is fixed, the fix will generally be released only for the cur
## Reporting a Vulnerability
Do not open a public Gitea issue for security vulnerabilities.
Do not open a public GitHub issue for security vulnerabilities.
Report vulnerabilities privately by email to `fraujulian@lechner.top`.
+2 -21
View File
@@ -1,9 +1,7 @@
/** @type {import('eslint').Linter.FlatConfig[]} */
const prettierConfig = require('eslint-config-prettier/flat');
const config = [
{
ignores: ['coverage/', 'dist/', 'node_modules/'],
ignores: ['dist/', 'node_modules/'],
},
{
@@ -79,23 +77,6 @@ const config = [
},
},
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
parserOptions: {
project: ['./tsconfig.eslint.json'],
tsconfigRootDir: __dirname,
},
},
rules: {
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-misused-promises': ['error', { checksVoidReturn: false }],
'@typescript-eslint/no-unsafe-assignment': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
},
},
{
files: ['**/*.{js,cjs}'],
languageOptions: {
@@ -107,4 +88,4 @@ const config = [
},
];
module.exports = [...config, prettierConfig];
module.exports = config;
+25
View File
@@ -0,0 +1,25 @@
/** @type {import('eslint').Linter.FlatConfig[]} */
const base = require('./eslint.config.cjs');
const typeAwareLayer = {
files: ['**/*.{ts,tsx}'],
languageOptions: {
parser: require('@typescript-eslint/parser'),
parserOptions: {
project: ['./tsconfig.eslint.json'],
tsconfigRootDir: __dirname,
},
},
plugins: {
'@typescript-eslint': require('@typescript-eslint/eslint-plugin'),
},
rules: {
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-misused-promises': ['warn', { checksVoidReturn: false }],
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
},
};
module.exports = [...base, typeAwareLayer];
+550 -1587
View File
File diff suppressed because it is too large Load Diff
+24 -27
View File
@@ -22,27 +22,30 @@
"files": [
"dist"
],
"sideEffects": false,
"directories": {
"lib": "src"
},
"scripts": {
"version:place": "node set-version.js set-ci-version",
"version:check": "node set-version.js check-placeholder",
"version:fix": "node set-version.js fix-placeholder",
"lint": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs",
"lint:fix": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs --fix",
"lint:types": "eslint . --config eslint.config.typeaware.cjs --ext .ts,.tsx",
"format": "prettier --write .",
"format:check": "prettier --check .",
"typecheck": "tsc --noEmit --declaration --isolatedDeclarations",
"typecheck": "tsc --noEmit",
"test": "jest --runInBand",
"check": "npm run version:check && npm run format:check && npm run lint && npm run typecheck && npm run test",
"check": "npm run version:check && npm run format:check && npm run lint && npm run lint:types && npm run typecheck && npm run test",
"fix": "npm run version:fix && npm run format && npm run lint:fix",
"build": "tsup",
"build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsup && tsc -p tsconfig.build.json && node scripts/copy-dts.cjs",
"prepare": "husky"
},
"repository": {
"type": "git",
"url": "git+https://git.lechner-systems.at/FrauJulian/Discord-Audio-Stream.git"
"url": "git+https://github.com/FrauJulian/Discord-Audio-Stream.git"
},
"bugs": "https://git.lechner-systems.at/FrauJulian/Discord-Audio-Stream/issues",
"bugs": "https://github.com/FrauJulian/Discord-Audio-Stream/issues",
"funding": "https://ko-fi.com/FrauJulian",
"keywords": [
"discord",
@@ -67,52 +70,46 @@
]
},
"devDependencies": {
"@discordjs/opus": "^0.10.0",
"@jest/globals": "^30.4.1",
"@types/ejs": "^3.1.5",
"@types/node": "^24.0.0",
"@typescript-eslint/eslint-plugin": "^8.67.0",
"@typescript-eslint/parser": "^8.67.0",
"eslint": "^9.39.5",
"@types/node": "^26.0.0",
"@typescript-eslint/eslint-plugin": "^8.61.1",
"@typescript-eslint/parser": "^8.61.1",
"eslint": "^10.7.0",
"eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-n": "^18.3.0",
"eslint-plugin-n": "^18.1.0",
"eslint-plugin-promise": "^7.3.0",
"eslint-plugin-unused-imports": "^4.4.1",
"husky": "^9.1.7",
"jest": "^30.4.2",
"prettier": "^3.9.6",
"ts-jest": "^29.4.12",
"prettier": "^3.8.4",
"ts-jest": "^29.4.11",
"tsup": "^8.5.1",
"@typescript/native": "npm:typescript@^7.0.2",
"typescript": "npm:@typescript/typescript6@^6.0.2"
"typescript": "^6.0.3"
},
"peerDependencies": {
"@discordjs/opus": "^0.10.0",
"@discordjs/voice": "^0.19.2",
"@snazzah/davey": "^0.1.12",
"ffmpeg-static": "^5.3.0",
"opusscript": "^0.0.8"
"libsodium-wrappers": "^0.8.4",
"opusscript": "^0.0.8",
"prism-media": "^1.3.5"
},
"peerDependenciesMeta": {
"@discordjs/opus": {
"optional": true
},
"ffmpeg-static": {
"optional": true
},
"opusscript": {
"libsodium-wrappers": {
"optional": true
}
},
"overrides": {
"@discordjs/node-pre-gyp": {
"tar": "^7.5.22"
},
"esbuild": "^0.28.2"
"esbuild": "^0.28.1"
},
"engines": {
"node": "24.x"
"node": ">=22.22.3"
},
"private": false,
"publishConfig": {
+11
View File
@@ -0,0 +1,11 @@
const { copyFileSync, existsSync } = require('node:fs');
const { join } = require('node:path');
const declarationFile = join(__dirname, '..', 'dist', 'index.d.ts');
const esmDeclarationFile = join(__dirname, '..', 'dist', 'index.d.mts');
if (!existsSync(declarationFile)) {
throw new Error(`Missing declaration file: ${declarationFile}`);
}
copyFileSync(declarationFile, esmDeclarationFile);
+1 -1
View File
@@ -76,7 +76,7 @@ function fixPlaceholder() {
function getCiVersion() {
const major = process.env.VERSION_MAJOR;
const minor = process.env.VERSION_MINOR;
const patch = process.env.VERSION_PATCH;
const patch = process.env.VERSION_PATCH ?? process.env.GITHUB_RUN_NUMBER;
const segments = { major, minor, patch };
for (const [name, value] of Object.entries(segments)) {
+29 -158
View File
@@ -4,7 +4,6 @@ import {
createAudioResource,
entersState,
joinVoiceChannel,
AudioPlayerStatus,
NoSubscriberBehavior,
StreamType,
VoiceConnectionStatus,
@@ -22,30 +21,14 @@ import type {
} from './types';
const DEFAULT_CONNECT_TIMEOUT_MS = 20_000;
const DISCONNECT_RECOVERY_TIMEOUT_MS = 5_000;
const MAX_TIMER_DELAY_MS = 2_147_483_647;
const DEFAULT_RENEW_INTERVAL_MS = 5_400_000;
function assertValidTimerDelay(value: number, optionName: string): void {
if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {
throw new AudioManagerConfigError(
`${optionName} must be an integer between 1 and ${MAX_TIMER_DELAY_MS} milliseconds.`,
);
}
}
function assertValidVolumePercent(value: number): void {
if (!Number.isFinite(value) || value < 0 || value > 100) {
throw new AudioManagerConfigError('Volume must be between 0 and 100 percent.');
}
}
export default class AudioManager implements Disposable {
export default class AudioManager {
private readonly audioPlayer: AudioPlayer;
private connection: VoiceConnection | undefined;
private resource: AudioResource | undefined;
private ffmpeg: FfmpegProcessHandle | undefined;
private connectAttempt: AbortController | undefined;
private renewTimer: NodeJS.Timeout | undefined;
private playbackState: PlaybackState = 'idle';
private connectionOptions: VoiceConnectionOptions | undefined;
@@ -54,23 +37,9 @@ export default class AudioManager implements Disposable {
Omit<AudioManagerOptions, 'connectTimeoutMs'>;
public constructor(options: AudioManagerOptions = {}) {
const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
assertValidTimerDelay(connectTimeoutMs, 'connectTimeoutMs');
if (typeof options.renewIntervalMs === 'number') {
assertValidTimerDelay(options.renewIntervalMs, 'renewIntervalMs');
}
if (options.volume?.initialPercent !== undefined) {
if (options.volume.enabled !== true) {
throw new AudioManagerConfigError('volume.initialPercent requires volume.enabled to be true.');
}
assertValidVolumePercent(options.volume.initialPercent);
}
this.options = {
...options,
connectTimeoutMs,
connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
};
this.connectionOptions = options.connection;
this.audioSource = options.source;
@@ -79,15 +48,6 @@ export default class AudioManager implements Disposable {
noSubscriber: NoSubscriberBehavior.Play,
},
});
this.audioPlayer.on('error', (error) => {
this.finishPlayback(error.resource);
this.reportError(error);
});
this.audioPlayer.on(AudioPlayerStatus.Idle, (oldState) => {
if ('resource' in oldState) {
this.finishPlayback(oldState.resource);
}
});
}
public get state(): PlaybackState {
@@ -99,7 +59,7 @@ export default class AudioManager implements Disposable {
}
public get isConnected(): boolean {
return this.connection?.state.status === VoiceConnectionStatus.Ready;
return Boolean(this.connection);
}
public setConnection(options: VoiceConnectionOptions): void {
@@ -119,55 +79,30 @@ export default class AudioManager implements Disposable {
throw new AudioManagerConfigError('Voice connection options are required before connecting.');
}
this.cancelConnectAttempt();
const attempt = new AbortController();
this.connectAttempt = attempt;
this.clearRenewTimer();
this.playbackState = 'connecting';
const previousConnection = this.connection;
this.connection = undefined;
let connection: VoiceConnection | undefined;
this.connection?.destroy();
const connection = joinVoiceChannel({
guildId: this.connectionOptions.guildId,
channelId: this.connectionOptions.channelId,
adapterCreator: this.connectionOptions.adapterCreator,
});
this.connection = connection;
connection.subscribe(this.audioPlayer);
try {
previousConnection?.destroy();
connection = joinVoiceChannel({
guildId: this.connectionOptions.guildId,
channelId: this.connectionOptions.channelId,
adapterCreator: this.connectionOptions.adapterCreator,
});
this.connection = connection;
this.observeConnection(connection);
connection.subscribe(this.audioPlayer);
await entersState(
connection,
VoiceConnectionStatus.Ready,
AbortSignal.any([attempt.signal, AbortSignal.timeout(this.options.connectTimeoutMs)]),
);
await entersState(connection, VoiceConnectionStatus.Ready, this.options.connectTimeoutMs);
} catch (error) {
if (this.connectAttempt !== attempt) {
throw new AudioManagerStateError('Voice connection was stopped before it became ready.', {
cause: error,
});
}
this.connectAttempt = undefined;
if (connection && connection.state.status !== VoiceConnectionStatus.Destroyed) {
connection.destroy();
}
connection.destroy();
if (this.connection === connection) {
this.connection = undefined;
}
this.playbackState = 'stopped';
throw error;
}
if (this.connectAttempt !== attempt || this.connection !== connection) {
if (this.connection !== connection) {
throw new AudioManagerStateError('Voice connection was stopped before it became ready.');
}
this.connectAttempt = undefined;
this.playbackState = 'ready';
this.scheduleRenewal();
}
@@ -179,7 +114,7 @@ export default class AudioManager implements Disposable {
this.setSource(source);
}
if (!this.isConnected) {
if (!this.connection) {
throw new AudioManagerStateError('A voice connection is required before audio can be played.');
}
@@ -197,22 +132,17 @@ export default class AudioManager implements Disposable {
inlineVolume: this.options.volume?.enabled === true,
});
} catch (error) {
if (this.ffmpeg !== ffmpeg) {
throw error instanceof AudioManagerStateError
? error
: new AudioManagerStateError('Playback was stopped before ffmpeg became ready.', {
cause: error,
});
if (this.ffmpeg === ffmpeg) {
this.stopCurrentPlayback();
}
this.stopCurrentPlayback();
throw error;
}
if (this.options.volume?.enabled === true && this.options.volume.initialPercent !== undefined) {
this.setVolume(this.options.volume.initialPercent);
}
try {
if (this.options.volume?.enabled === true && this.options.volume.initialPercent !== undefined) {
this.setVolume(this.options.volume.initialPercent);
}
this.audioPlayer.play(this.resource);
this.playbackState = 'playing';
} catch (error) {
@@ -254,7 +184,6 @@ export default class AudioManager implements Disposable {
return;
}
this.cancelConnectAttempt();
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
@@ -271,7 +200,9 @@ export default class AudioManager implements Disposable {
throw new AudioManagerStateError('Volume control requires volume.enabled to be true.');
}
assertValidVolumePercent(volumeInPercent);
if (!Number.isFinite(volumeInPercent) || volumeInPercent < 0 || volumeInPercent > 100) {
throw new AudioManagerConfigError('Volume must be between 0 and 100 percent.');
}
if (!this.resource?.volume) {
throw new AudioManagerStateError('No audio resource with volume control is currently active.');
@@ -285,7 +216,6 @@ export default class AudioManager implements Disposable {
return;
}
this.cancelConnectAttempt();
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
@@ -296,10 +226,6 @@ export default class AudioManager implements Disposable {
this.playbackState = 'disposed';
}
public [Symbol.dispose](): void {
this.dispose();
}
private resolveSource(): ResolvedAudioSource {
if (!this.audioSource) {
throw new AudioManagerConfigError('Audio source is required before playback can start.');
@@ -312,7 +238,7 @@ export default class AudioManager implements Disposable {
source: this.audioSource,
};
} catch (error) {
throw new AudioManagerConfigError('Invalid audio source URL.', { cause: error });
throw new AudioManagerConfigError(`Invalid audio source URL. Cause: ${String(error)}`);
}
}
@@ -325,18 +251,14 @@ export default class AudioManager implements Disposable {
}
private scheduleRenewal(): void {
const renewIntervalMs = this.options.renewIntervalMs;
const renewIntervalMs = this.options.renewIntervalMs ?? DEFAULT_RENEW_INTERVAL_MS;
if (renewIntervalMs === undefined || renewIntervalMs === false) {
if (renewIntervalMs === false) {
return;
}
this.renewTimer = setTimeout(() => {
void this.start().catch((error: unknown) => {
if (this.playbackState === 'disposed') {
return;
}
void this.start().catch(() => {
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
@@ -344,7 +266,6 @@ export default class AudioManager implements Disposable {
this.connection?.destroy();
this.connection = undefined;
this.playbackState = 'stopped';
this.reportError(error);
});
}, renewIntervalMs);
@@ -353,51 +274,6 @@ export default class AudioManager implements Disposable {
}
}
private observeConnection(connection: VoiceConnection): void {
connection.on('error', (error) => {
this.reportError(error);
});
connection.on(VoiceConnectionStatus.Disconnected, () => this.handleDisconnectedConnection(connection));
}
private async handleDisconnectedConnection(connection: VoiceConnection): Promise<void> {
try {
await Promise.race([
entersState(connection, VoiceConnectionStatus.Signalling, DISCONNECT_RECOVERY_TIMEOUT_MS),
entersState(connection, VoiceConnectionStatus.Connecting, DISCONNECT_RECOVERY_TIMEOUT_MS),
]);
} catch (error) {
if (this.connection !== connection) {
return;
}
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
this.connection = undefined;
if (connection.state.status !== VoiceConnectionStatus.Destroyed) {
connection.destroy();
}
this.playbackState = 'stopped';
this.reportError(error);
}
}
private finishPlayback(resource: AudioResource): void {
if (this.resource !== resource) {
return;
}
this.stopCurrentPlayback();
if (this.playbackState !== 'disposed') {
this.playbackState = this.isConnected ? 'ready' : 'stopped';
}
}
private reportError(error: unknown): void {
this.options.onError?.(error instanceof Error ? error : new Error(String(error)));
}
private clearRenewTimer(): void {
if (this.renewTimer) {
clearTimeout(this.renewTimer);
@@ -405,11 +281,6 @@ export default class AudioManager implements Disposable {
}
}
private cancelConnectAttempt(): void {
this.connectAttempt?.abort();
this.connectAttempt = undefined;
}
private stopCurrentPlayback(): void {
this.resource?.playStream.destroy();
this.resource = undefined;
+7 -4
View File
@@ -1,6 +1,6 @@
export class AudioManagerError extends Error {
public constructor(message: string, options?: ErrorOptions) {
super(message, options);
public constructor(message: string) {
super(message);
this.name = new.target.name;
}
}
@@ -10,7 +10,10 @@ export class AudioManagerConfigError extends AudioManagerError {}
export class AudioManagerStateError extends AudioManagerError {}
export class FfmpegProcessError extends AudioManagerError {
public constructor(message: string, cause?: unknown) {
super(message, cause === undefined ? undefined : { cause });
public constructor(
message: string,
public readonly cause?: unknown,
) {
super(message);
}
}
+39 -76
View File
@@ -14,8 +14,8 @@ const FORCE_KILL_TIMEOUT_MS = 2_000;
const STDERR_TAIL_BYTES = 4_096;
export type FfmpegProcessHandle = {
readonly process: ChildProcessByStdio<null, Readable, Readable>;
readonly ready: Promise<void>;
process: ChildProcessByStdio<null, Readable, Readable>;
ready: Promise<void>;
stop(): void;
};
@@ -36,8 +36,7 @@ export function resolveFfmpegExecutable(options: FfmpegOptions = {}): string {
}
} catch (error) {
throw new AudioManagerConfigError(
'Unable to resolve ffmpeg-static. Install it or pass ffmpeg.executablePath.',
{ cause: error },
`Unable to resolve ffmpeg-static. Install it or pass ffmpeg.executablePath. Cause: ${String(error)}`,
);
}
@@ -53,8 +52,7 @@ export function startFfmpeg(input: string, options: FfmpegOptions = {}): FfmpegP
...(options.outputArgs ?? DEFAULT_OUTPUT_ARGS),
];
const childProcess = spawn(executable, args, { stdio: ['ignore', 'pipe', 'pipe'] });
const abortController = new AbortController();
const ready = waitForFfmpegOutput(childProcess, abortController.signal);
const ready = waitForFfmpegOutput(childProcess);
childProcess.stderr.resume();
@@ -62,76 +60,49 @@ export function startFfmpeg(input: string, options: FfmpegOptions = {}): FfmpegP
process: childProcess,
ready,
stop: (): void => {
stopProcess(childProcess, abortController);
stopProcess(childProcess);
},
};
}
function waitForFfmpegOutput(
childProcess: ChildProcessByStdio<null, Readable, Readable>,
signal: AbortSignal,
): Promise<void> {
const { promise, resolve, reject } = Promise.withResolvers<void>();
function waitForFfmpegOutput(childProcess: ChildProcessByStdio<null, Readable, Readable>): Promise<void> {
let stderrTail = '';
let settled = false;
const appendStderr = (chunk: Buffer | string): void => {
stderrTail = (stderrTail + String(chunk)).slice(-STDERR_TAIL_BYTES);
};
const cleanup = (): void => {
childProcess.off('exit', onExit);
childProcess.stdout.off('readable', onReadable);
childProcess.stderr.off('data', appendStderr);
signal.removeEventListener('abort', onAbort);
};
const settle = (complete: () => void): void => {
if (settled) {
return;
}
settled = true;
cleanup();
complete();
};
const fail = (message: string, cause?: unknown): void => {
settle(() => reject(new FfmpegProcessError(addStderrTail(message, stderrTail), cause)));
};
const onError = (error: Error): void => {
if (!settled) {
fail(`Unable to start ffmpeg. Cause: ${error.message}`, error);
}
};
const onExit = (code: number | null, exitSignal: NodeJS.Signals | null): void => {
fail(`ffmpeg exited before producing audio. Exit code: ${code ?? 'none'}, signal: ${exitSignal ?? 'none'}.`);
};
const onReadable = (): void => {
settle(() => resolve());
};
const onAbort = (): void => {
const reason: unknown = signal.reason;
settle(() =>
reject(
reason instanceof Error
? reason
: new FfmpegProcessError('ffmpeg was stopped before producing audio.', reason),
),
);
};
childProcess.stderr.on('data', appendStderr);
childProcess.on('error', onError);
childProcess.once('exit', onExit);
childProcess.stdout.once('readable', onReadable);
signal.addEventListener('abort', onAbort, { once: true });
return promise;
return new Promise((resolve, reject) => {
const cleanup = (): void => {
childProcess.off('error', onError);
childProcess.off('exit', onExit);
childProcess.stdout.off('readable', onReadable);
};
const fail = (message: string, cause?: unknown): void => {
cleanup();
reject(new FfmpegProcessError(addStderrTail(message, stderrTail), cause));
};
const onError = (error: Error): void => {
fail(`Unable to start ffmpeg. Cause: ${error.message}`, error);
};
const onExit = (code: number | null, signal: NodeJS.Signals | null): void => {
fail(`ffmpeg exited before producing audio. Exit code: ${code ?? 'none'}, signal: ${signal ?? 'none'}.`);
};
const onReadable = (): void => {
cleanup();
resolve();
};
childProcess.once('error', onError);
childProcess.once('exit', onExit);
childProcess.stdout.once('readable', onReadable);
});
}
function addStderrTail(message: string, stderrTail: string): string {
@@ -140,30 +111,22 @@ function addStderrTail(message: string, stderrTail: string): string {
return trimmedTail ? `${message} stderr: ${trimmedTail}` : message;
}
function stopProcess(
childProcess: ChildProcessByStdio<null, Readable, Readable>,
abortController: AbortController,
): void {
if (abortController.signal.aborted) {
return;
}
abortController.abort(new FfmpegProcessError('ffmpeg was stopped before producing audio.'));
function stopProcess(childProcess: ChildProcessByStdio<null, Readable, Readable>): void {
childProcess.stdout.destroy();
childProcess.stderr.destroy();
childProcess.removeAllListeners();
if (childProcess.exitCode !== null || childProcess.signalCode !== null) {
if (childProcess.killed || childProcess.exitCode !== null || childProcess.signalCode !== null) {
return;
}
childProcess.kill('SIGTERM');
const forceKillTimeout = setTimeout(() => {
if (childProcess.exitCode === null && childProcess.signalCode === null) {
if (!childProcess.killed && childProcess.exitCode === null && childProcess.signalCode === null) {
childProcess.kill('SIGKILL');
}
}, FORCE_KILL_TIMEOUT_MS);
childProcess.once('close', () => clearTimeout(forceKillTimeout));
forceKillTimeout.unref();
}
+2 -7
View File
@@ -143,9 +143,9 @@ export type AudioManagerOptions = {
/**
* Milliseconds after which the manager reconnects and restarts playback.
*
* Renewal is disabled unless an interval is provided.
* Set to `false` to disable renewal.
*
* @defaultValue `false`
* @defaultValue `5_400_000`
*/
renewIntervalMs?: number | false;
@@ -156,11 +156,6 @@ export type AudioManagerOptions = {
*/
connectTimeoutMs?: number;
/**
* Receives asynchronous audio player and voice connection errors.
*/
onError?: (error: Error) => void;
/**
* Optional inline volume configuration.
*/
+20 -213
View File
@@ -1,12 +1,5 @@
import { jest, describe, beforeEach, afterEach, it, expect } from '@jest/globals';
import {
AudioPlayerStatus,
createAudioPlayer,
createAudioResource,
entersState,
joinVoiceChannel,
VoiceConnectionStatus,
} from '@discordjs/voice';
import { createAudioResource, entersState, joinVoiceChannel } from '@discordjs/voice';
import { resolve } from 'node:path';
import { PassThrough } from 'node:stream';
@@ -17,37 +10,18 @@ import type { FfmpegProcessHandle } from '../src/ffmpeg';
import type { AudioSource, VoiceConnectionOptions } from '../src';
import type { VoiceConnection } from '@discordjs/voice';
type MockListener = (...args: unknown[]) => unknown;
const audioPlayerListeners = new Map<string, MockListener>();
const connectionListeners = new Map<string, MockListener>();
const secondConnectionListeners = new Map<string, MockListener>();
const mockAudioPlayer = {
on: jest.fn((event: string, listener: MockListener) => {
audioPlayerListeners.set(event, listener);
return mockAudioPlayer;
}),
play: jest.fn(),
pause: jest.fn(),
unpause: jest.fn(),
stop: jest.fn(),
};
const mockConnection = {
state: { status: 'ready' },
on: jest.fn((event: string, listener: MockListener) => {
connectionListeners.set(event, listener);
return mockConnection;
}),
subscribe: jest.fn(),
disconnect: jest.fn(),
destroy: jest.fn(),
};
const mockSecondConnection = {
state: { status: 'ready' },
on: jest.fn((event: string, listener: MockListener) => {
secondConnectionListeners.set(event, listener);
return mockSecondConnection;
}),
subscribe: jest.fn(),
disconnect: jest.fn(),
destroy: jest.fn(),
@@ -71,9 +45,6 @@ const mockFfmpegHandle: FfmpegProcessHandle = {
};
jest.mock('@discordjs/voice', () => ({
AudioPlayerStatus: {
Idle: 'idle',
},
NoSubscriberBehavior: {
Play: 'play',
},
@@ -81,11 +52,7 @@ jest.mock('@discordjs/voice', () => ({
Raw: 'raw',
},
VoiceConnectionStatus: {
Connecting: 'connecting',
Destroyed: 'destroyed',
Disconnected: 'disconnected',
Ready: 'ready',
Signalling: 'signalling',
},
createAudioPlayer: jest.fn(() => mockAudioPlayer),
createAudioResource: jest.fn(() => mockAudioResource),
@@ -112,6 +79,15 @@ const fileSourcePath = 'tests/audio.mp3';
const resolvedFileSourcePath = resolve(process.cwd(), fileSourcePath);
type MockedEntersStateReturn = ReturnType<typeof entersState>;
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
let resolve!: (value: T) => void;
const promise = new Promise<T>((promiseResolve) => {
resolve = promiseResolve;
});
return { promise, resolve };
}
function createMockFfmpegHandle(): FfmpegProcessHandle {
return {
process: {
@@ -122,24 +98,9 @@ function createMockFfmpegHandle(): FfmpegProcessHandle {
};
}
function listenerFor(listeners: Map<string, MockListener>, event: string): MockListener {
const listener = listeners.get(event);
if (!listener) {
throw new Error(`No listener registered for ${event}.`);
}
return listener;
}
describe('AudioManager', () => {
beforeEach(() => {
jest.clearAllMocks();
audioPlayerListeners.clear();
connectionListeners.clear();
secondConnectionListeners.clear();
mockConnection.state.status = VoiceConnectionStatus.Ready;
mockSecondConnection.state.status = VoiceConnectionStatus.Ready;
});
afterEach(() => {
@@ -169,72 +130,6 @@ describe('AudioManager', () => {
expect(mockAudioPlayer.play).toHaveBeenCalledWith(mockAudioResource);
});
it('does not schedule connection renewal by default', async () => {
jest.useFakeTimers();
const manager = new AudioManager({ connection: connectionOptions });
await manager.connect();
expect(jest.getTimerCount()).toBe(0);
manager.dispose();
});
it('reports voice connection errors without interrupting playback', async () => {
const connectionError = new Error('voice connection failed');
const onError = jest.fn();
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
onError,
});
await manager.start();
listenerFor(connectionListeners, 'error')(connectionError);
expect(onError).toHaveBeenCalledWith(connectionError);
expect(manager.state).toBe('playing');
});
it('keeps playback while a disconnected voice connection recovers', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.start();
await listenerFor(connectionListeners, VoiceConnectionStatus.Disconnected)();
expect(entersState).toHaveBeenCalledWith(mockVoiceConnection, VoiceConnectionStatus.Signalling, 5_000);
expect(entersState).toHaveBeenCalledWith(mockVoiceConnection, VoiceConnectionStatus.Connecting, 5_000);
expect(mockConnection.destroy).not.toHaveBeenCalled();
expect(manager.state).toBe('playing');
});
it('stops playback after an unrecoverable voice disconnect', async () => {
const disconnectError = new Error('voice connection did not recover');
const onError = jest.fn();
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
onError,
});
await manager.start();
jest.mocked(entersState).mockRejectedValueOnce(disconnectError).mockRejectedValueOnce(disconnectError);
mockConnection.state.status = VoiceConnectionStatus.Disconnected;
await listenerFor(connectionListeners, VoiceConnectionStatus.Disconnected)();
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioPlayer.stop).toHaveBeenCalledWith(true);
expect(mockConnection.destroy).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(disconnectError);
expect(manager.state).toBe('stopped');
expect(manager.isConnected).toBe(false);
});
it('cleans up when connection startup fails', async () => {
jest.useFakeTimers();
@@ -253,22 +148,9 @@ describe('AudioManager', () => {
expect(jest.getTimerCount()).toBe(0);
});
it('restores the stopped state when voice setup throws synchronously', async () => {
const connectionError = new Error('voice setup failed');
jest.mocked(joinVoiceChannel).mockImplementationOnce(() => {
throw connectionError;
});
const manager = new AudioManager({ connection: connectionOptions, renewIntervalMs: false });
await expect(manager.connect()).rejects.toBe(connectionError);
expect(manager.state).toBe('stopped');
expect(manager.isConnected).toBe(false);
});
it('does not become ready when stopped during connection startup', async () => {
jest.useFakeTimers();
const ready = Promise.withResolvers<VoiceConnection>();
const ready = deferred<VoiceConnection>();
jest.mocked(entersState).mockReturnValueOnce(ready.promise as unknown as MockedEntersStateReturn);
const manager = new AudioManager({
connection: connectionOptions,
@@ -286,9 +168,9 @@ describe('AudioManager', () => {
expect(jest.getTimerCount()).toBe(0);
});
it('keeps the latest connection when a stale connection attempt rejects', async () => {
const firstReady = Promise.withResolvers<VoiceConnection>();
const secondReady = Promise.withResolvers<VoiceConnection>();
it('keeps the latest connection when concurrent connects resolve out of order', async () => {
const firstReady = deferred<VoiceConnection>();
const secondReady = deferred<VoiceConnection>();
jest.mocked(joinVoiceChannel)
.mockReturnValueOnce(mockVoiceConnection)
.mockReturnValueOnce(mockSecondVoiceConnection);
@@ -302,7 +184,7 @@ describe('AudioManager', () => {
const firstConnect = manager.connect();
const secondConnect = manager.connect();
firstReady.reject(new Error('stale connection failed'));
firstReady.resolve(mockVoiceConnection);
secondReady.resolve(mockSecondVoiceConnection);
await expect(firstConnect).rejects.toThrow(AudioManagerStateError);
@@ -315,7 +197,7 @@ describe('AudioManager', () => {
});
it('does not become ready when disposed during connection startup', async () => {
const ready = Promise.withResolvers<VoiceConnection>();
const ready = deferred<VoiceConnection>();
jest.mocked(entersState).mockReturnValueOnce(ready.promise as unknown as MockedEntersStateReturn);
const manager = new AudioManager({
connection: connectionOptions,
@@ -324,7 +206,7 @@ describe('AudioManager', () => {
const connectPromise = manager.connect();
manager.dispose();
ready.reject(new Error('disposed connection failed'));
ready.resolve(mockVoiceConnection);
await expect(connectPromise).rejects.toThrow(AudioManagerStateError);
@@ -436,44 +318,8 @@ describe('AudioManager', () => {
expect(mockAudioResource.playStream.destroy).toHaveBeenCalledTimes(1);
});
it('cleans up and reports asynchronous audio player errors', async () => {
const playerError = Object.assign(new Error('audio stream failed'), { resource: mockAudioResource });
const onError = jest.fn();
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
onError,
});
await manager.start();
listenerFor(audioPlayerListeners, 'error')(playerError);
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioResource.playStream.destroy).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(playerError);
expect(manager.state).toBe('ready');
expect(manager.isPlaying).toBe(false);
});
it('returns to ready when the current audio resource becomes idle', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.start();
listenerFor(audioPlayerListeners, AudioPlayerStatus.Idle)({ resource: mockAudioResource });
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioResource.playStream.destroy).toHaveBeenCalledTimes(1);
expect(manager.state).toBe('ready');
expect(manager.isPlaying).toBe(false);
});
it('does not report playback when stopped before ffmpeg is ready', async () => {
const ready = Promise.withResolvers<void>();
const ready = deferred<void>();
jest.mocked(startFfmpeg).mockReturnValueOnce({
...mockFfmpegHandle,
ready: ready.promise,
@@ -496,7 +342,7 @@ describe('AudioManager', () => {
});
it('does not report playback when disposed before ffmpeg is ready', async () => {
const ready = Promise.withResolvers<void>();
const ready = deferred<void>();
jest.mocked(startFfmpeg).mockReturnValueOnce({
...mockFfmpegHandle,
ready: ready.promise,
@@ -519,7 +365,7 @@ describe('AudioManager', () => {
});
it('keeps only the latest concurrent playback', async () => {
const firstReady = Promise.withResolvers<void>();
const firstReady = deferred<void>();
const firstHandle = {
...createMockFfmpegHandle(),
ready: firstReady.promise,
@@ -615,36 +461,6 @@ describe('AudioManager', () => {
expect(mockAudioResource.volume.setVolume).toHaveBeenCalledWith(0.35);
});
it('rejects invalid initial volume before allocating audio resources', () => {
expect(
() =>
new AudioManager({
volume: {
enabled: true,
initialPercent: 101,
},
}),
).toThrow(AudioManagerConfigError);
expect(
() =>
new AudioManager({
volume: {
enabled: false,
initialPercent: 50,
},
}),
).toThrow(AudioManagerConfigError);
expect(createAudioPlayer).not.toHaveBeenCalled();
expect(createAudioResource).not.toHaveBeenCalled();
expect(startFfmpeg).not.toHaveBeenCalled();
});
it('rejects timer delays that Node.js cannot schedule safely', () => {
expect(() => new AudioManager({ connectTimeoutMs: 0 })).toThrow(AudioManagerConfigError);
expect(() => new AudioManager({ renewIntervalMs: 2_147_483_648 })).toThrow(AudioManagerConfigError);
});
it('rejects volume changes when inline volume is disabled', () => {
const manager = new AudioManager({ renewIntervalMs: false });
@@ -801,15 +617,6 @@ describe('AudioManager', () => {
expect(() => manager.setConnection(connectionOptions)).toThrow(AudioManagerStateError);
});
it('supports explicit resource management', () => {
const manager = (() => {
using disposableManager = new AudioManager({ renewIntervalMs: false });
return disposableManager;
})();
expect(manager.state).toBe('disposed');
});
it('prevents use after disposal', async () => {
const manager = new AudioManager({
connection: connectionOptions,
+10 -29
View File
@@ -20,12 +20,11 @@ type MockChildProcess = {
stderr: {
destroy: jest.Mock;
on: jest.Mock;
off: jest.Mock;
resume: jest.Mock;
};
on: jest.Mock;
once: jest.Mock;
off: jest.Mock;
removeAllListeners: jest.Mock;
kill: jest.Mock;
killed: boolean;
exitCode: number | null;
@@ -42,12 +41,11 @@ function createMockChildProcess(): MockChildProcess {
stderr: {
destroy: jest.fn(),
on: jest.fn(),
off: jest.fn(),
resume: jest.fn(),
},
on: jest.fn(),
once: jest.fn(),
off: jest.fn(),
removeAllListeners: jest.fn(),
kill: jest.fn(),
killed: false,
exitCode: null,
@@ -63,10 +61,6 @@ function getProcessHandler(childProcess: MockChildProcess, eventName: string): (
return childProcess.once.mock.calls.find(([event]) => event === eventName)?.[1] as (...args: unknown[]) => void;
}
function getPersistentProcessHandler(childProcess: MockChildProcess, eventName: string): (...args: unknown[]) => void {
return childProcess.on.mock.calls.find(([event]) => event === eventName)?.[1] as (...args: unknown[]) => void;
}
function getStdoutHandler(childProcess: MockChildProcess, eventName: string): (...args: unknown[]) => void {
return childProcess.stdout.once.mock.calls.find(([event]) => event === eventName)?.[1] as (
...args: unknown[]
@@ -123,7 +117,7 @@ describe('ffmpeg helpers', () => {
],
{ stdio: ['ignore', 'pipe', 'pipe'] },
);
expect(childProcess.on).toHaveBeenCalledWith('error', expect.any(Function));
expect(childProcess.once).toHaveBeenCalledWith('error', expect.any(Function));
expect(childProcess.once).toHaveBeenCalledWith('exit', expect.any(Function));
expect(childProcess.stdout.once).toHaveBeenCalledWith('readable', expect.any(Function));
expect(childProcess.stderr.on).toHaveBeenCalledWith('data', expect.any(Function));
@@ -135,16 +129,12 @@ describe('ffmpeg helpers', () => {
mockSpawnReturn(childProcess);
const handle = startFfmpeg('tests/audio.mp3');
const errorHandler = getPersistentProcessHandler(childProcess, 'error');
const spawnError = new Error('spawn ENOENT');
const errorHandler = getProcessHandler(childProcess, 'error');
errorHandler(spawnError);
errorHandler(new Error('spawn ENOENT'));
await expect(handle.ready).rejects.toMatchObject({
cause: spawnError,
message: expect.stringContaining('spawn ENOENT'),
name: FfmpegProcessError.name,
});
await expect(handle.ready).rejects.toThrow(FfmpegProcessError);
await expect(handle.ready).rejects.toThrow('spawn ENOENT');
});
it('includes stderr when ffmpeg exits before producing audio', async () => {
@@ -182,10 +172,8 @@ describe('ffmpeg helpers', () => {
const handle = startFfmpeg('tests/audio.mp3');
const readableHandler = getStdoutHandler(childProcess, 'readable');
const exitHandler = getProcessHandler(childProcess, 'exit');
const errorHandler = getPersistentProcessHandler(childProcess, 'error');
readableHandler();
errorHandler(new Error('late process error'));
exitHandler(1, null);
await expect(handle.ready).resolves.toBeUndefined();
@@ -208,22 +196,17 @@ describe('ffmpeg helpers', () => {
);
});
it('stops a running child process and schedules a force kill fallback', async () => {
it('stops a running child process and schedules a force kill fallback', () => {
jest.useFakeTimers();
const childProcess = createMockChildProcess();
childProcess.kill.mockImplementation(() => {
childProcess.killed = true;
return true;
});
mockSpawnReturn(childProcess);
const handle = startFfmpeg('tests/audio.mp3');
const readyExpectation = expect(handle.ready).rejects.toThrow('stopped before producing audio');
handle.stop();
await readyExpectation;
expect(childProcess.stdout.destroy).toHaveBeenCalledTimes(1);
expect(childProcess.stderr.destroy).toHaveBeenCalledTimes(1);
expect(childProcess.removeAllListeners).toHaveBeenCalledTimes(1);
expect(childProcess.kill).toHaveBeenCalledWith('SIGTERM');
jest.advanceTimersByTime(2_000);
@@ -231,16 +214,14 @@ describe('ffmpeg helpers', () => {
expect(childProcess.kill).toHaveBeenNthCalledWith(2, 'SIGKILL');
});
it('does not signal a process that already exited', async () => {
it('does not signal a process that already exited', () => {
const childProcess = createMockChildProcess();
childProcess.exitCode = 0;
mockSpawnReturn(childProcess);
const handle = startFfmpeg('tests/audio.mp3');
const readyExpectation = expect(handle.ready).rejects.toThrow('stopped before producing audio');
handle.stop();
await readyExpectation;
expect(childProcess.kill).not.toHaveBeenCalled();
});
});
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": true,
"declarationMap": false,
"emitDeclarationOnly": true,
"rootDir": "./src"
},
"include": ["src/**/*.ts"]
}
-3
View File
@@ -1,7 +1,4 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"skipLibCheck": true
},
"include": ["src/**/*.ts", "tests/**/*.ts", "tsup.config.ts"]
}
+14 -5
View File
@@ -1,22 +1,31 @@
{
"compilerOptions": {
"target": "ES2024",
"lib": ["ES2024"],
"module": "Node20",
"target": "ES2022",
"lib": ["ES2022"],
"module": "Node16",
"moduleResolution": "node16",
"resolveJsonModule": true,
"types": [],
"rootDir": "./",
"outDir": "./dist",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"isolatedModules": true,
"erasableSyntaxOnly": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"useUnknownInCatchVariables": true,
"skipLibCheck": true,
"noEmitOnError": true
},
"include": ["src"],
+2 -2
View File
@@ -1,8 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./dist-test",
"skipLibCheck": true
"isolatedModules": true,
"outDir": "./dist-test"
},
"include": ["src/**/*.ts", "tests/**/*.ts", "tsup.config.ts"]
}
+1 -6
View File
@@ -3,12 +3,7 @@ import { defineConfig } from 'tsup';
export default defineConfig({
format: ['cjs', 'esm'],
entry: ['./src/index.ts'],
dts: {
compilerOptions: {
// tsup's declaration bundler still sets the removed baseUrl option internally.
ignoreDeprecations: '6.0',
},
},
dts: false,
shims: true,
skipNodeModulesBundle: true,
clean: true,