spotify-now-playing-banner 0.1.1 → 0.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/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 — plus a bundled server endpoint that reads Spotify for you.
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.
4
4
 
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`.
5
+ Credentials are passed explicitly by you. **The package never reads environment variables.** You can pass them as component props (direct browser calls, with the security caveat below) or to the bundled server handler (recommended).
6
6
 
7
7
  ## Install
8
8
 
@@ -10,69 +10,90 @@ No Spotify credentials are shipped to the browser. The server helper included in
10
10
  npm install spotify-now-playing-banner
11
11
  ```
12
12
 
13
- React 18 or newer is required as a peer dependency. `axios` is installed automatically for the server helper.
13
+ React 18 or newer is required as a peer dependency. `axios` is installed automatically for the Spotify client.
14
14
 
15
- ## Usage
16
-
17
- Mount the bundled handler at `/api/spotify`, then render the banner with no props:
15
+ ## Usage with credentials as props
18
16
 
19
17
  ```tsx
20
18
  import { SpotifyBanner } from 'spotify-now-playing-banner'
21
19
  import 'spotify-now-playing-banner/styles.css'
22
20
 
23
21
  export function NowPlaying() {
24
- return <SpotifyBanner />
22
+ return (
23
+ <SpotifyBanner
24
+ credentials={{
25
+ clientId: 'your-client-id',
26
+ clientSecret: 'your-client-secret',
27
+ refreshToken: 'your-refresh-token'
28
+ }}
29
+ />
30
+ )
25
31
  }
26
32
  ```
27
33
 
28
- ### 1. Set the credentials on the server
34
+ Shorthand props are also supported:
29
35
 
30
- ```sh
31
- SPOTIFY_CLIENT_ID=...
32
- SPOTIFY_CLIENT_SECRET=...
33
- SPOTIFY_REFRESH_TOKEN=...
36
+ ```tsx
37
+ <SpotifyBanner
38
+ clientId="your-client-id"
39
+ clientSecret="your-client-secret"
40
+ refreshToken="your-refresh-token"
41
+ />
34
42
  ```
35
43
 
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.
44
+ When credentials are present, the component calls `api.spotify.com` directly with axios and no `endpoint` is needed.
37
45
 
38
- ### 2. Expose the endpoint
46
+ > **Security warning:** props are part of the client bundle. Anyone can read your `clientSecret` and `refreshToken`. Use this only for personal/local tools where exposure is acceptable. For public sites, use the server handler below.
39
47
 
40
- **Next.js App Router** (`app/api/spotify/route.ts`):
48
+ ## Usage with the bundled server handler (recommended)
49
+
50
+ Your app reads its own environment (the package does not), passes the credentials to the handler, and the component needs no props:
41
51
 
42
52
  ```ts
53
+ // app/api/spotify/route.ts
43
54
  import { createSpotifyHandler } from 'spotify-now-playing-banner/server'
44
55
 
45
- export const GET = createSpotifyHandler()
46
- export const OPTIONS = GET
47
- ```
56
+ const handler = createSpotifyHandler({
57
+ clientId: process.env.SPOTIFY_CLIENT_ID!,
58
+ clientSecret: process.env.SPOTIFY_CLIENT_SECRET!,
59
+ refreshToken: process.env.SPOTIFY_REFRESH_TOKEN!
60
+ })
48
61
 
49
- **Next.js Pages Router / Vercel Node function** (`api/spotify.mjs`):
62
+ export const GET = handler
63
+ export const OPTIONS = handler
64
+ ```
50
65
 
51
- ```js
66
+ ```ts
67
+ // api/spotify.mjs — Next.js Pages Router / Vercel Node function
52
68
  import { createSpotifyHandler } from 'spotify-now-playing-banner/server'
53
69
 
54
- export default createSpotifyHandler()
70
+ export default createSpotifyHandler({
71
+ clientId: process.env.SPOTIFY_CLIENT_ID,
72
+ clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
73
+ refreshToken: process.env.SPOTIFY_REFRESH_TOKEN
74
+ })
55
75
  ```
56
76
 
57
- **Plain Node 18+ server:**
77
+ ```tsx
78
+ <SpotifyBanner />
79
+ ```
58
80
 
59
- ```js
60
- import { createServer } from 'node:http'
61
- import { createSpotifyHandler } from 'spotify-now-playing-banner/server'
81
+ 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 another origin can poll it.
62
82
 
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
- ```
83
+ ## Props
72
84
 
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.
85
+ | Prop | Type | Default | Description |
86
+ | --- | --- | --- | --- |
87
+ | `credentials` | `{ clientId, clientSecret, refreshToken }` | – | Call Spotify directly from the browser. **Publicly visible.** |
88
+ | `clientId` | `string` | – | Shorthand for `credentials.clientId`. |
89
+ | `clientSecret` | `string` | – | Shorthand for `credentials.clientSecret`. |
90
+ | `refreshToken` | `string` | – | Shorthand for `credentials.refreshToken`. |
91
+ | `endpoint` | `string` | `/api/spotify` | Status URL used when no credentials are passed. Not needed with the bundled handler. May be a full cross-origin URL. |
92
+ | `initialStatus` | `SpotifyStatus \| null` | `null` | Status to render before the first successful poll. The component renders nothing until it has data. |
93
+ | `pollIntervalMs` | `number` | `3000` | Polling interval. Set to `0` to disable polling and render only `initialStatus`. |
94
+ | `className` | `string` | – | Extra class names on the root `<section>`. |
74
95
 
75
- ### Optional props
96
+ 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.
76
97
 
77
98
  ```tsx
78
99
  import lastPlayed from './data/last-played.json'
@@ -90,41 +111,32 @@ export function NowPlaying() {
90
111
  }
