spotify-now-playing-banner 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # spotify-now-playing-banner
2
2
 
3
- A small React component that shows what you're listening to on Spotify — track, artist, album art, live progress, and the next item in your queue — and keeps it up to date by polling your own API endpoint.
3
+ A small React component that shows what you're listening to on Spotify — track, artist, album art, live progress, and the next item in your queue — plus a bundled server endpoint that reads Spotify for you.
4
4
 
5
- No Spotify credentials are shipped to the browser. Your server holds them and exposes a read-only status endpoint.
5
+ No Spotify credentials are shipped to the browser. The server helper included in this package holds them, talks to Spotify with [axios](https://axios-http.com/), and exposes a read-only status endpoint at `/api/spotify`.
6
6
 
7
7
  ## Install
8
8
 
@@ -10,20 +10,69 @@ No Spotify credentials are shipped to the browser. Your server holds them and ex
10
10
  npm install spotify-now-playing-banner
11
11
  ```
12
12
 
13
- React 18 or newer is required as a peer dependency.
13
+ React 18 or newer is required as a peer dependency. `axios` is installed automatically for the server helper.
14
14
 
15
15
  ## Usage
16
16
 
17
+ Mount the bundled handler at `/api/spotify`, then render the banner with no props:
18
+
17
19
  ```tsx
18
20
  import { SpotifyBanner } from 'spotify-now-playing-banner'
19
21
  import 'spotify-now-playing-banner/styles.css'
20
22
 
21
23
  export function NowPlaying() {
22
- return <SpotifyBanner endpoint="/api/spotify" />
24
+ return <SpotifyBanner />
23
25
  }
24
26
  ```
25
27
 
26
- You can render a build-time snapshot immediately and update it from the API:
28
+ ### 1. Set the credentials on the server
29
+
30
+ ```sh
31
+ SPOTIFY_CLIENT_ID=...
32
+ SPOTIFY_CLIENT_SECRET=...
33
+ SPOTIFY_REFRESH_TOKEN=...
34
+ ```
35
+
36
+ See [Spotify's guide](https://developer.spotify.com/documentation/web-api/concepts/authorization) for how to obtain a refresh token. These values must only exist on the server — never prefix them with `NEXT_PUBLIC_`/`VITE_` or import them into client code.
37
+
38
+ ### 2. Expose the endpoint
39
+
40
+ **Next.js App Router** (`app/api/spotify/route.ts`):
41
+
42
+ ```ts
43
+ import { createSpotifyHandler } from 'spotify-now-playing-banner/server'
44
+
45
+ export const GET = createSpotifyHandler()
46
+ export const OPTIONS = GET
47
+ ```
48
+
49
+ **Next.js Pages Router / Vercel Node function** (`api/spotify.mjs`):
50
+
51
+ ```js
52
+ import { createSpotifyHandler } from 'spotify-now-playing-banner/server'
53
+
54
+ export default createSpotifyHandler()
55
+ ```
56
+
57
+ **Plain Node 18+ server:**
58
+
59
+ ```js
60
+ import { createServer } from 'node:http'
61
+ import { createSpotifyHandler } from 'spotify-now-playing-banner/server'
62
+
63
+ const handler = createSpotifyHandler()
64
+ createServer((req, res) => {
65
+ if (req.url === '/api/spotify') void handler(req, res)
66
+ else {
67
+ res.statusCode = 404
68
+ res.end()
69
+ }
70
+ }).listen(3000)
71
+ ```
72
+
73
+ The handler accepts both a Web `Request` and a Node `(req, res)` pair, caches snapshots for 5 seconds, and sets permissive CORS headers so a site on a different origin can poll it.
74
+
75
+ ### Optional props
27
76
 
28
77
  ```tsx
29
78
  import lastPlayed from './data/last-played.json'
@@ -33,7 +82,6 @@ import 'spotify-now-playing-banner/styles.css'
33
82
  export function NowPlaying() {
34
83
  return (
35
84
  <SpotifyBanner
36
- endpoint="https://your-api.example.com/api/spotify"
37
85
  initialStatus={lastPlayed as SpotifyStatus}
38
86
  pollIntervalMs={5000}
39
87
  className="my-banner"
@@ -42,20 +90,56 @@ export function NowPlaying() {
42
90
  }
43
91
  ```
44
92
 
45
- ### Props
46
-
47
93
  | Prop | Type | Default | Description |
48
94
  | --- | --- | --- | --- |
49
- | `endpoint` | `string` | `/api/spotify` | URL that returns a `SpotifyStatus` JSON object. May be a full cross-origin URL. |
95
+ | `endpoint` | `string` | `/api/spotify` | Override the status URL. Not needed when using the bundled handler. May be a full cross-origin URL. |
50
96
  | `initialStatus` | `SpotifyStatus \| null` | `null` | Status to render before the first successful poll. The component renders nothing until it has data. |
51
97
  | `pollIntervalMs` | `number` | `3000` | Polling interval. Set to `0` to disable polling and render only `initialStatus`. |
52
98
  | `className` | `string` | – | Extra class names on the root `<section>`. |
53
99
 
54
100
  The component re-fetches immediately when the tab becomes visible again, ignores stale/out-of-order responses, and locally advances the progress bar between polls. It also detects seeks or playback on another device and re-anchors progress.
55
101
 
102
+ ## Server API
103
+
104
+ Everything is exported from `spotify-now-playing-banner/server`:
105
+
106
+ | Export | Description |
107
+ | --- | --- |
108
+ | `createSpotifyHandler(options?)` | Build the read-only endpoint (Web or Node style). |
109
+ | `getSpotifyStatus(options?)` | Fetch the status JSON directly, e.g. from a server component or a build script. |
110
+ | `fetchSpotifyStatus(options?)` | Same, but also returns `ageMs` for the server cache. |
111
+ | `credentialsFromEnv(env?)` | Read and validate the three credentials from an env object. |
112
+ | `clearSpotifyCache()` | Clear cached token/status (useful in tests). |
113
+ | `SpotifyError` | Error type with an optional HTTP `status`. |
114
+
115
+ Options let you override credentials explicitly, change the cache duration, or point at custom HTTP endpoints for tests:
116
+
117
+ ```ts
118
+ const handler = createSpotifyHandler({
119
+ clientId: process.env.MY_CLIENT_ID,
120
+ clientSecret: process.env.MY_CLIENT_SECRET,
121
+ refreshToken: process.env.MY_REFRESH_TOKEN,
122
+ cacheMs: 10_000,
123
+ cors: false
124
+ })
125
+ ```
126
+
127
+ Credentials are resolved in this order: explicit option → environment variable.
128
+
129
+ ```tsx
130
+ // Server component: render a snapshot immediately.
131
+ import { getSpotifyStatus } from 'spotify-now-playing-banner/server'
132
+ import { SpotifyBanner } from 'spotify-now-playing-banner'
133
+
134
+ export default async function Page() {
135
+ const status = await getSpotifyStatus()
136
+ return <SpotifyBanner initialStatus={status} />
137
+ }
138
+ ```
139
+
56
140
  ## API contract
57
141
 
58
- The endpoint must respond to `GET` with one of these JSON shapes:
142
+ The endpoint responds to `GET` with one of these JSON shapes:
59
143
 
60
144
  ```json
61
145
  {
@@ -87,24 +171,7 @@ Fields:
87
171
  - `next` — optional queued item; only displayed while `playing` is `true`.
88
172
  - `ageMs` — optional age of a server-cached snapshot in ms, used to keep progress accurate.
89
173
 
90
- Return `null` (or a non-2xx status) when nothing is available; the component keeps its last known data.
91
-
92
- ## Server setup
93
-
94
- The endpoint needs Spotify credentials in environment variables:
95
-
96
- ```sh
97
- SPOTIFY_CLIENT_ID=...
98
- SPOTIFY_CLIENT_SECRET=...
99
- SPOTIFY_REFRESH_TOKEN=...
100
- ```
101
-
102
- A ready-to-use implementation lives in the source repository:
103
-
104
- - `lib/spotify.mjs` — refreshes the access token, reads `me/player/currently-playing`, the queue, and `me/player/recently-played`, and normalizes the result.
105
- - `api/spotify.mjs` — a Vercel-style handler that caches responses for 5 seconds and sets `Access-Control-Allow-Origin: *` for cross-origin sites.
106
-
107
- If your site is on a different origin than the API, enable CORS on the endpoint (the included handler already does).
174
+ The endpoint returns `null` when nothing is available; the component keeps its last known data. Errors return a JSON `{ error }` body with a 500/502 status.
108
175
 
109
176
  ## Styling
110
177
 
package/dist/index.d.ts CHANGED
@@ -1,44 +1,13 @@
1
1
  import * as react from 'react';
2
-
3
- /** A track (or podcast episode) in the playback queue. */
4
- type SpotifyQueueItem = {
5
- track: string;
6
- artist: string;
7
- album?: string;
8
- image: string;
9
- url: string;
10
- };
11
- /** The response returned by the Spotify status endpoint this component polls. */
12
- type SpotifyStatus = {
13
- playing: boolean;
14
- track: string;
15
- artist: string;
16
- album: string;
17
- image: string;
18
- url: string;
19
- playedAt: string | null;
20
- progressMs?: number | null;
21
- durationMs?: number | null;
22
- next?: SpotifyQueueItem | null;
23
- /** Age of the server-side snapshot in milliseconds. */
24
- ageMs?: number;
25
- };
26
- type SpotifyBannerProps = {
27
- /** URL of the endpoint that returns a SpotifyStatus. Defaults to `/api/spotify`. */
28
- endpoint?: string;
29
- /** Data to render before the first poll succeeds. */
30
- initialStatus?: SpotifyStatus | null;
31
- /** Polling interval in milliseconds. Set to 0 to disable polling. Defaults to 3000. */
32
- pollIntervalMs?: number;
33
- /** Extra class names applied to the root element. */
34
- className?: string;
35
- };
2
+ import { S as SpotifyBannerProps } from './types-CJlhN267.js';
3
+ export { a as SpotifyQueueItem, b as SpotifyStatus } from './types-CJlhN267.js';
36
4
 
37
5
  /**
38
- * Shows the current (or most recent) Spotify track and polls an endpoint for
39
- * updates. Styling comes from `spotify-now-playing-banner/styles.css`.
6
+ * Shows the current (or most recent) Spotify track and polls `/api/spotify`
7
+ * for updates. Mount the bundled `createSpotifyHandler()` at that route to
8
+ * use the component without passing an `endpoint` prop.
9
+ * Styling comes from `spotify-now-playing-banner/styles.css`.
40
10
  */
41
11
  declare function SpotifyBanner({ endpoint, initialStatus, pollIntervalMs, className }: SpotifyBannerProps): react.JSX.Element | null;
42
12
 
43
- export { SpotifyBanner };
44
- export type { SpotifyBannerProps, SpotifyQueueItem, SpotifyStatus };
13
+ export { SpotifyBanner, SpotifyBannerProps };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/SpotifyBanner.tsx"],"sourcesContent":["import { useEffect, useState } from 'react'\nimport type { SpotifyBannerProps, SpotifyStatus } from './types'\n\ntype ProgressAnchor = {\n progressMs: number\n at: number\n key: string\n}\n\nfunction trackKey(status: SpotifyStatus) {\n return `${status.track}|${status.playedAt ?? ''}`\n}\n\nfunction formatTime(ms: number) {\n const totalSeconds = Math.max(0, Math.floor(ms / 1000))\n const minutes = Math.floor(totalSeconds / 60)\n const seconds = totalSeconds % 60\n return `${minutes}:${String(seconds).padStart(2, '0')}`\n}\n\n/**\n * Shows the current (or most recent) Spotify track and polls an endpoint for\n * updates. Styling comes from `spotify-now-playing-banner/styles.css`.\n */\nexport function SpotifyBanner({\n endpoint = '/api/spotify',\n initialStatus = null,\n pollIntervalMs = 3000,\n className\n}: SpotifyBannerProps) {\n const [status, setStatus] = useState<SpotifyStatus | null>(initialStatus)\n const [anchor, setAnchor] = useState<ProgressAnchor | null>(null)\n const [now, setNow] = useState(() => Date.now())\n\n useEffect(() => {\n if (pollIntervalMs <= 0) return\n\n let mounted = true\n let latestRequest = 0\n\n const refresh = async () => {\n const requestId = ++latestRequest\n try {\n const response = await fetch(endpoint, { cache: 'no-store' })\n if (!response.ok) return\n\n const live = (await response.json()) as SpotifyStatus | null\n if (!mounted || requestId !== latestRequest || !live?.track) return\n\n const at = Date.now()\n const ageMs = Number.isFinite(live.ageMs) ? Math.max(0, live.ageMs!) : 0\n const snapshotAt = at - ageMs\n const nextAnchor: ProgressAnchor | null =\n typeof live.progressMs === 'number'\n ? { progressMs: live.progressMs, at: snapshotAt, key: trackKey(live) }\n : null\n\n setStatus(live)\n setNow(at)\n setAnchor((prev) => {\n if (!nextAnchor) return null\n if (!prev || prev.key !== nextAnchor.key) return nextAnchor\n\n // A cached snapshot already includes its age, so it should agree with\n // the locally projected position. Keep the smoother local anchor\n // unless there's a real jump (seek, resume on another device).\n const projected = prev.progressMs + Math.max(0, snapshotAt - prev.at)\n return Math.abs(nextAnchor.progressMs - projected) > 1000 ? nextAnchor : prev\n })\n } catch {\n // Keep the last known status when the endpoint is unavailable.\n }\n }\n\n void refresh()\n\n const interval = window.setInterval(() => {\n void refresh()\n }, pollIntervalMs)\n\n const onVisibilityChange = () => {\n if (document.visibilityState === 'visible') void refresh()\n }\n document.addEventListener('visibilitychange', onVisibilityChange)\n\n return () => {\n mounted = false\n window.clearInterval(interval)\n document.removeEventListener('visibilitychange', onVisibilityChange)\n }\n }, [endpoint, pollIntervalMs])\n\n // Advance progress locally between polls. Paused tracks stay put.\n useEffect(() => {\n if (!status?.playing || !anchor) return\n const interval = window.setInterval(() => setNow(Date.now()), 500)\n return () => window.clearInterval(interval)\n }, [status?.playing, anchor])\n\n const progress = (() => {\n if (!status || !anchor || anchor.key !== trackKey(status)) return null\n const duration = status.durationMs\n if (!duration || duration <= 0) return null\n\n const current = Math.min(\n duration,\n anchor.progressMs + (status.playing ? Math.max(0, now - anchor.at) : 0)\n )\n return { current, duration, percent: Math.min(100, (current / duration) * 100) }\n })()\n\n const upNext = status?.playing ? status.next : null\n if (!status) return null\n\n return (\n <section className={className ? `spb-banner ${className}` : 'spb-banner'}>\n <a\n href={status.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"spb-banner__link\"\n aria-label={`${status.playing ? 'Now playing' : 'Last played'} on Spotify: ${status.track} by ${status.artist}${\n progress ? `, ${formatTime(progress.current)} of ${formatTime(progress.duration)}` : ''\n }${upNext?.track ? `, up next: ${upNext.track} by ${upNext.artist}` : ''}`}\n >\n <img\n src={status.image}\n alt=\"\"\n aria-hidden=\"true\"\n className=\"spb-banner__backdrop\"\n />\n <div className=\"spb-banner__overlay\" />\n\n <div className=\"spb-banner__content\">\n <div className=\"spb-banner__meta\">\n <span className=\"spb-banner__badge\">▶ Spotify</span>\n <span className=\"spb-banner__label\">\n {status.playing ? 'Now playing' : 'Last played'}\n </span>\n {progress && (\n <span className=\"spb-banner__time\">\n {formatTime(progress.current)} / {formatTime(progress.duration)}\n </span>\n )}\n </div>\n <p className=\"spb-banner__title\">{status.track}</p>\n <p className=\"spb-banner__artist\">{status.artist}</p>\n\n {upNext?.track && (\n <div className=\"spb-banner__up-next\">\n {upNext.image && (\n <img\n src={upNext.image}\n alt=\"\"\n aria-hidden=\"true\"\n className=\"spb-banner__up-next-image\"\n />\n )}\n <span className=\"spb-banner__up-next-label\">Up next</span>\n <span className=\"spb-banner__up-next-title\">\n {upNext.track}\n {upNext.artist && <span className=\"spb-banner__up-next-artist\"> — {upNext.artist}</span>}\n </span>\n </div>\n )}\n </div>\n\n <img\n src={status.image}\n alt={status.album ? `${status.album} album art` : 'Album art'}\n className=\"spb-banner__art\"\n />\n\n {progress && (\n <div\n className=\"spb-banner__progress\"\n role=\"progressbar\"\n aria-label=\"Track progress\"\n aria-valuemin={0}\n aria-valuemax={progress.duration}\n aria-valuenow={Math.round(progress.current)}\n >\n <div className=\"spb-banner__progress-fill\" style={{ width: `${progress.percent}%` }}>\n <span className=\"spb-banner__progress-dot\" />\n </div>\n </div>\n )}\n </a>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C;AAAA;AAAA,gBACC,KAAK,OAAO;AAAA,gBACZ,KAAI;AAAA,gBACJ,eAAY;AAAA,gBACZ,WAAU;AAAA;AAAA,YACZ;AAAA,YAEF,oBAAC,UAAK,WAAU,6BAA4B,qBAAO;AAAA,YACnD,qBAAC,UAAK,WAAU,6BACb;AAAA,qBAAO;AAAA,cACP,OAAO,UAAU,qBAAC,UAAK,WAAU,8BAA6B;AAAA;AAAA,gBAAI,OAAO;AAAA,iBAAO;AAAA,eACnF;AAAA,aACF;AAAA,WAEJ;AAAA,QAEA;AAAA,UAAC;AAAA;AAAA,YACC,KAAK,OAAO;AAAA,YACZ,KAAK,OAAO,QAAQ,GAAG,OAAO,KAAK,eAAe;AAAA,YAClD,WAAU;AAAA;AAAA,QACZ;AAAA,QAEC,YACC;AAAA,UAAC;AAAA;AAAA,YACC,WAAU;AAAA,YACV,MAAK;AAAA,YACL,cAAW;AAAA,YACX,iBAAe;AAAA,YACf,iBAAe,SAAS;AAAA,YACxB,iBAAe,KAAK,MAAM,SAAS,OAAO;AAAA,YAE1C,8BAAC,SAAI,WAAU,6BAA4B,OAAO,EAAE,OAAO,GAAG,SAAS,OAAO,IAAI,GAChF,8BAAC,UAAK,WAAU,4BAA2B,GAC7C;AAAA;AAAA,QACF;AAAA;AAAA;AAAA,EAEJ,GACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/SpotifyBanner.tsx"],"sourcesContent":["import { useEffect, useState } from 'react'\nimport type { SpotifyBannerProps, SpotifyStatus } from './types'\n\ntype ProgressAnchor = {\n progressMs: number\n at: number\n key: string\n}\n\nfunction trackKey(status: SpotifyStatus) {\n return `${status.track}|${status.playedAt ?? ''}`\n}\n\nfunction formatTime(ms: number) {\n const totalSeconds = Math.max(0, Math.floor(ms / 1000))\n const minutes = Math.floor(totalSeconds / 60)\n const seconds = totalSeconds % 60\n return `${minutes}:${String(seconds).padStart(2, '0')}`\n}\n\n/**\n * Shows the current (or most recent) Spotify track and polls `/api/spotify`\n * for updates. Mount the bundled `createSpotifyHandler()` at that route to\n * use the component without passing an `endpoint` prop.\n * Styling comes from `spotify-now-playing-banner/styles.css`.\n */\nexport function SpotifyBanner({\n endpoint = '/api/spotify',\n initialStatus = null,\n pollIntervalMs = 3000,\n className\n}: SpotifyBannerProps) {\n const [status, setStatus] = useState<SpotifyStatus | null>(initialStatus)\n const [anchor, setAnchor] = useState<ProgressAnchor | null>(null)\n const [now, setNow] = useState(() => Date.now())\n\n useEffect(() => {\n if (pollIntervalMs <= 0) return\n\n let mounted = true\n let latestRequest = 0\n\n const refresh = async () => {\n const requestId = ++latestRequest\n try {\n const response = await fetch(endpoint, { cache: 'no-store' })\n if (!response.ok) return\n\n const live = (await response.json()) as SpotifyStatus | null\n if (!mounted || requestId !== latestRequest || !live?.track) return\n\n const at = Date.now()\n const ageMs = Number.isFinite(live.ageMs) ? Math.max(0, live.ageMs!) : 0\n const snapshotAt = at - ageMs\n const nextAnchor: ProgressAnchor | null =\n typeof live.progressMs === 'number'\n ? { progressMs: live.progressMs, at: snapshotAt, key: trackKey(live) }\n : null\n\n setStatus(live)\n setNow(at)\n setAnchor((prev) => {\n if (!nextAnchor) return null\n if (!prev || prev.key !== nextAnchor.key) return nextAnchor\n\n // A cached snapshot already includes its age, so it should agree with\n // the locally projected position. Keep the smoother local anchor\n // unless there's a real jump (seek, resume on another device).\n const projected = prev.progressMs + Math.max(0, snapshotAt - prev.at)\n return Math.abs(nextAnchor.progressMs - projected) > 1000 ? nextAnchor : prev\n })\n } catch {\n // Keep the last known status when the endpoint is unavailable.\n }\n }\n\n void refresh()\n\n const interval = window.setInterval(() => {\n void refresh()\n }, pollIntervalMs)\n\n const onVisibilityChange = () => {\n if (document.visibilityState === 'visible') void refresh()\n }\n document.addEventListener('visibilitychange', onVisibilityChange)\n\n return () => {\n mounted = false\n window.clearInterval(interval)\n document.removeEventListener('visibilitychange', onVisibilityChange)\n }\n }, [endpoint, pollIntervalMs])\n\n // Advance progress locally between polls. Paused tracks stay put.\n useEffect(() => {\n if (!status?.playing || !anchor) return\n const interval = window.setInterval(() => setNow(Date.now()), 500)\n return () => window.clearInterval(interval)\n }, [status?.playing, anchor])\n\n const progress = (() => {\n if (!status || !anchor || anchor.key !== trackKey(status)) return null\n const duration = status.durationMs\n if (!duration || duration <= 0) return null\n\n const current = Math.min(\n duration,\n anchor.progressMs + (status.playing ? Math.max(0, now - anchor.at) : 0)\n )\n return { current, duration, percent: Math.min(100, (current / duration) * 100) }\n })()\n\n const upNext = status?.playing ? status.next : null\n if (!status) return null\n\n return (\n <section className={className ? `spb-banner ${className}` : 'spb-banner'}>\n <a\n href={status.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"spb-banner__link\"\n aria-label={`${status.playing ? 'Now playing' : 'Last played'} on Spotify: ${status.track} by ${status.artist}${\n progress ? `, ${formatTime(progress.current)} of ${formatTime(progress.duration)}` : ''\n }${upNext?.track ? `, up next: ${upNext.track} by ${upNext.artist}` : ''}`}\n >\n <img\n src={status.image}\n alt=\"\"\n aria-hidden=\"true\"\n className=\"spb-banner__backdrop\"\n />\n <div className=\"spb-banner__overlay\" />\n\n <div className=\"spb-banner__content\">\n <div className=\"spb-banner__meta\">\n <span className=\"spb-banner__badge\">▶ Spotify</span>\n <span className=\"spb-banner__label\">\n {status.playing ? 'Now playing' : 'Last played'}\n </span>\n {progress && (\n <span className=\"spb-banner__time\">\n {formatTime(progress.current)} / {formatTime(progress.duration)}\n </span>\n )}\n </div>\n <p className=\"spb-banner__title\">{status.track}</p>\n <p className=\"spb-banner__artist\">{status.artist}</p>\n\n {upNext?.track && (\n <div className=\"spb-banner__up-next\">\n {upNext.image && (\n <img\n src={upNext.image}\n alt=\"\"\n aria-hidden=\"true\"\n className=\"spb-banner__up-next-image\"\n />\n )}\n <span className=\"spb-banner__up-next-label\">Up next</span>\n <span className=\"spb-banner__up-next-title\">\n {upNext.track}\n {upNext.artist && <span className=\"spb-banner__up-next-artist\"> — {upNext.artist}</span>}\n </span>\n </div>\n )}\n </div>\n\n <img\n src={status.image}\n alt={status.album ? `${status.album} album art` : 'Album art'}\n className=\"spb-banner__art\"\n />\n\n {progress && (\n <div\n className=\"spb-banner__progress\"\n role=\"progressbar\"\n aria-label=\"Track progress\"\n aria-valuemin={0}\n aria-valuemax={progress.duration}\n aria-valuenow={Math.round(progress.current)}\n >\n <div className=\"spb-banner__progress-fill\" style={{ width: `${progress.percent}%` }}>\n <span className=\"spb-banner__progress-dot\" />\n </div>\n </div>\n )}\n </a>\n </section>\n )\n}\n"],"mappings":";AAAA,SAAS,WAAW,gBAAgB;AA+H5B,cAeM,YAfN;AAtHR,SAAS,SAAS,QAAuB;AACvC,SAAO,GAAG,OAAO,KAAK,IAAI,OAAO,YAAY,EAAE;AACjD;AAEA,SAAS,WAAW,IAAY;AAC9B,QAAM,eAAe,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,GAAI,CAAC;AACtD,QAAM,UAAU,KAAK,MAAM,eAAe,EAAE;AAC5C,QAAM,UAAU,eAAe;AAC/B,SAAO,GAAG,OAAO,IAAI,OAAO,OAAO,EAAE,SAAS,GAAG,GAAG,CAAC;AACvD;AAQO,SAAS,cAAc;AAAA,EAC5B,WAAW;AAAA,EACX,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB;AACF,GAAuB;AACrB,QAAM,CAAC,QAAQ,SAAS,IAAI,SAA+B,aAAa;AACxE,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAgC,IAAI;AAChE,QAAM,CAAC,KAAK,MAAM,IAAI,SAAS,MAAM,KAAK,IAAI,CAAC;AAE/C,YAAU,MAAM;AACd,QAAI,kBAAkB,EAAG;AAEzB,QAAI,UAAU;AACd,QAAI,gBAAgB;AAEpB,UAAM,UAAU,YAAY;AAC1B,YAAM,YAAY,EAAE;AACpB,UAAI;AACF,cAAM,WAAW,MAAM,MAAM,UAAU,EAAE,OAAO,WAAW,CAAC;AAC5D,YAAI,CAAC,SAAS,GAAI;AAElB,cAAM,OAAQ,MAA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 type SpotifyCredentials = {
5
+ clientId: string;
6
+ clientSecret: string;
7
+ refreshToken: string;
8
+ };
9
+ /** A status snapshot plus the age of the underlying server-side cache. */
10
+ type SpotifySnapshot = {
11
+ status: SpotifyStatus;
12
+ ageMs: number;
13
+ };
14
+ type SpotifyServiceOptions = Partial<SpotifyCredentials> & {
15
+ /** How long to cache a status snapshot, in milliseconds. Defaults to 5000. */
16
+ cacheMs?: number;
17
+ /** Override the token endpoint (useful for tests). */
18
+ tokenUrl?: string;
19
+ /** Override the Web API base URL (useful for tests). */
20
+ apiBaseUrl?: string;
21
+ };
22
+ /** Minimal Node request shape, so `@types/node` is not required. */
23
+ interface NodeRequestLike {
24
+ method?: string;
25
+ url?: string;
26
+ headers?: Record<string, string | string[] | undefined>;
27
+ }
28
+ /** Minimal Node response shape, so `@types/node` is not required. */
29
+ interface NodeResponseLike {
30
+ statusCode?: number;
31
+ setHeader(name: string, value: string | string[]): unknown;
32
+ end(body?: string): unknown;
33
+ }
34
+ /**
35
+ * Accepts either a Web `Request` (Next.js App Router, Vercel, Edge) or a Node
36
+ * `(req, res)` pair (Next.js Pages Router, plain Node/Vercel functions).
37
+ */
38
+ interface SpotifyHandler {
39
+ (request: Request): Promise<Response>;
40
+ (req: NodeRequestLike, res: NodeResponseLike): Promise<void>;
41
+ }
42
+ type SpotifyHandlerOptions = SpotifyServiceOptions & {
43
+ /** Add permissive CORS headers so a site on another origin can poll. Defaults to true. */
44
+ cors?: boolean;
45
+ };
46
+
47
+ /**
48
+ * Create a read-only Spotify status endpoint that reads credentials from the
49
+ * server environment. The returned function works as either:
50
+ *
51
+ * - a Web handler: `export const GET = createSpotifyHandler()`
52
+ * - a Node handler: `export default createSpotifyHandler()` in `api/spotify.mjs`
53
+ *
54
+ * Responses include the optional `ageMs` field so the banner can keep progress
55
+ * accurate when a snapshot comes from the in-memory cache.
56
+ */
57
+ declare function createSpotifyHandler(options?: SpotifyHandlerOptions): SpotifyHandler;
58
+
59
+ /** An error from Spotify or from the credential configuration. */
60
+ declare class SpotifyError extends Error {
61
+ readonly status?: number;
62
+ constructor(message: string, status?: number);
63
+ }
64
+ /** Drop all in-memory token/status caches. Useful between tests. */
65
+ declare function clearSpotifyCache(): void;
66
+ /** Read the three Spotify credentials from `process.env`. */
67
+ declare function credentialsFromEnv(env?: Record<string, string | undefined>): SpotifyCredentials | null;
68
+ /**
69
+ * Fetch and normalize the current Spotify status. Results are cached in memory
70
+ * for `cacheMs` milliseconds and de-duplicated while a request is in flight.
71
+ */
72
+ declare function fetchSpotifyStatus(options?: SpotifyServiceOptions): Promise<SpotifySnapshot | null>;
73
+ /** Convenience helper returning just the status JSON the banner expects. */
74
+ declare function getSpotifyStatus(options?: SpotifyServiceOptions): Promise<SpotifyStatus | null>;
75
+
76
+ export { SpotifyError, clearSpotifyCache, createSpotifyHandler, credentialsFromEnv, fetchSpotifyStatus, getSpotifyStatus };
77
+ export type { NodeRequestLike, NodeResponseLike, SpotifyCredentials, SpotifyHandler, SpotifyHandlerOptions, SpotifyServiceOptions, SpotifySnapshot };
@@ -0,0 +1,283 @@
1
+ // src/server/spotify.ts
2
+ import axios from "axios";
3
+ var TOKEN_URL = "https://accounts.spotify.com/api/token";
4
+ var API_BASE_URL = "https://api.spotify.com/v1";
5
+ var REQUEST_TIMEOUT = 1e4;
6
+ var SpotifyError = class extends Error {
7
+ status;
8
+ constructor(message, status) {
9
+ super(message);
10
+ this.name = "SpotifyError";
11
+ this.status = status;
12
+ }
13
+ };
14
+ var tokenCache = null;
15
+ var rotatedRefreshToken = null;
16
+ var tokenInFlight = null;
17
+ var statusCache = null;
18
+ var statusInFlight = null;
19
+ function clearSpotifyCache() {
20
+ tokenCache = null;
21
+ rotatedRefreshToken = null;
22
+ tokenInFlight = null;
23
+ statusCache = null;
24
+ statusInFlight = null;
25
+ }
26
+ function readEnv() {
27
+ const globalWithProcess = globalThis;
28
+ return globalWithProcess.process?.env ?? {};
29
+ }
30
+ function credentialsFromEnv(env = readEnv()) {
31
+ const clientId = env.SPOTIFY_CLIENT_ID;
32
+ const clientSecret = env.SPOTIFY_CLIENT_SECRET;
33
+ const refreshToken = env.SPOTIFY_REFRESH_TOKEN;
34
+ if (!clientId || !clientSecret || !refreshToken) return null;
35
+ return { clientId, clientSecret, refreshToken };
36
+ }
37
+ function resolveCredentials(options) {
38
+ const fromEnv = credentialsFromEnv();
39
+ const credentials = {
40
+ clientId: options.clientId ?? fromEnv?.clientId ?? "",
41
+ clientSecret: options.clientSecret ?? fromEnv?.clientSecret ?? "",
42
+ refreshToken: options.refreshToken ?? fromEnv?.refreshToken ?? rotatedRefreshToken ?? ""
43
+ };
44
+ if (!credentials.clientId || !credentials.clientSecret || !credentials.refreshToken) {
45
+ throw new SpotifyError(
46
+ "Missing Spotify credentials. Set SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET and SPOTIFY_REFRESH_TOKEN on the server, or pass them to createSpotifyHandler()."
47
+ );
48
+ }
49
+ return credentials;
50
+ }
51
+ function base64(input) {
52
+ if (typeof btoa === "function") return btoa(input);
53
+ const globalWithBuffer = globalThis;
54
+ return globalWithBuffer.Buffer?.from(input, "utf8").toString("base64") ?? "";
55
+ }
56
+ function describeError(error, fallback) {
57
+ if (error instanceof SpotifyError) return error;
58
+ if (axios.isAxiosError(error)) {
59
+ const status = error.response?.status;
60
+ const detail = error.response?.data?.error?.message;
61
+ const message = status === 401 || status === 403 ? "Spotify rejected the credentials or refresh token" : detail ?? error.message;
62
+ return new SpotifyError(`${fallback}: ${message}`, status);
63
+ }
64
+ return new SpotifyError(
65
+ `${fallback}: ${error instanceof Error ? error.message : "unknown error"}`
66
+ );
67
+ }
68
+ async function getAccessToken(credentials, tokenUrl) {
69
+ const now = Date.now();
70
+ if (tokenCache && tokenCache.expiresAt > now + 6e4) return tokenCache.value;
71
+ if (tokenInFlight) return tokenInFlight;
72
+ tokenInFlight = (async () => {
73
+ try {
74
+ const body = new URLSearchParams({
75
+ grant_type: "refresh_token",
76
+ refresh_token: credentials.refreshToken
77
+ });
78
+ const { data } = await axios.post(tokenUrl, body.toString(), {
79
+ headers: {
80
+ Authorization: `Basic ${base64(`${credentials.clientId}:${credentials.clientSecret}`)}`,
81
+ "Content-Type": "application/x-www-form-urlencoded"
82
+ },
83
+ timeout: REQUEST_TIMEOUT
84
+ });
85
+ if (!data.access_token) {
86
+ throw new SpotifyError("Spotify token response did not contain an access token");
87
+ }
88
+ tokenCache = {
89
+ value: data.access_token,
90
+ expiresAt: Date.now() + (data.expires_in ?? 3600) * 1e3
91
+ };
92
+ if (data.refresh_token) rotatedRefreshToken = data.refresh_token;
93
+ return tokenCache.value;
94
+ } catch (error) {
95
+ throw describeError(error, "Could not refresh the Spotify access token");
96
+ } finally {
97
+ tokenInFlight = null;
98
+ }
99
+ })();
100
+ return tokenInFlight;
101
+ }
102
+ function artistOf(track) {
103
+ return (track.artists ?? []).map((artist) => artist.name).filter(Boolean).join(", ");
104
+ }
105
+ function imageOf(track) {
106
+ const images = track.album?.images ?? track.show?.images ?? track.images ?? [];
107
+ const largest = [...images].sort((a, b) => (b.width ?? 0) - (a.width ?? 0))[0];
108
+ return largest?.url ?? "";
109
+ }
110
+ function albumOf(track) {
111
+ return track.album?.name ?? track.show?.name ?? "";
112
+ }
113
+ function urlOf(track) {
114
+ return track.external_urls?.spotify ?? "";
115
+ }
116
+ function toStatus(track, playing, playedAt, progressMs = null) {
117
+ return {
118
+ playing,
119
+ track: track.name,
120
+ artist: artistOf(track),
121
+ album: albumOf(track),
122
+ image: imageOf(track),
123
+ url: urlOf(track),
124
+ playedAt,
125
+ progressMs,
126
+ durationMs: typeof track.duration_ms === "number" ? track.duration_ms : null,
127
+ next: null
128
+ };
129
+ }
130
+ function toQueueItem(track) {
131
+ if (!track?.name) return null;
132
+ return {
133
+ track: track.name,
134
+ artist: artistOf(track),
135
+ album: albumOf(track) || void 0,
136
+ image: imageOf(track),
137
+ url: urlOf(track)
138
+ };
139
+ }
140
+ async function getCurrentlyPlaying(api) {
141
+ const response = await api.get("/me/player/currently-playing", {
142
+ params: { additional_types: "track,episode" },
143
+ validateStatus: (status) => status === 200 || status === 204
144
+ });
145
+ return response.status === 200 ? response.data : null;
146
+ }
147
+ async function getNextTrack(api) {
148
+ try {
149
+ const { data } = await api.get("/me/player/queue");
150
+ return toQueueItem(data.items?.[0]);
151
+ } catch {
152
+ return null;
153
+ }
154
+ }
155
+ async function getLastPlayed(api) {
156
+ try {
157
+ const { data } = await api.get("/me/player/recently-played", {
158
+ params: { limit: 1 }
159
+ });
160
+ const entry = data.items?.[0];
161
+ if (!entry?.track) return null;
162
+ return toStatus(entry.track, false, entry.played_at ?? null);
163
+ } catch {
164
+ return null;
165
+ }
166
+ }
167
+ async function fetchSpotifyStatus(options = {}) {
168
+ const cacheMs = Math.max(0, options.cacheMs ?? 5e3);
169
+ const ageMs = statusCache ? Date.now() - statusCache.fetchedAt : 0;
170
+ if (statusCache && ageMs < cacheMs) {
171
+ return { status: statusCache.snapshot.status, ageMs };
172
+ }
173
+ if (statusInFlight) return statusInFlight;
174
+ statusInFlight = (async () => {
175
+ try {
176
+ const credentials = resolveCredentials(options);
177
+ const token = await getAccessToken(credentials, options.tokenUrl ?? TOKEN_URL);
178
+ const api = axios.create({
179
+ baseURL: options.apiBaseUrl ?? API_BASE_URL,
180
+ timeout: REQUEST_TIMEOUT,
181
+ headers: { Authorization: `Bearer ${token}` }
182
+ });
183
+ let status = null;
184
+ let error = null;
185
+ try {
186
+ const current = await getCurrentlyPlaying(api);
187
+ if (current?.item) {
188
+ status = toStatus(
189
+ current.item,
190
+ current.is_playing === true,
191
+ typeof current.timestamp === "number" ? new Date(current.timestamp).toISOString() : null,
192
+ typeof current.progress_ms === "number" ? current.progress_ms : null
193
+ );
194
+ if (status.playing) status.next = await getNextTrack(api);
195
+ } else {
196
+ status = await getLastPlayed(api);
197
+ }
198
+ } catch (caught) {
199
+ error = caught;
200
+ }
201
+ if (error) throw describeError(error, "Could not read Spotify playback status");
202
+ if (status) {
203
+ statusCache = { snapshot: { status, ageMs: 0 }, fetchedAt: Date.now() };
204
+ return { status, ageMs: 0 };
205
+ }
206
+ statusCache = null;
207
+ return null;
208
+ } finally {
209
+ statusInFlight = null;
210
+ }
211
+ })();
212
+ return statusInFlight;
213
+ }
214
+ async function getSpotifyStatus(options = {}) {
215
+ const snapshot = await fetchSpotifyStatus(options);
216
+ return snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null;
217
+ }
218
+
219
+ // src/server/handler.ts
220
+ function responseHeaders(cors) {
221
+ return {
222
+ "Content-Type": "application/json; charset=utf-8",
223
+ "Cache-Control": "no-store",
224
+ ...cors ? {
225
+ "Access-Control-Allow-Origin": "*",
226
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
227
+ "Access-Control-Allow-Headers": "Content-Type"
228
+ } : {}
229
+ };
230
+ }
231
+ function sendNode(res, statusCode, body, cors) {
232
+ res.statusCode = statusCode;
233
+ for (const [name, value] of Object.entries(responseHeaders(cors))) {
234
+ res.setHeader(name, value);
235
+ }
236
+ res.end(body === void 0 ? void 0 : JSON.stringify(body));
237
+ }
238
+ function createSpotifyHandler(options = {}) {
239
+ const cors = options.cors !== false;
240
+ return (async (requestOrReq, res) => {
241
+ const isNodeStyle = res != null;
242
+ const method = isNodeStyle ? requestOrReq.method ?? "GET" : requestOrReq.method;
243
+ if (method === "OPTIONS") {
244
+ if (isNodeStyle) return sendNode(res, 204, void 0, cors);
245
+ return new Response(null, { status: 204, headers: responseHeaders(cors) });
246
+ }
247
+ if (method !== "GET" && method != null) {
248
+ const body = { error: "Method not allowed" };
249
+ if (isNodeStyle) return sendNode(res, 405, body, cors);
250
+ return new Response(JSON.stringify(body), {
251
+ status: 405,
252
+ headers: responseHeaders(cors)
253
+ });
254
+ }
255
+ try {
256
+ const snapshot = await fetchSpotifyStatus(options);
257
+ const body = snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null;
258
+ if (isNodeStyle) return sendNode(res, 200, body, cors);
259
+ return new Response(JSON.stringify(body), {
260
+ status: 200,
261
+ headers: responseHeaders(cors)
262
+ });
263
+ } catch (error) {
264
+ const message = error instanceof SpotifyError ? error.message : "Unable to fetch Spotify status";
265
+ const statusCode = error instanceof SpotifyError && error.status === 401 ? 502 : 500;
266
+ const body = { error: message };
267
+ if (isNodeStyle) return sendNode(res, statusCode, body, cors);
268
+ return new Response(JSON.stringify(body), {
269
+ status: statusCode,
270
+ headers: responseHeaders(cors)
271
+ });
272
+ }
273
+ });
274
+ }
275
+ export {
276
+ SpotifyError,
277
+ clearSpotifyCache,
278
+ createSpotifyHandler,
279
+ credentialsFromEnv,
280
+ fetchSpotifyStatus,
281
+ getSpotifyStatus
282
+ };
283
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/server/spotify.ts","../../src/server/handler.ts"],"sourcesContent":["import axios from 'axios'\nimport type { SpotifyQueueItem, SpotifyStatus } from '../types'\nimport type {\n SpotifyCredentials,\n SpotifyServiceOptions,\n SpotifySnapshot\n} from './types'\n\nconst TOKEN_URL = 'https://accounts.spotify.com/api/token'\nconst API_BASE_URL = 'https://api.spotify.com/v1'\nconst REQUEST_TIMEOUT = 10_000\n\ntype SpotifyImage = { url: string; width?: number; height?: number }\n\ntype SpotifyTrack = {\n name: string\n type?: string\n duration_ms?: number\n external_urls?: { spotify?: string }\n artists?: Array<{ name: string }>\n album?: { name?: string; images?: SpotifyImage[] }\n show?: { name?: string; images?: SpotifyImage[] }\n images?: SpotifyImage[]\n}\n\ntype TokenResponse = { access_token: string; expires_in?: number; refresh_token?: string }\ntype CurrentlyPlayingResponse = {\n is_playing?: boolean\n progress_ms?: number | null\n timestamp?: number\n item?: SpotifyTrack | null\n}\ntype QueueResponse = { items?: SpotifyTrack[] }\ntype RecentlyPlayedResponse = {\n items?: Array<{ played_at?: string; track?: SpotifyTrack }>\n}\ntype ErrorResponse = { error?: { message?: string } }\n\n/** An error from Spotify or from the credential configuration. */\nexport class SpotifyError extends Error {\n readonly status?: number\n\n constructor(message: string, status?: number) {\n super(message)\n this.name = 'SpotifyError'\n this.status = status\n }\n}\n\nlet tokenCache: { value: string; expiresAt: number } | null = null\nlet rotatedRefreshToken: string | null = null\nlet tokenInFlight: Promise<string> | null = null\n\nlet statusCache: { snapshot: SpotifySnapshot; fetchedAt: number } | null = null\nlet statusInFlight: Promise<SpotifySnapshot | null> | null = null\n\n/** Drop all in-memory token/status caches. Useful between tests. */\nexport function clearSpotifyCache(): void {\n tokenCache = null\n rotatedRefreshToken = null\n tokenInFlight = null\n statusCache = null\n statusInFlight = null\n}\n\nfunction readEnv(): Record<string, string | undefined> {\n const globalWithProcess = globalThis as {\n process?: { env?: Record<string, string | undefined> }\n }\n return globalWithProcess.process?.env ?? {}\n}\n\n/** Read the three Spotify credentials from `process.env`. */\nexport function credentialsFromEnv(\n env: Record<string, string | undefined> = readEnv()\n): SpotifyCredentials | null {\n const clientId = env.SPOTIFY_CLIENT_ID\n const clientSecret = env.SPOTIFY_CLIENT_SECRET\n const refreshToken = env.SPOTIFY_REFRESH_TOKEN\n\n if (!clientId || !clientSecret || !refreshToken) return null\n return { clientId, clientSecret, refreshToken }\n}\n\nfunction resolveCredentials(options: SpotifyServiceOptions): SpotifyCredentials {\n const fromEnv = credentialsFromEnv()\n const credentials: SpotifyCredentials = {\n clientId: options.clientId ?? fromEnv?.clientId ?? '',\n clientSecret: options.clientSecret ?? fromEnv?.clientSecret ?? '',\n refreshToken: options.refreshToken ?? fromEnv?.refreshToken ?? rotatedRefreshToken ?? ''\n }\n\n if (!credentials.clientId || !credentials.clientSecret || !credentials.refreshToken) {\n throw new SpotifyError(\n 'Missing Spotify credentials. Set SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET and SPOTIFY_REFRESH_TOKEN on the server, or pass them to createSpotifyHandler().'\n )\n }\n return credentials\n}\n\nfunction base64(input: string): string {\n if (typeof btoa === 'function') return btoa(input)\n const globalWithBuffer = globalThis as {\n Buffer?: { from(value: string, encoding: string): { toString(encoding: string): string } }\n }\n return globalWithBuffer.Buffer?.from(input, 'utf8').toString('base64') ?? ''\n}\n\nfunction describeError(error: unknown, fallback: string): SpotifyError {\n if (error instanceof SpotifyError) return error\n if (axios.isAxiosError(error)) {\n const status = error.response?.status\n const detail = (error.response?.data as ErrorResponse | undefined)?.error?.message\n const message = status === 401 || status === 403\n ? 'Spotify rejected the credentials or refresh token'\n : (detail ?? error.message)\n return new SpotifyError(`${fallback}: ${message}`, status)\n }\n return new SpotifyError(\n `${fallback}: ${error instanceof Error ? error.message : 'unknown error'}`\n )\n}\n\nasync function getAccessToken(\n credentials: SpotifyCredentials,\n tokenUrl: string\n): Promise<string> {\n const now = Date.now()\n if (tokenCache && tokenCache.expiresAt > now + 60_000) return tokenCache.value\n if (tokenInFlight) return tokenInFlight\n\n tokenInFlight = (async () => {\n try {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: credentials.refreshToken\n })\n\n const { data } = await axios.post<TokenResponse>(tokenUrl, body.toString(), {\n headers: {\n Authorization: `Basic ${base64(`${credentials.clientId}:${credentials.clientSecret}`)}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n timeout: REQUEST_TIMEOUT\n })\n\n if (!data.access_token) {\n throw new SpotifyError('Spotify token response did not contain an access token')\n }\n\n tokenCache = {\n value: data.access_token,\n expiresAt: Date.now() + (data.expires_in ?? 3600) * 1000\n }\n if (data.refresh_token) rotatedRefreshToken = data.refresh_token\n return tokenCache.value\n } catch (error) {\n throw describeError(error, 'Could not refresh the Spotify access token')\n } finally {\n tokenInFlight = null\n }\n })()\n\n return tokenInFlight\n}\n\nfunction artistOf(track: SpotifyTrack): string {\n return (track.artists ?? []).map((artist) => artist.name).filter(Boolean).join(', ')\n}\n\nfunction imageOf(track: SpotifyTrack): string {\n const images = track.album?.images ?? track.show?.images ?? track.images ?? []\n const largest = [...images].sort((a, b) => (b.width ?? 0) - (a.width ?? 0))[0]\n return largest?.url ?? ''\n}\n\nfunction albumOf(track: SpotifyTrack): string {\n return track.album?.name ?? track.show?.name ?? ''\n}\n\nfunction urlOf(track: SpotifyTrack): string {\n return track.external_urls?.spotify ?? ''\n}\n\nfunction toStatus(\n track: SpotifyTrack,\n playing: boolean,\n playedAt: string | null,\n progressMs: number | null = null\n): SpotifyStatus {\n return {\n playing,\n track: track.name,\n artist: artistOf(track),\n album: albumOf(track),\n image: imageOf(track),\n url: urlOf(track),\n playedAt,\n progressMs,\n durationMs: typeof track.duration_ms === 'number' ? track.duration_ms : null,\n next: null\n }\n}\n\nfunction toQueueItem(track: SpotifyTrack | undefined): SpotifyQueueItem | null {\n if (!track?.name) return null\n return {\n track: track.name,\n artist: artistOf(track),\n album: albumOf(track) || undefined,\n image: imageOf(track),\n url: urlOf(track)\n }\n}\n\nasync function getCurrentlyPlaying(\n api: ReturnType<typeof axios.create>\n): Promise<CurrentlyPlayingResponse | null> {\n const response = await api.get<CurrentlyPlayingResponse>('/me/player/currently-playing', {\n params: { additional_types: 'track,episode' },\n validateStatus: (status) => status === 200 || status === 204\n })\n return response.status === 200 ? response.data : null\n}\n\nasync function getNextTrack(\n api: ReturnType<typeof axios.create>\n): Promise<SpotifyQueueItem | null> {\n try {\n const { data } = await api.get<QueueResponse>('/me/player/queue')\n return toQueueItem(data.items?.[0])\n } catch {\n // The queue is optional; a banner without \"up next\" is still useful.\n return null\n }\n}\n\nasync function getLastPlayed(\n api: ReturnType<typeof axios.create>\n): Promise<SpotifyStatus | null> {\n try {\n const { data } = await api.get<RecentlyPlayedResponse>('/me/player/recently-played', {\n params: { limit: 1 }\n })\n const entry = data.items?.[0]\n if (!entry?.track) return null\n return toStatus(entry.track, false, entry.played_at ?? null)\n } catch {\n return null\n }\n}\n\n/**\n * Fetch and normalize the current Spotify status. Results are cached in memory\n * for `cacheMs` milliseconds and de-duplicated while a request is in flight.\n */\nexport async function fetchSpotifyStatus(\n options: SpotifyServiceOptions = {}\n): Promise<SpotifySnapshot | null> {\n const cacheMs = Math.max(0, options.cacheMs ?? 5000)\n const ageMs = statusCache ? Date.now() - statusCache.fetchedAt : 0\n if (statusCache && ageMs < cacheMs) {\n return { status: statusCache.snapshot.status, ageMs }\n }\n if (statusInFlight) return statusInFlight\n\n statusInFlight = (async () => {\n try {\n const credentials = resolveCredentials(options)\n const token = await getAccessToken(credentials, options.tokenUrl ?? TOKEN_URL)\n const api = axios.create({\n baseURL: options.apiBaseUrl ?? API_BASE_URL,\n timeout: REQUEST_TIMEOUT,\n headers: { Authorization: `Bearer ${token}` }\n })\n\n let status: SpotifyStatus | null = null\n let error: unknown = null\n try {\n const current = await getCurrentlyPlaying(api)\n if (current?.item) {\n status = toStatus(\n current.item,\n current.is_playing === true,\n typeof current.timestamp === 'number'\n ? new Date(current.timestamp).toISOString()\n : null,\n typeof current.progress_ms === 'number' ? current.progress_ms : null\n )\n if (status.playing) status.next = await getNextTrack(api)\n } else {\n status = await getLastPlayed(api)\n }\n } catch (caught) {\n error = caught\n }\n\n if (error) throw describeError(error, 'Could not read Spotify playback status')\n\n if (status) {\n statusCache = { snapshot: { status, ageMs: 0 }, fetchedAt: Date.now() }\n return { status, ageMs: 0 }\n }\n statusCache = null\n return null\n } finally {\n statusInFlight = null\n }\n })()\n\n return statusInFlight\n}\n\n/** Convenience helper returning just the status JSON the banner expects. */\nexport async function getSpotifyStatus(\n options: SpotifyServiceOptions = {}\n): Promise<SpotifyStatus | null> {\n const snapshot = await fetchSpotifyStatus(options)\n return snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null\n}\n","import { fetchSpotifyStatus, SpotifyError } from './spotify'\nimport type {\n NodeRequestLike,\n NodeResponseLike,\n SpotifyHandler,\n SpotifyHandlerOptions\n} from './types'\n\nfunction responseHeaders(cors: boolean): Record<string, string> {\n return {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n ...(cors\n ? {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type'\n }\n : {})\n }\n}\n\nfunction sendNode(\n res: NodeResponseLike,\n statusCode: number,\n body: unknown,\n cors: boolean\n): void {\n res.statusCode = statusCode\n for (const [name, value] of Object.entries(responseHeaders(cors))) {\n res.setHeader(name, value)\n }\n res.end(body === undefined ? undefined : JSON.stringify(body))\n}\n\n/**\n * Create a read-only Spotify status endpoint that reads credentials from the\n * server environment. The returned function works as either:\n *\n * - a Web handler: `export const GET = createSpotifyHandler()`\n * - a Node handler: `export default createSpotifyHandler()` in `api/spotify.mjs`\n *\n * Responses include the optional `ageMs` field so the banner can keep progress\n * accurate when a snapshot comes from the in-memory cache.\n */\nexport function createSpotifyHandler(options: SpotifyHandlerOptions = {}): SpotifyHandler {\n const cors = options.cors !== false\n\n return (async (\n requestOrReq: Request | NodeRequestLike,\n res?: NodeResponseLike\n ): Promise<Response | void> => {\n const isNodeStyle = res != null\n const method = isNodeStyle\n ? (requestOrReq as NodeRequestLike).method ?? 'GET'\n : (requestOrReq as Request).method\n\n if (method === 'OPTIONS') {\n if (isNodeStyle) return sendNode(res!, 204, undefined, cors)\n return new Response(null, { status: 204, headers: responseHeaders(cors) })\n }\n\n if (method !== 'GET' && method != null) {\n const body = { error: 'Method not allowed' }\n if (isNodeStyle) return sendNode(res!, 405, body, cors)\n return new Response(JSON.stringify(body), {\n status: 405,\n headers: responseHeaders(cors)\n })\n }\n\n try {\n const snapshot = await fetchSpotifyStatus(options)\n const body = snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null\n if (isNodeStyle) return sendNode(res!, 200, body, cors)\n return new Response(JSON.stringify(body), {\n status: 200,\n headers: responseHeaders(cors)\n })\n } catch (error) {\n const message = error instanceof SpotifyError\n ? error.message\n : 'Unable to fetch Spotify status'\n const statusCode = error instanceof SpotifyError && error.status === 401 ? 502 : 500\n const body = { error: message }\n if (isNodeStyle) return sendNode(res!, statusCode, body, cors)\n return new Response(JSON.stringify(body), {\n status: statusCode,\n headers: responseHeaders(cors)\n })\n }\n }) as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,YAAa,QAAO,SAAS,KAAM,YAAY,MAAM,IAAI;AAC7D,aAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,QACxC,QAAQ;AAAA,QACR,SAAS,gBAAgB,IAAI;AAAA,MAC/B,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,38 @@
1
+ /** A track (or podcast episode) in the playback queue. */
2
+ type SpotifyQueueItem = {
3
+ track: string;
4
+ artist: string;
5
+ album?: string;
6
+ image: string;
7
+ url: string;
8
+ };
9
+ /** The response returned by the Spotify status endpoint this component polls. */
10
+ type SpotifyStatus = {
11
+ playing: boolean;
12
+ track: string;
13
+ artist: string;
14
+ album: string;
15
+ image: string;
16
+ url: string;
17
+ playedAt: string | null;
18
+ progressMs?: number | null;
19
+ durationMs?: number | null;
20
+ next?: SpotifyQueueItem | null;
21
+ /** Age of the server-side snapshot in milliseconds. */
22
+ ageMs?: number;
23
+ };
24
+ type SpotifyBannerProps = {
25
+ /**
26
+ * URL of the status endpoint. Defaults to `/api/spotify`, which is served by
27
+ * the bundled `createSpotifyHandler()`. You normally don't need to set this.
28
+ */
29
+ endpoint?: string;
30
+ /** Data to render before the first poll succeeds. */
31
+ initialStatus?: SpotifyStatus | null;
32
+ /** Polling interval in milliseconds. Set to 0 to disable polling. Defaults to 3000. */
33
+ pollIntervalMs?: number;
34
+ /** Extra class names applied to the root element. */
35
+ className?: string;
36
+ };
37
+
38
+ export type { SpotifyBannerProps as S, SpotifyQueueItem as a, SpotifyStatus as b };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spotify-now-playing-banner",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "A reusable React banner that shows a Spotify now-playing or last-played track, with live progress and up-next.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,6 +20,11 @@
20
20
  "import": "./dist/index.js",
21
21
  "default": "./dist/index.js"
22
22
  },
23
+ "./server": {
24
+ "types": "./dist/server/index.d.ts",
25
+ "import": "./dist/server/index.js",
26
+ "default": "./dist/server/index.js"
27
+ },
23
28
  "./styles.css": "./dist/styles.css",
24
29
  "./package.json": "./package.json"
25
30
  },
@@ -43,5 +48,8 @@
43
48
  "@types/react": "^19.3.3",
44
49
  "tsup": "^9.0.0",
45
50
  "typescript": "^6.0.3"
51
+ },
52
+ "dependencies": {
53
+ "axios": "^1.21.1"
46
54
  }
47
55
  }