also looking at this
chore: enhance logging
#55
12 files
+379
-9
| @@ -0,0 +1,12 @@ | ||
| 1 | --- | |
| 2 | description: Code Style & Structure specifics | |
| 3 | globs: | |
| 4 | --- | |
| 5 | ## Code Style & Structure | |
| 6 | ||
| 7 | - Write concise, technical TypeScript code with accurate examples in the docblock | |
| 8 | - If Bun native modules are available, use them | |
| 9 | - Use functional and declarative programming patterns; avoid classes unless needed | |
| 10 | - Prefer iteration and modularization over code duplication | |
| 11 | - Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`) | |
| 12 | - Use proper jsdoc comments for functions, types, interfaces, and ensure examples are accurate | |
| @@ -0,0 +1,9 @@ | ||
| 1 | --- | |
| 2 | description: Documentation specific rules | |
| 3 | globs: docs/**/*.md | |
| 4 | --- | |
| 5 | ## Documentation | |
| 6 | ||
| 7 | - Write documentation for all functions, types, interfaces, and ensure examples are accurate | |
| 8 | - The `./docs` directory is where the vitepress markdown documentation is stored | |
| 9 | - Make sure to update the docs markdown files | |
| @@ -0,0 +1,11 @@ | ||
| 1 | --- | |
| 2 | description: Error Handling and Validation specifics | |
| 3 | globs: | |
| 4 | --- | |
| 5 | ## Error Handling and Validation | |
| 6 | ||
| 7 | - Prioritize error handling: handle errors and edge cases early | |
| 8 | - Use early returns and guard clauses | |
| 9 | - Implement proper error logging and user-friendly messages | |
| 10 | - Use error boundaries for unexpected errors | |
| 11 | - when `neverthrow` is available, ensure errors are typed | |
| @@ -0,0 +1,11 @@ | ||
| 1 | --- | |
| 2 | description: Key code conventions | |
| 3 | globs: | |
| 4 | --- | |
| 5 | ## Key Conventions | |
| 6 | ||
| 7 | - If there are two equally valid implementations, the browser version should be preferred | |
| 8 | - Aim for 100% test coverage | |
| 9 | - Avoid usage of `any` | |
| 10 | - Reuse eslint-ignore comments where present, unless not needed | |
| 11 | - ensure we log everything properly, including for debug reasons | |
| @@ -0,0 +1,11 @@ | ||
| 1 | --- | |
| 2 | description: Project structure information | |
| 3 | globs: | |
| 4 | --- | |
| 5 | ## Project Structure | |
| 6 | ||
| 7 | - the `./src` directory is the source code | |
| 8 | - the `./test` directory is the test code | |
| 9 | - the `./bin` directory is the command-line code | |
| 10 | - you can also call the CLI via `./clarity ...` | |
| 11 | - the `./docs` directory is the documentation | |
| @@ -0,0 +1,198 @@ | ||
| 1 | --- | |
| 2 | description: General information based on the latest ./README.md content | |
| 3 | globs: | |
| 4 | --- | |
| 5 | Update it if APIs change: | |
| 6 | ||
| 7 | # AAX Audio Converter | |
| 8 | ||
| 9 | A TypeScript library and CLI tool for converting Audible AAX audiobooks to standard MP3, M4A, or M4B formats. | |
| 10 | ||
| 11 |  | |
| 12 | ||
| 13 | ## Features | |
| 14 | ||
| 15 | - Convert AAX files to MP3, M4A, or M4B formats | |
| 16 | - Preserve chapter information | |
| 17 | - Automatically detect Audible activation code | |
| 18 | - Split audiobooks by chapters | |
| 19 | - Simple command-line interface | |
| 20 | ||
| 21 | ## Installation | |
| 22 | ||
| 23 | ```bash | |
| 24 | # Install globally | |
| 25 | npm install -g @stacksjs/aax | |
| 26 | ||
| 27 | # Or use with npx | |
| 28 | npx @stacksjs/aax | |
| 29 | ``` | |
| 30 | ||
| 31 | ## Requirements | |
| 32 | ||
| 33 | - `ffmpeg` & [`audible`](https://github.com/mkb79/audible-cli) must be installed and available in your PATH | |
| 34 | ||
| 35 | _Please read [Using the Audible CLI Integration](#using-the-audible-cli-integration) for more information._ | |
| 36 | ||
| 37 | ## CLI Usage | |
| 38 | ||
| 39 | ### Convert an AAX file to MP3 | |
| 40 | ||
| 41 | ```bash | |
| 42 | aax convert /path/to/audiobook.aax | |
| 43 | ``` | |
| 44 | ||
| 45 | ### Convert with custom options | |
| 46 | ||
| 47 | ```bash | |
| 48 | aax convert /path/to/audiobook.aax --format m4b --output ./my-audiobooks --bitrate 192 | |
| 49 | ``` | |
| 50 | ||
| 51 | ### Convert and split by chapters | |
| 52 | ||
| 53 | ```bash | |
| 54 | aax split /path/to/audiobook.aax | |
| 55 | ``` | |
| 56 | ||
| 57 | ### Available CLI Options | |
| 58 | ||
| 59 | - `-o, --output <dir>` - Output directory (default: ./converted) | |
| 60 | - `-f, --format <format>` - Output format: mp3, m4a, m4b (default: mp3) | |
| 61 | - `-c, --code <code>` - Audible activation code (auto-detected if not provided) | |
| 62 | - `--chapters` - Preserve chapter information (default: true) | |
| 63 | - `-b, --bitrate <kbps>` - Audio bitrate in kbps (default: 'source' to match the original file) | |
| 64 | - `-v, --verbose` - Enable verbose logging | |
| 65 | - `--flat-folder-structure` - Use flat folder structure | |
| 66 | - `--series-title-in-folder-structure` - Include series title in folder structure | |
| 67 | - `--variable-bit-rate` - Apply variable bit rate | |
| 68 | - `--aac-encoding-44-1` - Fix AAC encoding for 44.1 kHz | |
| 69 | - `--use-named-chapters` - Use named chapters if available | |
| 70 | - `--skip-short-chapters-duration <seconds>` - Skip short chapters between book parts | |
| 71 | - `--skip-very-short-chapter-duration <seconds>` - Skip very short chapters at begin and end | |
| 72 | ||
| 73 | ## Library Usage | |
| 74 | ||
| 75 | ```typescript | |
| 76 | import { convertAAX } from 'aax' | |
| 77 | ||
| 78 | async function convertBook() { | |
| 79 | const result = await convertAAX({ | |
| 80 | inputFile: '/path/to/audiobook.aax', | |
| 81 | outputFormat: 'mp3', | |
| 82 | outputDir: './converted', | |
| 83 | chaptersEnabled: true, | |
| 84 | bitrate: 128, | |
| 85 | }) | |
| 86 | ||
| 87 | if (result.success) { | |
| 88 | console.log(`Conversion complete: ${result.outputPath}`) | |
| 89 | } | |
| 90 | else { | |
| 91 | console.error(`Conversion failed: ${result.error}`) | |
| 92 | } | |
| 93 | } | |
| 94 | ``` | |
| 95 | ||
| 96 | ## Configuration | |
| 97 | ||
| 98 | You can create an `aax.config.ts` or `aax.config.js` file in your project root to customize default settings: | |
| 99 | ||
| 100 | ```typescript | |
| 101 | export default { | |
| 102 | verbose: true, | |
| 103 | outputFormat: 'mp3', | |
| 104 | outputDir: './my-audiobooks', | |
| 105 | chaptersEnabled: true, | |
| 106 | bitrate: 192, | |
| 107 | // Optional: manually set the activation code | |
| 108 | // activationCode: '1a2b3c4d', | |
| 109 | // Optional: specify a custom FFmpeg path | |
| 110 | // ffmpegPath: '/usr/local/bin/ffmpeg', | |
| 111 | // New options | |
| 112 | flatFolderStructure: false, | |
| 113 | seriesTitleInFolderStructure: true, | |
| 114 | fullCaptionForBookFolder: false, | |
| 115 | partFolderPrefix: 'standard', | |
| 116 | sequenceNumberDigits: 2, | |
| 117 | customSearchWords: [], | |
| 118 | additionalPunctuation: '', | |
| 119 | intermediateFileCopy: false, | |
| 120 | aacEncoding44_1: false, | |
| 121 | variableBitRate: false, | |
| 122 | reduceBitRate: 'no', | |
| 123 | fileType: 'm4a', | |
| 124 | useISOLatin1: false, | |
| 125 | extractCoverImage: true, | |
| 126 | useNamedChapters: true, | |
| 127 | skipShortChaptersDuration: 25, | |
| 128 | skipVeryShortChapterDuration: 10, | |
| 129 | verifyChapterMarks: 'all', | |
| 130 | preferEmbeddedChapterTimes: true, | |
| 131 | } | |
| 132 | ``` | |
| 133 | ||
| 134 | ## Using the Audible CLI Integration | |
| 135 | ||
| 136 | This tool integrates with the Audible CLI to automatically retrieve activation bytes (activation codes) from Audible's servers using your account credentials. This makes it much easier to convert your AAX audiobooks without manually finding activation codes. | |
| 137 | ||
| 138 | ### Prerequisites | |
| 139 | ||
| 140 | 1. Download the Audible CLI binary and place it in the root of your project: | |
| 141 | - [Audible CLI Releases](https://github.com/mkb79/audible-cli/releases) | |
| 142 | - Choose the appropriate version for your OS (e.g., `audible-cli-0.2.0-windows-amd64.exe` for Windows) | |
| 143 | - Rename it to `audible` and place it in the project root | |
| 144 | ||
| 145 | ### Setting up Audible CLI | |
| 146 | ||
| 147 | Run the setup command: | |
| 148 | ||
| 149 | ```bash | |
| 150 | aax setup-audible | |
| 151 | ``` | |
| 152 | ||
| 153 | This will: | |
| 154 | ||
| 155 | 1. Check if the audible binary exists | |
| 156 | 2. Make it executable | |
| 157 | 3. Run the quickstart wizard (you'll need to follow the interactive prompts to log in to your Audible account) | |
| 158 | 4. Retrieve your activation bytes from Audible's servers | |
| 159 | 5. Save them for future use | |
| 160 | ||
| 161 | During the setup process, you'll see something like this: | |
| 162 | ||
| 163 | ``` | |
| 164 | Setting up Audible CLI and retrieving activation bytes... | |
| 165 | Note: You may be prompted to log in to your Audible account. | |
| 166 | Follow the prompts in the terminal to complete the setup. | |
| 167 | ||
| 168 | Attempting to get activation bytes from Audible CLI... | |
| 169 | Audible CLI is not configured. Setting up... | |
| 170 | Starting Audible CLI quickstart. Please follow the prompts to log in to your Audible account. | |
| 171 | # ... (interactive login process) ... | |
| 172 | ||
| 173 | Fetching activation bytes from Audible server... | |
| 174 | ✅ Found activation bytes from Audible CLI: 2c****** | |
| 175 | ||
| 176 | ✅ Successfully retrieved activation bytes: 2c****** | |
| 177 | ||
| 178 | You can now use this activation code with the convert command: | |
| 179 | aax convert your-audiobook.aax -c 2c1eeb0a | |
| 180 | ||
| 181 | The activation code has been saved and will be used automatically for future conversions. | |
| 182 | ``` | |
| 183 | ||
| 184 | Once set up, your activation code will be automatically used for all future conversions, so you don't need to specify it manually. | |
| 185 | ||
| 186 | ### Manual Setup (if the automated setup fails) | |
| 187 | ||
| 188 | If the automated setup fails, you can do it manually: | |
| 189 | ||
| 190 | 1. Run: `./audible quickstart` | |
| 191 | 2. Follow the prompts to log in to your Audible account | |
| 192 | 3. Once set up, run: `./audible activation-bytes` | |
| 193 | 4. Note the activation code (a 8-character hex string like `2c1eeb0a`) | |
| 194 | 5. Use this code with the convert command: | |
| 195 | ||
| 196 | ```bash | |
| 197 | aax convert your-audiobook.aax -c YOUR_ACTIVATION_CODE | |
| 198 | ``` | |
| @@ -0,0 +1,9 @@ | ||
| 1 | --- | |
| 2 | description: Syntax and Formatting specifics | |
| 3 | globs: | |
| 4 | --- | |
| 5 | ## Syntax and Formatting | |
| 6 | ||
| 7 | - Use the "function" keyword for pure functions | |
| 8 | - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements | |
| 9 | - Make sure everything is properly commented | |
| @@ -0,0 +1,10 @@ | ||
| 1 | --- | |
| 2 | description: Testing specifics | |
| 3 | globs: | |
| 4 | --- | |
| 5 | ## Testing | |
| 6 | ||
| 7 | - Write tests for all functions, types, interfaces, and ensure examples are accurate | |
| 8 | - The `./test` directory is where the tests are stored | |
| 9 | - Use `bun test` to run the tests | |
| 10 | - Use bun native modules for testing from `import { x, y, z } from 'bun:test'` | |
| @@ -0,0 +1,9 @@ | ||
| 1 | --- | |
| 2 | description: TypeScript Usage specifics | |
| 3 | globs: docs/**/*.md | |
| 4 | --- | |
| 5 | ## TypeScript Usage | |
| 6 | ||
| 7 | - Use TypeScript for all code; prefer interfaces over types | |
| 8 | - Avoid enums; use `maps` instead, or `as const` | |
| 9 | - Use functional components with TypeScript interfaces | |
| @@ -4,7 +4,7 @@ import path from 'node:path' | ||
| 4 | 4 | import { config } from './config' |
| 5 | 5 | import { getActivationBytesFromAudibleCli } from './utils/activation' |
| 6 | 6 | import { checkFFmpeg, runFFmpeg } from './utils/ffmpeg' |
| 7 | import { logger } from './utils/logger' | |
| 7 | import { logger, reportError } from './utils/logger' | |
| 8 | 8 | import { getBookMetadata } from './utils/metadata' |
| 9 | 9 | |
| 10 | 10 | function generateOutputPath(metadata: any, options: ConversionOptions): string { |
| @@ -71,7 +71,16 @@ export async function convertAAX(options: ConversionOptions): Promise<Conversion | ||
| 71 | 71 | // Check for ffmpeg |
| 72 | 72 | const ffmpegAvailable = await checkFFmpeg() |
| 73 | 73 | if (!ffmpegAvailable) { |
| 74 | logger.error('FFmpeg is not available. Please install FFmpeg and try again.') | |
| 74 | reportError(new Error('FFmpeg is not available'), { | |
| 75 | heading: 'FFmpeg not found. Required for conversion.', | |
| 76 | details: 'The converter requires FFmpeg to decrypt and transcode AAX files.', | |
| 77 | hints: [ | |
| 78 | 'Install on macOS: brew install ffmpeg', | |
| 79 | 'Install on Linux: use your package manager (e.g., apt install ffmpeg)', | |
| 80 | 'Install on Windows: https://ffmpeg.org/download.html', | |
| 81 | 'Alternatively set ffmpegPath in aax.config.ts to your ffmpeg binary', | |
| 82 | ], | |
| 83 | }) | |
| 75 | 84 | return { |
| 76 | 85 | success: false, |
| 77 | 86 | error: 'FFmpeg not found. Required for conversion.', |
| @@ -83,9 +92,15 @@ export async function convertAAX(options: ConversionOptions): Promise<Conversion | ||
| 83 | 92 | const activationCode = options.activationCode || config.activationCode || await getActivationBytesFromAudibleCli() |
| 84 | 93 | |
| 85 | 94 | if (!activationCode) { |
| 86 | logger.error('No activation code provided for decryption.') | |
| 87 | logger.info('You can specify an activation code with the -c option or set it in your config.') | |
| 88 | logger.info('To auto-detect activation code, run "aax setup-audible" first.') | |
| 95 | reportError(new Error('Missing activation code'), { | |
| 96 | heading: 'No activation code provided for decryption.', | |
| 97 | details: 'Audible AAX files require an 8-character activation code (activation bytes) to decrypt.', | |
| 98 | hints: [ | |
| 99 | 'Provide activationCode in options or in aax.config.ts', | |
| 100 | 'Use Audible CLI to fetch: audible activation-bytes (run audible quickstart first)', | |
| 101 | 'Try environment overrides and run again with AAX_LOG_LEVEL=debug for more output', | |
| 102 | ], | |
| 103 | }) | |
| 89 | 104 | return { |
| 90 | 105 | success: false, |
| 91 | 106 | error: 'No activation code provided. This is required to convert AAX files.', |
| @@ -231,7 +246,15 @@ export async function convertAAX(options: ConversionOptions): Promise<Conversion | ||
| 231 | 246 | } |
| 232 | 247 | } |
| 233 | 248 | |
| 234 | logger.error('Conversion failed. Check the logs for details.') | |
| 249 | reportError(new Error('Conversion failed'), { | |
| 250 | heading: 'Conversion failed.', | |
| 251 | details: 'FFmpeg returned a non-zero exit code.', | |
| 252 | hints: [ | |
| 253 | 'Verify the activation code is correct (case sensitive)', | |
| 254 | 'Try running with AAX_LOG_LEVEL=debug to see the FFmpeg command and output', | |
| 255 | 'Ensure input file is a valid AAX and not corrupted', | |
| 256 | ], | |
| 257 | }) | |
| 235 | 258 | return { |
| 236 | 259 | success: false, |
| 237 | 260 | error: `FFmpeg conversion failed: ${output}`, |
| @@ -239,7 +262,12 @@ export async function convertAAX(options: ConversionOptions): Promise<Conversion | ||
| 239 | 262 | } |
| 240 | 263 | } |
| 241 | 264 | catch (error) { |
| 242 | logger.error(`Error during conversion: ${(error as Error).message}`) | |
| 265 | reportError(error, { | |
| 266 | heading: 'Unexpected error during conversion.', | |
| 267 | hints: [ | |
| 268 | 'Re-run with AAX_LOG_LEVEL=debug to include stack traces', | |
| 269 | ], | |
| 270 | }) | |
| 243 | 271 | return { |
| 244 | 272 | success: false, |
| 245 | 273 | error: `Error during conversion: ${(error as Error).message}`, |
| @@ -1,9 +1,16 @@ | ||
| 1 | import process from 'node:process' | |
| 1 | 2 | import { Logger } from '@stacksjs/clarity' |
| 2 | 3 | |
| 4 | // Determine log level via env (falls back to info). Only allow levels supported by clarity Logger | |
| 5 | const envLevel = (process.env.AAX_LOG_LEVEL || '').toLowerCase() | |
| 6 | const allowedLevels = ['error', 'info', 'debug'] as const | |
| 7 | type AllowedLevel = typeof allowedLevels[number] | |
| 8 | const level: AllowedLevel = (allowedLevels as readonly string[]).includes(envLevel) ? (envLevel as AllowedLevel) : 'info' | |
| 9 | ||
| 3 | 10 | // Create a logger instance with a fancy UI |
| 4 | 11 | export const logger: Logger = new Logger('aax', { |
| 5 | 12 | fancy: true, |
| 6 | level: 'info', | |
| 13 | level, | |
| 7 | 14 | showTags: true, |
| 8 | 15 | }) |
| 9 | 16 | |
| @@ -73,3 +80,58 @@ export function formatTime(ms: number): string { | ||
| 73 | 80 | |
| 74 | 81 | return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}` |
| 75 | 82 | } |
| 83 | ||
| 84 | /** | |
| 85 | * Report an error with optional heading, details and hints. | |
| 86 | * In debug mode (AAX_LOG_LEVEL=debug or AAX_DEBUG=1), also prints stack traces when available. | |
| 87 | */ | |
| 88 | export function reportError( | |
| 89 | error: unknown, | |
| 90 | options?: { | |
| 91 | heading?: string | |
| 92 | details?: string | |
| 93 | hints?: string[] | |
| 94 | }, | |
| 95 | ): void { | |
| 96 | const isDebug = level === 'debug' || process.env.AAX_DEBUG === '1' | |
| 97 | ||
| 98 | const heading = options?.heading | |
| 99 | const details = options?.details | |
| 100 | const hints = options?.hints || [] | |
| 101 | ||
| 102 | // Extract message/stack from various error shapes | |
| 103 | const errObj = normalizeError(error) | |
| 104 | ||
| 105 | if (heading) | |
| 106 | logger.error(heading) | |
| 107 | ||
| 108 | if (errObj.message) | |
| 109 | logger.error(errObj.message) | |
| 110 | ||
| 111 | if (details) | |
| 112 | logger.warn(details) | |
| 113 | ||
| 114 | for (const hint of hints) | |
| 115 | logger.warn(`Hint: ${hint}`) | |
| 116 | ||
| 117 | if (isDebug && errObj.stack) | |
| 118 | logger.debug(errObj.stack) | |
| 119 | } | |
| 120 | ||
| 121 | /** | |
| 122 | * Normalize unknown errors to a consistent shape. | |
| 123 | */ | |
| 124 | export function normalizeError(error: unknown): { message: string; stack?: string } { | |
| 125 | if (error instanceof Error) { | |
| 126 | return { message: error.message, stack: error.stack } | |
| 127 | } | |
| 128 | if (typeof error === 'string') { | |
| 129 | return { message: error } | |
| 130 | } | |
| 131 | try { | |
| 132 | return { message: JSON.stringify(error) } | |
| 133 | } | |
| 134 | catch { | |
| 135 | return { message: String(error) } | |
| 136 | } | |
| 137 | } | |