91
112
  ```
92
113
 
93
- | Prop | Type | Default | Description |
94
- | --- | --- | --- | --- |
95
- | `endpoint` | `string` | `/api/spotify` | Override the status URL. Not needed when using the bundled handler. May be a full cross-origin URL. |
96
- | `initialStatus` | `SpotifyStatus \| null` | `null` | Status to render before the first successful poll. The component renders nothing until it has data. |
97
- | `pollIntervalMs` | `number` | `3000` | Polling interval. Set to `0` to disable polling and render only `initialStatus`. |
98
- | `className` | `string` | – | Extra class names on the root `<section>`. |
99
-
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.
114
+ ## Spotify API (browser-safe helpers)
101
115
 
102
- ## Server API
103
-
104
- Everything is exported from `spotify-now-playing-banner/server`:
116
+ Everything is exported from the main entry, and also from `spotify-now-playing-banner/server`:
105
117
 
106
118
  | Export | Description |
107
119
  | --- | --- |
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). |
120
+ | `createSpotifyApi(credentials, options?)` | Credential-bound client with its own token/status caches. |
121
+ | `getSpotifyStatus(credentials, options?)` | One-off status fetch (call `api.getStatus()` to reuse a cache). |
122
+ | `fetchSpotifyStatus(credentials, options?)` | One-off fetch including `ageMs`. |
123
+ | `createSpotifyHandler(options)` | Server endpoint factory; options include the three credentials. |
113
124
  | `SpotifyError` | Error type with an optional HTTP `status`. |
114
125
 
115
- Options let you override credentials explicitly, change the cache duration, or point at custom HTTP endpoints for tests:
126
+ Each `SpotifyApi` instance keeps its own caches, so different credentials never share state.
116
127
 
117
128
  ```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
- })
129
+ import { createSpotifyApi } from 'spotify-now-playing-banner'
130
+
131
+ const api = createSpotifyApi(
132
+ { clientId: 'id', clientSecret: 'secret', refreshToken: 'token' },
133
+ { cacheMs: 10_000 }
134
+ )
135
+ const status = await api.getStatus()
136
+ api.clearCache()
125
137
  ```
126
138
 
127
- Credentials are resolved in this order: explicit option → environment variable.
139
+ Options: `cacheMs` (default 5000), `tokenUrl` and `apiBaseUrl` (overrides, useful for tests). The handler additionally accepts `cors: false` to disable CORS headers.
128
140
 
129
141
  ```tsx
130
142
  // Server component: render a snapshot immediately.
@@ -132,14 +144,18 @@ import { getSpotifyStatus } from 'spotify-now-playing-banner/server'
132
144
  import { SpotifyBanner } from 'spotify-now-playing-banner'
133
145
 
134
146
  export default async function Page() {
135
- const status = await getSpotifyStatus()
147
+ const status = await getSpotifyStatus({
148
+ clientId: process.env.SPOTIFY_CLIENT_ID!,
149
+ clientSecret: process.env.SPOTIFY_CLIENT_SECRET!,
150
+ refreshToken: process.env.SPOTIFY_REFRESH_TOKEN!
151
+ })
136
152
  return <SpotifyBanner initialStatus={status} />
137
153
  }
138
154
  ```
139
155
 
140
156
  ## API contract
141
157
 
142
- The endpoint responds to `GET` with one of these JSON shapes:
158
+ The status JSON (returned by the handler, `api.getStatus()`, or your own endpoint) looks like:
143
159
 
144
160
  ```json
