@sdeck/plugin-system 0.2.0 → 0.4.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
@@ -3,776 +3,25 @@
3
3
  import { execFile as execFile3, spawn as spawn3 } from "child_process";
4
4
  import { cpus as cpus2, freemem, homedir as homedir3, totalmem } from "os";
5
5
  import { basename, join as join3 } from "path";
6
+ import {
7
+ defineAction,
8
+ definePlugin,
9
+ defineTrigger,
10
+ Shared as Shared2
11
+ } from "@sdeck/plugin";
12
+ import {
13
+ formatAccelerator,
14
+ iconLayer,
15
+ iconLook,
16
+ parseAccelerator as parseAccelerator2,
17
+ textLayer
18
+ } from "@sdeck/schema";
6
19
 
7
- // ../core/src/element.ts
8
- var runtime;
9
- function registerElementRuntime(next) {
10
- runtime = next;
11
- }
12
- // ../react/src/render.ts
13
- function isReactElement(value) {
14
- return typeof value === "object" && value !== null && "$$typeof" in value;
15
- }
16
- var defaultRenderer = {};
17
- var fontRenderers = new WeakMap;
18
- async function createRenderer(fonts) {
19
- const { Renderer } = await import("@takumi-rs/core");
20
- const renderer = new Renderer;
21
- for (const font of fonts) {
22
- await renderer.registerFont({
23
- name: font.name,
24
- data: font.data,
25
- ...font.weight !== undefined && { weight: font.weight },
26
- ...font.style !== undefined && { style: font.style }
27
- });
28
- }
29
- return renderer;
30
- }
31
- function getRenderer(fonts) {
32
- if (!fonts?.length) {
33
- defaultRenderer.current ??= createRenderer([]);
34
- defaultRenderer.current.catch(() => {
35
- defaultRenderer.current = undefined;
36
- });
37
- return defaultRenderer.current;
38
- }
39
- let renderer = fontRenderers.get(fonts);
40
- if (!renderer) {
41
- renderer = createRenderer(fonts);
42
- renderer.catch(() => fontRenderers.delete(fonts));
43
- fontRenderers.set(fonts, renderer);
44
- }
45
- return renderer;
46
- }
47
- var number = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
48
- function toNode(node, text = true) {
49
- if ("text" in node) {
50
- return text ? { type: "text", text: node.text } : { type: "container", children: [] };
51
- }
52
- const { style, tw, src, width, height } = node.props;
53
- const common = {
54
- ...typeof tw === "string" && { tw }
55
- };
56
- if (node.type === "img") {
57
- if (typeof src !== "string")
58
- throw new Error("<img> needs a string `src` (URL or data: URI)");
59
- return {
60
- type: "image",
61
- src,
62
- ...number(width) !== undefined && { width: number(width) },
63
- ...number(height) !== undefined && { height: number(height) },
64
- ...typeof style === "object" && style !== null && { style },
65
- ...common
66
- };
67
- }
68
- return {
69
- type: "container",
70
- style: { display: "flex", ...typeof style === "object" ? style : {} },
71
- children: node.children.filter((child) => text || !("text" in child)).map((child) => toNode(child, text)),
72
- ...common
73
- };
74
- }
75
- var reconciler;
76
- var flushing = 0;
77
- function flushAll(renderer) {
78
- flushing++;
79
- try {
80
- renderer.flushSyncWork();
81
- for (let i = 0;i < 20 && renderer.flushPassiveEffects(); i++)
82
- renderer.flushSyncWork();
83
- } finally {
84
- flushing--;
85
- }
86
- }
87
- function loadReconciler() {
88
- reconciler ??= (async () => {
89
- let factoryModule;
90
- let constants;
91
- let React;
92
- try {
93
- [factoryModule, constants, React] = await Promise.all([
94
- import("react-reconciler"),
95
- import("react-reconciler/constants.js"),
96
- import("react")
97
- ]);
98
- } catch (cause) {
99
- throw new Error("Rendering React elements requires `react` (>=19.3) to be installed", {
100
- cause
101
- });
102
- }
103
- let priority = constants.NoEventPriority;
104
- const noop = () => {};
105
- const hostConfig = {
106
- supportsMutation: true,
107
- supportsPersistence: false,
108
- supportsHydration: false,
109
- isPrimaryRenderer: true,
110
- warnsIfNotActing: false,
111
- noTimeout: -1,
112
- scheduleTimeout: setTimeout,
113
- cancelTimeout: clearTimeout,
114
- supportsMicrotasks: true,
115
- scheduleMicrotask: queueMicrotask,
116
- createInstance: (type, props) => {
117
- const { children: _children, ...rest } = props;
118
- return { type, props: rest, children: [] };
119
- },
120
- createTextInstance: (text) => ({ text }),
121
- shouldSetTextContent: () => false,
122
- appendInitialChild: (parent, child) => parent.children.push(child),
123
- appendChild: (parent, child) => parent.children.push(child),
124
- appendChildToContainer: (container, child) => container.children.push(child),
125
- insertBefore: (parent, child, before) => {
126
- const children = parent.children;
127
- const existing = children.indexOf(child);
128
- if (existing !== -1)
129
- children.splice(existing, 1);
130
- children.splice(children.indexOf(before), 0, child);
131
- },
132
- insertInContainerBefore: (container, child, before) => {
133
- const children = container.children;
134
- const existing = children.indexOf(child);
135
- if (existing !== -1)
136
- children.splice(existing, 1);
137
- children.splice(children.indexOf(before), 0, child);
138
- },
139
- removeChild: (parent, child) => {
140
- parent.children.splice(parent.children.indexOf(child), 1);
141
- },
142
- removeChildFromContainer: (container, child) => {
143
- container.children.splice(container.children.indexOf(child), 1);
144
- },
145
- clearContainer: (container) => {
146
- container.children = [];
147
- },
148
- commitUpdate: (instance, _type, _prev, next) => {
149
- const { children: _children, ...rest } = next;
150
- instance.props = rest;
151
- },
152
- commitTextUpdate: (text, _old, next) => {
153
- text.text = next;
154
- },
155
- finalizeInitialChildren: () => false,
156
- getPublicInstance: (instance) => instance,
157
- getRootHostContext: () => ({}),
158
- getChildHostContext: (parent) => parent,
159
- prepareForCommit: () => null,
160
- resetAfterCommit: (container) => container.onCommit(),
161
- preparePortalMount: noop,
162
- detachDeletedInstance: noop,
163
- hideInstance: noop,
164
- unhideInstance: noop,
165
- hideTextInstance: noop,
166
- unhideTextInstance: noop,
167
- getInstanceFromNode: () => null,
168
- beforeActiveInstanceBlur: noop,
169
- afterActiveInstanceBlur: noop,
170
- prepareScopeUpdate: noop,
171
- getInstanceFromScope: () => null,
172
- bindToConsole: (method, args) => console[method]?.bind(console, ...args) ?? noop,
173
- extraDevToolsConfig: null,
174
- rendererVersion: "0.0.0",
175
- rendererPackageName: "sdeck",
176
- getCurrentUpdatePriority: () => priority,
177
- setCurrentUpdatePriority: (next) => {
178
- priority = next;
179
- },
180
- resolveUpdatePriority: () => priority !== constants.NoEventPriority ? priority : flushing > 0 ? constants.DiscreteEventPriority : constants.DefaultEventPriority,
181
- resolveEventType: () => null,
182
- resolveEventTimeStamp: () => -1.1,
183
- shouldAttemptEagerTransition: () => false,
184
- trackSchedulerEvent: noop,
185
- requestPostPaintCallback: noop,
186
- maySuspendCommit: () => false,
187
- preloadInstance: () => true,
188
- startSuspendingCommit: noop,
189
- suspendInstance: noop,
190
- waitForCommitToBeReady: () => null,
191
- getSuspendedCommitReason: () => null,
192
- NotPendingTransition: null,
193
- HostTransitionContext: React.createContext(null),
194
- resetFormInstance: noop
195
- };
196
- const factory = factoryModule.default ?? factoryModule;
197
- return factory(hostConfig);
198
- })();
199
- reconciler.catch(() => {
200
- reconciler = undefined;
201
- });
202
- return reconciler;
203
- }
204
- function noopIndicator() {}
205
- async function createReactRoot(size, onFrame, options = {}) {
206
- const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);
207
- let dirty = false;
208
- let drawing;
209
- let lastTree;
210
- let unmounted = false;
211
- let renderError;
212
- let initial = true;
213
- const fail = (error) => {
214
- if (initial)
215
- renderError ??= { error };
216
- else
217
- (options.onError ?? ((e) => console.error("sdeck: React render failed:", e)))(error);
218
- };
219
- async function draw() {
220
- await Promise.resolve();
221
- while (dirty && !unmounted) {
222
- dirty = false;
223
- try {
224
- const [root] = container.children;
225
- if (!root)
226
- continue;
227
- const tree = toNode(root, options.text !== false);
228
- const key = JSON.stringify(tree);
229
- if (key === lastTree)
230
- continue;
231
- lastTree = key;
232
- const pixels = await takumi.render(tree, {
233
- width: size.width,
234
- height: size.height,
235
- format: "raw",
236
- ...options.scale !== undefined && { devicePixelRatio: options.scale }
237
- });
238
- await onFrame({
239
- data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
240
- width: size.width,
241
- height: size.height,
242
- channels: 4
243
- });
244
- } catch (error) {
245
- lastTree = undefined;
246
- fail(error);
247
- }
248
- }
249
- drawing = undefined;
250
- }
251
- const container = {
252
- children: [],
253
- onCommit() {
254
- dirty = true;
255
- drawing ??= draw();
256
- }
257
- };
258
- const onError = (error) => fail(error);
259
- const onCaughtError = () => {};
260
- const root = renderer.createContainer(container, 1, null, false, null, "", onError, onCaughtError, onError, noopIndicator, null);
261
- const flush = () => flushAll(renderer);
262
- const handle = {
263
- render(element) {
264
- if (unmounted)
265
- throw new Error("This React root was unmounted");
266
- renderer.updateContainerSync(element, root, null, null);
267
- flush();
268
- },
269
- async idle() {
270
- while (drawing)
271
- await drawing;
272
- if (initial && renderError) {
273
- const { error } = renderError;
274
- renderError = undefined;
275
- throw error;
276
- }
277
- initial = false;
278
- },
279
- async unmount() {
280
- if (unmounted)
281
- return;
282
- renderer.updateContainerSync(null, root, null, null);
283
- flush();
284
- unmounted = true;
285
- await drawing;
286
- }
287
- };
288
- return handle;
289
- }
290
- async function renderReact(element, size, fonts, scale) {
291
- let frame;
292
- const root = await createReactRoot(size, (next) => {
293
- frame = next;
294
- }, { ...fonts && { fonts }, ...scale !== undefined && { scale } });
295
- try {
296
- root.render(element);
297
- await root.idle();
298
- } finally {
299
- await root.unmount();
300
- }
301
- if (!frame)
302
- throw new Error("React element rendered nothing");
303
- return frame;
304
- }
305
- registerElementRuntime({
306
- matches: isReactElement,
307
- render: (element, size, options) => renderReact(element, size, options?.fonts),
308
- createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options)
309
- });
310
- // ../app/src/app.tsx
311
- import { Fragment, useSyncExternalStore } from "react";
312
-
313
- // ../app/src/context.ts
314
- import { createContext, useContext } from "react";
315
- var DeckContext = createContext(undefined);
316
- var SlotContext = createContext(undefined);
317
- var NavigatorContext = createContext(undefined);
318
- // ../app/src/hooks.ts
319
- import { useContext as useContext2, useEffect, useRef, useState, useSyncExternalStore as useSyncExternalStore2 } from "react";
320
-
321
- // ../app/src/swipe.ts
322
- var trackers = new WeakMap;
323
- // ../schema/src/keys.ts
324
- var MODIFIER_NAMES = {
325
- ctrl: "ctrl",
326
- control: "ctrl",
327
- alt: "alt",
328
- option: "alt",
329
- shift: "shift",
330
- win: "win",
331
- meta: "win",
332
- super: "win",
333
- cmd: "win",
334
- command: "win"
335
- };
336
- var MODIFIER_ORDER = ["ctrl", "alt", "shift", "win"];
337
- var MODIFIER_CODES = {
338
- ctrl: 17,
339
- alt: 18,
340
- shift: 16,
341
- win: 91
342
- };
343
- function range(prefix, first, last, code) {
344
- const out = {};
345
- for (let n = first;n <= last; n++)
346
- out[`${prefix}${n}`] = code + n - first;
347
- return out;
348
- }
349
- var KEY_CODES = {
350
- ...Object.fromEntries(Array.from({ length: 26 }, (_, i) => [String.fromCharCode(97 + i), 65 + i])),
351
- ...range("", 0, 9, 48),
352
- ...range("f", 1, 24, 112),
353
- ...range("num", 0, 9, 96),
354
- backspace: 8,
355
- tab: 9,
356
- enter: 13,
357
- pause: 19,
358
- capslock: 20,
359
- escape: 27,
360
- space: 32,
361
- pageup: 33,
362
- pagedown: 34,
363
- end: 35,
364
- home: 36,
365
- left: 37,
366
- up: 38,
367
- right: 39,
368
- down: 40,
369
- printscreen: 44,
370
- insert: 45,
371
- delete: 46,
372
- menu: 93,
373
- multiply: 106,
374
- add: 107,
375
- subtract: 109,
376
- decimal: 110,
377
- divide: 111,
378
- numlock: 144,
379
- scrolllock: 145,
380
- volumemute: 173,
381
- volumedown: 174,
382
- volumeup: 175,
383
- medianext: 176,
384
- mediaprevious: 177,
385
- mediastop: 178,
386
- playpause: 179,
387
- ";": 186,
388
- "=": 187,
389
- ",": 188,
390
- "-": 189,
391
- ".": 190,
392
- "/": 191,
393
- "`": 192,
394
- "[": 219,
395
- "\\": 220,
396
- "]": 221,
397
- "'": 222
398
- };
399
- var ALIASES = {
400
- return: "enter",
401
- esc: "escape",
402
- del: "delete",
403
- ins: "insert",
404
- pgup: "pageup",
405
- pgdn: "pagedown",
406
- plus: "=",
407
- minus: "-",
408
- comma: ",",
409
- period: ".",
410
- prtsc: "printscreen",
411
- spacebar: "space",
412
- arrowleft: "left",
413
- arrowup: "up",
414
- arrowright: "right",
415
- arrowdown: "down"
416
- };
417
- function parseAccelerator(text) {
418
- const parts = text.split("+").map((p) => p.trim().toLowerCase()).filter(Boolean);
419
- if (parts.length === 0)
420
- throw new Error("no keys given");
421
- const modifiers = new Set;
422
- let key;
423
- for (const part of parts) {
424
- const modifier = MODIFIER_NAMES[part];
425
- if (modifier) {
426
- modifiers.add(modifier);
427
- continue;
428
- }
429
- const name = ALIASES[part] ?? part;
430
- if (!Object.hasOwn(KEY_CODES, name))
431
- throw new Error(`unknown key "${part}"`);
432
- if (key !== undefined)
433
- throw new Error(`"${text}" has more than one key besides modifiers`);
434
- key = name;
435
- }
436
- if (key === undefined) {
437
- const only = modifiers.size === 1 ? [...modifiers][0] : undefined;
438
- if (!only)
439
- throw new Error(`"${text}" needs a key besides the modifiers`);
440
- return { modifiers: [], key: only, code: MODIFIER_CODES[only] };
441
- }
442
- return {
443
- modifiers: MODIFIER_ORDER.filter((m) => modifiers.has(m)),
444
- key,
445
- code: KEY_CODES[key]
446
- };
447
- }
448
- function formatAccelerator(accelerator) {
449
- return [...accelerator.modifiers, accelerator.key].join("+");
450
- }
451
- // ../schema/src/layers.ts
452
- function iconLayer(id, icon, options = {}) {
453
- const { color, size = 52, position = "middle", visible, row, frame } = options;
454
- const src = /^[a-z0-9]+\/[A-Za-z0-9-]+$/.test(icon) ? `icon:${icon}` : icon;
455
- return {
456
- id,
457
- type: "image",
458
- src,
459
- size,
460
- position,
461
- ...color && { color },
462
- ...visible && { visible },
463
- ...row && { row },
464
- ...frame && { frame }
465
- };
466
- }
467
- function iconLook(options) {
468
- const { icon, background, caption = "", color = "#ffffff" } = options;
469
- return {
470
- background,
471
- layers: [
472
- iconLayer("icon", icon, {
473
- color,
474
- size: caption ? 46 : 58,
475
- position: caption ? "top" : "middle"
476
- }),
477
- ...caption ? [textLayer("label", caption, { color, size: 13, position: "bottom" })] : []
478
- ]
479
- };
480
- }
481
- function textLayer(id, text, options = {}) {
482
- const { color = "#ffffff", size = 14, weight = 700, position = "middle" } = options;
483
- const { visible, row, frame } = options;
484
- return {
485
- id,
486
- type: "text",
487
- text,
488
- color,
489
- size,
490
- weight,
491
- position,
492
- ...visible && { visible },
493
- ...row && { row },
494
- ...frame && { frame }
495
- };
496
- }
497
- // ../plugin/src/settings.ts
498
- function checkSchema(schema, sources = {}) {
499
- const problems = [];
500
- const types = new Set([
501
- "text",
502
- "number",
503
- "boolean",
504
- "color",
505
- "select",
506
- "page",
507
- "image",
508
- "secret"
509
- ]);
510
- for (const [key, field] of Object.entries(schema)) {
511
- if (!field || typeof field !== "object" || !types.has(field.type)) {
512
- problems.push(`setting "${key}" has an unknown type`);
513
- continue;
514
- }
515
- if (typeof field.label !== "string")
516
- problems.push(`setting "${key}" needs a label`);
517
- const source = "source" in field ? field.source : undefined;
518
- if (source !== undefined && !(source in sources)) {
519
- problems.push(`setting "${key}" uses unknown option source "${source}"`);
520
- }
521
- if (field.type === "select" && (!Array.isArray(field.options) || field.options.length === 0 && source === undefined)) {
522
- problems.push(`setting "${key}" needs at least one option or a source`);
523
- }
524
- for (const other of "dependsOn" in field && field.dependsOn || []) {
525
- if (!(other in schema))
526
- problems.push(`setting "${key}" depends on unknown "${other}"`);
527
- }
528
- if (field.visibleIf !== undefined) {
529
- for (const other of Object.keys(field.visibleIf)) {
530
- if (!(other in schema))
531
- problems.push(`setting "${key}" depends on unknown "${other}"`);
532
- }
533
- }
534
- }
535
- return problems;
536
- }
537
-
538
- // ../plugin/src/plugin.ts
539
- var PERMISSIONS = [
540
- "shell",
541
- "process",
542
- "filesystem",
543
- "network",
544
- "input",
545
- "audio",
546
- "clipboard"
547
- ];
548
- var ID = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/;
549
- var NAMESPACE = /^[a-z][\w-]{0,31}$/;
550
- var LOCAL_ID = /^[\w.-]+$/;
551
- function defineAction(def) {
552
- return {
553
- ...def,
554
- slots: def.slots ?? ["key"],
555
- settings: def.settings ?? {}
556
- };
557
- }
558
- function defineTrigger(def) {
559
- return { ...def, settings: def.settings ?? {} };
560
- }
561
- function definePlugin(def) {
562
- const problems = checkPlugin(def);
563
- if (problems.length > 0) {
564
- throw new TypeError(`invalid plugin "${def?.id}": ${problems.join("; ")}`);
565
- }
566
- return def;
567
- }
568
- function checkLocalIds(kind, items, problems) {
569
- const seen = new Set;
570
- for (const item of items) {
571
- const name = typeof item?.id === "string" ? item.id : "?";
572
- if (typeof item?.id !== "string" || !LOCAL_ID.test(item.id)) {
573
- problems.push(`${kind} "${name}": id must be letters, digits, ".", "-" or "_"`);
574
- } else if (seen.has(item.id)) {
575
- problems.push(`${kind} "${name}" is defined twice`);
576
- }
577
- seen.add(name);
578
- }
579
- return seen;
580
- }
581
- function checkPlugin(value) {
582
- if (!value || typeof value !== "object")
583
- return ["not an object"];
584
- const def = value;
585
- const problems = [];
586
- if (typeof def.id !== "string" || !ID.test(def.id)) {
587
- problems.push("id must be a package-style name (lowercase, e.g. `my-plugin` or `@me/plugin`)");
588
- }
589
- if (typeof def.name !== "string" || def.name === "")
590
- problems.push("name is required");
591
- if (typeof def.version !== "string" || def.version === "")
592
- problems.push("version is required");
593
- if (def.namespace !== undefined && !NAMESPACE.test(def.namespace)) {
594
- problems.push("namespace must be lowercase letters, digits, - or _ (starting with a letter)");
595
- }
596
- if (def.activate !== undefined && typeof def.activate !== "function") {
597
- problems.push("activate must be a function");
598
- }
599
- if (def.permissions !== undefined) {
600
- if (!Array.isArray(def.permissions))
601
- problems.push("permissions must be an array");
602
- else
603
- for (const p of def.permissions)
604
- if (!PERMISSIONS.includes(p))
605
- problems.push(`unknown permission "${String(p)}"`);
606
- }
607
- if (def.settings !== undefined) {
608
- for (const p of checkSchema(def.settings, def.optionSources ?? {})) {
609
- problems.push(`plugin ${p}`);
610
- }
611
- }
612
- if (def.commands !== undefined) {
613
- if (!Array.isArray(def.commands))
614
- problems.push("commands must be an array");
615
- else {
616
- checkLocalIds("command", def.commands, problems);
617
- for (const c of def.commands) {
618
- const name = typeof c?.id === "string" ? c.id : "?";
619
- if (typeof c?.name !== "string")
620
- problems.push(`command "${name}": name is required`);
621
- if (typeof c?.run !== "function")
622
- problems.push(`command "${name}": run is required`);
623
- }
624
- }
625
- }
626
- if (def.onboarding !== undefined)
627
- problems.push(...checkOnboarding(def));
628
- const sources = def.optionSources ?? {};
629
- if (typeof sources !== "object")
630
- problems.push("optionSources must be an object");
631
- else
632
- for (const [name, fn] of Object.entries(sources))
633
- if (typeof fn !== "function")
634
- problems.push(`option source "${name}" must be a function`);
635
- if (!Array.isArray(def.actions))
636
- return [...problems, "actions must be an array"];
637
- checkLocalIds("action", def.actions, problems);
638
- for (const action of def.actions) {
639
- const name = typeof action?.id === "string" ? action.id : "?";
640
- if (typeof action?.name !== "string")
641
- problems.push(`action "${name}": name is required`);
642
- const hasComponent = typeof action?.component === "function" || typeof action?.component === "object";
643
- const hasRun = typeof action?.run === "function";
644
- if (!hasComponent && !hasRun)
645
- problems.push(`action "${name}": needs run or component`);
646
- if (action?.look !== undefined && typeof action.look !== "function") {
647
- problems.push(`action "${name}": look must be a function`);
648
- }
649
- const slots = action?.slots ?? ["key"];
650
- if (!Array.isArray(slots) || slots.length === 0 || slots.some((s) => !["key", "sensor", "window"].includes(s))) {
651
- problems.push(`action "${name}": slots must list "key", "sensor" and/or "window"`);
652
- }
653
- for (const p of checkSchema(action?.settings ?? {}, sources)) {
654
- problems.push(`action "${name}": ${p}`);
655
- }
656
- for (const [key, field] of Object.entries(action?.settings ?? {})) {
657
- if (field?.type === "secret") {
658
- problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
659
- }
660
- }
661
- }
662
- if (def.state !== undefined) {
663
- if (!Array.isArray(def.state))
664
- problems.push("state must be an array");
665
- else {
666
- checkLocalIds("state", def.state, problems);
667
- for (const s of def.state) {
668
- const name = typeof s?.id === "string" ? s.id : "?";
669
- if (typeof s?.name !== "string")
670
- problems.push(`state "${name}": name is required`);
671
- if (!["number", "string", "boolean", "json"].includes(s?.type)) {
672
- problems.push(`state "${name}": type must be number, string, boolean or json`);
673
- }
674
- if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
675
- problems.push(`state "${name}": poll needs read() and everyMs > 0`);
676
- }
677
- if (s?.start !== undefined && typeof s.start !== "function") {
678
- problems.push(`state "${name}": start must be a function`);
679
- }
680
- }
681
- }
682
- }
683
- if (def.triggers !== undefined) {
684
- if (!Array.isArray(def.triggers))
685
- problems.push("triggers must be an array");
686
- else {
687
- checkLocalIds("trigger", def.triggers, problems);
688
- for (const t of def.triggers) {
689
- const name = typeof t?.id === "string" ? t.id : "?";
690
- if (typeof t?.name !== "string")
691
- problems.push(`trigger "${name}": name is required`);
692
- if (typeof t?.subscribe !== "function") {
693
- problems.push(`trigger "${name}": subscribe is required`);
694
- }
695
- for (const p of checkSchema(t?.settings ?? {}, sources)) {
696
- problems.push(`trigger "${name}": ${p}`);
697
- }
698
- }
699
- }
700
- }
701
- return problems;
702
- }
703
- function checkOnboarding(def) {
704
- const onboarding = def.onboarding;
705
- if (!Array.isArray(onboarding?.steps))
706
- return ["onboarding: steps must be an array"];
707
- const problems = [];
708
- checkLocalIds("onboarding step", onboarding.steps, problems);
709
- const settings = def.settings ?? {};
710
- const commands = new Set((def.commands ?? []).map((c) => c.id));
711
- for (const step of onboarding.steps) {
712
- const name = typeof step?.id === "string" ? step.id : "?";
713
- if (typeof step?.title !== "string")
714
- problems.push(`onboarding step "${name}": title is required`);
715
- for (const key of step?.settings ?? []) {
716
- if (!(key in settings))
717
- problems.push(`onboarding step "${name}": no setting "${key}"`);
718
- }
719
- if (step?.command !== undefined && !commands.has(step.command)) {
720
- problems.push(`onboarding step "${name}": no command "${step.command}"`);
721
- }
722
- if (step?.done !== undefined && typeof step.done !== "function") {
723
- problems.push(`onboarding step "${name}": done must be a function`);
724
- }
725
- }
726
- const page = onboarding.starterPage;
727
- if (page) {
728
- const actions = new Set((def.actions ?? []).map((a) => a.id));
729
- const used = [
730
- ...Object.values(page.keys ?? {}),
731
- ...Object.values(page.sensors ?? {}),
732
- ...page.window ? [page.window] : []
733
- ];
734
- for (const { action } of used) {
735
- if (!actions.has(action))
736
- problems.push(`onboarding starter page: no action "${action}"`);
737
- }
738
- }
739
- return problems;
740
- }
741
- // ../plugin/src/shared.ts
742
- class Shared {
743
- #listeners = new Set;
744
- #start;
745
- #stop;
746
- #last;
747
- constructor(start) {
748
- this.#start = start;
749
- }
750
- get last() {
751
- return this.#last?.value;
752
- }
753
- listen(listener) {
754
- this.#listeners.add(listener);
755
- if (!this.#stop) {
756
- this.#stop = this.#start((value) => {
757
- this.#last = { value };
758
- for (const l of [...this.#listeners])
759
- l(value);
760
- });
761
- }
762
- return () => {
763
- this.#listeners.delete(listener);
764
- if (this.#listeners.size === 0) {
765
- this.#stop?.();
766
- this.#stop = undefined;
767
- this.#last = undefined;
768
- }
769
- };
770
- }
771
- }
772
20
  // src/controls.ts
