@sdeck/plugin-audio 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.tsx", "../../core/src/element.ts", "../../react/src/render.ts", "../../app/src/app.tsx", "../../app/src/context.ts", "../../app/src/hooks.ts", "../../app/src/swipe.ts", "../../engine/src/state.ts", "../../schema/src/layers.ts", "../../plugin/src/bridge.ts", "../../plugin/src/settings.ts", "../../plugin/src/plugin.ts", "../src/helper.ts"],
4
+ "sourcesContent": [
5
+ "import { existsSync } from \"node:fs\";\nimport {\n defineAction,\n definePlugin,\n type PluginContext,\n type StateDef,\n useHostState,\n useImage,\n useKeyRepeat,\n useSensorPressed,\n useSensorRepeat,\n} from \"@sdeck/plugin\";\nimport { iconLayer, type Look, textLayer } from \"@sdeck/schema\";\nimport {\n type AudioDevice,\n AudioHelper,\n AudioUnavailable,\n BUILD_HINT,\n type Change,\n findHelper,\n type Snapshot,\n type Target,\n} from \"./helper.ts\";\n\nexport * from \"./helper.ts\";\n\n/** `Spotify.exe` → `spotify`, the key of `audio.apps`. */\nexport function appKey(name: string): string {\n return name\n .trim()\n .toLowerCase()\n .replace(/\\.exe$/, \"\");\n}\n\n/** What the plugin publishes, from one snapshot of the devices. */\nexport function audioState(snapshot: Snapshot | undefined) {\n if (!snapshot) {\n return {\n master: undefined,\n mic: undefined,\n output: undefined,\n input: undefined,\n outputs: undefined,\n inputs: undefined,\n apps: undefined,\n };\n }\n const level = (d: AudioDevice | undefined) =>\n d && { volume: d.volume, muted: d.muted, name: d.name };\n const output = snapshot.outputs.find((d) => d.default);\n const input = snapshot.inputs.find((d) => d.default);\n return {\n master: level(output),\n mic: level(input),\n output: output?.name,\n input: input?.name,\n outputs: snapshot.outputs,\n inputs: snapshot.inputs,\n apps: Object.fromEntries(snapshot.apps.map((app) => [appKey(app.name), app])),\n };\n}\n\n// -- The helper ---------------------------------------------------------------------------------\n\nlet context: PluginContext | undefined;\n\nconst helper = new AudioHelper({\n command: () => {\n if (process.platform !== \"win32\") {\n throw new AudioUnavailable(\"Audio control is available on Windows only\");\n }\n const path = String(context?.settings().helper || \"\") || findHelper();\n if (!path) throw new AudioUnavailable(`${BUILD_HINT}.`);\n return [path];\n },\n onProblem: (problem) => context?.status(problem?.message, \"error\"),\n});\n\nconst stateOf = (\n id: keyof ReturnType<typeof audioState>,\n name: string,\n type: \"string\" | \"json\",\n description: string,\n): StateDef => ({\n id,\n name,\n type,\n description,\n start: (set) => helper.subscribe((snapshot) => set(audioState(snapshot)[id])),\n});\n\n/** An icon (`lucide/mic`) as an image, once loaded. */\nconst useIcon = (icon: string, color: string) => useImage(`icon:${icon}`, color);\n\n// -- Volume -------------------------------------------------------------------------------------\n\nconst TARGETS = [\n { value: \"output\", label: \"Speakers (default output)\" },\n { value: \"input\", label: \"Microphone (default input)\" },\n { value: \"app\", label: \"One app\" },\n] as const;\n\ninterface TargetSettings {\n target: \"output\" | \"input\" | \"app\";\n app: string;\n}\n\nfunction targetOf(s: TargetSettings): Target {\n if (s.target !== \"app\") return { kind: s.target };\n if (!s.app.trim()) throw new Error(\"choose an app\");\n return { kind: \"app\", app: s.app.trim() };\n}\n\n/** The state path of a target's level, for templates and expressions. */\nexport function targetPath(s: TargetSettings): string {\n if (s.target === \"output\") return \"audio.master\";\n if (s.target === \"input\") return \"audio.mic\";\n return `audio.apps[${JSON.stringify(appKey(s.app))}]`;\n}\n\nconst targetName = (s: TargetSettings) =>\n s.target === \"output\" ? \"Volume\" : s.target === \"input\" ? \"Mic\" : appKey(s.app) || \"App\";\n\n/** Brand icons of common apps, by executable name. */\nconst APP_ICONS: Record<string, string> = {\n spotify: \"si/SiSpotify\",\n discord: \"si/SiDiscord\",\n chrome: \"si/SiGooglechrome\",\n firefox: \"si/SiFirefoxbrowser\",\n msedge: \"fa6/FaEdge\",\n brave: \"si/SiBrave\",\n opera: \"si/SiOpera\",\n steam: \"si/SiSteam\",\n vlc: \"si/SiVlcmediaplayer\",\n obs64: \"si/SiObsstudio\",\n slack: \"fa6/FaSlack\",\n zoom: \"si/SiZoom\",\n system: \"lucide/bell\",\n};\n\n/** The icons of a target: sounding and muted. */\nexport function targetIcons(s: TargetSettings): { on: string; off: string } {\n if (s.target === \"output\") return { on: \"lucide/volume-2\", off: \"lucide/volume-x\" };\n if (s.target === \"input\") return { on: \"lucide/mic\", off: \"lucide/mic-off\" };\n const brand = APP_ICONS[appKey(s.app)];\n // A brand keeps its own mark when muted; it turns red.\n return brand ? { on: brand, off: brand } : { on: \"lucide/app-window\", off: \"lucide/volume-x\" };\n}\n\nconst targetFields = {\n target: { type: \"select\", label: \"Control\", default: \"output\", options: TARGETS },\n app: {\n type: \"text\",\n label: \"App\",\n source: \"apps\",\n placeholder: \"spotify.exe\",\n description: \"The executable name, as it appears while the app plays sound.\",\n visibleIf: { target: \"app\" },\n },\n} as const;\n\ntype Operation = \"up\" | \"down\" | \"set\" | \"mute\" | \"unmute\" | \"toggle\";\n\nasync function adjust(\n target: Target,\n operation: Operation,\n step: number,\n level: number,\n): Promise<Change> {\n switch (operation) {\n case \"up\":\n return helper.request(\"setVolume\", { target, delta: step });\n case \"down\":\n return helper.request(\"setVolume\", { target, delta: -step });\n case \"set\":\n return helper.request(\"setVolume\", { target, volume: level });\n case \"toggle\":\n return helper.request(\"setMute\", { target });\n default:\n return helper.request(\"setMute\", { target, muted: operation === \"mute\" });\n }\n}\n\nconst OPERATION_NAMES: Record<Operation, string> = {\n up: \"Volume up\",\n down: \"Volume down\",\n set: \"Set volume\",\n mute: \"Mute\",\n unmute: \"Unmute\",\n toggle: \"Toggle mute\",\n};\n\nconst volume = defineAction({\n id: \"volume\",\n name: \"Volume\",\n description: \"Changes or mutes the speakers, the microphone or one app, and shows its level.\",\n category: \"Audio\",\n icon: \"volume-2\",\n slots: [\"key\", \"sensor\"],\n settings: {\n ...targetFields,\n operation: {\n type: \"select\",\n label: \"When pressed\",\n default: \"toggle\",\n options: Object.entries(OPERATION_NAMES).map(([value, label]) => ({ value, label })) as {\n value: Operation;\n label: string;\n }[],\n },\n step: {\n type: \"number\",\n label: \"Step (%)\",\n default: 5,\n min: 1,\n max: 50,\n visibleIf: { operation: [\"up\", \"down\"] },\n },\n level: {\n type: \"number\",\n label: \"Level (%)\",\n default: 50,\n min: 0,\n max: 100,\n visibleIf: { operation: \"set\" },\n },\n background: { type: \"color\", label: \"Background\", default: \"#172554\" },\n },\n run: async ({ settings }) => {\n const target = targetOf(settings);\n const { before, after } = await adjust(\n target,\n settings.operation,\n settings.step,\n settings.level,\n );\n return {\n result: after,\n label: `${OPERATION_NAMES[settings.operation]} (${targetName(settings)})`,\n undo: async () => {\n await helper.request(\"setVolume\", { target, volume: before.volume });\n await helper.request(\"setMute\", { target, muted: before.muted });\n },\n };\n },\n look: (s): Look => {\n const path = targetPath(s);\n const muted = `${path}.muted`;\n const icons = targetIcons(s);\n const step = s.operation === \"up\" ? \"plus\" : s.operation === \"down\" ? \"minus\" : \"\";\n return {\n background: s.background,\n layers: [\n iconLayer(\"icon\", icons.on, {\n size: 42,\n position: \"top\",\n visible: `!${muted}`,\n row: \"icon\",\n }),\n iconLayer(\"muted\", icons.off, {\n color: \"#f87171\",\n size: 42,\n position: \"top\",\n visible: muted,\n row: \"icon\",\n }),\n ...(step\n ? [iconLayer(\"step\", `lucide/${step}`, { size: 22, position: \"top\", row: \"icon\" })]\n : []),\n textLayer(\"level\", `{{${path}.volume == null ? \"N/A\" : ${path}.volume + \"%\"}}`, {\n size: 18,\n position: \"bottom\",\n }),\n {\n id: \"bar\",\n type: \"bar\",\n value: `${path}.volume ?? 0`,\n color: \"#60a5fa\",\n track: \"#1e293b\",\n position: \"bottom\",\n thickness: 6,\n },\n ],\n };\n },\n});\n\n// -- Slider -------------------------------------------------------------------------------------\n\nconst slider = defineAction({\n id: \"slider\",\n name: \"Volume slider\",\n description:\n \"A level bar on a sensor strip: touch it to step the volume (the left one lowers, the right one raises), hold to keep going.\",\n category: \"Audio\",\n icon: \"sliders-horizontal\",\n slots: [\"sensor\", \"window\", \"key\"],\n settings: {\n ...targetFields,\n direction: {\n type: \"select\",\n label: \"Touching it\",\n default: \"auto\",\n options: [\n { value: \"auto\", label: \"Left lowers, right raises\" },\n { value: \"down\", label: \"Lowers\" },\n { value: \"up\", label: \"Raises\" },\n ],\n },\n step: { type: \"number\", label: \"Step (%)\", default: 4, min: 1, max: 50 },\n color: { type: \"color\", label: \"Bar colour\", default: \"#60a5fa\" },\n },\n run: async ({ settings }) => {\n const target = targetOf(settings);\n const delta = settings.direction === \"down\" ? -settings.step : settings.step;\n const { before, after } = await helper.request(\"setVolume\", { target, delta });\n return {\n result: after,\n label: `${targetName(settings)} ${after.volume}%`,\n undo: () => helper.request(\"setVolume\", { target, volume: before.volume }),\n };\n },\n component: ({ settings, slot, plugin }) => {\n const name = settings.target === \"output\" ? \"master\" : settings.target === \"input\" ? \"mic\" : \"\";\n const whole = useHostState(name ? `audio.${name}` : \"audio.apps\");\n const level = (\n name ? whole : (whole as Record<string, unknown> | undefined)?.[appKey(settings.app)]\n ) as { volume: number; muted: boolean } | undefined;\n const down =\n settings.direction === \"down\" ||\n (settings.direction === \"auto\" && slot.kind !== \"window\" && slot.index % 2 === 0);\n const step = () => {\n helper\n .request(\"setVolume\", {\n target: targetOf(settings),\n delta: down ? -settings.step : settings.step,\n })\n .catch((error: Error) => plugin.log(\"slider:\", error.message));\n };\n const sensorPressed = useSensorPressed(slot.kind === \"sensor\" ? slot.index : 0);\n const index = slot.kind === \"window\" ? -1 : slot.index;\n useSensorRepeat((i) => slot.kind === \"sensor\" && i === index && step(), {\n sensor: slot.kind === \"sensor\" ? index : -1,\n intervalMs: 150,\n });\n useKeyRepeat((i) => slot.kind === \"key\" && i === index && step(), {\n key: slot.kind === \"key\" ? index : -1,\n intervalMs: 150,\n });\n const strip = slot.kind === \"sensor\";\n const text = !level ? \"N/A\" : `${level.volume}%`;\n const icons = targetIcons(settings);\n const size = strip ? 12 : 24;\n const icon = useIcon(level?.muted ? icons.off : icons.on, \"#ffffff\");\n const arrow = useIcon(down ? \"lucide/minus\" : \"lucide/plus\", \"#ffffff\");\n return (\n <div\n style={{\n display: \"flex\",\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n background: strip && sensorPressed ? \"#334155\" : \"#0f172a\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n position: \"absolute\",\n left: 0,\n top: 0,\n bottom: 0,\n width: `${level?.volume ?? 0}%`,\n background: level?.muted ? \"#7f1d1d\" : settings.color,\n opacity: 0.6,\n }}\n />\n <div\n style={{\n display: \"flex\",\n flexDirection: \"row\",\n alignItems: \"center\",\n gap: strip ? 3 : 6,\n color: \"#ffffff\",\n fontWeight: 700,\n fontSize: 20,\n }}\n >\n {strip && arrow ? <img src={arrow} width={10} height={10} alt=\"\" /> : null}\n {icon ? <img src={icon} width={size} height={size} alt=\"\" /> : null}\n {/* On a sensor the bar alone shows the level. */}\n {strip ? null : <div style={{ display: \"flex\" }}>{text}</div>}\n </div>\n </div>\n );\n },\n});\n\n// -- Default device -----------------------------------------------------------------------------\n\nconst NEXT = \"__next\";\n\n/** The device after the default one, for \"Next device\". */\nexport function nextDevice(devices: readonly AudioDevice[]): AudioDevice | undefined {\n const at = devices.findIndex((d) => d.default);\n return devices[(at + 1) % devices.length];\n}\n\nconst defaultDevice = defineAction({\n id: \"default-device\",\n name: \"Switch audio device\",\n description: \"Makes another speaker or microphone the default, or steps through them.\",\n category: \"Audio\",\n icon: \"speaker\",\n slots: [\"key\", \"sensor\"],\n settings: {\n flow: {\n type: \"select\",\n label: \"Switch the\",\n default: \"output\",\n options: [\n { value: \"output\", label: \"Output (speakers)\" },\n { value: \"input\", label: \"Input (microphone)\" },\n ],\n },\n output: {\n type: \"select\",\n label: \"To\",\n default: NEXT,\n source: \"outputs\",\n options: [{ value: NEXT, label: \"The next device\" }],\n visibleIf: { flow: \"output\" },\n },\n input: {\n type: \"select\",\n label: \"To\",\n default: NEXT,\n source: \"inputs\",\n options: [{ value: NEXT, label: \"The next device\" }],\n visibleIf: { flow: \"input\" },\n },\n background: { type: \"color\", label: \"Background\", default: \"#3b0764\" },\n },\n run: async ({ settings }) => {\n const wanted = settings.flow === \"output\" ? settings.output : settings.input;\n const snapshot = await helper.request(\"snapshot\");\n const devices = settings.flow === \"output\" ? snapshot.outputs : snapshot.inputs;\n const device = wanted === NEXT ? nextDevice(devices) : devices.find((d) => d.id === wanted);\n if (!device) throw new Error(\"that audio device is not connected\");\n const { previous } = await helper.request(\"setDefault\", { device: device.id });\n return {\n result: device.name,\n label: `Audio ${settings.flow}: ${device.name}`,\n ...(previous && {\n undo: () => helper.request(\"setDefault\", { device: previous }),\n }),\n };\n },\n look: (s): Look => ({\n background: s.background,\n layers: [\n iconLayer(\"icon\", s.flow === \"output\" ? \"lucide/headphones\" : \"lucide/mic\", {\n size: 44,\n position: \"top\",\n row: \"icon\",\n }),\n iconLayer(\"switch\", \"lucide/arrow-left-right\", {\n color: \"#c4b5fd\",\n size: 22,\n position: \"top\",\n row: \"icon\",\n }),\n textLayer(\"device\", `{{audio.${s.flow} ?? \"N/A\"}}`, { size: 11, position: \"bottom\" }),\n ],\n }),\n});\n\nconst deviceOptions = async (flow: \"outputs\" | \"inputs\") =>\n (await helper.request(\"snapshot\"))[flow].map((d) => ({ value: d.id, label: d.name }));\n\nexport default definePlugin({\n id: \"@sdeck/plugin-audio\",\n name: \"Audio\",\n version: \"0.1.0\",\n namespace: \"audio\",\n description: \"Volume and mute for speakers, microphone and each app, and device switching.\",\n author: \"sdeck\",\n permissions: [\"audio\", \"process\"],\n settings: {\n helper: {\n type: \"text\",\n label: \"Audio helper\",\n placeholder: \"Found automatically\",\n description: \"Full path of sdeck-audio, if it is somewhere unusual.\",\n },\n },\n onboarding: {\n steps: [\n {\n id: \"helper\",\n title: \"The audio helper\",\n body: \"sdeck reaches your speakers, microphone and apps through a small helper that comes with this plugin on Windows. Leave this empty unless it is somewhere else.\",\n settings: [\"helper\"],\n done: (activated) => {\n const custom = String(activated.settings().helper ?? \"\").trim();\n return custom ? existsSync(custom) : findHelper() !== undefined;\n },\n },\n ],\n },\n actions: [volume, slider, defaultDevice],\n optionSources: {\n outputs: () => deviceOptions(\"outputs\"),\n inputs: () => deviceOptions(\"inputs\"),\n apps: async () =>\n (await helper.request(\"snapshot\")).apps.map((a) => ({ value: a.name, label: a.name })),\n },\n state: [\n stateOf(\"master\", \"Speakers\", \"json\", \"audio.master.volume, .muted, .name\"),\n stateOf(\"mic\", \"Microphone\", \"json\", \"audio.mic.volume, .muted, .name\"),\n stateOf(\"output\", \"Output device\", \"string\", \"The default output's name.\"),\n stateOf(\"input\", \"Input device\", \"string\", \"The default input's name.\"),\n stateOf(\"outputs\", \"Output devices\", \"json\", \"Every output with its level.\"),\n stateOf(\"inputs\", \"Input devices\", \"json\", \"Every input with its level.\"),\n stateOf(\"apps\", \"App volumes\", \"json\", \"audio.apps.spotify.volume, .muted, .active\"),\n ],\n activate(activated) {\n context = activated;\n if (process.platform !== \"win32\") {\n activated.status(\"Audio control is available on Windows only\", \"info\");\n } else if (!findHelper() && !activated.settings().helper) {\n activated.status(`${BUILD_HINT}.`, \"info\");\n }\n return () => {\n helper.close();\n context = undefined;\n };\n },\n});\n",
6
+ "import type { Renderable } from \"./index.ts\";\n\nexport interface Size {\n width: number;\n height: number;\n}\n\n/** Decoded pixels: 3 (RGB) or 4 (RGBA) interleaved 8-bit channels. */\nexport interface RawImage {\n data: Uint8Array;\n width: number;\n height: number;\n channels: 3 | 4;\n}\n\nexport const isRawImage = (value: unknown): value is RawImage =>\n typeof value === \"object\" &&\n value !== null &&\n !ArrayBuffer.isView(value) &&\n \"data\" in value &&\n \"width\" in value &&\n \"height\" in value &&\n \"channels\" in value;\n\n/** A font for rendering text in elements (TTF, OTF or WOFF; not WOFF2). */\nexport interface DeckFont {\n name: string;\n data: Uint8Array | ArrayBuffer;\n weight?: 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;\n style?: \"normal\" | \"italic\";\n}\n\nexport interface ElementOptions {\n /** Extra fonts for text (a renderer has a built-in fallback font). */\n fonts?: readonly DeckFont[];\n /** Called when rendering or sending a frame fails after the initial render (default: log). */\n onError?: (error: unknown) => void;\n /**\n * Draws everything this many times larger: the element is laid out at the target size divided\n * by `scale` (default 1).\n */\n scale?: number;\n /** Set `false` to draw no text at all, whatever the element holds (default `true`). */\n text?: boolean;\n}\n\n/**\n * A live element tree that redraws its target whenever its state changes. Frames are coalesced:\n * if state changes while one is being sent, only the latest is drawn next.\n */\nexport interface ElementRoot {\n /** Renders `element` (replacing the previous one, keeping state where types match). */\n render(element: Renderable): void;\n /** Resolves once every pending frame has been drawn. */\n idle(): Promise<void>;\n /** Unmounts the tree (running cleanups) and stops drawing. */\n unmount(): Promise<void>;\n}\n\n/** What a renderer package (such as `@sdeck/react`) provides to the core. */\nexport interface ElementRuntime {\n /** True if `value` is an element this runtime can draw. */\n matches(value: unknown): boolean;\n /** Renders `element` once to upright pixels of exactly `size`. */\n render(element: Renderable, size: Size, options?: ElementOptions): Promise<RawImage>;\n /** Mounts a live tree; every change is passed to `onFrame` as upright pixels of `size`. */\n createRoot(\n size: Size,\n onFrame: (frame: RawImage) => void | Promise<void>,\n options?: ElementOptions,\n ): Promise<ElementRoot>;\n}\n\nlet runtime: ElementRuntime | undefined;\n\n/** Registers the renderer used for elements. `@sdeck/react` does this when imported. */\nexport function registerElementRuntime(next: ElementRuntime): void {\n runtime = next;\n}\n\nexport function getElementRuntime(): ElementRuntime {\n if (!runtime) {\n throw new Error(\n \"Drawing elements needs a renderer: install and import `@sdeck/react` (once, anywhere)\",\n );\n }\n return runtime;\n}\n\n/** True for elements the registered renderer can draw (false if none is registered). */\nexport const isRenderable = (value: unknown): value is Renderable =>\n runtime !== undefined && typeof value === \"object\" && value !== null && runtime.matches(value);\n",
7
+ "import {\n type DeckFont,\n type ElementOptions,\n type ElementRoot,\n type RawImage,\n registerElementRuntime,\n type Size,\n} from \"@sdeck/core\";\nimport type { Renderer } from \"@takumi-rs/core\";\nimport type { ReactElement, ReactNode } from \"react\";\n\n/** A font for rendering text in React elements (TTF, OTF or WOFF; not WOFF2). */\nexport type ReactFont = DeckFont;\n\nexport interface ReactRenderOptions extends ElementOptions {}\n\n/**\n * A live React tree that redraws its target whenever state changes. Hooks, effects, context,\n * suspense and timers all work, because this is a real React renderer.\n */\nexport interface ReactRoot extends ElementRoot {\n /** Renders `element` (replacing the previous one, keeping state where types match). */\n render(element: ReactNode): void;\n}\n\ndeclare module \"@sdeck/core\" {\n interface RenderableRegistry {\n react: ReactNode;\n }\n}\n\n/** True for anything created by `React.createElement` / JSX. */\nexport function isReactElement(value: unknown): value is ReactElement {\n return typeof value === \"object\" && value !== null && \"$$typeof\" in value;\n}\n\n// --- Takumi ------------------------------------------------------------------------------------\n\nconst defaultRenderer: { current?: Promise<Renderer> } = {};\nconst fontRenderers = new WeakMap<readonly DeckFont[], Promise<Renderer>>();\n\nasync function createRenderer(fonts: readonly DeckFont[]): Promise<Renderer> {\n const { Renderer } = await import(\"@takumi-rs/core\");\n const renderer = new Renderer();\n for (const font of fonts) {\n await renderer.registerFont({\n name: font.name,\n data: font.data,\n ...(font.weight !== undefined && { weight: font.weight }),\n ...(font.style !== undefined && { style: font.style }),\n });\n }\n return renderer;\n}\n\n/** One Renderer for the built-in font, and one per distinct `fonts` array. */\nfunction getRenderer(fonts: readonly DeckFont[] | undefined): Promise<Renderer> {\n if (!fonts?.length) {\n defaultRenderer.current ??= createRenderer([]);\n defaultRenderer.current.catch(() => {\n defaultRenderer.current = undefined;\n });\n return defaultRenderer.current;\n }\n let renderer = fontRenderers.get(fonts);\n if (!renderer) {\n renderer = createRenderer(fonts);\n renderer.catch(() => fontRenderers.delete(fonts));\n fontRenderers.set(fonts, renderer);\n }\n return renderer;\n}\n\n// --- The renderer: React elements -> a plain host tree -> Takumi nodes. ---------------------------\n\ninterface HostText {\n text: string;\n}\ninterface HostElement {\n type: string;\n props: Record<string, unknown>;\n children: Array<HostElement | HostText>;\n}\ninterface Container {\n children: Array<HostElement | HostText>;\n onCommit: () => void;\n}\n\ntype TakumiNode =\n | { type: \"text\"; text: string; style?: object; tw?: string }\n | { type: \"image\"; src: string; width?: number; height?: number; style?: object; tw?: string }\n | { type: \"container\"; children: TakumiNode[]; style?: object; tw?: string };\n\nconst number = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n\n/**\n * Host elements follow HTML names: `<img src width height>` is an image, everything else\n * (`div`, `span`, ...) is a flex container, like in satori. Text and numbers are text nodes.\n * `style` is Takumi's style object (camelCase CSS), and `tw` takes Tailwind classes. Without\n * `text`, text nodes are left out.\n */\nfunction toNode(node: HostElement | HostText, text = true): TakumiNode {\n if (\"text\" in node) {\n return text ? { type: \"text\", text: node.text } : { type: \"container\", children: [] };\n }\n\n const { style, tw, src, width, height } = node.props;\n const common = {\n ...(typeof tw === \"string\" && { tw }),\n };\n if (node.type === \"img\") {\n if (typeof src !== \"string\") throw new Error(\"<img> needs a string `src` (URL or data: URI)\");\n return {\n type: \"image\",\n src,\n ...(number(width) !== undefined && { width: number(width) }),\n ...(number(height) !== undefined && { height: number(height) }),\n ...(typeof style === \"object\" && style !== null && { style }),\n ...common,\n };\n }\n return {\n type: \"container\",\n style: { display: \"flex\", ...(typeof style === \"object\" ? style : {}) },\n children: node.children\n .filter((child) => text || !(\"text\" in child))\n .map((child) => toNode(child, text)),\n ...common,\n };\n}\n\n/** The subset of react-reconciler that we use. */\ninterface Reconciler {\n createContainer(...args: unknown[]): unknown;\n updateContainer(element: ReactNode, root: unknown, parent: null, callback: null): unknown;\n updateContainerSync(element: ReactNode, root: unknown, parent: null, callback: null): unknown;\n flushSyncWork(): boolean;\n flushPassiveEffects(): boolean;\n}\n\nlet reconciler: Promise<Reconciler> | undefined;\n\n/**\n * Above zero while a root flushes its effects. State set by those effects is then rendered at once,\n * rather than in a later task, so a one-shot frame never misses it.\n */\nlet flushing = 0;\n\n/** Flushes the sync commit, then any effects and the renders they cause. */\nfunction flushAll(renderer: Reconciler) {\n flushing++;\n try {\n renderer.flushSyncWork();\n for (let i = 0; i < 20 && renderer.flushPassiveEffects(); i++) renderer.flushSyncWork();\n } finally {\n flushing--;\n }\n}\n\nfunction loadReconciler(): Promise<Reconciler> {\n reconciler ??= (async () => {\n let factoryModule: unknown;\n let constants: typeof import(\"react-reconciler/constants.js\");\n let React: typeof import(\"react\");\n try {\n [factoryModule, constants, React] = await Promise.all([\n import(\"react-reconciler\"),\n import(\"react-reconciler/constants.js\"),\n import(\"react\"),\n ]);\n } catch (cause) {\n throw new Error(\"Rendering React elements requires `react` (>=19.3) to be installed\", {\n cause,\n });\n }\n\n let priority: number = constants.NoEventPriority;\n const noop = () => {};\n const hostConfig = {\n supportsMutation: true,\n supportsPersistence: false,\n supportsHydration: false,\n isPrimaryRenderer: true,\n warnsIfNotActing: false,\n noTimeout: -1,\n scheduleTimeout: setTimeout,\n cancelTimeout: clearTimeout,\n supportsMicrotasks: true,\n scheduleMicrotask: queueMicrotask,\n\n createInstance: (type: string, props: Record<string, unknown>): HostElement => {\n const { children: _children, ...rest } = props;\n return { type, props: rest, children: [] };\n },\n createTextInstance: (text: string): HostText => ({ text }),\n shouldSetTextContent: () => false,\n appendInitialChild: (parent: HostElement, child: HostElement | HostText) =>\n parent.children.push(child),\n appendChild: (parent: HostElement, child: HostElement | HostText) =>\n parent.children.push(child),\n appendChildToContainer: (container: Container, child: HostElement | HostText) =>\n container.children.push(child),\n insertBefore: (parent: HostElement, child: HostElement | HostText, before: HostElement) => {\n const children = parent.children;\n const existing = children.indexOf(child);\n if (existing !== -1) children.splice(existing, 1);\n children.splice(children.indexOf(before), 0, child);\n },\n insertInContainerBefore: (\n container: Container,\n child: HostElement | HostText,\n before: HostElement,\n ) => {\n const children = container.children;\n const existing = children.indexOf(child);\n if (existing !== -1) children.splice(existing, 1);\n children.splice(children.indexOf(before), 0, child);\n },\n removeChild: (parent: HostElement, child: HostElement | HostText) => {\n parent.children.splice(parent.children.indexOf(child), 1);\n },\n removeChildFromContainer: (container: Container, child: HostElement | HostText) => {\n container.children.splice(container.children.indexOf(child), 1);\n },\n clearContainer: (container: Container) => {\n container.children = [];\n },\n commitUpdate: (\n instance: HostElement,\n _type: string,\n _prev: Record<string, unknown>,\n next: Record<string, unknown>,\n ) => {\n const { children: _children, ...rest } = next;\n instance.props = rest;\n },\n commitTextUpdate: (text: HostText, _old: string, next: string) => {\n text.text = next;\n },\n finalizeInitialChildren: () => false,\n getPublicInstance: (instance: unknown) => instance,\n // React requires a non-null host context.\n getRootHostContext: () => ({}),\n getChildHostContext: (parent: object) => parent,\n prepareForCommit: () => null,\n resetAfterCommit: (container: Container) => container.onCommit(),\n preparePortalMount: noop,\n detachDeletedInstance: noop,\n hideInstance: noop,\n unhideInstance: noop,\n hideTextInstance: noop,\n unhideTextInstance: noop,\n getInstanceFromNode: () => null,\n beforeActiveInstanceBlur: noop,\n afterActiveInstanceBlur: noop,\n prepareScopeUpdate: noop,\n getInstanceFromScope: () => null,\n bindToConsole: (method: string, args: unknown[]) =>\n (console as unknown as Record<string, (...a: unknown[]) => void>)[method]?.bind(\n console,\n ...args,\n ) ?? noop,\n extraDevToolsConfig: null,\n rendererVersion: \"0.0.0\",\n rendererPackageName: \"sdeck\",\n\n // React 19 scheduling and transition hooks.\n getCurrentUpdatePriority: () => priority,\n setCurrentUpdatePriority: (next: number) => {\n priority = next;\n },\n resolveUpdatePriority: () =>\n priority !== constants.NoEventPriority\n ? priority\n : flushing > 0\n ? constants.DiscreteEventPriority\n : constants.DefaultEventPriority,\n resolveEventType: () => null,\n resolveEventTimeStamp: () => -1.1,\n shouldAttemptEagerTransition: () => false,\n trackSchedulerEvent: noop,\n requestPostPaintCallback: noop,\n maySuspendCommit: () => false,\n preloadInstance: () => true,\n startSuspendingCommit: noop,\n suspendInstance: noop,\n waitForCommitToBeReady: () => null,\n getSuspendedCommitReason: () => null,\n NotPendingTransition: null,\n HostTransitionContext: React.createContext(null),\n resetFormInstance: noop,\n };\n\n // CommonJS module: the factory is `default` under ESM interop, or the module itself.\n type Factory = (config: never) => Reconciler;\n const factory = (factoryModule as { default?: Factory }).default ?? (factoryModule as Factory);\n return factory(hostConfig as never);\n })();\n reconciler.catch(() => {\n reconciler = undefined;\n });\n return reconciler;\n}\n\nfunction noopIndicator() {}\n\n/**\n * Mounts a live React tree. Every committed change is laid out and rasterised by\n * [Takumi](https://takumi.kane.tw) (flexbox and CSS via `style` / `tw` props) and passed to\n * `onFrame` as upright RGBA pixels of exactly `size`. Frames are coalesced: if state changes while\n * one is being sent, only the latest is drawn next.\n */\nexport async function createReactRoot(\n size: Size,\n onFrame: (frame: RawImage) => void | Promise<void>,\n options: ReactRenderOptions = {},\n): Promise<ReactRoot> {\n const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);\n\n let dirty = false;\n let drawing: Promise<void> | undefined;\n let lastTree: string | undefined;\n let unmounted = false;\n let renderError: { error: unknown } | undefined;\n let initial = true;\n\n const fail = (error: unknown) => {\n if (initial) renderError ??= { error };\n else (options.onError ?? ((e) => console.error(\"sdeck: React render failed:\", e)))(error);\n };\n\n async function draw() {\n // Yield first so `drawing` is assigned before this can finish and clear it.\n await Promise.resolve();\n while (dirty && !unmounted) {\n dirty = false;\n try {\n const [root] = container.children;\n if (!root) continue;\n const tree = toNode(root, options.text !== false);\n const key = JSON.stringify(tree);\n if (key === lastTree) continue; // nothing visible changed\n lastTree = key;\n const pixels = await takumi.render(tree as never, {\n width: size.width,\n height: size.height,\n format: \"raw\",\n ...(options.scale !== undefined && { devicePixelRatio: options.scale }),\n });\n await onFrame({\n data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),\n width: size.width,\n height: size.height,\n channels: 4,\n });\n } catch (error) {\n lastTree = undefined; // a failed frame was not drawn: draw it again next time\n fail(error);\n }\n }\n drawing = undefined;\n }\n\n const container: Container = {\n children: [],\n onCommit() {\n dirty = true;\n drawing ??= draw();\n },\n };\n\n const onError = (error: unknown) => fail(error);\n // An error caught by an error boundary is handled: the boundary draws its fallback.\n const onCaughtError = () => {};\n const root = renderer.createContainer(\n container,\n 1, // ConcurrentRoot\n null,\n false,\n null,\n \"\",\n onError, // uncaught\n onCaughtError,\n onError, // recoverable\n noopIndicator,\n null,\n );\n\n const flush = () => flushAll(renderer);\n\n const handle: ReactRoot = {\n render(element) {\n if (unmounted) throw new Error(\"This React root was unmounted\");\n renderer.updateContainerSync(element, root, null, null);\n flush();\n },\n async idle() {\n while (drawing) await drawing;\n if (initial && renderError) {\n const { error } = renderError;\n renderError = undefined;\n throw error;\n }\n initial = false;\n },\n async unmount() {\n if (unmounted) return;\n renderer.updateContainerSync(null, root, null, null);\n flush();\n unmounted = true;\n await drawing;\n },\n };\n return handle;\n}\n\n/**\n * Renders a React element once to upright RGBA pixels of exactly `size`. Hooks, context and\n * effects work; effects and the state updates they cause are applied before the frame is taken,\n * but timers are not awaited (use `createReactRoot` or `deck.mountKey` for live updates).\n */\nexport async function renderReact(\n element: ReactNode,\n size: Size,\n fonts?: readonly ReactFont[],\n scale?: number,\n): Promise<RawImage> {\n let frame: RawImage | undefined;\n const root = await createReactRoot(\n size,\n (next) => {\n frame = next;\n },\n { ...(fonts && { fonts }), ...(scale !== undefined && { scale }) },\n );\n try {\n root.render(element);\n await root.idle();\n } finally {\n await root.unmount();\n }\n if (!frame) throw new Error(\"React element rendered nothing\");\n return frame;\n}\n\nregisterElementRuntime({\n matches: isReactElement,\n render: (element, size, options) => renderReact(element, size, options?.fonts),\n createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options),\n});\n\n/** Where one element ends up when laid out, in the pixels of the target. */\nexport interface MeasuredElement {\n /** The element's `data-measure` prop. */\n id: string;\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\ninterface TakumiMeasurement {\n width: number;\n height: number;\n /** A 2D matrix `[a, b, c, d, e, f]`; `e` and `f` place the node's top left corner. */\n transform: readonly number[];\n children: readonly TakumiMeasurement[];\n}\n\n/**\n * Lays a React element out like {@link renderReact}, without drawing it, and reports where every\n * element with a `data-measure` prop is.\n */\nexport async function measureReact(\n element: ReactNode,\n size: Size,\n fonts?: readonly ReactFont[],\n): Promise<MeasuredElement[]> {\n const [takumi, renderer] = await Promise.all([getRenderer(fonts), loadReconciler()]);\n const container: Container = { children: [], onCommit() {} };\n let failure: { error: unknown } | undefined;\n const fail = (error: unknown) => {\n failure ??= { error };\n };\n const root = renderer.createContainer(\n container,\n 1,\n null,\n false,\n null,\n \"\",\n fail,\n () => {},\n fail,\n noopIndicator,\n null,\n );\n try {\n renderer.updateContainerSync(element, root, null, null);\n flushAll(renderer);\n if (failure) throw failure.error;\n const [host] = container.children;\n if (!host) return [];\n const measured = (await takumi.measure(toNode(host) as never, {\n width: size.width,\n height: size.height,\n })) as TakumiMeasurement;\n const found: MeasuredElement[] = [];\n // The measured tree has the same shape as the host tree.\n const walk = (node: HostElement | HostText, box: TakumiMeasurement | undefined) => {\n if (!box || \"text\" in node) return;\n const id = node.props[\"data-measure\"];\n if (typeof id === \"string\") {\n found.push({\n id,\n x: box.transform[4] ?? 0,\n y: box.transform[5] ?? 0,\n width: box.width,\n height: box.height,\n });\n }\n for (const [i, child] of node.children.entries()) walk(child, box.children[i]);\n };\n walk(host, measured);\n return found;\n } finally {\n renderer.updateContainerSync(null, root, null, null);\n renderer.flushSyncWork();\n }\n}\n",
8
+ "import {\n type ElementRoot,\n type MountOptions,\n manageDeck,\n type OpenOptions,\n type StreamDeck,\n toError,\n watchDeck,\n} from \"@sdeck/core\";\nimport { openStreamDeckNeo } from \"@sdeck/neo\";\nimport \"@sdeck/react\";\nimport { Fragment, type ReactNode, useSyncExternalStore } from \"react\";\nimport { DeckContext, NavigatorContext, SlotContext, type SlotInfo } from \"./context.ts\";\nimport { Navigator } from \"./navigator.ts\";\n\n/** What one page shows. Anything left out is blank. */\nexport interface PageDef {\n /**\n * Elements by key index: a sparse object (`{ 0: <A />, 3: <B /> }`) or an array. Keys the\n * connected deck doesn't have are ignored.\n * (Linters that flag arrays of JSX without `key` props prefer the object form.)\n */\n keys?: ReadonlyArray<ReactNode> | Readonly<Partial<Record<number, ReactNode>>>;\n /** The window (on decks that have one; the Neo's is 248×58). */\n window?: ReactNode;\n /**\n * The sensor indicator strips (the Neo's are 96×16), as `{ 0: <Left />, 1: <Right /> }` or an\n * array. Each strip redraw is a full-screen update, so only define these if you need them.\n */\n sensors?: ReadonlyArray<ReactNode> | Readonly<Partial<Record<number, ReactNode>>>;\n}\n\nexport interface AppDef {\n /** Pages by name. */\n pages: Readonly<Record<string, PageDef>>;\n /** Page shown first (default: the first page). */\n initial?: string;\n /**\n * The pages `next()`/`previous()` step through, in order (default: every page). Leave out pages\n * that are only opened from a key, such as folders.\n */\n sequence?: readonly string[];\n /** Brightness (0–100) applied on every connect. */\n brightness?: number;\n /** Dim the deck after a period without input. */\n idle?: { afterMs: number; brightness?: number };\n /** Sleep timeout stored in the deck, in seconds (0 disables). */\n sleepSeconds?: number;\n /** Colour of blank keys and the window (default `#000000`). */\n background?: string;\n /** Set `false` to keep all text off the sensor strips (default `true`). */\n sensorText?: boolean;\n /** Options for every mounted root (fonts, JPEG quality, `onError`). */\n mount?: MountOptions;\n /** Runs after each (re)connect, before the first page is drawn. */\n onConnect?: (deck: StreamDeck) => void | Promise<void>;\n}\n\n/** Validates an app definition (and gives you type checking while writing it). */\nexport function defineApp(app: AppDef): AppDef {\n const names = Object.keys(app.pages);\n if (names.length === 0) throw new RangeError(\"an app needs at least one page\");\n if (app.initial !== undefined && !(app.initial in app.pages)) {\n throw new RangeError(`initial page \"${app.initial}\" is not defined`);\n }\n for (const [name, page] of Object.entries(app.pages)) {\n const indices = Array.isArray(page.keys)\n ? page.keys.length > 0\n ? [page.keys.length - 1]\n : []\n : Object.keys(page.keys ?? {}).map(Number);\n for (const index of indices) {\n if (!Number.isInteger(index) || index < 0) {\n throw new RangeError(\n `page \"${name}\": key index must be a non-negative integer, got ${index}`,\n );\n }\n }\n }\n return app;\n}\n\nfunction createNavigator(app: AppDef): Navigator {\n const initial = app.initial ?? (Object.keys(app.pages)[0] as string);\n const pages = Object.keys(app.pages);\n const sequence = app.sequence?.filter((page) => Object.hasOwn(app.pages, page)) ?? pages;\n return new Navigator(initial, (page) => Object.hasOwn(app.pages, page), pages, sequence);\n}\n\n// -- Rendering ----------------------------------------------------------------\n\nfunction Blank({ background }: { background: string }) {\n return <div style={{ display: \"flex\", width: \"100%\", height: \"100%\", background }} />;\n}\n\n/** Draws the current page's content for one slot, remounting it (fresh state) on page change. */\nfunction PageSlot({\n app,\n nav,\n pick,\n}: {\n app: AppDef;\n nav: Navigator;\n pick: (page: PageDef) => ReactNode;\n}) {\n const { page } = useSyncExternalStore(nav.subscribe, nav.getSnapshot);\n const content = pick(app.pages[page] ?? {});\n return (\n <Fragment key={page}>{content ?? <Blank background={app.background ?? \"#000000\"} />}</Fragment>\n );\n}\n\nfunction Providers({\n deck,\n nav,\n slot,\n children,\n}: {\n deck: StreamDeck;\n nav: Navigator;\n slot: SlotInfo;\n children: ReactNode;\n}) {\n return (\n <DeckContext.Provider value={deck}>\n <NavigatorContext.Provider value={nav}>\n <SlotContext.Provider value={slot}>{children}</SlotContext.Provider>\n </NavigatorContext.Provider>\n </DeckContext.Provider>\n );\n}\n\n// -- One connection -----------------------------------------------------------\n\nexport interface MountAppOptions {\n /** Share a navigator across connections (default: a new one). */\n navigation?: Navigator;\n /**\n * How often to check the deck is still answering, in ms (default 3000, 0 disables).\n * A failed check (or any deck `error` that the deck fails to answer after) ends the session.\n */\n heartbeatMs?: number;\n /** Called with every error (render, send, listener). */\n onError?: (error: Error) => void;\n}\n\nexport interface AppSession {\n readonly navigation: Navigator;\n /** Resolves, with the cause, when the deck stops answering (for example when unplugged). */\n readonly lost: Promise<Error>;\n /** Unmounts everything, restores the logo and closes the deck. Never rejects. */\n dispose(): Promise<void>;\n}\n\n/**\n * Mounts `app` on an already-open deck: applies brightness and sleep, draws the current page on\n * every key and the window (and on sensor strips if any page defines them), and keeps it all in\n * sync with navigation. Use {@link runApp} to also handle detection and reconnecting.\n */\nexport async function mountApp(\n deck: StreamDeck,\n app: AppDef,\n options: MountAppOptions = {},\n): Promise<AppSession> {\n const nav = options.navigation ?? createNavigator(app);\n const { heartbeatMs = 3000 } = options;\n const cleanups: Array<() => void> = [];\n const roots: ElementRoot[] = [];\n\n const report = (error: unknown) => options.onError?.(toError(error));\n const watch = watchDeck(deck, { heartbeatMs, onError: report });\n const lost = watch.lost;\n cleanups.push(() => watch.stop());\n\n const dispose = async () => {\n for (const cleanup of cleanups.splice(0)) cleanup();\n await deck.close().catch(() => {});\n };\n\n try {\n if (app.brightness !== undefined) await deck.setBrightness(app.brightness);\n if (app.sleepSeconds !== undefined) {\n // Not every model stores a sleep timeout; skip it where unsupported.\n const sleepable = deck as StreamDeck & { setSleepDuration?(seconds: number): Promise<void> };\n await sleepable.setSleepDuration?.(app.sleepSeconds);\n }\n await app.onConnect?.(deck);\n\n if (app.idle) {\n const { afterMs, brightness: dimmed = 5 } = app.idle;\n const awake = app.brightness ?? 100;\n let dim: ReturnType<typeof setTimeout> | undefined;\n let isDim = false;\n const arm = () => {\n clearTimeout(dim);\n dim = setTimeout(() => {\n isDim = true;\n deck.setBrightness(dimmed).catch(report);\n }, afterMs);\n };\n const wake = () => {\n if (isDim) {\n isDim = false;\n deck.setBrightness(awake).catch(report);\n }\n arm();\n };\n for (const event of [\"keyDown\", \"keyUp\", \"sensorDown\", \"sensorUp\"] as const) {\n cleanups.push(deck.on(event, wake));\n }\n cleanups.push(() => clearTimeout(dim));\n arm();\n }\n\n const mountOptions: MountOptions = {\n background: app.background,\n ...app.mount,\n onError: app.mount?.onError ?? report,\n };\n const pages = Object.values(app.pages);\n const slot = (info: SlotInfo, pick: (page: PageDef) => ReactNode) => (\n <Providers deck={deck} nav={nav} slot={info}>\n <PageSlot app={app} nav={nav} pick={pick} />\n </Providers>\n );\n\n roots.push(\n ...(await Promise.all(\n Array.from({ length: deck.keyCount }, (_, index) =>\n deck.mountKey(\n index,\n slot({ kind: \"key\", index }, (page) => page.keys?.[index]),\n mountOptions,\n ),\n ),\n )),\n );\n if (deck.model.layout.window) {\n roots.push(\n await deck.mountWindow(\n slot({ kind: \"window\" }, (page) => page.window),\n mountOptions,\n ),\n );\n }\n // Strips are full-screen redraws: mount them last (so the first frame has the keys) and\n // only if some page uses them.\n for (let index = 0; index < deck.sensorCount; index++) {\n if (!pages.some((page) => page.sensors?.[index] !== undefined)) continue;\n roots.push(\n await deck.mountSensor(\n index,\n slot({ kind: \"sensor\", index }, (page) => page.sensors?.[index]),\n app.sensorText === false ? { ...mountOptions, text: false } : mountOptions,\n ),\n );\n }\n } catch (error) {\n await dispose();\n throw error;\n }\n\n return { navigation: nav, lost, dispose };\n}\n\n// -- Detection and reconnecting -----------------------------------------------\n\nexport type AppStatus = \"waiting\" | \"connected\" | \"stopped\";\n\nexport interface RunAppOptions extends Pick<MountAppOptions, \"heartbeatMs\" | \"onError\"> {\n /** Stop the app (and release the deck) when aborted. */\n signal?: AbortSignal;\n /** Which deck to open and how often to scan. `signal` and `wait` are managed for you. */\n open?: Omit<OpenOptions, \"signal\" | \"wait\">;\n /**\n * Opens the deck, for models other than the Neo: `(signal) => openDeck(myDriver, { signal })`.\n * Overrides `open`.\n */\n openDeck?: (signal: AbortSignal) => Promise<StreamDeck>;\n /** Keep going when the deck is unplugged, and redraw when it is back (default `true`). */\n reconnect?: boolean;\n /** Called when the app starts waiting for a deck, connects, or stops. */\n onStatus?: (status: AppStatus, deck?: StreamDeck) => void;\n}\n\nexport interface AppHandle {\n readonly status: AppStatus;\n /** The connected deck, or `undefined` while waiting. */\n readonly deck: StreamDeck | undefined;\n /** Drive navigation from outside React. It survives reconnects. */\n readonly navigation: Navigator;\n /** Stops the app and restores the logo. Resolves when the deck is released. */\n stop(): Promise<void>;\n /** Resolves once the app has stopped (after `stop()`, abort, or a lost deck with `reconnect: false`). */\n readonly finished: Promise<void>;\n}\n\n/**\n * Runs an app: waits for a Stream Deck (a Neo unless `openDeck` says otherwise), shows the app on\n * it, and when the deck is unplugged waits for it to come back and draws the app again, on the\n * page the user was on. Returns immediately; use the handle to stop it.\n *\n * ```tsx\n * const app = defineApp({ pages: { home: { keys: [<Button .../>] } } });\n * const handle = runApp(app, { onStatus: console.log });\n * process.once(\"SIGINT\", () => handle.stop());\n * ```\n */\nexport function runApp(app: AppDef, options: RunAppOptions = {}): AppHandle {\n const navigation = createNavigator(app);\n const handle = manageDeck<StreamDeck>({\n open: options.openDeck ?? ((signal) => openStreamDeckNeo({ ...options.open, signal })),\n // The manager watches the deck, so the session need not.\n async setup(deck) {\n const session = await mountApp(deck, app, {\n navigation,\n heartbeatMs: 0,\n ...(options.onError && { onError: options.onError }),\n });\n return () => session.dispose();\n },\n ...(options.reconnect !== undefined && { reconnect: options.reconnect }),\n ...(options.signal && { signal: options.signal }),\n ...(options.heartbeatMs !== undefined && { heartbeatMs: options.heartbeatMs }),\n ...(options.onStatus && { onStatus: options.onStatus }),\n ...(options.onError && { onError: options.onError }),\n });\n\n return {\n get status() {\n return handle.status;\n },\n get deck() {\n return handle.deck;\n },\n navigation,\n stop: handle.stop,\n finished: handle.finished,\n };\n}\n",
9
+ "import type { StreamDeck } from \"@sdeck/core\";\nimport { createContext, useContext } from \"react\";\nimport type { Navigator } from \"./navigator.ts\";\n\n/** Which part of the deck a component is rendered into. */\nexport type SlotInfo =\n | { readonly kind: \"key\"; readonly index: number }\n | { readonly kind: \"sensor\"; readonly index: number }\n | { readonly kind: \"window\" };\n\nexport const DeckContext = createContext<StreamDeck | undefined>(undefined);\nexport const SlotContext = createContext<SlotInfo | undefined>(undefined);\nexport const NavigatorContext = createContext<Navigator | undefined>(undefined);\n\n/**\n * The connected deck. Only valid inside an app mounted with `mountApp` / `runApp`. Pass the\n * model's class to get its type: `useDeck<StreamDeckNeo>()`.\n */\nexport function useDeck<D extends StreamDeck = StreamDeck>(): D {\n const deck = useContext(DeckContext);\n if (!deck) throw new Error(\"useDeck() must be used inside a component mounted by @sdeck/app\");\n return deck as D;\n}\n\n/** The slot this component is drawn in (a key, a sensor strip or the window), if any. */\nexport function useSlot(): SlotInfo | undefined {\n return useContext(SlotContext);\n}\n",
10
+ "import { useContext, useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport { NavigatorContext, useDeck, useSlot } from \"./context.ts\";\nimport type { NavState } from \"./navigator.ts\";\nimport { SWIPE_WINDOW_MS, type SwipeDirection, swipeTracker } from \"./swipe.ts\";\n\n/** Keeps the latest value in a ref so effects can call it without re-subscribing. */\nfunction useLatest<T>(value: T) {\n const ref = useRef(value);\n useEffect(() => {\n ref.current = value;\n });\n return ref;\n}\n\ntype Kind = \"key\" | \"sensor\";\n\n/** The explicit index, else the index of this component's own slot, else `undefined` (= any). */\nfunction useTarget(kind: Kind, explicit: number | undefined): number | undefined {\n const slot = useSlot();\n if (explicit !== undefined) return explicit;\n return slot?.kind === kind ? slot.index : undefined;\n}\n\nfunction useInput(\n kind: Kind,\n phase: \"Down\" | \"Up\",\n handler: (index: number) => void,\n explicit: number | undefined,\n): void {\n const deck = useDeck();\n const target = useTarget(kind, explicit);\n const latest = useLatest(handler);\n useEffect(() => {\n const matches = (index: number) => target === undefined || index === target;\n if (phase === \"Down\") {\n return deck.on(`${kind}Down`, (index) => matches(index) && latest.current(index));\n }\n // Only releases of presses this component saw: a press that started on another page (say,\n // the Back button that brought us here) must not count as a release here.\n const held = new Set<number>();\n const offDown = deck.on(`${kind}Down`, (index) => matches(index) && held.add(index));\n const offUp = deck.on(`${kind}Up`, (index) => {\n if (held.delete(index)) latest.current(index);\n });\n return () => {\n offDown();\n offUp();\n };\n }, [deck, kind, phase, target, latest]);\n}\n\nfunction usePressed(kind: Kind, explicit: number | undefined): boolean {\n const deck = useDeck();\n const target = useTarget(kind, explicit);\n const [pressed, setPressed] = useState(false);\n if (target === undefined) {\n throw new Error(\n `use${kind === \"key\" ? \"Key\" : \"Sensor\"}Pressed() needs an index outside a ${kind} slot`,\n );\n }\n useEffect(() => {\n setPressed(false);\n const offDown = deck.on(`${kind}Down`, (i) => i === target && setPressed(true));\n const offUp = deck.on(`${kind}Up`, (i) => i === target && setPressed(false));\n return () => {\n offDown();\n offUp();\n };\n }, [deck, kind, target]);\n return pressed;\n}\n\n// -- Keys ---------------------------------------------------------------------\n\n/**\n * Runs `handler(key)` when a key goes down. `key` defaults to the key slot this component is\n * drawn in; outside a key slot it listens to every key.\n */\nexport function useKeyDown(handler: (key: number) => void, key?: number): void {\n useInput(\"key\", \"Down\", handler, key);\n}\n\n/** Runs `handler(key)` when a key is released. `key` defaults like {@link useKeyDown}. */\nexport function useKeyUp(handler: (key: number) => void, key?: number): void {\n useInput(\"key\", \"Up\", handler, key);\n}\n\n/** `true` while the key is held. `key` defaults to this component's key slot. */\nexport function useKeyPressed(key?: number): boolean {\n return usePressed(\"key\", key);\n}\n\n/** Gestures shared by keys and touch sensors. Handlers get the key or sensor index. */\nexport interface PressGestures {\n /** Called when held for `longPressMs`. The release after it does not count as a press. */\n onLongPress?: (index: number) => void;\n /** Hold time for a long press (default 500 ms). */\n longPressMs?: number;\n /** Called when pressed twice within `doublePressMs`. */\n onDoublePress?: (index: number) => void;\n /** Window for the second press (default 300 ms). */\n doublePressMs?: number;\n /** Run `onPress` on the release even without other gestures. */\n onRelease?: boolean;\n /** @deprecated Use `onDoublePress`. */\n onDoubleTap?: (index: number) => void;\n /** @deprecated Use `doublePressMs`. */\n doubleTapMs?: number;\n}\n\nexport interface KeyPressOptions extends PressGestures {\n /** Key index; defaults to this component's key slot (any key outside one). */\n key?: number;\n}\n\nexport interface SensorPressOptions extends PressGestures {\n /** Sensor index; defaults to this component's sensor slot (any sensor outside one). */\n sensor?: number;\n}\n\nfunction usePress(\n kind: Kind,\n onPress: ((index: number) => void) | undefined,\n gestures: PressGestures,\n explicit: number | undefined,\n): void {\n const deck = useDeck();\n const target = useTarget(kind, explicit);\n const latest = useLatest({\n onPress,\n onLongPress: gestures.onLongPress,\n longPressMs: gestures.longPressMs ?? 500,\n onDoublePress: gestures.onDoublePress ?? gestures.onDoubleTap,\n doublePressMs: gestures.doublePressMs ?? gestures.doubleTapMs ?? 300,\n onRelease: gestures.onRelease ?? false,\n });\n\n useEffect(() => {\n // Asked for before subscribing, so it hears every touch first.\n const swipes = kind === \"sensor\" ? swipeTracker(deck) : undefined;\n // Per index, so a hook listening to every key keeps each key's gesture apart.\n const state = new Map<\n number,\n {\n long?: ReturnType<typeof setTimeout>;\n double?: ReturnType<typeof setTimeout>;\n deferred?: ReturnType<typeof setTimeout>;\n longFired: boolean;\n immediate: boolean;\n downAt: number;\n /** The sensor's swipe stamp when it was touched; a change means it was swiped. */\n stamp: number;\n }\n >();\n /** Indices that went down while this component was mounted. */\n const held = new Set<number>();\n const get = (index: number) => {\n let s = state.get(index);\n if (!s) {\n s = { longFired: false, immediate: false, downAt: 0, stamp: 0 };\n state.set(index, s);\n }\n return s;\n };\n\n const offDown = deck.on(`${kind}Down`, (index) => {\n if (target !== undefined && index !== target) return;\n // The touch that finishes a swipe is not a press.\n if (swipes?.completes(index)) return;\n held.add(index);\n const o = latest.current;\n const s = get(index);\n s.longFired = false;\n s.downAt = performance.now();\n s.stamp = swipes?.stamp(index) ?? 0;\n s.immediate = !o.onLongPress && !o.onDoublePress && !o.onRelease && !swipes?.active;\n if (s.immediate) {\n o.onPress?.(index);\n return;\n }\n if (o.onLongPress) {\n s.long = setTimeout(() => {\n if (swipes && swipes.stamp(index) !== s.stamp) return;\n s.longFired = true;\n // A long press also ends a pending first press of a double press.\n clearTimeout(s.double);\n s.double = undefined;\n latest.current.onLongPress?.(index);\n }, o.longPressMs);\n }\n });\n\n const offUp = deck.on(`${kind}Up`, (index) => {\n // A release without a press seen here (e.g. the Back button that led to this page).\n if (!held.delete(index)) return;\n const s = get(index);\n clearTimeout(s.long);\n if (s.immediate || s.longFired) return;\n if (!swipes?.active) return released(index, s);\n // Wait out the swipe window: the finger may be on its way to another sensor.\n const wait = Math.max(0, SWIPE_WINDOW_MS - (performance.now() - s.downAt));\n s.deferred = setTimeout(() => {\n if (swipes.stamp(index) === s.stamp) released(index, s);\n }, wait);\n });\n\n function released(index: number, s: ReturnType<typeof get>) {\n const o = latest.current;\n if (!o.onDoublePress) {\n o.onPress?.(index);\n } else if (s.double !== undefined) {\n clearTimeout(s.double);\n s.double = undefined;\n o.onDoublePress(index);\n } else {\n s.double = setTimeout(() => {\n s.double = undefined;\n latest.current.onPress?.(index);\n }, o.doublePressMs);\n }\n }\n\n return () => {\n offDown();\n offUp();\n for (const s of state.values()) {\n clearTimeout(s.long);\n clearTimeout(s.double);\n clearTimeout(s.deferred);\n }\n };\n }, [deck, kind, target, latest]);\n}\n\n/**\n * A key press, with optional long-press and double-press gestures.\n *\n * With no gestures, `onPress` fires the instant the key goes down (like Elgato's own software).\n * If `onLongPress` or `onDoublePress` is given, `onPress` waits for the release (and, with\n * `onDoublePress`, for the double-press window) so the gestures can be told apart.\n */\nexport function useKeyPress(\n onPress: ((key: number) => void) | undefined,\n options: KeyPressOptions = {},\n): void {\n usePress(\"key\", onPress, options, options.key);\n}\n\n/** A touch-sensor press, with the same gestures and timing rules as {@link useKeyPress}. */\nexport function useSensorPress(\n onPress: ((sensor: number) => void) | undefined,\n options: SensorPressOptions = {},\n): void {\n usePress(\"sensor\", onPress, options, options.sensor);\n}\n\nexport interface KeyRepeatOptions {\n key?: number;\n /** Wait before repeating starts (default 400 ms). */\n delayMs?: number;\n /** Time between repeats (default 100 ms). */\n intervalMs?: number;\n}\n\nfunction useRepeat(\n kind: Kind,\n handler: (index: number) => void,\n explicit: number | undefined,\n options: { delayMs?: number; intervalMs?: number },\n): void {\n const deck = useDeck();\n const target = useTarget(kind, explicit);\n const latest = useLatest({ handler, ...options });\n\n useEffect(() => {\n const swipes = kind === \"sensor\" ? swipeTracker(deck) : undefined;\n let first: ReturnType<typeof setTimeout> | undefined;\n let delay: ReturnType<typeof setTimeout> | undefined;\n let repeat: ReturnType<typeof setInterval> | undefined;\n const stop = () => {\n clearTimeout(delay);\n clearInterval(repeat);\n };\n const offDown = deck.on(`${kind}Down`, (index) => {\n if (target !== undefined && index !== target) return;\n if (swipes?.completes(index)) return;\n stop();\n clearTimeout(first);\n const stamp = swipes?.stamp(index);\n const swiped = () => swipes !== undefined && swipes.stamp(index) !== stamp;\n const run = () => {\n if (!swiped()) latest.current.handler(index);\n };\n // While swipes are watched, the first run waits to be told apart from one.\n if (swipes?.active) first = setTimeout(run, SWIPE_WINDOW_MS);\n else run();\n const wait = latest.current.delayMs ?? 400;\n delay = setTimeout(\n () => {\n repeat = setInterval(run, latest.current.intervalMs ?? 100);\n },\n swipes?.active ? Math.max(wait, SWIPE_WINDOW_MS) : wait,\n );\n });\n const offUp = deck.on(`${kind}Up`, (index) => {\n if (target === undefined || index === target) stop();\n });\n return () => {\n offDown();\n offUp();\n stop();\n clearTimeout(first);\n };\n }, [deck, kind, target, latest]);\n}\n\n/** Calls `handler` on key down, then again every `intervalMs` while held (volume, scrolling...). */\nexport function useKeyRepeat(handler: (key: number) => void, options: KeyRepeatOptions = {}): void {\n useRepeat(\"key\", handler, options.key, options);\n}\n\nexport interface SensorRepeatOptions {\n sensor?: number;\n delayMs?: number;\n intervalMs?: number;\n}\n\n/** {@link useKeyRepeat} for a touch sensor. */\nexport function useSensorRepeat(\n handler: (sensor: number) => void,\n options: SensorRepeatOptions = {},\n): void {\n useRepeat(\"sensor\", handler, options.sensor, options);\n}\n\n/**\n * Calls `handler` when a finger swipes from one touch sensor to another. While mounted, sensor\n * presses wait briefly for the release so swiping does not press them. `undefined` listens for\n * nothing.\n */\nexport function useSwipe(handler: ((direction: SwipeDirection) => void) | undefined): void {\n const deck = useDeck();\n const latest = useLatest(handler);\n const on = handler !== undefined;\n useEffect(() => {\n if (!on) return;\n return swipeTracker(deck).listen((direction) => latest.current?.(direction));\n }, [deck, on, latest]);\n}\n\n// -- Touch sensors ------------------------------------------------------------\n\n/** Runs `handler(sensor)` when a touch sensor is touched. `sensor` defaults to this slot's. */\nexport function useSensorDown(handler: (sensor: number) => void, sensor?: number): void {\n useInput(\"sensor\", \"Down\", handler, sensor);\n}\n\n/** Runs `handler(sensor)` when a touch sensor is released. */\nexport function useSensorUp(handler: (sensor: number) => void, sensor?: number): void {\n useInput(\"sensor\", \"Up\", handler, sensor);\n}\n\n/** `true` while the sensor is touched. `sensor` defaults to this component's sensor slot. */\nexport function useSensorPressed(sensor?: number): boolean {\n return usePressed(\"sensor\", sensor);\n}\n\n// -- Time ---------------------------------------------------------------------\n\n/** Calls `callback` every `ms` milliseconds. Pass `null` to pause. */\nexport function useInterval(callback: () => void, ms: number | null): void {\n const latest = useLatest(callback);\n useEffect(() => {\n if (ms === null) return;\n const id = setInterval(() => latest.current(), ms);\n return () => clearInterval(id);\n }, [ms, latest]);\n}\n\n/** The current time, refreshed every `ms` (default 1000). */\nexport function useNow(ms = 1000): Date {\n const [now, setNow] = useState(() => new Date());\n useInterval(() => setNow(new Date()), ms);\n return now;\n}\n\n// -- Navigation ---------------------------------------------------------------\n\nexport interface Navigation extends NavState {\n /** `true` when there is a page to go back to. */\n readonly canGoBack: boolean;\n /** `true` when `forward()` has a page to return to (after going back). */\n readonly canGoForward: boolean;\n push(page: string): void;\n replace(page: string): void;\n back(): boolean;\n forward(): boolean;\n /** Go to the page defined after this one; `wrap` goes round from the last to the first. */\n next(wrap?: boolean): boolean;\n /** Go to the page defined before this one (page order, not history). */\n previous(wrap?: boolean): boolean;\n home(): void;\n /** All pages, in the order they were defined. */\n readonly pages: readonly string[];\n /** The pages `next()` and `previous()` step through. */\n readonly sequence: readonly string[];\n}\n\n/** The app's current page and functions to change it. */\nexport function useNavigation(): Navigation {\n const nav = useContext(NavigatorContext);\n if (!nav) throw new Error(\"useNavigation() must be used inside a component mounted by sdeck/app\");\n const state = useSyncExternalStore(nav.subscribe, nav.getSnapshot);\n return {\n ...state,\n canGoBack: state.stack.length > 1,\n canGoForward: state.forwardStack.length > 0,\n push: nav.push,\n replace: nav.replace,\n back: nav.back,\n forward: nav.forward,\n next: nav.next,\n previous: nav.previous,\n pages: nav.pages,\n sequence: nav.sequence,\n home: nav.home,\n };\n}\n\n/** Name of the page currently shown. */\nexport function usePage(): string {\n return useNavigation().page;\n}\n",
11
+ "/**\n * Swipes across the touch sensors: touching one strip and then another within a short window. The\n * Neo has one sensor on each side of the window, so a finger sliding from one to the other is two\n * touches in quick succession.\n *\n * While something listens for swipes, sensor presses wait for the release and the swipe window,\n * so a swipe does not also press the sensors it crosses.\n */\nimport type { StreamDeck } from \"@sdeck/core\";\n\n/** Which way the finger moved: `right` goes from a lower sensor index to a higher one. */\nexport type SwipeDirection = \"left\" | \"right\";\n\n/** The longest time between touching the first sensor and the second (ms). */\nexport const SWIPE_WINDOW_MS = 400;\n\nexport class SwipeTracker {\n readonly #handlers = new Set<(direction: SwipeDirection) => void>();\n readonly #stamps = new Map<number, number>();\n /** Sensors whose current touch is the end of a swipe. */\n readonly #completing = new Set<number>();\n #first: { index: number; at: number } | undefined;\n\n constructor(deck: StreamDeck) {\n deck.on(\"sensorDown\", (index) => this.#down(index));\n }\n\n /** Whether anything listens (presses must then wait to be told apart from swipes). */\n get active(): boolean {\n return this.#handlers.size > 0;\n }\n\n /** Changes every time `index` takes part in a swipe. */\n stamp(index: number): number {\n return this.#stamps.get(index) ?? 0;\n }\n\n /** Whether the current touch of `index` finished a swipe (so it is not a press). */\n completes(index: number): boolean {\n return this.#completing.has(index);\n }\n\n listen(handler: (direction: SwipeDirection) => void): () => void {\n this.#handlers.add(handler);\n return () => void this.#handlers.delete(handler);\n }\n\n #down(index: number): void {\n this.#completing.delete(index);\n const now = performance.now();\n const first = this.#first;\n if (!this.active || !first || first.index === index || now - first.at > SWIPE_WINDOW_MS) {\n this.#first = { index, at: now };\n return;\n }\n this.#first = undefined;\n this.#completing.add(index);\n for (const sensor of [first.index, index]) this.#stamps.set(sensor, this.stamp(sensor) + 1);\n const direction: SwipeDirection = index > first.index ? \"right\" : \"left\";\n for (const handler of [...this.#handlers]) handler(direction);\n }\n}\n\nconst trackers = new WeakMap<StreamDeck, SwipeTracker>();\n\n/**\n * The deck's swipe tracker. Callers that subscribe to sensor events must ask for it first, so it\n * hears each touch before they do.\n */\nexport function swipeTracker(deck: StreamDeck): SwipeTracker {\n let tracker = trackers.get(deck);\n if (!tracker) {\n tracker = new SwipeTracker(deck);\n trackers.set(deck, tracker);\n }\n return tracker;\n}\n",
12
+ "/**\n * Live values published by plugins, addressed `namespace.id` (`system.cpu`, `audio.master`).\n * Providers are started on demand: a polled value is only read while something watches it, and\n * stopped shortly after the last watcher leaves (so switching pages does not restart them).\n */\n\nexport type StateValueType = \"number\" | \"string\" | \"boolean\" | \"json\";\n\nexport interface StateMeta {\n /** `namespace.id`. */\n key: string;\n name: string;\n type: StateValueType;\n unit?: string;\n description?: string;\n}\n\nexport interface StateSource {\n meta: StateMeta;\n /** Read every `everyMs` while watched. */\n poll?: { everyMs: number; read: () => unknown | Promise<unknown> };\n /** Push updates while watched; returns a stop function. */\n start?: (set: (value: unknown) => void) => (() => void) | undefined;\n}\n\ninterface Entry {\n source: StateSource | undefined;\n value: unknown;\n /** When the value was last set (ms epoch), 0 = never. */\n at: number;\n watchers: number;\n stop: (() => void) | undefined;\n linger: ReturnType<typeof setTimeout> | undefined;\n}\n\n/** Equality for JSON-like values (polls return fresh objects every time). */\nexport function sameValue(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const ka = Object.keys(a);\n const kb = Object.keys(b);\n if (ka.length !== kb.length) return false;\n return ka.every(\n (k) =>\n Object.hasOwn(b, k) &&\n sameValue((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n}\n\nexport interface StateStoreOptions {\n /** How long a provider keeps running after its last watcher leaves. */\n lingerMs?: number;\n onError?: (key: string, error: unknown) => void;\n}\n\nexport class StateStore {\n readonly #entries = new Map<string, Entry>();\n /** namespace → id → value, rebuilt per namespace on change (so it can be handed out as scope). */\n #tree: Record<string, Record<string, unknown>> = {};\n readonly #listeners = new Map<string, Set<() => void>>();\n readonly #anyListeners = new Set<(key: string) => void>();\n readonly #lingerMs: number;\n readonly #onError: StateStoreOptions[\"onError\"];\n\n constructor(options: StateStoreOptions = {}) {\n this.#lingerMs = options.lingerMs ?? 3000;\n this.#onError = options.onError;\n }\n\n #entry(key: string): Entry {\n let e = this.#entries.get(key);\n if (!e) {\n e = {\n source: undefined,\n value: undefined,\n at: 0,\n watchers: 0,\n stop: undefined,\n linger: undefined,\n };\n this.#entries.set(key, e);\n }\n return e;\n }\n\n /** Registers a provider. Returns a function that removes it (and its value). */\n register(source: StateSource): () => void {\n const { key } = source.meta;\n if (!/^[\\w-]+\\.[\\w.-]+$/.test(key)) throw new TypeError(`bad state key \"${key}\"`);\n const e = this.#entry(key);\n this.#halt(e);\n e.source = source;\n if (e.watchers > 0) this.#run(key, e);\n return () => {\n if (e.source !== source) return;\n this.#halt(e);\n e.source = undefined;\n this.set(key, undefined);\n if (e.watchers === 0) this.#entries.delete(key);\n };\n }\n\n /** Metadata of every registered value (for editors). */\n list(): StateMeta[] {\n return [...this.#entries.values()].flatMap((e) => (e.source ? [e.source.meta] : []));\n }\n\n /** Sets a value directly (plugins pushing state; also what providers call). */\n set(key: string, value: unknown): void {\n const e = this.#entry(key);\n e.at = Date.now();\n if (sameValue(e.value, value)) return;\n e.value = value;\n const dot = key.indexOf(\".\");\n const ns = key.slice(0, dot);\n const id = key.slice(dot + 1);\n const next = { ...this.#tree[ns] };\n if (value === undefined) delete next[id];\n else next[id] = value;\n this.#tree = { ...this.#tree, [ns]: next };\n this.#notify(key, ns);\n }\n\n get(key: string): unknown {\n return this.#entries.get(key)?.value;\n }\n\n /** `{ system: { cpu: 12 }, … }` — the current values, for expression scopes. Immutable. */\n tree(): Readonly<Record<string, Readonly<Record<string, unknown>>>> {\n return this.#tree;\n }\n\n /**\n * Watches the state behind expression `paths` (`system.cpu`, `system` = the whole namespace).\n * Starts providers as needed. Returns a function that stops watching.\n */\n watch(paths: Iterable<string>, listener: () => void): () => void {\n const keys = new Set<string>();\n for (const path of paths) {\n const parts = path.split(\".\");\n if (parts.length >= 2) keys.add(`${parts[0]}.${parts[1]}`);\n else if (parts[0]) {\n // A whole namespace: watch what is registered under it now.\n for (const key of this.#entries.keys()) if (key.startsWith(`${parts[0]}.`)) keys.add(key);\n keys.add(`${parts[0]}.*`);\n }\n }\n for (const key of keys) {\n let set = this.#listeners.get(key);\n if (!set) {\n set = new Set();\n this.#listeners.set(key, set);\n }\n set.add(listener);\n if (!key.endsWith(\".*\")) this.#acquire(key);\n }\n let done = false;\n return () => {\n if (done) return;\n done = true;\n for (const key of keys) {\n this.#listeners.get(key)?.delete(listener);\n if (!key.endsWith(\".*\")) this.#release(key);\n }\n };\n }\n\n /** Called with the key of every change. */\n onChange(listener: (key: string) => void): () => void {\n this.#anyListeners.add(listener);\n return () => void this.#anyListeners.delete(listener);\n }\n\n /**\n * The current value of `key`, reading a polled provider once if nothing keeps it fresh (for\n * workflow conditions that are evaluated once).\n */\n async read(key: string): Promise<unknown> {\n const e = this.#entries.get(key);\n if (!e?.source?.poll || (e.watchers > 0 && e.at > 0)) return e?.value;\n try {\n this.set(key, await e.source.poll.read());\n } catch (error) {\n this.#onError?.(key, error);\n }\n return this.get(key);\n }\n\n /**\n * The value as it is now, for showing in an editor: a watched value as it stands, else one\n * read just for this. Nothing is stored, and a value that cannot be read is `undefined`.\n */\n async sample(key: string): Promise<unknown> {\n const e = this.#entries.get(key);\n if (!e?.source?.poll || (e.watchers > 0 && e.at > 0)) return e?.value;\n try {\n return await e.source.poll.read();\n } catch {\n return undefined;\n }\n }\n\n /** Refreshes every key behind `paths` that is not already being kept fresh. */\n async refresh(paths: Iterable<string>): Promise<void> {\n const keys = new Set<string>();\n for (const path of paths) {\n const [ns, id] = path.split(\".\");\n if (ns && id) keys.add(`${ns}.${id}`);\n else if (ns)\n for (const key of this.#entries.keys()) if (key.startsWith(`${ns}.`)) keys.add(key);\n }\n await Promise.all([...keys].map((k) => this.read(k)));\n }\n\n /** Stops every provider. */\n close(): void {\n for (const e of this.#entries.values()) this.#halt(e);\n this.#entries.clear();\n this.#listeners.clear();\n }\n\n #notify(key: string, ns: string) {\n for (const l of [...(this.#listeners.get(key) ?? [])]) l();\n for (const l of [...(this.#listeners.get(`${ns}.*`) ?? [])]) {\n if (!this.#listeners.get(key)?.has(l)) l();\n }\n for (const l of [...this.#anyListeners]) l(key);\n }\n\n #acquire(key: string) {\n const e = this.#entry(key);\n e.watchers++;\n if (e.linger) {\n clearTimeout(e.linger);\n e.linger = undefined;\n }\n if (e.watchers === 1 && !e.stop) this.#run(key, e);\n }\n\n #release(key: string) {\n const e = this.#entries.get(key);\n if (!e) return;\n e.watchers = Math.max(0, e.watchers - 1);\n if (e.watchers > 0 || !e.stop) return;\n e.linger = setTimeout(() => {\n e.linger = undefined;\n if (e.watchers === 0) this.#halt(e);\n }, this.#lingerMs);\n }\n\n #run(key: string, e: Entry) {\n const source = e.source;\n if (!source) return;\n const set = (value: unknown) => {\n if (e.source === source) this.set(key, value);\n };\n if (source.start) {\n try {\n e.stop = source.start(set) ?? (() => {});\n } catch (error) {\n this.#onError?.(key, error);\n e.stop = () => {};\n }\n return;\n }\n if (source.poll) {\n const { everyMs, read } = source.poll;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const tick = async () => {\n try {\n const value = await read();\n if (!stopped) set(value);\n } catch (error) {\n if (!stopped) this.#onError?.(key, error);\n }\n if (!stopped) timer = setTimeout(tick, Math.max(50, everyMs));\n };\n void tick();\n e.stop = () => {\n stopped = true;\n clearTimeout(timer);\n };\n }\n }\n\n #halt(e: Entry) {\n if (e.linger) clearTimeout(e.linger);\n e.linger = undefined;\n const stop = e.stop;\n e.stop = undefined;\n try {\n stop?.();\n } catch {\n // A provider failing to stop must not stop the others.\n }\n }\n}\n",
13
+ "/** Short ways to write the layers of a look, for plugins and templates. */\nimport type { Frame, ImageLayer, Look, TextLayer, VerticalPosition } from \"./types.ts\";\n\nexport interface IconOptions {\n color?: string;\n /** % of the slot's shorter side (default 52). */\n size?: number;\n position?: VerticalPosition;\n visible?: string;\n row?: string;\n /** Places it exactly instead, in percent of the slot. */\n frame?: Frame;\n}\n\n/**\n * An icon: `lucide/play` or `si/SiDiscord` (or any image source, which is kept as it is).\n */\nexport function iconLayer(id: string, icon: string, options: IconOptions = {}): ImageLayer {\n const { color, size = 52, position = \"middle\", visible, row, frame } = options;\n const src = /^[a-z0-9]+\\/[A-Za-z0-9-]+$/.test(icon) ? `icon:${icon}` : icon;\n return {\n id,\n type: \"image\",\n src,\n size,\n position,\n ...(color && { color }),\n ...(visible && { visible }),\n ...(row && { row }),\n ...(frame && { frame }),\n };\n}\n\nexport interface TextOptions {\n color?: string;\n /** px (default 14). */\n size?: number;\n weight?: 400 | 700;\n position?: VerticalPosition;\n visible?: string;\n row?: string;\n frame?: Frame;\n}\n\n/**\n * A key that is an icon, with a short caption under it only when there is one. The look most\n * actions start with.\n */\nexport function iconLook(options: {\n icon: string;\n background: string;\n caption?: string;\n color?: string;\n}): Look {\n const { icon, background, caption = \"\", color = \"#ffffff\" } = options;\n return {\n background,\n layers: [\n iconLayer(\"icon\", icon, {\n color,\n size: caption ? 46 : 58,\n position: caption ? \"top\" : \"middle\",\n }),\n ...(caption\n ? [textLayer(\"label\", caption, { color, size: 13, position: \"bottom\" as const })]\n : []),\n ],\n };\n}\n\nexport function textLayer(id: string, text: string, options: TextOptions = {}): TextLayer {\n const { color = \"#ffffff\", size = 14, weight = 700, position = \"middle\" } = options;\n const { visible, row, frame } = options;\n return {\n id,\n type: \"text\",\n text,\n color,\n size,\n weight,\n position,\n ...(visible && { visible }),\n ...(row && { row }),\n ...(frame && { frame }),\n };\n}\n",
14
+ "/**\n * Live state for action components. The host provides a `HostBridge` around every slot; these\n * hooks subscribe to exactly what they read and re-render when it changes.\n */\nimport { compile, type Scope, sameValue, template } from \"@sdeck/engine\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\nexport interface HostBridge {\n /**\n * Watches state keys and variables behind expression paths (`system.cpu`, `vars.mode`).\n * Starts providers as needed. Returns a function that stops watching.\n */\n watch(paths: readonly string[], listener: () => void): () => void;\n /** The current expression scope (state namespaces, `vars`, `self`…). */\n scope(): Scope;\n /** Runs a plugin action as a workflow step would (recorded in the history). */\n run(plugin: string, action: string, settings?: Record<string, unknown>): Promise<unknown>;\n /** Sets a global variable. */\n setVariable(name: string, value: unknown): void;\n /**\n * What to draw for an image source (an icon reference, a URL or a `data:` URI), or\n * `undefined` while it loads. `color` applies to icons.\n */\n image(src: string, color?: string): string | undefined;\n /** Called when an image finishes loading. */\n watchImages(listener: () => void): () => void;\n}\n\nexport const HostBridgeContext = createContext<HostBridge | undefined>(undefined);\n\nfunction useBridge(): HostBridge {\n const bridge = useContext(HostBridgeContext);\n if (!bridge)\n throw new Error(\"sdeck live-state hooks must be used inside an action drawn by the host\");\n return bridge;\n}\n\n/** Re-renders every second while `on` (for `now()`/`time()` in templates). */\nfunction useClock(on: boolean): number {\n const [tick, setTick] = useState(0);\n useEffect(() => {\n if (!on) return;\n const timer = setInterval(() => setTick((t) => t + 1), 1000);\n return () => clearInterval(timer);\n }, [on]);\n return tick;\n}\n\nfunction useWatched<T>(paths: readonly string[], read: () => T): T {\n const bridge = useBridge();\n const key = paths.join(\"\\n\");\n // biome-ignore lint/correctness/useExhaustiveDependencies: `key` stands for `paths`.\n const subscribe = useCallback(\n (listener: () => void) => bridge.watch(paths, listener),\n [bridge, key],\n );\n // Expressions can build fresh arrays/objects; keep the previous one while equal so React does\n // not see a new snapshot on every read.\n const last = useRef<{ value: T } | undefined>(undefined);\n const snapshot = () => {\n const value = read();\n if (last.current && sameValue(last.current.value, value)) return last.current.value;\n last.current = { value };\n return value;\n };\n return useSyncExternalStore(subscribe, snapshot);\n}\n\n/** The value of an expression (`system.cpu > 80`, `vars.mode`), kept up to date. */\nexport function useExpression(source: string): unknown {\n const bridge = useBridge();\n const expression = useMemo(() => compile(source), [source]);\n useClock(expression.timeDependent);\n return useWatched(expression.paths, () => expression.evaluate(bridge.scope()));\n}\n\n/** A `{{template}}` rendered to text, kept up to date: `useTemplate(\"CPU {{system.cpu}}%\")`. */\nexport function useTemplate(source: string): string {\n const bridge = useBridge();\n const compiled = useMemo(() => template(source), [source]);\n useClock(compiled.timeDependent);\n return useWatched(compiled.paths, () => compiled.render(bridge.scope()));\n}\n\n/** A live state value by key (`system.cpu`). */\nexport function useHostState(key: string): unknown {\n const bridge = useBridge();\n const paths = useMemo(() => [key], [key]);\n return useWatched(paths, () => {\n const dot = key.indexOf(\".\");\n const ns = bridge.scope()[key.slice(0, dot)] as Record<string, unknown> | undefined;\n return dot > 0 ? ns?.[key.slice(dot + 1)] : undefined;\n });\n}\n\n/** A global variable and a setter for it. */\nexport function useVariable(name: string): [unknown, (value: unknown) => void] {\n const bridge = useBridge();\n const paths = useMemo(() => [`vars.${name}`], [name]);\n const value = useWatched(paths, () => (bridge.scope().vars as Record<string, unknown>)[name]);\n const set = useCallback((v: unknown) => bridge.setVariable(name, v), [bridge, name]);\n return [value, set];\n}\n\n/** Runs another plugin's action from a component (`run(\"@sdeck/plugin-system\", \"open\", {...})`). */\nexport function useRunAction(): HostBridge[\"run\"] {\n return useBridge().run;\n}\n\n/**\n * An image ready to draw with `<img src>`: an icon (`icon:lucide/play`, `icon:si/SiDiscord`) in\n * `color`, a URL or a `data:` URI. `undefined` until it has loaded.\n */\nexport function useImage(src: string, color?: string): string | undefined {\n const bridge = useBridge();\n return useSyncExternalStore(bridge.watchImages, () =>\n src ? bridge.image(src, color) : undefined,\n );\n}\n",
15
+ "/**\n * Action settings are described by a plain-data schema. The host turns it into a form in the\n * configuration UI, and `resolveSettings` turns whatever is stored into well-typed values.\n */\n\ntype Primitive = string | number | boolean;\n\ninterface FieldBase {\n /** Label shown in the configuration UI. */\n label: string;\n /** Help text under the field. */\n description?: string;\n /**\n * Shown only while other fields have these values: `{ to: \"page\" }` or\n * `{ mode: [\"a\", \"b\"] }`. Hidden fields keep their value.\n */\n visibleIf?: Readonly<Record<string, Primitive | readonly Primitive[]>>;\n}\n\nexport interface TextField extends FieldBase {\n type: \"text\";\n default?: string;\n placeholder?: string;\n multiline?: boolean;\n /** Suggestions from one of the plugin's `optionSources` (any text is still allowed). */\n source?: string;\n /** Other fields the suggestions depend on, passed to the source. */\n dependsOn?: readonly string[];\n}\n\nexport interface NumberField extends FieldBase {\n type: \"number\";\n default?: number;\n min?: number;\n max?: number;\n step?: number;\n}\n\nexport interface BooleanField extends FieldBase {\n type: \"boolean\";\n default?: boolean;\n}\n\n/**\n * A password or token, only for a plugin's own settings. It is kept in the host's secrets file\n * (never in the config, so it is safe to share or commit) and the UI never reads it back.\n */\nexport interface SecretField extends FieldBase {\n type: \"secret\";\n default?: string;\n placeholder?: string;\n}\n\n/** A `#rrggbb` colour. */\nexport interface ColorField extends FieldBase {\n type: \"color\";\n default?: string;\n}\n\nexport interface SelectOption {\n value: string;\n label: string;\n}\n\nexport interface SelectField extends FieldBase {\n type: \"select\";\n /** Fixed options. With `source`, shown before the fetched ones. */\n options: readonly SelectOption[];\n /**\n * Options fetched from one of the plugin's `optionSources` when the form opens (OBS\n * scenes, audio devices). Any stored string is then kept, since the list can change.\n */\n source?: string;\n /**\n * Other fields the fetched options depend on, passed to the source. The form asks for them\n * first, and clears this field when one of them changes.\n */\n dependsOn?: readonly string[];\n default?: string;\n}\n\n/** The name of one of the user's pages (the UI shows a page picker). */\nexport interface PageField extends FieldBase {\n type: \"page\";\n default?: string;\n}\n\n/** An image: an `http(s)` URL or a `data:` URI (the UI accepts a URL or a file). */\nexport interface ImageField extends FieldBase {\n type: \"image\";\n default?: string;\n}\n\nexport type SettingField =\n | TextField\n | NumberField\n | BooleanField\n | ColorField\n | SelectField\n | PageField\n | ImageField\n | SecretField;\n\nexport type SettingsSchema = Readonly<Record<string, SettingField>>;\n\n/** The value type of one field. */\nexport type FieldValue<F extends SettingField> = F extends NumberField\n ? number\n : F extends BooleanField\n ? boolean\n : F extends SelectField\n ? F extends { source: string }\n ? string\n : F[\"options\"][number][\"value\"]\n : string;\n\n/** The settings object an action receives for a schema. */\nexport type InferSettings<S extends SettingsSchema> = {\n -readonly [K in keyof S]: FieldValue<S[K]>;\n};\n\nconst HEX = /^#[0-9a-f]{6}$/i;\n\n/** The value a field takes when nothing (valid) is stored. */\nexport function defaultValue(field: SettingField): string | number | boolean {\n switch (field.type) {\n case \"number\":\n return field.default ?? field.min ?? 0;\n case \"boolean\":\n return field.default ?? false;\n case \"color\":\n return field.default ?? \"#000000\";\n case \"select\":\n return field.default ?? field.options[0]?.value ?? \"\";\n default:\n return field.default ?? \"\";\n }\n}\n\nfunction coerce(field: SettingField, value: unknown): string | number | boolean {\n switch (field.type) {\n case \"number\": {\n const n = typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : value;\n if (typeof n !== \"number\" || !Number.isFinite(n)) return defaultValue(field);\n return Math.min(field.max ?? Infinity, Math.max(field.min ?? -Infinity, n));\n }\n case \"boolean\":\n return typeof value === \"boolean\" ? value : defaultValue(field);\n case \"color\":\n return typeof value === \"string\" && HEX.test(value)\n ? value.toLowerCase()\n : defaultValue(field);\n case \"select\":\n if (typeof value !== \"string\") return defaultValue(field);\n if (field.source !== undefined) return value;\n return field.options.some((o) => o.value === value) ? value : defaultValue(field);\n default:\n return typeof value === \"string\" ? value : defaultValue(field);\n }\n}\n\n/**\n * Stored settings, made safe: every field of `schema` is present and of the right type (invalid\n * or missing values get the default, numbers are clamped), and unknown keys are dropped.\n */\nexport function resolveSettings<S extends SettingsSchema>(\n schema: S,\n stored: Readonly<Record<string, unknown>> | undefined,\n): InferSettings<S> {\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(schema)) out[key] = coerce(field, stored?.[key]);\n return out as InferSettings<S>;\n}\n\n/** Whether `field` is shown for these (resolved) settings. */\nexport function isFieldVisible(\n field: SettingField,\n settings: Readonly<Record<string, unknown>>,\n): boolean {\n if (!field.visibleIf) return true;\n return Object.entries(field.visibleIf).every(([key, want]) => {\n const value = settings[key];\n return Array.isArray(want) ? want.includes(value as Primitive) : value === want;\n });\n}\n\n/**\n * Problems with a schema (empty when it is fine). Used when a plugin is loaded. `sources` are\n * the plugin's option sources, checked against fields that name one.\n */\nexport function checkSchema(\n schema: SettingsSchema,\n sources: Readonly<Record<string, unknown>> = {},\n): string[] {\n const problems: string[] = [];\n const types = new Set([\n \"text\",\n \"number\",\n \"boolean\",\n \"color\",\n \"select\",\n \"page\",\n \"image\",\n \"secret\",\n ]);\n for (const [key, field] of Object.entries(schema)) {\n if (!field || typeof field !== \"object\" || !types.has(field.type)) {\n problems.push(`setting \"${key}\" has an unknown type`);\n continue;\n }\n if (typeof field.label !== \"string\") problems.push(`setting \"${key}\" needs a label`);\n const source = \"source\" in field ? field.source : undefined;\n if (source !== undefined && !(source in sources)) {\n problems.push(`setting \"${key}\" uses unknown option source \"${source}\"`);\n }\n if (\n field.type === \"select\" &&\n (!Array.isArray(field.options) || (field.options.length === 0 && source === undefined))\n ) {\n problems.push(`setting \"${key}\" needs at least one option or a source`);\n }\n for (const other of (\"dependsOn\" in field && field.dependsOn) || []) {\n if (!(other in schema)) problems.push(`setting \"${key}\" depends on unknown \"${other}\"`);\n }\n if (field.visibleIf !== undefined) {\n for (const other of Object.keys(field.visibleIf)) {\n if (!(other in schema)) problems.push(`setting \"${key}\" depends on unknown \"${other}\"`);\n }\n }\n }\n return problems;\n}\n",
16
+ "import type { SlotInfo } from \"@sdeck/app\";\nimport type { ExecSource, StateValueType } from \"@sdeck/engine\";\nimport type { Look, NavigateTarget } from \"@sdeck/schema\";\nimport type { ComponentType } from \"react\";\nimport {\n checkSchema,\n type InferSettings,\n type SelectOption,\n type SettingsSchema,\n} from \"./settings.ts\";\n\n/** Bumped when the plugin contract changes incompatibly. Hosts refuse plugins built for another. */\nexport const PLUGIN_API_VERSION = 2;\n\n/** Where an action can be placed. */\nexport type SlotKind = \"key\" | \"sensor\" | \"window\";\n\n/**\n * What a plugin declares it does. Shown to the user before enabling it. Plugins run in the host\n * process, so this is information, not a sandbox.\n */\nexport type Permission =\n | \"shell\"\n | \"process\"\n | \"filesystem\"\n | \"network\"\n | \"input\"\n | \"audio\"\n | \"clipboard\";\n\nexport const PERMISSIONS: readonly Permission[] = [\n \"shell\",\n \"process\",\n \"filesystem\",\n \"network\",\n \"input\",\n \"audio\",\n \"clipboard\",\n];\n\n/** Given to a plugin's `activate`, its actions, state providers and triggers. */\nexport interface PluginContext {\n readonly pluginId: string;\n /** Prefix of this plugin's state keys and events (`system` → `system.cpu`). */\n readonly namespace: string;\n /** A writable directory for this plugin's own files (created on first use). */\n readonly dataDir: string;\n /** Logs to the host, tagged with the plugin id. */\n log(...args: unknown[]): void;\n /** The plugin's own settings (secrets included), resolved against `PluginDef.settings`. */\n settings(): Record<string, unknown>;\n /** Called after the plugin's settings change; returns a function that stops. */\n onSettings(listener: () => void): () => void;\n /** Values the plugin keeps private between runs (tokens it obtained, for example). */\n readonly secrets: {\n get(key: string): string | undefined;\n set(key: string, value: string | undefined): Promise<void>;\n };\n /** Shown with the plugin in the UI (`Connected`, `Sign in to continue`). `undefined` clears. */\n status(text: string | undefined, level?: StatusLevel): void;\n /** Live state: `set` publishes `<namespace>.<id>`, `get` reads any key (`system.cpu`). */\n readonly state: {\n set(id: string, value: unknown): void;\n get(key: string): unknown;\n };\n /** Emits `<namespace>:<event>` on the event bus (workflows can trigger on it). */\n emit(event: string, payload?: unknown): void;\n /** Global user variables. */\n readonly vars: {\n get(name: string): unknown;\n set(name: string, value: unknown): void;\n };\n}\n\n/** How a plugin's status reads: fine, needing attention, or failing. */\nexport type StatusLevel = \"ok\" | \"info\" | \"error\";\n\n/** Something the user can run from the plugin's page (sign in, reconnect). */\nexport interface PluginCommand {\n /** Unique within the plugin. */\n id: string;\n name: string;\n description?: string;\n /** What it returns, if a string, is opened in the user's browser. Throw to fail. */\n run(context: PluginContext): unknown | Promise<unknown>;\n}\n\n/**\n * One step of setting a plugin up. Studio walks the user through the steps right after the plugin\n * is installed, and again from its \"Get started\" button.\n */\nexport interface OnboardingStep {\n /** Unique within the plugin's steps. */\n id: string;\n title: string;\n /**\n * What to do, in plain words. Blank lines start paragraphs; `**bold**`, `` `code` `` and\n * `[links](https://…)` work.\n */\n body?: string;\n /** The plugin's own settings this step asks for, by key (secrets too). */\n settings?: readonly string[];\n /** One of the plugin's commands, run from a button in this step (sign in, find devices). */\n command?: string;\n /** A web page to open, such as where to create an API key. */\n link?: { label: string; url: string };\n /**\n * Whether the step is done: a key is saved, the sign-in went through. Without it, a step that\n * asks for settings is done once they all have a value.\n */\n done?(context: PluginContext): boolean | Promise<boolean>;\n /** Not needed to use the plugin (Bluetooth lights need no cloud key). */\n optional?: boolean;\n}\n\n/** Keys a plugin offers as a page of their own at the end of onboarding. */\nexport interface StarterPage {\n /** The page's name (default: the plugin's). */\n name?: string;\n /** By key index: the action's id and settings. */\n keys: Readonly<Record<number, { action: string; settings?: Record<string, unknown> }>>;\n sensors?: Readonly<Record<number, { action: string; settings?: Record<string, unknown> }>>;\n window?: { action: string; settings?: Record<string, unknown> };\n}\n\n/** How a plugin is set up after it is installed. */\nexport interface Onboarding {\n /** A sentence or two shown before the steps. */\n intro?: string;\n steps: readonly OnboardingStep[];\n /**\n * The page of keys offered at the end. By default the plugin's first eight actions for keys;\n * `false` offers none.\n */\n starterPage?: StarterPage | false;\n}\n\n/** Props of an action's component. */\nexport interface ActionProps<S extends SettingsSchema = SettingsSchema> {\n /** This placement's settings, resolved against the schema (always complete and typed). */\n settings: InferSettings<S>;\n /** Saves changed settings for this placement (persisted and shown in the UI). */\n setSettings(patch: Partial<InferSettings<S>>): void;\n /** Where the action is drawn. */\n slot: SlotInfo;\n plugin: PluginContext;\n}\n\n/** Given to an action's `run`. */\nexport interface RunContext<S extends SettingsSchema = SettingsSchema> {\n /** Settings with `{{templates}}` already resolved, then checked against the schema. */\n settings: InferSettings<S>;\n plugin: PluginContext;\n /** What started the run (a key, a trigger, a workflow…). */\n source: ExecSource;\n /** Aborted when the execution is cancelled. Long work should stop. */\n signal: AbortSignal;\n /** The triggering event's payload, if any. */\n event: unknown;\n /** Controls of the deck the run started on (every deck, for triggers and workflows). */\n deck: DeckControls;\n}\n\n/** What a headless action can do to the decks. */\nexport interface DeckControls {\n /** Moves between pages, as a `navigate` workflow step does. Throws for an unknown page. */\n navigate(to: NavigateTarget, page?: string, options?: { wrap?: boolean }): void;\n /** The current brightness (0–100). */\n brightness(): number;\n /** Sets the brightness (0–100). */\n setBrightness(level: number): Promise<void>;\n}\n\n/**\n * What `run` gives back. `undo` reverts what the run did; it is recorded in the action history\n * and used by toggle buttons and the `undo` step.\n */\nexport interface RunOutcome {\n result?: unknown;\n undo?: () => unknown;\n /** Summary for the history, e.g. `Volume 30%`. */\n label?: string;\n}\n\nexport type RunResult = RunOutcome | undefined;\n\nexport interface ActionDef<S extends SettingsSchema = SettingsSchema> {\n /** Unique within the plugin, e.g. `\"clock\"`. */\n id: string;\n name: string;\n description?: string;\n /** Groups actions in the picker (default: the plugin's name). */\n category?: string;\n /**\n * Icon for the UI: a [lucide](https://lucide.dev/icons) icon name in kebab case (`\"timer\"`),\n * or an image URL / `data:` URI.\n */\n icon?: string;\n /** Slot kinds the action supports (default: keys only). */\n slots?: readonly SlotKind[];\n /** Settings shown in the UI, as a form. */\n settings?: S;\n /**\n * Does the work, without drawing anything: it can run from a key, a trigger or a workflow.\n * Throw to fail. An action needs `run`, `component`, or both.\n */\n // biome-ignore lint/suspicious/noConfusingVoidType: lets `run` simply not return anything.\n run?(context: RunContext<S>): RunResult | void | Promise<RunResult | void>;\n /**\n * Draws the action itself (it then handles its own input). It runs inside the deck's React\n * tree, so the `@sdeck/app` hooks and components work as in any app. Without it, the host\n * draws the button's look and runs `run` on press.\n */\n component?: ComponentType<ActionProps<S>>;\n /** The look a new button with this action starts with (default: its name on a dark key). */\n look?(settings: InferSettings<S>): Look;\n}\n\nexport type RunFn = (context: RunContext) => RunResult | undefined | Promise<RunResult | undefined>;\n\n/** An action with its settings type erased, as stored on a plugin. */\nexport interface Action {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly category?: string;\n readonly icon?: string;\n readonly slots: readonly SlotKind[];\n readonly settings: SettingsSchema;\n readonly run?: RunFn;\n readonly component?: ComponentType<ActionProps>;\n readonly look?: (settings: Record<string, unknown>) => Look;\n}\n\n/** A live value the plugin publishes as `<namespace>.<id>`. */\nexport interface StateDef {\n /** Letters, digits, `-`, `_` and `.` (`cpu`, `core.0`). */\n id: string;\n name: string;\n type: StateValueType;\n unit?: string;\n description?: string;\n /** Read every `everyMs` while something shows or waits on the value. */\n poll?: { everyMs: number; read(context: PluginContext): unknown | Promise<unknown> };\n /** Push updates while watched; return a stop function. */\n // biome-ignore lint/suspicious/noConfusingVoidType: lets `start` simply not return anything.\n start?(set: (value: unknown) => void, context: PluginContext): (() => void) | void;\n}\n\n/** Given to a trigger's `subscribe`. */\nexport interface TriggerContext<S extends SettingsSchema = SettingsSchema> {\n settings: InferSettings<S>;\n plugin: PluginContext;\n /** Starts the trigger's workflow; `event` becomes `event` in its expressions. */\n fire(event?: unknown): void;\n}\n\nexport interface TriggerDef<S extends SettingsSchema = SettingsSchema> {\n /** Unique within the plugin; the trigger type is `<plugin id>:<id>`. */\n id: string;\n name: string;\n description?: string;\n settings?: S;\n /** Starts watching; returns a function that stops. */\n // biome-ignore lint/suspicious/noConfusingVoidType: lets `subscribe` simply not return anything.\n subscribe(context: TriggerContext<S>): (() => void) | void;\n}\n\nexport interface Trigger {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly settings: SettingsSchema;\n readonly subscribe: (context: TriggerContext) => (() => void) | undefined;\n}\n\n/**\n * Fills fields that name it in `source` (OBS scenes, audio devices…). `settings` holds the\n * fields the asking field `dependsOn` (a server whose channels to list).\n */\nexport type OptionSource = (\n context: PluginContext,\n settings: Readonly<Record<string, unknown>>,\n) => SelectOption[] | Promise<SelectOption[]>;\n\n/** Undoes what `activate` did. */\nexport type Deactivate = () => void | Promise<void>;\n\nexport interface PluginDef {\n /** Unique id; for an installed plugin this must be its package name. */\n id: string;\n name: string;\n /** Semver version. */\n version: string;\n description?: string;\n author?: string;\n homepage?: string;\n /** State key and event prefix (default: derived from the id, `@sdeck/plugin-system` → `system`). */\n namespace?: string;\n actions: readonly Action[];\n state?: readonly StateDef[];\n triggers?: readonly Trigger[];\n optionSources?: Readonly<Record<string, OptionSource>>;\n permissions?: readonly Permission[];\n /** The plugin's own settings (a server address, a token), shown on its page. */\n settings?: SettingsSchema;\n /** Buttons on the plugin's page. */\n commands?: readonly PluginCommand[];\n /**\n * How to set the plugin up, step by step, shown after it is installed. Without it, Studio asks\n * for the plugin's settings and offers its commands in one step.\n */\n onboarding?: Onboarding;\n /** Runs when the plugin is enabled (and when the host starts). May return a cleanup. */\n // biome-ignore lint/suspicious/noConfusingVoidType: lets `activate` simply not return anything.\n activate?(context: PluginContext): void | Deactivate | Promise<void | Deactivate>;\n}\n\nconst ID = /^(@[a-z0-9][\\w.-]*\\/)?[a-z0-9][\\w.-]*$/;\nconst NAMESPACE = /^[a-z][\\w-]{0,31}$/;\nconst LOCAL_ID = /^[\\w.-]+$/;\n\n/** The namespace a plugin's state and events use. */\nexport function pluginNamespace(def: Pick<PluginDef, \"id\" | \"namespace\">): string {\n if (def.namespace) return def.namespace;\n const base = def.id\n .replace(/^@[^/]+\\//, \"\")\n .replace(/^sdeck-plugin-/, \"\")\n .replace(/^plugin-/, \"\")\n .toLowerCase()\n .replace(/[^\\w-]/g, \"-\");\n return /^[a-z]/.test(base) ? base.slice(0, 32) : `p-${base}`.slice(0, 32);\n}\n\n/**\n * Defines an action. `settings` is inferred, so `run` and `component` get typed settings:\n *\n * ```ts\n * export const hello = defineAction({\n * id: \"hello\",\n * name: \"Hello\",\n * settings: { name: { type: \"text\", label: \"Name\", default: \"world\" } },\n * run: ({ settings, plugin }) => plugin.log(`Hi ${settings.name}`),\n * });\n * ```\n */\nexport function defineAction<const S extends SettingsSchema = Record<never, never>>(\n def: ActionDef<S>,\n): Action {\n return {\n ...def,\n slots: def.slots ?? [\"key\"],\n settings: def.settings ?? {},\n } as unknown as Action;\n}\n\n/** Defines a trigger type with typed settings. */\nexport function defineTrigger<const S extends SettingsSchema = Record<never, never>>(\n def: TriggerDef<S>,\n): Trigger {\n return { ...def, settings: def.settings ?? {} } as unknown as Trigger;\n}\n\n/** Defines a plugin, checking it. A plugin module's default export must be one of these. */\nexport function definePlugin(def: PluginDef): PluginDef {\n const problems = checkPlugin(def);\n if (problems.length > 0) {\n throw new TypeError(`invalid plugin \"${def?.id}\": ${problems.join(\"; \")}`);\n }\n return def;\n}\n\nfunction checkLocalIds(\n kind: string,\n items: readonly { id?: unknown }[],\n problems: string[],\n): Set<string> {\n const seen = new Set<string>();\n for (const item of items) {\n const name = typeof item?.id === \"string\" ? item.id : \"?\";\n if (typeof item?.id !== \"string\" || !LOCAL_ID.test(item.id)) {\n problems.push(`${kind} \"${name}\": id must be letters, digits, \".\", \"-\" or \"_\"`);\n } else if (seen.has(item.id)) {\n problems.push(`${kind} \"${name}\" is defined twice`);\n }\n seen.add(name);\n }\n return seen;\n}\n\n/** Problems with something that should be a plugin (empty when it is fine). */\nexport function checkPlugin(value: unknown): string[] {\n if (!value || typeof value !== \"object\") return [\"not an object\"];\n const def = value as Partial<PluginDef>;\n const problems: string[] = [];\n if (typeof def.id !== \"string\" || !ID.test(def.id)) {\n problems.push(\"id must be a package-style name (lowercase, e.g. `my-plugin` or `@me/plugin`)\");\n }\n if (typeof def.name !== \"string\" || def.name === \"\") problems.push(\"name is required\");\n if (typeof def.version !== \"string\" || def.version === \"\") problems.push(\"version is required\");\n if (def.namespace !== undefined && !NAMESPACE.test(def.namespace)) {\n problems.push(\"namespace must be lowercase letters, digits, - or _ (starting with a letter)\");\n }\n if (def.activate !== undefined && typeof def.activate !== \"function\") {\n problems.push(\"activate must be a function\");\n }\n if (def.permissions !== undefined) {\n if (!Array.isArray(def.permissions)) problems.push(\"permissions must be an array\");\n else\n for (const p of def.permissions)\n if (!PERMISSIONS.includes(p)) problems.push(`unknown permission \"${String(p)}\"`);\n }\n if (def.settings !== undefined) {\n for (const p of checkSchema(def.settings, def.optionSources ?? {})) {\n problems.push(`plugin ${p}`);\n }\n }\n if (def.commands !== undefined) {\n if (!Array.isArray(def.commands)) problems.push(\"commands must be an array\");\n else {\n checkLocalIds(\"command\", def.commands, problems);\n for (const c of def.commands as Partial<PluginCommand>[]) {\n const name = typeof c?.id === \"string\" ? c.id : \"?\";\n if (typeof c?.name !== \"string\") problems.push(`command \"${name}\": name is required`);\n if (typeof c?.run !== \"function\") problems.push(`command \"${name}\": run is required`);\n }\n }\n }\n if (def.onboarding !== undefined) problems.push(...checkOnboarding(def));\n const sources = def.optionSources ?? {};\n if (typeof sources !== \"object\") problems.push(\"optionSources must be an object\");\n else\n for (const [name, fn] of Object.entries(sources))\n if (typeof fn !== \"function\") problems.push(`option source \"${name}\" must be a function`);\n\n if (!Array.isArray(def.actions)) return [...problems, \"actions must be an array\"];\n checkLocalIds(\"action\", def.actions, problems);\n for (const action of def.actions as Partial<Action>[]) {\n const name = typeof action?.id === \"string\" ? action.id : \"?\";\n if (typeof action?.name !== \"string\") problems.push(`action \"${name}\": name is required`);\n const hasComponent =\n typeof action?.component === \"function\" || typeof action?.component === \"object\";\n const hasRun = typeof action?.run === \"function\";\n if (!hasComponent && !hasRun) problems.push(`action \"${name}\": needs run or component`);\n if (action?.look !== undefined && typeof action.look !== \"function\") {\n problems.push(`action \"${name}\": look must be a function`);\n }\n const slots = action?.slots ?? [\"key\"];\n if (\n !Array.isArray(slots) ||\n slots.length === 0 ||\n slots.some((s) => ![\"key\", \"sensor\", \"window\"].includes(s))\n ) {\n problems.push(`action \"${name}\": slots must list \"key\", \"sensor\" and/or \"window\"`);\n }\n for (const p of checkSchema(action?.settings ?? {}, sources)) {\n problems.push(`action \"${name}\": ${p}`);\n }\n // Action settings are stored in the config, which must stay free of secrets.\n for (const [key, field] of Object.entries(action?.settings ?? {})) {\n if (field?.type === \"secret\") {\n problems.push(`action \"${name}\": setting \"${key}\": secrets belong in the plugin settings`);\n }\n }\n }\n\n if (def.state !== undefined) {\n if (!Array.isArray(def.state)) problems.push(\"state must be an array\");\n else {\n checkLocalIds(\"state\", def.state, problems);\n for (const s of def.state as Partial<StateDef>[]) {\n const name = typeof s?.id === \"string\" ? s.id : \"?\";\n if (typeof s?.name !== \"string\") problems.push(`state \"${name}\": name is required`);\n if (![\"number\", \"string\", \"boolean\", \"json\"].includes(s?.type as string)) {\n problems.push(`state \"${name}\": type must be number, string, boolean or json`);\n }\n if (s?.poll && (typeof s.poll.read !== \"function\" || !(s.poll.everyMs > 0))) {\n problems.push(`state \"${name}\": poll needs read() and everyMs > 0`);\n }\n if (s?.start !== undefined && typeof s.start !== \"function\") {\n problems.push(`state \"${name}\": start must be a function`);\n }\n }\n }\n }\n\n if (def.triggers !== undefined) {\n if (!Array.isArray(def.triggers)) problems.push(\"triggers must be an array\");\n else {\n checkLocalIds(\"trigger\", def.triggers, problems);\n for (const t of def.triggers as Partial<Trigger>[]) {\n const name = typeof t?.id === \"string\" ? t.id : \"?\";\n if (typeof t?.name !== \"string\") problems.push(`trigger \"${name}\": name is required`);\n if (typeof t?.subscribe !== \"function\") {\n problems.push(`trigger \"${name}\": subscribe is required`);\n }\n for (const p of checkSchema(t?.settings ?? {}, sources)) {\n problems.push(`trigger \"${name}\": ${p}`);\n }\n }\n }\n }\n return problems;\n}\n\n/** Problems with a plugin's onboarding: steps that name settings, commands or actions it lacks. */\nfunction checkOnboarding(def: Partial<PluginDef>): string[] {\n const onboarding = def.onboarding as Partial<Onboarding>;\n if (!Array.isArray(onboarding?.steps)) return [\"onboarding: steps must be an array\"];\n const problems: string[] = [];\n checkLocalIds(\"onboarding step\", onboarding.steps, problems);\n const settings = def.settings ?? {};\n const commands = new Set((def.commands ?? []).map((c) => c.id));\n for (const step of onboarding.steps as Partial<OnboardingStep>[]) {\n const name = typeof step?.id === \"string\" ? step.id : \"?\";\n if (typeof step?.title !== \"string\")\n problems.push(`onboarding step \"${name}\": title is required`);\n for (const key of step?.settings ?? []) {\n if (!(key in settings)) problems.push(`onboarding step \"${name}\": no setting \"${key}\"`);\n }\n if (step?.command !== undefined && !commands.has(step.command)) {\n problems.push(`onboarding step \"${name}\": no command \"${step.command}\"`);\n }\n if (step?.done !== undefined && typeof step.done !== \"function\") {\n problems.push(`onboarding step \"${name}\": done must be a function`);\n }\n }\n const page = onboarding.starterPage;\n if (page) {\n const actions = new Set((def.actions ?? []).map((a) => a.id));\n const used = [\n ...Object.values(page.keys ?? {}),\n ...Object.values(page.sensors ?? {}),\n ...(page.window ? [page.window] : []),\n ];\n for (const { action } of used) {\n if (!actions.has(action)) problems.push(`onboarding starter page: no action \"${action}\"`);\n }\n }\n return problems;\n}\n",
17
+ "/**\n * Talks to `sdeck-audio`, the helper process that reaches the system's audio devices. It runs\n * only while something needs it, and is restarted if it stops on its own.\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface Level {\n /** 0–100. */\n volume: number;\n muted: boolean;\n}\n\nexport interface AudioDevice extends Level {\n id: string;\n name: string;\n default: boolean;\n}\n\nexport interface AudioApp extends Level {\n /** Executable name, lowercased (`system` for system sounds). */\n name: string;\n active: boolean;\n}\n\nexport interface Snapshot {\n outputs: AudioDevice[];\n inputs: AudioDevice[];\n apps: AudioApp[];\n}\n\nexport interface Change {\n before: Level;\n after: Level;\n}\n\nexport type Target =\n | { kind: \"output\"; device?: string }\n | { kind: \"input\"; device?: string }\n | { kind: \"app\"; app: string };\n\nexport interface Requests {\n snapshot: { params: undefined; result: Snapshot };\n setVolume: { params: { target: Target; volume?: number; delta?: number }; result: Change };\n setMute: { params: { target: Target; muted?: boolean }; result: Change };\n setDefault: { params: { device: string }; result: { previous: string | null } };\n}\n\n/** Why there is no audio: shown to the user. */\nexport class AudioUnavailable extends Error {}\n\nexport const BUILD_HINT = \"Build the audio helper with `bun run build:audio`\";\n\n/**\n * Where the helper is: `SDECK_AUDIO_BIN`, the cargo build next to this package, or `bin/` next to\n * a bundled app.\n */\nexport function findHelper(\n env: Record<string, string | undefined> = process.env,\n base: string = import.meta.dir,\n exists: (path: string) => boolean = existsSync,\n): string | undefined {\n const name = process.platform === \"win32\" ? \"sdeck-audio.exe\" : \"sdeck-audio\";\n return [\n env.SDECK_AUDIO_BIN,\n join(base, \"..\", \"native\", \"target\", \"release\", name),\n join(base, \"..\", \"bin\", name),\n join(base, \"..\", \"native\", \"target\", \"debug\", name),\n ].find((path): path is string => Boolean(path) && exists(path as string));\n}\n\ninterface Pending {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\nexport interface AudioHelperOptions {\n /** The command line to run; throw {@link AudioUnavailable} when there is none. */\n command: () => string[];\n /** The helper could not run, or stopped. `undefined`: it works again. */\n onProblem?: (problem: Error | undefined) => void;\n /** How long it keeps running after the last user leaves. */\n lingerMs?: number;\n timeoutMs?: number;\n}\n\nexport class AudioHelper {\n readonly #options: AudioHelperOptions;\n readonly #listeners = new Set<(snapshot: Snapshot | undefined) => void>();\n readonly #pending = new Map<number, Pending>();\n #child: ChildProcess | undefined;\n #snapshot: Snapshot | undefined;\n #users = 0;\n #next = 1;\n #linger: ReturnType<typeof setTimeout> | undefined;\n #restart: ReturnType<typeof setTimeout> | undefined;\n #delay = 1000;\n\n constructor(options: AudioHelperOptions) {\n this.#options = options;\n }\n\n /** The devices as last reported, while the helper runs. */\n get snapshot(): Snapshot | undefined {\n return this.#snapshot;\n }\n\n /** Whether the helper process is running. */\n get running(): boolean {\n return this.#child !== undefined;\n }\n\n /** Hears every snapshot while subscribed (which keeps the helper running). */\n subscribe(listener: (snapshot: Snapshot | undefined) => void): () => void {\n this.#listeners.add(listener);\n const release = this.#acquire();\n if (this.#snapshot) listener(this.#snapshot);\n return () => {\n this.#listeners.delete(listener);\n release();\n };\n }\n\n async request<M extends keyof Requests>(\n method: M,\n params?: Requests[M][\"params\"],\n ): Promise<Requests[M][\"result\"]> {\n const release = this.#acquire();\n try {\n const child = this.#child ?? this.#start();\n const id = this.#next++;\n return (await new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.#pending.delete(id);\n reject(new Error(\"the audio helper did not answer\"));\n }, this.#options.timeoutMs ?? 5000);\n this.#pending.set(id, { resolve, reject, timer });\n child.stdin?.write(`${JSON.stringify({ id, method, params })}\\n`);\n })) as Requests[M][\"result\"];\n } finally {\n release();\n }\n }\n\n /** Stops the helper now, whoever uses it. */\n close(): void {\n this.#users = 0;\n this.#listeners.clear();\n clearTimeout(this.#linger);\n this.#stop();\n }\n\n #acquire(): () => void {\n this.#users++;\n clearTimeout(this.#linger);\n if (!this.#child && !this.#restart) {\n try {\n this.#start();\n } catch (error) {\n this.#options.onProblem?.(error as Error);\n }\n }\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.#users--;\n if (this.#users > 0) return;\n this.#linger = setTimeout(() => this.#stop(), this.#options.lingerMs ?? 3000);\n };\n }\n\n #start(): ChildProcess {\n clearTimeout(this.#restart);\n this.#restart = undefined;\n const [file, ...args] = this.#options.command();\n if (!file) throw new AudioUnavailable(BUILD_HINT);\n const child = spawn(file, args, { stdio: [\"pipe\", \"pipe\", \"pipe\"], windowsHide: true });\n this.#child = child;\n let buffer = \"\";\n let errors = \"\";\n child.stdout?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (chunk: string) => {\n buffer += chunk;\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n for (const line of lines) this.#receive(line);\n });\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (chunk: string) => {\n errors = (errors + chunk).slice(-2000);\n });\n // Writing to a helper that just died must not crash the host.\n child.stdin?.on(\"error\", () => {});\n const ended = (reason: string) => {\n if (this.#child !== child) return;\n this.#child = undefined;\n this.#fail(new Error(reason));\n this.#publish(undefined);\n this.#options.onProblem?.(new AudioUnavailable(reason));\n if (this.#users <= 0) return;\n this.#restart = setTimeout(() => {\n this.#restart = undefined;\n if (this.#users <= 0 || this.#child) return;\n try {\n this.#start();\n } catch (error) {\n this.#options.onProblem?.(error as Error);\n }\n }, this.#delay);\n this.#delay = Math.min(this.#delay * 2, 30_000);\n };\n child.once(\"error\", (error) => ended(`the audio helper cannot run: ${error.message}`));\n child.once(\"close\", (code) =>\n ended(errors.trim() || `the audio helper stopped (exit ${code})`),\n );\n return child;\n }\n\n #stop(): void {\n clearTimeout(this.#restart);\n this.#restart = undefined;\n const child = this.#child;\n this.#child = undefined;\n this.#fail(new Error(\"the audio helper was stopped\"));\n this.#publish(undefined);\n if (!child) return;\n // Closing its input asks it to exit; insist if it does not.\n child.stdin?.end();\n const kill = setTimeout(() => child.kill(), 2000);\n child.once(\"close\", () => clearTimeout(kill));\n }\n\n #receive(line: string): void {\n let message: { id?: number; result?: unknown; error?: string; event?: string; data?: unknown };\n try {\n message = JSON.parse(line);\n } catch {\n return;\n }\n if (message.event === \"snapshot\") {\n this.#delay = 1000;\n this.#options.onProblem?.(undefined);\n this.#publish(message.data as Snapshot);\n return;\n }\n const pending = this.#pending.get(message.id ?? -1);\n if (!pending) return;\n this.#pending.delete(message.id as number);\n clearTimeout(pending.timer);\n if (message.error !== undefined) pending.reject(new Error(message.error));\n else pending.resolve(message.result);\n }\n\n #publish(snapshot: Snapshot | undefined): void {\n if (this.#snapshot === undefined && snapshot === undefined) return;\n this.#snapshot = snapshot;\n for (const listener of [...this.#listeners]) listener(snapshot);\n }\n\n #fail(error: Error): void {\n for (const pending of this.#pending.values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