@sdeck/plugin-spotify 0.0.0-stage → 0.1.0

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/dist/index.js ADDED
@@ -0,0 +1,2165 @@
1
+ // @bun
2
+ // ../core/src/element.ts
3
+ var runtime;
4
+ function registerElementRuntime(next) {
5
+ runtime = next;
6
+ }
7
+ // ../react/src/render.ts
8
+ function isReactElement(value) {
9
+ return typeof value === "object" && value !== null && "$$typeof" in value;
10
+ }
11
+ var defaultRenderer = {};
12
+ var fontRenderers = new WeakMap;
13
+ async function createRenderer(fonts) {
14
+ const { Renderer } = await import("@takumi-rs/core");
15
+ const renderer = new Renderer;
16
+ for (const font of fonts) {
17
+ await renderer.registerFont({
18
+ name: font.name,
19
+ data: font.data,
20
+ ...font.weight !== undefined && { weight: font.weight },
21
+ ...font.style !== undefined && { style: font.style }
22
+ });
23
+ }
24
+ return renderer;
25
+ }
26
+ function getRenderer(fonts) {
27
+ if (!fonts?.length) {
28
+ defaultRenderer.current ??= createRenderer([]);
29
+ defaultRenderer.current.catch(() => {
30
+ defaultRenderer.current = undefined;
31
+ });
32
+ return defaultRenderer.current;
33
+ }
34
+ let renderer = fontRenderers.get(fonts);
35
+ if (!renderer) {
36
+ renderer = createRenderer(fonts);
37
+ renderer.catch(() => fontRenderers.delete(fonts));
38
+ fontRenderers.set(fonts, renderer);
39
+ }
40
+ return renderer;
41
+ }
42
+ var number = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
43
+ function toNode(node, text = true) {
44
+ if ("text" in node) {
45
+ return text ? { type: "text", text: node.text } : { type: "container", children: [] };
46
+ }
47
+ const { style, tw, src, width, height } = node.props;
48
+ const common = {
49
+ ...typeof tw === "string" && { tw }
50
+ };
51
+ if (node.type === "img") {
52
+ if (typeof src !== "string")
53
+ throw new Error("<img> needs a string `src` (URL or data: URI)");
54
+ return {
55
+ type: "image",
56
+ src,
57
+ ...number(width) !== undefined && { width: number(width) },
58
+ ...number(height) !== undefined && { height: number(height) },
59
+ ...typeof style === "object" && style !== null && { style },
60
+ ...common
61
+ };
62
+ }
63
+ return {
64
+ type: "container",
65
+ style: { display: "flex", ...typeof style === "object" ? style : {} },
66
+ children: node.children.filter((child) => text || !("text" in child)).map((child) => toNode(child, text)),
67
+ ...common
68
+ };
69
+ }
70
+ var reconciler;
71
+ var flushing = 0;
72
+ function flushAll(renderer) {
73
+ flushing++;
74
+ try {
75
+ renderer.flushSyncWork();
76
+ for (let i = 0;i < 20 && renderer.flushPassiveEffects(); i++)
77
+ renderer.flushSyncWork();
78
+ } finally {
79
+ flushing--;
80
+ }
81
+ }
82
+ function loadReconciler() {
83
+ reconciler ??= (async () => {
84
+ let factoryModule;
85
+ let constants;
86
+ let React;
87
+ try {
88
+ [factoryModule, constants, React] = await Promise.all([
89
+ import("react-reconciler"),
90
+ import("react-reconciler/constants.js"),
91
+ import("react")
92
+ ]);
93
+ } catch (cause) {
94
+ throw new Error("Rendering React elements requires `react` (>=19.3) to be installed", {
95
+ cause
96
+ });
97
+ }
98
+ let priority = constants.NoEventPriority;
99
+ const noop = () => {};
100
+ const hostConfig = {
101
+ supportsMutation: true,
102
+ supportsPersistence: false,
103
+ supportsHydration: false,
104
+ isPrimaryRenderer: true,
105
+ warnsIfNotActing: false,
106
+ noTimeout: -1,
107
+ scheduleTimeout: setTimeout,
108
+ cancelTimeout: clearTimeout,
109
+ supportsMicrotasks: true,
110
+ scheduleMicrotask: queueMicrotask,
111
+ createInstance: (type, props) => {
112
+ const { children: _children, ...rest } = props;
113
+ return { type, props: rest, children: [] };
114
+ },
115
+ createTextInstance: (text) => ({ text }),
116
+ shouldSetTextContent: () => false,
117
+ appendInitialChild: (parent, child) => parent.children.push(child),
118
+ appendChild: (parent, child) => parent.children.push(child),
119
+ appendChildToContainer: (container, child) => container.children.push(child),
120
+ insertBefore: (parent, child, before) => {
121
+ const children = parent.children;
122
+ const existing = children.indexOf(child);
123
+ if (existing !== -1)
124
+ children.splice(existing, 1);
125
+ children.splice(children.indexOf(before), 0, child);
126
+ },
127
+ insertInContainerBefore: (container, child, before) => {
128
+ const children = container.children;
129
+ const existing = children.indexOf(child);
130
+ if (existing !== -1)
131
+ children.splice(existing, 1);
132
+ children.splice(children.indexOf(before), 0, child);
133
+ },
134
+ removeChild: (parent, child) => {
135
+ parent.children.splice(parent.children.indexOf(child), 1);
136
+ },
137
+ removeChildFromContainer: (container, child) => {
138
+ container.children.splice(container.children.indexOf(child), 1);
139
+ },
140
+ clearContainer: (container) => {
141
+ container.children = [];
142
+ },
143
+ commitUpdate: (instance, _type, _prev, next) => {
144
+ const { children: _children, ...rest } = next;
145
+ instance.props = rest;
146
+ },
147
+ commitTextUpdate: (text, _old, next) => {
148
+ text.text = next;
149
+ },
150
+ finalizeInitialChildren: () => false,
151
+ getPublicInstance: (instance) => instance,
152
+ getRootHostContext: () => ({}),
153
+ getChildHostContext: (parent) => parent,
154
+ prepareForCommit: () => null,
155
+ resetAfterCommit: (container) => container.onCommit(),
156
+ preparePortalMount: noop,
157
+ detachDeletedInstance: noop,
158
+ hideInstance: noop,
159
+ unhideInstance: noop,
160
+ hideTextInstance: noop,
161
+ unhideTextInstance: noop,
162
+ getInstanceFromNode: () => null,
163
+ beforeActiveInstanceBlur: noop,
164
+ afterActiveInstanceBlur: noop,
165
+ prepareScopeUpdate: noop,
166
+ getInstanceFromScope: () => null,
167
+ bindToConsole: (method, args) => console[method]?.bind(console, ...args) ?? noop,
168
+ extraDevToolsConfig: null,
169
+ rendererVersion: "0.0.0",
170
+ rendererPackageName: "sdeck",
171
+ getCurrentUpdatePriority: () => priority,
172
+ setCurrentUpdatePriority: (next) => {
173
+ priority = next;
174
+ },
175
+ resolveUpdatePriority: () => priority !== constants.NoEventPriority ? priority : flushing > 0 ? constants.DiscreteEventPriority : constants.DefaultEventPriority,
176
+ resolveEventType: () => null,
177
+ resolveEventTimeStamp: () => -1.1,
178
+ shouldAttemptEagerTransition: () => false,
179
+ trackSchedulerEvent: noop,
180
+ requestPostPaintCallback: noop,
181
+ maySuspendCommit: () => false,
182
+ preloadInstance: () => true,
183
+ startSuspendingCommit: noop,
184
+ suspendInstance: noop,
185
+ waitForCommitToBeReady: () => null,
186
+ getSuspendedCommitReason: () => null,
187
+ NotPendingTransition: null,
188
+ HostTransitionContext: React.createContext(null),
189
+ resetFormInstance: noop
190
+ };
191
+ const factory = factoryModule.default ?? factoryModule;
192
+ return factory(hostConfig);
193
+ })();
194
+ reconciler.catch(() => {
195
+ reconciler = undefined;
196
+ });
197
+ return reconciler;
198
+ }
199
+ function noopIndicator() {}
200
+ async function createReactRoot(size, onFrame, options = {}) {
201
+ const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);
202
+ let dirty = false;
203
+ let drawing;
204
+ let lastTree;
205
+ let unmounted = false;
206
+ let renderError;
207
+ let initial = true;
208
+ const fail = (error) => {
209
+ if (initial)
210
+ renderError ??= { error };
211
+ else
212
+ (options.onError ?? ((e) => console.error("sdeck: React render failed:", e)))(error);
213
+ };
214
+ async function draw() {
215
+ await Promise.resolve();
216
+ while (dirty && !unmounted) {
217
+ dirty = false;
218
+ try {
219
+ const [root] = container.children;
220
+ if (!root)
221
+ continue;
222
+ const tree = toNode(root, options.text !== false);
223
+ const key = JSON.stringify(tree);
224
+ if (key === lastTree)
225
+ continue;
226
+ lastTree = key;
227
+ const pixels = await takumi.render(tree, {
228
+ width: size.width,
229
+ height: size.height,
230
+ format: "raw",
231
+ ...options.scale !== undefined && { devicePixelRatio: options.scale }
232
+ });
233
+ await onFrame({
234
+ data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
235
+ width: size.width,
236
+ height: size.height,
237
+ channels: 4
238
+ });
239
+ } catch (error) {
240
+ lastTree = undefined;
241
+ fail(error);
242
+ }
243
+ }
244
+ drawing = undefined;
245
+ }
246
+ const container = {
247
+ children: [],
248
+ onCommit() {
249
+ dirty = true;
250
+ drawing ??= draw();
251
+ }
252
+ };
253
+ const onError = (error) => fail(error);
254
+ const onCaughtError = () => {};
255
+ const root = renderer.createContainer(container, 1, null, false, null, "", onError, onCaughtError, onError, noopIndicator, null);
256
+ const flush = () => flushAll(renderer);
257
+ const handle = {
258
+ render(element) {
259
+ if (unmounted)
260
+ throw new Error("This React root was unmounted");
261
+ renderer.updateContainerSync(element, root, null, null);
262
+ flush();
263
+ },
264
+ async idle() {
265
+ while (drawing)
266
+ await drawing;
267
+ if (initial && renderError) {
268
+ const { error } = renderError;
269
+ renderError = undefined;
270
+ throw error;
271
+ }
272
+ initial = false;
273
+ },
274
+ async unmount() {
275
+ if (unmounted)
276
+ return;
277
+ renderer.updateContainerSync(null, root, null, null);
278
+ flush();
279
+ unmounted = true;
280
+ await drawing;
281
+ }
282
+ };
283
+ return handle;
284
+ }
285
+ async function renderReact(element, size, fonts, scale) {
286
+ let frame;
287
+ const root = await createReactRoot(size, (next) => {
288
+ frame = next;
289
+ }, { ...fonts && { fonts }, ...scale !== undefined && { scale } });
290
+ try {
291
+ root.render(element);
292
+ await root.idle();
293
+ } finally {
294
+ await root.unmount();
295
+ }
296
+ if (!frame)
297
+ throw new Error("React element rendered nothing");
298
+ return frame;
299
+ }
300
+ registerElementRuntime({
301
+ matches: isReactElement,
302
+ render: (element, size, options) => renderReact(element, size, options?.fonts),
303
+ createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options)
304
+ });
305
+ // ../app/src/app.tsx
306
+ import { Fragment, useSyncExternalStore } from "react";
307
+
308
+ // ../app/src/context.ts
309
+ import { createContext, useContext } from "react";
310
+ var DeckContext = createContext(undefined);
311
+ var SlotContext = createContext(undefined);
312
+ var NavigatorContext = createContext(undefined);
313
+ function useDeck() {
314
+ const deck = useContext(DeckContext);
315
+ if (!deck)
316
+ throw new Error("useDeck() must be used inside a component mounted by @sdeck/app");
317
+ return deck;
318
+ }
319
+ function useSlot() {
320
+ return useContext(SlotContext);
321
+ }
322
+ // ../app/src/hooks.ts
323
+ import { useContext as useContext2, useEffect, useRef, useState, useSyncExternalStore as useSyncExternalStore2 } from "react";
324
+
325
+ // ../app/src/swipe.ts
326
+ var SWIPE_WINDOW_MS = 400;
327
+
328
+ class SwipeTracker {
329
+ #handlers = new Set;
330
+ #stamps = new Map;
331
+ #completing = new Set;
332
+ #first;
333
+ constructor(deck) {
334
+ deck.on("sensorDown", (index) => this.#down(index));
335
+ }
336
+ get active() {
337
+ return this.#handlers.size > 0;
338
+ }
339
+ stamp(index) {
340
+ return this.#stamps.get(index) ?? 0;
341
+ }
342
+ completes(index) {
343
+ return this.#completing.has(index);
344
+ }
345
+ listen(handler) {
346
+ this.#handlers.add(handler);
347
+ return () => void this.#handlers.delete(handler);
348
+ }
349
+ #down(index) {
350
+ this.#completing.delete(index);
351
+ const now = performance.now();
352
+ const first = this.#first;
353
+ if (!this.active || !first || first.index === index || now - first.at > SWIPE_WINDOW_MS) {
354
+ this.#first = { index, at: now };
355
+ return;
356
+ }
357
+ this.#first = undefined;
358
+ this.#completing.add(index);
359
+ for (const sensor of [first.index, index])
360
+ this.#stamps.set(sensor, this.stamp(sensor) + 1);
361
+ const direction = index > first.index ? "right" : "left";
362
+ for (const handler of [...this.#handlers])
363
+ handler(direction);
364
+ }
365
+ }
366
+ var trackers = new WeakMap;
367
+ function swipeTracker(deck) {
368
+ let tracker = trackers.get(deck);
369
+ if (!tracker) {
370
+ tracker = new SwipeTracker(deck);
371
+ trackers.set(deck, tracker);
372
+ }
373
+ return tracker;
374
+ }
375
+
376
+ // ../app/src/hooks.ts
377
+ function useLatest(value) {
378
+ const ref = useRef(value);
379
+ useEffect(() => {
380
+ ref.current = value;
381
+ });
382
+ return ref;
383
+ }
384
+ function useTarget(kind, explicit) {
385
+ const slot = useSlot();
386
+ if (explicit !== undefined)
387
+ return explicit;
388
+ return slot?.kind === kind ? slot.index : undefined;
389
+ }
390
+ function usePress(kind, onPress, gestures, explicit) {
391
+ const deck = useDeck();
392
+ const target = useTarget(kind, explicit);
393
+ const latest = useLatest({
394
+ onPress,
395
+ onLongPress: gestures.onLongPress,
396
+ longPressMs: gestures.longPressMs ?? 500,
397
+ onDoublePress: gestures.onDoublePress ?? gestures.onDoubleTap,
398
+ doublePressMs: gestures.doublePressMs ?? gestures.doubleTapMs ?? 300,
399
+ onRelease: gestures.onRelease ?? false
400
+ });
401
+ useEffect(() => {
402
+ const swipes = kind === "sensor" ? swipeTracker(deck) : undefined;
403
+ const state = new Map;
404
+ const held = new Set;
405
+ const get = (index) => {
406
+ let s = state.get(index);
407
+ if (!s) {
408
+ s = { longFired: false, immediate: false, downAt: 0, stamp: 0 };
409
+ state.set(index, s);
410
+ }
411
+ return s;
412
+ };
413
+ const offDown = deck.on(`${kind}Down`, (index) => {
414
+ if (target !== undefined && index !== target)
415
+ return;
416
+ if (swipes?.completes(index))
417
+ return;
418
+ held.add(index);
419
+ const o = latest.current;
420
+ const s = get(index);
421
+ s.longFired = false;
422
+ s.downAt = performance.now();
423
+ s.stamp = swipes?.stamp(index) ?? 0;
424
+ s.immediate = !o.onLongPress && !o.onDoublePress && !o.onRelease && !swipes?.active;
425
+ if (s.immediate) {
426
+ o.onPress?.(index);
427
+ return;
428
+ }
429
+ if (o.onLongPress) {
430
+ s.long = setTimeout(() => {
431
+ if (swipes && swipes.stamp(index) !== s.stamp)
432
+ return;
433
+ s.longFired = true;
434
+ clearTimeout(s.double);
435
+ s.double = undefined;
436
+ latest.current.onLongPress?.(index);
437
+ }, o.longPressMs);
438
+ }
439
+ });
440
+ const offUp = deck.on(`${kind}Up`, (index) => {
441
+ if (!held.delete(index))
442
+ return;
443
+ const s = get(index);
444
+ clearTimeout(s.long);
445
+ if (s.immediate || s.longFired)
446
+ return;
447
+ if (!swipes?.active)
448
+ return released(index, s);
449
+ const wait = Math.max(0, SWIPE_WINDOW_MS - (performance.now() - s.downAt));
450
+ s.deferred = setTimeout(() => {
451
+ if (swipes.stamp(index) === s.stamp)
452
+ released(index, s);
453
+ }, wait);
454
+ });
455
+ function released(index, s) {
456
+ const o = latest.current;
457
+ if (!o.onDoublePress) {
458
+ o.onPress?.(index);
459
+ } else if (s.double !== undefined) {
460
+ clearTimeout(s.double);
461
+ s.double = undefined;
462
+ o.onDoublePress(index);
463
+ } else {
464
+ s.double = setTimeout(() => {
465
+ s.double = undefined;
466
+ latest.current.onPress?.(index);
467
+ }, o.doublePressMs);
468
+ }
469
+ }
470
+ return () => {
471
+ offDown();
472
+ offUp();
473
+ for (const s of state.values()) {
474
+ clearTimeout(s.long);
475
+ clearTimeout(s.double);
476
+ clearTimeout(s.deferred);
477
+ }
478
+ };
479
+ }, [deck, kind, target, latest]);
480
+ }
481
+ function useKeyPress(onPress, options = {}) {
482
+ usePress("key", onPress, options, options.key);
483
+ }
484
+ function useSensorPress(onPress, options = {}) {
485
+ usePress("sensor", onPress, options, options.sensor);
486
+ }
487
+ // ../engine/src/state.ts
488
+ function sameValue(a, b) {
489
+ if (Object.is(a, b))
490
+ return true;
491
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
492
+ return false;
493
+ if (Array.isArray(a) !== Array.isArray(b))
494
+ return false;
495
+ const ka = Object.keys(a);
496
+ const kb = Object.keys(b);
497
+ if (ka.length !== kb.length)
498
+ return false;
499
+ return ka.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k]));
500
+ }
501
+ // ../schema/src/layers.ts
502
+ function iconLayer(id, icon, options = {}) {
503
+ const { color, size = 52, position = "middle", visible, row, frame } = options;
504
+ const src = /^[a-z0-9]+\/[A-Za-z0-9-]+$/.test(icon) ? `icon:${icon}` : icon;
505
+ return {
506
+ id,
507
+ type: "image",
508
+ src,
509
+ size,
510
+ position,
511
+ ...color && { color },
512
+ ...visible && { visible },
513
+ ...row && { row },
514
+ ...frame && { frame }
515
+ };
516
+ }
517
+ function iconLook(options) {
518
+ const { icon, background, caption = "", color = "#ffffff" } = options;
519
+ return {
520
+ background,
521
+ layers: [
522
+ iconLayer("icon", icon, {
523
+ color,
524
+ size: caption ? 46 : 58,
525
+ position: caption ? "top" : "middle"
526
+ }),
527
+ ...caption ? [textLayer("label", caption, { color, size: 13, position: "bottom" })] : []
528
+ ]
529
+ };
530
+ }
531
+ function textLayer(id, text, options = {}) {
532
+ const { color = "#ffffff", size = 14, weight = 700, position = "middle" } = options;
533
+ const { visible, row, frame } = options;
534
+ return {
535
+ id,
536
+ type: "text",
537
+ text,
538
+ color,
539
+ size,
540
+ weight,
541
+ position,
542
+ ...visible && { visible },
543
+ ...row && { row },
544
+ ...frame && { frame }
545
+ };
546
+ }
547
+ // ../plugin/src/bridge.ts
548
+ import {
549
+ createContext as createContext2,
550
+ useCallback,
551
+ useContext as useContext3,
552
+ useEffect as useEffect2,
553
+ useMemo,
554
+ useRef as useRef2,
555
+ useState as useState2,
556
+ useSyncExternalStore as useSyncExternalStore3
557
+ } from "react";
558
+ var HostBridgeContext = createContext2(undefined);
559
+ function useBridge() {
560
+ const bridge = useContext3(HostBridgeContext);
561
+ if (!bridge)
562
+ throw new Error("sdeck live-state hooks must be used inside an action drawn by the host");
563
+ return bridge;
564
+ }
565
+ function useWatched(paths, read) {
566
+ const bridge = useBridge();
567
+ const key = paths.join(`
568
+ `);
569
+ const subscribe = useCallback((listener) => bridge.watch(paths, listener), [bridge, key]);
570
+ const last = useRef2(undefined);
571
+ const snapshot = () => {
572
+ const value = read();
573
+ if (last.current && sameValue(last.current.value, value))
574
+ return last.current.value;
575
+ last.current = { value };
576
+ return value;
577
+ };
578
+ return useSyncExternalStore3(subscribe, snapshot);
579
+ }
580
+ function useHostState(key) {
581
+ const bridge = useBridge();
582
+ const paths = useMemo(() => [key], [key]);
583
+ return useWatched(paths, () => {
584
+ const dot = key.indexOf(".");
585
+ const ns = bridge.scope()[key.slice(0, dot)];
586
+ return dot > 0 ? ns?.[key.slice(dot + 1)] : undefined;
587
+ });
588
+ }
589
+ function useImage(src, color) {
590
+ const bridge = useBridge();
591
+ return useSyncExternalStore3(bridge.watchImages, () => src ? bridge.image(src, color) : undefined);
592
+ }
593
+ // ../plugin/src/settings.ts
594
+ function checkSchema(schema, sources = {}) {
595
+ const problems = [];
596
+ const types = new Set([
597
+ "text",
598
+ "number",
599
+ "boolean",
600
+ "color",
601
+ "select",
602
+ "page",
603
+ "image",
604
+ "secret"
605
+ ]);
606
+ for (const [key, field] of Object.entries(schema)) {
607
+ if (!field || typeof field !== "object" || !types.has(field.type)) {
608
+ problems.push(`setting "${key}" has an unknown type`);
609
+ continue;
610
+ }
611
+ if (typeof field.label !== "string")
612
+ problems.push(`setting "${key}" needs a label`);
613
+ const source = "source" in field ? field.source : undefined;
614
+ if (source !== undefined && !(source in sources)) {
615
+ problems.push(`setting "${key}" uses unknown option source "${source}"`);
616
+ }
617
+ if (field.type === "select" && (!Array.isArray(field.options) || field.options.length === 0 && source === undefined)) {
618
+ problems.push(`setting "${key}" needs at least one option or a source`);
619
+ }
620
+ for (const other of "dependsOn" in field && field.dependsOn || []) {
621
+ if (!(other in schema))
622
+ problems.push(`setting "${key}" depends on unknown "${other}"`);
623
+ }
624
+ if (field.visibleIf !== undefined) {
625
+ for (const other of Object.keys(field.visibleIf)) {
626
+ if (!(other in schema))
627
+ problems.push(`setting "${key}" depends on unknown "${other}"`);
628
+ }
629
+ }
630
+ }
631
+ return problems;
632
+ }
633
+
634
+ // ../plugin/src/plugin.ts
635
+ var PERMISSIONS = [
636
+ "shell",
637
+ "process",
638
+ "filesystem",
639
+ "network",
640
+ "input",
641
+ "audio",
642
+ "clipboard"
643
+ ];
644
+ var ID = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/;
645
+ var NAMESPACE = /^[a-z][\w-]{0,31}$/;
646
+ var LOCAL_ID = /^[\w.-]+$/;
647
+ function defineAction(def) {
648
+ return {
649
+ ...def,
650
+ slots: def.slots ?? ["key"],
651
+ settings: def.settings ?? {}
652
+ };
653
+ }
654
+ function defineTrigger(def) {
655
+ return { ...def, settings: def.settings ?? {} };
656
+ }
657
+ function definePlugin(def) {
658
+ const problems = checkPlugin(def);
659
+ if (problems.length > 0) {
660
+ throw new TypeError(`invalid plugin "${def?.id}": ${problems.join("; ")}`);
661
+ }
662
+ return def;
663
+ }
664
+ function checkLocalIds(kind, items, problems) {
665
+ const seen = new Set;
666
+ for (const item of items) {
667
+ const name = typeof item?.id === "string" ? item.id : "?";
668
+ if (typeof item?.id !== "string" || !LOCAL_ID.test(item.id)) {
669
+ problems.push(`${kind} "${name}": id must be letters, digits, ".", "-" or "_"`);
670
+ } else if (seen.has(item.id)) {
671
+ problems.push(`${kind} "${name}" is defined twice`);
672
+ }
673
+ seen.add(name);
674
+ }
675
+ return seen;
676
+ }
677
+ function checkPlugin(value) {
678
+ if (!value || typeof value !== "object")
679
+ return ["not an object"];
680
+ const def = value;
681
+ const problems = [];
682
+ if (typeof def.id !== "string" || !ID.test(def.id)) {
683
+ problems.push("id must be a package-style name (lowercase, e.g. `my-plugin` or `@me/plugin`)");
684
+ }
685
+ if (typeof def.name !== "string" || def.name === "")
686
+ problems.push("name is required");
687
+ if (typeof def.version !== "string" || def.version === "")
688
+ problems.push("version is required");
689
+ if (def.namespace !== undefined && !NAMESPACE.test(def.namespace)) {
690
+ problems.push("namespace must be lowercase letters, digits, - or _ (starting with a letter)");
691
+ }
692
+ if (def.activate !== undefined && typeof def.activate !== "function") {
693
+ problems.push("activate must be a function");
694
+ }
695
+ if (def.permissions !== undefined) {
696
+ if (!Array.isArray(def.permissions))
697
+ problems.push("permissions must be an array");
698
+ else
699
+ for (const p of def.permissions)
700
+ if (!PERMISSIONS.includes(p))
701
+ problems.push(`unknown permission "${String(p)}"`);
702
+ }
703
+ if (def.settings !== undefined) {
704
+ for (const p of checkSchema(def.settings, def.optionSources ?? {})) {
705
+ problems.push(`plugin ${p}`);
706
+ }
707
+ }
708
+ if (def.commands !== undefined) {
709
+ if (!Array.isArray(def.commands))
710
+ problems.push("commands must be an array");
711
+ else {
712
+ checkLocalIds("command", def.commands, problems);
713
+ for (const c of def.commands) {
714
+ const name = typeof c?.id === "string" ? c.id : "?";
715
+ if (typeof c?.name !== "string")
716
+ problems.push(`command "${name}": name is required`);
717
+ if (typeof c?.run !== "function")
718
+ problems.push(`command "${name}": run is required`);
719
+ }
720
+ }
721
+ }
722
+ if (def.onboarding !== undefined)
723
+ problems.push(...checkOnboarding(def));
724
+ const sources = def.optionSources ?? {};
725
+ if (typeof sources !== "object")
726
+ problems.push("optionSources must be an object");
727
+ else
728
+ for (const [name, fn] of Object.entries(sources))
729
+ if (typeof fn !== "function")
730
+ problems.push(`option source "${name}" must be a function`);
731
+ if (!Array.isArray(def.actions))
732
+ return [...problems, "actions must be an array"];
733
+ checkLocalIds("action", def.actions, problems);
734
+ for (const action of def.actions) {
735
+ const name = typeof action?.id === "string" ? action.id : "?";
736
+ if (typeof action?.name !== "string")
737
+ problems.push(`action "${name}": name is required`);
738
+ const hasComponent = typeof action?.component === "function" || typeof action?.component === "object";
739
+ const hasRun = typeof action?.run === "function";
740
+ if (!hasComponent && !hasRun)
741
+ problems.push(`action "${name}": needs run or component`);
742
+ if (action?.look !== undefined && typeof action.look !== "function") {
743
+ problems.push(`action "${name}": look must be a function`);
744
+ }
745
+ const slots = action?.slots ?? ["key"];
746
+ if (!Array.isArray(slots) || slots.length === 0 || slots.some((s) => !["key", "sensor", "window"].includes(s))) {
747
+ problems.push(`action "${name}": slots must list "key", "sensor" and/or "window"`);
748
+ }
749
+ for (const p of checkSchema(action?.settings ?? {}, sources)) {
750
+ problems.push(`action "${name}": ${p}`);
751
+ }
752
+ for (const [key, field] of Object.entries(action?.settings ?? {})) {
753
+ if (field?.type === "secret") {
754
+ problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
755
+ }
756
+ }
757
+ }
758
+ if (def.state !== undefined) {
759
+ if (!Array.isArray(def.state))
760
+ problems.push("state must be an array");
761
+ else {
762
+ checkLocalIds("state", def.state, problems);
763
+ for (const s of def.state) {
764
+ const name = typeof s?.id === "string" ? s.id : "?";
765
+ if (typeof s?.name !== "string")
766
+ problems.push(`state "${name}": name is required`);
767
+ if (!["number", "string", "boolean", "json"].includes(s?.type)) {
768
+ problems.push(`state "${name}": type must be number, string, boolean or json`);
769
+ }
770
+ if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
771
+ problems.push(`state "${name}": poll needs read() and everyMs > 0`);
772
+ }
773
+ if (s?.start !== undefined && typeof s.start !== "function") {
774
+ problems.push(`state "${name}": start must be a function`);
775
+ }
776
+ }
777
+ }
778
+ }
779
+ if (def.triggers !== undefined) {
780
+ if (!Array.isArray(def.triggers))
781
+ problems.push("triggers must be an array");
782
+ else {
783
+ checkLocalIds("trigger", def.triggers, problems);
784
+ for (const t of def.triggers) {
785
+ const name = typeof t?.id === "string" ? t.id : "?";
786
+ if (typeof t?.name !== "string")
787
+ problems.push(`trigger "${name}": name is required`);
788
+ if (typeof t?.subscribe !== "function") {
789
+ problems.push(`trigger "${name}": subscribe is required`);
790
+ }
791
+ for (const p of checkSchema(t?.settings ?? {}, sources)) {
792
+ problems.push(`trigger "${name}": ${p}`);
793
+ }
794
+ }
795
+ }
796
+ }
797
+ return problems;
798
+ }
799
+ function checkOnboarding(def) {
800
+ const onboarding = def.onboarding;
801
+ if (!Array.isArray(onboarding?.steps))
802
+ return ["onboarding: steps must be an array"];
803
+ const problems = [];
804
+ checkLocalIds("onboarding step", onboarding.steps, problems);
805
+ const settings = def.settings ?? {};
806
+ const commands = new Set((def.commands ?? []).map((c) => c.id));
807
+ for (const step of onboarding.steps) {
808
+ const name = typeof step?.id === "string" ? step.id : "?";
809
+ if (typeof step?.title !== "string")
810
+ problems.push(`onboarding step "${name}": title is required`);
811
+ for (const key of step?.settings ?? []) {
812
+ if (!(key in settings))
813
+ problems.push(`onboarding step "${name}": no setting "${key}"`);
814
+ }
815
+ if (step?.command !== undefined && !commands.has(step.command)) {
816
+ problems.push(`onboarding step "${name}": no command "${step.command}"`);
817
+ }
818
+ if (step?.done !== undefined && typeof step.done !== "function") {
819
+ problems.push(`onboarding step "${name}": done must be a function`);
820
+ }
821
+ }
822
+ const page = onboarding.starterPage;
823
+ if (page) {
824
+ const actions = new Set((def.actions ?? []).map((a) => a.id));
825
+ const used = [
826
+ ...Object.values(page.keys ?? {}),
827
+ ...Object.values(page.sensors ?? {}),
828
+ ...page.window ? [page.window] : []
829
+ ];
830
+ for (const { action } of used) {
831
+ if (!actions.has(action))
832
+ problems.push(`onboarding starter page: no action "${action}"`);
833
+ }
834
+ }
835
+ return problems;
836
+ }
837
+ // ../plugin/src/shared.ts
838
+ class Shared {
839
+ #listeners = new Set;
840
+ #start;
841
+ #stop;
842
+ #last;
843
+ constructor(start) {
844
+ this.#start = start;
845
+ }
846
+ get last() {
847
+ return this.#last?.value;
848
+ }
849
+ listen(listener) {
850
+ this.#listeners.add(listener);
851
+ if (!this.#stop) {
852
+ this.#stop = this.#start((value) => {
853
+ this.#last = { value };
854
+ for (const l of [...this.#listeners])
855
+ l(value);
856
+ });
857
+ }
858
+ return () => {
859
+ this.#listeners.delete(listener);
860
+ if (this.#listeners.size === 0) {
861
+ this.#stop?.();
862
+ this.#stop = undefined;
863
+ this.#last = undefined;
864
+ }
865
+ };
866
+ }
867
+ }
868
+ // src/api.ts
869
+ import { createHash, randomBytes } from "crypto";
870
+ var SCOPES = [
871
+ "user-read-playback-state",
872
+ "user-modify-playback-state",
873
+ "user-read-currently-playing",
874
+ "user-library-read",
875
+ "user-library-modify",
876
+ "playlist-read-private",
877
+ "playlist-read-collaborative",
878
+ "playlist-modify-public",
879
+ "playlist-modify-private"
880
+ ];
881
+ var SPOTIFY = {
882
+ accounts: "https://accounts.spotify.com",
883
+ api: "https://api.spotify.com/v1"
884
+ };
885
+ function createPkce() {
886
+ const verifier = randomBytes(64).toString("base64url");
887
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
888
+ return { verifier, challenge };
889
+ }
890
+
891
+ class RateLimited extends Error {
892
+ retryAfterMs;
893
+ constructor(retryAfterMs) {
894
+ super(`Spotify asks to slow down for ${Math.ceil(retryAfterMs / 1000)} s`);
895
+ this.retryAfterMs = retryAfterMs;
896
+ }
897
+ }
898
+
899
+ class SignedOut extends Error {
900
+ constructor(message = "Sign in to Spotify from the plugin's page") {
901
+ super(message);
902
+ }
903
+ }
904
+ var REASONS = {
905
+ PREMIUM_REQUIRED: "Spotify only lets Premium accounts control playback",
906
+ NO_ACTIVE_DEVICE: "nothing is playing: start Spotify on a device first"
907
+ };
908
+ var page = (message) => new Response(`<!doctype html><meta charset="utf-8"><title>sdeck</title><p>${message}</p>`, {
909
+ headers: { "content-type": "text/html; charset=utf-8" }
910
+ });
911
+
912
+ class SpotifyClient {
913
+ #options;
914
+ #endpoints;
915
+ #fetch;
916
+ #access;
917
+ #refreshing;
918
+ constructor(options) {
919
+ this.#options = options;
920
+ this.#endpoints = options.endpoints ?? SPOTIFY;
921
+ this.#fetch = options.fetch ?? fetch;
922
+ }
923
+ get signedIn() {
924
+ return this.#options.tokens.get() !== undefined;
925
+ }
926
+ signIn(port, timeoutMs = 300000) {
927
+ const clientId = this.#options.clientId();
928
+ if (!clientId)
929
+ throw new Error("set your Spotify client id first");
930
+ const { verifier, challenge } = createPkce();
931
+ const state = randomBytes(16).toString("base64url");
932
+ let finish = () => {};
933
+ const done = new Promise((resolve, reject) => {
934
+ finish = (error) => error ? reject(error) : resolve();
935
+ });
936
+ const server = Bun.serve({
937
+ hostname: "127.0.0.1",
938
+ port,
939
+ fetch: async (request) => {
940
+ const url = new URL(request.url);
941
+ if (url.pathname !== "/callback")
942
+ return new Response("not found", { status: 404 });
943
+ if (url.searchParams.get("state") !== state) {
944
+ return new Response("wrong state", { status: 400 });
945
+ }
946
+ const code = url.searchParams.get("code");
947
+ if (!code) {
948
+ close(new Error(`Spotify said: ${url.searchParams.get("error") ?? "no code"}`));
949
+ return page("sdeck was not given access. You can close this tab.");
950
+ }
951
+ try {
952
+ await this.#token({
953
+ grant_type: "authorization_code",
954
+ code,
955
+ redirect_uri: redirect,
956
+ code_verifier: verifier
957
+ });
958
+ close();
959
+ return page("sdeck is connected to Spotify. You can close this tab.");
960
+ } catch (error) {
961
+ close(error);
962
+ return page("Signing in failed. See the plugin's page in sdeck.");
963
+ }
964
+ }
965
+ });
966
+ const redirect = `http://127.0.0.1:${server.port}/callback`;
967
+ const timer = setTimeout(() => close(new Error("signing in timed out")), timeoutMs);
968
+ let closed = false;
969
+ const close = (error) => {
970
+ if (closed)
971
+ return;
972
+ closed = true;
973
+ clearTimeout(timer);
974
+ setTimeout(() => server.stop(), 100);
975
+ finish(error);
976
+ };
977
+ const url = new URL("/authorize", this.#endpoints.accounts);
978
+ url.search = new URLSearchParams({
979
+ client_id: clientId,
980
+ response_type: "code",
981
+ redirect_uri: redirect,
982
+ scope: SCOPES.join(" "),
983
+ state,
984
+ code_challenge_method: "S256",
985
+ code_challenge: challenge
986
+ }).toString();
987
+ return { url: url.toString(), done, cancel: () => close(new Error("sign-in cancelled")) };
988
+ }
989
+ async signOut() {
990
+ this.#access = undefined;
991
+ await this.#options.tokens.set(undefined);
992
+ }
993
+ async request(method, path, query = {}, body) {
994
+ const url = new URL(`${this.#endpoints.api}${path}`);
995
+ for (const [key, value] of Object.entries(query))
996
+ url.searchParams.set(key, value);
997
+ for (let attempt = 0;; attempt++) {
998
+ const token = await this.#accessToken();
999
+ const response = await this.#fetch(url, {
1000
+ method,
1001
+ headers: {
1002
+ authorization: `Bearer ${token}`,
1003
+ ...body !== undefined && { "content-type": "application/json" }
1004
+ },
1005
+ ...body !== undefined && { body: JSON.stringify(body) },
1006
+ signal: AbortSignal.timeout(1e4)
1007
+ });
1008
+ if (response.status === 401 && attempt === 0) {
1009
+ this.#access = undefined;
1010
+ continue;
1011
+ }
1012
+ if (response.status === 429) {
1013
+ throw new RateLimited(Number(response.headers.get("retry-after") ?? 5) * 1000);
1014
+ }
1015
+ const text = await response.text();
1016
+ let answer;
1017
+ try {
1018
+ answer = text ? JSON.parse(text) : undefined;
1019
+ } catch {
1020
+ answer = undefined;
1021
+ }
1022
+ if (!response.ok) {
1023
+ const error = answer?.error;
1024
+ if (response.status === 403 && /scope/i.test(error?.message ?? "")) {
1025
+ throw new Error("Sign in to Spotify again to allow this (sdeck asks for more now)");
1026
+ }
1027
+ throw new Error(REASONS[error?.reason ?? ""] ?? error?.message ?? `Spotify answered ${response.status}`);
1028
+ }
1029
+ return answer;
1030
+ }
1031
+ }
1032
+ async#accessToken() {
1033
+ if (this.#access && Date.now() < this.#access.expires)
1034
+ return this.#access.token;
1035
+ const refresh = this.#options.tokens.get();
1036
+ if (!refresh)
1037
+ throw new SignedOut;
1038
+ this.#refreshing ??= this.#token({
1039
+ grant_type: "refresh_token",
1040
+ refresh_token: refresh
1041
+ }).finally(() => {
1042
+ this.#refreshing = undefined;
1043
+ });
1044
+ return this.#refreshing;
1045
+ }
1046
+ async#token(fields) {
1047
+ const response = await this.#fetch(new URL("/api/token", this.#endpoints.accounts), {
1048
+ method: "POST",
1049
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1050
+ body: new URLSearchParams({ ...fields, client_id: this.#options.clientId() }),
1051
+ signal: AbortSignal.timeout(1e4)
1052
+ });
1053
+ const body = await response.json().catch(() => ({}));
1054
+ if (!response.ok || !body.access_token) {
1055
+ if (body.error === "invalid_grant") {
1056
+ await this.signOut();
1057
+ throw new SignedOut("The Spotify sign-in expired: sign in again");
1058
+ }
1059
+ throw new Error(body.error_description ?? body.error ?? "Spotify gave no token");
1060
+ }
1061
+ if (body.refresh_token)
1062
+ await this.#options.tokens.set(body.refresh_token);
1063
+ const lifetime = Math.max(0, (body.expires_in ?? 3600) - 60);
1064
+ this.#access = { token: body.access_token, expires: Date.now() + lifetime * 1000 };
1065
+ return body.access_token;
1066
+ }
1067
+ }
1068
+ var IDLE = {
1069
+ playing: false,
1070
+ uri: "",
1071
+ track: "",
1072
+ artist: "",
1073
+ album: "",
1074
+ art: "",
1075
+ progress: 0,
1076
+ positionMs: 0,
1077
+ durationMs: 0,
1078
+ volume: undefined,
1079
+ shuffle: false,
1080
+ repeat: "off",
1081
+ device: "",
1082
+ deviceId: "",
1083
+ context: ""
1084
+ };
1085
+ function parsePlayer(body) {
1086
+ if (typeof body !== "object" || body === null)
1087
+ return IDLE;
1088
+ const raw = body;
1089
+ const item = raw.item ?? undefined;
1090
+ const images = item?.album?.images ?? item?.images ?? [];
1091
+ const art = [...images].sort((a, b) => Math.abs((a.width ?? 0) - 300) - Math.abs((b.width ?? 0) - 300))[0]?.url ?? "";
1092
+ const duration = item?.duration_ms ?? 0;
1093
+ const position = raw.progress_ms ?? 0;
1094
+ return {
1095
+ playing: raw.is_playing === true,
1096
+ uri: item?.uri ?? "",
1097
+ track: item?.name ?? "",
1098
+ artist: item?.artists?.map((a) => a.name).join(", ") ?? item?.show?.name ?? "",
1099
+ album: item?.album?.name ?? "",
1100
+ art,
1101
+ progress: duration > 0 ? Math.round(100 * position / duration) : 0,
1102
+ positionMs: position,
1103
+ durationMs: duration,
1104
+ volume: raw.device?.volume_percent ?? undefined,
1105
+ shuffle: raw.shuffle_state === true,
1106
+ repeat: raw.repeat_state === "track" || raw.repeat_state === "context" ? raw.repeat_state : "off",
1107
+ device: raw.device?.name ?? "",
1108
+ deviceId: raw.device?.id ?? "",
1109
+ context: raw.context?.uri ?? ""
1110
+ };
1111
+ }
1112
+ var KINDS = ["track", "episode", "album", "playlist", "artist", "show"];
1113
+ function spotifyUri(text) {
1114
+ const trimmed = text.trim();
1115
+ const fromUri = /^spotify:([a-z]+):([A-Za-z0-9]+)$/.exec(trimmed);
1116
+ const fromLink = /^https?:\/\/open\.spotify\.com\/(?:intl-[a-z-]+\/)?([a-z]+)\/([A-Za-z0-9]+)(?:[/?#].*)?$/i.exec(trimmed);
1117
+ const [, kind, id] = fromUri ?? fromLink ?? [];
1118
+ if (!kind || !id || !KINDS.includes(kind))
1119
+ return;
1120
+ return { uri: `spotify:${kind}:${id}`, kind };
1121
+ }
1122
+ function playBody(uri, kind) {
1123
+ return kind === "track" || kind === "episode" ? { uris: [uri] } : { context_uri: uri };
1124
+ }
1125
+ function parsePlaylists(body, me) {
1126
+ const items = body?.items ?? [];
1127
+ return items.flatMap((item) => {
1128
+ const p = item;
1129
+ if (!p?.id || !p.uri)
1130
+ return [];
1131
+ return [
1132
+ {
1133
+ id: p.id,
1134
+ uri: p.uri,
1135
+ name: p.name || "Untitled playlist",
1136
+ writable: p.owner?.id === me || p.collaborative === true
1137
+ }
1138
+ ];
1139
+ });
1140
+ }
1141
+ function parseDevices(body) {
1142
+ const devices = body?.devices ?? [];
1143
+ return devices.flatMap((item) => {
1144
+ const d = item;
1145
+ if (!d?.id || d.is_restricted)
1146
+ return [];
1147
+ return [{ id: d.id, name: d.name ?? d.id, type: d.type ?? "", active: d.is_active === true }];
1148
+ });
1149
+ }
1150
+
1151
+ // src/panels.tsx
1152
+ import { jsx, jsxs } from "react/jsx-runtime";
1153
+ var GREEN = "#1ed760";
1154
+ var BACKGROUND = "#121212";
1155
+ var MUTED = "#a7a7a7";
1156
+ var FAINT = "#2a2a2a";
1157
+ var disc = (color, opacity = 1) => `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100"><circle cx="50" cy="50" r="50" fill="${color}" fill-opacity="${opacity}"/></svg>`)}`;
1158
+ var box = { display: "flex" };
1159
+ function Icon({ icon, size, color }) {
1160
+ const src = useImage(`icon:${icon}`, color);
1161
+ return src ? /* @__PURE__ */ jsx("img", {
1162
+ src,
1163
+ width: size,
1164
+ height: size,
1165
+ alt: ""
1166
+ }) : /* @__PURE__ */ jsx("div", {
1167
+ style: { ...box, width: size, height: size }
1168
+ });
1169
+ }
1170
+ function Progress({ value, height }) {
1171
+ return /* @__PURE__ */ jsx("div", {
1172
+ style: { ...box, width: "100%", height, background: "rgba(255,255,255,0.18)" },
1173
+ children: /* @__PURE__ */ jsx("div", {
1174
+ style: {
1175
+ ...box,
1176
+ width: `${Math.min(100, Math.max(0, value))}%`,
1177
+ height,
1178
+ background: GREEN
1179
+ }
1180
+ })
1181
+ });
1182
+ }
1183
+ function useNowPlaying() {
1184
+ const asText = (value) => typeof value === "string" ? value : "";
1185
+ const track = asText(useHostState("spotify.track"));
1186
+ const artist = asText(useHostState("spotify.artist"));
1187
+ const artUrl = asText(useHostState("spotify.art"));
1188
+ const progress = Number(useHostState("spotify.progress") ?? 0) || 0;
1189
+ const playing = useHostState("spotify.playing") === true;
1190
+ const liked = useHostState("spotify.liked") === true;
1191
+ const art = useImage(artUrl);
1192
+ return { track, artist, art, progress, playing, liked };
1193
+ }
1194
+ function NowPlaying({ kind }) {
1195
+ const { track, artist, art, progress, playing, liked } = useNowPlaying();
1196
+ if (kind === "sensor") {
1197
+ return /* @__PURE__ */ jsxs("div", {
1198
+ style: {
1199
+ ...box,
1200
+ width: "100%",
1201
+ height: "100%",
1202
+ alignItems: "center",
1203
+ background: BACKGROUND,
1204
+ gap: 4,
1205
+ padding: "0 4px"
1206
+ },
1207
+ children: [
1208
+ /* @__PURE__ */ jsx(Icon, {
1209
+ icon: playing ? "tb/TbPlayerPlayFilled" : "tb/TbPlayerPauseFilled",
1210
+ size: 10,
1211
+ color: playing ? GREEN : MUTED
1212
+ }),
1213
+ /* @__PURE__ */ jsx("div", {
1214
+ style: { ...box, flexGrow: 1 },
1215
+ children: /* @__PURE__ */ jsx(Progress, {
1216
+ value: track ? progress : 0,
1217
+ height: 4
1218
+ })
1219
+ })
1220
+ ]
1221
+ });
1222
+ }
1223
+ if (!track) {
1224
+ return /* @__PURE__ */ jsxs("div", {
1225
+ style: {
1226
+ ...box,
1227
+ width: "100%",
1228
+ height: "100%",
1229
+ flexDirection: kind === "window" ? "row" : "column",
1230
+ alignItems: "center",
1231
+ justifyContent: "center",
1232
+ gap: 8,
1233
+ background: BACKGROUND
1234
+ },
1235
+ children: [
1236
+ /* @__PURE__ */ jsx(Icon, {
1237
+ icon: "si/SiSpotify",
1238
+ size: kind === "window" ? 30 : 40,
1239
+ color: GREEN
1240
+ }),
1241
+ /* @__PURE__ */ jsx("div", {
1242
+ style: { ...box, color: MUTED, fontSize: kind === "window" ? 15 : 11, fontWeight: 700 },
1243
+ children: "Not playing"
1244
+ })
1245
+ ]
1246
+ });
1247
+ }
1248
+ if (kind === "window") {
1249
+ return /* @__PURE__ */ jsxs("div", {
1250
+ style: {
1251
+ ...box,
1252
+ width: "100%",
1253
+ height: "100%",
1254
+ flexDirection: "column",
1255
+ background: BACKGROUND
1256
+ },
1257
+ children: [
1258
+ /* @__PURE__ */ jsxs("div", {
1259
+ style: { ...box, flexGrow: 1, alignItems: "center", gap: 10, padding: "0 10px 0 0" },
1260
+ children: [
1261
+ art ? /* @__PURE__ */ jsx("img", {
1262
+ src: art,
1263
+ width: 55,
1264
+ height: 55,
1265
+ alt: ""
1266
+ }) : /* @__PURE__ */ jsx("div", {
1267
+ style: {
1268
+ ...box,
1269
+ width: 55,
1270
+ height: 55,
1271
+ background: FAINT,
1272
+ alignItems: "center",
1273
+ justifyContent: "center"
1274
+ },
1275
+ children: /* @__PURE__ */ jsx(Icon, {
1276
+ icon: "lucide/music",
1277
+ size: 26,
1278
+ color: MUTED
1279
+ })
1280
+ }),
1281
+ /* @__PURE__ */ jsxs("div", {
1282
+ style: {
1283
+ ...box,
1284
+ flexDirection: "column",
1285
+ flexGrow: 1,
1286
+ flexShrink: 1,
1287
+ minWidth: 0,
1288
+ fontWeight: 700
1289
+ },
1290
+ children: [
1291
+ /* @__PURE__ */ jsx("div", {
1292
+ style: {
1293
+ ...box,
1294
+ color: "#ffffff",
1295
+ fontSize: 15,
1296
+ overflow: "hidden",
1297
+ whiteSpace: "nowrap"
1298
+ },
1299
+ children: track
1300
+ }),
1301
+ /* @__PURE__ */ jsx("div", {
1302
+ style: {
1303
+ ...box,
1304
+ color: MUTED,
1305
+ fontSize: 12,
1306
+ overflow: "hidden",
1307
+ whiteSpace: "nowrap"
1308
+ },
1309
+ children: artist
1310
+ })
1311
+ ]
1312
+ }),
1313
+ liked ? /* @__PURE__ */ jsx(Icon, {
1314
+ icon: "tb/TbHeartFilled",
1315
+ size: 16,
1316
+ color: GREEN
1317
+ }) : null,
1318
+ /* @__PURE__ */ jsx(Icon, {
1319
+ icon: playing ? "tb/TbPlayerPauseFilled" : "tb/TbPlayerPlayFilled",
1320
+ size: 20,
1321
+ color: playing ? "#ffffff" : GREEN
1322
+ })
1323
+ ]
1324
+ }),
1325
+ /* @__PURE__ */ jsx(Progress, {
1326
+ value: progress,
1327
+ height: 3
1328
+ })
1329
+ ]
1330
+ });
1331
+ }
1332
+ return /* @__PURE__ */ jsxs("div", {
1333
+ style: {
1334
+ ...box,
1335
+ width: "100%",
1336
+ height: "100%",
1337
+ position: "relative",
1338
+ background: BACKGROUND
1339
+ },
1340
+ children: [
1341
+ art ? /* @__PURE__ */ jsx("img", {
1342
+ src: art,
1343
+ width: 96,
1344
+ height: 96,
1345
+ alt: "",
1346
+ style: { position: "absolute", left: 0, top: 0, width: "100%", height: "100%" }
1347
+ }) : null,
1348
+ /* @__PURE__ */ jsxs("div", {
1349
+ style: {
1350
+ ...box,
1351
+ position: "absolute",
1352
+ left: 0,
1353
+ right: 0,
1354
+ bottom: 0,
1355
+ flexDirection: "column",
1356
+ padding: "14px 6px 0 6px",
1357
+ backgroundImage: "linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.88) 45%)",
1358
+ fontWeight: 700
1359
+ },
1360
+ children: [
1361
+ /* @__PURE__ */ jsx("div", {
1362
+ style: {
1363
+ ...box,
1364
+ color: "#ffffff",
1365
+ fontSize: 12,
1366
+ overflow: "hidden",
1367
+ whiteSpace: "nowrap"
1368
+ },
1369
+ children: track
1370
+ }),
1371
+ /* @__PURE__ */ jsx("div", {
1372
+ style: {
1373
+ ...box,
1374
+ color: "#d4d4d4",
1375
+ fontSize: 10,
1376
+ overflow: "hidden",
1377
+ whiteSpace: "nowrap",
1378
+ marginBottom: 5
1379
+ },
1380
+ children: artist
1381
+ }),
1382
+ /* @__PURE__ */ jsx("div", {
1383
+ style: { ...box, margin: "0 -6px" },
1384
+ children: /* @__PURE__ */ jsx(Progress, {
1385
+ value: progress,
1386
+ height: 3
1387
+ })
1388
+ })
1389
+ ]
1390
+ }),
1391
+ playing ? null : /* @__PURE__ */ jsx("div", {
1392
+ style: {
1393
+ ...box,
1394
+ position: "absolute",
1395
+ right: 6,
1396
+ top: 6,
1397
+ width: 26,
1398
+ height: 26,
1399
+ borderRadius: 13,
1400
+ alignItems: "center",
1401
+ justifyContent: "center",
1402
+ background: GREEN
1403
+ },
1404
+ children: /* @__PURE__ */ jsx(Icon, {
1405
+ icon: "tb/TbPlayerPlayFilled",
1406
+ size: 14,
1407
+ color: "#000000"
1408
+ })
1409
+ })
1410
+ ]
1411
+ });
1412
+ }
1413
+
1414
+ // src/index.tsx
1415
+ import { jsx as jsx2 } from "react/jsx-runtime";
1416
+ var DEFAULT_PORT = 43821;
1417
+ var POLL_MS = 3000;
1418
+ var context;
1419
+ var signingIn;
1420
+ var spotify = new SpotifyClient({
1421
+ clientId: () => String(context?.settings().clientId ?? "").trim(),
1422
+ tokens: {
1423
+ get: () => context?.secrets.get("refreshToken"),
1424
+ set: async (token) => {
1425
+ await context?.secrets.set("refreshToken", token);
1426
+ }
1427
+ }
1428
+ });
1429
+ var pollNow = () => {};
1430
+ var player = new Shared((emit) => {
1431
+ let stopped = false;
1432
+ let timer;
1433
+ let running = false;
1434
+ const tick = async () => {
1435
+ if (running || stopped)
1436
+ return;
1437
+ running = true;
1438
+ clearTimeout(timer);
1439
+ let wait = POLL_MS;
1440
+ try {
1441
+ const next = parsePlayer(await spotify.request("GET", "/me/player"));
1442
+ if (!stopped)
1443
+ emit(next);
1444
+ context?.status("Signed in to Spotify", "ok");
1445
+ } catch (error) {
1446
+ if (!stopped)
1447
+ emit(undefined);
1448
+ if (error instanceof RateLimited)
1449
+ wait = error.retryAfterMs;
1450
+ else if (error instanceof SignedOut)
1451
+ wait = 1e4;
1452
+ context?.status(error.message, error instanceof SignedOut ? "info" : "error");
1453
+ }
1454
+ running = false;
1455
+ if (!stopped)
1456
+ timer = setTimeout(tick, wait);
1457
+ };
1458
+ pollNow = () => {
1459
+ clearTimeout(timer);
1460
+ timer = setTimeout(tick, 400);
1461
+ };
1462
+ tick();
1463
+ return () => {
1464
+ stopped = true;
1465
+ clearTimeout(timer);
1466
+ pollNow = () => {};
1467
+ };
1468
+ });
1469
+ var readPlayer = async () => parsePlayer(await spotify.request("GET", "/me/player"));
1470
+ async function command(method, path, query, body) {
1471
+ await spotify.request(method, path, query, body);
1472
+ pollNow();
1473
+ }
1474
+ async function current() {
1475
+ const now = await readPlayer();
1476
+ if (!now.uri)
1477
+ throw new Error("nothing is playing");
1478
+ return now;
1479
+ }
1480
+ var isLiked = async (uri) => (await spotify.request("GET", "/me/library/contains", { uris: uri }))[0] === true;
1481
+ var likedNow = () => {};
1482
+ var liked = new Shared((emit) => {
1483
+ let uri = "";
1484
+ let checkedAt = 0;
1485
+ let stopped = false;
1486
+ const off = player.listen((p) => {
1487
+ const next = p?.uri ?? "";
1488
+ if (next === uri && Date.now() - checkedAt < 30000)
1489
+ return;
1490
+ uri = next;
1491
+ checkedAt = Date.now();
1492
+ if (!next)
1493
+ return emit(undefined);
1494
+ isLiked(next).then((value) => !stopped && uri === next && emit(value), () => !stopped && uri === next && emit(undefined));
1495
+ });
1496
+ likedNow = (track, value) => {
1497
+ if (track !== uri)
1498
+ return;
1499
+ checkedAt = Date.now();
1500
+ emit(value);
1501
+ };
1502
+ return () => {
1503
+ stopped = true;
1504
+ off();
1505
+ likedNow = () => {};
1506
+ };
1507
+ });
1508
+ var setLiked = async (uri, value) => {
1509
+ await spotify.request(value ? "PUT" : "DELETE", "/me/library", { uris: uri });
1510
+ likedNow(uri, value);
1511
+ };
1512
+ var me;
1513
+ function userId() {
1514
+ me ??= spotify.request("GET", "/me").then((body) => {
1515
+ const id = body?.id;
1516
+ if (!id)
1517
+ throw new Error("Spotify did not say who is signed in");
1518
+ return id;
1519
+ });
1520
+ me.catch(() => {
1521
+ me = undefined;
1522
+ });
1523
+ return me;
1524
+ }
1525
+ async function playlists() {
1526
+ const id = await userId();
1527
+ const all = [];
1528
+ for (let offset = 0;offset < 200; offset += 50) {
1529
+ const page = await spotify.request("GET", "/me/playlists", {
1530
+ limit: "50",
1531
+ offset: String(offset)
1532
+ });
1533
+ const found = parsePlaylists(page, id);
1534
+ all.push(...found);
1535
+ if (!page?.next)
1536
+ break;
1537
+ }
1538
+ return all;
1539
+ }
1540
+ var key = (icon, caption = "", color = "#ffffff") => iconLook({ icon, caption, background: BACKGROUND, color });
1541
+ var dot = (active) => iconLayer("dot", disc(GREEN), { size: 7, position: "bottom", visible: active });
1542
+ var switched = (active, on, off, colors) => [
1543
+ iconLayer("on", on, { color: colors.on, size: 58, visible: active }),
1544
+ iconLayer("off", off, { color: colors.off, size: 58, visible: `!(${active})` })
1545
+ ];
1546
+ var setPlaying = (play) => command("PUT", play ? "/me/player/play" : "/me/player/pause");
1547
+ var playPause = defineAction({
1548
+ id: "play-pause",
1549
+ name: "Play / pause",
1550
+ description: "Shows the cover of what is playing; pressing it plays or pauses.",
1551
+ category: "Spotify",
1552
+ icon: "play",
1553
+ slots: ["key", "sensor"],
1554
+ settings: {
1555
+ cover: { type: "boolean", label: "Show the cover art", default: true }
1556
+ },
1557
+ run: async () => {
1558
+ const before = (await readPlayer()).playing;
1559
+ await setPlaying(!before);
1560
+ return { label: before ? "Pause" : "Play", undo: () => setPlaying(before) };
1561
+ },
1562
+ look: (s) => {
1563
+ const centered = (size) => {
1564
+ const at = (100 - size) / 2;
1565
+ return { x: at, y: at, width: size, height: size };
1566
+ };
1567
+ const button = (visible) => [
1568
+ iconLayer("disc", disc(GREEN), { frame: centered(70), visible }),
1569
+ iconLayer("pause", "tb/TbPlayerPauseFilled", {
1570
+ color: "#000000",
1571
+ frame: centered(34),
1572
+ visible: `(${visible}) && spotify.playing`
1573
+ }),
1574
+ iconLayer("play", "tb/TbPlayerPlayFilled", {
1575
+ color: "#000000",
1576
+ frame: { ...centered(34), x: 35 },
1577
+ visible: `(${visible}) && !spotify.playing`
1578
+ })
1579
+ ];
1580
+ if (!s.cover)
1581
+ return { background: BACKGROUND, layers: button("true") };
1582
+ return {
1583
+ background: BACKGROUND,
1584
+ layers: [
1585
+ iconLayer("cover", "{{spotify.art}}", { frame: centered(100), visible: "spotify.art" }),
1586
+ iconLayer("shade", disc("#000000", 0.6), {
1587
+ frame: centered(48),
1588
+ visible: "spotify.art && !spotify.playing"
1589
+ }),
1590
+ iconLayer("resume", "tb/TbPlayerPlayFilled", {
1591
+ frame: { ...centered(24), x: 39 },
1592
+ visible: "spotify.art && !spotify.playing"
1593
+ }),
1594
+ ...button("!spotify.art")
1595
+ ]
1596
+ };
1597
+ }
1598
+ });
1599
+ var skip = (id, name, icon, back) => defineAction({
1600
+ id,
1601
+ name,
1602
+ category: "Spotify",
1603
+ icon,
1604
+ slots: ["key", "sensor"],
1605
+ run: async () => {
1606
+ await command("POST", `/me/player/${id}`);
1607
+ return { label: name, undo: () => command("POST", `/me/player/${back}`) };
1608
+ },
1609
+ look: () => key(id === "next" ? "tb/TbPlayerSkipForwardFilled" : "tb/TbPlayerSkipBackFilled")
1610
+ });
1611
+ var next = skip("next", "Next track", "skip-forward", "previous");
1612
+ var previous = skip("previous", "Previous track", "skip-back", "next");
1613
+ var nowPlaying = defineAction({
1614
+ id: "now-playing",
1615
+ name: "Now playing",
1616
+ description: "The current track and artist, with how far through it is.",
1617
+ category: "Spotify",
1618
+ icon: "music",
1619
+ slots: ["window", "key", "sensor"],
1620
+ settings: {
1621
+ press: {
1622
+ type: "select",
1623
+ label: "When pressed",
1624
+ default: "play-pause",
1625
+ options: [
1626
+ { value: "play-pause", label: "Play or pause" },
1627
+ { value: "next", label: "Next track" },
1628
+ { value: "like", label: "Like or unlike" },
1629
+ { value: "none", label: "Nothing" }
1630
+ ]
1631
+ }
1632
+ },
1633
+ run: async () => ({ result: await readPlayer() }),
1634
+ component: ({ settings, slot, plugin }) => {
1635
+ const act = () => {
1636
+ const press = settings.press;
1637
+ if (press === "none")
1638
+ return;
1639
+ const done = press === "next" ? command("POST", "/me/player/next") : press === "like" ? current().then(async ({ uri }) => setLiked(uri, !await isLiked(uri))) : readPlayer().then((p) => setPlaying(!p.playing));
1640
+ done.catch((error) => plugin.log("now playing:", error.message));
1641
+ };
1642
+ useKeyPress(slot.kind === "key" ? act : undefined, {
1643
+ key: slot.kind === "key" ? slot.index : -1
1644
+ });
1645
+ useSensorPress(slot.kind === "sensor" ? act : undefined, {
1646
+ sensor: slot.kind === "sensor" ? slot.index : -1
1647
+ });
1648
+ return /* @__PURE__ */ jsx2(NowPlaying, {
1649
+ kind: slot.kind
1650
+ });
1651
+ }
1652
+ });
1653
+ var unmuted = 50;
1654
+ var volume = defineAction({
1655
+ id: "volume",
1656
+ name: "Spotify volume",
1657
+ category: "Spotify",
1658
+ icon: "volume-1",
1659
+ slots: ["key", "sensor"],
1660
+ settings: {
1661
+ operation: {
1662
+ type: "select",
1663
+ label: "When pressed",
1664
+ default: "up",
1665
+ options: [
1666
+ { value: "up", label: "Volume up" },
1667
+ { value: "down", label: "Volume down" },
1668
+ { value: "set", label: "Set a level" },
1669
+ { value: "mute", label: "Mute / unmute" }
1670
+ ]
1671
+ },
1672
+ step: {
1673
+ type: "number",
1674
+ label: "Step (%)",
1675
+ default: 10,
1676
+ min: 1,
1677
+ max: 50,
1678
+ visibleIf: { operation: ["up", "down"] }
1679
+ },
1680
+ level: {
1681
+ type: "number",
1682
+ label: "Level (%)",
1683
+ default: 50,
1684
+ min: 0,
1685
+ max: 100,
1686
+ visibleIf: { operation: "set" }
1687
+ }
1688
+ },
1689
+ run: async ({ settings }) => {
1690
+ const before = (await readPlayer()).volume;
1691
+ if (before === undefined)
1692
+ throw new Error("this device does not report its volume");
1693
+ const { operation, step } = settings;
1694
+ if (operation === "mute" && before > 0)
1695
+ unmuted = before;
1696
+ const wanted = operation === "mute" ? before > 0 ? 0 : unmuted : operation === "set" ? settings.level : before + (operation === "up" ? step : -step);
1697
+ const level = Math.min(100, Math.max(0, Math.round(wanted)));
1698
+ const set = (value) => command("PUT", "/me/player/volume", { volume_percent: String(value) });
1699
+ await set(level);
1700
+ return { result: level, label: `Spotify volume ${level}%`, undo: () => set(before) };
1701
+ },
1702
+ look: (s) => {
1703
+ const icon = s.operation === "mute" ? "lucide/volume-x" : s.operation === "down" ? "lucide/volume-1" : "lucide/volume-2";
1704
+ const level = {
1705
+ id: "level",
1706
+ type: "bar",
1707
+ value: "spotify.volume ?? 0",
1708
+ color: GREEN,
1709
+ track: FAINT,
1710
+ position: "bottom",
1711
+ thickness: 6
1712
+ };
1713
+ if (s.operation === "mute") {
1714
+ return {
1715
+ background: BACKGROUND,
1716
+ layers: [
1717
+ ...switched("spotify.volume == 0", icon, "lucide/volume-2", {
1718
+ on: "#f87171",
1719
+ off: "#ffffff"
1720
+ }),
1721
+ level
1722
+ ]
1723
+ };
1724
+ }
1725
+ return {
1726
+ background: BACKGROUND,
1727
+ layers: [
1728
+ iconLayer("icon", icon, {
1729
+ color: "#ffffff",
1730
+ size: s.operation === "set" ? 42 : 52,
1731
+ position: s.operation === "set" ? "top" : "middle"
1732
+ }),
1733
+ ...s.operation === "set" ? [textLayer("label", `${s.level}%`, { color: MUTED, size: 14, position: "bottom" })] : [],
1734
+ level
1735
+ ]
1736
+ };
1737
+ }
1738
+ });
1739
+ var shuffle = defineAction({
1740
+ id: "shuffle",
1741
+ name: "Shuffle",
1742
+ category: "Spotify",
1743
+ icon: "shuffle",
1744
+ slots: ["key", "sensor"],
1745
+ run: async () => {
1746
+ const before = (await readPlayer()).shuffle;
1747
+ const set = (state) => command("PUT", "/me/player/shuffle", { state: String(state) });
1748
+ await set(!before);
1749
+ return { result: !before, label: `Shuffle ${before ? "off" : "on"}`, undo: () => set(before) };
1750
+ },
1751
+ look: () => ({
1752
+ background: BACKGROUND,
1753
+ layers: [
1754
+ ...switched("spotify.shuffle", "lucide/shuffle", "lucide/shuffle", {
1755
+ on: GREEN,
1756
+ off: MUTED
1757
+ }),
1758
+ dot("spotify.shuffle")
1759
+ ]
1760
+ })
1761
+ });
1762
+ function nextRepeat(mode) {
1763
+ return mode === "off" ? "context" : mode === "context" ? "track" : "off";
1764
+ }
1765
+ var repeat = defineAction({
1766
+ id: "repeat",
1767
+ name: "Repeat",
1768
+ description: "Cycles repeat: off, the playlist, one track.",
1769
+ category: "Spotify",
1770
+ icon: "repeat",
1771
+ slots: ["key", "sensor"],
1772
+ run: async () => {
1773
+ const before = (await readPlayer()).repeat;
1774
+ const state = nextRepeat(before);
1775
+ const set = (value) => command("PUT", "/me/player/repeat", { state: value });
1776
+ await set(state);
1777
+ return { result: state, label: `Repeat ${state}`, undo: () => set(before) };
1778
+ },
1779
+ look: () => ({
1780
+ background: BACKGROUND,
1781
+ layers: [
1782
+ iconLayer("off", "lucide/repeat", {
1783
+ color: MUTED,
1784
+ size: 58,
1785
+ visible: 'spotify.repeat != "context" && spotify.repeat != "track"'
1786
+ }),
1787
+ iconLayer("all", "lucide/repeat", {
1788
+ color: GREEN,
1789
+ size: 58,
1790
+ visible: 'spotify.repeat == "context"'
1791
+ }),
1792
+ iconLayer("one", "lucide/repeat-1", {
1793
+ color: GREEN,
1794
+ size: 58,
1795
+ visible: 'spotify.repeat == "track"'
1796
+ }),
1797
+ dot('spotify.repeat == "context" || spotify.repeat == "track"')
1798
+ ]
1799
+ })
1800
+ });
1801
+ var like = defineAction({
1802
+ id: "like",
1803
+ name: "Like",
1804
+ description: "Adds what is playing to Liked Songs, or takes it out. Lit while it is liked.",
1805
+ category: "Spotify",
1806
+ icon: "heart",
1807
+ slots: ["key", "sensor"],
1808
+ settings: {
1809
+ mode: {
1810
+ type: "select",
1811
+ label: "When pressed",
1812
+ default: "toggle",
1813
+ options: [
1814
+ { value: "toggle", label: "Like / unlike" },
1815
+ { value: "like", label: "Like" },
1816
+ { value: "unlike", label: "Unlike" }
1817
+ ]
1818
+ }
1819
+ },
1820
+ run: async ({ settings }) => {
1821
+ const { uri, track } = await current();
1822
+ const before = await isLiked(uri);
1823
+ const after = settings.mode === "toggle" ? !before : settings.mode === "like";
1824
+ if (after !== before)
1825
+ await setLiked(uri, after);
1826
+ return {
1827
+ result: after,
1828
+ label: `${after ? "Liked" : "Unliked"} ${track}`,
1829
+ ...after !== before && { undo: () => setLiked(uri, before) }
1830
+ };
1831
+ },
1832
+ look: () => ({
1833
+ background: BACKGROUND,
1834
+ layers: switched("spotify.liked == true", "tb/TbHeartFilled", "tb/TbHeart", {
1835
+ on: GREEN,
1836
+ off: MUTED
1837
+ })
1838
+ })
1839
+ });
1840
+ var addToPlaylist = defineAction({
1841
+ id: "add-to-playlist",
1842
+ name: "Add to playlist",
1843
+ description: "Adds what is playing to one of your playlists.",
1844
+ category: "Spotify",
1845
+ icon: "list-plus",
1846
+ slots: ["key", "sensor"],
1847
+ settings: {
1848
+ playlist: {
1849
+ type: "select",
1850
+ label: "Playlist",
1851
+ options: [],
1852
+ source: "playlists",
1853
+ description: "Yours, and ones you collaborate on."
1854
+ },
1855
+ text: { type: "text", label: "Text", placeholder: "Shown under the icon" }
1856
+ },
1857
+ run: async ({ settings }) => {
1858
+ if (!settings.playlist)
1859
+ throw new Error("Pick a playlist in the key's settings");
1860
+ const { uri, track } = await current();
1861
+ await spotify.request("POST", `/playlists/${encodeURIComponent(settings.playlist)}/items`, {}, {
1862
+ uris: [uri]
1863
+ });
1864
+ return { label: `Added ${track} to a playlist` };
1865
+ },
1866
+ look: (s) => key("lucide/list-plus", s.text)
1867
+ });
1868
+ var play = defineAction({
1869
+ id: "play",
1870
+ name: "Play",
1871
+ description: "Plays a playlist, album, artist, track or episode, or adds it to the queue.",
1872
+ category: "Spotify",
1873
+ icon: "list-music",
1874
+ slots: ["key", "sensor"],
1875
+ settings: {
1876
+ item: {
1877
+ type: "text",
1878
+ label: "What to play",
1879
+ source: "library",
1880
+ placeholder: "A Spotify link, or pick a playlist",
1881
+ description: "In Spotify: Share \u2192 Copy link."
1882
+ },
1883
+ mode: {
1884
+ type: "select",
1885
+ label: "When pressed",
1886
+ default: "play",
1887
+ options: [
1888
+ { value: "play", label: "Play now" },
1889
+ { value: "queue", label: "Add to the queue (tracks and episodes)" }
1890
+ ]
1891
+ },
1892
+ shuffle: {
1893
+ type: "boolean",
1894
+ label: "Shuffle",
1895
+ default: false,
1896
+ visibleIf: { mode: "play" }
1897
+ },
1898
+ text: { type: "text", label: "Text", placeholder: "Shown under the icon" }
1899
+ },
1900
+ run: async ({ settings }) => {
1901
+ const target = spotifyUri(settings.item);
1902
+ if (!target)
1903
+ throw new Error("set what to play: a Spotify link or spotify: URI");
1904
+ if (settings.mode === "queue") {
1905
+ if (target.kind !== "track" && target.kind !== "episode") {
1906
+ throw new Error("only tracks and episodes can be queued");
1907
+ }
1908
+ await command("POST", "/me/player/queue", { uri: target.uri });
1909
+ return { label: "Added to the queue" };
1910
+ }
1911
+ await command("PUT", "/me/player/play", {}, playBody(target.uri, target.kind));
1912
+ if (settings.shuffle)
1913
+ await command("PUT", "/me/player/shuffle", { state: "true" });
1914
+ return { label: `Play ${target.kind}` };
1915
+ },
1916
+ look: (s) => key(s.mode === "queue" ? "lucide/list-end" : "lucide/list-music", s.text)
1917
+ });
1918
+ var seek = defineAction({
1919
+ id: "seek",
1920
+ name: "Seek",
1921
+ description: "Jumps forward or back in the track.",
1922
+ category: "Spotify",
1923
+ icon: "fast-forward",
1924
+ slots: ["key", "sensor"],
1925
+ settings: {
1926
+ direction: {
1927
+ type: "select",
1928
+ label: "Direction",
1929
+ default: "forward",
1930
+ options: [
1931
+ { value: "forward", label: "Forward" },
1932
+ { value: "back", label: "Back" },
1933
+ { value: "start", label: "To the start" }
1934
+ ]
1935
+ },
1936
+ seconds: {
1937
+ type: "number",
1938
+ label: "Seconds",
1939
+ default: 15,
1940
+ min: 1,
1941
+ max: 600,
1942
+ visibleIf: { direction: ["forward", "back"] }
1943
+ }
1944
+ },
1945
+ run: async ({ settings }) => {
1946
+ const { positionMs, durationMs } = await current();
1947
+ const jump = settings.seconds * 1000;
1948
+ const wanted = settings.direction === "start" ? 0 : positionMs + (settings.direction === "forward" ? jump : -jump);
1949
+ const to = Math.round(Math.min(Math.max(0, durationMs - 1000), Math.max(0, wanted)));
1950
+ const go = (ms) => command("PUT", "/me/player/seek", { position_ms: String(ms) });
1951
+ await go(to);
1952
+ return { label: `Seek to ${Math.round(to / 1000)} s`, undo: () => go(positionMs) };
1953
+ },
1954
+ look: (s) => key(s.direction === "start" ? "lucide/undo-2" : s.direction === "forward" ? "lucide/fast-forward" : "lucide/rewind", s.direction === "start" ? "" : `${s.direction === "forward" ? "+" : "\u2212"}${s.seconds}s`)
1955
+ });
1956
+ var transfer = (id) => command("PUT", "/me/player", {}, { device_ids: [id], play: true });
1957
+ var device = defineAction({
1958
+ id: "device",
1959
+ name: "Play on a device",
1960
+ description: "Moves playback to another speaker, phone or computer.",
1961
+ category: "Spotify",
1962
+ icon: "speaker",
1963
+ slots: ["key", "sensor"],
1964
+ settings: {
1965
+ device: {
1966
+ type: "select",
1967
+ label: "Device",
1968
+ options: [],
1969
+ source: "devices",
1970
+ description: "Only devices with Spotify open are listed."
1971
+ },
1972
+ text: { type: "text", label: "Text", placeholder: "Shown under the icon" }
1973
+ },
1974
+ run: async ({ settings }) => {
1975
+ if (!settings.device)
1976
+ throw new Error("Pick a device in the key's settings");
1977
+ const before = (await readPlayer()).deviceId;
1978
+ await transfer(settings.device);
1979
+ return {
1980
+ label: "Moved playback",
1981
+ ...before && before !== settings.device && { undo: () => transfer(before) }
1982
+ };
1983
+ },
1984
+ look: (s) => key("lucide/speaker", s.text)
1985
+ });
1986
+ var trackChanged = defineTrigger({
1987
+ id: "track-changed",
1988
+ name: "When the track changes",
1989
+ description: "Fires with the new track whenever something else starts playing.",
1990
+ subscribe: ({ fire }) => {
1991
+ let uri;
1992
+ return player.listen((p) => {
1993
+ const next = p?.uri ?? "";
1994
+ if (uri !== undefined && next && next !== uri)
1995
+ fire(p);
1996
+ if (p)
1997
+ uri = next;
1998
+ });
1999
+ }
2000
+ });
2001
+ var stateOf = (id, name, type) => ({
2002
+ id,
2003
+ name,
2004
+ type,
2005
+ start: (set) => player.listen((p) => set(p?.[id]))
2006
+ });
2007
+ var playlistOptions = async (writable) => (await playlists()).filter((p) => !writable || p.writable).map((p) => ({ value: writable ? p.id : p.uri, label: p.name }));
2008
+ var src_default = definePlugin({
2009
+ id: "@sdeck/plugin-spotify",
2010
+ name: "Spotify",
2011
+ version: "0.1.0",
2012
+ namespace: "spotify",
2013
+ description: "Now playing, playback, Liked Songs, playlists and devices through the Spotify Web API.",
2014
+ author: "sdeck",
2015
+ permissions: ["network"],
2016
+ settings: {
2017
+ clientId: {
2018
+ type: "text",
2019
+ label: "Client ID",
2020
+ description: "Create an app at developer.spotify.com and add the redirect URI http://127.0.0.1:43821/callback (with your port)."
2021
+ },
2022
+ port: {
2023
+ type: "number",
2024
+ label: "Sign-in port",
2025
+ default: DEFAULT_PORT,
2026
+ min: 1024,
2027
+ max: 65535
2028
+ }
2029
+ },
2030
+ onboarding: {
2031
+ intro: "Spotify lets apps in only with an app of your own. It takes a minute.",
2032
+ steps: [
2033
+ {
2034
+ id: "app",
2035
+ title: "Create a Spotify app",
2036
+ body: "Open the Spotify developer dashboard, sign in and press **Create app**. Give it any name, add the redirect URI `http://127.0.0.1:43821/callback`, tick **Web API**, and save.\n\nThen copy the app's **Client ID** here.",
2037
+ link: {
2038
+ label: "Spotify developer dashboard",
2039
+ url: "https://developer.spotify.com/dashboard"
2040
+ },
2041
+ settings: ["clientId"]
2042
+ },
2043
+ {
2044
+ id: "sign-in",
2045
+ title: "Sign in",
2046
+ body: "Allow sdeck in the browser that opens. Controlling playback needs Spotify Premium.",
2047
+ command: "sign-in",
2048
+ done: (activated) => activated.secrets.get("refreshToken") !== undefined
2049
+ }
2050
+ ],
2051
+ starterPage: {
2052
+ name: "Spotify",
2053
+ keys: {
2054
+ 0: { action: "previous" },
2055
+ 1: { action: "play-pause" },
2056
+ 2: { action: "next" },
2057
+ 3: { action: "like" },
2058
+ 4: { action: "volume", settings: { operation: "down" } },
2059
+ 5: { action: "volume", settings: { operation: "up" } },
2060
+ 6: { action: "shuffle" },
2061
+ 7: { action: "repeat" }
2062
+ },
2063
+ window: { action: "now-playing" }
2064
+ }
2065
+ },
2066
+ commands: [
2067
+ {
2068
+ id: "sign-in",
2069
+ name: "Sign in",
2070
+ description: "Opens Spotify in your browser to allow access.",
2071
+ run: (activated) => {
2072
+ signingIn?.cancel();
2073
+ signingIn = spotify.signIn(Number(activated.settings().port));
2074
+ activated.status("Waiting for you to allow access in the browser", "info");
2075
+ signingIn.done.then(() => {
2076
+ activated.status("Signed in to Spotify", "ok");
2077
+ me = undefined;
2078
+ pollNow();
2079
+ }, (error) => activated.status(error.message, "error"));
2080
+ return signingIn.url;
2081
+ }
2082
+ },
2083
+ {
2084
+ id: "sign-out",
2085
+ name: "Sign out",
2086
+ run: async (activated) => {
2087
+ signingIn?.cancel();
2088
+ await spotify.signOut();
2089
+ me = undefined;
2090
+ activated.status("Signed out", "info");
2091
+ pollNow();
2092
+ }
2093
+ }
2094
+ ],
2095
+ actions: [
2096
+ playPause,
2097
+ next,
2098
+ previous,
2099
+ nowPlaying,
2100
+ like,
2101
+ addToPlaylist,
2102
+ play,
2103
+ seek,
2104
+ volume,
2105
+ shuffle,
2106
+ repeat,
2107
+ device
2108
+ ],
2109
+ triggers: [trackChanged],
2110
+ optionSources: {
2111
+ playlists: () => playlistOptions(true),
2112
+ library: () => playlistOptions(false),
2113
+ devices: async () => parseDevices(await spotify.request("GET", "/me/player/devices")).map((d) => ({
2114
+ value: d.id,
2115
+ label: `${d.name}${d.active ? " (playing)" : ""}`
2116
+ }))
2117
+ },
2118
+ state: [
2119
+ stateOf("playing", "Playing", "boolean"),
2120
+ stateOf("track", "Track", "string"),
2121
+ stateOf("artist", "Artist", "string"),
2122
+ stateOf("album", "Album", "string"),
2123
+ stateOf("art", "Cover art", "string"),
2124
+ stateOf("progress", "Progress", "number"),
2125
+ stateOf("volume", "Volume", "number"),
2126
+ stateOf("shuffle", "Shuffle", "boolean"),
2127
+ stateOf("repeat", "Repeat", "string"),
2128
+ stateOf("device", "Device", "string"),
2129
+ stateOf("uri", "Track URI", "string"),
2130
+ {
2131
+ id: "liked",
2132
+ name: "Liked",
2133
+ type: "boolean",
2134
+ description: "Whether what is playing is in Liked Songs.",
2135
+ start: (set) => liked.listen(set)
2136
+ }
2137
+ ],
2138
+ activate(activated) {
2139
+ context = activated;
2140
+ activated.status(activated.secrets.get("refreshToken") ? "Signed in to Spotify" : "Set your client id, then sign in", "info");
2141
+ return () => {
2142
+ signingIn?.cancel();
2143
+ context = undefined;
2144
+ };
2145
+ }
2146
+ });
2147
+ export {
2148
+ DEFAULT_PORT,
2149
+ IDLE,
2150
+ RateLimited,
2151
+ SCOPES,
2152
+ SPOTIFY,
2153
+ SignedOut,
2154
+ SpotifyClient,
2155
+ createPkce,
2156
+ src_default as default,
2157
+ nextRepeat,
2158
+ parseDevices,
2159
+ parsePlayer,
2160
+ parsePlaylists,
2161
+ playBody,
2162
+ spotifyUri
2163
+ };
2164
+
2165
+ //# debugId=6E302A0FD592C41264756E2164756E21