glimpse-sdk 0.2.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,14 +10,25 @@ Requires Node.js 20+.
10
10
  npm install glimpse-sdk
11
11
  ```
12
12
 
13
+ ## Develop
14
+
15
+ Create and live-run a TypeScript applet project with the Glimpse tooling:
16
+
17
+ ```sh
18
+ glimpse-applet new counter --lang typescript
19
+ cd counter
20
+ glimpse-applet dev
21
+ ```
22
+
23
+ Read `docs/custom-applets/tooling.md` for project layout, `applet.toml`, dev applets, linking, and diagnostics.
24
+
13
25
  ## Goals
14
26
 
15
27
  - typed protocol models
16
28
  - typed widget builders
17
29
  - async runtime
18
30
  - explicit typed handler registration
19
- - state-driven rendering via `await this.setState(...)`
20
- - single `render()` method that returns all panel state
31
+ - separate `status(state)` and `popover(state)` methods; state mutation via `await this.setState(...)`
21
32
 
22
33
  ## Example
23
34
 
@@ -29,9 +40,9 @@ import {
29
40
  Hero,
30
41
  Icon,
31
42
  Label,
32
- RenderResult,
33
43
  StatusItem,
34
- } from "./src/index.js";
44
+ type TreeNode,
45
+ } from "glimpse-sdk";
35
46
 
36
47
  interface DeployState {
37
48
  version: string;
@@ -50,25 +61,31 @@ class DeployApplet extends Applet<DeployState> {
50
61
  });
51
62
  }
52
63
 
53
- protected async render(): Promise<RenderResult> {
54
- return new RenderResult({
55
- status: [
56
- new StatusItem({
57
- id: "deploy",
58
- icon: Icon.name("software-update-available-symbolic"),
59
- label: this.state.status,
60
- }),
61
- ],
62
- hero: new Hero({
64
+ protected async status(state: DeployState): Promise<StatusItem[]> {
65
+ return [
66
+ new StatusItem({
67
+ id: "deploy",
68
+ icon: Icon.name("software-update-available-symbolic"),
69
+ label: state.status,
70
+ }),
71
+ ];
72
+ }
73
+
74
+ protected async popover(state: DeployState): Promise<TreeNode | null> {
75
+ return Box.vertical([
76
+ new Hero({
63
77
  icon: Icon.name("software-update-available-symbolic"),
64
78
  title: "Deploy",
65
- subtitle: this.state.version,
79
+ subtitle: state.version,
66
80
  }),
67
- tree: Box.vertical([
68
- new Label("Version"),
69
- new Button({ id: "deploy_now", label: "Deploy now" }),
70
- ]),
71
- });
81
+ new Label("Version"),
82
+ new Button({
83
+ id: "deploy_now",
84
+ label: "Deploy now",
85
+ icon: "media-playback-start-symbolic",
86
+ variant: "primary",
87
+ }),
88
+ ]);
72
89
  }
73
90
  }
74
91
 
@@ -85,4 +102,25 @@ Use explicit registration helpers instead of decorators:
85
102
  - `this.onChange(id, handler)`
86
103
  - `this.onToggle(id, handler)`
87
104
 
88
- The SDK owns the line transport and writes `status {json}` and `popover {json}` messages derived from `render()`.
105
+ The SDK owns the line transport. `status(state)` produces the panel items;
106
+ `popover(state)` produces the popover tree; both are pure functions of state.
107
+
108
+ ## IPC client
109
+
110
+ Talk to a running Glimpse daemon: subscribe to event channels and dispatch
111
+ actions. `ipc(service)` only resolves the socket path — the connection is
112
+ opened lazily.
113
+
114
+ ```ts
115
+ import { ipc } from "glimpse-sdk";
116
+
117
+ const sub = ipc("shell"); // "shell" | "wallpaper" | "idle" | "lock"
118
+
119
+ // Fire an action; awaits the ack, throws IpcError if the server rejects it.
120
+ const ack = await sub.dispatch("open_uri", { uri: "https://example.com" });
121
+
122
+ // Stream events until the socket closes.
123
+ for await (const ev of sub.listen("audio.*")) {
124
+ console.log(ev.name, ev.fields);
125
+ }
126
+ ```
package/dist/src/app.d.ts CHANGED
@@ -7,17 +7,19 @@ interface OutgoingMessage {
7
7
  data: unknown;
8
8
  line: string;
9
9
  }
10
- export declare class RenderResult {
11
- readonly options: {
12
- status?: StatusItem[];
13
- tree?: TreeNode | null;
14
- };
15
- constructor(options?: {
16
- status?: StatusItem[];
17
- tree?: TreeNode | null;
18
- });
19
- get status(): StatusItem[];
20
- get tree(): TreeNode | null;
10
+ interface ShowNotificationArgs {
11
+ summary: string;
12
+ body?: string;
13
+ urgency?: string;
14
+ }
15
+ interface OpenUriArgs {
16
+ uri: string;
17
+ }
18
+ interface CopyToClipboardArgs {
19
+ text: string;
20
+ }
21
+ interface DismissNotificationArgs {
22
+ id: number;
21
23
  }
22
24
  export declare abstract class Applet<State extends object> {
23
25
  state: State;
@@ -33,7 +35,8 @@ export declare abstract class Applet<State extends object> {
33
35
  protected onStart(): Promise<void>;
34
36
  protected onInit(_event: InitEvent): Promise<void>;
35
37
  protected onCallback(_event: CallbackEvent): Promise<void>;
36
- protected render(): Promise<RenderResult>;
38
+ protected status(_state: State): Promise<StatusItem[]>;
39
+ protected popover(_state: State): Promise<TreeNode | null>;
37
40
  setState(patch: Partial<State>): Promise<void>;
38
41
  onClick(id: string, handler: Handler<ClickEvent>): void;
39
42
  onScroll(id: string, handler: Handler<ScrollEvent>): void;
@@ -41,6 +44,11 @@ export declare abstract class Applet<State extends object> {
41
44
  onChange(id: string, handler: Handler<ChangeEvent>): void;
42
45
  onToggle(id: string, handler: Handler<ToggleEvent>): void;
43
46
  isPopoverOpen(): boolean;
47
+ protected showNotification(args: ShowNotificationArgs): void;
48
+ protected openUri(args: OpenUriArgs): void;
49
+ protected copyToClipboard(args: CopyToClipboardArgs): void;
50
+ protected dismissNotification(args: DismissNotificationArgs): void;
51
+ protected closePopover(): void;
44
52
  run(): Promise<void>;
45
53
  protected drainOutgoingForTest(): Promise<OutgoingMessage[]>;
46
54
  private register;
@@ -49,5 +57,6 @@ export declare abstract class Applet<State extends object> {
49
57
  private scheduleRender;
50
58
  private flushRender;
51
59
  private emit;
60
+ private emitAction;
52
61
  }
53
62
  export {};
package/dist/src/app.js CHANGED
@@ -1,17 +1,5 @@
1
1
  import { createInterface } from "node:readline";
2
2
  import { parseCallbackEvent, parseInitEvent, } from "./events.js";
3
- export class RenderResult {
4
- options;
5
- constructor(options = {}) {
6
- this.options = options;
7
- }
8
- get status() {
9
- return this.options.status ?? [];
10
- }
11
- get tree() {
12
- return this.options.tree ?? null;
13
- }
14
- }
15
3
  export class Applet {
16
4
  state;
17
5
  handlerMap = new Map();
@@ -27,8 +15,11 @@ export class Applet {
27
15
  async onStart() { }
28
16
  async onInit(_event) { }
29
17
  async onCallback(_event) { }
30
- async render() {
31
- return new RenderResult();
18
+ async status(_state) {
19
+ return [];
20
+ }
21
+ async popover(_state) {
22
+ return null;
32
23
  }
33
24
  async setState(patch) {
34
25
  this.state = { ...this.state, ...patch };
@@ -52,6 +43,21 @@ export class Applet {
52
43
  isPopoverOpen() {
53
44
  return this.popoverOpen;
54
45
  }
46
+ showNotification(args) {
47
+ this.emitAction("show_notification", args);
48
+ }
49
+ openUri(args) {
50
+ this.emitAction("open_uri", args);
51
+ }
52
+ copyToClipboard(args) {
53
+ this.emitAction("copy_to_clipboard", args);
54
+ }
55
+ dismissNotification(args) {
56
+ this.emitAction("dismiss_notification", args);
57
+ }
58
+ closePopover() {
59
+ this.emitAction("close_popover", {});
60
+ }
55
61
  async run() {
56
62
  process.stdout.on("error", (err) => {
57
63
  if (err.code === "EPIPE") {
@@ -138,15 +144,15 @@ export class Applet {
138
144
  await this.flushPromise;
139
145
  }
140
146
  async flushRender() {
141
- const rendered = await this.render();
142
- const status = rendered.status.map((item) => item.toProtocol());
143
- const tree = { root: rendered.tree?.toProtocol() ?? null };
147
+ const statusItems = await this.status(this.state);
148
+ const status = statusItems.map((item) => item.toProtocol());
144
149
  if (!deepEqual(status, this.lastStatus)) {
145
150
  this.lastStatus = status;
146
151
  this.emit("status", { items: status });
147
152
  }
148
- const publishPopover = this.popoverOpen || this.lastTree === null || tree.root === null;
149
- if (publishPopover && !deepEqual(tree, this.lastTree)) {
153
+ const widget = await this.popover(this.state);
154
+ const tree = { root: widget?.toProtocol() ?? null };
155
+ if (!deepEqual(tree, this.lastTree)) {
150
156
  this.lastTree = tree;
151
157
  this.emit("popover", tree);
152
158
  }
@@ -164,6 +170,9 @@ export class Applet {
164
170
  }
165
171
  }
166
172
  }
173
+ emitAction(type, args) {
174
+ this.emit("action", { type, arguments: args });
175
+ }
167
176
  }
168
177
  function parseLine(line) {
169
178
  const trimmed = line.trim();
@@ -1,4 +1,5 @@
1
- export { Applet, RenderResult } from "./app.js";
1
+ export { Applet } from "./app.js";
2
2
  export { type CallbackEvent, type ChangeEvent, type ClickEvent, type InitEvent, type InputEvent, type PopoverEvent, type ScrollEvent, type ToggleEvent, parseCallbackEvent, parseInitEvent, } from "./events.js";
3
- export { Icon, MenuItem, StatusItem } from "./protocol.js";
4
- export { ActionMenu, ActionMenuItem, ActionRow, type Align, Badge, Box, Button, Card, Checkbox, Collapsible, CollapsibleItem, Column, Copyable, DetailGrid, DetailGridItem, Dropdown, DropdownItem, EmptyState, Grid, GridChild, Header, Hero, IconWidget, Image, Item, Label, Meter, type Orientation, Progress, Row, Scale, Scroll, Section, Separator, Spinner, StatusDot, Switch, Toast, ToastAction, type TreeNode, type Variant, } from "./widgets.js";
3
+ export { Icon, StatusItem } from "./protocol.js";
4
+ export { type Event, IpcError, Subscriber, ipc } from "./ipc.js";
5
+ export { ActionItem, type Align, Badge, Box, Button, type ButtonVariant, Card, Checkbox, Column, type ContentFit, Copyable, EmptyState, Expander, Grid, GridChild, Hero, Image, Item, Label, LevelBar, type LevelBarMode, LinkButton, ListBox, MenuButton, Meter, Overlay, type Orientation, type PagerAppearance, PagerItem, PagerStrip, Picture, Progress, type Properties, PropertyList, Row, Scroll, Section, Select, SelectOption, Separator, Slider, Spinner, StatusDot, Switch, ToggleButton, TreeExpander, type TreeNode, type Variant, } from "./widgets.js";
package/dist/src/index.js CHANGED
@@ -1,4 +1,5 @@
1
- export { Applet, RenderResult } from "./app.js";
1
+ export { Applet } from "./app.js";
2
2
  export { parseCallbackEvent, parseInitEvent, } from "./events.js";
3
- export { Icon, MenuItem, StatusItem } from "./protocol.js";
4
- export { ActionMenu, ActionMenuItem, ActionRow, Badge, Box, Button, Card, Checkbox, Collapsible, CollapsibleItem, Column, Copyable, DetailGrid, DetailGridItem, Dropdown, DropdownItem, EmptyState, Grid, GridChild, Header, Hero, IconWidget, Image, Item, Label, Meter, Progress, Row, Scale, Scroll, Section, Separator, Spinner, StatusDot, Switch, Toast, ToastAction, } from "./widgets.js";
3
+ export { Icon, StatusItem } from "./protocol.js";
4
+ export { IpcError, Subscriber, ipc } from "./ipc.js";
5
+ export { ActionItem, Badge, Box, Button, Card, Checkbox, Column, Copyable, EmptyState, Expander, Grid, GridChild, Hero, Image, Item, Label, LevelBar, LinkButton, ListBox, MenuButton, Meter, Overlay, PagerItem, PagerStrip, Picture, Progress, PropertyList, Row, Scroll, Section, Select, SelectOption, Separator, Slider, Spinner, StatusDot, Switch, ToggleButton, TreeExpander, } from "./widgets.js";
@@ -0,0 +1,28 @@
1
+ /** One decoded event line; `fields` values are unescaped. */
2
+ export interface Event {
3
+ name: string;
4
+ ts: number;
5
+ fields: Record<string, string>;
6
+ }
7
+ /** Thrown on connection failure or a rejected dispatch (`ok=false`). */
8
+ export declare class IpcError extends Error {
9
+ }
10
+ /** A resolved IPC endpoint. Cheap to create; holds only the socket path. */
11
+ export declare class Subscriber {
12
+ private readonly socketPath;
13
+ constructor(socketPath: string);
14
+ /** Subscribe to `channel` (an exact name, `prefix.*`, or `*`) and yield
15
+ * events until the server closes the connection. */
16
+ listen(channel: string): AsyncGenerator<Event>;
17
+ /** Dispatch `action` with `params` on a fresh connection and await the
18
+ * ack. Resolves with the extra ack fields; rejects with `IpcError` if the
19
+ * server replies `ok=false`. */
20
+ dispatch(action: string, params?: Record<string, string>): Promise<Record<string, string>>;
21
+ private connect;
22
+ }
23
+ /** Resolve the {@link Subscriber} for `service` (`"shell"` for the panel).
24
+ *
25
+ * The socket is `<dir>/<service>.sock` (`shell` maps to `ipc.sock`) where
26
+ * `<dir>` is `$GLIMPSE_IPC_DIR`, else `$XDG_RUNTIME_DIR/glimpse`. No
27
+ * connection is made here. */
28
+ export declare function ipc(service?: string): Subscriber;
@@ -0,0 +1,214 @@
1
+ // Minimal client for the Glimpse IPC socket.
2
+ //
3
+ // `ipc(service)` resolves a `Subscriber` (no I/O — the connection is opened
4
+ // lazily). `Subscriber.listen` subscribes to an event channel and yields
5
+ // decoded `Event`s; `Subscriber.dispatch` sends an action and awaits the
6
+ // server ack on a one-shot connection. The wire protocol matches the
7
+ // `glimpse-shell watch` / `dispatch` CLIs.
8
+ import { createConnection } from "node:net";
9
+ import { createInterface } from "node:readline";
10
+ import { join } from "node:path";
11
+ /** Thrown on connection failure or a rejected dispatch (`ok=false`). */
12
+ export class IpcError extends Error {
13
+ }
14
+ /** A resolved IPC endpoint. Cheap to create; holds only the socket path. */
15
+ export class Subscriber {
16
+ socketPath;
17
+ constructor(socketPath) {
18
+ this.socketPath = socketPath;
19
+ }
20
+ /** Subscribe to `channel` (an exact name, `prefix.*`, or `*`) and yield
21
+ * events until the server closes the connection. */
22
+ async *listen(channel) {
23
+ const conn = await this.connect();
24
+ try {
25
+ conn.socket.write(`subscribe ${channel}\n`);
26
+ for (;;) {
27
+ const next = await conn.lines.next();
28
+ if (next.done)
29
+ return;
30
+ const line = next.value.trim();
31
+ if (line)
32
+ yield parseEvent(line);
33
+ }
34
+ }
35
+ finally {
36
+ close(conn);
37
+ }
38
+ }
39
+ /** Dispatch `action` with `params` on a fresh connection and await the
40
+ * ack. Resolves with the extra ack fields; rejects with `IpcError` if the
41
+ * server replies `ok=false`. */
42
+ async dispatch(action, params = {}) {
43
+ validateToken("action", action, false);
44
+ const entries = Object.entries(params);
45
+ for (const [k] of entries)
46
+ validateToken("param key", k, true);
47
+ const conn = await this.connect();
48
+ try {
49
+ let line = action;
50
+ for (const [k, v] of entries) {
51
+ line += ` ${k}=${escape(v)}`;
52
+ }
53
+ conn.socket.write(line + "\n");
54
+ const next = await conn.lines.next();
55
+ if (next.done) {
56
+ throw new IpcError("IPC server closed connection without ack");
57
+ }
58
+ return parseAck(next.value.trim());
59
+ }
60
+ finally {
61
+ close(conn);
62
+ }
63
+ }
64
+ connect() {
65
+ return new Promise((resolve, reject) => {
66
+ const socket = createConnection({ path: this.socketPath });
67
+ let connected = false;
68
+ // This handler stays attached for the socket's whole lifetime. Never
69
+ // remove it: an unhandled 'error' event on a Socket throws and crashes
70
+ // the process. `close()` only destroys the socket, it does not detach.
71
+ socket.on("error", (err) => {
72
+ if (connected) {
73
+ // Post-connect transport error: end the stream cleanly so the
74
+ // line iterator completes instead of crashing the process.
75
+ socket.destroy();
76
+ }
77
+ else {
78
+ reject(new IpcError(`cannot connect to IPC socket at ${this.socketPath}: ${err.message}`));
79
+ }
80
+ });
81
+ socket.once("connect", () => {
82
+ connected = true;
83
+ const rl = createInterface({ input: socket, crlfDelay: Infinity });
84
+ const lines = rl[Symbol.asyncIterator]();
85
+ void (async () => {
86
+ const hello = await lines.next();
87
+ if (hello.done || !hello.value.startsWith("hello")) {
88
+ rl.close();
89
+ socket.destroy();
90
+ reject(new IpcError(hello.done
91
+ ? "IPC server closed connection before hello"
92
+ : `unexpected IPC greeting: ${hello.value}`));
93
+ return;
94
+ }
95
+ resolve({ socket, rl, lines });
96
+ })();
97
+ });
98
+ });
99
+ }
100
+ }
101
+ /** Resolve the {@link Subscriber} for `service` (`"shell"` for the panel).
102
+ *
103
+ * The socket is `<dir>/<service>.sock` (`shell` maps to `ipc.sock`) where
104
+ * `<dir>` is `$GLIMPSE_IPC_DIR`, else `$XDG_RUNTIME_DIR/glimpse`. No
105
+ * connection is made here. */
106
+ export function ipc(service = "shell") {
107
+ return new Subscriber(socketPath(service));
108
+ }
109
+ function socketPath(service) {
110
+ const override = process.env.GLIMPSE_IPC_DIR;
111
+ let dir;
112
+ if (override) {
113
+ dir = override;
114
+ }
115
+ else {
116
+ const runtime = process.env.XDG_RUNTIME_DIR;
117
+ if (!runtime) {
118
+ throw new IpcError("neither GLIMPSE_IPC_DIR nor XDG_RUNTIME_DIR is set; " +
119
+ "cannot locate the Glimpse IPC socket");
120
+ }
121
+ dir = join(runtime, "glimpse");
122
+ }
123
+ return join(dir, service === "shell" ? "ipc.sock" : `${service}.sock`);
124
+ }
125
+ function close(conn) {
126
+ conn.rl.close();
127
+ conn.socket.destroy();
128
+ }
129
+ // The wire protocol splits client lines on whitespace and never unescapes
130
+ // the command name or a field key, so an `action`/key with whitespace would
131
+ // forge extra tokens or whole client lines. Values are safe (escaped).
132
+ function validateToken(label, token, forbidEq) {
133
+ if (token.length === 0) {
134
+ throw new IpcError(`IPC ${label} must not be empty`);
135
+ }
136
+ if (/\s/.test(token)) {
137
+ throw new IpcError(`IPC ${label} "${token}" must not contain whitespace`);
138
+ }
139
+ if (forbidEq && token.includes("=")) {
140
+ throw new IpcError(`IPC param key "${token}" must not contain '='`);
141
+ }
142
+ }
143
+ function escape(s) {
144
+ return s
145
+ .replaceAll("\\", "\\\\")
146
+ .replaceAll("\n", "\\n")
147
+ .replaceAll("\t", "\\t")
148
+ .replaceAll(" ", "\\s");
149
+ }
150
+ function unescape(s) {
151
+ let out = "";
152
+ for (let i = 0; i < s.length; i++) {
153
+ if (s[i] !== "\\") {
154
+ out += s[i];
155
+ continue;
156
+ }
157
+ const next = s[++i];
158
+ if (next === "s")
159
+ out += " ";
160
+ else if (next === "n")
161
+ out += "\n";
162
+ else if (next === "t")
163
+ out += "\t";
164
+ else if (next === "\\")
165
+ out += "\\";
166
+ else if (next === undefined)
167
+ out += "\\";
168
+ else
169
+ out += "\\" + next;
170
+ }
171
+ return out;
172
+ }
173
+ function parseEvent(line) {
174
+ const tokens = line.split(/\s+/);
175
+ const name = tokens[0] ?? "";
176
+ let ts = 0;
177
+ const fields = {};
178
+ for (const token of tokens.slice(1)) {
179
+ const eq = token.indexOf("=");
180
+ if (eq < 0)
181
+ continue;
182
+ const key = token.slice(0, eq);
183
+ const value = unescape(token.slice(eq + 1));
184
+ if (key === "ts" && /^\d+$/.test(value)) {
185
+ ts = Number(value);
186
+ continue;
187
+ }
188
+ fields[key] = value;
189
+ }
190
+ return { name, ts, fields };
191
+ }
192
+ function parseAck(line) {
193
+ const tokens = line.split(/\s+/);
194
+ if (tokens[0] !== "ack") {
195
+ throw new IpcError(`expected an ack, got: ${line}`);
196
+ }
197
+ let ok = false;
198
+ const fields = {};
199
+ for (const token of tokens.slice(1)) {
200
+ const eq = token.indexOf("=");
201
+ if (eq < 0)
202
+ continue;
203
+ const key = token.slice(0, eq);
204
+ const value = unescape(token.slice(eq + 1));
205
+ if (key === "ok")
206
+ ok = value === "true";
207
+ else
208
+ fields[key] = value;
209
+ }
210
+ if (!ok) {
211
+ throw new IpcError(fields.error ?? "command failed");
212
+ }
213
+ return fields;
214
+ }
@@ -26,18 +26,3 @@ export declare class StatusItem {
26
26
  });
27
27
  toProtocol(): Record<string, unknown>;
28
28
  }
29
- export declare class MenuItem {
30
- readonly options: {
31
- id: string;
32
- label: string;
33
- visible?: boolean;
34
- enabled?: boolean;
35
- };
36
- constructor(options: {
37
- id: string;
38
- label: string;
39
- visible?: boolean;
40
- enabled?: boolean;
41
- });
42
- toProtocol(): Record<string, unknown>;
43
- }
@@ -37,22 +37,3 @@ export class StatusItem {
37
37
  return payload;
38
38
  }
39
39
  }
40
- export class MenuItem {
41
- options;
42
- constructor(options) {
43
- this.options = options;
44
- }
45
- toProtocol() {
46
- const payload = {
47
- id: this.options.id,
48
- label: this.options.label,
49
- };
50
- if (this.options.visible !== undefined) {
51
- payload.visible = this.options.visible;
52
- }
53
- if (this.options.enabled !== undefined) {
54
- payload.enabled = this.options.enabled;
55
- }
56
- return payload;
57
- }
58
- }