145
161
  {
@@ -169,9 +185,9 @@ Fields:
169
185
  - `playedAt` — ISO timestamp, or `null`.
170
186
  - `progressMs` / `durationMs` — optional; progress is hidden when absent.
171
187
  - `next` — optional queued item; only displayed while `playing` is `true`.
172
- - `ageMs` — optional age of a server-cached snapshot in ms, used to keep progress accurate.
188
+ - `ageMs` — optional age of a cached snapshot in ms, used to keep progress accurate.
173
189
 
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.
190
+ The handler returns `null` when nothing is available; the component keeps its last known data. Errors return `{ error }` with a 500/502 status.
175
191
 
176
192
  ## Styling
177
193
 
@@ -197,5 +213,3 @@ npm pack --dry-run
197
213
  ```
198
214
 
199
215
  `npm pack --dry-run` prints the exact files that would be published (`dist/`, this README, and the license). Credentials and local data files are not included.
200
-
201
- Maintainers publish with `npm login` followed by `npm publish`; use `npm version patch|minor|major` before each release.
@@ -0,0 +1,234 @@
1
+ // src/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
+ function assertCredentials(credentials) {
15
+ if (!credentials?.clientId || !credentials.clientSecret || !credentials.refreshToken) {
16
+ throw new SpotifyError(
17
+ "Spotify credentials are missing. Pass clientId, clientSecret and refreshToken to createSpotifyApi() or to <SpotifyBanner credentials={...}>."
18
+ );
19
+ }
20
+ return credentials;
21
+ }
22
+ function base64(input) {
23
+ if (typeof btoa === "function") return btoa(input);
24
+ const globalWithBuffer = globalThis;
25
+ return globalWithBuffer.Buffer?.from(input, "utf8").toString("base64") ?? "";
26
+ }
27
+ function describeError(error, fallback) {
28
+ if (error instanceof SpotifyError) return error;
29
+ if (axios.isAxiosError(error)) {
30
+ const status = error.response?.status;
31
+ const detail = error.response?.data?.error?.message;
32
+ const message = status === 401 || status === 403 ? "Spotify rejected the credentials or refresh token" : detail ?? error.message;
33
+ return new SpotifyError(`${fallback}: ${message}`, status);
34
+ }
35
+ return new SpotifyError(
36
+ `${fallback}: ${error instanceof Error ? error.message : "unknown error"}`
37
+ );
38
+ }
39
+ function artistOf(track) {
40
+ return (track.artists ?? []).map((artist) => artist.name).filter(Boolean).join(", ");
41
+ }
42
+ function imageOf(track) {
43
+ const images = track.album?.images ?? track.show?.images ?? track.images ?? [];
44
+ const largest = [...images].sort((a, b) => (b.width ?? 0) - (a.width ?? 0))[0];
45
+ return largest?.url ?? "";
46
+ }
47
+ function albumOf(track) {
48
+ return track.album?.name ?? track.show?.name ?? "";
49
+ }
50
+ function urlOf(track) {
51
+ return track.external_urls?.spotify ?? "";
52
+ }
53
+ function toStatus(track, playing, playedAt, progressMs = null) {
54
+ return {
55
+ playing,
56
+ track: track.name,
57
+ artist: artistOf(track),
58
+ album: albumOf(track),
59
+ image: imageOf(track),
60
+ url: urlOf(track),
61
+ playedAt,
62
+ progressMs,
63
+ durationMs: typeof track.duration_ms === "number" ? track.duration_ms : null,
64
+ next: null
65
+ };
66
+ }
67
+ function toQueueItem(track) {
68
+ if (!track?.name) return null;
69
+ return {
70
+ track: track.name,
71
+ artist: artistOf(track),
72
+ album: albumOf(track) || void 0,
73
+ image: imageOf(track),
74
+ url: urlOf(track)
75
+ };
76
+ }
77
+ var SpotifyApi = class {
78
+ credentials;
79
+ options;
80
+ tokenCache = null;
81
+ rotatedRefreshToken = null;
82
+ tokenInFlight = null;
83
+ statusCache = null;
84
+ statusInFlight = null;
85
+ constructor(credentials, options = {}) {
86
+ this.credentials = { ...assertCredentials(credentials) };
87
+ this.options = options;
88
+ }
89
+ /** Discard this instance's cached token and status. */
90
+ clearCache() {
91
+ this.tokenCache = null;
92
+ this.rotatedRefreshToken = null;
93
+ this.tokenInFlight = null;
94
+ this.statusCache = null;
95
+ this.statusInFlight = null;
96
+ }
97
+ async getAccessToken() {
98
+ const now = Date.now();
99
+ if (this.tokenCache && this.tokenCache.expiresAt > now + 6e4) {
100
+ return this.tokenCache.value;
101
+ }
102
+ if (this.tokenInFlight) return this.tokenInFlight;
103
+ this.tokenInFlight = (async () => {
104
+ try {
105
+ const body = new URLSearchParams({
106
+ grant_type: "refresh_token",
107
+ refresh_token: this.rotatedRefreshToken ?? this.credentials.refreshToken
108
+ });
109
+ const { data } = await axios.post(
110
+ this.options.tokenUrl ?? TOKEN_URL,
111
+ body.toString(),
112
+ {
113
+ headers: {
114
+ Authorization: `Basic ${base64(`${this.credentials.clientId}:${this.credentials.clientSecret}`)}`,
115
+ "Content-Type": "application/x-www-form-urlencoded"
116
+ },
117
+ timeout: REQUEST_TIMEOUT
118
+ }
119
+ );
120
+ if (!data.access_token) {
121
+ throw new SpotifyError("Spotify token response did not contain an access token");
122
+ }
123
+ this.tokenCache = {
124
+ value: data.access_token,
125
+ expiresAt: Date.now() + (data.expires_in ?? 3600) * 1e3
126
+ };
127
+ if (data.refresh_token) this.rotatedRefreshToken = data.refresh_token;
128
+ return this.tokenCache.value;
129
+ } catch (error) {
130
+ throw describeError(error, "Could not refresh the Spotify access token");
131
+ } finally {
132
+ this.tokenInFlight = null;
133
+ }
134
+ })();
135
+ return this.tokenInFlight;
136
+ }
137
+ async getCurrentlyPlaying(api) {
138
+ const response = await api.get("/me/player/currently-playing", {
139
+ params: { additional_types: "track,episode" },
140
+ validateStatus: (status) => status === 200 || status === 204
141
+ });
142
+ return response.status === 200 ? response.data : null;
143
+ }
144
+ async getNextTrack(api) {
145
+ try {
146
+ const { data } = await api.get("/me/player/queue");
147
+ return toQueueItem(data.items?.[0]);
148
+ } catch {
149
+ return null;
150
+ }
151
+ }
152
+ async getLastPlayed(api) {
153
+ try {
154
+ const { data } = await api.get("/me/player/recently-played", {
155
+ params: { limit: 1 }
156
+ });
157
+ const entry = data.items?.[0];
158
+ if (!entry?.track) return null;
159
+ return toStatus(entry.track, false, entry.played_at ?? null);
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+ /** Fetch a status snapshot, reusing a fresh cached snapshot when available. */
165
+ async getSnapshot() {
166
+ const cacheMs = Math.max(0, this.options.cacheMs ?? 5e3);
167
+ const ageMs = this.statusCache ? Date.now() - this.statusCache.fetchedAt : 0;
168
+ if (this.statusCache && ageMs < cacheMs) {
169
+ return { status: this.statusCache.snapshot.status, ageMs };
170
+ }
171
+ if (this.statusInFlight) return this.statusInFlight;
172
+ this.statusInFlight = (async () => {
173
+ try {
174
+ const token = await this.getAccessToken();
175
+ const api = axios.create({
176
+ baseURL: this.options.apiBaseUrl ?? API_BASE_URL,
177
+ timeout: REQUEST_TIMEOUT,
178
+ headers: { Authorization: `Bearer ${token}` }
179
+ });
180
+ let status = null;
181
+ let error = null;
182
+ try {
183
+ const current = await this.getCurrentlyPlaying(api);
184
+ if (current?.item) {
185
+ status = toStatus(
186
+ current.item,
187
+ current.is_playing === true,
188
+ typeof current.timestamp === "number" ? new Date(current.timestamp).toISOString() : null,
189
+ typeof current.progress_ms === "number" ? current.progress_ms : null
190
+ );
191
+ if (status.playing) status.next = await this.getNextTrack(api);
192
+ } else {
193
+ status = await this.getLastPlayed(api);
194
+ }
195
+ } catch (caught) {
196
+ error = caught;
197
+ }
198
+ if (error) throw describeError(error, "Could not read Spotify playback status");
199
+ if (status) {
200
+ this.statusCache = { snapshot: { status, ageMs: 0 }, fetchedAt: Date.now() };
201
+ return { status, ageMs: 0 };
202
+ }
203
+ this.statusCache = null;
204
+ return null;
205
+ } finally {
206
+ this.statusInFlight = null;
207
+ }
208
+ })();
209
+ return this.statusInFlight;
210
+ }
211
+ /** Fetch just the status JSON (including `ageMs`) the banner expects. */
212
+ async getStatus() {
213
+ const snapshot = await this.getSnapshot();
214
+ return snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null;
215
+ }
216
+ };
217
+ function createSpotifyApi(credentials, options = {}) {
218
+ return new SpotifyApi(credentials, options);
219
+ }
220
+ async function fetchSpotifyStatus(credentials, options = {}) {
221
+ return createSpotifyApi(credentials, options).getSnapshot();
222
+ }
223
+ async function getSpotifyStatus(credentials, options = {}) {
224
+ return createSpotifyApi(credentials, options).getStatus();
225
+ }
226
+
227
+ export {
228
+ SpotifyError,
229
+ SpotifyApi,
230
+ createSpotifyApi,
231
+ fetchSpotifyStatus,
232
+ getSpotifyStatus
233
+ };
234
+ //# sourceMappingURL=chunk-GKEANZNP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/spotify.ts"],"sourcesContent":["import axios from 'axios'\nimport type { SpotifyCredentials, SpotifyQueueItem, SpotifyStatus } 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 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 invalid credential input. */\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\n/** A status snapshot plus the age of the API's cached copy. */\nexport type SpotifySnapshot = {\n status: SpotifyStatus\n ageMs: number\n}\n\nexport type SpotifyApiOptions = {\n /** Cache lifetime in milliseconds. Defaults to 5000. */\n cacheMs?: number\n /** Override the token endpoint (useful for tests). */\n tokenUrl?: string\n /** Override the Web API base URL (useful for tests). */\n apiBaseUrl?: string\n}\n\nfunction assertCredentials(credentials: SpotifyCredentials | undefined): SpotifyCredentials {\n if (!credentials?.clientId || !credentials.clientSecret || !credentials.refreshToken) {\n throw new SpotifyError(\n 'Spotify credentials are missing. Pass clientId, clientSecret and refreshToken to createSpotifyApi() or to <SpotifyBanner credentials={...}>.'\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\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\n/**\n * A credential-bound Spotify client. Each instance keeps its own token and\n * status caches, so different credentials never share state.\n */\nexport class SpotifyApi {\n private readonly credentials: SpotifyCredentials\n private readonly options: SpotifyApiOptions\n\n private tokenCache: { value: string; expiresAt: number } | null = null\n private rotatedRefreshToken: string | null = null\n private tokenInFlight: Promise<string> | null = null\n\n private statusCache: { snapshot: SpotifySnapshot; fetchedAt: number } | null = null\n private statusInFlight: Promise<SpotifySnapshot | null> | null = null\n\n constructor(credentials: SpotifyCredentials, options: SpotifyApiOptions = {}) {\n this.credentials = { ...assertCredentials(credentials) }\n this.options = options\n }\n\n /** Discard this instance's cached token and status. */\n clearCache(): void {\n this.tokenCache = null\n this.rotatedRefreshToken = null\n this.tokenInFlight = null\n this.statusCache = null\n this.statusInFlight = null\n }\n\n private async getAccessToken(): Promise<string> {\n const now = Date.now()\n if (this.tokenCache && this.tokenCache.expiresAt > now + 60_000) {\n return this.tokenCache.value\n }\n if (this.tokenInFlight) return this.tokenInFlight\n\n this.tokenInFlight = (async () => {\n try {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: this.rotatedRefreshToken ?? this.credentials.refreshToken\n })\n\n const { data } = await axios.post<TokenResponse>(\n this.options.tokenUrl ?? TOKEN_URL,\n body.toString(),\n {\n headers: {\n Authorization: `Basic ${base64(`${this.credentials.clientId}:${this.credentials.clientSecret}`)}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n timeout: REQUEST_TIMEOUT\n }\n )\n\n if (!data.access_token) {\n throw new SpotifyError('Spotify token response did not contain an access token')\n }\n\n this.tokenCache = {\n value: data.access_token,\n expiresAt: Date.now() + (data.expires_in ?? 3600) * 1000\n }\n if (data.refresh_token) this.rotatedRefreshToken = data.refresh_token\n return this.tokenCache.value\n } catch (error) {\n throw describeError(error, 'Could not refresh the Spotify access token')\n } finally {\n this.tokenInFlight = null\n }\n })()\n\n return this.tokenInFlight\n }\n\n private async 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\n private async 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\n private async 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 /** Fetch a status snapshot, reusing a fresh cached snapshot when available. */\n async getSnapshot(): Promise<SpotifySnapshot | null> {\n const cacheMs = Math.max(0, this.options.cacheMs ?? 5000)\n const ageMs = this.statusCache ? Date.now() - this.statusCache.fetchedAt : 0\n if (this.statusCache && ageMs < cacheMs) {\n return { status: this.statusCache.snapshot.status, ageMs }\n }\n if (this.statusInFlight) return this.statusInFlight\n\n this.statusInFlight = (async () => {\n try {\n const token = await this.getAccessToken()\n const api = axios.create({\n baseURL: this.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 this.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 this.getNextTrack(api)\n } else {\n status = await this.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 this.statusCache = { snapshot: { status, ageMs: 0 }, fetchedAt: Date.now() }\n return { status, ageMs: 0 }\n }\n this.statusCache = null\n return null\n } finally {\n this.statusInFlight = null\n }\n })()\n\n return this.statusInFlight\n }\n\n /** Fetch just the status JSON (including `ageMs`) the banner expects. */\n async getStatus(): Promise<SpotifyStatus | null> {\n const snapshot = await this.getSnapshot()\n return snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null\n }\n}\n\n/** Create a credential-bound Spotify client. */\nexport function createSpotifyApi(\n credentials: SpotifyCredentials,\n options: SpotifyApiOptions = {}\n): SpotifyApi {\n return new SpotifyApi(credentials, options)\n}\n\n/** One-off snapshot fetch. Use `createSpotifyApi` to keep the cache between calls. */\nexport async function fetchSpotifyStatus(\n credentials: SpotifyCredentials,\n options: SpotifyApiOptions = {}\n): Promise<SpotifySnapshot | null> {\n return createSpotifyApi(credentials, options).getSnapshot()\n}\n\n/** One-off status fetch. Use `createSpotifyApi` to keep the cache between calls. */\nexport async function getSpotifyStatus(\n credentials: SpotifyCredentials,\n options: SpotifyApiOptions = {}\n): Promise<SpotifyStatus | null> {\n return createSpotifyApi(credentials, options).getStatus()\n}\n"],"mappings":";AAAA,OAAO,WAAW;AAGlB,IAAM,YAAY;AAClB,IAAM,eAAe;AACrB,IAAM,kBAAkB;AA4BjB,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EAET,YAAY,SAAiB,QAAiB;AAC5C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAiBA,SAAS,kBAAkB,aAAiE;AAC1F,MAAI,CAAC,aAAa,YAAY,CAAC,YAAY,gBAAgB,CAAC,YAAY,cAAc;AACpF,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,OAAO,OAAuB;AACrC,MAAI,OAAO,SAAS,WAAY,QAAO,KAAK,KAAK;AACjD,QAAM,mBAAmB;AAGzB,SAAO,iBAAiB,QAAQ,KAAK,OAAO,MAAM,EAAE,SAAS,QAAQ,KAAK;AAC5E;AAEA,SAAS,cAAc,OAAgB,UAAgC;AACrE,MAAI,iBAAiB,aAAc,QAAO;AAC1C,MAAI,MAAM,aAAa,KAAK,GAAG;AAC7B,UAAM,SAAS,MAAM,UAAU;AAC/B,UAAM,SAAU,MAA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AAA,EAGA,MAAM,YAA2C;AAC/C,UAAM,WAAW,MAAM,KAAK,YAAY;AACxC,WAAO,WAAW,EAAE,GAAG,SAAS,QAAQ,OAAO,SAAS,MAAM,IAAI;AAAA,EACpE;AACF;AAGO,SAAS,iBACd,aACA,UAA6B,CAAC,GAClB;AACZ,SAAO,IAAI,WAAW,aAAa,OAAO;AAC5C;AAGA,eAAsB,mBACpB,aACA,UAA6B,CAAC,GACG;AACjC,SAAO,iBAAiB,aAAa,OAAO,EAAE,YAAY;AAC5D;AAGA,eAAsB,iBACpB,aACA,UAA6B,CAAC,GACC;AAC/B,SAAO,iBAAiB,aAAa,OAAO,EAAE,UAAU;AAC1D;","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,13 +1,17 @@
1
1
  import * as react from 'react';
