@sdeck/plugin 0.1.0 → 0.2.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 CHANGED
@@ -1,2700 +1,28 @@
1
- // ../core/src/deck.ts
2
- import sharp3 from "sharp";
1
+ // src/index.ts
2
+ export * from "@sdeck/app";
3
3
 
4
- // ../core/src/element.ts
5
- var isRawImage = (value) => typeof value === "object" && value !== null && !ArrayBuffer.isView(value) && ("data" in value) && ("width" in value) && ("height" in value) && ("channels" in value);
6
- var runtime;
7
- function registerElementRuntime(next) {
8
- runtime = next;
9
- }
10
- function getElementRuntime() {
11
- if (!runtime) {
12
- throw new Error("Drawing elements needs a renderer: install and import `@sdeck/react` (once, anywhere)");
13
- }
14
- return runtime;
15
- }
16
- var isRenderable = (value) => runtime !== undefined && typeof value === "object" && value !== null && runtime.matches(value);
17
-
18
- // ../core/src/framebuffer.ts
19
- var view = (data, offset, length) => Buffer.from(data.buffer, data.byteOffset + offset, length);
20
-
21
- class Framebuffer {
22
- width;
23
- height;
24
- data;
25
- constructor(size) {
26
- this.width = size.width;
27
- this.height = size.height;
28
- this.data = new Uint8Array(size.width * size.height * 3);
29
- }
30
- #check(rect, rgb) {
31
- if (rect.x < 0 || rect.y < 0 || rect.x + rect.width > this.width || rect.y + rect.height > this.height) {
32
- throw new RangeError(`region ${rect.width}×${rect.height} at (${rect.x}, ${rect.y}) is outside the ${this.width}×${this.height} screen`);
33
- }
34
- if (rgb && rgb.length !== rect.width * rect.height * 3) {
35
- throw new RangeError(`expected ${rect.width}×${rect.height} RGB pixels, got ${rgb.length} bytes`);
36
- }
37
- }
38
- equals(rect, rgb) {
39
- this.#check(rect, rgb);
40
- const row = rect.width * 3;
41
- for (let y = 0;y < rect.height; y++) {
42
- const at = ((rect.y + y) * this.width + rect.x) * 3;
43
- if (!view(this.data, at, row).equals(view(rgb, y * row, row)))
44
- return false;
45
- }
46
- return true;
47
- }
48
- blit(rect, rgb) {
49
- this.#check(rect, rgb);
50
- const row = rect.width * 3;
51
- if (rect.x === 0 && rect.width === this.width) {
52
- this.data.set(rgb, rect.y * row);
53
- return;
54
- }
55
- for (let y = 0;y < rect.height; y++) {
56
- this.data.set(rgb.subarray(y * row, (y + 1) * row), ((rect.y + y) * this.width + rect.x) * 3);
57
- }
58
- }
59
- fill(color, rect = { x: 0, y: 0, width: this.width, height: this.height }) {
60
- this.blit(rect, solidRgb(rect, color));
61
- }
62
- read(rect = { x: 0, y: 0, width: this.width, height: this.height }) {
63
- this.#check(rect);
64
- if (rect.x === 0 && rect.y === 0 && rect.width === this.width && rect.height === this.height) {
65
- return { data: this.data.slice(), width: this.width, height: this.height, channels: 3 };
66
- }
67
- const row = rect.width * 3;
68
- const out = new Uint8Array(row * rect.height);
69
- for (let y = 0;y < rect.height; y++) {
70
- const at = ((rect.y + y) * this.width + rect.x) * 3;
71
- out.set(this.data.subarray(at, at + row), y * row);
72
- }
73
- return { data: out, width: rect.width, height: rect.height, channels: 3 };
74
- }
75
- }
76
- function solidRgb(size, [r, g, b]) {
77
- const out = new Uint8Array(size.width * size.height * 3);
78
- for (let i = 0;i < out.length; i += 3) {
79
- out[i] = r;
80
- out[i + 1] = g;
81
- out[i + 2] = b;
82
- }
83
- return out;
84
- }
85
- function parseHexColor(color) {
86
- const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())?.[1];
87
- if (!hex)
88
- return;
89
- const full = hex.length === 3 ? [...hex].map((c) => c + c).join("") : hex;
90
- const n = Number.parseInt(full, 16);
91
- return [n >> 16 & 255, n >> 8 & 255, n & 255];
92
- }
93
- function flattenRgba(rgba, [br, bg, bb]) {
94
- const out = new Uint8Array(rgba.length / 4 * 3);
95
- for (let i = 0, j = 0;i < rgba.length; i += 4, j += 3) {
96
- const a = rgba[i + 3];
97
- if (a === 255) {
98
- out[j] = rgba[i];
99
- out[j + 1] = rgba[i + 1];
100
- out[j + 2] = rgba[i + 2];
101
- } else {
102
- const inv = 255 - a;
103
- out[j] = (rgba[i] * a + br * inv + 127) / 255;
104
- out[j + 1] = (rgba[i + 1] * a + bg * inv + 127) / 255;
105
- out[j + 2] = (rgba[i + 2] * a + bb * inv + 127) / 255;
106
- }
107
- }
108
- return out;
109
- }
110
-
111
- // ../core/src/image.ts
112
- import sharp from "sharp";
113
- var SUPPORTED_FORMATS = new Set(["png", "jpeg", "webp"]);
114
- async function prepareImage(source, size, options = {}) {
115
- const { fit = "cover", background = "#000000", fonts } = options;
116
- const input = isRenderable(source) ? await getElementRuntime().render(source, size, fonts ? { fonts } : {}) : source;
117
- let pipeline;
118
- if (isRawImage(input)) {
119
- const { data, width, height, channels } = input;
120
- pipeline = sharp(data, { raw: { width, height, channels } });
121
- } else {
122
- const encoded = input;
123
- const { format } = await sharp(encoded).metadata();
124
- if (!format || !SUPPORTED_FORMATS.has(format)) {
125
- throw new Error(`Unsupported image format "${format ?? "unknown"}"; use PNG, JPEG or WebP`);
126
- }
127
- pipeline = sharp(encoded);
128
- }
129
- return pipeline.autoOrient().resize(size.width, size.height, { fit, background }).flatten({ background });
130
- }
131
- async function toRgb(source, size, options = {}) {
132
- const { background = "#000000", fonts } = options;
133
- const input = isRenderable(source) ? await getElementRuntime().render(source, size, fonts ? { fonts } : {}) : source;
134
- if (isRawImage(input) && input.width === size.width && input.height === size.height) {
135
- if (input.channels === 3)
136
- return input.data;
137
- const bg = parseHexColor(background);
138
- if (bg)
139
- return flattenRgba(input.data, bg);
140
- }
141
- const { data, info } = await (await prepareImage(input, size, options)).toColourspace("srgb").raw().toBuffer({ resolveWithObject: true });
142
- if (info.channels !== 3) {
143
- throw new Error(`expected RGB pixels, got ${info.channels} channels`);
144
- }
145
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
146
- }
147
- async function encodeJpeg(rgb, size, options = {}) {
148
- const { quality = 90, rotation = 0 } = options;
149
- let pipeline = sharp(rgb, { raw: { width: size.width, height: size.height, channels: 3 } });
150
- if (rotation === 180)
151
- pipeline = pipeline.rotate(180);
152
- const jpeg = await pipeline.jpeg({ quality, progressive: false, chromaSubsampling: "4:4:4" }).toBuffer();
153
- return new Uint8Array(jpeg.buffer, jpeg.byteOffset, jpeg.byteLength);
154
- }
155
-
156
- // ../core/src/layout.ts
157
- import sharp2 from "sharp";
158
- function placements(layout, geometry) {
159
- if ((layout.keys?.length ?? 0) > geometry.keys.length) {
160
- throw new RangeError(`at most ${geometry.keys.length} key images, got ${layout.keys?.length}`);
161
- }
162
- if ((layout.sensors?.length ?? 0) > geometry.sensors.length) {
163
- throw new RangeError(`at most ${geometry.sensors.length} sensor images, got ${layout.sensors?.length}`);
164
- }
165
- if (layout.window !== undefined && !geometry.window) {
166
- throw new RangeError("this deck has no window");
167
- }
168
- const out = [
169
- ...geometry.keys.map((rect, i) => [layout.keys?.[i], rect]),
170
- ...geometry.sensors.map((rect, i) => [
171
- layout.sensors?.[i],
172
- rect
173
- ])
174
- ];
175
- if (geometry.window)
176
- out.push([layout.window, geometry.window]);
177
- return out;
178
- }
179
- async function background(size, color) {
180
- const { data } = await sharp2({ create: { ...size, channels: 3, background: color } }).raw().toBuffer({ resolveWithObject: true });
181
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
182
- }
183
- async function compose(layout, geometry, options) {
184
- const { background: color = "#000000" } = options;
185
- const slots = placements(layout, geometry);
186
- const screen = new Framebuffer(geometry.screen);
187
- const hex = parseHexColor(color);
188
- const [base, ...pixels] = await Promise.all([
189
- hex ? undefined : background(geometry.screen, color),
190
- ...slots.map(([source, rect]) => source === undefined ? undefined : toRgb(source, rect, options))
191
- ]);
192
- if (hex)
193
- screen.fill(hex);
194
- else if (base)
195
- screen.blit({ x: 0, y: 0, ...geometry.screen }, base);
196
- slots.forEach(([, rect], i) => {
197
- const rgb = pixels[i];
198
- if (rgb)
199
- screen.blit(rect, rgb);
200
- });
201
- return screen;
202
- }
203
- async function composeScreenRaw(layout, geometry, options = {}) {
204
- const screen = await compose(layout, geometry, options);
205
- return { data: screen.data, width: screen.width, height: screen.height, channels: 3 };
206
- }
207
-
208
- // ../core/src/deck.ts
209
- var toError = (error) => error instanceof Error ? error : new Error(String(error));
210
- var nextTick = () => new Promise((resolve) => setImmediate(resolve));
211
-
212
- class StreamDeck {
213
- model;
214
- transport;
215
- #listeners = {
216
- keyDown: new Set,
217
- keyUp: new Set,
218
- sensorDown: new Set,
219
- sensorUp: new Set,
220
- draw: new Set,
221
- error: new Set
222
- };
223
- #unsubscribe;
224
- #pressed = [];
225
- #closed = false;
226
- #roots = new Set;
227
- #queue = Promise.resolve();
228
- #screen;
229
- #allSlots;
230
- #known = new Set;
231
- #gen = new Map;
232
- #seq = new Map;
233
- #frame;
234
- #pumping = false;
235
- constructor(transport, model) {
236
- this.transport = transport;
237
- this.model = model;
238
- this.#screen = new Framebuffer(model.layout.screen);
239
- this.#allSlots = [
240
- ...model.layout.keys.map((_, i) => `key:${i}`),
241
- ...model.layout.sensors.map((_, i) => `sensor:${i}`),
242
- ...model.layout.window ? ["window"] : [],
243
- "rest"
244
- ];
245
- this.#unsubscribe = [
246
- transport.onData((data) => this.#handleInput(data)),
247
- transport.onError((error) => this.emit("error", toError(error)))
248
- ];
249
- }
250
- get keyCount() {
251
- return this.model.layout.keys.length;
252
- }
253
- get sensorCount() {
254
- return this.model.layout.sensors.length;
255
- }
256
- get keySize() {
257
- return this.#size(this.model.layout.keys[0], "keys");
258
- }
259
- get sensorSize() {
260
- return this.#size(this.model.layout.sensors[0], "sensor strips");
261
- }
262
- get windowSize() {
263
- return this.#size(this.model.layout.window, "a window");
264
- }
265
- get screenSize() {
266
- return this.model.layout.screen;
267
- }
268
- get closed() {
269
- return this.#closed;
270
- }
271
- slotDrawing(kind, index = 0) {
272
- const { layout, design } = this.model;
273
- const rect = kind === "window" ? layout.window : (kind === "key" ? layout.keys : layout.sensors)[index];
274
- const size = this.#size(rect, kind === "window" ? "a window" : `${kind} ${index}`);
275
- const base = design?.[kind];
276
- if (!base)
277
- return { size, scale: 1 };
278
- const scale = Math.min(size.width / base.width, size.height / base.height);
279
- return {
280
- size: { width: Math.round(size.width / scale), height: Math.round(size.height / scale) },
281
- scale
282
- };
283
- }
284
- #size(rect, what) {
285
- if (!rect)
286
- throw new Error(`${this.model.name} has no ${what}`);
287
- return { width: rect.width, height: rect.height };
288
- }
289
- #windowRect() {
290
- const rect = this.model.layout.window;
291
- if (!rect)
292
- throw new Error(`${this.model.name} has no window`);
293
- return rect;
294
- }
295
- get #screenRect() {
296
- return { x: 0, y: 0, ...this.screenSize };
297
- }
298
- on(event, listener) {
299
- this.#listeners[event].add(listener);
300
- return () => this.off(event, listener);
301
- }
302
- off(event, listener) {
303
- this.#listeners[event].delete(listener);
304
- }
305
- emit(event, ...args) {
306
- for (const listener of [...this.#listeners[event]]) {
307
- try {
308
- listener(...args);
309
- } catch (error) {
310
- if (event !== "error")
311
- this.emit("error", toError(error));
312
- }
313
- }
314
- }
315
- sendWindowJpeg(_jpeg) {
316
- return Promise.reject(new Error(`${this.model.name} has no window`));
317
- }
318
- sendWindowRegionJpeg(_region, _jpeg) {
319
- return Promise.reject(new Error(`${this.model.name} cannot update part of the window`));
320
- }
321
- async sendFillKey(index, color) {
322
- const size = this.#size(this.model.layout.keys[index], "keys");
323
- await this.sendKeyJpeg(index, await this.#encode(solidRgb(size, color), size));
324
- }
325
- async sendFillScreen(color) {
326
- const size = this.screenSize;
327
- await this.sendScreenJpeg(await this.#encode(solidRgb(size, color), size));
328
- }
329
- async onClosing() {}
330
- async ping() {
331
- await this.getSerialNumber();
332
- }
333
- async setKeyImage(index, image, options) {
334
- this.assertKey(index);
335
- const slot = `key:${index}`;
336
- const rect = this.model.layout.keys[index];
337
- const current = this.#claim([slot]);
338
- const rgb = await toRgb(image, rect, options);
339
- if (!current())
340
- return;
341
- await this.#commit([slot], rect, rgb, () => {
342
- const jpeg = this.#encode(rgb, rect, options?.quality);
343
- return async () => this.sendKeyJpeg(index, await jpeg);
344
- });
345
- }
346
- async setWindowImage(image, options) {
347
- const rect = this.#windowRect();
348
- const current = this.#claim(["window"]);
349
- const rgb = await toRgb(image, rect, options);
350
- if (!current())
351
- return;
352
- await this.#commit(["window"], rect, rgb, () => {
353
- const jpeg = this.#encode(rgb, rect, options?.quality);
354
- return async () => this.sendWindowJpeg(await jpeg);
355
- });
356
- }
357
- async setWindowRegionImage(region, image, options) {
358
- const rect = this.#windowRegion(region);
359
- const rgb = await toRgb(image, rect, options);
360
- await this.#commit(["window"], rect, rgb, () => {
361
- const jpeg = this.#encode(rgb, rect, options?.quality);
362
- return async () => this.sendWindowRegionJpeg(region, await jpeg);
363
- });
364
- }
365
- async setSensorImage(index, image, options) {
366
- this.assertSensor(index);
367
- const slot = `sensor:${index}`;
368
- const rect = this.model.layout.sensors[index];
369
- const current = this.#claim([slot]);
370
- const rgb = await toRgb(image, rect, options);
371
- if (!current() || this.#unchanged([slot], rect, rgb))
372
- return;
373
- this.#screen.blit(rect, rgb);
374
- this.#touch([slot]);
375
- await this.#requestFrame(options?.quality);
376
- }
377
- async setScreenImage(image, options) {
378
- const current = this.#claim(this.#allSlots);
379
- const rgb = await toRgb(image, this.screenSize, options);
380
- if (current())
381
- await this.#drawScreen(rgb, options?.quality);
382
- }
383
- async setScreenLayout(layout, options) {
384
- const current = this.#claim(this.#allSlots);
385
- const { data } = await composeScreenRaw(layout, this.model.layout, options);
386
- if (current())
387
- await this.#drawScreen(data, options?.quality);
388
- }
389
- fillKey(index, color) {
390
- this.assertKey(index);
391
- const slot = `key:${index}`;
392
- const rect = this.model.layout.keys[index];
393
- this.#claim([slot]);
394
- return this.#commit([slot], rect, solidRgb(rect, color), () => () => this.sendFillKey(index, color));
395
- }
396
- fillScreen(color) {
397
- this.#claim(this.#allSlots);
398
- const rect = this.#screenRect;
399
- return this.#commit(this.#allSlots, rect, solidRgb(rect, color), () => () => this.sendFillScreen(color));
400
- }
401
- setKeyJpeg(index, jpeg) {
402
- this.assertKey(index);
403
- return this.#raw([`key:${index}`], () => this.sendKeyJpeg(index, jpeg));
404
- }
405
- setScreenJpeg(jpeg) {
406
- return this.#raw(this.#allSlots, () => this.sendScreenJpeg(jpeg));
407
- }
408
- setWindowJpeg(jpeg) {
409
- return this.#raw(["window"], () => this.sendWindowJpeg(jpeg));
410
- }
411
- setWindowRegionJpeg(region, jpeg) {
412
- this.#windowRegion(region);
413
- return this.#raw(["window"], () => this.sendWindowRegionJpeg(region, jpeg));
414
- }
415
- readScreen(region) {
416
- return this.#screen.read(region);
417
- }
418
- async snapshot(region) {
419
- const { data, width, height } = this.#screen.read(region);
420
- const png = await sharp3(data, { raw: { width, height, channels: 3 } }).png().toBuffer();
421
- return new Uint8Array(png.buffer, png.byteOffset, png.byteLength);
422
- }
423
- #encode(rgb, size, quality) {
424
- const jpeg = encodeJpeg(rgb, size, { quality, rotation: this.model.rotation });
425
- jpeg.catch(() => {});
426
- return jpeg;
427
- }
428
- #windowRegion(region) {
429
- const win = this.#windowRect();
430
- if (region.x < 0 || region.y < 0 || region.width <= 0 || region.height <= 0 || region.x + region.width > win.width || region.y + region.height > win.height) {
431
- throw new RangeError(`region ${region.width}×${region.height} at (${region.x}, ${region.y}) is outside the ${win.width}×${win.height} window`);
432
- }
433
- return { ...region, x: win.x + region.x, y: win.y + region.y };
434
- }
435
- #claim(slots) {
436
- const seqs = slots.map((slot) => {
437
- const seq = (this.#seq.get(slot) ?? 0) + 1;
438
- this.#seq.set(slot, seq);
439
- return seq;
440
- });
441
- return () => slots.every((slot, i) => this.#seq.get(slot) === seqs[i]);
442
- }
443
- #touch(slots) {
444
- const gens = new Map;
445
- for (const slot of slots) {
446
- const gen = (this.#gen.get(slot) ?? 0) + 1;
447
- this.#gen.set(slot, gen);
448
- this.#known.delete(slot);
449
- gens.set(slot, gen);
450
- }
451
- return gens;
452
- }
453
- #gens(slots) {
454
- return new Map(slots.map((slot) => [slot, this.#gen.get(slot) ?? 0]));
455
- }
456
- #unchanged(slots, rect, rgb) {
457
- return slots.every((slot) => this.#known.has(slot)) && this.#screen.equals(rect, rgb);
458
- }
459
- async#settle(write, gens, region) {
460
- try {
461
- await write;
462
- } catch (error) {
463
- for (const slot of gens.keys())
464
- this.#known.delete(slot);
465
- throw error;
466
- }
467
- for (const [slot, gen] of gens)
468
- if (this.#gen.get(slot) === gen)
469
- this.#known.add(slot);
470
- this.emit("draw", region);
471
- }
472
- #commit(slots, rect, rgb, prepare) {
473
- if (this.#unchanged(slots, rect, rgb))
474
- return Promise.resolve();
475
- this.#screen.blit(rect, rgb);
476
- const gens = this.#touch(slots);
477
- return this.#settle(this.enqueue(prepare()), gens, rect);
478
- }
479
- async#raw(slots, write) {
480
- this.#claim(slots);
481
- this.#touch(slots);
482
- await this.enqueue(write);
483
- }
484
- async#drawScreen(rgb, quality) {
485
- const rect = this.#screenRect;
486
- if (this.#unchanged(this.#allSlots, rect, rgb))
487
- return;
488
- this.#screen.blit(rect, rgb);
489
- this.#touch(this.#allSlots);
490
- await this.#requestFrame(quality);
491
- }
492
- #requestFrame(quality) {
493
- this.#frame ??= { waiters: [] };
494
- const frame = this.#frame;
495
- if (quality !== undefined)
496
- frame.quality = quality;
497
- const done = new Promise((resolve, reject) => frame.waiters.push({ resolve, reject }));
498
- if (!this.#pumping)
499
- this.#pump();
500
- return done;
501
- }
502
- async#pump() {
503
- this.#pumping = true;
504
- try {
505
- while (this.#frame) {
506
- await nextTick();
507
- const frame = this.#frame;
508
- this.#frame = undefined;
509
- const gens = this.#gens(this.#allSlots);
510
- const jpeg = this.#encode(this.#screen.data.slice(), this.screenSize, frame.quality);
511
- const write = this.enqueue(async () => this.sendScreenJpeg(await jpeg));
512
- try {
513
- await this.#settle(write, gens, this.#screenRect);
514
- for (const waiter of frame.waiters)
515
- waiter.resolve();
516
- } catch (error) {
517
- for (const waiter of frame.waiters)
518
- waiter.reject(error);
519
- }
520
- }
521
- } finally {
522
- this.#pumping = false;
523
- }
524
- }
525
- mountKey(index, element, options) {
526
- this.assertKey(index);
527
- return this.#mount("key", index, (frame) => this.setKeyImage(index, frame, { ...options, fit: "fill" }), element, options);
528
- }
529
- mountSensor(index, element, options) {
530
- this.assertSensor(index);
531
- return this.#mount("sensor", index, (frame) => this.setSensorImage(index, frame, { ...options, fit: "fill" }), element, options);
532
- }
533
- mountWindow(element, options) {
534
- return this.#mount("window", 0, (frame) => this.setWindowImage(frame, { ...options, fit: "fill" }), element, options);
535
- }
536
- mountScreen(element, options) {
537
- return this.#mount("screen", 0, (frame) => this.setScreenImage(frame, { ...options, fit: "fill" }), element, options);
538
- }
539
- async#mount(kind, index, send, element, options = {}) {
540
- if (this.#closed)
541
- throw new Error(`${this.model.name} is closed`);
542
- const drawing = kind === "screen" ? { size: this.screenSize, scale: 1 } : this.slotDrawing(kind, index);
543
- const pixels = drawing.scale === 1 ? drawing.size : {
544
- width: Math.round(drawing.size.width * drawing.scale),
545
- height: Math.round(drawing.size.height * drawing.scale)
546
- };
547
- const inner = await getElementRuntime().createRoot(pixels, send, {
548
- ...drawing.scale !== 1 && { scale: drawing.scale },
549
- ...options,
550
- onError: options.onError ?? ((error) => this.emit("error", toError(error)))
551
- });
552
- const roots = this.#roots;
553
- const root = {
554
- render: (next) => inner.render(next),
555
- idle: () => inner.idle(),
556
- async unmount() {
557
- roots.delete(root);
558
- await inner.unmount();
559
- }
560
- };
561
- roots.add(root);
562
- try {
563
- root.render(element);
564
- await root.idle();
565
- } catch (error) {
566
- await root.unmount();
567
- throw error;
568
- }
569
- return root;
570
- }
571
- async close() {
572
- if (this.#closed)
573
- return;
574
- await Promise.all([...this.#roots].map((root) => root.unmount()));
575
- this.#closed = true;
576
- for (const stop of this.#unsubscribe)
577
- stop();
578
- try {
579
- await this.enqueueUnchecked(() => this.onClosing());
580
- } finally {
581
- await this.transport.close();
582
- }
583
- }
584
- assertKey(index) {
585
- if (!Number.isInteger(index) || index < 0 || index >= this.keyCount) {
586
- throw new RangeError(`key index must be 0–${this.keyCount - 1}, got ${index}`);
587
- }
588
- }
589
- assertSensor(index) {
590
- if (!Number.isInteger(index) || index < 0 || index >= this.sensorCount) {
591
- throw new RangeError(`sensor index must be 0–${Math.max(0, this.sensorCount - 1)}, got ${index}`);
592
- }
593
- }
594
- enqueue(task) {
595
- if (this.#closed)
596
- return Promise.reject(new Error(`${this.model.name} is closed`));
597
- return this.enqueueUnchecked(task);
598
- }
599
- enqueueUnchecked(task) {
600
- const run = this.#queue.then(task, task);
601
- this.#queue = run.catch(() => {
602
- return;
603
- });
604
- return run;
605
- }
606
- #handleInput(data) {
607
- const states = this.parseInput(data);
608
- if (!states)
609
- return;
610
- const keys = this.keyCount;
611
- for (let i = 0;i < states.length; i++) {
612
- const pressed = states[i] === true;
613
- if (pressed === (this.#pressed[i] === true))
614
- continue;
615
- if (i < keys) {
616
- this.emit(pressed ? "keyDown" : "keyUp", i);
617
- } else {
618
- this.emit(pressed ? "sensorDown" : "sensorUp", i - keys);
619
- }
620
- }
621
- this.#pressed = states;
622
- }
623
- }
624
- // ../core/src/detect.ts
625
- import { devices, devicesAsync, HID } from "node-hid";
626
-
627
- // ../core/src/transport.ts
628
- function view2(data) {
629
- return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
630
- }
631
- function fromNodeHid(device) {
632
- return {
633
- async write(data) {
634
- device.write(view2(data));
635
- },
636
- async sendFeatureReport(data) {
637
- device.sendFeatureReport(view2(data));
638
- },
639
- async getFeatureReport(reportId, length) {
640
- return Uint8Array.from(device.getFeatureReport(reportId, length));
641
- },
642
- onData(listener) {
643
- device.on("data", listener);
644
- return () => device.removeListener("data", listener);
645
- },
646
- onError(listener) {
647
- device.on("error", listener);
648
- return () => device.removeListener("error", listener);
649
- },
650
- async close() {
651
- device.close();
652
- }
653
- };
654
- }
655
-
656
- // ../core/src/detect.ts
657
- var nodeHid = {
658
- devices: () => devices(),
659
- devicesAsync: () => devicesAsync(),
660
- HID
661
- };
662
- var asArray = (value) => Array.isArray(value) ? value : [value];
663
- function findDecks(devices, drivers) {
664
- const list = asArray(drivers);
665
- const found = new Map;
666
- for (const device of devices) {
667
- const driver = list.find(({ model }) => model.vendorId === device.vendorId && model.productId === device.productId);
668
- if (!driver || !device.path || found.has(device.path))
669
- continue;
670
- found.set(device.path, {
671
- path: device.path,
672
- serialNumber: device.serialNumber || undefined,
673
- driver
674
- });
675
- }
676
- return [...found.values()];
677
- }
678
- async function listDecks(drivers, options = {}) {
679
- const hid = options.hid ?? nodeHid;
680
- return findDecks(hid.devicesAsync ? await hid.devicesAsync() : hid.devices(), drivers);
681
- }
682
- function sleep(ms, signal) {
683
- return new Promise((resolve, reject) => {
684
- if (signal?.aborted)
685
- return reject(signal.reason);
686
- const onAbort = () => {
687
- clearTimeout(timer);
688
- reject(signal?.reason);
689
- };
690
- const timer = setTimeout(() => {
691
- signal?.removeEventListener("abort", onAbort);
692
- resolve();
693
- }, ms);
694
- signal?.addEventListener("abort", onAbort, { once: true });
695
- });
696
- }
697
- async function tryOpen(hid, drivers, options) {
698
- const match = (await listDecks(drivers, { hid })).find((deck) => (options.path === undefined || deck.path === options.path) && (options.serialNumber === undefined || deck.serialNumber === options.serialNumber));
699
- return match?.driver.create(fromNodeHid(new hid.HID(match.path)));
700
- }
701
- async function openDeck(drivers, options = {}) {
702
- const hid = options.hid ?? nodeHid;
703
- const { wait = true, pollIntervalMs = 1000, timeoutMs = Number.POSITIVE_INFINITY } = options;
704
- const { signal } = options;
705
- const deadline = Date.now() + timeoutMs;
706
- let lastError;
707
- for (;; ) {
708
- signal?.throwIfAborted();
709
- try {
710
- const deck = await tryOpen(hid, drivers, options);
711
- if (deck)
712
- return deck;
713
- lastError = undefined;
714
- } catch (error) {
715
- lastError = error;
716
- }
717
- const remaining = deadline - Date.now();
718
- if (!wait || remaining <= 0)
719
- break;
720
- await sleep(Math.min(pollIntervalMs, remaining), signal);
721
- }
722
- const names = asArray(drivers).map(({ model }) => model.name).join(" or ");
723
- const filtered = options.path !== undefined || options.serialNumber !== undefined;
724
- throw new Error(`No ${names} found${filtered ? " matching the given path/serialNumber" : ""}`, {
725
- cause: lastError
726
- });
727
- }
728
- // ../core/src/manager.ts
729
- var withTimeout = (promise, ms) => new Promise((resolve, reject) => {
730
- const timer = setTimeout(() => reject(new Error(`no answer from the deck in ${ms} ms`)), ms);
731
- promise.then((value) => {
732
- clearTimeout(timer);
733
- resolve(value);
734
- }, (error) => {
735
- clearTimeout(timer);
736
- reject(error);
737
- });
738
- });
739
- var pause = (ms, signal) => new Promise((resolve) => {
740
- const done = () => {
741
- clearTimeout(timer);
742
- signal.removeEventListener("abort", done);
743
- resolve();
744
- };
745
- const timer = setTimeout(done, ms);
746
- signal.addEventListener("abort", done, { once: true });
747
- });
748
- function watchDeck(deck, options = {}) {
749
- const { heartbeatMs = 3000, timeoutMs = 2000 } = options;
750
- let markLost = () => {};
751
- const lost = new Promise((resolve) => {
752
- markLost = resolve;
753
- });
754
- let running = false;
755
- const probe = async () => {
756
- if (running)
757
- return;
758
- running = true;
759
- try {
760
- await withTimeout(deck.ping(), timeoutMs);
761
- } catch (error) {
762
- markLost(toError(error));
763
- } finally {
764
- running = false;
765
- }
766
- };
767
- const stops = [
768
- deck.on("error", (error) => {
769
- options.onError?.(error);
770
- probe();
771
- })
772
- ];
773
- if (heartbeatMs > 0) {
774
- const timer = setInterval(() => void probe(), heartbeatMs);
775
- stops.push(() => clearInterval(timer));
776
- }
777
- return {
778
- lost,
779
- stop() {
780
- for (const stop of stops.splice(0))
781
- stop();
782
- }
783
- };
784
- }
785
- function manageDeck(options) {
786
- const { reconnect = true, retryMs = 1000 } = options;
787
- const controller = new AbortController;
788
- const { signal } = controller;
789
- if (options.signal?.aborted)
790
- controller.abort();
791
- else
792
- options.signal?.addEventListener("abort", () => controller.abort(), { once: true });
793
- let status = "waiting";
794
- let current;
795
- const setStatus = (next, deck) => {
796
- status = next;
797
- current = deck;
798
- options.onStatus?.(next, deck);
799
- };
800
- const report = (error) => options.onError?.(toError(error));
801
- const release = (deck) => withTimeout(deck.close(), 2000).catch(() => {});
802
- const finished = (async () => {
803
- while (!signal.aborted) {
804
- setStatus("waiting");
805
- let deck;
806
- let cleanup;
807
- try {
808
- deck = await options.open(signal);
809
- cleanup = await options.setup?.(deck, signal);
810
- } catch (error) {
811
- if (deck)
812
- await release(deck);
813
- if (signal.aborted)
814
- break;
815
- report(error);
816
- await pause(retryMs, signal);
817
- continue;
818
- }
819
- const watch = watchDeck(deck, {
820
- ...options.heartbeatMs !== undefined && { heartbeatMs: options.heartbeatMs },
821
- ...options.timeoutMs !== undefined && { timeoutMs: options.timeoutMs },
822
- onError: report
823
- });
824
- setStatus("connected", deck);
825
- const aborted = new Promise((resolve) => {
826
- if (signal.aborted)
827
- resolve(undefined);
828
- else
829
- signal.addEventListener("abort", () => resolve(undefined), { once: true });
830
- });
831
- const cause = await Promise.race([watch.lost, aborted]);
832
- watch.stop();
833
- try {
834
- await cleanup?.();
835
- } catch (error) {
836
- report(error);
837
- }
838
- await release(deck);
839
- if (cause)
840
- report(cause);
841
- if (!reconnect)
842
- break;
843
- }
844
- setStatus("stopped");
845
- })();
846
- return {
847
- get status() {
848
- return status;
849
- },
850
- get deck() {
851
- return current;
852
- },
853
- stop: async () => {
854
- controller.abort();
855
- await finished;
856
- },
857
- finished
858
- };
859
- }
860
- // ../neo/src/protocol.ts
861
- var ELGATO_VENDOR_ID = 4057;
862
- var STREAM_DECK_NEO_PRODUCT_ID = 154;
863
- var OUTPUT_REPORT_SIZE = 1024;
864
- var FEATURE_REPORT_SIZE = 32;
865
- var INPUT_REPORT_ID = 1;
866
- var OUTPUT_REPORT_ID = 2;
867
- var SETTER_REPORT_ID = 3;
868
- var GetterReportId = {
869
- FirmwareLd: 4,
870
- FirmwareAp2: 5,
871
- SerialNumber: 6,
872
- FirmwareAp1: 7,
873
- UnitInformation: 8,
874
- SleepDuration: 10
875
- };
876
- var SetterCommand = {
877
- ShowLogo: 2,
878
- FillLcd: 5,
879
- FillKey: 6,
880
- Brightness: 8,
881
- SleepDuration: 13
882
- };
883
- var OutputCommand = {
884
- ButtonImage: 7,
885
- FullScreenImage: 8,
886
- WindowImage: 11,
887
- PartialWindowImage: 12
888
- };
889
- function assertUint(name, value, max) {
890
- if (!Number.isInteger(value) || value < 0 || value > max) {
891
- throw new RangeError(`${name} must be an integer between 0 and ${max}, got ${value}`);
892
- }
893
- }
894
- function assertRgb([r, g, b]) {
895
- assertUint("red", r, 255);
896
- assertUint("green", g, 255);
897
- assertUint("blue", b, 255);
898
- }
899
- function byteAt(data, offset) {
900
- return data[offset] ?? 0;
901
- }
902
- function u16At(data, offset) {
903
- return byteAt(data, offset) | byteAt(data, offset + 1) << 8;
904
- }
905
- function u32At(data, offset) {
906
- return (u16At(data, offset) | u16At(data, offset + 2) << 16) >>> 0;
907
- }
908
- function i32At(data, offset) {
909
- return u32At(data, offset) | 0;
910
- }
911
- function asciiString(data) {
912
- let end = data.length;
913
- const nul = data.indexOf(0);
914
- if (nul !== -1)
915
- end = nul;
916
- let out = "";
917
- for (let i = 0;i < end; i++)
918
- out += String.fromCharCode(byteAt(data, i));
919
- return out;
920
- }
921
- function featureReport(command, ...payload) {
922
- const report = new Uint8Array(FEATURE_REPORT_SIZE);
923
- report[0] = SETTER_REPORT_ID;
924
- report[1] = command;
925
- report.set(payload, 2);
926
- return report;
927
- }
928
- function showLogoReport() {
929
- return featureReport(SetterCommand.ShowLogo);
930
- }
931
- function fillLcdReport(color) {
932
- assertRgb(color);
933
- return featureReport(SetterCommand.FillLcd, ...color);
934
- }
935
- function fillKeyReport(index, color) {
936
- assertUint("key index", index, 255);
937
- assertRgb(color);
938
- return featureReport(SetterCommand.FillKey, index, ...color);
939
- }
940
- function brightnessReport(percent) {
941
- assertUint("brightness", percent, 100);
942
- return featureReport(SetterCommand.Brightness, percent);
943
- }
944
- function sleepDurationReport(seconds) {
945
- assertUint("sleep duration", seconds, 2147483647);
946
- return featureReport(SetterCommand.SleepDuration, seconds & 255, seconds >>> 8 & 255, seconds >>> 16 & 255, seconds >>> 24 & 255);
947
- }
948
- function parseFirmwareVersion(report) {
949
- return {
950
- checksum: u32At(report, 2),
951
- version: asciiString(report.subarray(6, 14))
952
- };
953
- }
954
- function parseSerialNumber(report) {
955
- const length = byteAt(report, 1);
956
- return asciiString(report.subarray(2, 2 + length));
957
- }
958
- function parseSleepDuration(report) {
959
- return i32At(report, 2);
960
- }
961
- function parseUnitInformation(report) {
962
- if (report.length < 15) {
963
- throw new RangeError(`unit information report too short: ${report.length} bytes`);
964
- }
965
- return {
966
- keyRows: byteAt(report, 1),
967
- keyColumns: byteAt(report, 2),
968
- keyWidth: u16At(report, 3),
969
- keyHeight: u16At(report, 5),
970
- lcdWidth: u16At(report, 7),
971
- lcdHeight: u16At(report, 9),
972
- imageBitsPerPixel: byteAt(report, 11),
973
- imageColorScheme: byteAt(report, 12),
974
- galleryKeyImages: byteAt(report, 13),
975
- galleryLcdImages: byteAt(report, 14),
976
- demoFrames: byteAt(report, 15)
977
- };
978
- }
979
- function chunkedImagePackets(image, headerSize, writeHeader) {
980
- if (image.length === 0)
981
- throw new RangeError("image data is empty");
982
- const maxChunk = OUTPUT_REPORT_SIZE - headerSize;
983
- const packets = [];
984
- for (let offset = 0, index = 0;offset < image.length; offset += maxChunk, index++) {
985
- const chunk = image.subarray(offset, offset + maxChunk);
986
- const isLast = offset + maxChunk >= image.length;
987
- if (index > 65535)
988
- throw new RangeError("image is too large");
989
- const packet = new Uint8Array(OUTPUT_REPORT_SIZE);
990
- packet[0] = OUTPUT_REPORT_ID;
991
- writeHeader(packet, index, chunk.length, isLast);
992
- packet.set(chunk, headerSize);
993
- packets.push(packet);
994
- }
995
- return packets;
996
- }
997
- function standardImagePackets(command, byte2, image) {
998
- return chunkedImagePackets(image, 8, (packet, index, size, isLast) => {
999
- packet[1] = command;
1000
- packet[2] = byte2;
1001
- packet[3] = isLast ? 1 : 0;
1002
- packet[4] = size & 255;
1003
- packet[5] = size >>> 8;
1004
- packet[6] = index & 255;
1005
- packet[7] = index >>> 8;
1006
- });
1007
- }
1008
- function buttonImagePackets(index, jpeg) {
1009
- assertUint("key index", index, 255);
1010
- return standardImagePackets(OutputCommand.ButtonImage, index, jpeg);
1011
- }
1012
- function fullScreenImagePackets(jpeg) {
1013
- return standardImagePackets(OutputCommand.FullScreenImage, 0, jpeg);
1014
- }
1015
- function windowImagePackets(jpeg) {
1016
- return standardImagePackets(OutputCommand.WindowImage, 0, jpeg);
1017
- }
1018
- function partialWindowImagePackets(region, jpeg) {
1019
- assertUint("x", region.x, 65535);
1020
- assertUint("y", region.y, 65535);
1021
- assertUint("width", region.width, 65535);
1022
- assertUint("height", region.height, 65535);
1023
- return chunkedImagePackets(jpeg, 16, (packet, index, size, isLast) => {
1024
- packet[1] = OutputCommand.PartialWindowImage;
1025
- packet[2] = region.x & 255;
1026
- packet[3] = region.x >>> 8;
1027
- packet[4] = region.y & 255;
1028
- packet[5] = region.y >>> 8;
1029
- packet[6] = region.width & 255;
1030
- packet[7] = region.width >>> 8;
1031
- packet[8] = region.height & 255;
1032
- packet[9] = region.height >>> 8;
1033
- packet[10] = isLast ? 1 : 0;
1034
- packet[11] = index & 255;
1035
- packet[12] = index >>> 8;
1036
- packet[13] = size & 255;
1037
- packet[14] = size >>> 8;
1038
- packet[15] = 0;
1039
- });
1040
- }
1041
- function parseInputReport(data) {
1042
- if (data.length < 4 || data[0] !== INPUT_REPORT_ID || data[1] !== 0)
1043
- return null;
1044
- const count = Math.min(u16At(data, 2), data.length - 4);
1045
- const states = [];
1046
- for (let i = 0;i < count; i++)
1047
- states.push(byteAt(data, 4 + i) === 1);
1048
- return states;
1049
- }
1050
-
1051
- // ../neo/src/model.ts
1052
- var NEO_LAYOUT = {
1053
- screen: { width: 480, height: 320 },
1054
- keys: Array.from({ length: 8 }, (_, i) => ({
1055
- x: 3 + i % 4 * 126,
1056
- y: 9 + Math.floor(i / 4) * 126,
1057
- width: 96,
1058
- height: 96
1059
- })),
1060
- sensors: [
1061
- { x: 3, y: 283, width: 96, height: 16 },
1062
- { x: 381, y: 283, width: 96, height: 16 }
1063
- ],
1064
- window: { x: 116, y: 262, width: 248, height: 58 }
1065
- };
1066
- var NEO_MODEL = {
1067
- id: "neo",
1068
- name: "Stream Deck Neo",
1069
- vendorId: ELGATO_VENDOR_ID,
1070
- productId: STREAM_DECK_NEO_PRODUCT_ID,
1071
- layout: NEO_LAYOUT,
1072
- rotation: 180
1073
- };
1074
-
1075
- // ../neo/src/neo.ts
1076
- var FIRMWARE_REPORT_IDS = {
1077
- ld: GetterReportId.FirmwareLd,
1078
- ap1: GetterReportId.FirmwareAp1,
1079
- ap2: GetterReportId.FirmwareAp2
1080
- };
1081
-
1082
- class StreamDeckNeo extends StreamDeck {
1083
- static KEY_COUNT = 8;
1084
- static SENSOR_COUNT = 2;
1085
- static KEY_SIZE = { width: 96, height: 96 };
1086
- static SCREEN_SIZE = { width: 480, height: 320 };
1087
- static WINDOW_SIZE = { width: 248, height: 58 };
1088
- static SENSOR_SIZE = { width: 96, height: 16 };
1089
- constructor(transport) {
1090
- super(transport, NEO_MODEL);
1091
- }
1092
- parseInput(data) {
1093
- return parseInputReport(data) ?? undefined;
1094
- }
1095
- sendKeyJpeg(index, jpeg) {
1096
- return this.#write(buttonImagePackets(index, jpeg));
1097
- }
1098
- sendScreenJpeg(jpeg) {
1099
- return this.#write(fullScreenImagePackets(jpeg));
1100
- }
1101
- sendWindowJpeg(jpeg) {
1102
- return this.#write(windowImagePackets(jpeg));
1103
- }
1104
- sendWindowRegionJpeg(region, jpeg) {
1105
- return this.#write(partialWindowImagePackets(region, jpeg));
1106
- }
1107
- sendFillKey(index, color) {
1108
- return this.transport.sendFeatureReport(fillKeyReport(index, color));
1109
- }
1110
- sendFillScreen(color) {
1111
- return this.transport.sendFeatureReport(fillLcdReport(color));
1112
- }
1113
- async onClosing() {
1114
- await this.transport.sendFeatureReport(showLogoReport());
1115
- }
1116
- setBrightness(percent) {
1117
- return this.#feature(brightnessReport(percent));
1118
- }
1119
- showLogo() {
1120
- return this.#feature(showLogoReport());
1121
- }
1122
- setSleepDuration(seconds) {
1123
- return this.#feature(sleepDurationReport(seconds));
1124
- }
1125
- async getSleepDuration() {
1126
- return parseSleepDuration(await this.#getFeature(GetterReportId.SleepDuration));
1127
- }
1128
- async getFirmwareVersion(kind = "ap2") {
1129
- return parseFirmwareVersion(await this.#getFeature(FIRMWARE_REPORT_IDS[kind]));
1130
- }
1131
- async getSerialNumber() {
1132
- return parseSerialNumber(await this.#getFeature(GetterReportId.SerialNumber));
1133
- }
1134
- async getUnitInformation() {
1135
- return parseUnitInformation(await this.#getFeature(GetterReportId.UnitInformation));
1136
- }
1137
- #feature(report) {
1138
- return this.enqueue(() => this.transport.sendFeatureReport(report));
1139
- }
1140
- #getFeature(reportId) {
1141
- return this.enqueue(() => this.transport.getFeatureReport(reportId, FEATURE_REPORT_SIZE));
1142
- }
1143
- async#write(packets) {
1144
- for (const packet of packets)
1145
- await this.transport.write(packet);
1146
- }
1147
- }
1148
- var neoDriver = {
1149
- model: NEO_MODEL,
1150
- create: (transport) => new StreamDeckNeo(transport)
1151
- };
1152
-
1153
- // ../neo/src/detect.ts
1154
- function openStreamDeckNeo(options = {}) {
1155
- return openDeck(neoDriver, options);
1156
- }
1157
- // ../react/src/render.ts
1158
- function isReactElement(value) {
1159
- return typeof value === "object" && value !== null && "$$typeof" in value;
1160
- }
1161
- var defaultRenderer = {};
1162
- var fontRenderers = new WeakMap;
1163
- async function createRenderer(fonts) {
1164
- const { Renderer } = await import("@takumi-rs/core");
1165
- const renderer = new Renderer;
1166
- for (const font of fonts) {
1167
- await renderer.registerFont({
1168
- name: font.name,
1169
- data: font.data,
1170
- ...font.weight !== undefined && { weight: font.weight },
1171
- ...font.style !== undefined && { style: font.style }
1172
- });
1173
- }
1174
- return renderer;
1175
- }
1176
- function getRenderer(fonts) {
1177
- if (!fonts?.length) {
1178
- defaultRenderer.current ??= createRenderer([]);
1179
- defaultRenderer.current.catch(() => {
1180
- defaultRenderer.current = undefined;
1181
- });
1182
- return defaultRenderer.current;
1183
- }
1184
- let renderer = fontRenderers.get(fonts);
1185
- if (!renderer) {
1186
- renderer = createRenderer(fonts);
1187
- renderer.catch(() => fontRenderers.delete(fonts));
1188
- fontRenderers.set(fonts, renderer);
1189
- }
1190
- return renderer;
1191
- }
1192
- var number = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
1193
- function toNode(node, text = true) {
1194
- if ("text" in node) {
1195
- return text ? { type: "text", text: node.text } : { type: "container", children: [] };
1196
- }
1197
- const { style, tw, src, width, height } = node.props;
1198
- const common = {
1199
- ...typeof tw === "string" && { tw }
1200
- };
1201
- if (node.type === "img") {
1202
- if (typeof src !== "string")
1203
- throw new Error("<img> needs a string `src` (URL or data: URI)");
1204
- return {
1205
- type: "image",
1206
- src,
1207
- ...number(width) !== undefined && { width: number(width) },
1208
- ...number(height) !== undefined && { height: number(height) },
1209
- ...typeof style === "object" && style !== null && { style },
1210
- ...common
1211
- };
1212
- }
1213
- return {
1214
- type: "container",
1215
- style: { display: "flex", ...typeof style === "object" ? style : {} },
1216
- children: node.children.filter((child) => text || !("text" in child)).map((child) => toNode(child, text)),
1217
- ...common
1218
- };
1219
- }
1220
- var reconciler;
1221
- var flushing = 0;
1222
- function flushAll(renderer) {
1223
- flushing++;
1224
- try {
1225
- renderer.flushSyncWork();
1226
- for (let i = 0;i < 20 && renderer.flushPassiveEffects(); i++)
1227
- renderer.flushSyncWork();
1228
- } finally {
1229
- flushing--;
1230
- }
1231
- }
1232
- function loadReconciler() {
1233
- reconciler ??= (async () => {
1234
- let factoryModule;
1235
- let constants;
1236
- let React;
1237
- try {
1238
- [factoryModule, constants, React] = await Promise.all([
1239
- import("react-reconciler"),
1240
- import("react-reconciler/constants.js"),
1241
- import("react")
1242
- ]);
1243
- } catch (cause) {
1244
- throw new Error("Rendering React elements requires `react` (>=19.3) to be installed", {
1245
- cause
1246
- });
1247
- }
1248
- let priority = constants.NoEventPriority;
1249
- const noop = () => {};
1250
- const hostConfig = {
1251
- supportsMutation: true,
1252
- supportsPersistence: false,
1253
- supportsHydration: false,
1254
- isPrimaryRenderer: true,
1255
- warnsIfNotActing: false,
1256
- noTimeout: -1,
1257
- scheduleTimeout: setTimeout,
1258
- cancelTimeout: clearTimeout,
1259
- supportsMicrotasks: true,
1260
- scheduleMicrotask: queueMicrotask,
1261
- createInstance: (type, props) => {
1262
- const { children: _children, ...rest } = props;
1263
- return { type, props: rest, children: [] };
1264
- },
1265
- createTextInstance: (text) => ({ text }),
1266
- shouldSetTextContent: () => false,
1267
- appendInitialChild: (parent, child) => parent.children.push(child),
1268
- appendChild: (parent, child) => parent.children.push(child),
1269
- appendChildToContainer: (container, child) => container.children.push(child),
1270
- insertBefore: (parent, child, before) => {
1271
- const children = parent.children;
1272
- const existing = children.indexOf(child);
1273
- if (existing !== -1)
1274
- children.splice(existing, 1);
1275
- children.splice(children.indexOf(before), 0, child);
1276
- },
1277
- insertInContainerBefore: (container, child, before) => {
1278
- const children = container.children;
1279
- const existing = children.indexOf(child);
1280
- if (existing !== -1)
1281
- children.splice(existing, 1);
1282
- children.splice(children.indexOf(before), 0, child);
1283
- },
1284
- removeChild: (parent, child) => {
1285
- parent.children.splice(parent.children.indexOf(child), 1);
1286
- },
1287
- removeChildFromContainer: (container, child) => {
1288
- container.children.splice(container.children.indexOf(child), 1);
1289
- },
1290
- clearContainer: (container) => {
1291
- container.children = [];
1292
- },
1293
- commitUpdate: (instance, _type, _prev, next) => {
1294
- const { children: _children, ...rest } = next;
1295
- instance.props = rest;
1296
- },
1297
- commitTextUpdate: (text, _old, next) => {
1298
- text.text = next;
1299
- },
1300
- finalizeInitialChildren: () => false,
1301
- getPublicInstance: (instance) => instance,
1302
- getRootHostContext: () => ({}),
1303
- getChildHostContext: (parent) => parent,
1304
- prepareForCommit: () => null,
1305
- resetAfterCommit: (container) => container.onCommit(),
1306
- preparePortalMount: noop,
1307
- detachDeletedInstance: noop,
1308
- hideInstance: noop,
1309
- unhideInstance: noop,
1310
- hideTextInstance: noop,
1311
- unhideTextInstance: noop,
1312
- getInstanceFromNode: () => null,
1313
- beforeActiveInstanceBlur: noop,
1314
- afterActiveInstanceBlur: noop,
1315
- prepareScopeUpdate: noop,
1316
- getInstanceFromScope: () => null,
1317
- bindToConsole: (method, args) => console[method]?.bind(console, ...args) ?? noop,
1318
- extraDevToolsConfig: null,
1319
- rendererVersion: "0.0.0",
1320
- rendererPackageName: "sdeck",
1321
- getCurrentUpdatePriority: () => priority,
1322
- setCurrentUpdatePriority: (next) => {
1323
- priority = next;
1324
- },
1325
- resolveUpdatePriority: () => priority !== constants.NoEventPriority ? priority : flushing > 0 ? constants.DiscreteEventPriority : constants.DefaultEventPriority,
1326
- resolveEventType: () => null,
1327
- resolveEventTimeStamp: () => -1.1,
1328
- shouldAttemptEagerTransition: () => false,
1329
- trackSchedulerEvent: noop,
1330
- requestPostPaintCallback: noop,
1331
- maySuspendCommit: () => false,
1332
- preloadInstance: () => true,
1333
- startSuspendingCommit: noop,
1334
- suspendInstance: noop,
1335
- waitForCommitToBeReady: () => null,
1336
- getSuspendedCommitReason: () => null,
1337
- NotPendingTransition: null,
1338
- HostTransitionContext: React.createContext(null),
1339
- resetFormInstance: noop
1340
- };
1341
- const factory = factoryModule.default ?? factoryModule;
1342
- return factory(hostConfig);
1343
- })();
1344
- reconciler.catch(() => {
1345
- reconciler = undefined;
1346
- });
1347
- return reconciler;
1348
- }
1349
- function noopIndicator() {}
1350
- async function createReactRoot(size, onFrame, options = {}) {
1351
- const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);
1352
- let dirty = false;
1353
- let drawing;
1354
- let lastTree;
1355
- let unmounted = false;
1356
- let renderError;
1357
- let initial = true;
1358
- const fail = (error) => {
1359
- if (initial)
1360
- renderError ??= { error };
1361
- else
1362
- (options.onError ?? ((e) => console.error("sdeck: React render failed:", e)))(error);
1363
- };
1364
- async function draw() {
1365
- await Promise.resolve();
1366
- while (dirty && !unmounted) {
1367
- dirty = false;
1368
- try {
1369
- const [root] = container.children;
1370
- if (!root)
1371
- continue;
1372
- const tree = toNode(root, options.text !== false);
1373
- const key = JSON.stringify(tree);
1374
- if (key === lastTree)
1375
- continue;
1376
- lastTree = key;
1377
- const pixels = await takumi.render(tree, {
1378
- width: size.width,
1379
- height: size.height,
1380
- format: "raw",
1381
- ...options.scale !== undefined && { devicePixelRatio: options.scale }
1382
- });
1383
- await onFrame({
1384
- data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
1385
- width: size.width,
1386
- height: size.height,
1387
- channels: 4
1388
- });
1389
- } catch (error) {
1390
- lastTree = undefined;
1391
- fail(error);
1392
- }
1393
- }
1394
- drawing = undefined;
1395
- }
1396
- const container = {
1397
- children: [],
1398
- onCommit() {
1399
- dirty = true;
1400
- drawing ??= draw();
1401
- }
1402
- };
1403
- const onError = (error) => fail(error);
1404
- const onCaughtError = () => {};
1405
- const root = renderer.createContainer(container, 1, null, false, null, "", onError, onCaughtError, onError, noopIndicator, null);
1406
- const flush = () => flushAll(renderer);
1407
- const handle = {
1408
- render(element) {
1409
- if (unmounted)
1410
- throw new Error("This React root was unmounted");
1411
- renderer.updateContainerSync(element, root, null, null);
1412
- flush();
1413
- },
1414
- async idle() {
1415
- while (drawing)
1416
- await drawing;
1417
- if (initial && renderError) {
1418
- const { error } = renderError;
1419
- renderError = undefined;
1420
- throw error;
1421
- }
1422
- initial = false;
1423
- },
1424
- async unmount() {
1425
- if (unmounted)
1426
- return;
1427
- renderer.updateContainerSync(null, root, null, null);
1428
- flush();
1429
- unmounted = true;
1430
- await drawing;
1431
- }
1432
- };
1433
- return handle;
1434
- }
1435
- async function renderReact(element, size, fonts, scale) {
1436
- let frame;
1437
- const root = await createReactRoot(size, (next) => {
1438
- frame = next;
1439
- }, { ...fonts && { fonts }, ...scale !== undefined && { scale } });
1440
- try {
1441
- root.render(element);
1442
- await root.idle();
1443
- } finally {
1444
- await root.unmount();
1445
- }
1446
- if (!frame)
1447
- throw new Error("React element rendered nothing");
1448
- return frame;
1449
- }
1450
- registerElementRuntime({
1451
- matches: isReactElement,
1452
- render: (element, size, options) => renderReact(element, size, options?.fonts),
1453
- createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options)
1454
- });
1455
- // ../app/src/app.tsx
1456
- import { Fragment, useSyncExternalStore } from "react";
1457
-
1458
- // ../app/src/context.ts
1459
- import { createContext, useContext } from "react";
1460
- var DeckContext = createContext(undefined);
1461
- var SlotContext = createContext(undefined);
1462
- var NavigatorContext = createContext(undefined);
1463
- function useDeck() {
1464
- const deck = useContext(DeckContext);
1465
- if (!deck)
1466
- throw new Error("useDeck() must be used inside a component mounted by @sdeck/app");
1467
- return deck;
1468
- }
1469
- function useSlot() {
1470
- return useContext(SlotContext);
1471
- }
1472
-
1473
- // ../app/src/navigator.ts
1474
- class Navigator {
1475
- #initial;
1476
- #has;
1477
- #listeners = new Set;
1478
- #state;
1479
- pages;
1480
- sequence;
1481
- constructor(initial, has, pages = [], sequence = pages) {
1482
- this.#initial = initial;
1483
- this.#has = has;
1484
- this.pages = pages;
1485
- this.sequence = sequence;
1486
- this.#state = { page: initial, stack: [initial], forwardStack: [] };
1487
- }
1488
- getSnapshot = () => this.#state;
1489
- subscribe = (listener) => {
1490
- this.#listeners.add(listener);
1491
- return () => void this.#listeners.delete(listener);
1492
- };
1493
- get page() {
1494
- return this.#state.page;
1495
- }
1496
- push = (page) => {
1497
- this.#assert(page);
1498
- if (page === this.#state.page)
1499
- return;
1500
- this.#set([...this.#state.stack, page], []);
1501
- };
1502
- replace = (page) => {
1503
- this.#assert(page);
1504
- if (page === this.#state.page)
1505
- return;
1506
- this.#set([...this.#state.stack.slice(0, -1), page], []);
1507
- };
1508
- back = () => {
1509
- const { stack, page, forwardStack } = this.#state;
1510
- if (stack.length < 2)
1511
- return false;
1512
- this.#set(stack.slice(0, -1), [page, ...forwardStack]);
1513
- return true;
1514
- };
1515
- forward = () => {
1516
- const [next, ...rest] = this.#state.forwardStack;
1517
- if (next === undefined)
1518
- return false;
1519
- this.#set([...this.#state.stack, next], rest);
1520
- return true;
1521
- };
1522
- next = (wrap = false) => this.#step(1, wrap);
1523
- previous = (wrap = false) => this.#step(-1, wrap);
1524
- #step(by, wrap) {
1525
- const order = this.sequence;
1526
- const n = order.length;
1527
- const i = order.indexOf(this.#state.page);
1528
- if (i === -1 || n < 2)
1529
- return false;
1530
- let j = i + by;
1531
- if (j < 0 || j >= n) {
1532
- if (!wrap)
1533
- return false;
1534
- j = (j + n) % n;
1535
- }
1536
- this.push(order[j]);
1537
- return true;
1538
- }
1539
- home = () => {
1540
- const { stack, page, forwardStack } = this.#state;
1541
- if (stack.length === 1 && page === this.#initial && forwardStack.length === 0)
1542
- return;
1543
- this.#set([this.#initial], []);
1544
- };
1545
- #assert(page) {
1546
- if (!this.#has(page))
1547
- throw new RangeError(`unknown page "${page}"`);
1548
- }
1549
- #set(stack, forwardStack) {
1550
- this.#state = { page: stack.at(-1), stack, forwardStack };
1551
- for (const listener of [...this.#listeners])
1552
- listener();
1553
- }
1554
- }
1555
-
1556
- // ../app/src/app.tsx
1557
- import { jsx } from "react/jsx-runtime";
1558
- function defineApp(app) {
1559
- const names = Object.keys(app.pages);
1560
- if (names.length === 0)
1561
- throw new RangeError("an app needs at least one page");
1562
- if (app.initial !== undefined && !(app.initial in app.pages)) {
1563
- throw new RangeError(`initial page "${app.initial}" is not defined`);
1564
- }
1565
- for (const [name, page] of Object.entries(app.pages)) {
1566
- const indices = Array.isArray(page.keys) ? page.keys.length > 0 ? [page.keys.length - 1] : [] : Object.keys(page.keys ?? {}).map(Number);
1567
- for (const index of indices) {
1568
- if (!Number.isInteger(index) || index < 0) {
1569
- throw new RangeError(`page "${name}": key index must be a non-negative integer, got ${index}`);
1570
- }
1571
- }
1572
- }
1573
- return app;
1574
- }
1575
- function createNavigator(app) {
1576
- const initial = app.initial ?? Object.keys(app.pages)[0];
1577
- const pages = Object.keys(app.pages);
1578
- const sequence = app.sequence?.filter((page) => Object.hasOwn(app.pages, page)) ?? pages;
1579
- return new Navigator(initial, (page) => Object.hasOwn(app.pages, page), pages, sequence);
1580
- }
1581
- function Blank({ background }) {
1582
- return /* @__PURE__ */ jsx("div", {
1583
- style: { display: "flex", width: "100%", height: "100%", background }
1584
- });
1585
- }
1586
- function PageSlot({
1587
- app,
1588
- nav,
1589
- pick
1590
- }) {
1591
- const { page } = useSyncExternalStore(nav.subscribe, nav.getSnapshot);
1592
- const content = pick(app.pages[page] ?? {});
1593
- return /* @__PURE__ */ jsx(Fragment, {
1594
- children: content ?? /* @__PURE__ */ jsx(Blank, {
1595
- background: app.background ?? "#000000"
1596
- })
1597
- }, page);
1598
- }
1599
- function Providers({
1600
- deck,
1601
- nav,
1602
- slot,
1603
- children
1604
- }) {
1605
- return /* @__PURE__ */ jsx(DeckContext.Provider, {
1606
- value: deck,
1607
- children: /* @__PURE__ */ jsx(NavigatorContext.Provider, {
1608
- value: nav,
1609
- children: /* @__PURE__ */ jsx(SlotContext.Provider, {
1610
- value: slot,
1611
- children
1612
- })
1613
- })
1614
- });
1615
- }
1616
- async function mountApp(deck, app, options = {}) {
1617
- const nav = options.navigation ?? createNavigator(app);
1618
- const { heartbeatMs = 3000 } = options;
1619
- const cleanups = [];
1620
- const roots = [];
1621
- const report = (error) => options.onError?.(toError(error));
1622
- const watch = watchDeck(deck, { heartbeatMs, onError: report });
1623
- const lost = watch.lost;
1624
- cleanups.push(() => watch.stop());
1625
- const dispose = async () => {
1626
- for (const cleanup of cleanups.splice(0))
1627
- cleanup();
1628
- await deck.close().catch(() => {});
1629
- };
1630
- try {
1631
- if (app.brightness !== undefined)
1632
- await deck.setBrightness(app.brightness);
1633
- if (app.sleepSeconds !== undefined) {
1634
- const sleepable = deck;
1635
- await sleepable.setSleepDuration?.(app.sleepSeconds);
1636
- }
1637
- await app.onConnect?.(deck);
1638
- if (app.idle) {
1639
- const { afterMs, brightness: dimmed = 5 } = app.idle;
1640
- const awake = app.brightness ?? 100;
1641
- let dim;
1642
- let isDim = false;
1643
- const arm = () => {
1644
- clearTimeout(dim);
1645
- dim = setTimeout(() => {
1646
- isDim = true;
1647
- deck.setBrightness(dimmed).catch(report);
1648
- }, afterMs);
1649
- };
1650
- const wake = () => {
1651
- if (isDim) {
1652
- isDim = false;
1653
- deck.setBrightness(awake).catch(report);
1654
- }
1655
- arm();
1656
- };
1657
- for (const event of ["keyDown", "keyUp", "sensorDown", "sensorUp"]) {
1658
- cleanups.push(deck.on(event, wake));
1659
- }
1660
- cleanups.push(() => clearTimeout(dim));
1661
- arm();
1662
- }
1663
- const mountOptions = {
1664
- background: app.background,
1665
- ...app.mount,
1666
- onError: app.mount?.onError ?? report
1667
- };
1668
- const pages = Object.values(app.pages);
1669
- const slot = (info, pick) => /* @__PURE__ */ jsx(Providers, {
1670
- deck,
1671
- nav,
1672
- slot: info,
1673
- children: /* @__PURE__ */ jsx(PageSlot, {
1674
- app,
1675
- nav,
1676
- pick
1677
- })
1678
- });
1679
- roots.push(...await Promise.all(Array.from({ length: deck.keyCount }, (_, index) => deck.mountKey(index, slot({ kind: "key", index }, (page) => page.keys?.[index]), mountOptions))));
1680
- if (deck.model.layout.window) {
1681
- roots.push(await deck.mountWindow(slot({ kind: "window" }, (page) => page.window), mountOptions));
1682
- }
1683
- for (let index = 0;index < deck.sensorCount; index++) {
1684
- if (!pages.some((page) => page.sensors?.[index] !== undefined))
1685
- continue;
1686
- roots.push(await deck.mountSensor(index, slot({ kind: "sensor", index }, (page) => page.sensors?.[index]), app.sensorText === false ? { ...mountOptions, text: false } : mountOptions));
1687
- }
1688
- } catch (error) {
1689
- await dispose();
1690
- throw error;
1691
- }
1692
- return { navigation: nav, lost, dispose };
1693
- }
1694
- function runApp(app, options = {}) {
1695
- const navigation = createNavigator(app);
1696
- const handle = manageDeck({
1697
- open: options.openDeck ?? ((signal) => openStreamDeckNeo({ ...options.open, signal })),
1698
- async setup(deck) {
1699
- const session = await mountApp(deck, app, {
1700
- navigation,
1701
- heartbeatMs: 0,
1702
- ...options.onError && { onError: options.onError }
1703
- });
1704
- return () => session.dispose();
1705
- },
1706
- ...options.reconnect !== undefined && { reconnect: options.reconnect },
1707
- ...options.signal && { signal: options.signal },
1708
- ...options.heartbeatMs !== undefined && { heartbeatMs: options.heartbeatMs },
1709
- ...options.onStatus && { onStatus: options.onStatus },
1710
- ...options.onError && { onError: options.onError }
1711
- });
1712
- return {
1713
- get status() {
1714
- return handle.status;
1715
- },
1716
- get deck() {
1717
- return handle.deck;
1718
- },
1719
- navigation,
1720
- stop: handle.stop,
1721
- finished: handle.finished
1722
- };
1723
- }
1724
- // ../app/src/hooks.ts
1725
- import { useContext as useContext2, useEffect, useRef, useState, useSyncExternalStore as useSyncExternalStore2 } from "react";
1726
-
1727
- // ../app/src/swipe.ts
1728
- var SWIPE_WINDOW_MS = 400;
1729
-
1730
- class SwipeTracker {
1731
- #handlers = new Set;
1732
- #stamps = new Map;
1733
- #completing = new Set;
1734
- #first;
1735
- constructor(deck) {
1736
- deck.on("sensorDown", (index) => this.#down(index));
1737
- }
1738
- get active() {
1739
- return this.#handlers.size > 0;
1740
- }
1741
- stamp(index) {
1742
- return this.#stamps.get(index) ?? 0;
1743
- }
1744
- completes(index) {
1745
- return this.#completing.has(index);
1746
- }
1747
- listen(handler) {
1748
- this.#handlers.add(handler);
1749
- return () => void this.#handlers.delete(handler);
1750
- }
1751
- #down(index) {
1752
- this.#completing.delete(index);
1753
- const now = performance.now();
1754
- const first = this.#first;
1755
- if (!this.active || !first || first.index === index || now - first.at > SWIPE_WINDOW_MS) {
1756
- this.#first = { index, at: now };
1757
- return;
1758
- }
1759
- this.#first = undefined;
1760
- this.#completing.add(index);
1761
- for (const sensor of [first.index, index])
1762
- this.#stamps.set(sensor, this.stamp(sensor) + 1);
1763
- const direction = index > first.index ? "right" : "left";
1764
- for (const handler of [...this.#handlers])
1765
- handler(direction);
1766
- }
1767
- }
1768
- var trackers = new WeakMap;
1769
- function swipeTracker(deck) {
1770
- let tracker = trackers.get(deck);
1771
- if (!tracker) {
1772
- tracker = new SwipeTracker(deck);
1773
- trackers.set(deck, tracker);
1774
- }
1775
- return tracker;
1776
- }
1777
-
1778
- // ../app/src/hooks.ts
1779
- function useLatest(value) {
1780
- const ref = useRef(value);
1781
- useEffect(() => {
1782
- ref.current = value;
1783
- });
1784
- return ref;
1785
- }
1786
- function useTarget(kind, explicit) {
1787
- const slot = useSlot();
1788
- if (explicit !== undefined)
1789
- return explicit;
1790
- return slot?.kind === kind ? slot.index : undefined;
1791
- }
1792
- function useInput(kind, phase, handler, explicit) {
1793
- const deck = useDeck();
1794
- const target = useTarget(kind, explicit);
1795
- const latest = useLatest(handler);
1796
- useEffect(() => {
1797
- const matches = (index) => target === undefined || index === target;
1798
- if (phase === "Down") {
1799
- return deck.on(`${kind}Down`, (index) => matches(index) && latest.current(index));
1800
- }
1801
- const held = new Set;
1802
- const offDown = deck.on(`${kind}Down`, (index) => matches(index) && held.add(index));
1803
- const offUp = deck.on(`${kind}Up`, (index) => {
1804
- if (held.delete(index))
1805
- latest.current(index);
1806
- });
1807
- return () => {
1808
- offDown();
1809
- offUp();
1810
- };
1811
- }, [deck, kind, phase, target, latest]);
1812
- }
1813
- function usePressed(kind, explicit) {
1814
- const deck = useDeck();
1815
- const target = useTarget(kind, explicit);
1816
- const [pressed, setPressed] = useState(false);
1817
- if (target === undefined) {
1818
- throw new Error(`use${kind === "key" ? "Key" : "Sensor"}Pressed() needs an index outside a ${kind} slot`);
1819
- }
1820
- useEffect(() => {
1821
- setPressed(false);
1822
- const offDown = deck.on(`${kind}Down`, (i) => i === target && setPressed(true));
1823
- const offUp = deck.on(`${kind}Up`, (i) => i === target && setPressed(false));
1824
- return () => {
1825
- offDown();
1826
- offUp();
1827
- };
1828
- }, [deck, kind, target]);
1829
- return pressed;
1830
- }
1831
- function useKeyDown(handler, key) {
1832
- useInput("key", "Down", handler, key);
1833
- }
1834
- function useKeyUp(handler, key) {
1835
- useInput("key", "Up", handler, key);
1836
- }
1837
- function useKeyPressed(key) {
1838
- return usePressed("key", key);
1839
- }
1840
- function usePress(kind, onPress, gestures, explicit) {
1841
- const deck = useDeck();
1842
- const target = useTarget(kind, explicit);
1843
- const latest = useLatest({
1844
- onPress,
1845
- onLongPress: gestures.onLongPress,
1846
- longPressMs: gestures.longPressMs ?? 500,
1847
- onDoublePress: gestures.onDoublePress ?? gestures.onDoubleTap,
1848
- doublePressMs: gestures.doublePressMs ?? gestures.doubleTapMs ?? 300,
1849
- onRelease: gestures.onRelease ?? false
1850
- });
1851
- useEffect(() => {
1852
- const swipes = kind === "sensor" ? swipeTracker(deck) : undefined;
1853
- const state = new Map;
1854
- const held = new Set;
1855
- const get = (index) => {
1856
- let s = state.get(index);
1857
- if (!s) {
1858
- s = { longFired: false, immediate: false, downAt: 0, stamp: 0 };
1859
- state.set(index, s);
1860
- }
1861
- return s;
1862
- };
1863
- const offDown = deck.on(`${kind}Down`, (index) => {
1864
- if (target !== undefined && index !== target)
1865
- return;
1866
- if (swipes?.completes(index))
1867
- return;
1868
- held.add(index);
1869
- const o = latest.current;
1870
- const s = get(index);
1871
- s.longFired = false;
1872
- s.downAt = performance.now();
1873
- s.stamp = swipes?.stamp(index) ?? 0;
1874
- s.immediate = !o.onLongPress && !o.onDoublePress && !o.onRelease && !swipes?.active;
1875
- if (s.immediate) {
1876
- o.onPress?.(index);
1877
- return;
1878
- }
1879
- if (o.onLongPress) {
1880
- s.long = setTimeout(() => {
1881
- if (swipes && swipes.stamp(index) !== s.stamp)
1882
- return;
1883
- s.longFired = true;
1884
- clearTimeout(s.double);
1885
- s.double = undefined;
1886
- latest.current.onLongPress?.(index);
1887
- }, o.longPressMs);
1888
- }
1889
- });
1890
- const offUp = deck.on(`${kind}Up`, (index) => {
1891
- if (!held.delete(index))
1892
- return;
1893
- const s = get(index);
1894
- clearTimeout(s.long);
1895
- if (s.immediate || s.longFired)
1896
- return;
1897
- if (!swipes?.active)
1898
- return released(index, s);
1899
- const wait = Math.max(0, SWIPE_WINDOW_MS - (performance.now() - s.downAt));
1900
- s.deferred = setTimeout(() => {
1901
- if (swipes.stamp(index) === s.stamp)
1902
- released(index, s);
1903
- }, wait);
1904
- });
1905
- function released(index, s) {
1906
- const o = latest.current;
1907
- if (!o.onDoublePress) {
1908
- o.onPress?.(index);
1909
- } else if (s.double !== undefined) {
1910
- clearTimeout(s.double);
1911
- s.double = undefined;
1912
- o.onDoublePress(index);
1913
- } else {
1914
- s.double = setTimeout(() => {
1915
- s.double = undefined;
1916
- latest.current.onPress?.(index);
1917
- }, o.doublePressMs);
1918
- }
1919
- }
1920
- return () => {
1921
- offDown();
1922
- offUp();
1923
- for (const s of state.values()) {
1924
- clearTimeout(s.long);
1925
- clearTimeout(s.double);
1926
- clearTimeout(s.deferred);
1927
- }
1928
- };
1929
- }, [deck, kind, target, latest]);
1930
- }
1931
- function useKeyPress(onPress, options = {}) {
1932
- usePress("key", onPress, options, options.key);
1933
- }
1934
- function useSensorPress(onPress, options = {}) {
1935
- usePress("sensor", onPress, options, options.sensor);
1936
- }
1937
- function useRepeat(kind, handler, explicit, options) {
1938
- const deck = useDeck();
1939
- const target = useTarget(kind, explicit);
1940
- const latest = useLatest({ handler, ...options });
1941
- useEffect(() => {
1942
- const swipes = kind === "sensor" ? swipeTracker(deck) : undefined;
1943
- let first;
1944
- let delay;
1945
- let repeat;
1946
- const stop = () => {
1947
- clearTimeout(delay);
1948
- clearInterval(repeat);
1949
- };
1950
- const offDown = deck.on(`${kind}Down`, (index) => {
1951
- if (target !== undefined && index !== target)
1952
- return;
1953
- if (swipes?.completes(index))
1954
- return;
1955
- stop();
1956
- clearTimeout(first);
1957
- const stamp = swipes?.stamp(index);
1958
- const swiped = () => swipes !== undefined && swipes.stamp(index) !== stamp;
1959
- const run = () => {
1960
- if (!swiped())
1961
- latest.current.handler(index);
1962
- };
1963
- if (swipes?.active)
1964
- first = setTimeout(run, SWIPE_WINDOW_MS);
1965
- else
1966
- run();
1967
- const wait = latest.current.delayMs ?? 400;
1968
- delay = setTimeout(() => {
1969
- repeat = setInterval(run, latest.current.intervalMs ?? 100);
1970
- }, swipes?.active ? Math.max(wait, SWIPE_WINDOW_MS) : wait);
1971
- });
1972
- const offUp = deck.on(`${kind}Up`, (index) => {
1973
- if (target === undefined || index === target)
1974
- stop();
1975
- });
1976
- return () => {
1977
- offDown();
1978
- offUp();
1979
- stop();
1980
- clearTimeout(first);
1981
- };
1982
- }, [deck, kind, target, latest]);
1983
- }
1984
- function useKeyRepeat(handler, options = {}) {
1985
- useRepeat("key", handler, options.key, options);
1986
- }
1987
- function useSensorRepeat(handler, options = {}) {
1988
- useRepeat("sensor", handler, options.sensor, options);
1989
- }
1990
- function useSwipe(handler) {
1991
- const deck = useDeck();
1992
- const latest = useLatest(handler);
1993
- const on = handler !== undefined;
1994
- useEffect(() => {
1995
- if (!on)
1996
- return;
1997
- return swipeTracker(deck).listen((direction) => latest.current?.(direction));
1998
- }, [deck, on, latest]);
1999
- }
2000
- function useSensorDown(handler, sensor) {
2001
- useInput("sensor", "Down", handler, sensor);
2002
- }
2003
- function useSensorUp(handler, sensor) {
2004
- useInput("sensor", "Up", handler, sensor);
2005
- }
2006
- function useSensorPressed(sensor) {
2007
- return usePressed("sensor", sensor);
2008
- }
2009
- function useInterval(callback, ms) {
2010
- const latest = useLatest(callback);
2011
- useEffect(() => {
2012
- if (ms === null)
2013
- return;
2014
- const id = setInterval(() => latest.current(), ms);
2015
- return () => clearInterval(id);
2016
- }, [ms, latest]);
2017
- }
2018
- function useNow(ms = 1000) {
2019
- const [now, setNow] = useState(() => new Date);
2020
- useInterval(() => setNow(new Date), ms);
2021
- return now;
2022
- }
2023
- function useNavigation() {
2024
- const nav = useContext2(NavigatorContext);
2025
- if (!nav)
2026
- throw new Error("useNavigation() must be used inside a component mounted by sdeck/app");
2027
- const state = useSyncExternalStore2(nav.subscribe, nav.getSnapshot);
2028
- return {
2029
- ...state,
2030
- canGoBack: state.stack.length > 1,
2031
- canGoForward: state.forwardStack.length > 0,
2032
- push: nav.push,
2033
- replace: nav.replace,
2034
- back: nav.back,
2035
- forward: nav.forward,
2036
- next: nav.next,
2037
- previous: nav.previous,
2038
- pages: nav.pages,
2039
- sequence: nav.sequence,
2040
- home: nav.home
2041
- };
2042
- }
2043
- function usePage() {
2044
- return useNavigation().page;
2045
- }
2046
-
2047
- // ../app/src/components.tsx
2048
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
2049
- var fill = {
2050
- display: "flex",
2051
- width: "100%",
2052
- height: "100%",
2053
- alignItems: "center",
2054
- justifyContent: "center"
2055
- };
2056
- function KeyButton({
2057
- label,
2058
- icon,
2059
- iconSize,
2060
- color = "#2b2b2b",
2061
- textColor = "#ffffff",
2062
- pressedColor = "#5a5a5a",
2063
- fontSize = 18,
2064
- onPress,
2065
- ...gestures
2066
- }) {
2067
- const pressed = useKeyPressed();
2068
- useKeyPress(onPress, gestures);
2069
- const size = iconSize ?? (label ? 48 : 64);
2070
- return /* @__PURE__ */ jsxs("div", {
2071
- style: {
2072
- ...fill,
2073
- flexDirection: "column",
2074
- gap: 4,
2075
- background: pressed ? pressedColor : color,
2076
- color: textColor,
2077
- fontSize,
2078
- fontWeight: 700
2079
- },
2080
- children: [
2081
- icon ? /* @__PURE__ */ jsx2("img", {
2082
- src: icon,
2083
- width: size,
2084
- height: size,
2085
- alt: ""
2086
- }) : null,
2087
- label ? /* @__PURE__ */ jsx2("div", {
2088
- style: { display: "flex" },
2089
- children: label
2090
- }) : null
2091
- ]
2092
- });
2093
- }
2094
- function SensorButton({
2095
- label,
2096
- color = "#2b2b2b",
2097
- textColor = "#ffffff",
2098
- pressedColor = "#5a5a5a",
2099
- fontSize = 11,
2100
- onPress,
2101
- ...gestures
2102
- }) {
2103
- const pressed = useSensorPressed();
2104
- useSensorPress(onPress, gestures);
2105
- return /* @__PURE__ */ jsx2("div", {
2106
- style: {
2107
- ...fill,
2108
- background: pressed ? pressedColor : color,
2109
- color: textColor,
2110
- fontSize,
2111
- fontWeight: 700
2112
- },
2113
- children: label ?? null
2114
- });
2115
- }
2116
- function BackButton(props) {
2117
- const { back } = useNavigation();
2118
- return /* @__PURE__ */ jsx2(KeyButton, {
2119
- label: "Back",
2120
- ...props,
2121
- onPress: () => back()
2122
- });
2123
- }
2124
- function Clock({
2125
- format = { hour: "2-digit", minute: "2-digit", second: "2-digit" },
2126
- locale = "en-GB",
2127
- color = "#7CFC00",
2128
- background = "#202020",
2129
- fontSize = 34
2130
- }) {
2131
- const now = useNow(1000);
2132
- return /* @__PURE__ */ jsx2("div", {
2133
- style: { ...fill, background, color, fontSize },
2134
- children: now.toLocaleTimeString(locale, format)
2135
- });
2136
- }
2137
- // ../engine/src/expr.ts
2138
- class ExpressionError extends Error {
2139
- position;
2140
- constructor(message, position) {
2141
- super(message);
2142
- this.name = "ExpressionError";
2143
- this.position = position;
2144
- }
2145
- }
2146
- var OPS = ["===", "!==", "==", "!=", "<=", ">=", "&&", "||", "??", ..."+-*/%<>!?:.,()[]"];
2147
- function tokenize(src) {
2148
- const out = [];
2149
- let i = 0;
2150
- while (i < src.length) {
2151
- const c = src[i];
2152
- if (/\s/.test(c)) {
2153
- i++;
2154
- continue;
2155
- }
2156
- if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(src[i + 1] ?? "")) {
2157
- const m = /^(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/i.exec(src.slice(i));
2158
- const text = m?.[0] ?? c;
2159
- out.push({ t: "num", v: Number(text), at: i });
2160
- i += text.length;
2161
- continue;
2162
- }
2163
- if (c === '"' || c === "'") {
2164
- let v = "";
2165
- let j = i + 1;
2166
- for (;j < src.length && src[j] !== c; j++) {
2167
- if (src[j] === "\\" && j + 1 < src.length) {
2168
- const e = src[++j];
2169
- v += e === "n" ? `
2170
- ` : e === "t" ? "\t" : e;
2171
- } else
2172
- v += src[j];
2173
- }
2174
- if (j >= src.length)
2175
- throw new ExpressionError("unterminated string", i);
2176
- out.push({ t: "str", v, at: i });
2177
- i = j + 1;
2178
- continue;
2179
- }
2180
- if (/[A-Za-z_$]/.test(c)) {
2181
- const m = /^[A-Za-z_$][\w$]*/.exec(src.slice(i));
2182
- const v = m?.[0] ?? c;
2183
- out.push({ t: "id", v, at: i });
2184
- i += v.length;
2185
- continue;
2186
- }
2187
- const op = OPS.find((o) => src.startsWith(o, i));
2188
- if (!op)
2189
- throw new ExpressionError(`unexpected "${c}"`, i);
2190
- out.push({ t: "op", v: op.length === 3 ? op.slice(0, 2) : op, at: i });
2191
- i += op.length;
2192
- }
2193
- out.push({ t: "end", at: src.length });
2194
- return out;
2195
- }
2196
- var BINARY = [
2197
- ["??"],
2198
- ["||"],
2199
- ["&&"],
2200
- ["==", "!="],
2201
- ["<", "<=", ">", ">="],
2202
- ["+", "-"],
2203
- ["*", "/", "%"]
2204
- ];
2205
- var KEYWORDS = {
2206
- true: true,
2207
- false: false,
2208
- null: null,
2209
- undefined: undefined
2210
- };
2211
-
2212
- class Parser {
2213
- #i = 0;
2214
- #tokens;
2215
- constructor(tokens) {
2216
- this.#tokens = tokens;
2217
- }
2218
- get #peek() {
2219
- return this.#tokens[this.#i];
2220
- }
2221
- #isOp(v) {
2222
- const t = this.#peek;
2223
- return t.t === "op" && t.v === v;
2224
- }
2225
- #expect(v) {
2226
- if (!this.#isOp(v))
2227
- throw new ExpressionError(`expected "${v}"`, this.#peek.at);
2228
- this.#i++;
2229
- }
2230
- parse() {
2231
- const node = this.#ternary();
2232
- if (this.#peek.t !== "end")
2233
- throw new ExpressionError("unexpected input", this.#peek.at);
2234
- return node;
2235
- }
2236
- #ternary() {
2237
- const test = this.#binary(0);
2238
- if (!this.#isOp("?"))
2239
- return test;
2240
- this.#i++;
2241
- const then = this.#ternary();
2242
- this.#expect(":");
2243
- return { kind: "ternary", test, then, else: this.#ternary() };
2244
- }
2245
- #binary(level) {
2246
- if (level >= BINARY.length)
2247
- return this.#unary();
2248
- let left = this.#binary(level + 1);
2249
- const ops = BINARY[level];
2250
- for (;; ) {
2251
- const t = this.#peek;
2252
- if (t.t !== "op" || !ops.includes(t.v))
2253
- return left;
2254
- this.#i++;
2255
- left = { kind: "binary", op: t.v, left, right: this.#binary(level + 1) };
2256
- }
2257
- }
2258
- #unary() {
2259
- const t = this.#peek;
2260
- if (t.t === "op" && (t.v === "!" || t.v === "-" || t.v === "+")) {
2261
- this.#i++;
2262
- return { kind: "unary", op: t.v, arg: this.#unary() };
2263
- }
2264
- return this.#postfix();
2265
- }
2266
- #postfix() {
2267
- let node = this.#primary();
2268
- for (;; ) {
2269
- if (this.#isOp(".")) {
2270
- this.#i++;
2271
- const t = this.#peek;
2272
- if (t.t !== "id")
2273
- throw new ExpressionError("expected a property name", t.at);
2274
- this.#i++;
2275
- node = {
2276
- kind: "member",
2277
- object: node,
2278
- property: { kind: "literal", value: t.v },
2279
- computed: false
2280
- };
2281
- } else if (this.#isOp("[")) {
2282
- this.#i++;
2283
- const property = this.#ternary();
2284
- this.#expect("]");
2285
- node = { kind: "member", object: node, property, computed: true };
2286
- } else if (this.#isOp("(")) {
2287
- if (node.kind !== "ident")
2288
- throw new ExpressionError("only functions can be called", this.#peek.at);
2289
- const at = this.#peek.at;
2290
- this.#i++;
2291
- if (!Object.hasOwn(FUNCTIONS, node.name)) {
2292
- throw new ExpressionError(`unknown function "${node.name}"`, at);
2293
- }
2294
- node = { kind: "call", name: node.name, args: this.#list(")") };
2295
- } else
2296
- return node;
2297
- }
2298
- }
2299
- #list(close) {
2300
- const items = [];
2301
- if (this.#isOp(close)) {
2302
- this.#i++;
2303
- return items;
2304
- }
2305
- for (;; ) {
2306
- items.push(this.#ternary());
2307
- if (this.#isOp(",")) {
2308
- this.#i++;
2309
- continue;
2310
- }
2311
- this.#expect(close);
2312
- return items;
2313
- }
2314
- }
2315
- #primary() {
2316
- const t = this.#peek;
2317
- this.#i++;
2318
- switch (t.t) {
2319
- case "num":
2320
- case "str":
2321
- return { kind: "literal", value: t.v };
2322
- case "id":
2323
- return Object.hasOwn(KEYWORDS, t.v) ? { kind: "literal", value: KEYWORDS[t.v] } : { kind: "ident", name: t.v };
2324
- case "op":
2325
- if (t.v === "(") {
2326
- const inner = this.#ternary();
2327
- this.#expect(")");
2328
- return inner;
2329
- }
2330
- if (t.v === "[")
2331
- return { kind: "array", items: this.#list("]") };
2332
- throw new ExpressionError(`unexpected "${t.v}"`, t.at);
2333
- case "end":
2334
- throw new ExpressionError("unexpected end", t.at);
2335
- }
2336
- }
2337
- }
2338
- var BLOCKED = new Set(["__proto__", "prototype", "constructor"]);
2339
- function member(object, key) {
2340
- if (object === null || object === undefined)
2341
- return;
2342
- if (typeof object === "string") {
2343
- if (key === "length")
2344
- return object.length;
2345
- return typeof key === "number" ? object[key] : undefined;
2346
- }
2347
- if (Array.isArray(object)) {
2348
- if (key === "length")
2349
- return object.length;
2350
- return typeof key === "number" ? object[key] : undefined;
2351
- }
2352
- if (typeof object !== "object")
2353
- return;
2354
- const k = String(key);
2355
- if (BLOCKED.has(k) || !Object.hasOwn(object, k))
2356
- return;
2357
- return object[k];
2358
- }
2359
- function looseEqual(a, b) {
2360
- if (typeof a === "number" && typeof b === "string" && b.trim() !== "")
2361
- return a === Number(b);
2362
- if (typeof b === "number" && typeof a === "string" && a.trim() !== "")
2363
- return b === Number(a);
2364
- if (a === undefined)
2365
- return b === undefined || b === null;
2366
- if (a === null)
2367
- return b === undefined || b === null;
2368
- return Object.is(a, b) || a === b;
2369
- }
2370
- var toNum = (v) => typeof v === "number" ? v : Number(v ?? Number.NaN);
2371
- function compare(op, a, b) {
2372
- const both = typeof a === "string" && typeof b === "string";
2373
- const x = both ? a : toNum(a);
2374
- const y = both ? b : toNum(b);
2375
- switch (op) {
2376
- case "<":
2377
- return x < y;
2378
- case "<=":
2379
- return x <= y;
2380
- case ">":
2381
- return x > y;
2382
- case ">=":
2383
- return x >= y;
2384
- }
2385
- }
2386
- function evaluate(node, scope) {
2387
- switch (node.kind) {
2388
- case "literal":
2389
- return node.value;
2390
- case "ident":
2391
- return Object.hasOwn(scope, node.name) ? scope[node.name] : undefined;
2392
- case "member":
2393
- return member(evaluate(node.object, scope), evaluate(node.property, scope));
2394
- case "array":
2395
- return node.items.map((n) => evaluate(n, scope));
2396
- case "call": {
2397
- const fn = FUNCTIONS[node.name];
2398
- return fn(...node.args.map((n) => evaluate(n, scope)));
2399
- }
2400
- case "unary": {
2401
- const v = evaluate(node.arg, scope);
2402
- return node.op === "!" ? !v : node.op === "-" ? -toNum(v) : toNum(v);
2403
- }
2404
- case "ternary":
2405
- return evaluate(node.test, scope) ? evaluate(node.then, scope) : evaluate(node.else, scope);
2406
- case "binary": {
2407
- const { op } = node;
2408
- if (op === "&&")
2409
- return evaluate(node.left, scope) && evaluate(node.right, scope);
2410
- if (op === "||")
2411
- return evaluate(node.left, scope) || evaluate(node.right, scope);
2412
- if (op === "??")
2413
- return evaluate(node.left, scope) ?? evaluate(node.right, scope);
2414
- const a = evaluate(node.left, scope);
2415
- const b = evaluate(node.right, scope);
2416
- switch (op) {
2417
- case "+":
2418
- return typeof a === "string" || typeof b === "string" ? display(a) + display(b) : toNum(a) + toNum(b);
2419
- case "-":
2420
- return toNum(a) - toNum(b);
2421
- case "*":
2422
- return toNum(a) * toNum(b);
2423
- case "/":
2424
- return toNum(a) / toNum(b);
2425
- case "%":
2426
- return toNum(a) % toNum(b);
2427
- case "==":
2428
- return looseEqual(a, b);
2429
- case "!=":
2430
- return !looseEqual(a, b);
2431
- default:
2432
- return compare(op, a, b);
2433
- }
2434
- }
2435
- }
2436
- }
2437
- var pad2 = (n) => String(n).padStart(2, "0");
2438
- function display(value) {
2439
- if (value === undefined || value === null)
2440
- return "";
2441
- if (typeof value === "number") {
2442
- if (!Number.isFinite(value))
2443
- return Number.isNaN(value) ? "" : value > 0 ? "∞" : "-∞";
2444
- return String(Math.round(value * 100) / 100);
2445
- }
2446
- if (typeof value === "string")
2447
- return value;
2448
- if (typeof value === "boolean")
2449
- return value ? "true" : "false";
2450
- try {
2451
- return JSON.stringify(value) ?? "";
2452
- } catch {
2453
- return "";
2454
- }
2455
- }
2456
- var UNITS = ["B", "KB", "MB", "GB", "TB", "PB"];
2457
- function currentTurn(first, second, at) {
2458
- const lengths = (Array.isArray(first) ? first.map(toNum) : Array.from({ length: Math.min(100, Math.max(0, Math.trunc(toNum(first)))) }, () => toNum(second ?? 5))).map((s) => Number.isFinite(s) && s > 0 ? s : 0);
2459
- const total = lengths.reduce((a, b) => a + b, 0);
2460
- if (total <= 0)
2461
- return 0;
2462
- let into = at / 1000 % total;
2463
- for (const [i, length] of lengths.entries()) {
2464
- if (into < length)
2465
- return i;
2466
- into -= length;
2467
- }
2468
- return lengths.length - 1;
2469
- }
2470
- var FUNCTIONS = {
2471
- round: (x, digits) => {
2472
- const d = Math.max(0, Math.min(10, Math.trunc(toNum(digits ?? 0)) || 0));
2473
- const f = 10 ** d;
2474
- return Math.round(toNum(x) * f) / f;
2475
- },
2476
- floor: (x) => Math.floor(toNum(x)),
2477
- ceil: (x) => Math.ceil(toNum(x)),
2478
- abs: (x) => Math.abs(toNum(x)),
2479
- min: (...xs) => Math.min(...xs.flat().map(toNum)),
2480
- max: (...xs) => Math.max(...xs.flat().map(toNum)),
2481
- clamp: (x, lo, hi) => Math.min(toNum(hi), Math.max(toNum(lo), toNum(x))),
2482
- fmt: (x, digits) => {
2483
- const n = toNum(x);
2484
- if (!Number.isFinite(n))
2485
- return "";
2486
- return n.toFixed(Math.max(0, Math.min(10, Math.trunc(toNum(digits ?? 0)) || 0)));
2487
- },
2488
- bytes: (x) => {
2489
- let n = toNum(x);
2490
- if (!Number.isFinite(n))
2491
- return "";
2492
- let u = 0;
2493
- while (Math.abs(n) >= 1024 && u < UNITS.length - 1) {
2494
- n /= 1024;
2495
- u++;
2496
- }
2497
- return `${u === 0 ? n : n.toFixed(n < 10 ? 1 : 0)} ${UNITS[u]}`;
2498
- },
2499
- pad: (x, width, fill) => display(x).padStart(Math.min(64, toNum(width) || 0), display(fill ?? "0") || "0"),
2500
- str: (x) => display(x),
2501
- num: (x) => {
2502
- const n = toNum(x);
2503
- return Number.isFinite(n) ? n : 0;
2504
- },
2505
- upper: (s) => display(s).toUpperCase(),
2506
- lower: (s) => display(s).toLowerCase(),
2507
- trim: (s) => display(s).trim(),
2508
- len: (x) => typeof x === "string" || Array.isArray(x) ? x.length : 0,
2509
- contains: (haystack, needle) => Array.isArray(haystack) ? haystack.some((v) => looseEqual(v, needle)) : display(haystack).includes(display(needle)),
2510
- startsWith: (s, p) => display(s).startsWith(display(p)),
2511
- endsWith: (s, p) => display(s).endsWith(display(p)),
2512
- replace: (s, a, b) => display(s).split(display(a)).join(display(b)),
2513
- join: (xs, sep) => Array.isArray(xs) ? xs.map(display).join(sep === undefined ? ", " : display(sep)) : "",
2514
- if: (c, a, b) => c ? a : b,
2515
- now: () => Date.now(),
2516
- time: (seconds) => {
2517
- const d = new Date;
2518
- const hm = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
2519
- return seconds ? `${hm}:${pad2(d.getSeconds())}` : hm;
2520
- },
2521
- turn: (first, second) => currentTurn(first, second, Date.now()),
2522
- date: () => {
2523
- const d = new Date;
2524
- return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
2525
- }
2526
- };
2527
- function pathOf(node) {
2528
- if (node.kind === "ident")
2529
- return node.name;
2530
- if (node.kind === "member") {
2531
- const base = pathOf(node.object);
2532
- if (base === undefined)
2533
- return;
2534
- if (!node.computed && node.property.kind === "literal")
2535
- return `${base}.${String(node.property.value)}`;
2536
- return base;
2537
- }
2538
- return;
2539
- }
2540
- var TIME_FUNCTIONS = new Set(["now", "time", "date", "turn"]);
2541
- function collect(node, paths, flags) {
2542
- switch (node.kind) {
2543
- case "ident":
2544
- paths.add(node.name);
2545
- return;
2546
- case "member": {
2547
- const path = pathOf(node);
2548
- if (path !== undefined)
2549
- paths.add(path);
2550
- else
2551
- collect(node.object, paths, flags);
2552
- if (node.computed)
2553
- collect(node.property, paths, flags);
2554
- return;
2555
- }
2556
- case "call":
2557
- if (TIME_FUNCTIONS.has(node.name))
2558
- flags.time = true;
2559
- for (const a of node.args)
2560
- collect(a, paths, flags);
2561
- return;
2562
- case "array":
2563
- for (const a of node.items)
2564
- collect(a, paths, flags);
2565
- return;
2566
- case "unary":
2567
- collect(node.arg, paths, flags);
2568
- return;
2569
- case "binary":
2570
- collect(node.left, paths, flags);
2571
- collect(node.right, paths, flags);
2572
- return;
2573
- case "ternary":
2574
- collect(node.test, paths, flags);
2575
- collect(node.then, paths, flags);
2576
- collect(node.else, paths, flags);
2577
- return;
2578
- case "literal":
2579
- return;
2580
- }
2581
- }
2582
- function minimal(paths) {
2583
- const sorted = [...paths].sort((a, b) => a.length - b.length);
2584
- const out = [];
2585
- for (const p of sorted)
2586
- if (!out.some((q) => p === q || p.startsWith(`${q}.`)))
2587
- out.push(p);
2588
- return out;
2589
- }
2590
- var cache = new Map;
2591
- function compile(source) {
2592
- const hit = cache.get(source);
2593
- if (hit)
2594
- return hit;
2595
- const trimmed = source.trim();
2596
- const ast = trimmed === "" ? { kind: "literal", value: undefined } : new Parser(tokenize(trimmed)).parse();
2597
- const paths = new Set;
2598
- const flags = { time: false };
2599
- collect(ast, paths, flags);
2600
- const expression = {
2601
- source,
2602
- paths: minimal(paths),
2603
- timeDependent: flags.time,
2604
- evaluate(scope) {
2605
- try {
2606
- return evaluate(ast, scope);
2607
- } catch {
2608
- return;
2609
- }
2610
- }
2611
- };
2612
- if (cache.size > 2000)
2613
- cache.clear();
2614
- cache.set(source, expression);
2615
- return expression;
2616
- }
2617
-
2618
- // ../engine/src/state.ts
2619
- function sameValue(a, b) {
2620
- if (Object.is(a, b))
2621
- return true;
2622
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
2623
- return false;
2624
- if (Array.isArray(a) !== Array.isArray(b))
2625
- return false;
2626
- const ka = Object.keys(a);
2627
- const kb = Object.keys(b);
2628
- if (ka.length !== kb.length)
2629
- return false;
2630
- return ka.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k]));
2631
- }
2632
-
2633
- // ../engine/src/template.ts
2634
- var HOLE = /\{\{([\s\S]*?)\}\}/g;
2635
- function parts(source) {
2636
- const out = [];
2637
- let last = 0;
2638
- for (const m of source.matchAll(HOLE)) {
2639
- if (m.index > last)
2640
- out.push(source.slice(last, m.index));
2641
- try {
2642
- out.push(compile(m[1] ?? ""));
2643
- } catch (error) {
2644
- out.push(error instanceof ExpressionError ? new ExpressionError(error.message, m.index + 2 + error.position) : new ExpressionError(String(error), m.index));
2645
- }
2646
- last = m.index + m[0].length;
2647
- }
2648
- if (last < source.length)
2649
- out.push(source.slice(last));
2650
- return out;
2651
- }
2652
- var cache2 = new Map;
2653
- function template(source) {
2654
- const hit = cache2.get(source);
2655
- if (hit)
2656
- return hit;
2657
- const list = parts(source);
2658
- const expressions = list.filter((p) => typeof p === "object" && !(p instanceof ExpressionError));
2659
- const errors = list.filter((p) => p instanceof ExpressionError);
2660
- const paths = [...new Set(expressions.flatMap((e) => e.paths))];
2661
- const render = (scope) => list.map((p) => typeof p === "string" ? p : p instanceof ExpressionError ? "⚠" : display(p.evaluate(scope))).join("");
2662
- const single = list.length === 1 && expressions.length === 1 ? expressions[0] : undefined;
2663
- const t = {
2664
- source,
2665
- render,
2666
- value: (scope) => single ? single.evaluate(scope) : render(scope),
2667
- paths,
2668
- timeDependent: expressions.some((e) => e.timeDependent),
2669
- errors,
2670
- dynamic: expressions.length + errors.length > 0
2671
- };
2672
- if (cache2.size > 2000)
2673
- cache2.clear();
2674
- cache2.set(source, t);
2675
- return t;
2676
- }
2677
4
  // src/bridge.ts
5
+ import { compile, sameValue, template } from "@sdeck/engine";
2678
6
  import {
2679
- createContext as createContext2,
7
+ createContext,
2680
8
  useCallback,
2681
- useContext as useContext3,
2682
- useEffect as useEffect2,
9
+ useContext,
10
+ useEffect,
2683
11
  useMemo,
2684
- useRef as useRef2,
2685
- useState as useState2,
2686
- useSyncExternalStore as useSyncExternalStore3
12
+ useRef,
13
+ useState,
14
+ useSyncExternalStore
2687
15
  } from "react";
2688
- var HostBridgeContext = createContext2(undefined);
16
+ var HostBridgeContext = createContext(undefined);
2689
17
  function useBridge() {
2690
- const bridge = useContext3(HostBridgeContext);
18
+ const bridge = useContext(HostBridgeContext);
2691
19
  if (!bridge)
2692
20
  throw new Error("sdeck live-state hooks must be used inside an action drawn by the host");
2693
21
  return bridge;
2694
22
  }
2695
23
  function useClock(on) {
2696
- const [tick, setTick] = useState2(0);
2697
- useEffect2(() => {
24
+ const [tick, setTick] = useState(0);
25
+ useEffect(() => {
2698
26
  if (!on)
2699
27
  return;
2700
28
  const timer = setInterval(() => setTick((t) => t + 1), 1000);
@@ -2707,7 +35,7 @@ function useWatched(paths, read) {
2707
35
  const key = paths.join(`
2708
36
  `);
2709
37
  const subscribe = useCallback((listener) => bridge.watch(paths, listener), [bridge, key]);
2710
- const last = useRef2(undefined);
38
+ const last = useRef(undefined);
2711
39
  const snapshot = () => {
2712
40
  const value = read();
2713
41
  if (last.current && sameValue(last.current.value, value))
@@ -2715,7 +43,7 @@ function useWatched(paths, read) {
2715
43
  last.current = { value };
2716
44
  return value;
2717
45
  };
2718
- return useSyncExternalStore3(subscribe, snapshot);
46
+ return useSyncExternalStore(subscribe, snapshot);
2719
47
  }
2720
48
  function useExpression(source) {
2721
49
  const bridge = useBridge();
@@ -2750,7 +78,7 @@ function useRunAction() {
2750
78
  }
2751
79
  function useImage(src, color) {
2752
80
  const bridge = useBridge();
2753
- return useSyncExternalStore3(bridge.watchImages, () => src ? bridge.image(src, color) : undefined);
81
+ return useSyncExternalStore(bridge.watchImages, () => src ? bridge.image(src, color) : undefined);
2754
82
  }
2755
83
  // src/connection.ts
2756
84
  class PermanentError extends Error {
@@ -2919,6 +247,86 @@ class ManagedConnection {
2919
247
  this.#options.onStatus?.("disconnected");
2920
248
  }
2921
249
  }
250
+ // src/permissions.ts
251
+ var PERMISSION_TEXTS = {
252
+ network: {
253
+ name: "Network",
254
+ description: "Connect to the internet and to devices on your network.",
255
+ action: "use the network"
256
+ },
257
+ filesystem: {
258
+ name: "Files",
259
+ description: "Read and change your files. Its own data folder is always allowed.",
260
+ action: "use files outside its own folder"
261
+ },
262
+ process: {
263
+ name: "Start programs",
264
+ description: "Open apps and run programs that are installed on this computer.",
265
+ action: "start programs",
266
+ powerful: true
267
+ },
268
+ shell: {
269
+ name: "Run commands",
270
+ description: "Run any command line. Commands can do everything you can.",
271
+ action: "run commands",
272
+ powerful: true
273
+ },
274
+ input: {
275
+ name: "Keyboard and mouse",
276
+ description: "Press keys, type text and control media playback.",
277
+ action: "press keys"
278
+ },
279
+ clipboard: {
280
+ name: "Clipboard",
281
+ description: "Read and change what you copied.",
282
+ action: "use the clipboard"
283
+ },
284
+ audio: {
285
+ name: "Sound",
286
+ description: "Change volumes, mute apps and switch audio devices.",
287
+ action: "control sound"
288
+ },
289
+ environment: {
290
+ name: "Environment variables",
291
+ description: "Read environment variables, which can contain keys and tokens.",
292
+ action: "read environment variables"
293
+ },
294
+ variables: {
295
+ name: "Your variables",
296
+ description: "Read and change the variables your workflows use.",
297
+ action: "use your variables"
298
+ },
299
+ state: {
300
+ name: "Other plugins' values",
301
+ description: "Read live values from other plugins, such as the app in front.",
302
+ action: "read other plugins' values"
303
+ },
304
+ actions: {
305
+ name: "Other plugins' actions",
306
+ description: "Run actions of other plugins, with the permissions those have.",
307
+ action: "run other plugins' actions",
308
+ powerful: true
309
+ },
310
+ native: {
311
+ name: "Native code",
312
+ description: "Load compiled code, which sdeck cannot limit in any way.",
313
+ action: "load native code",
314
+ powerful: true
315
+ }
316
+ };
317
+ var PERMISSIONS = Object.keys(PERMISSION_TEXTS);
318
+
319
+ class PermissionError extends Error {
320
+ permission;
321
+ name = "PermissionError";
322
+ code = "EACCES";
323
+ constructor(plugin, permission, detail) {
324
+ const { name, action } = PERMISSION_TEXTS[permission];
325
+ super(`${plugin} is not allowed to ${action}${detail ? ` (${detail})` : ""}. ` + `Allow "${name}" in the plugin's permissions.`);
326
+ this.permission = permission;
327
+ }
328
+ }
329
+
2922
330
  // src/settings.ts
2923
331
  var HEX = /^#[0-9a-f]{6}$/i;
2924
332
  function defaultValue(field) {
@@ -2929,12 +337,32 @@ function defaultValue(field) {
2929
337
  return field.default ?? false;
2930
338
  case "color":
2931
339
  return field.default ?? "#000000";
340
+ case "groups":
341
+ return field.default ?? [];
2932
342
  case "select":
2933
343
  return field.default ?? field.options[0]?.value ?? "";
2934
344
  default:
2935
345
  return field.default ?? "";
2936
346
  }
2937
347
  }
348
+ function optionGroups(value) {
349
+ if (!Array.isArray(value))
350
+ return;
351
+ const ids = new Set;
352
+ return value.flatMap((group) => {
353
+ if (typeof group?.id !== "string" || !group.id || ids.has(group.id))
354
+ return [];
355
+ ids.add(group.id);
356
+ const members = Array.isArray(group.members) ? group.members : [];
357
+ return [
358
+ {
359
+ id: group.id,
360
+ name: typeof group.name === "string" ? group.name : "",
361
+ members: [...new Set(members.filter((m) => typeof m === "string"))]
362
+ }
363
+ ];
364
+ });
365
+ }
2938
366
  function coerce(field, value) {
2939
367
  switch (field.type) {
2940
368
  case "number": {
@@ -2947,6 +375,8 @@ function coerce(field, value) {
2947
375
  return typeof value === "boolean" ? value : defaultValue(field);
2948
376
  case "color":
2949
377
  return typeof value === "string" && HEX.test(value) ? value.toLowerCase() : defaultValue(field);
378
+ case "groups":
379
+ return optionGroups(value) ?? defaultValue(field);
2950
380
  case "select":
2951
381
  if (typeof value !== "string")
2952
382
  return defaultValue(field);
@@ -2963,6 +393,9 @@ function resolveSettings(schema, stored) {
2963
393
  out[key] = coerce(field, stored?.[key]);
2964
394
  return out;
2965
395
  }
396
+ function behaviorFields(schema) {
397
+ return Object.fromEntries(Object.entries(schema).filter(([, field]) => !field.appearance));
398
+ }
2966
399
  function isFieldVisible(field, settings) {
2967
400
  if (!field.visibleIf)
2968
401
  return true;
@@ -2981,6 +414,7 @@ function checkSchema(schema, sources = {}) {
2981
414
  "select",
2982
415
  "page",
2983
416
  "image",
417
+ "groups",
2984
418
  "secret"
2985
419
  ]);
2986
420
  for (const [key, field] of Object.entries(schema)) {
@@ -2991,6 +425,9 @@ function checkSchema(schema, sources = {}) {
2991
425
  if (typeof field.label !== "string")
2992
426
  problems.push(`setting "${key}" needs a label`);
2993
427
  const source = "source" in field ? field.source : undefined;
428
+ if (field.type === "groups" && source === undefined) {
429
+ problems.push(`setting "${key}" needs a source`);
430
+ }
2994
431
  if (source !== undefined && !(source in sources)) {
2995
432
  problems.push(`setting "${key}" uses unknown option source "${source}"`);
2996
433
  }
@@ -3013,15 +450,6 @@ function checkSchema(schema, sources = {}) {
3013
450
 
3014
451
  // src/plugin.ts
3015
452
  var PLUGIN_API_VERSION = 2;
3016
- var PERMISSIONS = [
3017
- "shell",
3018
- "process",
3019
- "filesystem",
3020
- "network",
3021
- "input",
3022
- "audio",
3023
- "clipboard"
3024
- ];
3025
453
  var ID = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/;
3026
454
  var NAMESPACE = /^[a-z][\w-]{0,31}$/;
3027
455
  var LOCAL_ID = /^[\w.-]+$/;
@@ -3048,6 +476,14 @@ function definePlugin(def) {
3048
476
  }
3049
477
  return def;
3050
478
  }
479
+ function checkNeeds(part, needs, asked) {
480
+ if (needs === undefined)
481
+ return [];
482
+ if (!Array.isArray(needs))
483
+ return [`${part}: permissions must be an array`];
484
+ const missing = needs.filter((p) => !Array.isArray(asked) || !asked.includes(p));
485
+ return missing.map((p) => `${part}: permission "${String(p)}" is not in the plugin's permissions`);
486
+ }
3051
487
  function checkLocalIds(kind, items, problems) {
3052
488
  const seen = new Set;
3053
489
  for (const item of items) {
@@ -3103,6 +539,7 @@ function checkPlugin(value) {
3103
539
  problems.push(`command "${name}": name is required`);
3104
540
  if (typeof c?.run !== "function")
3105
541
  problems.push(`command "${name}": run is required`);
542
+ problems.push(...checkNeeds(`command "${name}"`, c?.permissions, def.permissions));
3106
543
  }
3107
544
  }
3108
545
  }
@@ -3124,8 +561,10 @@ function checkPlugin(value) {
3124
561
  problems.push(`action "${name}": name is required`);
3125
562
  const hasComponent = typeof action?.component === "function" || typeof action?.component === "object";
3126
563
  const hasRun = typeof action?.run === "function";
3127
- if (!hasComponent && !hasRun)
564
+ if (!hasComponent && !hasRun && !action?.display) {
3128
565
  problems.push(`action "${name}": needs run or component`);
566
+ }
567
+ problems.push(...checkNeeds(`action "${name}"`, action?.permissions, def.permissions));
3129
568
  if (action?.look !== undefined && typeof action.look !== "function") {
3130
569
  problems.push(`action "${name}": look must be a function`);
3131
570
  }
@@ -3140,6 +579,9 @@ function checkPlugin(value) {
3140
579
  if (field?.type === "secret") {
3141
580
  problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
3142
581
  }
582
+ if (field?.type === "groups") {
583
+ problems.push(`action "${name}": setting "${key}": groups belong in the plugin settings`);
584
+ }
3143
585
  }
3144
586
  }
3145
587
  if (def.state !== undefined) {
@@ -3154,6 +596,7 @@ function checkPlugin(value) {
3154
596
  if (!["number", "string", "boolean", "json"].includes(s?.type)) {
3155
597
  problems.push(`state "${name}": type must be number, string, boolean or json`);
3156
598
  }
599
+ problems.push(...checkNeeds(`state "${name}"`, s?.permissions, def.permissions));
3157
600
  if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
3158
601
  problems.push(`state "${name}": poll needs read() and everyMs > 0`);
3159
602
  }
@@ -3175,6 +618,7 @@ function checkPlugin(value) {
3175
618
  if (typeof t?.subscribe !== "function") {
3176
619
  problems.push(`trigger "${name}": subscribe is required`);
3177
620
  }
621
+ problems.push(...checkNeeds(`trigger "${name}"`, t?.permissions, def.permissions));
3178
622
  for (const p of checkSchema(t?.settings ?? {}, sources)) {
3179
623
  problems.push(`trigger "${name}": ${p}`);
3180
624
  }
@@ -3296,57 +740,35 @@ class Shared {
3296
740
  }
3297
741
  }
3298
742
  export {
3299
- BackButton,
3300
- Clock,
3301
743
  HOST_MODULES,
3302
744
  HostBridgeContext,
3303
- KeyButton,
3304
745
  ManagedConnection,
3305
- Navigator,
3306
746
  PERMISSIONS,
747
+ PERMISSION_TEXTS,
3307
748
  PLUGIN_API_VERSION,
3308
749
  PLUGIN_KEYWORD,
3309
750
  PermanentError,
751
+ PermissionError,
3310
752
  SUPPORTED_API_VERSIONS,
3311
- SWIPE_WINDOW_MS,
3312
- SensorButton,
3313
753
  Shared,
754
+ behaviorFields,
3314
755
  checkPlugin,
3315
756
  checkSchema,
3316
757
  defaultValue,
3317
758
  defineAction,
3318
- defineApp,
3319
759
  definePlugin,
3320
760
  defineTrigger,
3321
761
  isFieldVisible,
3322
- mountApp,
762
+ optionGroups,
3323
763
  parseManifest,
3324
764
  pluginNamespace,
3325
765
  resolveSettings,
3326
- runApp,
3327
- useDeck,
3328
766
  useExpression,
3329
767
  useHostState,
3330
768
  useImage,
3331
- useInterval,
3332
- useKeyDown,
3333
- useKeyPress,
3334
- useKeyPressed,
3335
- useKeyRepeat,
3336
- useKeyUp,
3337
- useNavigation,
3338
- useNow,
3339
- usePage,
3340
769
  useRunAction,
3341
- useSensorDown,
3342
- useSensorPress,
3343
- useSensorPressed,
3344
- useSensorRepeat,
3345
- useSensorUp,
3346
- useSlot,
3347
- useSwipe,
3348
770
  useTemplate,
3349
771
  useVariable
3350
772
  };
3351
773
 
3352
- //# debugId=317791B36DA824C564756E2164756E21
774
+ //# debugId=C5D6970438DF66E064756E2164756E21