odesli.js 1.1.1 → 1.1.2
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.
- package/.eslintrc.js +0 -1
- package/.github/workflows/ci.yml +3 -3
- package/.github/workflows/publish-github-packages.yml +50 -0
- package/.github/workflows/{publish.yml → publish-npm.yml} +10 -1
- package/.prettierignore +30 -30
- package/CHANGELOG.md +36 -0
- package/LICENSE +14 -14
- package/README.md +25 -2
- package/lib/index.d.ts +484 -484
- package/lib/index.js +390 -390
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -1,390 +1,390 @@
|
|
|
1
|
-
const fetch = require('node-fetch')
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Simple in-memory cache for API responses
|
|
5
|
-
* @private
|
|
6
|
-
*/
|
|
7
|
-
const cache = new Map()
|
|
8
|
-
const CACHE_TTL = 5 * 60 * 1000 // 5 minutes
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Clear expired cache entries
|
|
12
|
-
* @private
|
|
13
|
-
*/
|
|
14
|
-
function clearExpiredCache () {
|
|
15
|
-
const now = Date.now()
|
|
16
|
-
for (const [key, value] of cache.entries()) {
|
|
17
|
-
if (now - value.timestamp > CACHE_TTL) {
|
|
18
|
-
cache.delete(key)
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Get cached response if available and not expired
|
|
25
|
-
* @param {string} key - Cache key
|
|
26
|
-
* @returns {Object|null} Cached response or null if not found/expired
|
|
27
|
-
* @private
|
|
28
|
-
*/
|
|
29
|
-
function getCachedResponse (key) {
|
|
30
|
-
clearExpiredCache()
|
|
31
|
-
const cached = cache.get(key)
|
|
32
|
-
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
|
|
33
|
-
return cached.data
|
|
34
|
-
}
|
|
35
|
-
return null
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Cache a response
|
|
40
|
-
* @param {string} key - Cache key
|
|
41
|
-
* @param {Object} data - Response data to cache
|
|
42
|
-
* @private
|
|
43
|
-
*/
|
|
44
|
-
function cacheResponse (key, data) {
|
|
45
|
-
cache.set(key, {
|
|
46
|
-
data,
|
|
47
|
-
timestamp: Date.now()
|
|
48
|
-
})
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Odesli API Client
|
|
53
|
-
*
|
|
54
|
-
* A Node.js client for the Odesli API (formerly song.link/album.link) that helps you find links to music across multiple streaming platforms.
|
|
55
|
-
*
|
|
56
|
-
* @example
|
|
57
|
-
* ```javascript
|
|
58
|
-
* const Odesli = require('odesli.js');
|
|
59
|
-
*
|
|
60
|
-
* // Initialize without API key (10 requests/minute limit)
|
|
61
|
-
* const odesli = new Odesli();
|
|
62
|
-
*
|
|
63
|
-
* // Or with API key for higher limits
|
|
64
|
-
* const odesli = new Odesli({
|
|
65
|
-
* apiKey: 'your-api-key-here',
|
|
66
|
-
* version: 'v1-alpha.1'
|
|
67
|
-
* });
|
|
68
|
-
*
|
|
69
|
-
* // Fetch a song by URL
|
|
70
|
-
* const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
|
|
71
|
-
* console.log(`${song.title} by ${song.artist[0]}`);
|
|
72
|
-
* ```
|
|
73
|
-
*/
|
|
74
|
-
module.exports = class Odesli {
|
|
75
|
-
/**
|
|
76
|
-
* Create a new Odesli instance
|
|
77
|
-
*
|
|
78
|
-
* @param {Object} options - Configuration options
|
|
79
|
-
* @param {string} [options.apiKey] - Optional API key for higher rate limits (10+ requests/minute). Without an API key, you're limited to 10 requests per minute.
|
|
80
|
-
* @param {string} [options.version='v1-alpha.1'] - API version to use
|
|
81
|
-
* @param {boolean} [options.cache=true] - Enable response caching (5 minute TTL)
|
|
82
|
-
* @param {number} [options.timeout=10000] - Request timeout in milliseconds
|
|
83
|
-
*
|
|
84
|
-
* @example
|
|
85
|
-
* ```javascript
|
|
86
|
-
* // Basic usage without API key
|
|
87
|
-
* const odesli = new Odesli();
|
|
88
|
-
*
|
|
89
|
-
* // With API key for higher limits
|
|
90
|
-
* const odesli = new Odesli({
|
|
91
|
-
* apiKey: 'your-api-key-here',
|
|
92
|
-
* version: 'v1-alpha.1',
|
|
93
|
-
* cache: true,
|
|
94
|
-
* timeout: 10000
|
|
95
|
-
* });
|
|
96
|
-
* ```
|
|
97
|
-
*/
|
|
98
|
-
constructor (options = {}) {
|
|
99
|
-
const { apiKey = undefined, version = 'v1-alpha.1', cache = true, timeout = 10000 } = options || {}
|
|
100
|
-
this.apiKey = apiKey || undefined
|
|
101
|
-
this.version = version || 'v1-alpha.1'
|
|
102
|
-
this.cacheEnabled = cache
|
|
103
|
-
this.timeout = timeout
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Make a request to the Odesli API with caching and timeout support
|
|
108
|
-
*
|
|
109
|
-
* @param {string} path - API endpoint path
|
|
110
|
-
* @returns {Promise<Object>} API response
|
|
111
|
-
* @private
|
|
112
|
-
*/
|
|
113
|
-
async _request (path) {
|
|
114
|
-
const url = `https://api.song.link/${this.version}/${path}${this.apiKey !== undefined ? `&key=${this.apiKey}` : ''}`
|
|
115
|
-
|
|
116
|
-
// Check cache first if enabled
|
|
117
|
-
if (this.cacheEnabled) {
|
|
118
|
-
const cached = getCachedResponse(url)
|
|
119
|
-
if (cached) {
|
|
120
|
-
return cached
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
try {
|
|
125
|
-
// Create AbortController for timeout
|
|
126
|
-
const controller = new AbortController()
|
|
127
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout)
|
|
128
|
-
|
|
129
|
-
const response = await fetch(url, {
|
|
130
|
-
signal: controller.signal,
|
|
131
|
-
headers: {
|
|
132
|
-
'User-Agent': 'odesli.js/1.0.3',
|
|
133
|
-
Accept: 'application/json'
|
|
134
|
-
}
|
|
135
|
-
})
|
|
136
|
-
|
|
137
|
-
clearTimeout(timeoutId)
|
|
138
|
-
|
|
139
|
-
if (!response.ok) {
|
|
140
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
const result = await response.json()
|
|
144
|
-
|
|
145
|
-
// Handle errors
|
|
146
|
-
if (result.statusCode) {
|
|
147
|
-
// Codes in the `4xx` range indicate an error that failed given the information provided
|
|
148
|
-
if (result.statusCode === 429) throw new Error(`${result.statusCode}: ${result.code}, You are being rate limited, No API Key is 10 Requests / Minute.`)
|
|
149
|
-
// Codes in the `4xx` range indicate an error that failed given the information provided
|
|
150
|
-
if (result.statusCode.toString().startsWith(4)) throw new Error(`${result.statusCode}: ${result.code}, Codes in the 4xx range indicate an error that failed given the information provided.`)
|
|
151
|
-
// Codes in the 5xx range indicate an error with Songlink's servers.
|
|
152
|
-
if (result.statusCode.toString().startsWith(5)) throw new Error(`${result.statusCode}: ${result.code}, Codes in the 5xx range indicate an error with Songlink's servers.`)
|
|
153
|
-
// Otherwise if the code is not 200 (Success), throw a generic error.
|
|
154
|
-
if (result.statusCode !== 200) throw new Error(`${result.statusCode}: ${result.code}`)
|
|
155
|
-
// return undefined as we didn't find anything.
|
|
156
|
-
return undefined
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// Cache successful responses
|
|
160
|
-
if (this.cacheEnabled && result) {
|
|
161
|
-
cacheResponse(url, result)
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
return result
|
|
165
|
-
} catch (err) {
|
|
166
|
-
if (err.name === 'AbortError') {
|
|
167
|
-
throw new Error(`Request timeout after ${this.timeout}ms`)
|
|
168
|
-
}
|
|
169
|
-
if (err.message === 'Unexpected token < in JSON at position 0') {
|
|
170
|
-
throw new Error('API returned an unexpected result.')
|
|
171
|
-
}
|
|
172
|
-
throw err
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Clear the response cache
|
|
178
|
-
*
|
|
179
|
-
* @example
|
|
180
|
-
* ```javascript
|
|
181
|
-
* const odesli = new Odesli();
|
|
182
|
-
* odesli.clearCache(); // Clear all cached responses
|
|
183
|
-
* ```
|
|
184
|
-
*/
|
|
185
|
-
clearCache () {
|
|
186
|
-
cache.clear()
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/**
|
|
190
|
-
* Get cache statistics
|
|
191
|
-
*
|
|
192
|
-
* @returns {Object} Cache statistics
|
|
193
|
-
* @example
|
|
194
|
-
* ```javascript
|
|
195
|
-
* const odesli = new Odesli();
|
|
196
|
-
* const stats = odesli.getCacheStats();
|
|
197
|
-
* console.log(`Cache size: ${stats.size}, Hit rate: ${stats.hitRate}%`);
|
|
198
|
-
* ```
|
|
199
|
-
*/
|
|
200
|
-
getCacheStats () {
|
|
201
|
-
clearExpiredCache()
|
|
202
|
-
return {
|
|
203
|
-
size: cache.size,
|
|
204
|
-
ttl: CACHE_TTL
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
/**
|
|
209
|
-
* Fetch song/album information by URL from any supported streaming platform
|
|
210
|
-
*
|
|
211
|
-
* @param {string} url - URL from any supported streaming platform (Spotify, Apple Music, YouTube, etc.)
|
|
212
|
-
* @param {string} [country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
|
|
213
|
-
* @returns {Promise<Object>} Song/album information with links to all available platforms
|
|
214
|
-
*
|
|
215
|
-
* @example
|
|
216
|
-
* ```javascript
|
|
217
|
-
* // Fetch a song by Spotify URL
|
|
218
|
-
* const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
|
|
219
|
-
* console.log(`${song.title} by ${song.artist[0]}`);
|
|
220
|
-
*
|
|
221
|
-
* // Fetch with custom country
|
|
222
|
-
* const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR', 'GB');
|
|
223
|
-
*
|
|
224
|
-
* // Get all available platform links
|
|
225
|
-
* Object.keys(song.linksByPlatform).forEach(platform => {
|
|
226
|
-
* console.log(`${platform}: ${song.linksByPlatform[platform].url}`);
|
|
227
|
-
* });
|
|
228
|
-
* ```
|
|
229
|
-
*
|
|
230
|
-
* @throws {Error} When no URL is provided
|
|
231
|
-
* @throws {Error} When API returns an error (rate limiting, invalid URL, etc.)
|
|
232
|
-
*/
|
|
233
|
-
async fetch (url, country = 'US') {
|
|
234
|
-
if (!url) throw new Error('No URL was provided to odesli.fetch()')
|
|
235
|
-
const path = `links?url=${encodeURIComponent(url)}&userCountry=${country}`
|
|
236
|
-
const song = await this._request(path)
|
|
237
|
-
|
|
238
|
-
// Handle edge cases where response is malformed
|
|
239
|
-
if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
|
|
240
|
-
return song || {}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
const id = song.entitiesByUniqueId[song.entityUniqueId].id
|
|
244
|
-
const title = song.entitiesByUniqueId[song.entityUniqueId].title
|
|
245
|
-
|
|
246
|
-
// Convert Artist into Array for easier extraction of features
|
|
247
|
-
Object.values(song.entitiesByUniqueId).forEach(function (values) {
|
|
248
|
-
if (values.artistName && typeof values.artistName === 'string') {
|
|
249
|
-
values.artistName = values.artistName.split(', ')
|
|
250
|
-
}
|
|
251
|
-
})
|
|
252
|
-
|
|
253
|
-
const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
|
|
254
|
-
const type = song.entitiesByUniqueId[song.entityUniqueId].type
|
|
255
|
-
const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
|
|
256
|
-
|
|
257
|
-
return {
|
|
258
|
-
...song,
|
|
259
|
-
id,
|
|
260
|
-
title,
|
|
261
|
-
artist,
|
|
262
|
-
type,
|
|
263
|
-
thumbnail
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/**
|
|
268
|
-
* Fetch song/album information by platform, type, and ID
|
|
269
|
-
*
|
|
270
|
-
* @param {string} platform - Platform name (spotify, appleMusic, youtube, etc.)
|
|
271
|
-
* @param {string} type - Content type ('song' or 'album')
|
|
272
|
-
* @param {string} id - Platform-specific ID (can be full format like 'SPOTIFY_SONG::123' or just '123')
|
|
273
|
-
* @param {string} [country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
|
|
274
|
-
* @returns {Promise<Object>} Song/album information with links to all available platforms
|
|
275
|
-
*
|
|
276
|
-
* @example
|
|
277
|
-
* ```javascript
|
|
278
|
-
* // Get song by Spotify ID
|
|
279
|
-
* const song = await odesli.getByParams('spotify', 'song', '4Km5HrUvYTaSUfiSGPJeQR');
|
|
280
|
-
* console.log(song.title);
|
|
281
|
-
*
|
|
282
|
-
* // Get album by Apple Music ID
|
|
283
|
-
* const album = await odesli.getByParams('appleMusic', 'album', '123456789');
|
|
284
|
-
* console.log(album.title);
|
|
285
|
-
*
|
|
286
|
-
* // Using full ID format
|
|
287
|
-
* const song = await odesli.getByParams('spotify', 'song', 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
|
|
288
|
-
* ```
|
|
289
|
-
*
|
|
290
|
-
* @throws {Error} When platform, type, or ID is not provided
|
|
291
|
-
* @throws {Error} When API returns an error
|
|
292
|
-
*/
|
|
293
|
-
async getByParams (platform, type, id, country = 'US') {
|
|
294
|
-
if (!platform) throw new Error('No `platform` was provided to odesli.getByParams()')
|
|
295
|
-
if (!type) throw new Error('No `type` was provided to odesli.getByParams()')
|
|
296
|
-
if (!id) throw new Error('No `id` was provided to odesli.getByParams()')
|
|
297
|
-
|
|
298
|
-
// if they happen to input the full id (PLATFORM_SONG::UNIQUEID), just get the UNIQUEID
|
|
299
|
-
id = id.replace(/[^::]+::/g, '')
|
|
300
|
-
const path = `links?platform=${platform}&type=${type}&id=${id}&userCountry=${country}`
|
|
301
|
-
const song = await this._request(path)
|
|
302
|
-
|
|
303
|
-
// Handle edge cases where response is malformed
|
|
304
|
-
if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
|
|
305
|
-
return song || {}
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
// Convert Artist into Array for easier extraction of features
|
|
309
|
-
Object.values(song.entitiesByUniqueId).forEach(function (values) {
|
|
310
|
-
if (values.artistName && typeof values.artistName === 'string') {
|
|
311
|
-
values.artistName = values.artistName.split(', ')
|
|
312
|
-
}
|
|
313
|
-
})
|
|
314
|
-
|
|
315
|
-
// Easier extraction of page's title, album, and thumbnail
|
|
316
|
-
const title = song.entitiesByUniqueId[song.entityUniqueId].title
|
|
317
|
-
const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
|
|
318
|
-
const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
|
|
319
|
-
const entityType = song.entitiesByUniqueId[song.entityUniqueId].type
|
|
320
|
-
|
|
321
|
-
return {
|
|
322
|
-
...song,
|
|
323
|
-
title,
|
|
324
|
-
artist,
|
|
325
|
-
thumbnail,
|
|
326
|
-
type: entityType
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
/**
|
|
331
|
-
* Fetch song/album information by entity ID
|
|
332
|
-
*
|
|
333
|
-
* @param {string} id - Full entity ID in format 'PLATFORM_TYPE::UNIQUEID' (e.g., 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR')
|
|
334
|
-
* @param {string} [country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
|
|
335
|
-
* @returns {Promise<Object>} Song/album information with links to all available platforms
|
|
336
|
-
*
|
|
337
|
-
* @example
|
|
338
|
-
* ```javascript
|
|
339
|
-
* // Get song by entity ID
|
|
340
|
-
* const song = await odesli.getById('SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
|
|
341
|
-
* console.log(song.title);
|
|
342
|
-
*
|
|
343
|
-
* // Get album by entity ID
|
|
344
|
-
* const album = await odesli.getById('APPLEMUSIC_ALBUM::123456789');
|
|
345
|
-
* console.log(album.title);
|
|
346
|
-
* ```
|
|
347
|
-
*
|
|
348
|
-
* @throws {Error} When ID is not provided
|
|
349
|
-
* @throws {Error} When ID format is invalid (must match 'PLATFORM_TYPE::UNIQUEID')
|
|
350
|
-
* @throws {Error} When API returns an error
|
|
351
|
-
*/
|
|
352
|
-
async getById (id, country = 'US') {
|
|
353
|
-
if (!id) throw new Error('No `id` was provided to odesli.getById()')
|
|
354
|
-
if (!id.match(/\w+_\w+::\w+/g)) throw new Error('Provided Entity ID Does not match format. `<PLATFORM>_<SONG|ALBUM>::<UNIQUEID>`')
|
|
355
|
-
|
|
356
|
-
// Convert string into seperate params
|
|
357
|
-
const platform = id.replace(/_\w+::\w+/g, '').toLowerCase()
|
|
358
|
-
const type = id.replace(/\w+_/g, '').replace(/::\w+/g, '').toLowerCase()
|
|
359
|
-
const unique = id.replace(/\w+::/g, '')
|
|
360
|
-
|
|
361
|
-
const path = `links?platform=${platform}&type=${type}&id=${unique}&userCountry=${country}`
|
|
362
|
-
const song = await this._request(path)
|
|
363
|
-
|
|
364
|
-
// Handle edge cases where response is malformed
|
|
365
|
-
if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
|
|
366
|
-
return song || {}
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
// Convert Artist into Array for easier extraction of features
|
|
370
|
-
Object.values(song.entitiesByUniqueId).forEach(function (values) {
|
|
371
|
-
if (values.artistName && typeof values.artistName === 'string') {
|
|
372
|
-
values.artistName = values.artistName.split(', ')
|
|
373
|
-
}
|
|
374
|
-
})
|
|
375
|
-
|
|
376
|
-
// Easier extraction of page's title, album, and thumbnail
|
|
377
|
-
const title = song.entitiesByUniqueId[song.entityUniqueId].title
|
|
378
|
-
const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
|
|
379
|
-
const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
|
|
380
|
-
const entityType = song.entitiesByUniqueId[song.entityUniqueId].type
|
|
381
|
-
|
|
382
|
-
return {
|
|
383
|
-
...song,
|
|
384
|
-
title,
|
|
385
|
-
artist,
|
|
386
|
-
thumbnail,
|
|
387
|
-
type: entityType
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
}
|
|
1
|
+
const fetch = require('node-fetch')
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Simple in-memory cache for API responses
|
|
5
|
+
* @private
|
|
6
|
+
*/
|
|
7
|
+
const cache = new Map()
|
|
8
|
+
const CACHE_TTL = 5 * 60 * 1000 // 5 minutes
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Clear expired cache entries
|
|
12
|
+
* @private
|
|
13
|
+
*/
|
|
14
|
+
function clearExpiredCache () {
|
|
15
|
+
const now = Date.now()
|
|
16
|
+
for (const [key, value] of cache.entries()) {
|
|
17
|
+
if (now - value.timestamp > CACHE_TTL) {
|
|
18
|
+
cache.delete(key)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Get cached response if available and not expired
|
|
25
|
+
* @param {string} key - Cache key
|
|
26
|
+
* @returns {Object|null} Cached response or null if not found/expired
|
|
27
|
+
* @private
|
|
28
|
+
*/
|
|
29
|
+
function getCachedResponse (key) {
|
|
30
|
+
clearExpiredCache()
|
|
31
|
+
const cached = cache.get(key)
|
|
32
|
+
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
|
|
33
|
+
return cached.data
|
|
34
|
+
}
|
|
35
|
+
return null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Cache a response
|
|
40
|
+
* @param {string} key - Cache key
|
|
41
|
+
* @param {Object} data - Response data to cache
|
|
42
|
+
* @private
|
|
43
|
+
*/
|
|
44
|
+
function cacheResponse (key, data) {
|
|
45
|
+
cache.set(key, {
|
|
46
|
+
data,
|
|
47
|
+
timestamp: Date.now()
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Odesli API Client
|
|
53
|
+
*
|
|
54
|
+
* A Node.js client for the Odesli API (formerly song.link/album.link) that helps you find links to music across multiple streaming platforms.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```javascript
|
|
58
|
+
* const Odesli = require('odesli.js');
|
|
59
|
+
*
|
|
60
|
+
* // Initialize without API key (10 requests/minute limit)
|
|
61
|
+
* const odesli = new Odesli();
|
|
62
|
+
*
|
|
63
|
+
* // Or with API key for higher limits
|
|
64
|
+
* const odesli = new Odesli({
|
|
65
|
+
* apiKey: 'your-api-key-here',
|
|
66
|
+
* version: 'v1-alpha.1'
|
|
67
|
+
* });
|
|
68
|
+
*
|
|
69
|
+
* // Fetch a song by URL
|
|
70
|
+
* const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
|
|
71
|
+
* console.log(`${song.title} by ${song.artist[0]}`);
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
module.exports = class Odesli {
|
|
75
|
+
/**
|
|
76
|
+
* Create a new Odesli instance
|
|
77
|
+
*
|
|
78
|
+
* @param {Object} options - Configuration options
|
|
79
|
+
* @param {string} [options.apiKey] - Optional API key for higher rate limits (10+ requests/minute). Without an API key, you're limited to 10 requests per minute.
|
|
80
|
+
* @param {string} [options.version='v1-alpha.1'] - API version to use
|
|
81
|
+
* @param {boolean} [options.cache=true] - Enable response caching (5 minute TTL)
|
|
82
|
+
* @param {number} [options.timeout=10000] - Request timeout in milliseconds
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```javascript
|
|
86
|
+
* // Basic usage without API key
|
|
87
|
+
* const odesli = new Odesli();
|
|
88
|
+
*
|
|
89
|
+
* // With API key for higher limits
|
|
90
|
+
* const odesli = new Odesli({
|
|
91
|
+
* apiKey: 'your-api-key-here',
|
|
92
|
+
* version: 'v1-alpha.1',
|
|
93
|
+
* cache: true,
|
|
94
|
+
* timeout: 10000
|
|
95
|
+
* });
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
constructor (options = {}) {
|
|
99
|
+
const { apiKey = undefined, version = 'v1-alpha.1', cache = true, timeout = 10000 } = options || {}
|
|
100
|
+
this.apiKey = apiKey || undefined
|
|
101
|
+
this.version = version || 'v1-alpha.1'
|
|
102
|
+
this.cacheEnabled = cache
|
|
103
|
+
this.timeout = timeout
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Make a request to the Odesli API with caching and timeout support
|
|
108
|
+
*
|
|
109
|
+
* @param {string} path - API endpoint path
|
|
110
|
+
* @returns {Promise<Object>} API response
|
|
111
|
+
* @private
|
|
112
|
+
*/
|
|
113
|
+
async _request (path) {
|
|
114
|
+
const url = `https://api.song.link/${this.version}/${path}${this.apiKey !== undefined ? `&key=${this.apiKey}` : ''}`
|
|
115
|
+
|
|
116
|
+
// Check cache first if enabled
|
|
117
|
+
if (this.cacheEnabled) {
|
|
118
|
+
const cached = getCachedResponse(url)
|
|
119
|
+
if (cached) {
|
|
120
|
+
return cached
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
// Create AbortController for timeout
|
|
126
|
+
const controller = new AbortController()
|
|
127
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout)
|
|
128
|
+
|
|
129
|
+
const response = await fetch(url, {
|
|
130
|
+
signal: controller.signal,
|
|
131
|
+
headers: {
|
|
132
|
+
'User-Agent': 'odesli.js/1.0.3',
|
|
133
|
+
Accept: 'application/json'
|
|
134
|
+
}
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
clearTimeout(timeoutId)
|
|
138
|
+
|
|
139
|
+
if (!response.ok) {
|
|
140
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const result = await response.json()
|
|
144
|
+
|
|
145
|
+
// Handle errors
|
|
146
|
+
if (result.statusCode) {
|
|
147
|
+
// Codes in the `4xx` range indicate an error that failed given the information provided
|
|
148
|
+
if (result.statusCode === 429) throw new Error(`${result.statusCode}: ${result.code}, You are being rate limited, No API Key is 10 Requests / Minute.`)
|
|
149
|
+
// Codes in the `4xx` range indicate an error that failed given the information provided
|
|
150
|
+
if (result.statusCode.toString().startsWith(4)) throw new Error(`${result.statusCode}: ${result.code}, Codes in the 4xx range indicate an error that failed given the information provided.`)
|
|
151
|
+
// Codes in the 5xx range indicate an error with Songlink's servers.
|
|
152
|
+
if (result.statusCode.toString().startsWith(5)) throw new Error(`${result.statusCode}: ${result.code}, Codes in the 5xx range indicate an error with Songlink's servers.`)
|
|
153
|
+
// Otherwise if the code is not 200 (Success), throw a generic error.
|
|
154
|
+
if (result.statusCode !== 200) throw new Error(`${result.statusCode}: ${result.code}`)
|
|
155
|
+
// return undefined as we didn't find anything.
|
|
156
|
+
return undefined
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Cache successful responses
|
|
160
|
+
if (this.cacheEnabled && result) {
|
|
161
|
+
cacheResponse(url, result)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return result
|
|
165
|
+
} catch (err) {
|
|
166
|
+
if (err.name === 'AbortError') {
|
|
167
|
+
throw new Error(`Request timeout after ${this.timeout}ms`)
|
|
168
|
+
}
|
|
169
|
+
if (err.message === 'Unexpected token < in JSON at position 0') {
|
|
170
|
+
throw new Error('API returned an unexpected result.')
|
|
171
|
+
}
|
|
172
|
+
throw err
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Clear the response cache
|
|
178
|
+
*
|
|
179
|
+
* @example
|
|
180
|
+
* ```javascript
|
|
181
|
+
* const odesli = new Odesli();
|
|
182
|
+
* odesli.clearCache(); // Clear all cached responses
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
clearCache () {
|
|
186
|
+
cache.clear()
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Get cache statistics
|
|
191
|
+
*
|
|
192
|
+
* @returns {Object} Cache statistics
|
|
193
|
+
* @example
|
|
194
|
+
* ```javascript
|
|
195
|
+
* const odesli = new Odesli();
|
|
196
|
+
* const stats = odesli.getCacheStats();
|
|
197
|
+
* console.log(`Cache size: ${stats.size}, Hit rate: ${stats.hitRate}%`);
|
|
198
|
+
* ```
|
|
199
|
+
*/
|
|
200
|
+
getCacheStats () {
|
|
201
|
+
clearExpiredCache()
|
|
202
|
+
return {
|
|
203
|
+
size: cache.size,
|
|
204
|
+
ttl: CACHE_TTL
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Fetch song/album information by URL from any supported streaming platform
|
|
210
|
+
*
|
|
211
|
+
* @param {string} url - URL from any supported streaming platform (Spotify, Apple Music, YouTube, etc.)
|
|
212
|
+
* @param {string} [country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
|
|
213
|
+
* @returns {Promise<Object>} Song/album information with links to all available platforms
|
|
214
|
+
*
|
|
215
|
+
* @example
|
|
216
|
+
* ```javascript
|
|
217
|
+
* // Fetch a song by Spotify URL
|
|
218
|
+
* const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
|
|
219
|
+
* console.log(`${song.title} by ${song.artist[0]}`);
|
|
220
|
+
*
|
|
221
|
+
* // Fetch with custom country
|
|
222
|
+
* const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR', 'GB');
|
|
223
|
+
*
|
|
224
|
+
* // Get all available platform links
|
|
225
|
+
* Object.keys(song.linksByPlatform).forEach(platform => {
|
|
226
|
+
* console.log(`${platform}: ${song.linksByPlatform[platform].url}`);
|
|
227
|
+
* });
|
|
228
|
+
* ```
|
|
229
|
+
*
|
|
230
|
+
* @throws {Error} When no URL is provided
|
|
231
|
+
* @throws {Error} When API returns an error (rate limiting, invalid URL, etc.)
|
|
232
|
+
*/
|
|
233
|
+
async fetch (url, country = 'US') {
|
|
234
|
+
if (!url) throw new Error('No URL was provided to odesli.fetch()')
|
|
235
|
+
const path = `links?url=${encodeURIComponent(url)}&userCountry=${country}`
|
|
236
|
+
const song = await this._request(path)
|
|
237
|
+
|
|
238
|
+
// Handle edge cases where response is malformed
|
|
239
|
+
if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
|
|
240
|
+
return song || {}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const id = song.entitiesByUniqueId[song.entityUniqueId].id
|
|
244
|
+
const title = song.entitiesByUniqueId[song.entityUniqueId].title
|
|
245
|
+
|
|
246
|
+
// Convert Artist into Array for easier extraction of features
|
|
247
|
+
Object.values(song.entitiesByUniqueId).forEach(function (values) {
|
|
248
|
+
if (values.artistName && typeof values.artistName === 'string') {
|
|
249
|
+
values.artistName = values.artistName.split(', ')
|
|
250
|
+
}
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
|
|
254
|
+
const type = song.entitiesByUniqueId[song.entityUniqueId].type
|
|
255
|
+
const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
|
|
256
|
+
|
|
257
|
+
return {
|
|
258
|
+
...song,
|
|
259
|
+
id,
|
|
260
|
+
title,
|
|
261
|
+
artist,
|
|
262
|
+
type,
|
|
263
|
+
thumbnail
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Fetch song/album information by platform, type, and ID
|
|
269
|
+
*
|
|
270
|
+
* @param {string} platform - Platform name (spotify, appleMusic, youtube, etc.)
|
|
271
|
+
* @param {string} type - Content type ('song' or 'album')
|
|
272
|
+
* @param {string} id - Platform-specific ID (can be full format like 'SPOTIFY_SONG::123' or just '123')
|
|
273
|
+
* @param {string} [country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
|
|
274
|
+
* @returns {Promise<Object>} Song/album information with links to all available platforms
|
|
275
|
+
*
|
|
276
|
+
* @example
|
|
277
|
+
* ```javascript
|
|
278
|
+
* // Get song by Spotify ID
|
|
279
|
+
* const song = await odesli.getByParams('spotify', 'song', '4Km5HrUvYTaSUfiSGPJeQR');
|
|
280
|
+
* console.log(song.title);
|
|
281
|
+
*
|
|
282
|
+
* // Get album by Apple Music ID
|
|
283
|
+
* const album = await odesli.getByParams('appleMusic', 'album', '123456789');
|
|
284
|
+
* console.log(album.title);
|
|
285
|
+
*
|
|
286
|
+
* // Using full ID format
|
|
287
|
+
* const song = await odesli.getByParams('spotify', 'song', 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
|
|
288
|
+
* ```
|
|
289
|
+
*
|
|
290
|
+
* @throws {Error} When platform, type, or ID is not provided
|
|
291
|
+
* @throws {Error} When API returns an error
|
|
292
|
+
*/
|
|
293
|
+
async getByParams (platform, type, id, country = 'US') {
|
|
294
|
+
if (!platform) throw new Error('No `platform` was provided to odesli.getByParams()')
|
|
295
|
+
if (!type) throw new Error('No `type` was provided to odesli.getByParams()')
|
|
296
|
+
if (!id) throw new Error('No `id` was provided to odesli.getByParams()')
|
|
297
|
+
|
|
298
|
+
// if they happen to input the full id (PLATFORM_SONG::UNIQUEID), just get the UNIQUEID
|
|
299
|
+
id = id.replace(/[^::]+::/g, '')
|
|
300
|
+
const path = `links?platform=${platform}&type=${type}&id=${id}&userCountry=${country}`
|
|
301
|
+
const song = await this._request(path)
|
|
302
|
+
|
|
303
|
+
// Handle edge cases where response is malformed
|
|
304
|
+
if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
|
|
305
|
+
return song || {}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Convert Artist into Array for easier extraction of features
|
|
309
|
+
Object.values(song.entitiesByUniqueId).forEach(function (values) {
|
|
310
|
+
if (values.artistName && typeof values.artistName === 'string') {
|
|
311
|
+
values.artistName = values.artistName.split(', ')
|
|
312
|
+
}
|
|
313
|
+
})
|
|
314
|
+
|
|
315
|
+
// Easier extraction of page's title, album, and thumbnail
|
|
316
|
+
const title = song.entitiesByUniqueId[song.entityUniqueId].title
|
|
317
|
+
const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
|
|
318
|
+
const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
|
|
319
|
+
const entityType = song.entitiesByUniqueId[song.entityUniqueId].type
|
|
320
|
+
|
|
321
|
+
return {
|
|
322
|
+
...song,
|
|
323
|
+
title,
|
|
324
|
+
artist,
|
|
325
|
+
thumbnail,
|
|
326
|
+
type: entityType
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Fetch song/album information by entity ID
|
|
332
|
+
*
|
|
333
|
+
* @param {string} id - Full entity ID in format 'PLATFORM_TYPE::UNIQUEID' (e.g., 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR')
|
|
334
|
+
* @param {string} [country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
|
|
335
|
+
* @returns {Promise<Object>} Song/album information with links to all available platforms
|
|
336
|
+
*
|
|
337
|
+
* @example
|
|
338
|
+
* ```javascript
|
|
339
|
+
* // Get song by entity ID
|
|
340
|
+
* const song = await odesli.getById('SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
|
|
341
|
+
* console.log(song.title);
|
|
342
|
+
*
|
|
343
|
+
* // Get album by entity ID
|
|
344
|
+
* const album = await odesli.getById('APPLEMUSIC_ALBUM::123456789');
|
|
345
|
+
* console.log(album.title);
|
|
346
|
+
* ```
|
|
347
|
+
*
|
|
348
|
+
* @throws {Error} When ID is not provided
|
|
349
|
+
* @throws {Error} When ID format is invalid (must match 'PLATFORM_TYPE::UNIQUEID')
|
|
350
|
+
* @throws {Error} When API returns an error
|
|
351
|
+
*/
|
|
352
|
+
async getById (id, country = 'US') {
|
|
353
|
+
if (!id) throw new Error('No `id` was provided to odesli.getById()')
|
|
354
|
+
if (!id.match(/\w+_\w+::\w+/g)) throw new Error('Provided Entity ID Does not match format. `<PLATFORM>_<SONG|ALBUM>::<UNIQUEID>`')
|
|
355
|
+
|
|
356
|
+
// Convert string into seperate params
|
|
357
|
+
const platform = id.replace(/_\w+::\w+/g, '').toLowerCase()
|
|
358
|
+
const type = id.replace(/\w+_/g, '').replace(/::\w+/g, '').toLowerCase()
|
|
359
|
+
const unique = id.replace(/\w+::/g, '')
|
|
360
|
+
|
|
361
|
+
const path = `links?platform=${platform}&type=${type}&id=${unique}&userCountry=${country}`
|
|
362
|
+
const song = await this._request(path)
|
|
363
|
+
|
|
364
|
+
// Handle edge cases where response is malformed
|
|
365
|
+
if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
|
|
366
|
+
return song || {}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// Convert Artist into Array for easier extraction of features
|
|
370
|
+
Object.values(song.entitiesByUniqueId).forEach(function (values) {
|
|
371
|
+
if (values.artistName && typeof values.artistName === 'string') {
|
|
372
|
+
values.artistName = values.artistName.split(', ')
|
|
373
|
+
}
|
|
374
|
+
})
|
|
375
|
+
|
|
376
|
+
// Easier extraction of page's title, album, and thumbnail
|
|
377
|
+
const title = song.entitiesByUniqueId[song.entityUniqueId].title
|
|
378
|
+
const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
|
|
379
|
+
const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
|
|
380
|
+
const entityType = song.entitiesByUniqueId[song.entityUniqueId].type
|
|
381
|
+
|
|
382
|
+
return {
|
|
383
|
+
...song,
|
|
384
|
+
title,
|
|
385
|
+
artist,
|
|
386
|
+
thumbnail,
|
|
387
|
+
type: entityType
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|