2
- import { S as SpotifyBannerProps } from './types-CJlhN267.js';
3
- export { a as SpotifyQueueItem, b as SpotifyStatus } from './types-CJlhN267.js';
2
+ import { S as SpotifyBannerProps } from './spotify-B7X9bmfI.js';
3
+ export { a as SpotifyApi, b as SpotifyApiOptions, c as SpotifyCredentials, d as SpotifyError, e as SpotifyQueueItem, f as SpotifySnapshot, g as SpotifyStatus, h as createSpotifyApi, i as fetchSpotifyStatus, j as getSpotifyStatus } from './spotify-B7X9bmfI.js';
4
4
 
5
5
  /**
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.
6
+ * Shows the current (or most recent) Spotify track. Pass `credentials` to
7
+ * call Spotify directly, or rely on the bundled server handler at
8
+ * `/api/spotify` by omitting them.
9
+ *
10
+ * WARNING: credentials passed to a client component are public. Prefer the
11
+ * server handler for real applications.
12
+ *
9
13
  * Styling comes from `spotify-now-playing-banner/styles.css`.
10
14
  */
11
- declare function SpotifyBanner({ endpoint, initialStatus, pollIntervalMs, className }: SpotifyBannerProps): react.JSX.Element | null;
15
+ declare function SpotifyBanner({ credentials, clientId, clientSecret, refreshToken, endpoint, initialStatus, pollIntervalMs, className }: SpotifyBannerProps): react.JSX.Element | null;
12
16
 