773
21
  import { execFile } from "child_process";
774
22
  import { mkdir } from "fs/promises";
775
23
  import { dirname } from "path";
24
+ import { MODIFIER_CODES, parseAccelerator } from "@sdeck/schema";
776
25
  var MEDIA_KEYS = {
777
26
  "play-pause": "playpause",
778
27
  next: "medianext",
@@ -1323,6 +572,7 @@ import { spawn as spawn2 } from "child_process";
1323
572
  import { existsSync, readdirSync, watch } from "fs";
1324
573
  import { homedir as homedir2, networkInterfaces } from "os";
1325
574
  import { join as join2 } from "path";
575
+ import { Shared } from "@sdeck/plugin";
1326
576
  function processChanges(before, after) {
1327
577
  return {
1328
578
  started: [...after].filter((p) => !before.has(p)),
@@ -1552,6 +802,7 @@ function runShell(command, cwd, signal) {
1552
802
  var buttonLook = (icon, caption, image, background) => iconLook({ icon: image || icon, caption, background });
1553
803
  var open = defineAction({
1554
804
  id: "open",
805
+ permissions: ["process"],
1555
806
  name: "Open",
1556
807
  description: "Opens a website, file, folder or app.",
1557
808
  category: "System",
@@ -1562,9 +813,14 @@ var open = defineAction({
1562
813
  label: "URL or path",
1563
814
  placeholder: "https://example.com or C:\\Tools\\app.exe"
1564
815
  },
1565
- text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1566
- image: { type: "image", label: "Image" },
1567
- background: { type: "color", label: "Background", default: "#0969da" }
816
+ text: {
817
+ type: "text",
818
+ label: "Text",
819
+ placeholder: "Optional, under the icon",
820
+ appearance: true
821
+ },
822
+ image: { type: "image", label: "Image", appearance: true },
823
+ background: { type: "color", label: "Background", default: "#0969da", appearance: true }
1568
824
  },
1569
825
  run: ({ settings, plugin }) => {
1570
826
  if (!settings.target)
@@ -1577,6 +833,7 @@ var open = defineAction({
1577
833
  });
1578
834
  var command = defineAction({
1579
835
  id: "command",
836
+ permissions: ["shell"],
1580
837
  name: "Run command",
1581
838
  description: "Runs a shell command. Fails when it exits with an error; its output is the result.",
1582
839
  category: "System",
@@ -1590,9 +847,14 @@ var command = defineAction({
1590
847
  description: "Run to revert it (from the history, or a toggle's second press).",
1591
848
  multiline: true
1592
849
  },
1593
- text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1594
- image: { type: "image", label: "Image" },
1595
- background: { type: "color", label: "Background", default: "#24292f" }
850
+ text: {
851
+ type: "text",
852
+ label: "Text",
853
+ placeholder: "Optional, under the icon",
854
+ appearance: true
855
+ },
856
+ image: { type: "image", label: "Image", appearance: true },
857
+ background: { type: "color", label: "Background", default: "#24292f", appearance: true }
1596
858
  },
1597
859
  run: async ({ settings, plugin, signal }) => {
1598
860
  if (!settings.command)
@@ -1667,6 +929,7 @@ var METRICS = {
1667
929
  };
1668
930
  var stats = defineAction({
1669
931
  id: "stats",
932
+ permissions: [],
1670
933
  name: "System stats",
1671
934
  description: "Live CPU, memory, disk, network, GPU, ping and FPS (also usable anywhere as {{system.cpu}}).",
1672
935
  category: "Monitoring",
@@ -1694,9 +957,7 @@ var stats = defineAction({
1694
957
  color: { type: "color", label: "Colour", default: "#58a6ff" },
1695
958
  background: { type: "color", label: "Background", default: "#0d1117" }
1696
959
  },
1697
- run: () => {
1698
- return;
1699
- },
960
+ display: true,
1700
961
  look: (s) => {
1701
962
  const bar = (id, value) => ({
1702
963
  id,
@@ -1752,6 +1013,7 @@ var MEDIA = {
1752
1013
  };
1753
1014
  var media = defineAction({
1754
1015
  id: "media",
1016
+ permissions: ["input"],
1755
1017
  name: "Media and volume",
1756
1018
  description: "Presses a media or volume key, as a keyboard would.",
1757
1019
  category: "Controls",
@@ -1773,7 +1035,7 @@ var media = defineAction({
1773
1035
  max: 50,
1774
1036
  visibleIf: { key: ["volume-up", "volume-down"] }
1775
1037
  },
1776
- background: { type: "color", label: "Background", default: "#1f2937" }
1038
+ background: { type: "color", label: "Background", default: "#1f2937", appearance: true }
1777
1039
  },
1778
1040
  run: async ({ settings }) => {
1779
1041
  const controls = await systemControls();
@@ -1800,6 +1062,7 @@ var media = defineAction({
1800
1062
  });
1801
1063
  var hotkey = defineAction({
1802
1064
  id: "hotkey",
1065
+ permissions: ["input"],
1803
1066
  name: "Press a shortcut",
1804
1067
  description: "Sends a keyboard shortcut to the focused app.",
1805
1068
  category: "Controls",
@@ -1807,11 +1070,16 @@ var hotkey = defineAction({
1807
1070
  slots: ["key", "sensor"],
1808
1071
  settings: {
1809
1072
  keys: { type: "text", label: "Shortcut", placeholder: "ctrl+shift+m" },
1810
- text: { type: "text", label: "Text", placeholder: "Defaults to the shortcut" },
1811
- background: { type: "color", label: "Background", default: "#374151" }
1073
+ text: {
1074
+ type: "text",
1075
+ label: "Text",
1076
+ placeholder: "Defaults to the shortcut",
1077
+ appearance: true
1078
+ },
1079
+ background: { type: "color", label: "Background", default: "#374151", appearance: true }
1812
1080
  },
1813
1081
  run: async ({ settings }) => {
1814
- const accelerator = parseAccelerator(settings.keys);
1082
+ const accelerator = parseAccelerator2(settings.keys);
1815
1083
  await (await systemControls()).hotkey(accelerator);
1816
1084
  return { label: `Press ${formatAccelerator(accelerator)}` };
1817
1085
  },
@@ -1819,6 +1087,7 @@ var hotkey = defineAction({
1819
1087
  });
1820
1088
  var type = defineAction({
1821
1089
  id: "type",
1090
+ permissions: ["input"],
1822
1091
  name: "Type text",
1823
1092
  description: "Types text into the focused app. The text can use {{templates}}.",
1824
1093
  category: "Controls",
@@ -1826,8 +1095,13 @@ var type = defineAction({
1826
1095
  slots: ["key", "sensor"],
1827
1096
  settings: {
1828
1097
  content: { type: "text", label: "Text to type", multiline: true },
1829
- text: { type: "text", label: "Key text", placeholder: "Optional, under the icon" },
1830
- background: { type: "color", label: "Background", default: "#374151" }
1098
+ text: {
1099
+ type: "text",
1100
+ label: "Key text",
1101
+ placeholder: "Optional, under the icon",
1102
+ appearance: true
1103
+ },
1104
+ background: { type: "color", label: "Background", default: "#374151", appearance: true }
1831
1105
  },
1832
1106
  run: async ({ settings }) => {
1833
1107
  if (!settings.content)
@@ -1839,13 +1113,19 @@ var type = defineAction({
1839
1113
  });
1840
1114
  var lock = defineAction({
1841
1115
  id: "lock",
1116
+ permissions: ["process"],
1842
1117
  name: "Lock the screen",
1843
1118
  category: "Controls",
1844
1119
  icon: "lock",
1845
1120
  slots: ["key", "sensor"],
1846
1121
  settings: {
1847
- text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1848
- background: { type: "color", label: "Background", default: "#7c2d12" }
1122
+ text: {
1123
+ type: "text",
1124
+ label: "Text",
1125
+ placeholder: "Optional, under the icon",
1126
+ appearance: true
1127
+ },
1128
+ background: { type: "color", label: "Background", default: "#7c2d12", appearance: true }
1849
1129
  },
1850
1130
  run: async () => {
1851
1131
  await (await systemControls()).lock();
@@ -1855,14 +1135,20 @@ var lock = defineAction({
1855
1135
  });
1856
1136
  var sleep = defineAction({
1857
1137
  id: "sleep",
1138
+ permissions: ["process"],
1858
1139
  name: "Sleep",
1859
1140
  description: "Puts the computer to sleep.",
1860
1141
  category: "Controls",
1861
1142
  icon: "moon",
1862
1143
  slots: ["key", "sensor"],
1863
1144
  settings: {
1864
- text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1865
- background: { type: "color", label: "Background", default: "#1e1b4b" }
1145
+ text: {
1146
+ type: "text",
1147
+ label: "Text",
1148
+ placeholder: "Optional, under the icon",
1149
+ appearance: true
1150
+ },
1151
+ background: { type: "color", label: "Background", default: "#1e1b4b", appearance: true }
1866
1152
  },
1867
1153
  run: async () => {
1868
1154
  await (await systemControls()).sleep();
@@ -1878,6 +1164,7 @@ function screenshotName(at) {
1878
1164
  }
1879
1165
  var screenshot = defineAction({
1880
1166
  id: "screenshot",
1167
+ permissions: ["process", "filesystem"],
1881
1168
  name: "Screenshot",
1882
1169
  description: "Saves the screen to a file (the result), or opens the region picker.",
1883
1170
  category: "Controls",
@@ -1899,8 +1186,13 @@ var screenshot = defineAction({
1899
1186
  placeholder: "Pictures/sdeck",
1900
1187
  visibleIf: { mode: "file" }
1901
1188
  },
1902
- text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1903
- background: { type: "color", label: "Background", default: "#065f46" }
1189
+ text: {
1190
+ type: "text",
1191
+ label: "Text",
1192
+ placeholder: "Optional, under the icon",
1193
+ appearance: true
1194
+ },
1195
+ background: { type: "color", label: "Background", default: "#065f46", appearance: true }
1904
1196
  },
1905
1197
  run: async ({ settings }) => {
1906
1198
  const controls = await systemControls();
@@ -1921,13 +1213,14 @@ var screenshot = defineAction({
1921
1213
  });
1922
1214
  var pingAction = defineAction({
1923
1215
  id: "ping",
1216
+ permissions: ["network"],
1924
1217
  name: "Ping",
1925
1218
  description: "Pings a host; the result is the round trip in ms. Fails when it does not answer.",
1926
1219
  category: "Monitoring",
1927
1220
  icon: "radio",
1928
1221
  settings: {
1929
1222
  host: { type: "text", label: "Host", default: "1.1.1.1" },
1930
- background: { type: "color", label: "Background", default: "#0d1117" }
1223
+ background: { type: "color", label: "Background", default: "#0d1117", appearance: true }
1931
1224
  },
1932
1225
  run: async ({ settings, signal }) => {
1933
1226
  const ms = await ping(settings.host, signal);
@@ -1935,7 +1228,7 @@ var pingAction = defineAction({
1935
1228
  },
1936
1229
  look: (s) => iconLook({ icon: "lucide/activity", caption: s.host, background: s.background })
1937
1230
  });
1938
- var processes = new Shared((emit) => {
1231
+ var processes = new Shared2((emit) => {
1939
1232
  let stopped = false;
1940
1233
  let timer;
1941
1234
  const tick = async () => {
@@ -1951,20 +1244,20 @@ var processes = new Shared((emit) => {
1951
1244
  clearTimeout(timer);
1952
1245
  };
1953
1246
  });
1954
- var network = new Shared((emit) => {
1247
+ var network = new Shared2((emit) => {
1955
1248
  emit(networkAddresses());
1956
1249
  const timer = setInterval(() => emit(networkAddresses()), 5000);
1957
1250
  return () => clearInterval(timer);
1958
1251
  });
1959
1252
  var idleError;
1960
- var idle = new Shared((emit) => {
1253
+ var idle = new Shared2((emit) => {
1961
1254
  idleError = undefined;
1962
1255
  return watchIdle(emit, (error) => {
1963
1256
  idleError = error;
1964
1257
  });
1965
1258
  });
1966
1259
  var foregroundError;
1967
- var foreground = new Shared((emit) => {
1260
+ var foreground = new Shared2((emit) => {
1968
1261
  foregroundError = undefined;
1969
1262
  return watchForeground(emit, (error) => {
1970
1263
  foregroundError = error;
@@ -2017,13 +1310,14 @@ async function disks(context) {
2017
1310
  }
2018
1311
  return out;
2019
1312
  }
2020
- var throughputSource = new Shared((emit) => watchNetwork(emit, (error) => networkError?.(error)));
1313
+ var throughputSource = new Shared2((emit) => watchNetwork(emit, (error) => networkError?.(error)));
2021
1314
  var networkError;
2022
1315
  var netState = (id, name, pick) => ({
2023
1316
  id,
2024
1317
  name,
2025
1318
  type: "number",
2026
1319
  unit: "B/s",
1320
+ permissions: ["process"],
2027
1321
  start: (set, context) => {
2028
1322
  networkError = (error) => markUnavailable(context, "network speed", error);
2029
1323
  return throughputSource.listen((rate) => set(pick(rate)));
@@ -2034,6 +1328,7 @@ var gpuState = (id, name, type, pick, unit) => ({
2034
1328
  name,
2035
1329
  type,
2036
1330
  ...unit && { unit },
1331
+ permissions: ["process"],
2037
1332
  poll: {
2038
1333
  everyMs: 2000,
2039
1334
  read: async (context) => {
@@ -2047,6 +1342,7 @@ var monitoring = [
2047
1342
  let sample;
2048
1343
  return {
2049
1344
  id: "cpuCores",
1345
+ permissions: [],
2050
1346
  name: "CPU use per core",
2051
1347
  type: "json",
2052
1348
  description: "system.cpuCores[0] is the first core.",
@@ -2061,6 +1357,7 @@ var monitoring = [
2061
1357
  })(),
2062
1358
  {
2063
1359
  id: "disks",
1360
+ permissions: ["filesystem"],
2064
1361
  name: "Disks",
2065
1362
  type: "json",
2066
1363
  description: "system.disks.c.percent, .free, .total (choose them in the plugin's settings).",
@@ -2068,6 +1365,7 @@ var monitoring = [
2068
1365
  },
2069
1366
  {
2070
1367
  id: "disk",
1368
+ permissions: ["filesystem"],
2071
1369
  name: "Disk space used",
2072
1370
  type: "number",
2073
1371
  unit: "%",
@@ -2081,6 +1379,7 @@ var monitoring = [
2081
1379
  netState("netUp", "Upload speed", (c) => c.sent),
2082
1380
  {
2083
1381
  id: "ping",
1382
+ permissions: ["network"],
2084
1383
  name: "Ping",
2085
1384
  type: "number",
2086
1385
  unit: "ms",
@@ -2096,6 +1395,7 @@ var monitoring = [
2096
1395
  gpuState("gpuName", "GPU name", "string", (g) => g.name),
2097
1396
  {
2098
1397
  id: "cpuTemp",
1398
+ permissions: ["process"],
2099
1399
  name: "CPU temperature",
2100
1400
  type: "number",
2101
1401
  unit: "\xB0C",
@@ -2106,6 +1406,7 @@ var monitoring = [
2106
1406
  },
2107
1407
  {
2108
1408
  id: "fps",
1409
+ permissions: ["process"],
2109
1410
  name: "Frame rate",
2110
1411
  type: "number",
2111
1412
  description: "Of the app in front, measured by PresentMon.",
@@ -2160,6 +1461,7 @@ function onProcess(name, want, fire) {
2160
1461
  }
2161
1462
  var appOpen = defineTrigger({
2162
1463
  id: "app-open",
1464
+ permissions: ["process"],
2163
1465
  name: "When an app opens",
2164
1466
  description: "Runs when a process starts (checked every 3 s).",
2165
1467
  settings: processSetting,
@@ -2167,6 +1469,7 @@ var appOpen = defineTrigger({
2167
1469
  });
2168
1470
  var appClose = defineTrigger({
2169
1471
  id: "app-close",
1472
+ permissions: ["process"],
2170
1473
  name: "When an app closes",
2171
1474
  description: "Runs when a process exits (checked every 3 s).",
2172
1475
  settings: processSetting,
@@ -2174,6 +1477,7 @@ var appClose = defineTrigger({
2174
1477
  });
2175
1478
  var fileCreated = defineTrigger({
2176
1479
  id: "file-created",
1480
+ permissions: ["filesystem"],
2177
1481
  name: "When a file appears",
2178
1482
  description: "Runs when a new file shows up in a folder (event.name, event.path).",
2179
1483
  settings: {
@@ -2197,6 +1501,7 @@ var fileCreated = defineTrigger({
2197
1501
  });
2198
1502
  var networkChange = defineTrigger({
2199
1503
  id: "network-change",
1504
+ permissions: [],
2200
1505
  name: "When the network changes",
2201
1506
  description: "Runs when network addresses change (event.online, event.addresses).",
2202
1507
  settings: {},
@@ -2214,6 +1519,7 @@ var networkChange = defineTrigger({
2214
1519
  });
2215
1520
  var idleTrigger = defineTrigger({
2216
1521
  id: "idle",
1522
+ permissions: ["process"],
2217
1523
  name: "When the computer is idle",
2218
1524
  description: "Runs after no keyboard or mouse input for a while, or when input comes back.",
2219
1525
  settings: {
@@ -2254,6 +1560,7 @@ var idleTrigger = defineTrigger({
2254
1560
  });
2255
1561
  var appFocus = defineTrigger({
2256
1562
  id: "app-focus",
1563
+ permissions: ["process"],
2257
1564
  name: "When an app comes to the front",
2258
1565
  description: "Runs when a window of this app gets focus (event.app), or of any app if empty.",
2259
1566
  settings: {
@@ -2283,7 +1590,7 @@ var appFocus = defineTrigger({
2283
1590
  var src_default = definePlugin({
2284
1591
  id: "@sdeck/plugin-system",
2285
1592
  name: "System",
2286
- version: "0.2.0",
1593
+ version: "0.4.0",
2287
1594
  description: "Open apps and run commands, press media keys and shortcuts, lock and sleep, take screenshots, and monitor the computer.",
2288
1595
  author: "sdeck",
2289
1596
  permissions: ["shell", "process", "input", "network", "filesystem"],
@@ -2310,6 +1617,7 @@ var src_default = definePlugin({
2310
1617
  let sample;
2311
1618
  return {
2312
1619
  id: "cpu",
1620
+ permissions: [],
2313
1621
  name: "CPU use",
2314
1622
  type: "number",
2315
1623
  unit: "%",
@@ -2324,6 +1632,7 @@ var src_default = definePlugin({
2324
1632
  })(),
2325
1633
  {
2326
1634
  id: "memory",
1635
+ permissions: [],
2327
1636
  name: "Memory use",
2328
1637
  type: "number",
2329
1638
  unit: "%",
@@ -2331,6 +1640,7 @@ var src_default = definePlugin({
2331
1640
  },
2332
1641
  {
2333
1642
  id: "memoryFree",
1643
+ permissions: [],
2334
1644
  name: "Free memory",
2335
1645
  type: "number",
2336
1646
  unit: "bytes",
@@ -2338,6 +1648,7 @@ var src_default = definePlugin({
2338
1648
  },
2339
1649
  {
2340
1650
  id: "processes",
1651
+ permissions: ["process"],
2341
1652
  name: "Running processes",
2342
1653
  type: "json",
2343
1654
  description: 'Lowercased names; e.g. contains(system.processes, "javaw.exe").',
@@ -2345,6 +1656,7 @@ var src_default = definePlugin({
2345
1656
  },
2346
1657
  {
2347
1658
  id: "idle",
1659
+ permissions: ["process"],
2348
1660
  name: "Idle time",
2349
1661
  type: "number",
2350
1662
  unit: "s",
@@ -2353,6 +1665,7 @@ var src_default = definePlugin({
2353
1665
  },
2354
1666
  {
2355
1667
  id: "foreground",
1668
+ permissions: ["process"],
2356
1669
  name: "App in front",
2357
1670
  type: "string",
2358
1671
  description: `The focused window's executable, lowercased ("javaw.exe"); empty when none. Profiles switch on it.`,
@@ -2360,6 +1673,7 @@ var src_default = definePlugin({
2360
1673
  },
2361
1674
  {
2362
1675
  id: "online",
1676
+ permissions: [],
2363
1677
  name: "Online",
2364
1678
  type: "boolean",
2365
1679
  description: "Whether any network interface has an address.",
@@ -2414,4 +1728,4 @@ export {
2414
1728
  xHotkey
2415
1729
  };
2416
1730
 
2417
- //# debugId=FB0D3C42A9AF9F4864756E2164756E21
1731
+ //# debugId=B4585026ACC8439264756E2164756E21