odesli.js 1.1.2 → 1.3.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.
@@ -0,0 +1,382 @@
1
+ /**
2
+ * Plugin System for Odesli API
3
+ * Allows extensible functionality through plugins
4
+ */
5
+
6
+ class PluginSystem {
7
+ constructor() {
8
+ this.plugins = new Map()
9
+ this.hooks = new Map()
10
+ this.middleware = []
11
+ this.transformers = []
12
+
13
+ // Register built-in hooks
14
+ this.registerHook('beforeRequest', [])
15
+ this.registerHook('afterRequest', [])
16
+ this.registerHook('beforeResponse', [])
17
+ this.registerHook('afterResponse', [])
18
+ this.registerHook('onError', [])
19
+ this.registerHook('onRateLimit', [])
20
+ this.registerHook('onCacheHit', [])
21
+ this.registerHook('onCacheMiss', [])
22
+ }
23
+
24
+ /**
25
+ * Register a plugin
26
+ */
27
+ registerPlugin(name, plugin) {
28
+ if (this.plugins.has(name)) {
29
+ throw new Error(`Plugin "${name}" is already registered`)
30
+ }
31
+
32
+ // Validate plugin structure
33
+ if (typeof plugin !== 'object' || plugin === null) {
34
+ throw new Error(`Plugin "${name}" must be an object`)
35
+ }
36
+
37
+ // Initialize plugin if it has an init method
38
+ if (typeof plugin.init === 'function') {
39
+ plugin.init()
40
+ }
41
+
42
+ this.plugins.set(name, plugin)
43
+
44
+ // Register hooks if plugin provides them
45
+ if (plugin.hooks) {
46
+ Object.entries(plugin.hooks).forEach(([hookName, handler]) => {
47
+ this.registerHookHandler(hookName, handler)
48
+ })
49
+ }
50
+
51
+ // Register middleware if plugin provides it
52
+ if (plugin.middleware) {
53
+ this.middleware.push({
54
+ name,
55
+ middleware: plugin.middleware
56
+ })
57
+ }
58
+
59
+ // Register transformers if plugin provides them
60
+ if (plugin.transformers) {
61
+ this.transformers.push({
62
+ name,
63
+ transformers: plugin.transformers
64
+ })
65
+ }
66
+
67
+ return this
68
+ }
69
+
70
+ /**
71
+ * Unregister a plugin
72
+ */
73
+ unregisterPlugin(name) {
74
+ const plugin = this.plugins.get(name)
75
+ if (!plugin) {
76
+ throw new Error(`Plugin "${name}" is not registered`)
77
+ }
78
+
79
+ // Cleanup plugin if it has a cleanup method
80
+ if (typeof plugin.cleanup === 'function') {
81
+ plugin.cleanup()
82
+ }
83
+
84
+ // Remove middleware
85
+ this.middleware = this.middleware.filter(m => m.name !== name)
86
+
87
+ // Remove transformers
88
+ this.transformers = this.transformers.filter(t => t.name !== name)
89
+
90
+ // Remove hook handlers
91
+ this.hooks.forEach((handlers, hookName) => {
92
+ this.hooks.set(hookName, handlers.filter(h => h.pluginName !== name))
93
+ })
94
+
95
+ this.plugins.delete(name)
96
+ return this
97
+ }
98
+
99
+ /**
100
+ * Register a hook
101
+ */
102
+ registerHook(name, defaultHandlers = []) {
103
+ if (!this.hooks.has(name)) {
104
+ this.hooks.set(name, defaultHandlers)
105
+ }
106
+ return this
107
+ }
108
+
109
+ /**
110
+ * Register a hook handler
111
+ */
112
+ registerHookHandler(hookName, handler, pluginName = null) {
113
+ if (!this.hooks.has(hookName)) {
114
+ this.registerHook(hookName)
115
+ }
116
+
117
+ const handlers = this.hooks.get(hookName)
118
+ handlers.push({
119
+ handler,
120
+ pluginName,
121
+ priority: handler.priority || 0
122
+ })
123
+
124
+ // Sort by priority (higher priority first)
125
+ handlers.sort((a, b) => b.priority - a.priority)
126
+
127
+ return this
128
+ }
129
+
130
+ /**
131
+ * Execute hook handlers
132
+ */
133
+ async executeHook(hookName, context = {}) {
134
+ const handlers = this.hooks.get(hookName) || []
135
+
136
+ for (const { handler } of handlers) {
137
+ try {
138
+ if (typeof handler === 'function') {
139
+ await handler(context)
140
+ }
141
+ } catch (error) {
142
+ // Prevent infinite recursion by only calling onError if it's not already an onError hook
143
+ if (hookName !== 'onError') {
144
+ try {
145
+ await this.executeHook('onError', { error, hookName, context })
146
+ } catch (errorHookError) {
147
+ // If error hook fails, just log it to prevent infinite loops
148
+ console.error('Error in onError hook:', errorHookError.message)
149
+ }
150
+ } else {
151
+ // If we're already in an onError hook, just log the error
152
+ console.error('Error in onError hook:', error.message)
153
+ }
154
+ }
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Execute middleware chain
160
+ */
161
+ async executeMiddleware(context, next) {
162
+ let index = 0
163
+
164
+ const executeNext = async () => {
165
+ if (index >= this.middleware.length) {
166
+ return await next()
167
+ }
168
+
169
+ const { middleware } = this.middleware[index++]
170
+ return await middleware(context, executeNext)
171
+ }
172
+
173
+ return await executeNext()
174
+ }
175
+
176
+ /**
177
+ * Transform data through all transformers
178
+ */
179
+ async transformData(data, type, context = {}) {
180
+ let transformedData = data
181
+
182
+ for (const { transformers } of this.transformers) {
183
+ if (transformers[type]) {
184
+ try {
185
+ transformedData = await transformers[type](transformedData, context)
186
+ } catch (error) {
187
+ await this.executeHook('onError', { error, type, context })
188
+ }
189
+ }
190
+ }
191
+
192
+ return transformedData
193
+ }
194
+
195
+ /**
196
+ * Get plugin by name
197
+ */
198
+ getPlugin(name) {
199
+ return this.plugins.get(name)
200
+ }
201
+
202
+ /**
203
+ * Get all registered plugins
204
+ */
205
+ getPlugins() {
206
+ return Array.from(this.plugins.keys())
207
+ }
208
+
209
+ /**
210
+ * Check if plugin is registered
211
+ */
212
+ hasPlugin(name) {
213
+ return this.plugins.has(name)
214
+ }
215
+
216
+ /**
217
+ * Get plugin info
218
+ */
219
+ getPluginInfo(name) {
220
+ const plugin = this.plugins.get(name)
221
+ if (!plugin) return null
222
+
223
+ return {
224
+ name,
225
+ hooks: Object.keys(plugin.hooks || {}),
226
+ hasMiddleware: !!plugin.middleware,
227
+ hasTransformers: !!plugin.transformers,
228
+ version: plugin.version,
229
+ description: plugin.description
230
+ }
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Example plugins
236
+ */
237
+
238
+ // Logging Plugin
239
+ const loggingPlugin = {
240
+ name: 'logging',
241
+ version: '1.0.0',
242
+ description: 'Adds comprehensive logging to API requests',
243
+
244
+ init() {
245
+ console.log('Logging plugin initialized')
246
+ },
247
+
248
+ hooks: {
249
+ beforeRequest: async (context) => {
250
+ console.log(`[${new Date().toISOString()}] Request: ${context.url}`)
251
+ },
252
+
253
+ afterRequest: async (context) => {
254
+ console.log(`[${new Date().toISOString()}] Response: ${context.statusCode} (${context.responseTime}ms)`)
255
+ },
256
+
257
+ onError: async (context) => {
258
+ console.error(`[${new Date().toISOString()}] Error: ${context.error.message}`)
259
+ }
260
+ }
261
+ }
262
+
263
+ // Caching Plugin
264
+ const cachingPlugin = {
265
+ name: 'caching',
266
+ version: '1.0.0',
267
+ description: 'Enhanced caching with TTL and invalidation',
268
+
269
+ init() {
270
+ this.cache = new Map()
271
+ this.ttl = 5 * 60 * 1000 // 5 minutes
272
+ },
273
+
274
+ hooks: {
275
+ beforeRequest: async (context) => {
276
+ const cached = this.cache.get(context.url)
277
+ if (cached && Date.now() - cached.timestamp < this.ttl) {
278
+ context.cached = true
279
+ context.response = cached.data
280
+
281
+ }
282
+ },
283
+
284
+ afterResponse: async (context) => {
285
+ if (!context.cached && context.response) {
286
+ this.cache.set(context.url, {
287
+ data: context.response,
288
+ timestamp: Date.now()
289
+ })
290
+ }
291
+ }
292
+ },
293
+
294
+ cleanup() {
295
+ this.cache.clear()
296
+ }
297
+ }
298
+
299
+ // Analytics Plugin
300
+ const analyticsPlugin = {
301
+ name: 'analytics',
302
+ version: '1.0.0',
303
+ description: 'Tracks usage analytics and metrics',
304
+
305
+ init() {
306
+ this.metrics = {
307
+ requests: 0,
308
+ errors: 0,
309
+ cacheHits: 0,
310
+ responseTimes: []
311
+ }
312
+ },
313
+
314
+ hooks: {
315
+ beforeRequest: async (context) => {
316
+ context.startTime = Date.now()
317
+ this.metrics.requests++
318
+ },
319
+
320
+ afterResponse: async (context) => {
321
+ const responseTime = Date.now() - context.startTime
322
+ this.metrics.responseTimes.push(responseTime)
323
+
324
+ if (context.cached) {
325
+ this.metrics.cacheHits++
326
+ }
327
+ },
328
+
329
+ onError: async (_context) => {
330
+ this.metrics.errors++
331
+ }
332
+ },
333
+
334
+ getMetrics() {
335
+ return {
336
+ ...this.metrics,
337
+ avgResponseTime: this.metrics.responseTimes.length > 0
338
+ ? this.metrics.responseTimes.reduce((a, b) => a + b, 0) / this.metrics.responseTimes.length
339
+ : 0,
340
+ cacheHitRate: this.metrics.requests > 0
341
+ ? (this.metrics.cacheHits / this.metrics.requests) * 100
342
+ : 0
343
+ }
344
+ }
345
+ }
346
+
347
+ // Response Transformer Plugin
348
+ const responseTransformerPlugin = {
349
+ name: 'response-transformer',
350
+ version: '1.0.0',
351
+ description: 'Transforms API responses into different formats',
352
+
353
+ transformers: {
354
+ 'song': async (data, _context) => {
355
+ // Transform song data
356
+ return {
357
+ ...data,
358
+ formattedTitle: data.title?.toUpperCase(),
359
+ artistCount: data.artist?.length || 0,
360
+ hasThumbnail: !!data.thumbnail
361
+ }
362
+ },
363
+
364
+ 'album': async (data, _context) => {
365
+ // Transform album data
366
+ return {
367
+ ...data,
368
+ formattedTitle: data.title?.toUpperCase(),
369
+ artistCount: data.artist?.length || 0,
370
+ hasThumbnail: !!data.thumbnail
371
+ }
372
+ }
373
+ }
374
+ }
375
+
376
+ module.exports = {
377
+ PluginSystem,
378
+ loggingPlugin,
379
+ cachingPlugin,
380
+ analyticsPlugin,
381
+ responseTransformerPlugin
382
+ }
@@ -0,0 +1,3 @@
1
+ import * as cjs from './plugin-system.js';
2
+ export * from './plugin-system.js';
3
+ export default cjs;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Rate Limiter for Odesli API
3
+ * Implements various rate limiting strategies
4
+ */
5
+
6
+ class RateLimiter {
7
+ constructor(options = {}) {
8
+ this.maxRequests = options.maxRequests || 10 // Default: 10 requests per window
9
+ this.windowMs = options.windowMs || 60000 // Default: 1 minute window
10
+ this.strategy = options.strategy || 'token-bucket' // token-bucket, leaky-bucket, sliding-window
11
+ this.retryAfterMs = options.retryAfterMs || 1000 // Default retry delay
12
+
13
+ // Token bucket specific
14
+ this.tokens = this.maxRequests
15
+ this.lastRefill = Date.now()
16
+
17
+ // Sliding window specific
18
+ this.requests = []
19
+
20
+ // Leaky bucket specific
21
+ this.queue = []
22
+ this.processing = false
23
+ }
24
+
25
+ /**
26
+ * Token Bucket Algorithm
27
+ * Most efficient for burst handling
28
+ */
29
+ async tokenBucket() {
30
+ const now = Date.now()
31
+ const timePassed = now - this.lastRefill
32
+ const tokensToAdd = Math.floor(timePassed / this.windowMs) * this.maxRequests
33
+
34
+ this.tokens = Math.min(this.maxRequests, this.tokens + tokensToAdd)
35
+ this.lastRefill = now
36
+
37
+ if (this.tokens >= 1) {
38
+ this.tokens--
39
+ return true
40
+ }
41
+
42
+ // Calculate wait time
43
+ const waitTime = this.windowMs - (timePassed % this.windowMs)
44
+ await new Promise(resolve => setTimeout(resolve, waitTime))
45
+ return this.tokenBucket()
46
+ }
47
+
48
+ /**
49
+ * Leaky Bucket Algorithm
50
+ * Good for smoothing out traffic
51
+ */
52
+ async leakyBucket() {
53
+ return new Promise((resolve) => {
54
+ this.queue.push(resolve)
55
+ this.processQueue()
56
+ })
57
+ }
58
+
59
+ async processQueue() {
60
+ if (this.processing || this.queue.length === 0) return
61
+
62
+ this.processing = true
63
+
64
+ while (this.queue.length > 0) {
65
+ const resolve = this.queue.shift()
66
+ resolve()
67
+ await new Promise(resolve => setTimeout(resolve, this.windowMs / this.maxRequests))
68
+ }
69
+
70
+ this.processing = false
71
+ }
72
+
73
+ /**
74
+ * Sliding Window Algorithm
75
+ * Most accurate for rate limiting
76
+ */
77
+ async slidingWindow() {
78
+ const now = Date.now()
79
+ const windowStart = now - this.windowMs
80
+
81
+ // Remove old requests outside the window
82
+ this.requests = this.requests.filter(timestamp => timestamp > windowStart)
83
+
84
+ if (this.requests.length < this.maxRequests) {
85
+ this.requests.push(now)
86
+ return true
87
+ }
88
+
89
+ // Calculate wait time until next slot opens
90
+ const oldestRequest = this.requests[0]
91
+ const waitTime = oldestRequest + this.windowMs - now
92
+ await new Promise(resolve => setTimeout(resolve, waitTime))
93
+ return this.slidingWindow()
94
+ }
95
+
96
+ /**
97
+ * Main rate limit method
98
+ */
99
+ async waitForSlot() {
100
+ switch (this.strategy) {
101
+ case 'token-bucket':
102
+ return this.tokenBucket()
103
+ case 'leaky-bucket':
104
+ return this.leakyBucket()
105
+ case 'sliding-window':
106
+ return this.slidingWindow()
107
+ default:
108
+ return this.tokenBucket()
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Handle rate limit response from API
114
+ */
115
+ async handleRateLimitResponse(retryAfterSeconds) {
116
+ const waitTime = (retryAfterSeconds || 60) * 1000
117
+ await new Promise(resolve => setTimeout(resolve, waitTime))
118
+ }
119
+
120
+ /**
121
+ * Get current rate limit status
122
+ */
123
+ getStatus() {
124
+ switch (this.strategy) {
125
+ case 'token-bucket':
126
+ return {
127
+ available: this.tokens,
128
+ max: this.maxRequests,
129
+ used: this.maxRequests - this.tokens,
130
+ refillRate: this.maxRequests / (this.windowMs / 1000)
131
+ }
132
+ case 'sliding-window':
133
+ return {
134
+ used: this.requests.length,
135
+ max: this.maxRequests,
136
+ windowMs: this.windowMs
137
+ }
138
+ case 'leaky-bucket':
139
+ return {
140
+ queued: this.queue.length,
141
+ processing: this.processing,
142
+ max: this.maxRequests
143
+ }
144
+ }
145
+ }
146
+ }
147
+
148
+ module.exports = { RateLimiter }
@@ -0,0 +1,3 @@
1
+ import * as cjs from './rate-limiter.js';
2
+ export * from './rate-limiter.js';
3
+ export default cjs;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odesli.js",
3
- "version": "1.1.2",
3
+ "version": "1.3.2",
4
4
  "description": "Node.js Client to query odesli.co (song.link/album.link) API",
5
5
  "main": "lib/index.js",
6
6
  "module": "lib/index.js",
@@ -71,6 +71,7 @@
71
71
  "eslint-plugin-prettier": "^5.5.0",
72
72
  "eslint-plugin-promise": "^6.6.0",
73
73
  "jest": "^29.5.0",
74
+ "jest-fetch-mock": "^3.0.3",
74
75
  "jsdoc": "^4.0.2",
75
76
  "prettier": "^3.0.0",
76
77
  "snyk": "^1.1234.0",