odesli.js 1.3.9 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,247 +0,0 @@
1
- // Example: No API key is used. You are limited to 10 requests/minute. Some requests may return 401/429 if the rate limit is exceeded.
2
- const Odesli = require('odesli.js');
3
- const { RateLimiter } = require('odesli.js/rate-limiter');
4
-
5
- async function advancedExample() {
6
- console.log('šŸš€ Advanced Odesli.js Usage Example\n');
7
-
8
- // Initialize advanced features
9
- const rateLimiter = new RateLimiter({
10
- maxRequests: 8,
11
- windowMs: 60000,
12
- strategy: 'token-bucket',
13
- });
14
-
15
- // Initialize Odesli with advanced configuration (no API key)
16
- const odesli = new Odesli({
17
- apiKey: process.env.ODESLI_API_KEY,
18
- version: 'v1-alpha.1',
19
- validateParams: true,
20
- logger: (message, level) => {
21
- if (level === 'error' || level === 'warn') {
22
- console.log(`[${level.toUpperCase()}]`, message);
23
- } else {
24
- console.log(`[${level.toUpperCase()}]`, message);
25
- }
26
- },
27
- });
28
-
29
- // Get the integrated metrics collector
30
- const metrics = odesli.getMetrics();
31
-
32
- if (!process.env.ODESLI_API_KEY) {
33
- console.log(
34
- 'ā„¹ļø No API key set in environment. You are limited to 10 requests per minute. Set ODESLI_API_KEY for higher limits.'
35
- );
36
- }
37
-
38
- try {
39
- // Example 1: Advanced parameter fetching with metrics
40
- console.log('šŸŒ Fetching song for UK market with custom options...');
41
-
42
- const startTime = Date.now();
43
- metrics.recordRequest({
44
- url: 'param-based-request',
45
- startTime,
46
- platform: 'spotify',
47
- country: 'GB',
48
- });
49
-
50
- const paramSong = await odesli.getByParams(
51
- 'spotify',
52
- 'song',
53
- '4Km5HrUvYTaSUfiSGPJeQR',
54
- {
55
- country: 'GB',
56
- skipCache: false,
57
- timeout: 5000,
58
- }
59
- );
60
-
61
- metrics.recordRequest({
62
- url: 'param-based-request',
63
- startTime,
64
- endTime: Date.now(),
65
- success: true,
66
- statusCode: 200,
67
- platform: 'spotify',
68
- country: 'GB',
69
- });
70
-
71
- console.log(`Param Title: ${paramSong.title}`);
72
- console.log();
73
-
74
- // Example 2: Entity ID fetching with rate limiting
75
- console.log('šŸ†” Fetching by entity ID with rate limiting...');
76
-
77
- await rateLimiter.waitForSlot();
78
-
79
- const idSong = await odesli.getById(
80
- 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR',
81
- {
82
- country: 'US',
83
- skipCache: true,
84
- }
85
- );
86
-
87
- console.log(`ID Title: ${idSong.title}`);
88
- console.log();
89
-
90
- // Example 3: Enhanced batch fetching with error handling (see below)
91
- console.log('šŸ“Š Enhanced batch fetching with detailed error handling...');
92
-
93
- // Example 4: Platform detection and ID extraction
94
- console.log('šŸ” Platform detection and ID extraction...');
95
-
96
- const testUrls = [
97
- 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
98
- 'https://music.apple.com/us/album/bad-and-boujee/1440811686?i=1440811687',
99
- 'https://www.youtube.com/watch?v=S-sJp1FfG7Q',
100
- ];
101
-
102
- testUrls.forEach(url => {
103
- const platform = odesli.detectPlatform(url);
104
- const id = odesli.extractId(url);
105
- console.log(`URL: ${url}`);
106
- console.log(` Platform: ${platform}`);
107
- console.log(` ID: ${id}`);
108
- });
109
- console.log();
110
-
111
- // Example 5: Supported platforms
112
- console.log('šŸ“± Supported platforms:');
113
- const platforms = odesli.getSupportedPlatforms();
114
- console.log(platforms.join(', '));
115
- console.log();
116
-
117
- // Example 6: Cache statistics with metrics
118
- console.log('šŸ“Š Cache and metrics statistics:');
119
- const cacheStats = odesli.getCacheStats();
120
- console.log(`Cache hits: ${cacheStats.hitCount}`);
121
- console.log(`Cache misses: ${cacheStats.missCount}`);
122
- console.log(`Cache size: ${cacheStats.size}`);
123
- console.log(`Hit rate: ${(cacheStats.hitRate * 100).toFixed(2)}%`);
124
-
125
- const metricsSummary = metrics.getSummary();
126
- console.log(`\nšŸ“ˆ Metrics Summary (from MetricsCollector):`);
127
- console.log(` Total requests: ${metricsSummary.counters.totalRequests}`);
128
- console.log(
129
- ` Success rate: ${(metricsSummary.rates.successRate * 100).toFixed(1)}%`
130
- );
131
- console.log(
132
- ` Average response time: ${metricsSummary.recent.avgResponseTime}ms`
133
- );
134
- console.log(
135
- ` Requests per minute: ${metricsSummary.recent.requestsPerMinute}`
136
- );
137
- console.log();
138
-
139
- // Example 7: User-Agent information
140
- console.log('🌐 User-Agent information:');
141
- const userAgent = odesli.getUserAgent();
142
- console.log(`User-Agent: ${userAgent}`);
143
- console.log();
144
-
145
- // Example 8: Plugin system demonstration - requires separate plugin system initialization
146
- console.log('šŸ”Œ Plugin system demonstration:');
147
- // For this example, we'll create a separate PluginSystem.
148
- // In a real app, you might integrate it into the Odesli class similarly to MetricsCollector.
149
- const {
150
- PluginSystem,
151
- loggingPlugin,
152
- analyticsPlugin,
153
- } = require('odesli.js/plugin-system');
154
- const pluginSystem = new PluginSystem();
155
- pluginSystem.registerPlugin('logging', loggingPlugin);
156
- pluginSystem.registerPlugin('analytics', analyticsPlugin);
157
- console.log('Registered plugins:', pluginSystem.getPlugins());
158
-
159
- pluginSystem.getPlugins().forEach(pluginName => {
160
- const info = pluginSystem.getPluginInfo(pluginName);
161
- console.log(` ${pluginName}: ${info.description}`);
162
- });
163
- console.log();
164
-
165
- // Example 9: Error handling with validation
166
- console.log('āš ļø Testing parameter validation...');
167
-
168
- try {
169
- await odesli.fetch('invalid-url');
170
- } catch (error) {
171
- console.log(`Validation error: ${error.message}`);
172
- }
173
-
174
- try {
175
- await odesli.getByParams('invalid-platform', 'song', '123');
176
- } catch (error) {
177
- console.log(`Platform validation error: ${error.message}`);
178
- }
179
-
180
- try {
181
- await odesli.fetch('https://open.spotify.com/track/123', 'INVALID');
182
- } catch (error) {
183
- console.log(`Country validation error: ${error.message}`);
184
- }
185
-
186
- // Batch fetch with enhanced error handling
187
- console.log(
188
- '\nšŸ“Š Rate-limited batch fetching with enhanced error handling...'
189
- );
190
- const batchUrls = [
191
- 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
192
- 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
193
- 'https://open.spotify.com/track/1z6WtY7X4HQJvzxC4UgkS1', // Invalid track
194
- 'https://open.spotify.com/track/2CIMQHirSU0MQqyYHq0eOx', // Invalid track
195
- 'https://open.spotify.com/track/3Wrjm47oTz2sjIgck11l5e',
196
- 'https://music.apple.com/us/album/blinding-lights/1493120897?i=1493120900', // Apple Music with track ID
197
- ];
198
-
199
- const batchResults = await odesli.fetchBatch(batchUrls, {
200
- country: 'US',
201
- concurrency: 3,
202
- });
203
-
204
- console.log('\nšŸ“‹ Batch Results Summary:');
205
- let successCount = 0;
206
- let errorCount = 0;
207
-
208
- batchResults.forEach((result, index) => {
209
- if (result.success) {
210
- successCount++;
211
- console.log(
212
- `āœ… Song ${index + 1}: ${result.title} by ${result.artist.join(', ')}`
213
- );
214
- } else {
215
- errorCount++;
216
- console.log(`āŒ Song ${index + 1}: ${result.error}`);
217
- console.log(` Platform: ${result.platform || 'Unknown'}`);
218
- console.log(` Extracted ID: ${result.extractedId || 'Not found'}`);
219
- console.log(` Error Type: ${result.errorType}`);
220
- console.log(` Suggestion: ${result.suggestion}`);
221
- console.log(` Retryable: ${result.retryable ? 'Yes' : 'No'}`);
222
- console.log('');
223
- }
224
- });
225
-
226
- console.log(
227
- `šŸ“Š Batch Summary: ${successCount} successful, ${errorCount} failed`
228
- );
229
-
230
- console.log('\nšŸŽ‰ Advanced usage example completed successfully!');
231
- } catch (error) {
232
- if (
233
- error.message &&
234
- (error.message.includes('401') || error.message.includes('429'))
235
- ) {
236
- console.error('Error:', error.message);
237
- console.error(
238
- 'You may need an API key for higher limits. See https://odesli.co/'
239
- );
240
- } else {
241
- console.error('āŒ Error:', error.message);
242
- }
243
- }
244
- }
245
-
246
- // Run the example
247
- advancedExample().catch(console.error);
@@ -1,100 +0,0 @@
1
- // Example: No API key is used. You are limited to 10 requests/minute. Some requests may return 401/429 if the rate limit is exceeded.
2
- const Odesli = require('odesli.js');
3
- // For ESM (import)
4
- // import { Odesli } from '../lib/index.mjs';
5
-
6
- // For advanced features, uncomment these lines:
7
- // const { RateLimiter } = require('odesli.js/rate-limiter');
8
- // const { MetricsCollector } = require('odesli.js/metrics');
9
-
10
- // Initialize without API key (public usage, rate-limited)
11
- const odesli = new Odesli({
12
- timeout: 10000,
13
- cache: true,
14
- });
15
-
16
- async function basicExample() {
17
- try {
18
- console.log('=== Basic Usage Examples ===\n');
19
-
20
- // Single URL fetch
21
- console.log('1. Fetching single song...');
22
- const song = await odesli.fetch(
23
- 'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh'
24
- );
25
- console.log(`Title: ${song.title}`);
26
- console.log(`Artist: ${song.artist.join(', ')}`);
27
- console.log(`Platforms: ${Object.keys(song.linksByPlatform).join(', ')}\n`);
28
-
29
- // Batch fetch multiple URLs
30
- console.log('2. Fetching multiple songs...');
31
- const songs = await odesli.fetch([
32
- 'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh',
33
- 'https://music.apple.com/us/album/blinding-lights/1493120897?i=1493120900',
34
- ]);
35
-
36
- songs.forEach((song, index) => {
37
- console.log(
38
- `Song ${index + 1}: ${song.title} by ${song.artist.join(', ')}`
39
- );
40
- });
41
- console.log();
42
-
43
- // Get links for specific platform
44
- console.log('3. Getting Apple Music link...');
45
- const appleMusicLink = song.linksByPlatform.appleMusic?.url;
46
- console.log(`Apple Music: ${appleMusicLink}\n`);
47
-
48
- // Platform detection
49
- console.log('4. Platform detection...');
50
- const platform = odesli.detectPlatform(
51
- 'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh'
52
- );
53
- console.log(`Detected platform: ${platform}\n`);
54
-
55
- // Country-specific fetch
56
- console.log('5. Country-specific fetch...');
57
- const ukSong = await odesli.fetch(
58
- 'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh',
59
- { country: 'GB' }
60
- );
61
- console.log(`UK fetch successful: ${ukSong.title}\n`);
62
-
63
- // Get available country options
64
- console.log('6. Available country options...');
65
- const countryOptions = Odesli.getCountryOptions();
66
- console.log(`Total countries: ${countryOptions.length}`);
67
- console.log(
68
- `Sample countries: ${countryOptions
69
- .slice(0, 5)
70
- .map(c => `${c.code} (${c.name})`)
71
- .join(', ')}\n`
72
- );
73
-
74
- // Cache statistics
75
- console.log('7. Cache statistics...');
76
- const cacheStats = odesli.getCacheStats();
77
- console.log(`Cache hits: ${cacheStats.hitCount}`);
78
- console.log(`Cache misses: ${cacheStats.missCount}`);
79
- console.log(`Cache size: ${cacheStats.size}`);
80
- console.log(`Hit rate: ${(cacheStats.hitRate * 100).toFixed(2)}%`);
81
-
82
- // User-Agent information
83
- console.log('\n8. User-Agent...');
84
- console.log(`Current User-Agent: ${odesli.getUserAgent()}`);
85
- } catch (error) {
86
- if (
87
- error.message &&
88
- (error.message.includes('401') || error.message.includes('429'))
89
- ) {
90
- console.error('Error:', error.message);
91
- console.error(
92
- 'You may need an API key for higher limits. See https://odesli.co/'
93
- );
94
- } else {
95
- console.error('Error:', error.message);
96
- }
97
- }
98
- }
99
-
100
- basicExample();
@@ -1,119 +0,0 @@
1
- // Cache Test Example
2
- // This example demonstrates how caching works by making the same request multiple times
3
- const Odesli = require('odesli.js');
4
-
5
- async function cacheTest() {
6
- console.log('🧪 Testing Cache Functionality\n');
7
-
8
- // Initialize with caching enabled
9
- const odesli = new Odesli({
10
- cache: true,
11
- timeout: 10000,
12
- });
13
-
14
- const testUrl = 'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh';
15
-
16
- try {
17
- // First request - should be a cache miss
18
- console.log('1. First request (should be cache miss)...');
19
- const start1 = Date.now();
20
- const song1 = await odesli.fetch(testUrl);
21
- const time1 = Date.now() - start1;
22
- console.log(`āœ… Got: ${song1.title} (took ${time1}ms)`);
23
-
24
- // Check cache stats after first request
25
- const stats1 = odesli.getCacheStats();
26
- console.log(
27
- ` Cache hits: ${stats1.hitCount}, misses: ${stats1.missCount}, hit rate: ${(stats1.hitRate * 100).toFixed(1)}%\n`
28
- );
29
-
30
- // Second request - should be a cache hit
31
- console.log('2. Second request (should be cache hit)...');
32
- const start2 = Date.now();
33
- const song2 = await odesli.fetch(testUrl);
34
- const time2 = Date.now() - start2;
35
- console.log(`āœ… Got: ${song2.title} (took ${time2}ms)`);
36
-
37
- // Check cache stats after second request
38
- const stats2 = odesli.getCacheStats();
39
- console.log(
40
- ` Cache hits: ${stats2.hitCount}, misses: ${stats2.missCount}, hit rate: ${(stats2.hitRate * 100).toFixed(1)}%\n`
41
- );
42
-
43
- // Third request - should also be a cache hit
44
- console.log('3. Third request (should be cache hit)...');
45
- const start3 = Date.now();
46
- const song3 = await odesli.fetch(testUrl);
47
- const time3 = Date.now() - start3;
48
- console.log(`āœ… Got: ${song3.title} (took ${time3}ms)`);
49
-
50
- // Check final cache stats
51
- const stats3 = odesli.getCacheStats();
52
- console.log(
53
- ` Cache hits: ${stats3.hitCount}, misses: ${stats3.missCount}, hit rate: ${(stats3.hitRate * 100).toFixed(1)}%\n`
54
- );
55
-
56
- // Test with skipCache option
57
- console.log('4. Request with skipCache=true (should be cache miss)...');
58
- const start4 = Date.now();
59
- const song4 = await odesli.fetch(testUrl, { skipCache: true });
60
- const time4 = Date.now() - start4;
61
- console.log(`āœ… Got: ${song4.title} (took ${time4}ms)`);
62
-
63
- const stats4 = odesli.getCacheStats();
64
- console.log(
65
- ` Cache hits: ${stats4.hitCount}, misses: ${stats4.missCount}, hit rate: ${(stats4.hitRate * 100).toFixed(1)}%\n`
66
- );
67
-
68
- // Performance comparison
69
- console.log('šŸ“Š Performance Summary:');
70
- console.log(` First request (miss): ${time1}ms`);
71
- console.log(` Second request (hit): ${time2}ms`);
72
- console.log(` Third request (hit): ${time3}ms`);
73
- console.log(` Skip cache request: ${time4}ms`);
74
-
75
- if (time2 < time1) {
76
- console.log(
77
- ` āœ… Cache is working! Hit was ${Math.round(time1 / time2)}x faster than miss`
78
- );
79
- } else {
80
- console.log(
81
- ` āš ļø Cache hit wasn't faster (network might be very fast)`
82
- );
83
- }
84
-
85
- // Clear cache and test again
86
- console.log('\n5. Clearing cache...');
87
- odesli.clearCache();
88
- const statsAfterClear = odesli.getCacheStats();
89
- console.log(
90
- ` After clear: hits: ${statsAfterClear.hitCount}, misses: ${statsAfterClear.missCount}\n`
91
- );
92
-
93
- // Test after clearing cache
94
- console.log('6. Request after clearing cache (should be cache miss)...');
95
- const start5 = Date.now();
96
- const song5 = await odesli.fetch(testUrl);
97
- const time5 = Date.now() - start5;
98
- console.log(`āœ… Got: ${song5.title} (took ${time5}ms)`);
99
-
100
- const finalStats = odesli.getCacheStats();
101
- console.log(
102
- ` Final stats: hits: ${finalStats.hitCount}, misses: ${finalStats.missCount}, hit rate: ${(finalStats.hitRate * 100).toFixed(1)}%`
103
- );
104
- } catch (error) {
105
- if (
106
- error.message &&
107
- (error.message.includes('401') || error.message.includes('429'))
108
- ) {
109
- console.error('Error:', error.message);
110
- console.error(
111
- 'You may need an API key for higher limits. See https://odesli.co/'
112
- );
113
- } else {
114
- console.error('Error:', error.message);
115
- }
116
- }
117
- }
118
-
119
- cacheTest();
@@ -1,83 +0,0 @@
1
- const Odesli = require('odesli.js');
2
- const { RateLimiter } = require('odesli.js/rate-limiter');
3
- const odesli = new Odesli();
4
-
5
- // Test URLs
6
- const urls = [
7
- 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
8
- 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
9
- 'https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp',
10
- 'https://open.spotify.com/track/6rqhFgbbKwnb9MLmUQDhG6',
11
- ];
12
-
13
- // Function to test a strategy
14
- async function testStrategy(strategy, maxRequests, windowMs) {
15
- console.log(`\nšŸ”§ Testing ${strategy.toUpperCase()} Strategy`);
16
- console.log(`šŸ“Š Config: ${maxRequests} requests per ${windowMs / 1000}s`);
17
- console.log('─'.repeat(50));
18
-
19
- const limiter = new RateLimiter({
20
- maxRequests,
21
- windowMs,
22
- strategy,
23
- });
24
-
25
- const startTime = Date.now();
26
-
27
- // Submit all requests at once
28
- const promises = urls.map(async (url, index) => {
29
- const requestStart = Date.now();
30
- console.log(`ā³ Request ${index + 1}: Waiting for slot...`);
31
-
32
- await limiter.waitForSlot();
33
- const waitTime = Date.now() - requestStart;
34
-
35
- console.log(`āœ… Request ${index + 1}: Got slot (waited ${waitTime}ms)`);
36
- const song = await odesli.fetch(url);
37
- console.log(`šŸŽµ Request ${index + 1}: ${song.title}`);
38
-
39
- return { song, waitTime };
40
- });
41
-
42
- const results = await Promise.all(promises);
43
- const totalTime = Date.now() - startTime;
44
-
45
- console.log(`\nšŸ“ˆ Results for ${strategy}:`);
46
- console.log(`ā±ļø Total time: ${totalTime}ms`);
47
- console.log(
48
- `šŸ“Š Average wait: ${Math.round(results.reduce((sum, r) => sum + r.waitTime, 0) / results.length)}ms`
49
- );
50
- console.log(`šŸŽÆ Strategy status:`, limiter.getStatus());
51
- }
52
-
53
- // Test all strategies
54
- (async () => {
55
- console.log('šŸš€ Rate Limiter Strategy Comparison');
56
- console.log('='.repeat(60));
57
-
58
- // 1. TOKEN BUCKET - Good for burst handling
59
- await testStrategy('token-bucket', 2, 3000);
60
-
61
- // 2. SLIDING WINDOW - Most accurate rate limiting
62
- await testStrategy('sliding-window', 2, 3000);
63
-
64
- // 3. LEAKY BUCKET - Good for smoothing traffic
65
- await testStrategy('leaky-bucket', 2, 3000);
66
-
67
- console.log('\nšŸ“š Strategy Guide:');
68
- console.log('='.repeat(60));
69
- console.log('šŸŽÆ TOKEN BUCKET:');
70
- console.log(' āœ… Pros: Handles bursts well, efficient memory usage');
71
- console.log(' āŒ Cons: Less precise timing, can allow slight overages');
72
- console.log(' šŸŽÆ Use when: You want to allow some burst traffic');
73
- console.log('');
74
- console.log('šŸ”„ SLIDING WINDOW:');
75
- console.log(' āœ… Pros: Most accurate, precise timing, no overages');
76
- console.log(' āŒ Cons: More memory usage, slightly more complex');
77
- console.log(' šŸŽÆ Use when: You need exact rate limiting (recommended)');
78
- console.log('');
79
- console.log('šŸ’§ LEAKY BUCKET:');
80
- console.log(' āœ… Pros: Smooths traffic, predictable output rate');
81
- console.log(' āŒ Cons: Can delay requests, less responsive to bursts');
82
- console.log(' šŸŽÆ Use when: You want to smooth out traffic spikes');
83
- })();
@@ -1,60 +0,0 @@
1
- // Test Apple Music ID extraction improvements
2
- const Odesli = require('odesli.js');
3
-
4
- const odesli = new Odesli();
5
-
6
- console.log('šŸŽ Testing Apple Music ID Extraction Improvements\n');
7
-
8
- // Test various Apple Music URL formats
9
- const testUrls = [
10
- // Album URLs with track IDs
11
- 'https://music.apple.com/us/album/blinding-lights/1493120897?i=1493120900',
12
- 'https://music.apple.com/gb/album/watermelon-sugar/1493120897?i=1493120901',
13
- 'https://itunes.apple.com/us/album/bad-guy/1493120897?i=1493120902',
14
-
15
- // Direct track URLs
16
- 'https://music.apple.com/us/album/blinding-lights/1493120897',
17
- 'https://itunes.apple.com/us/album/watermelon-sugar/1493120898',
18
-
19
- // Other formats
20
- 'https://music.apple.com/us/album/123456789',
21
- 'https://itunes.apple.com/us/album/987654321?i=123456789',
22
-
23
- // Invalid URLs for comparison
24
- 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
25
- 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
26
- 'invalid-url',
27
- ];
28
-
29
- console.log('šŸ“‹ Testing URL parsing:');
30
- testUrls.forEach((url, index) => {
31
- const platform = odesli.detectPlatform(url);
32
- const extractedId = odesli.extractId(url);
33
-
34
- console.log(`${index + 1}. ${url}`);
35
- console.log(` Platform: ${platform || 'Unknown'}`);
36
- console.log(` Extracted ID: ${extractedId || 'Not found'}`);
37
-
38
- if (platform === 'appleMusic' && extractedId) {
39
- console.log(` āœ… Successfully extracted Apple Music ID: ${extractedId}`);
40
- } else if (platform === 'appleMusic' && !extractedId) {
41
- console.log(` āŒ Failed to extract Apple Music ID`);
42
- }
43
- console.log('');
44
- });
45
-
46
- console.log('šŸŽÆ Summary:');
47
- const appleMusicUrls = testUrls.filter(
48
- url => odesli.detectPlatform(url) === 'appleMusic'
49
- );
50
- const successfulExtractions = appleMusicUrls.filter(url =>
51
- odesli.extractId(url)
52
- );
53
-
54
- console.log(`Total Apple Music URLs: ${appleMusicUrls.length}`);
55
- console.log(`Successful ID extractions: ${successfulExtractions.length}`);
56
- console.log(
57
- `Success rate: ${((successfulExtractions.length / appleMusicUrls.length) * 100).toFixed(1)}%`
58
- );
59
-
60
- console.log('\n✨ Apple Music ID extraction test completed!');
@@ -1,46 +0,0 @@
1
- // Example: No API key is used. You are limited to 10 requests/minute. Some requests may return 401/429 if the rate limit is exceeded.
2
- const Odesli = require('odesli.js');
3
-
4
- async function userAgentExample() {
5
- console.log('🌐 Odesli.js User-Agent Example\n');
6
-
7
- // Initialize the client (no API key)
8
- const odesli = new Odesli();
9
-
10
- // Display the User-Agent string
11
- console.log('Current User-Agent:');
12
- console.log(odesli.getUserAgent());
13
- console.log();
14
-
15
- // Show package information
16
- console.log('Package Information:');
17
- console.log(`Name: ${require('../package.json').name}`);
18
- console.log(`Version: ${require('../package.json').version}`);
19
- console.log(`Node.js: ${process.version}`);
20
- console.log(`Platform: ${process.platform}`);
21
- console.log();
22
-
23
- // Example of how the User-Agent looks in requests
24
- console.log('The User-Agent will be sent with every API request:');
25
- console.log(`GET https://api.song.link/v1-alpha.1/links?...`);
26
- console.log(`User-Agent: ${odesli.getUserAgent()}`);
27
- console.log();
28
-
29
- // Test with custom headers
30
- console.log('With custom headers:');
31
- const odesliWithCustomHeaders = new Odesli({
32
- headers: {
33
- 'X-Custom-Header': 'MyApp/1.0',
34
- 'User-Agent': 'CustomUserAgent/1.0', // This will override the default
35
- },
36
- });
37
-
38
- console.log('Custom User-Agent (overridden):');
39
- console.log(odesliWithCustomHeaders.getUserAgent());
40
- console.log(
41
- 'Note: The custom User-Agent in headers will be used instead of the default one.'
42
- );
43
- }
44
-
45
- // Run the example
46
- userAgentExample().catch(console.error);
package/jest.config.js DELETED
@@ -1,14 +0,0 @@
1
- module.exports = {
2
- testEnvironment: 'node',
3
- roots: ['<rootDir>/tests'],
4
- testMatch: ['**/__tests__/**/*.js', '**/?(*.)+(spec|test).js'],
5
- collectCoverageFrom: ['lib/**/*.js', '!lib/**/*.d.ts'],
6
- coverageDirectory: 'coverage',
7
- coverageReporters: ['text', 'lcov', 'html'],
8
- setupFilesAfterEnv: ['./tests/setup.js'],
9
- testEnvironmentOptions: {
10
- url: 'http://localhost',
11
- },
12
- testPathIgnorePatterns: ['/node_modules/', '/docs/'],
13
- coveragePathIgnorePatterns: ['/node_modules/', '/tests/'],
14
- };