13
17
  export { SpotifyBanner, SpotifyBannerProps };
package/dist/index.js CHANGED
@@ -1,5 +1,13 @@
1
+ import {
2
+ SpotifyApi,
3
+ SpotifyError,
4
+ createSpotifyApi,
5
+ fetchSpotifyStatus,
6
+ getSpotifyStatus
7
+ } from "./chunk-GKEANZNP.js";
8
+
1
9
  // src/SpotifyBanner.tsx
2
- import { useEffect, useState } from "react";
10
+ import { useEffect, useMemo, useState } from "react";
3
11
  import { jsx, jsxs } from "react/jsx-runtime";
4
12
  function trackKey(status) {
5
13
  return `${status.track}|${status.playedAt ?? ""}`;
@@ -11,11 +19,30 @@ function formatTime(ms) {
11
19
  return `${minutes}:${String(seconds).padStart(2, "0")}`;
12
20
  }
13
21
  function SpotifyBanner({
22
+ credentials,
23
+ clientId,
24
+ clientSecret,
25
+ refreshToken,
14
26
  endpoint = "/api/spotify",
15
27
  initialStatus = null,
16
28
  pollIntervalMs = 3e3,
17
29
  className
18
30
  }) {
31
+ const resolvedCredentials = useMemo(
32
+ () => credentials ?? (clientId && clientSecret && refreshToken ? { clientId, clientSecret, refreshToken } : null),
33
+ [
34
+ credentials?.clientId,
35
+ credentials?.clientSecret,
36
+ credentials?.refreshToken,
37
+ clientId,
38
+ clientSecret,
39
+ refreshToken
40
+ ]
41
+ );
42
+ const api = useMemo(
43
+ () => resolvedCredentials ? createSpotifyApi(resolvedCredentials) : null,
44
+ [resolvedCredentials]
45
+ );
19
46
  const [status, setStatus] = useState(initialStatus);
20
47
  const [anchor, setAnchor] = useState(null);
21
48
  const [now, setNow] = useState(() => Date.now());
@@ -26,9 +53,11 @@ function SpotifyBanner({
26
53
  const refresh = async () => {
27
54
  const requestId = ++latestRequest;
28
55
  try {
29
- const response = await fetch(endpoint, { cache: "no-store" });
30
- if (!response.ok) return;
31
- const live = await response.json();
56
+ const live = api ? await api.getStatus() : await (async () => {
57
+ const response = await fetch(endpoint, { cache: "no-store" });
58
+ if (!response.ok) return null;
59
+ return await response.json();
60
+ })();
32
61
  if (!mounted || requestId !== latestRequest || !live?.track) return;
33
62
  const at = Date.now();
34
63
  const ageMs = Number.isFinite(live.ageMs) ? Math.max(0, live.ageMs) : 0;
@@ -58,7 +87,7 @@ function SpotifyBanner({
58
87
  window.clearInterval(interval);
59
88
  document.removeEventListener("visibilitychange", onVisibilityChange);
60
89
  };
61
- }, [endpoint, pollIntervalMs]);
90
+ }, [api, endpoint, pollIntervalMs]);
62
91
  useEffect(() => {
63
92
  if (!status?.playing || !anchor) return;
64
93
  const interval = window.setInterval(() => setNow(Date.now()), 500);
@@ -152,6 +181,11 @@ function SpotifyBanner({
152
181
  ) });
153
182
  }
154
183
  export {
155
- SpotifyBanner
184
+ SpotifyApi,
185
+ SpotifyBanner,
186
+ SpotifyError,
187
+ createSpotifyApi,
188
+ fetchSpotifyStatus,
189
+ getSpotifyStatus
156
190
  };
157
191
  //# sourceMappingURL=index.js.map
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 `/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,MAAM,SAAS,KAAK;AAClC,YAAI,CAAC,WAAW,cAAc,iBAAiB,CAAC,MAAM,MAAO;AAE7D,cAAM,KAAK,KAAK,IAAI;AACpB,cAAM,QAAQ,OAAO,SAAS,KAAK,KAAK,IAAI,KAAK,IAAI,GAAG,KAAK,KAAM,IAAI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C,oBAAC,OAAE,WAAU,sBAAsB,iBAAO,QAAO;AAAA,UAEhD,QAAQ,SACP,qBAAC,SAAI,WAAU,uBACZ;AAAA,mBAAO,SACN;AAAA,cAAC;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, useMemo, useState } from 'react'\nimport { createSpotifyApi } from './spotify'\nimport type { SpotifyBannerProps, SpotifyCredentials, 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. Pass `credentials` to\n * call Spotify directly, or rely on the bundled server handler at\n * `/api/spotify` by omitting them.\n *\n * WARNING: credentials passed to a client component are public. Prefer the\n * server handler for real applications.\n *\n * Styling comes from `spotify-now-playing-banner/styles.css`.\n */\nexport function SpotifyBanner({\n credentials,\n clientId,\n clientSecret,\n refreshToken,\n endpoint = '/api/spotify',\n initialStatus = null,\n pollIntervalMs = 3000,\n className\n}: SpotifyBannerProps) {\n const resolvedCredentials = useMemo<SpotifyCredentials | null>(\n () => credentials\n ?? (clientId && clientSecret && refreshToken\n ? { clientId, clientSecret, refreshToken }\n : null),\n [\n credentials?.clientId,\n credentials?.clientSecret,\n credentials?.refreshToken,\n clientId,\n clientSecret,\n refreshToken\n ]\n )\n\n const api = useMemo(\n () => (resolvedCredentials ? createSpotifyApi(resolvedCredentials) : null),\n [resolvedCredentials]\n )\n\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 live = api\n ? await api.getStatus()\n : await (async () => {\n const response = await fetch(endpoint, { cache: 'no-store' })\n if (!response.ok) return null\n return (await response.json()) as SpotifyStatus | null\n })()\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 }, [api, 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,SAAS,gBAAgB;AA+JrC,cAeM,YAfN;AArJR,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,GA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AEhD,QAAQ,SACP,qBAAC,SAAI,WAAU,uBACZ;AAAA,mBAAO,SACN;AAAA,cAAC;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,24 +1,6 @@
1
- import { SpotifyStatus } from '../index.js';
1
+ import { c as SpotifyCredentials, b as SpotifyApiOptions } from '../spotify-B7X9bmfI.js';
2
+ export { a as SpotifyApi, d as SpotifyError, f as SpotifySnapshot, h as createSpotifyApi, i as fetchSpotifyStatus, j as getSpotifyStatus } from '../spotify-B7X9bmfI.js';
2
3
 
3
- /** Spotify OAuth app credentials used to obtain an access token. */
4
- 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
4
  /** Minimal Node request shape, so `@types/node` is not required. */
23
5
  interface NodeRequestLike {
24
6
  method?: string;
@@ -39,39 +21,21 @@ interface SpotifyHandler {
39
21
  (request: Request): Promise<Response>;
40
22
  (req: NodeRequestLike, res: NodeResponseLike): Promise<void>;
41
23
  }
42
- type SpotifyHandlerOptions = SpotifyServiceOptions & {
43
- /** Add permissive CORS headers so a site on another origin can poll. Defaults to true. */
24
+ type SpotifyHandlerOptions = SpotifyCredentials & SpotifyApiOptions & {
25
+ /** Add permissive CORS headers so another origin can poll. Defaults to true. */
44
26
  cors?: boolean;
45
27
  };
46
28
 
47
29
  /**
48
- * Create a read-only Spotify status endpoint that reads credentials from the
49
- * server environment. The returned function works as either:
30
+ * Create a read-only Spotify status endpoint from explicit credentials.
31
+ * The returned function works as either:
50
32
  *
51
- * - a Web handler: `export const GET = createSpotifyHandler()`
52
- * - a Node handler: `export default createSpotifyHandler()` in `api/spotify.mjs`
33
+ * - a Web handler: `export const GET = createSpotifyHandler(credentials)`
34
+ * - a Node handler: `export default createSpotifyHandler(credentials)`
53
35
  *
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.
36
+ * No environment variables are read by this package.
71
37
  */
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>;
38
+ declare function createSpotifyHandler(options: SpotifyHandlerOptions): SpotifyHandler;
75
39
 
76
- export { SpotifyError, clearSpotifyCache, createSpotifyHandler, credentialsFromEnv, fetchSpotifyStatus, getSpotifyStatus };
77
- export type { NodeRequestLike, NodeResponseLike, SpotifyCredentials, SpotifyHandler, SpotifyHandlerOptions, SpotifyServiceOptions, SpotifySnapshot };
40
+ export { SpotifyApiOptions, SpotifyCredentials, createSpotifyHandler };
41
+ export type { NodeRequestLike, NodeResponseLike, SpotifyHandler, SpotifyHandlerOptions };
@@ -1,220 +1,10 @@
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
- }
1
+ import {
2
+ SpotifyApi,
3
+ SpotifyError,
4
+ createSpotifyApi,
5
+ fetchSpotifyStatus,
6
+ getSpotifyStatus
7
+ } from "../chunk-GKEANZNP.js";
218
8
 
219
9
  // src/server/handler.ts
220
10
  function responseHeaders(cors) {
@@ -235,8 +25,9 @@ function sendNode(res, statusCode, body, cors) {
235
25
  }
236
26
  res.end(body === void 0 ? void 0 : JSON.stringify(body));
237
27
  }
238
- function createSpotifyHandler(options = {}) {
28
+ function createSpotifyHandler(options) {
239
29
  const cors = options.cors !== false;
30
+ const api = createSpotifyApi(options, options);
240
31
  return (async (requestOrReq, res) => {
241
32
  const isNodeStyle = res != null;
242
33
  const method = isNodeStyle ? requestOrReq.method ?? "GET" : requestOrReq.method;
@@ -253,7 +44,7 @@ function createSpotifyHandler(options = {}) {
253
44
  });
254
45
  }
255
46
  try {
256
- const snapshot = await fetchSpotifyStatus(options);
47
+ const snapshot = await api.getSnapshot();
257
48
  const body = snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null;
258
49
  if (isNodeStyle) return sendNode(res, 200, body, cors);
259
50
  return new Response(JSON.stringify(body), {
@@ -273,10 +64,10 @@ function createSpotifyHandler(options = {}) {
273
64
  });
274
65
  }
275
66
  export {
67
+ SpotifyApi,
276
68
  SpotifyError,
277
- clearSpotifyCache,
69
+ createSpotifyApi,
278
70
  createSpotifyHandler,
279
- credentialsFromEnv,
280
71
  fetchSpotifyStatus,
281
72
  getSpotifyStatus
282
73
  };
@@ -1 +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 SpotifyHandler\n}\n"],"mappings":";AAAA,OAAO,WAAW;AAQlB,IAAM,YAAY;AAClB,IAAM,eAAe;AACrB,IAAM,kBAAkB;AA6BjB,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EAET,YAAY,SAAiB,QAAiB;AAC5C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAEA,IAAI,aAA0D;AAC9D,IAAI,sBAAqC;AACzC,IAAI,gBAAwC;AAE5C,IAAI,cAAuE;AAC3E,IAAI,iBAAyD;AAGtD,SAAS,oBAA0B;AACxC,eAAa;AACb,wBAAsB;AACtB,kBAAgB;AAChB,gBAAc;AACd,mBAAiB;AACnB;AAEA,SAAS,UAA8C;AACrD,QAAM,oBAAoB;AAG1B,SAAO,kBAAkB,SAAS,OAAO,CAAC;AAC5C;AAGO,SAAS,mBACd,MAA0C,QAAQ,GACvB;AAC3B,QAAM,WAAW,IAAI;AACrB,QAAM,eAAe,IAAI;AACzB,QAAM,eAAe,IAAI;AAEzB,MAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,aAAc,QAAO;AACxD,SAAO,EAAE,UAAU,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AAI;AAAA,MAC/B,CAAC;AAAA,IACH;AAEA,QAAI;AACF,YAAM,WAAW,MAAM,mBAAmB,OAAO;AACjD,YAAM,OAAO,WAAW,EAAE,GAAG,SAAS,QAAQ,OAAO,SAAS,MAAM,IAAI;AACxE,UAAI,YAAa,QAAO,SAAS,KAAM,KAAK,MAAM,IAAI;AACtD,aAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,QACxC,QAAQ;AAAA,QACR,SAAS,gBAAgB,IAAI;AAAA,MAC/B,CAAC;AAAA,IACH,SAAS,OAAO;AACd,YAAM,UAAU,iBAAiB,eAC7B,MAAM,UACN;AACJ,YAAM,aAAa,iBAAiB,gBAAgB,MAAM,WAAW,MAAM,MAAM;AACjF,YAAM,OAAO,EAAE,OAAO,QAAQ;AAC9B,UAAI,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":[]}
1
+ {"version":3,"sources":["../../src/server/handler.ts"],"sourcesContent":["import { createSpotifyApi, 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 from explicit credentials.\n * The returned function works as either:\n *\n * - a Web handler: `export const GET = createSpotifyHandler(credentials)`\n * - a Node handler: `export default createSpotifyHandler(credentials)`\n *\n * No environment variables are read by this package.\n */\nexport function createSpotifyHandler(options: SpotifyHandlerOptions): SpotifyHandler {\n const cors = options.cors !== false\n const api = createSpotifyApi(options, options)\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 api.getSnapshot()\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 SpotifyHandler\n}\n"],"mappings":";;;;;;;;;AAQA,SAAS,gBAAgB,MAAuC;AAC9D,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,iBAAiB;AAAA,IACjB,GAAI,OACA;AAAA,MACE,+BAA+B;AAAA,MAC/B,gCAAgC;AAAA,MAChC,gCAAgC;AAAA,IAClC,IACA,CAAC;AAAA,EACP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,MAAM,UACN;AACJ,YAAM,aAAa,iBAAiB,gBAAgB,MAAM,WAAW,MAAM,MAAM;AACjF,YAAM,OAAO,EAAE,OAAO,QAAQ;AAC9B,UAAI,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,106 @@
1
+ /** Spotify OAuth app credentials. */
2
+ type SpotifyCredentials = {
3
+ clientId: string;
4
+ clientSecret: string;
5
+ refreshToken: string;
6
+ };
7
+ /** A track (or podcast episode) in the playback queue. */
8
+ type SpotifyQueueItem = {
9
+ track: string;
10
+ artist: string;
11
+ album?: string;
12
+ image: string;
13
+ url: string;
14
+ };
15
+ /** The status JSON returned by the Spotify status endpoint or API helper. */
16
+ type SpotifyStatus = {
17
+ playing: boolean;
18
+ track: string;
19
+ artist: string;
20
+ album: string;
21
+ image: string;
22
+ url: string;
23
+ playedAt: string | null;
24
+ progressMs?: number | null;
25
+ durationMs?: number | null;
26
+ next?: SpotifyQueueItem | null;
27
+ /** Age of the server-side snapshot in milliseconds. */
28
+ ageMs?: number;
29
+ };
30
+ type SpotifyBannerProps = {
31
+ /**
32
+ * Spotify credentials for direct, in-browser calls to the Spotify API.
33
+ * WARNING: anything in client props is public — anyone can read these
34
+ * values. Prefer the server handler for real applications.
35
+ */
36
+ credentials?: SpotifyCredentials;
37
+ /** Shorthand for `credentials.clientId`. */
38
+ clientId?: string;
39
+ /** Shorthand for `credentials.clientSecret`. */
40
+ clientSecret?: string;
41
+ /** Shorthand for `credentials.refreshToken`. */
42
+ refreshToken?: string;
43
+ /**
44
+ * URL of the status endpoint. Defaults to `/api/spotify`. Used only when no
45
+ * credentials are passed. Not needed when using the bundled handler.
46
+ */
47
+ endpoint?: string;
48
+ /** Data to render before the first poll succeeds. */
49
+ initialStatus?: SpotifyStatus | null;
50
+ /** Polling interval in milliseconds. Set to 0 to disable polling. Defaults to 3000. */
51
+ pollIntervalMs?: number;
52
+ /** Extra class names applied to the root element. */
53
+ className?: string;
54
+ };
55
+
56
+ /** An error from Spotify or from invalid credential input. */
57
+ declare class SpotifyError extends Error {
58
+ readonly status?: number;
59
+ constructor(message: string, status?: number);
60
+ }
61
+ /** A status snapshot plus the age of the API's cached copy. */
62
+ type SpotifySnapshot = {
63
+ status: SpotifyStatus;
64
+ ageMs: number;
65
+ };
66
+ type SpotifyApiOptions = {
67
+ /** Cache lifetime in milliseconds. Defaults to 5000. */
68
+ cacheMs?: number;
69
+ /** Override the token endpoint (useful for tests). */
70
+ tokenUrl?: string;
71
+ /** Override the Web API base URL (useful for tests). */
72
+ apiBaseUrl?: string;
73
+ };
74
+ /**
75
+ * A credential-bound Spotify client. Each instance keeps its own token and
76
+ * status caches, so different credentials never share state.
77
+ */
78
+ declare class SpotifyApi {
79
+ private readonly credentials;
80
+ private readonly options;
81
+ private tokenCache;
82
+ private rotatedRefreshToken;
83
+ private tokenInFlight;
84
+ private statusCache;
85
+ private statusInFlight;
86
+ constructor(credentials: SpotifyCredentials, options?: SpotifyApiOptions);
87
+ /** Discard this instance's cached token and status. */
88
+ clearCache(): void;
89
+ private getAccessToken;
90
+ private getCurrentlyPlaying;
91
+ private getNextTrack;
92
+ private getLastPlayed;
93
+ /** Fetch a status snapshot, reusing a fresh cached snapshot when available. */
94
+ getSnapshot(): Promise<SpotifySnapshot | null>;
95
+ /** Fetch just the status JSON (including `ageMs`) the banner expects. */
96
+ getStatus(): Promise<SpotifyStatus | null>;
97
+ }
98
+ /** Create a credential-bound Spotify client. */
99
+ declare function createSpotifyApi(credentials: SpotifyCredentials, options?: SpotifyApiOptions): SpotifyApi;
100
+ /** One-off snapshot fetch. Use `createSpotifyApi` to keep the cache between calls. */
101
+ declare function fetchSpotifyStatus(credentials: SpotifyCredentials, options?: SpotifyApiOptions): Promise<SpotifySnapshot | null>;
102
+ /** One-off status fetch. Use `createSpotifyApi` to keep the cache between calls. */
103
+ declare function getSpotifyStatus(credentials: SpotifyCredentials, options?: SpotifyApiOptions): Promise<SpotifyStatus | null>;
104
+
105
+ export { SpotifyApi as a, SpotifyError as d, createSpotifyApi as h, fetchSpotifyStatus as i, getSpotifyStatus as j };
106
+ export type { SpotifyBannerProps as S, SpotifyApiOptions as b, SpotifyCredentials as c, SpotifyQueueItem as e, SpotifySnapshot as f, SpotifyStatus as g };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spotify-now-playing-banner",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
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",
@@ -1,38 +0,0 @@
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 };