opentray 0.6.0 → 0.8.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 +50 -1
- package/dist/cli.mjs +1 -1
- package/dist/client-C27qmRfr.d.mts +102 -0
- package/dist/client-C27qmRfr.d.mts.map +1 -0
- package/dist/index.d.mts +5 -5
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +117 -19
- package/dist/index.mjs.map +1 -1
- package/dist/{local-broker-C9siWyRh.mjs → local-broker-BMxjb-eO.mjs} +99 -15
- package/dist/local-broker-BMxjb-eO.mjs.map +1 -0
- package/dist/node.d.mts +4 -1
- package/dist/node.d.mts.map +1 -1
- package/dist/node.mjs +1 -1
- package/package.json +11 -8
- package/dist/client-DQn3DLZw.d.mts +0 -62
- package/dist/client-DQn3DLZw.d.mts.map +0 -1
- package/dist/local-broker-C9siWyRh.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -17,6 +17,27 @@ pnpm add opentray
|
|
|
17
17
|
|
|
18
18
|
`packages/cli` is the only unscoped npm package in this monorepo.
|
|
19
19
|
|
|
20
|
+
## Caller identity and per-caller isolation
|
|
21
|
+
|
|
22
|
+
Each host application gets its own broker process. OpenTray does not aggregate
|
|
23
|
+
multiple callers onto one shared tray; a broker is pinned to exactly one caller
|
|
24
|
+
session so its process is identifiable in the task manager and killing it only
|
|
25
|
+
affects that one application.
|
|
26
|
+
|
|
27
|
+
The SDK derives a caller label with this precedence:
|
|
28
|
+
|
|
29
|
+
1. An explicit label: `connectLocalBroker({ callerLabel: "myapp" })`.
|
|
30
|
+
2. `npm_package_name` when present.
|
|
31
|
+
3. The basename of the running script.
|
|
32
|
+
4. The neutral fallback `opentray` when nothing usable is available.
|
|
33
|
+
|
|
34
|
+
The label is sanitized to a filesystem- and process-safe component and scopes
|
|
35
|
+
the broker endpoint, runtime directory, ready file, and the process name, so two
|
|
36
|
+
host applications using the same OpenTray version resolve distinct brokers and
|
|
37
|
+
endpoints. A broker rejects a second incoming connection with a typed
|
|
38
|
+
`OPENTRAY_BROKER_SINGLE_SESSION` error rather than silently sharing state.
|
|
39
|
+
|
|
40
|
+
|
|
20
41
|
## Example
|
|
21
42
|
|
|
22
43
|
Run a protocol-only example that creates a space, creates a tray, dispatches an extension command, and prints each client frame:
|
|
@@ -31,10 +52,18 @@ The top-level SDK now exposes the mainline broker-backed path directly:
|
|
|
31
52
|
import { createSpace, createTray, resolveDefaultSpace } from "opentray";
|
|
32
53
|
|
|
33
54
|
const space = await createSpace({ id: "com.example.status", default: true });
|
|
34
|
-
await space.createTray({
|
|
55
|
+
const tray = await space.createTray({
|
|
35
56
|
trayId: "status",
|
|
36
57
|
title: "Status",
|
|
37
58
|
icon: { type: "file", path: "./assets/tray-icon.png" },
|
|
59
|
+
menu: { items: [{ type: "item", id: 1, title: "Open", primaryEvent: true }] },
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
await tray.setTitle("Status: ready");
|
|
63
|
+
tray.onMenuClick(({ itemId }) => {
|
|
64
|
+
if (itemId === 1) {
|
|
65
|
+
// Open a native menu action or a WebView surface.
|
|
66
|
+
}
|
|
38
67
|
});
|
|
39
68
|
|
|
40
69
|
const defaultSpace = await resolveDefaultSpace();
|
|
@@ -88,6 +117,26 @@ const panel = tray.createWebviewWindow({
|
|
|
88
117
|
await panel.show();
|
|
89
118
|
```
|
|
90
119
|
|
|
120
|
+
For tray-anchored or screen-aware surfaces, use `WebviewPlacementKit` from `@opentray/ext-webview` instead of hand-authoring raw broker frames or creating a one-off panel abstraction.
|
|
121
|
+
|
|
122
|
+
Run the placement demo when you want to review tray, screen, and edge-aware placement:
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
cargo build -p opentray-bin -p opentray-ext-webview
|
|
126
|
+
pnpm --filter opentray example:placement
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
This demo follows the `skills/opentray` placement law: extension-owned WebView mounting, continuous `WebviewPlacementKit.watch()`, `applyOnce()`, tray/screen/edge anchors, and a page-owned frameless drag region.
|
|
130
|
+
|
|
131
|
+
Run the media query demo when you want to review responsive native window style and constraints:
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
cargo build -p opentray-bin -p opentray-ext-webview
|
|
135
|
+
pnpm --filter opentray example:mediaQuery
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
This demo focuses on `styleKit.apply(...)` and `mediaQueryKit.match(...)`. Keep it separate from placement debugging so size/style callbacks do not obscure placement behavior.
|
|
139
|
+
|
|
91
140
|
Run the dedicated tray-panel demo:
|
|
92
141
|
|
|
93
142
|
```bash
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as inspectDaemon, c as stopDaemon, i as createNodeDaemonDriver, n as resolveDaemonPaths, o as restartDaemon, r as readPackageVersion, s as startDaemon, t as connectLocalBroker } from "./local-broker-
|
|
2
|
+
import { a as inspectDaemon, c as stopDaemon, i as createNodeDaemonDriver, n as resolveDaemonPaths, o as restartDaemon, r as readPackageVersion, s as startDaemon, t as connectLocalBroker } from "./local-broker-BMxjb-eO.mjs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { realpathSync } from "node:fs";
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { ClientFrame, ClientRequestFrame, ExtensionEnvelope, Icon, Menu, RequestId, ServerFrame, SpaceOptions, SpaceRef, Tooltip, TrayBoundsResult, TrayEvent, TrayId, TrayOptions } from "@opentray/spec";
|
|
2
|
+
|
|
3
|
+
//#region src/client.d.ts
|
|
4
|
+
interface OpenTrayTransport {
|
|
5
|
+
request(frame: ClientRequestFrame): Promise<ServerFrame>;
|
|
6
|
+
}
|
|
7
|
+
type BrokerEventFrame = Extract<ServerFrame, {
|
|
8
|
+
type: "event" | "ext-event";
|
|
9
|
+
}>;
|
|
10
|
+
interface OpenTrayEventSource {
|
|
11
|
+
onEvent(listener: (frame: BrokerEventFrame) => void): () => void;
|
|
12
|
+
}
|
|
13
|
+
interface OpenTrayConnection extends OpenTrayTransport, OpenTrayEventSource {}
|
|
14
|
+
interface OpenTrayClient {
|
|
15
|
+
createSpace(options: SpaceOptions): Promise<SpaceHandle>;
|
|
16
|
+
resolveDefaultSpace(): Promise<SpaceHandle>;
|
|
17
|
+
/** @deprecated Use `createSpace`. */
|
|
18
|
+
createSurface(options: SpaceOptions): Promise<SpaceHandle>;
|
|
19
|
+
}
|
|
20
|
+
interface SpaceHandle {
|
|
21
|
+
space: SpaceRef;
|
|
22
|
+
createTray(options: TrayOptions): Promise<TrayHandle>;
|
|
23
|
+
}
|
|
24
|
+
interface EventfulSpaceHandle extends Omit<SpaceHandle, "createTray"> {
|
|
25
|
+
createTray(options: TrayOptions): Promise<EventfulTrayHandle>;
|
|
26
|
+
}
|
|
27
|
+
/** @deprecated Use `SpaceHandle`. */
|
|
28
|
+
type SurfaceHandle = SpaceHandle;
|
|
29
|
+
interface TrayHandle {
|
|
30
|
+
space: SpaceRef;
|
|
31
|
+
trayId: TrayId;
|
|
32
|
+
getBounds(): Promise<TrayBoundsResult>;
|
|
33
|
+
setMenu(menu: Menu): Promise<void>;
|
|
34
|
+
setTooltip(tooltip: Tooltip): Promise<void>;
|
|
35
|
+
setIcon(icon: Icon): Promise<void>;
|
|
36
|
+
setTitle(title: string): Promise<void>;
|
|
37
|
+
loadExtension(options: ExtensionLoadOptions): Promise<void>;
|
|
38
|
+
commandExtension(ext: string, data: unknown): Promise<void>;
|
|
39
|
+
requestExtension(ext: string, data: unknown): Promise<ExtensionEnvelope[]>;
|
|
40
|
+
extend<TCapability extends object, TOptions = undefined>(extension: TrayExtension<TCapability, TOptions>, options?: TOptions): TrayHandle & TCapability;
|
|
41
|
+
destroy(): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
type TrayScopedEvent = Exclude<TrayEvent, {
|
|
44
|
+
type: "ready";
|
|
45
|
+
}>;
|
|
46
|
+
type TrayEventType = TrayScopedEvent["type"];
|
|
47
|
+
type TrayEventByType<TEvent extends TrayEventType> = Extract<TrayScopedEvent, {
|
|
48
|
+
type: TEvent;
|
|
49
|
+
}>;
|
|
50
|
+
interface EventfulTrayHandle extends TrayHandle {
|
|
51
|
+
extend<TCapability extends object, TOptions = undefined>(extension: TrayExtension<TCapability, TOptions>, options?: TOptions): EventfulTrayHandle & TCapability;
|
|
52
|
+
listenExtension<TData = unknown>(ext: string, handler: (event: ExtensionEnvelope<TData>) => void): () => void;
|
|
53
|
+
listen<TEvent extends TrayEventType>(event: TEvent, handler: (event: TrayEventByType<TEvent>) => void): () => void;
|
|
54
|
+
onMenuClick(handler: (event: TrayEventByType<"menuClick">) => void): () => void;
|
|
55
|
+
onTrayClick(handler: (event: TrayEventByType<"trayClick">) => void): () => void;
|
|
56
|
+
onTrayDoubleClick(handler: (event: TrayEventByType<"trayDoubleClick">) => void): () => void;
|
|
57
|
+
}
|
|
58
|
+
interface ExtensionLoadOptions {
|
|
59
|
+
name: string;
|
|
60
|
+
path: string;
|
|
61
|
+
mountId?: string;
|
|
62
|
+
}
|
|
63
|
+
interface TrayExtensionMountSpec {
|
|
64
|
+
name?: string;
|
|
65
|
+
path?: string;
|
|
66
|
+
mountId?: string;
|
|
67
|
+
}
|
|
68
|
+
interface TrayExtensionContext {
|
|
69
|
+
readonly name: string;
|
|
70
|
+
readonly path: string;
|
|
71
|
+
readonly mountId: string;
|
|
72
|
+
ensureLoaded(): Promise<void>;
|
|
73
|
+
command(data: unknown): Promise<void>;
|
|
74
|
+
request(data: unknown): Promise<ExtensionEnvelope[]>;
|
|
75
|
+
}
|
|
76
|
+
interface TrayExtension<TCapability extends object, TOptions = undefined> {
|
|
77
|
+
readonly name: string;
|
|
78
|
+
readonly path: string;
|
|
79
|
+
resolveMount?(options: TOptions | undefined): TrayExtensionMountSpec;
|
|
80
|
+
extend(tray: TrayHandle, context: TrayExtensionContext, options: TOptions | undefined): TCapability;
|
|
81
|
+
}
|
|
82
|
+
declare const createInitFrame: (clientVersion: string) => ClientFrame;
|
|
83
|
+
interface CreateClientOptions {
|
|
84
|
+
requestIdPrefix?: string;
|
|
85
|
+
}
|
|
86
|
+
interface OpenTrayEventfulClient extends Omit<OpenTrayClient, "createSpace" | "resolveDefaultSpace" | "createSurface"> {
|
|
87
|
+
createSpace(options: SpaceOptions): Promise<EventfulSpaceHandle>;
|
|
88
|
+
resolveDefaultSpace(): Promise<EventfulSpaceHandle>;
|
|
89
|
+
/** @deprecated Use `createSpace`. */
|
|
90
|
+
createSurface(options: SpaceOptions): Promise<EventfulSpaceHandle>;
|
|
91
|
+
}
|
|
92
|
+
declare function createClient(transport: OpenTrayConnection, options?: CreateClientOptions): OpenTrayEventfulClient;
|
|
93
|
+
declare function createClient(transport: OpenTrayTransport, options?: CreateClientOptions): OpenTrayClient;
|
|
94
|
+
declare function createSpaceHandle(transport: OpenTrayConnection, space: SpaceRef, nextRequestId?: () => RequestId): EventfulSpaceHandle;
|
|
95
|
+
declare function createSpaceHandle(transport: OpenTrayTransport, space: SpaceRef, nextRequestId?: () => RequestId): SpaceHandle;
|
|
96
|
+
/** @deprecated Use `createSpaceHandle`. */
|
|
97
|
+
declare const createSurfaceHandle: typeof createSpaceHandle;
|
|
98
|
+
declare function createTrayHandle(transport: OpenTrayConnection, space: SpaceRef, trayId: TrayId, nextRequestId?: () => RequestId): EventfulTrayHandle;
|
|
99
|
+
declare function createTrayHandle(transport: OpenTrayTransport, space: SpaceRef, trayId: TrayId, nextRequestId?: () => RequestId): TrayHandle;
|
|
100
|
+
//#endregion
|
|
101
|
+
export { createTrayHandle as C, createSurfaceHandle as S, TrayExtensionMountSpec as _, ExtensionLoadOptions as a, createInitFrame as b, OpenTrayEventSource as c, SpaceHandle as d, SurfaceHandle as f, TrayExtensionContext as g, TrayExtension as h, EventfulTrayHandle as i, OpenTrayEventfulClient as l, TrayEventType as m, CreateClientOptions as n, OpenTrayClient as o, TrayEventByType as p, EventfulSpaceHandle as r, OpenTrayConnection as s, BrokerEventFrame as t, OpenTrayTransport as u, TrayHandle as v, createSpaceHandle as x, createClient as y };
|
|
102
|
+
//# sourceMappingURL=client-C27qmRfr.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-C27qmRfr.d.mts","names":[],"sources":["../src/client.ts"],"mappings":";;;UAkBiB,iBAAA;EACf,OAAA,CAAQ,KAAA,EAAO,kBAAA,GAAqB,OAAA,CAAQ,WAAA;AAAA;AAAA,KAGlC,gBAAA,GAAmB,OAAO,CAAC,WAAA;EAAe,IAAA;AAAA;AAAA,UAErC,mBAAA;EACf,OAAA,CAAQ,QAAA,GAAW,KAAA,EAAO,gBAAgB;AAAA;AAAA,UAG3B,kBAAA,SAA2B,iBAAA,EAAmB,mBAAmB;AAAA,UAEjE,cAAA;EACf,WAAA,CAAY,OAAA,EAAS,YAAA,GAAe,OAAA,CAAQ,WAAA;EAC5C,mBAAA,IAAuB,OAAA,CAAQ,WAAA;EAba;EAe5C,aAAA,CAAc,OAAA,EAAS,YAAA,GAAe,OAAA,CAAQ,WAAA;AAAA;AAAA,UAG/B,WAAA;EACf,KAAA,EAAO,QAAA;EACP,UAAA,CAAW,OAAA,EAAS,WAAA,GAAc,OAAA,CAAQ,UAAA;AAAA;AAAA,UAG3B,mBAAA,SAA4B,IAAA,CAAK,WAAA;EAChD,UAAA,CAAW,OAAA,EAAS,WAAA,GAAc,OAAA,CAAQ,kBAAA;AAAA;;KAIhC,aAAA,GAAgB,WAAW;AAAA,UAEtB,UAAA;EACf,KAAA,EAAO,QAAA;EACP,MAAA,EAAQ,MAAA;EACR,SAAA,IAAa,OAAA,CAAQ,gBAAA;EACrB,OAAA,CAAQ,IAAA,EAAM,IAAA,GAAO,OAAA;EACrB,UAAA,CAAW,OAAA,EAAS,OAAA,GAAU,OAAA;EAC9B,OAAA,CAAQ,IAAA,EAAM,IAAA,GAAO,OAAA;EACrB,QAAA,CAAS,KAAA,WAAgB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
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { C as createTrayHandle, S as createSurfaceHandle, _ as TrayExtensionMountSpec, a as ExtensionLoadOptions, b as createInitFrame, c as OpenTrayEventSource, d as SpaceHandle, f as SurfaceHandle, g as TrayExtensionContext, h as TrayExtension, i as EventfulTrayHandle, l as OpenTrayEventfulClient, m as TrayEventType, n as CreateClientOptions, o as OpenTrayClient, p as TrayEventByType, r as EventfulSpaceHandle, s as OpenTrayConnection, t as BrokerEventFrame, u as OpenTrayTransport, v as TrayHandle, x as createSpaceHandle, y as createClient } from "./client-C27qmRfr.mjs";
|
|
2
2
|
import { BrokerEndpointIdentity, BrokerEndpointIdentityOptions, PROTOCOL_VERSION, SpaceOptions, SpaceRef, TrayOptions, createBrokerEndpointIdentity, formatBrokerEndpointName, formatBrokerStateRoot, formatUnixSocketPath, formatWindowsPipeName, isSupportedProtocolVersion } from "@opentray/spec";
|
|
3
3
|
|
|
4
4
|
//#region src/sdk.d.ts
|
|
@@ -13,11 +13,11 @@ interface BrokerConnectOptions {
|
|
|
13
13
|
interface CreateTrayOptions extends BrokerConnectOptions {
|
|
14
14
|
space?: SpaceRef;
|
|
15
15
|
}
|
|
16
|
-
declare const createSpace: (options: SpaceOptions, brokerOptions?: BrokerConnectOptions) => Promise<
|
|
16
|
+
declare const createSpace: (options: SpaceOptions, brokerOptions?: BrokerConnectOptions) => Promise<EventfulSpaceHandle>;
|
|
17
17
|
/** @deprecated Use `createSpace`. */
|
|
18
18
|
declare const createSurface: (options: SpaceOptions, brokerOptions?: BrokerConnectOptions) => Promise<SurfaceHandle>;
|
|
19
|
-
declare const resolveDefaultSpace: (brokerOptions?: BrokerConnectOptions) => Promise<
|
|
20
|
-
declare const createTray: (options: TrayOptions, brokerOptions?: CreateTrayOptions) => Promise<
|
|
19
|
+
declare const resolveDefaultSpace: (brokerOptions?: BrokerConnectOptions) => Promise<EventfulSpaceHandle>;
|
|
20
|
+
declare const createTray: (options: TrayOptions, brokerOptions?: CreateTrayOptions) => Promise<EventfulTrayHandle>;
|
|
21
21
|
//#endregion
|
|
22
|
-
export { type BrokerConnectOptions, type BrokerEndpointIdentity, type BrokerEndpointIdentityOptions, type CreateClientOptions, type CreateTrayOptions, type ExtensionLoadOptions, type OpenTrayClient, type OpenTrayTransport, PROTOCOL_VERSION, type SpaceHandle, type SurfaceHandle, type TrayExtension, type TrayExtensionContext, type TrayExtensionMountSpec, type TrayHandle, createBrokerEndpointIdentity, createClient, createInitFrame, createSpace, createSpaceHandle, createSurface, createSurfaceHandle, createTray, createTrayHandle, formatBrokerEndpointName, formatBrokerStateRoot, formatUnixSocketPath, formatWindowsPipeName, isSupportedProtocolVersion, resolveDefaultSpace };
|
|
22
|
+
export { type BrokerConnectOptions, type BrokerEndpointIdentity, type BrokerEndpointIdentityOptions, type BrokerEventFrame, type CreateClientOptions, type CreateTrayOptions, type EventfulSpaceHandle, type EventfulTrayHandle, type ExtensionLoadOptions, type OpenTrayClient, type OpenTrayConnection, type OpenTrayEventSource, type OpenTrayEventfulClient, type OpenTrayTransport, PROTOCOL_VERSION, type SpaceHandle, type SurfaceHandle, type TrayEventByType, type TrayEventType, type TrayExtension, type TrayExtensionContext, type TrayExtensionMountSpec, type TrayHandle, createBrokerEndpointIdentity, createClient, createInitFrame, createSpace, createSpaceHandle, createSurface, createSurfaceHandle, createTray, createTrayHandle, formatBrokerEndpointName, formatBrokerStateRoot, formatUnixSocketPath, formatWindowsPipeName, isSupportedProtocolVersion, resolveDefaultSpace };
|
|
23
23
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/sdk.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/sdk.ts"],"mappings":";;;;UAWiB,oBAAA;EACf,QAAA;EACA,OAAA;EACA,cAAA;EACA,eAAA;EACA,aAAA;EACA,SAAA;AAAA;AAAA,UAGe,iBAAA,SAA0B,oBAAoB;EAC7D,KAAA,GAAQ,QAAA;AAAA;AAAA,cAGG,WAAA,GACX,OAAA,EAAS,YAAA,EACT,aAAA,GAAe,oBAAA,KACd,OAAA,CAAQ,mBAAA;;cAME,aAAA,GACX,OAAA,EAAS,YAAA,EACT,aAAA,GAAe,oBAAA,KACd,OAAA,CAAQ,aAAA;AAAA,cAEE,mBAAA,GACX,aAAA,GAAe,oBAAA,KACd,OAAA,CAAQ,mBAAA;AAAA,cAKE,UAAA,GACX,OAAA,EAAS,WAAA,EACT,aAAA,GAAe,iBAAA,KACd,OAAA,CAAQ,kBAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as connectLocalBroker } from "./local-broker-
|
|
1
|
+
import { t as connectLocalBroker } from "./local-broker-BMxjb-eO.mjs";
|
|
2
2
|
import { PROTOCOL_VERSION, PROTOCOL_VERSION as PROTOCOL_VERSION$1, createBrokerEndpointIdentity, formatBrokerEndpointName, formatBrokerStateRoot, formatUnixSocketPath, formatWindowsPipeName, isSupportedProtocolVersion } from "@opentray/spec";
|
|
3
3
|
//#region src/client.ts
|
|
4
4
|
const createInitFrame = (clientVersion) => ({
|
|
@@ -6,7 +6,7 @@ const createInitFrame = (clientVersion) => ({
|
|
|
6
6
|
protocolVersion: PROTOCOL_VERSION$1,
|
|
7
7
|
clientVersion
|
|
8
8
|
});
|
|
9
|
-
|
|
9
|
+
function createClient(transport, options = {}) {
|
|
10
10
|
const nextRequestId = createRequestIdFactory(options.requestIdPrefix ?? "opentray");
|
|
11
11
|
return {
|
|
12
12
|
async createSpace(spaceOptions) {
|
|
@@ -30,22 +30,24 @@ const createClient = (transport, options = {}) => {
|
|
|
30
30
|
return this.createSpace(spaceOptions);
|
|
31
31
|
}
|
|
32
32
|
};
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
33
|
+
}
|
|
34
|
+
function createSpaceHandle(transport, space, nextRequestId = createRequestIdFactory("opentray")) {
|
|
35
|
+
return {
|
|
36
|
+
space,
|
|
37
|
+
async createTray(options) {
|
|
38
|
+
const requestId = nextRequestId();
|
|
39
|
+
return createTrayHandle(transport, space, expectResponse(await transport.request({
|
|
40
|
+
type: "create-tray",
|
|
41
|
+
requestId,
|
|
42
|
+
space,
|
|
43
|
+
tray: options
|
|
44
|
+
}), requestId, "tray-created").trayId, nextRequestId);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
46
48
|
/** @deprecated Use `createSpaceHandle`. */
|
|
47
49
|
const createSurfaceHandle = createSpaceHandle;
|
|
48
|
-
|
|
50
|
+
function createTrayHandle(transport, space, trayId, nextRequestId = createRequestIdFactory("opentray")) {
|
|
49
51
|
let nextMountOrdinal = 1;
|
|
50
52
|
const nextMountId = (extensionName) => {
|
|
51
53
|
const mountId = `${formatMountIdComponent(extensionName)}.${formatMountIdComponent(trayId)}.${nextMountOrdinal}`;
|
|
@@ -64,6 +66,46 @@ const createTrayHandle = (transport, space, trayId, nextRequestId = createReques
|
|
|
64
66
|
trayId
|
|
65
67
|
}), requestId, "tray-bounds").bounds;
|
|
66
68
|
},
|
|
69
|
+
async setMenu(menu) {
|
|
70
|
+
const requestId = nextRequestId();
|
|
71
|
+
expectResponse(await transport.request({
|
|
72
|
+
type: "set-tray-menu",
|
|
73
|
+
requestId,
|
|
74
|
+
spaceId: space.spaceId,
|
|
75
|
+
trayId,
|
|
76
|
+
menu
|
|
77
|
+
}), requestId, "ack");
|
|
78
|
+
},
|
|
79
|
+
async setTooltip(tooltip) {
|
|
80
|
+
const requestId = nextRequestId();
|
|
81
|
+
expectResponse(await transport.request({
|
|
82
|
+
type: "set-tray-tooltip",
|
|
83
|
+
requestId,
|
|
84
|
+
spaceId: space.spaceId,
|
|
85
|
+
trayId,
|
|
86
|
+
tooltip
|
|
87
|
+
}), requestId, "ack");
|
|
88
|
+
},
|
|
89
|
+
async setIcon(icon) {
|
|
90
|
+
const requestId = nextRequestId();
|
|
91
|
+
expectResponse(await transport.request({
|
|
92
|
+
type: "set-tray-icon",
|
|
93
|
+
requestId,
|
|
94
|
+
spaceId: space.spaceId,
|
|
95
|
+
trayId,
|
|
96
|
+
icon
|
|
97
|
+
}), requestId, "ack");
|
|
98
|
+
},
|
|
99
|
+
async setTitle(title) {
|
|
100
|
+
const requestId = nextRequestId();
|
|
101
|
+
expectResponse(await transport.request({
|
|
102
|
+
type: "set-tray-title",
|
|
103
|
+
requestId,
|
|
104
|
+
spaceId: space.spaceId,
|
|
105
|
+
trayId,
|
|
106
|
+
title
|
|
107
|
+
}), requestId, "ack");
|
|
108
|
+
},
|
|
67
109
|
async loadExtension(options) {
|
|
68
110
|
const requestId = nextRequestId();
|
|
69
111
|
expectResponse(await transport.request({
|
|
@@ -76,15 +118,23 @@ const createTrayHandle = (transport, space, trayId, nextRequestId = createReques
|
|
|
76
118
|
}), requestId, "ack");
|
|
77
119
|
},
|
|
78
120
|
async commandExtension(ext, data) {
|
|
121
|
+
await this.requestExtension(ext, data);
|
|
122
|
+
},
|
|
123
|
+
async requestExtension(ext, data) {
|
|
79
124
|
const requestId = nextRequestId();
|
|
80
|
-
|
|
125
|
+
const response = await transport.request({
|
|
81
126
|
type: "ext-command",
|
|
82
127
|
requestId,
|
|
83
128
|
spaceId: space.spaceId,
|
|
84
129
|
trayId,
|
|
85
130
|
ext,
|
|
86
131
|
data
|
|
87
|
-
})
|
|
132
|
+
});
|
|
133
|
+
if (response.type === "ack") {
|
|
134
|
+
expectResponse(response, requestId, "ack");
|
|
135
|
+
return [];
|
|
136
|
+
}
|
|
137
|
+
return expectResponse(response, requestId, "ext-command-result").events;
|
|
88
138
|
},
|
|
89
139
|
extend(extension, options) {
|
|
90
140
|
const context = createTrayExtensionContext(handle, extension, options, nextMountId);
|
|
@@ -101,8 +151,51 @@ const createTrayHandle = (transport, space, trayId, nextRequestId = createReques
|
|
|
101
151
|
}), requestId, "ack");
|
|
102
152
|
}
|
|
103
153
|
};
|
|
104
|
-
return handle;
|
|
154
|
+
if (!isOpenTrayEventSource(transport)) return handle;
|
|
155
|
+
return attachEventfulTrayHandle(handle, transport, nextMountId);
|
|
156
|
+
}
|
|
157
|
+
const attachEventfulTrayHandle = (handle, source, nextMountId) => {
|
|
158
|
+
const listen = (event, handler) => source.onEvent((frame) => {
|
|
159
|
+
if (frame.type !== "event" || frame.event.type !== event) return;
|
|
160
|
+
if (!isOwnedTrayEvent(frame.event, handle.space.spaceId, handle.trayId)) return;
|
|
161
|
+
handler(frame.event);
|
|
162
|
+
});
|
|
163
|
+
const eventful = {
|
|
164
|
+
...handle,
|
|
165
|
+
listenExtension(ext, handler) {
|
|
166
|
+
return source.onEvent((frame) => {
|
|
167
|
+
if (frame.type !== "ext-event" || frame.ext !== ext) return;
|
|
168
|
+
if (frame.spaceId !== handle.space.spaceId || frame.trayId !== handle.trayId) return;
|
|
169
|
+
handler({
|
|
170
|
+
scope: {
|
|
171
|
+
spaceId: frame.spaceId,
|
|
172
|
+
trayId: frame.trayId,
|
|
173
|
+
ext: frame.ext
|
|
174
|
+
},
|
|
175
|
+
data: frame.data
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
},
|
|
179
|
+
listen,
|
|
180
|
+
onMenuClick(handler) {
|
|
181
|
+
return listen("menuClick", handler);
|
|
182
|
+
},
|
|
183
|
+
onTrayClick(handler) {
|
|
184
|
+
return listen("trayClick", handler);
|
|
185
|
+
},
|
|
186
|
+
onTrayDoubleClick(handler) {
|
|
187
|
+
return listen("trayDoubleClick", handler);
|
|
188
|
+
},
|
|
189
|
+
extend(extension, options) {
|
|
190
|
+
const context = createTrayExtensionContext(eventful, extension, options, nextMountId);
|
|
191
|
+
const capability = extension.extend(eventful, context, options);
|
|
192
|
+
return Object.assign({}, eventful, capability);
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
return eventful;
|
|
105
196
|
};
|
|
197
|
+
const isOwnedTrayEvent = (event, spaceId, trayId) => event.type !== "ready" && event.spaceId === spaceId && event.trayId === trayId;
|
|
198
|
+
const isOpenTrayEventSource = (transport) => "onEvent" in transport && typeof transport.onEvent === "function";
|
|
106
199
|
const createTrayExtensionContext = (tray, extension, options, nextMountId) => {
|
|
107
200
|
const mount = extension.resolveMount?.(options) ?? {};
|
|
108
201
|
const name = mount.name ?? extension.name;
|
|
@@ -128,6 +221,10 @@ const createTrayExtensionContext = (tray, extension, options, nextMountId) => {
|
|
|
128
221
|
async command(data) {
|
|
129
222
|
await ensureLoaded();
|
|
130
223
|
await tray.commandExtension(mountId, data);
|
|
224
|
+
},
|
|
225
|
+
async request(data) {
|
|
226
|
+
await ensureLoaded();
|
|
227
|
+
return tray.requestExtension(mountId, data);
|
|
131
228
|
}
|
|
132
229
|
};
|
|
133
230
|
};
|
|
@@ -156,6 +253,7 @@ const requestIdOf = (frame) => {
|
|
|
156
253
|
case "tray-created":
|
|
157
254
|
case "tray-bounds":
|
|
158
255
|
case "ack":
|
|
256
|
+
case "ext-command-result":
|
|
159
257
|
case "daemon-health": return frame.requestId;
|
|
160
258
|
case "error": return frame.requestId;
|
|
161
259
|
case "ready":
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["PROTOCOL_VERSION"],"sources":["../src/client.ts","../src/sdk.ts"],"sourcesContent":["import {\n PROTOCOL_VERSION,\n type ClientFrame,\n type ClientRequestFrame,\n type RequestId,\n type ServerFrame,\n type SpaceOptions,\n type SpaceRef,\n type TrayBoundsResult,\n type TrayId,\n type TrayOptions,\n} from \"@opentray/spec\";\n\nexport interface OpenTrayTransport {\n request(frame: ClientRequestFrame): Promise<ServerFrame>;\n}\n\nexport interface OpenTrayClient {\n createSpace(options: SpaceOptions): Promise<SpaceHandle>;\n resolveDefaultSpace(): Promise<SpaceHandle>;\n /** @deprecated Use `createSpace`. */\n createSurface(options: SpaceOptions): Promise<SpaceHandle>;\n}\n\nexport interface SpaceHandle {\n space: SpaceRef;\n createTray(options: TrayOptions): Promise<TrayHandle>;\n}\n\n/** @deprecated Use `SpaceHandle`. */\nexport type SurfaceHandle = SpaceHandle;\n\nexport interface TrayHandle {\n space: SpaceRef;\n trayId: TrayId;\n getBounds(): Promise<TrayBoundsResult>;\n loadExtension(options: ExtensionLoadOptions): Promise<void>;\n commandExtension(ext: string, data: unknown): Promise<void>;\n extend<TCapability extends object, TOptions = undefined>(\n extension: TrayExtension<TCapability, TOptions>,\n options?: TOptions,\n ): TrayHandle & TCapability;\n destroy(): Promise<void>;\n}\n\nexport interface ExtensionLoadOptions {\n name: string;\n path: string;\n mountId?: string;\n}\n\nexport interface TrayExtensionMountSpec {\n name?: string;\n path?: string;\n mountId?: string;\n}\n\nexport interface TrayExtensionContext {\n readonly name: string;\n readonly path: string;\n readonly mountId: string;\n ensureLoaded(): Promise<void>;\n command(data: unknown): Promise<void>;\n}\n\nexport interface TrayExtension<TCapability extends object, TOptions = undefined> {\n readonly name: string;\n readonly path: string;\n resolveMount?(options: TOptions | undefined): TrayExtensionMountSpec;\n extend(tray: TrayHandle, context: TrayExtensionContext, options: TOptions | undefined): TCapability;\n}\n\nexport const createInitFrame = (clientVersion: string): ClientFrame => ({\n type: \"init\",\n protocolVersion: PROTOCOL_VERSION,\n clientVersion,\n});\n\nexport interface CreateClientOptions {\n requestIdPrefix?: string;\n}\n\nexport const createClient = (\n transport: OpenTrayTransport,\n options: CreateClientOptions = {},\n): OpenTrayClient => {\n const nextRequestId = createRequestIdFactory(options.requestIdPrefix ?? \"opentray\");\n\n return {\n async createSpace(spaceOptions): Promise<SpaceHandle> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"create-space\",\n requestId,\n ...spaceOptions,\n });\n const space = expectResponse(response, requestId, \"space-created\").space;\n return createSpaceHandle(transport, space, nextRequestId);\n },\n async resolveDefaultSpace(): Promise<SpaceHandle> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"resolve-default-space\",\n requestId,\n });\n const space = expectResponse(response, requestId, \"default-space\").space;\n return createSpaceHandle(transport, space, nextRequestId);\n },\n async createSurface(spaceOptions): Promise<SpaceHandle> {\n return this.createSpace(spaceOptions);\n },\n };\n};\n\nexport const createSpaceHandle = (\n transport: OpenTrayTransport,\n space: SpaceRef,\n nextRequestId: () => RequestId = createRequestIdFactory(\"opentray\"),\n): SpaceHandle => ({\n space,\n async createTray(options: TrayOptions): Promise<TrayHandle> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"create-tray\",\n requestId,\n space,\n tray: options,\n });\n const frame = expectResponse(response, requestId, \"tray-created\");\n return createTrayHandle(transport, space, frame.trayId, nextRequestId);\n },\n});\n\n/** @deprecated Use `createSpaceHandle`. */\nexport const createSurfaceHandle = createSpaceHandle;\n\nexport const createTrayHandle = (\n transport: OpenTrayTransport,\n space: SpaceRef,\n trayId: TrayId,\n nextRequestId: () => RequestId = createRequestIdFactory(\"opentray\"),\n): TrayHandle => {\n let nextMountOrdinal = 1;\n const nextMountId = (extensionName: string): string => {\n const mountId = `${formatMountIdComponent(extensionName)}.${formatMountIdComponent(trayId)}.${nextMountOrdinal}`;\n nextMountOrdinal += 1;\n return mountId;\n };\n const handle: TrayHandle = {\n space,\n trayId,\n async getBounds(): Promise<TrayBoundsResult> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"get-tray-bounds\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n });\n return expectResponse(response, requestId, \"tray-bounds\").bounds;\n },\n async loadExtension(options): Promise<void> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"load-ext\",\n requestId,\n spaceId: space.spaceId,\n name: options.name,\n path: options.path,\n ...(options.mountId === undefined ? {} : { mountId: options.mountId }),\n });\n expectResponse(response, requestId, \"ack\");\n },\n async commandExtension(ext: string, data: unknown): Promise<void> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"ext-command\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n ext,\n data,\n });\n expectResponse(response, requestId, \"ack\");\n },\n extend<TCapability extends object, TOptions = undefined>(\n extension: TrayExtension<TCapability, TOptions>,\n options?: TOptions,\n ): TrayHandle & TCapability {\n const context = createTrayExtensionContext(handle, extension, options, nextMountId);\n const capability = extension.extend(handle, context, options);\n return Object.assign({}, handle, capability);\n },\n async destroy(): Promise<void> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"destroy-tray\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n });\n expectResponse(response, requestId, \"ack\");\n },\n };\n return handle;\n};\n\nconst createTrayExtensionContext = <TCapability extends object, TOptions>(\n tray: TrayHandle,\n extension: TrayExtension<TCapability, TOptions>,\n options: TOptions | undefined,\n nextMountId: (extensionName: string) => string,\n): TrayExtensionContext => {\n const mount = extension.resolveMount?.(options) ?? {};\n const name = mount.name ?? extension.name;\n const path = mount.path ?? extension.path;\n const mountId = mount.mountId ?? nextMountId(name);\n let loadPromise: Promise<void> | undefined;\n\n const ensureLoaded = async (): Promise<void> => {\n if (loadPromise === undefined) {\n loadPromise = tray.loadExtension({ name, path, mountId }).catch((error: unknown) => {\n loadPromise = undefined;\n throw error;\n });\n }\n await loadPromise;\n };\n\n return {\n name,\n path,\n mountId,\n ensureLoaded,\n async command(data: unknown): Promise<void> {\n await ensureLoaded();\n await tray.commandExtension(mountId, data);\n },\n };\n};\n\nconst formatMountIdComponent = (value: string): string => {\n const formatted = value.replaceAll(/[^a-zA-Z0-9._+-]/g, \"_\");\n return formatted.length > 0 ? formatted : \"ext\";\n};\n\nconst createRequestIdFactory = (prefix: string): (() => RequestId) => {\n let next = 1;\n return () => {\n const requestId = `${prefix}-${next}`;\n next += 1;\n return requestId;\n };\n};\n\nconst expectResponse = <TType extends ServerFrame[\"type\"]>(\n frame: ServerFrame,\n requestId: RequestId,\n type: TType,\n): Extract<ServerFrame, { type: TType }> => {\n if (frame.type === \"error\") {\n throw new Error(`${frame.code}: ${frame.message}`);\n }\n if (frame.type !== type) {\n throw new Error(`expected ${type} for ${requestId}, received ${frame.type}`);\n }\n if (requestIdOf(frame) !== requestId) {\n throw new Error(`expected response for ${requestId}, received ${requestIdOf(frame) ?? \"none\"}`);\n }\n return frame as Extract<ServerFrame, { type: TType }>;\n};\n\nconst requestIdOf = (frame: ServerFrame): RequestId | undefined => {\n switch (frame.type) {\n case \"space-created\":\n case \"default-space\":\n case \"tray-created\":\n case \"tray-bounds\":\n case \"ack\":\n case \"daemon-health\":\n return frame.requestId;\n case \"error\":\n return frame.requestId;\n case \"ready\":\n case \"event\":\n case \"ext-event\":\n return undefined;\n }\n};\n","import type { SpaceOptions, SpaceRef, TrayOptions } from \"@opentray/spec\";\n\nimport { createClient, createSpaceHandle, type SpaceHandle, type SurfaceHandle, type TrayHandle } from \"./client\";\nimport { connectLocalBroker } from \"./local-broker\";\n\nexport interface BrokerConnectOptions {\n endpoint?: string;\n homeDir?: string;\n packageVersion?: string;\n protocolVersion?: number;\n clientVersion?: string;\n autoStart?: boolean;\n}\n\nexport interface CreateTrayOptions extends BrokerConnectOptions {\n space?: SpaceRef;\n}\n\nexport const createSpace = async (\n options: SpaceOptions,\n brokerOptions: BrokerConnectOptions = {},\n): Promise<SpaceHandle> => {\n const connection = await connectLocalBroker(brokerOptions);\n return createClient(connection).createSpace(options);\n};\n\n/** @deprecated Use `createSpace`. */\nexport const createSurface = async (\n options: SpaceOptions,\n brokerOptions: BrokerConnectOptions = {},\n): Promise<SurfaceHandle> => createSpace(options, brokerOptions);\n\nexport const resolveDefaultSpace = async (\n brokerOptions: BrokerConnectOptions = {},\n): Promise<SpaceHandle> => {\n const connection = await connectLocalBroker(brokerOptions);\n return createClient(connection).resolveDefaultSpace();\n};\n\nexport const createTray = async (\n options: TrayOptions,\n brokerOptions: CreateTrayOptions = {},\n): Promise<TrayHandle> => {\n const { space, ...connectOptions } = brokerOptions;\n const connection = await connectLocalBroker(connectOptions);\n const spaceHandle = space ? createSpaceHandle(connection, space) : await createClient(connection).resolveDefaultSpace();\n return spaceHandle.createTray(options);\n};\n"],"mappings":";;;AAwEA,MAAa,mBAAmB,mBAAwC;CACtE,MAAM;CACN,iBAAiBA;CACjB;AACF;AAMA,MAAa,gBACX,WACA,UAA+B,CAAC,MACb;CACnB,MAAM,gBAAgB,uBAAuB,QAAQ,mBAAmB,UAAU;CAElF,OAAO;EACL,MAAM,YAAY,cAAoC;GACpD,MAAM,YAAY,cAAc;GAMhC,MAAM,QAAQ,eAAe,MALN,UAAU,QAAQ;IACvC,MAAM;IACN;IACA,GAAG;GACL,CAAC,GACsC,WAAW,eAAe,EAAE;GACnE,OAAO,kBAAkB,WAAW,OAAO,aAAa;EAC1D;EACA,MAAM,sBAA4C;GAChD,MAAM,YAAY,cAAc;GAKhC,MAAM,QAAQ,eAAe,MAJN,UAAU,QAAQ;IACvC,MAAM;IACN;GACF,CAAC,GACsC,WAAW,eAAe,EAAE;GACnE,OAAO,kBAAkB,WAAW,OAAO,aAAa;EAC1D;EACA,MAAM,cAAc,cAAoC;GACtD,OAAO,KAAK,YAAY,YAAY;EACtC;CACF;AACF;AAEA,MAAa,qBACX,WACA,OACA,gBAAiC,uBAAuB,UAAU,OACjD;CACjB;CACA,MAAM,WAAW,SAA2C;EAC1D,MAAM,YAAY,cAAc;EAQhC,OAAO,iBAAiB,WAAW,OADrB,eAAe,MANN,UAAU,QAAQ;GACvC,MAAM;GACN;GACA;GACA,MAAM;EACR,CAAC,GACsC,WAAW,cACJ,EAAE,QAAQ,aAAa;CACvE;AACF;;AAGA,MAAa,sBAAsB;AAEnC,MAAa,oBACX,WACA,OACA,QACA,gBAAiC,uBAAuB,UAAU,MACnD;CACf,IAAI,mBAAmB;CACvB,MAAM,eAAe,kBAAkC;EACrD,MAAM,UAAU,GAAG,uBAAuB,aAAa,EAAE,GAAG,uBAAuB,MAAM,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;AAGA,MAAa,gBAAgB,OAC3B,SACA,gBAAsC,CAAC,MACZ,YAAY,SAAS,aAAa;AAE/D,MAAa,sBAAsB,OACjC,gBAAsC,CAAC,MACd;CAEzB,OAAO,aAAa,MADK,mBAAmB,aAAa,CAC3B,EAAE,oBAAoB;AACtD;AAEA,MAAa,aAAa,OACxB,SACA,gBAAmC,CAAC,MACZ;CACxB,MAAM,EAAE,OAAO,GAAG,mBAAmB;CACrC,MAAM,aAAa,MAAM,mBAAmB,cAAc;CAE1D,QADoB,QAAQ,kBAAkB,YAAY,KAAK,IAAI,MAAM,aAAa,UAAU,EAAE,oBAAoB,GACnG,WAAW,OAAO;AACvC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["PROTOCOL_VERSION"],"sources":["../src/client.ts","../src/sdk.ts"],"sourcesContent":["import {\n PROTOCOL_VERSION,\n type ClientFrame,\n type ClientRequestFrame,\n type ExtensionEnvelope,\n type Icon,\n type Menu,\n type RequestId,\n type ServerFrame,\n type SpaceOptions,\n type SpaceRef,\n type Tooltip,\n type TrayBoundsResult,\n type TrayEvent,\n type TrayId,\n type TrayOptions,\n} from \"@opentray/spec\";\n\nexport interface OpenTrayTransport {\n request(frame: ClientRequestFrame): Promise<ServerFrame>;\n}\n\nexport type BrokerEventFrame = Extract<ServerFrame, { type: \"event\" | \"ext-event\" }>;\n\nexport interface OpenTrayEventSource {\n onEvent(listener: (frame: BrokerEventFrame) => void): () => void;\n}\n\nexport interface OpenTrayConnection extends OpenTrayTransport, OpenTrayEventSource {}\n\nexport interface OpenTrayClient {\n createSpace(options: SpaceOptions): Promise<SpaceHandle>;\n resolveDefaultSpace(): Promise<SpaceHandle>;\n /** @deprecated Use `createSpace`. */\n createSurface(options: SpaceOptions): Promise<SpaceHandle>;\n}\n\nexport interface SpaceHandle {\n space: SpaceRef;\n createTray(options: TrayOptions): Promise<TrayHandle>;\n}\n\nexport interface EventfulSpaceHandle extends Omit<SpaceHandle, \"createTray\"> {\n createTray(options: TrayOptions): Promise<EventfulTrayHandle>;\n}\n\n/** @deprecated Use `SpaceHandle`. */\nexport type SurfaceHandle = SpaceHandle;\n\nexport interface TrayHandle {\n space: SpaceRef;\n trayId: TrayId;\n getBounds(): Promise<TrayBoundsResult>;\n setMenu(menu: Menu): Promise<void>;\n setTooltip(tooltip: Tooltip): Promise<void>;\n setIcon(icon: Icon): Promise<void>;\n setTitle(title: string): Promise<void>;\n loadExtension(options: ExtensionLoadOptions): Promise<void>;\n commandExtension(ext: string, data: unknown): Promise<void>;\n requestExtension(ext: string, data: unknown): Promise<ExtensionEnvelope[]>;\n extend<TCapability extends object, TOptions = undefined>(\n extension: TrayExtension<TCapability, TOptions>,\n options?: TOptions,\n ): TrayHandle & TCapability;\n destroy(): Promise<void>;\n}\n\nexport type TrayScopedEvent = Exclude<TrayEvent, { type: \"ready\" }>;\nexport type TrayEventType = TrayScopedEvent[\"type\"];\nexport type TrayEventByType<TEvent extends TrayEventType> = Extract<TrayScopedEvent, { type: TEvent }>;\n\nexport interface EventfulTrayHandle extends TrayHandle {\n extend<TCapability extends object, TOptions = undefined>(\n extension: TrayExtension<TCapability, TOptions>,\n options?: TOptions,\n ): EventfulTrayHandle & TCapability;\n listenExtension<TData = unknown>(\n ext: string,\n handler: (event: ExtensionEnvelope<TData>) => void,\n ): () => void;\n listen<TEvent extends TrayEventType>(\n event: TEvent,\n handler: (event: TrayEventByType<TEvent>) => void,\n ): () => void;\n onMenuClick(handler: (event: TrayEventByType<\"menuClick\">) => void): () => void;\n onTrayClick(handler: (event: TrayEventByType<\"trayClick\">) => void): () => void;\n onTrayDoubleClick(handler: (event: TrayEventByType<\"trayDoubleClick\">) => void): () => void;\n}\n\nexport interface ExtensionLoadOptions {\n name: string;\n path: string;\n mountId?: string;\n}\n\nexport interface TrayExtensionMountSpec {\n name?: string;\n path?: string;\n mountId?: string;\n}\n\nexport interface TrayExtensionContext {\n readonly name: string;\n readonly path: string;\n readonly mountId: string;\n ensureLoaded(): Promise<void>;\n command(data: unknown): Promise<void>;\n request(data: unknown): Promise<ExtensionEnvelope[]>;\n}\n\nexport interface TrayExtension<TCapability extends object, TOptions = undefined> {\n readonly name: string;\n readonly path: string;\n resolveMount?(options: TOptions | undefined): TrayExtensionMountSpec;\n extend(tray: TrayHandle, context: TrayExtensionContext, options: TOptions | undefined): TCapability;\n}\n\nexport const createInitFrame = (clientVersion: string): ClientFrame => ({\n type: \"init\",\n protocolVersion: PROTOCOL_VERSION,\n clientVersion,\n});\n\nexport interface CreateClientOptions {\n requestIdPrefix?: string;\n}\n\nexport interface OpenTrayEventfulClient extends Omit<OpenTrayClient, \"createSpace\" | \"resolveDefaultSpace\" | \"createSurface\"> {\n createSpace(options: SpaceOptions): Promise<EventfulSpaceHandle>;\n resolveDefaultSpace(): Promise<EventfulSpaceHandle>;\n /** @deprecated Use `createSpace`. */\n createSurface(options: SpaceOptions): Promise<EventfulSpaceHandle>;\n}\n\nexport function createClient(\n transport: OpenTrayConnection,\n options?: CreateClientOptions,\n): OpenTrayEventfulClient;\nexport function createClient(transport: OpenTrayTransport, options?: CreateClientOptions): OpenTrayClient;\nexport function createClient(\n transport: OpenTrayTransport,\n options: CreateClientOptions = {},\n): OpenTrayClient | OpenTrayEventfulClient {\n const nextRequestId = createRequestIdFactory(options.requestIdPrefix ?? \"opentray\");\n\n return {\n async createSpace(spaceOptions): Promise<SpaceHandle> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"create-space\",\n requestId,\n ...spaceOptions,\n });\n const space = expectResponse(response, requestId, \"space-created\").space;\n return createSpaceHandle(transport, space, nextRequestId);\n },\n async resolveDefaultSpace(): Promise<SpaceHandle> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"resolve-default-space\",\n requestId,\n });\n const space = expectResponse(response, requestId, \"default-space\").space;\n return createSpaceHandle(transport, space, nextRequestId);\n },\n async createSurface(spaceOptions): Promise<SpaceHandle> {\n return this.createSpace(spaceOptions);\n },\n };\n};\n\nexport function createSpaceHandle(\n transport: OpenTrayConnection,\n space: SpaceRef,\n nextRequestId?: () => RequestId,\n): EventfulSpaceHandle;\nexport function createSpaceHandle(\n transport: OpenTrayTransport,\n space: SpaceRef,\n nextRequestId?: () => RequestId,\n): SpaceHandle;\nexport function createSpaceHandle(\n transport: OpenTrayTransport,\n space: SpaceRef,\n nextRequestId: () => RequestId = createRequestIdFactory(\"opentray\"),\n): SpaceHandle | EventfulSpaceHandle {\n return {\n space,\n async createTray(options: TrayOptions): Promise<TrayHandle | EventfulTrayHandle> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"create-tray\",\n requestId,\n space,\n tray: options,\n });\n const frame = expectResponse(response, requestId, \"tray-created\");\n return createTrayHandle(transport, space, frame.trayId, nextRequestId);\n },\n };\n}\n\n/** @deprecated Use `createSpaceHandle`. */\nexport const createSurfaceHandle = createSpaceHandle;\n\nexport function createTrayHandle(\n transport: OpenTrayConnection,\n space: SpaceRef,\n trayId: TrayId,\n nextRequestId?: () => RequestId,\n): EventfulTrayHandle;\nexport function createTrayHandle(\n transport: OpenTrayTransport,\n space: SpaceRef,\n trayId: TrayId,\n nextRequestId?: () => RequestId,\n): TrayHandle;\nexport function createTrayHandle(\n transport: OpenTrayTransport,\n space: SpaceRef,\n trayId: TrayId,\n nextRequestId: () => RequestId = createRequestIdFactory(\"opentray\"),\n): TrayHandle | EventfulTrayHandle {\n let nextMountOrdinal = 1;\n const nextMountId = (extensionName: string): string => {\n const mountId = `${formatMountIdComponent(extensionName)}.${formatMountIdComponent(trayId)}.${nextMountOrdinal}`;\n nextMountOrdinal += 1;\n return mountId;\n };\n const handle: TrayHandle = {\n space,\n trayId,\n async getBounds(): Promise<TrayBoundsResult> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"get-tray-bounds\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n });\n return expectResponse(response, requestId, \"tray-bounds\").bounds;\n },\n async setMenu(menu: Menu): Promise<void> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"set-tray-menu\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n menu,\n });\n expectResponse(response, requestId, \"ack\");\n },\n async setTooltip(tooltip: Tooltip): Promise<void> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"set-tray-tooltip\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n tooltip,\n });\n expectResponse(response, requestId, \"ack\");\n },\n async setIcon(icon: Icon): Promise<void> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"set-tray-icon\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n icon,\n });\n expectResponse(response, requestId, \"ack\");\n },\n async setTitle(title: string): Promise<void> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"set-tray-title\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n title,\n });\n expectResponse(response, requestId, \"ack\");\n },\n async loadExtension(options): Promise<void> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"load-ext\",\n requestId,\n spaceId: space.spaceId,\n name: options.name,\n path: options.path,\n ...(options.mountId === undefined ? {} : { mountId: options.mountId }),\n });\n expectResponse(response, requestId, \"ack\");\n },\n async commandExtension(ext: string, data: unknown): Promise<void> {\n await this.requestExtension(ext, data);\n },\n async requestExtension(ext: string, data: unknown): Promise<ExtensionEnvelope[]> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"ext-command\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n ext,\n data,\n });\n if (response.type === \"ack\") {\n expectResponse(response, requestId, \"ack\");\n return [];\n }\n return expectResponse(response, requestId, \"ext-command-result\").events;\n },\n extend<TCapability extends object, TOptions = undefined>(\n extension: TrayExtension<TCapability, TOptions>,\n options?: TOptions,\n ): TrayHandle & TCapability {\n const context = createTrayExtensionContext(handle, extension, options, nextMountId);\n const capability = extension.extend(handle, context, options);\n return Object.assign({}, handle, capability);\n },\n async destroy(): Promise<void> {\n const requestId = nextRequestId();\n const response = await transport.request({\n type: \"destroy-tray\",\n requestId,\n spaceId: space.spaceId,\n trayId,\n });\n expectResponse(response, requestId, \"ack\");\n },\n };\n if (!isOpenTrayEventSource(transport)) {\n return handle;\n }\n return attachEventfulTrayHandle(handle, transport, nextMountId);\n}\n\nconst attachEventfulTrayHandle = (\n handle: TrayHandle,\n source: OpenTrayEventSource,\n nextMountId: (extensionName: string) => string,\n): EventfulTrayHandle => {\n const listen: EventfulTrayHandle[\"listen\"] = (event, handler) =>\n source.onEvent((frame) => {\n if (frame.type !== \"event\" || frame.event.type !== event) {\n return;\n }\n if (!isOwnedTrayEvent(frame.event, handle.space.spaceId, handle.trayId)) {\n return;\n }\n handler(frame.event as TrayEventByType<typeof event>);\n });\n\n const eventful: EventfulTrayHandle = {\n ...handle,\n listenExtension<TData = unknown>(ext: string, handler: (event: ExtensionEnvelope<TData>) => void) {\n return source.onEvent((frame) => {\n if (frame.type !== \"ext-event\" || frame.ext !== ext) {\n return;\n }\n if (frame.spaceId !== handle.space.spaceId || frame.trayId !== handle.trayId) {\n return;\n }\n handler({\n scope: { spaceId: frame.spaceId, trayId: frame.trayId, ext: frame.ext },\n data: frame.data as TData,\n });\n });\n },\n listen,\n onMenuClick(handler) {\n return listen(\"menuClick\", handler);\n },\n onTrayClick(handler) {\n return listen(\"trayClick\", handler);\n },\n onTrayDoubleClick(handler) {\n return listen(\"trayDoubleClick\", handler);\n },\n extend<TCapability extends object, TOptions = undefined>(\n extension: TrayExtension<TCapability, TOptions>,\n options?: TOptions,\n ): EventfulTrayHandle & TCapability {\n const context = createTrayExtensionContext(eventful, extension, options, nextMountId);\n const capability = extension.extend(eventful, context, options);\n return Object.assign({}, eventful, capability);\n },\n };\n return eventful;\n};\n\nconst isOwnedTrayEvent = (event: TrayEvent, spaceId: string, trayId: string): event is TrayScopedEvent =>\n event.type !== \"ready\" && event.spaceId === spaceId && event.trayId === trayId;\n\nconst isOpenTrayEventSource = (transport: OpenTrayTransport): transport is OpenTrayConnection =>\n \"onEvent\" in transport && typeof transport.onEvent === \"function\";\n\nconst createTrayExtensionContext = <TCapability extends object, TOptions>(\n tray: TrayHandle,\n extension: TrayExtension<TCapability, TOptions>,\n options: TOptions | undefined,\n nextMountId: (extensionName: string) => string,\n): TrayExtensionContext => {\n const mount = extension.resolveMount?.(options) ?? {};\n const name = mount.name ?? extension.name;\n const path = mount.path ?? extension.path;\n const mountId = mount.mountId ?? nextMountId(name);\n let loadPromise: Promise<void> | undefined;\n\n const ensureLoaded = async (): Promise<void> => {\n if (loadPromise === undefined) {\n loadPromise = tray.loadExtension({ name, path, mountId }).catch((error: unknown) => {\n loadPromise = undefined;\n throw error;\n });\n }\n await loadPromise;\n };\n\n return {\n name,\n path,\n mountId,\n ensureLoaded,\n async command(data: unknown): Promise<void> {\n await ensureLoaded();\n await tray.commandExtension(mountId, data);\n },\n async request(data: unknown): Promise<ExtensionEnvelope[]> {\n await ensureLoaded();\n return tray.requestExtension(mountId, data);\n },\n };\n};\n\nconst formatMountIdComponent = (value: string): string => {\n const formatted = value.replaceAll(/[^a-zA-Z0-9._+-]/g, \"_\");\n return formatted.length > 0 ? formatted : \"ext\";\n};\n\nconst createRequestIdFactory = (prefix: string): (() => RequestId) => {\n let next = 1;\n return () => {\n const requestId = `${prefix}-${next}`;\n next += 1;\n return requestId;\n };\n};\n\nconst expectResponse = <TType extends ServerFrame[\"type\"]>(\n frame: ServerFrame,\n requestId: RequestId,\n type: TType,\n): Extract<ServerFrame, { type: TType }> => {\n if (frame.type === \"error\") {\n throw new Error(`${frame.code}: ${frame.message}`);\n }\n if (frame.type !== type) {\n throw new Error(`expected ${type} for ${requestId}, received ${frame.type}`);\n }\n if (requestIdOf(frame) !== requestId) {\n throw new Error(`expected response for ${requestId}, received ${requestIdOf(frame) ?? \"none\"}`);\n }\n return frame as Extract<ServerFrame, { type: TType }>;\n};\n\nconst requestIdOf = (frame: ServerFrame): RequestId | undefined => {\n switch (frame.type) {\n case \"space-created\":\n case \"default-space\":\n case \"tray-created\":\n case \"tray-bounds\":\n case \"ack\":\n case \"ext-command-result\":\n case \"daemon-health\":\n return frame.requestId;\n case \"error\":\n return frame.requestId;\n case \"ready\":\n case \"event\":\n case \"ext-event\":\n return undefined;\n }\n};\n","import type { SpaceOptions, SpaceRef, TrayOptions } from \"@opentray/spec\";\n\nimport {\n createClient,\n createSpaceHandle,\n type EventfulSpaceHandle,\n type EventfulTrayHandle,\n type SurfaceHandle,\n} from \"./client\";\nimport { connectLocalBroker } from \"./local-broker\";\n\nexport interface BrokerConnectOptions {\n endpoint?: string;\n homeDir?: string;\n packageVersion?: string;\n protocolVersion?: number;\n clientVersion?: string;\n autoStart?: boolean;\n}\n\nexport interface CreateTrayOptions extends BrokerConnectOptions {\n space?: SpaceRef;\n}\n\nexport const createSpace = async (\n options: SpaceOptions,\n brokerOptions: BrokerConnectOptions = {},\n): Promise<EventfulSpaceHandle> => {\n const connection = await connectLocalBroker(brokerOptions);\n return createClient(connection).createSpace(options);\n};\n\n/** @deprecated Use `createSpace`. */\nexport const createSurface = async (\n options: SpaceOptions,\n brokerOptions: BrokerConnectOptions = {},\n): Promise<SurfaceHandle> => createSpace(options, brokerOptions);\n\nexport const resolveDefaultSpace = async (\n brokerOptions: BrokerConnectOptions = {},\n): Promise<EventfulSpaceHandle> => {\n const connection = await connectLocalBroker(brokerOptions);\n return createClient(connection).resolveDefaultSpace();\n};\n\nexport const createTray = async (\n options: TrayOptions,\n brokerOptions: CreateTrayOptions = {},\n): Promise<EventfulTrayHandle> => {\n const { space, ...connectOptions } = brokerOptions;\n const connection = await connectLocalBroker(connectOptions);\n const spaceHandle = space ? createSpaceHandle(connection, space) : await createClient(connection).resolveDefaultSpace();\n return spaceHandle.createTray(options);\n};\n"],"mappings":";;;AAqHA,MAAa,mBAAmB,mBAAwC;CACtE,MAAM;CACN,iBAAiBA;CACjB;AACF;AAkBA,SAAgB,aACd,WACA,UAA+B,CAAC,GACS;CACzC,MAAM,gBAAgB,uBAAuB,QAAQ,mBAAmB,UAAU;CAElF,OAAO;EACL,MAAM,YAAY,cAAoC;GACpD,MAAM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CAEnD,IAAI,MAAM,SAAS,MACjB,MAAM,IAAI,MAAM,YAAY,KAAK,OAAO,UAAU,aAAa,MAAM,MAAM;CAE7E,IAAI,YAAY,KAAK,MAAM,WACzB,MAAM,IAAI,MAAM,yBAAyB,UAAU,aAAa,YAAY,KAAK,KAAK,QAAQ;CAEhG,OAAO;AACT;AAEA,MAAM,eAAe,UAA8C;CACjE,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,iBACH,OAAO,MAAM;EACf,KAAK,SACH,OAAO,MAAM;EACf,KAAK;EACL,KAAK;EACL,KAAK,aACH;CACJ;AACF;;;AChdA,MAAa,cAAc,OACzB,SACA,gBAAsC,CAAC,MACN;CAEjC,OAAO,aAAa,MADK,mBAAmB,aAAa,CAC3B,EAAE,YAAY,OAAO;AACrD;;AAGA,MAAa,gBAAgB,OAC3B,SACA,gBAAsC,CAAC,MACZ,YAAY,SAAS,aAAa;AAE/D,MAAa,sBAAsB,OACjC,gBAAsC,CAAC,MACN;CAEjC,OAAO,aAAa,MADK,mBAAmB,aAAa,CAC3B,EAAE,oBAAoB;AACtD;AAEA,MAAa,aAAa,OACxB,SACA,gBAAmC,CAAC,MACJ;CAChC,MAAM,EAAE,OAAO,GAAG,mBAAmB;CACrC,MAAM,aAAa,MAAM,mBAAmB,cAAc;CAE1D,QADoB,QAAQ,kBAAkB,YAAY,KAAK,IAAI,MAAM,aAAa,UAAU,EAAE,oBAAoB,GACnG,WAAW,OAAO;AACvC"}
|
|
@@ -1,12 +1,35 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
-
import { PROTOCOL_VERSION, createBrokerEndpointIdentity, formatUnixSocketPath, formatWindowsPipeName, parseServerFrame } from "@opentray/spec";
|
|
2
|
+
import { PROTOCOL_VERSION, createBrokerEndpointIdentity, formatUnixSocketPath, formatWindowsPipeName, parseServerFrame, sanitizeCallerLabel } from "@opentray/spec";
|
|
3
3
|
import { createConnection } from "node:net";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { basename, dirname, join } from "node:path";
|
|
6
7
|
import { constants } from "node:fs";
|
|
7
8
|
import { access, chmod, mkdir, open, readFile, rm, unlink, writeFile } from "node:fs/promises";
|
|
8
9
|
import { spawn } from "node:child_process";
|
|
9
|
-
|
|
10
|
+
//#region src/daemon/caller-label.ts
|
|
11
|
+
/**
|
|
12
|
+
* Derives a caller label using the precedence: explicit > npm_package_name >
|
|
13
|
+
* script basename > neutral default. The result is always sanitized to a
|
|
14
|
+
* filesystem- and process-safe component, so callers can use it directly in
|
|
15
|
+
* endpoint identity, runtime directories, and process titles.
|
|
16
|
+
*/
|
|
17
|
+
const resolveCallerLabel = (options = {}) => {
|
|
18
|
+
const env = options.env ?? process.env;
|
|
19
|
+
const argv = options.argv ?? process.argv;
|
|
20
|
+
const candidates = [];
|
|
21
|
+
if (options.explicit !== void 0 && options.explicit.length > 0) candidates.push(options.explicit);
|
|
22
|
+
const npmName = options.npmPackageName ?? env.npm_package_name;
|
|
23
|
+
if (typeof npmName === "string" && npmName.length > 0) candidates.push(npmName);
|
|
24
|
+
const scriptPath = options.scriptPath ?? argv[1];
|
|
25
|
+
if (typeof scriptPath === "string" && scriptPath.length > 0) candidates.push(basename(scriptPath));
|
|
26
|
+
for (const candidate of candidates) {
|
|
27
|
+
const sanitized = sanitizeCallerLabel(candidate);
|
|
28
|
+
if (sanitized.length > 0) return sanitized;
|
|
29
|
+
}
|
|
30
|
+
return sanitizeCallerLabel(void 0);
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
10
33
|
//#region src/daemon/native-target.ts
|
|
11
34
|
const resolveBrokerNativeTarget = (platform = process.platform, arch = process.arch) => {
|
|
12
35
|
const packageOs = platformToPackageOs(platform);
|
|
@@ -78,7 +101,9 @@ const commandForBinary = (binary, paths, cwd) => {
|
|
|
78
101
|
"--package-version",
|
|
79
102
|
paths.packageVersion,
|
|
80
103
|
"--protocol-version",
|
|
81
|
-
`${paths.protocolVersion}
|
|
104
|
+
`${paths.protocolVersion}`,
|
|
105
|
+
"--caller-label",
|
|
106
|
+
paths.callerLabel
|
|
82
107
|
]
|
|
83
108
|
};
|
|
84
109
|
if (cwd !== void 0) command.cwd = cwd;
|
|
@@ -115,8 +140,14 @@ const findWorkspaceRoot = async (start) => {
|
|
|
115
140
|
current = parent;
|
|
116
141
|
}
|
|
117
142
|
};
|
|
143
|
+
const resolveDevBrokerBinaryPath = (workspaceRoot, platform = process.platform) => join(workspaceRoot, "target", "debug", platform === "win32" ? "opentray.exe" : "opentray");
|
|
144
|
+
const terminateWorkspaceDevBrokerProcess = async (workspaceRoot, platform = process.platform) => {
|
|
145
|
+
if (platform !== "win32") return;
|
|
146
|
+
await terminateWindowsProcessByExecutable(resolveDevBrokerBinaryPath(workspaceRoot, platform));
|
|
147
|
+
};
|
|
118
148
|
const ensureDevBrokerBinary = async (workspaceRoot) => {
|
|
119
|
-
const binary =
|
|
149
|
+
const binary = resolveDevBrokerBinaryPath(workspaceRoot);
|
|
150
|
+
await terminateWorkspaceDevBrokerProcess(workspaceRoot);
|
|
120
151
|
await runCargoBuild(workspaceRoot);
|
|
121
152
|
return binary;
|
|
122
153
|
};
|
|
@@ -146,6 +177,45 @@ const exists = async (path) => {
|
|
|
146
177
|
return false;
|
|
147
178
|
}
|
|
148
179
|
};
|
|
180
|
+
const terminateWindowsProcessByExecutable = (binary) => new Promise((resolve, reject) => {
|
|
181
|
+
const child = spawn("powershell.exe", [
|
|
182
|
+
"-NoProfile",
|
|
183
|
+
"-NonInteractive",
|
|
184
|
+
"-ExecutionPolicy",
|
|
185
|
+
"Bypass",
|
|
186
|
+
"-Command",
|
|
187
|
+
String.raw`
|
|
188
|
+
$ErrorActionPreference = 'Stop'
|
|
189
|
+
$target = [System.IO.Path]::GetFullPath(${powerShellString(binary)})
|
|
190
|
+
$processes = @(Get-CimInstance Win32_Process -Filter "Name = 'opentray.exe'" | Where-Object {
|
|
191
|
+
$_.ExecutablePath -and ([System.IO.Path]::GetFullPath($_.ExecutablePath) -ieq $target)
|
|
192
|
+
})
|
|
193
|
+
foreach ($process in $processes) {
|
|
194
|
+
Stop-Process -Id $process.ProcessId -Force -ErrorAction Stop
|
|
195
|
+
}
|
|
196
|
+
foreach ($process in $processes) {
|
|
197
|
+
Wait-Process -Id $process.ProcessId -Timeout 5 -ErrorAction SilentlyContinue
|
|
198
|
+
}
|
|
199
|
+
`
|
|
200
|
+
], { stdio: [
|
|
201
|
+
"ignore",
|
|
202
|
+
"ignore",
|
|
203
|
+
"pipe"
|
|
204
|
+
] });
|
|
205
|
+
let stderr = "";
|
|
206
|
+
child.stderr?.on("data", (chunk) => {
|
|
207
|
+
stderr += String(chunk);
|
|
208
|
+
});
|
|
209
|
+
child.once("error", reject);
|
|
210
|
+
child.once("exit", (code) => {
|
|
211
|
+
if (code === 0) {
|
|
212
|
+
resolve();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
reject(/* @__PURE__ */ new Error(`failed to stop running dev broker before cargo build: ${stderr.trim() || code}`));
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
const powerShellString = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
149
219
|
const isNodeError$1 = (error) => error instanceof Error && "code" in error;
|
|
150
220
|
//#endregion
|
|
151
221
|
//#region src/daemon/lifecycle.ts
|
|
@@ -163,7 +233,8 @@ const createNodeDaemonDriver = (cliEntrypoint) => ({
|
|
|
163
233
|
...process.env,
|
|
164
234
|
OPENTRAY_DAEMON_HOME: paths.homeDir,
|
|
165
235
|
OPENTRAY_DAEMON_PACKAGE_VERSION: paths.packageVersion,
|
|
166
|
-
OPENTRAY_DAEMON_CLI_ENTRYPOINT: cliEntrypoint
|
|
236
|
+
OPENTRAY_DAEMON_CLI_ENTRYPOINT: cliEntrypoint,
|
|
237
|
+
OPENTRAY_DAEMON_CALLER_LABEL: paths.callerLabel
|
|
167
238
|
},
|
|
168
239
|
stdio: resolveBrokerStdio(process.env[DAEMON_STDIO_ENV])
|
|
169
240
|
});
|
|
@@ -315,15 +386,19 @@ const readPackageVersion = async (packageJsonUrl) => {
|
|
|
315
386
|
const isPackageJsonWithVersion = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && "version" in value && typeof value.version === "string";
|
|
316
387
|
//#endregion
|
|
317
388
|
//#region src/daemon/paths.ts
|
|
318
|
-
const resolveDaemonPaths = ({ homeDir, packageVersion, platform = process.platform }) => {
|
|
319
|
-
const identity = createBrokerEndpointIdentity({ packageVersion }
|
|
389
|
+
const resolveDaemonPaths = ({ homeDir, packageVersion, callerLabel, platform = process.platform }) => {
|
|
390
|
+
const identity = createBrokerEndpointIdentity(callerLabel === void 0 ? { packageVersion } : {
|
|
391
|
+
packageVersion,
|
|
392
|
+
callerLabel
|
|
393
|
+
});
|
|
320
394
|
const normalizedHome = homeDir.replace(/[\\/]+$/u, "");
|
|
321
|
-
const stateRoot = `${normalizedHome}/.opentray/${identity.packageVersion}`;
|
|
395
|
+
const stateRoot = `${normalizedHome}/.opentray/${identity.packageVersion}/${identity.callerLabel}`;
|
|
322
396
|
const runtimeDir = `${stateRoot}/runtime`;
|
|
323
397
|
const endpoint = platform === "win32" ? formatWindowsPipeName(identity) : formatUnixSocketPath(normalizedHome, identity);
|
|
324
398
|
return {
|
|
325
399
|
homeDir: normalizedHome,
|
|
326
400
|
packageVersion: identity.packageVersion,
|
|
401
|
+
callerLabel: identity.callerLabel,
|
|
327
402
|
protocolVersion: identity.protocolVersion,
|
|
328
403
|
stateRoot,
|
|
329
404
|
runtimeDir,
|
|
@@ -339,9 +414,11 @@ const packageJsonUrl = new URL("../package.json", import.meta.url);
|
|
|
339
414
|
const connectLocalBroker = async (options = {}) => {
|
|
340
415
|
const packageVersion = options.packageVersion ?? await readPackageVersion(packageJsonUrl);
|
|
341
416
|
const clientVersion = options.clientVersion ?? packageVersion;
|
|
417
|
+
const callerLabel = options.callerLabel ?? resolveCallerLabel();
|
|
342
418
|
const paths = resolveDaemonPaths({
|
|
343
419
|
homeDir: options.homeDir ?? process.env.OPENTRAY_HOME ?? homedir(),
|
|
344
|
-
packageVersion
|
|
420
|
+
packageVersion,
|
|
421
|
+
callerLabel
|
|
345
422
|
});
|
|
346
423
|
const endpoint = options.endpoint ?? paths.endpoint;
|
|
347
424
|
const autoStart = options.autoStart ?? endpoint === paths.endpoint;
|
|
@@ -353,13 +430,14 @@ const connectLocalBroker = async (options = {}) => {
|
|
|
353
430
|
driver: options.daemonDriver ?? createNodeDaemonDriver(cliEntrypoint)
|
|
354
431
|
});
|
|
355
432
|
}
|
|
356
|
-
const connection = new LocalBrokerConnection(await connectSocket(endpoint), endpoint);
|
|
433
|
+
const connection = new LocalBrokerConnection(await connectSocket(endpoint), endpoint, callerLabel);
|
|
357
434
|
await connection.init(clientVersion, options.protocolVersion ?? PROTOCOL_VERSION);
|
|
358
435
|
return connection;
|
|
359
436
|
};
|
|
360
437
|
var LocalBrokerConnection = class {
|
|
361
438
|
socket;
|
|
362
439
|
endpoint;
|
|
440
|
+
callerLabel;
|
|
363
441
|
sessionId = "";
|
|
364
442
|
/** @deprecated Use `sessionId`. */
|
|
365
443
|
leaseId = "";
|
|
@@ -367,9 +445,10 @@ var LocalBrokerConnection = class {
|
|
|
367
445
|
listeners = /* @__PURE__ */ new Set();
|
|
368
446
|
pending = /* @__PURE__ */ new Map();
|
|
369
447
|
ready;
|
|
370
|
-
constructor(socket, endpoint) {
|
|
448
|
+
constructor(socket, endpoint, callerLabel) {
|
|
371
449
|
this.socket = socket;
|
|
372
450
|
this.endpoint = endpoint;
|
|
451
|
+
this.callerLabel = callerLabel;
|
|
373
452
|
socket.setEncoding("utf8");
|
|
374
453
|
socket.on("data", (chunk) => {
|
|
375
454
|
this.consume(String(chunk));
|
|
@@ -433,7 +512,7 @@ var LocalBrokerConnection = class {
|
|
|
433
512
|
dispatchLine(line) {
|
|
434
513
|
const parsed = parseServerFrame(line);
|
|
435
514
|
if (!parsed.ok || parsed.frame === void 0) {
|
|
436
|
-
this.rejectAll(new Error(parsed.error ?? "invalid server frame"));
|
|
515
|
+
this.rejectAll(/* @__PURE__ */ new Error(`${parsed.error ?? "invalid server frame"}: ${line}`));
|
|
437
516
|
return;
|
|
438
517
|
}
|
|
439
518
|
this.dispatchFrame(parsed.frame);
|
|
@@ -451,8 +530,12 @@ var LocalBrokerConnection = class {
|
|
|
451
530
|
this.pending.delete(frame.requestId);
|
|
452
531
|
return;
|
|
453
532
|
}
|
|
454
|
-
this.ready
|
|
455
|
-
|
|
533
|
+
if (this.ready) {
|
|
534
|
+
this.ready.reject(error);
|
|
535
|
+
this.ready = void 0;
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
this.rejectAll(error);
|
|
456
539
|
return;
|
|
457
540
|
}
|
|
458
541
|
const requestId = responseRequestId(frame);
|
|
@@ -488,6 +571,7 @@ const responseRequestId = (frame) => {
|
|
|
488
571
|
case "tray-created":
|
|
489
572
|
case "tray-bounds":
|
|
490
573
|
case "ack":
|
|
574
|
+
case "ext-command-result":
|
|
491
575
|
case "daemon-health": return frame.requestId;
|
|
492
576
|
case "ready":
|
|
493
577
|
case "event":
|
|
@@ -502,4 +586,4 @@ const resolveCliEntrypoint = () => {
|
|
|
502
586
|
//#endregion
|
|
503
587
|
export { inspectDaemon as a, stopDaemon as c, createNodeDaemonDriver as i, resolveDaemonPaths as n, restartDaemon as o, readPackageVersion as r, startDaemon as s, connectLocalBroker as t };
|
|
504
588
|
|
|
505
|
-
//# sourceMappingURL=local-broker-
|
|
589
|
+
//# sourceMappingURL=local-broker-BMxjb-eO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local-broker-BMxjb-eO.mjs","names":["isNodeError"],"sources":["../src/daemon/caller-label.ts","../src/daemon/native-target.ts","../src/daemon/broker-command.ts","../src/daemon/lifecycle.ts","../src/daemon/package-version.ts","../src/daemon/paths.ts","../src/local-broker.ts"],"sourcesContent":["import { basename } from \"node:path\";\n\nimport { sanitizeCallerLabel } from \"@opentray/spec\";\n\nexport interface CallerLabelSources {\n /** Explicit developer-provided label, highest precedence. */\n readonly explicit?: string;\n /** `npm_package_name` environment value. */\n readonly npmPackageName?: string;\n /** Script path resolved from `process.argv[1]` or equivalent. */\n readonly scriptPath?: string;\n}\n\nexport interface ResolveCallerLabelOptions extends Partial<CallerLabelSources> {\n env?: NodeJS.ProcessEnv;\n argv?: readonly string[];\n}\n\n/**\n * Derives a caller label using the precedence: explicit > npm_package_name >\n * script basename > neutral default. The result is always sanitized to a\n * filesystem- and process-safe component, so callers can use it directly in\n * endpoint identity, runtime directories, and process titles.\n */\nexport const resolveCallerLabel = (options: ResolveCallerLabelOptions = {}): string => {\n const env = options.env ?? process.env;\n const argv = options.argv ?? process.argv;\n\n const candidates: string[] = [];\n if (options.explicit !== undefined && options.explicit.length > 0) {\n candidates.push(options.explicit);\n }\n const npmName = options.npmPackageName ?? env.npm_package_name;\n if (typeof npmName === \"string\" && npmName.length > 0) {\n candidates.push(npmName);\n }\n const scriptPath = options.scriptPath ?? argv[1];\n if (typeof scriptPath === \"string\" && scriptPath.length > 0) {\n candidates.push(basename(scriptPath));\n }\n\n for (const candidate of candidates) {\n const sanitized = sanitizeCallerLabel(candidate);\n if (sanitized.length > 0) {\n return sanitized;\n }\n }\n\n return sanitizeCallerLabel(undefined);\n};\n","export type BrokerPackageOs = \"darwin\" | \"linux\" | \"windows\";\nexport type BrokerArch = \"arm64\" | \"x64\";\n\nexport interface BrokerNativeTarget {\n packageName: string;\n binaryRelativePath: string;\n}\n\nexport const resolveBrokerNativeTarget = (\n platform: string = process.platform,\n arch: string = process.arch,\n): BrokerNativeTarget => {\n const packageOs = platformToPackageOs(platform);\n const nativeArch = normalizeArch(arch);\n return {\n packageName: `@opentray/${packageOs}-${nativeArch}`,\n binaryRelativePath: `bin/${packageOs === \"windows\" ? \"opentray.exe\" : \"opentray\"}`,\n };\n};\n\nconst platformToPackageOs = (platform: string): BrokerPackageOs => {\n switch (platform) {\n case \"darwin\":\n case \"linux\":\n return platform;\n case \"win32\":\n return \"windows\";\n default:\n throw new MissingPlatformBrokerBinaryError(\n `unsupported OpenTray broker platform: ${platform}`,\n platform,\n process.arch,\n );\n }\n};\n\nconst normalizeArch = (arch: string): BrokerArch => {\n switch (arch) {\n case \"arm64\":\n case \"x64\":\n return arch;\n default:\n throw new MissingPlatformBrokerBinaryError(\n `unsupported OpenTray broker architecture: ${arch}`,\n process.platform,\n arch,\n );\n }\n};\n\nexport class MissingPlatformBrokerBinaryError extends Error {\n readonly code = \"OPENTRAY_MISSING_PLATFORM_BROKER_BINARY\";\n readonly platform: string;\n readonly arch: string;\n readonly packageName: string | undefined;\n readonly binaryPath: string | undefined;\n\n constructor(\n message: string,\n platform: string,\n arch: string,\n options: {\n packageName?: string;\n binaryPath?: string;\n cause?: unknown;\n } = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = \"MissingPlatformBrokerBinaryError\";\n this.platform = platform;\n this.arch = arch;\n this.packageName = options.packageName;\n this.binaryPath = options.binaryPath;\n }\n}\n","import { access, chmod } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport { spawn } from \"node:child_process\";\n\nimport type { DaemonPaths } from \"./paths\";\nimport { MissingPlatformBrokerBinaryError, resolveBrokerNativeTarget } from \"./native-target\";\n\nexport interface BrokerCommand {\n command: string;\n args: string[];\n cwd?: string;\n}\n\nconst sourceUrl = import.meta.url;\nconst requireFromSource = createRequire(sourceUrl);\n\nexport interface ResolveBrokerCommandOptions {\n env?: NodeJS.ProcessEnv;\n platform?: NodeJS.Platform;\n arch?: string;\n sourceDir?: string;\n resolvePackageJson?: (packageName: string) => string | undefined;\n findWorkspaceRoot?: (start: string) => Promise<string | undefined>;\n ensureDevBrokerBinary?: (workspaceRoot: string) => Promise<string>;\n}\n\nexport const resolveBrokerCommand = async (\n paths: DaemonPaths,\n options: ResolveBrokerCommandOptions = {},\n): Promise<BrokerCommand> => {\n const env = options.env ?? process.env;\n const explicit = env.OPENTRAY_BROKER_BIN;\n if (explicit !== undefined && explicit.length > 0) {\n return commandForBinary(explicit, paths);\n }\n\n const sourceDir = options.sourceDir ?? dirname(fileURLToPath(sourceUrl));\n const workspaceRoot = await (options.findWorkspaceRoot ?? findWorkspaceRoot)(sourceDir);\n if (workspaceRoot !== undefined) {\n const binary = await (options.ensureDevBrokerBinary ?? ensureDevBrokerBinary)(workspaceRoot);\n return commandForBinary(binary, paths, workspaceRoot);\n }\n\n const platform = options.platform ?? process.platform;\n const arch = options.arch ?? process.arch;\n const installedBinary = await resolveInstalledBrokerBinary({\n platform,\n arch,\n resolvePackageJson: options.resolvePackageJson ?? resolvePackageJson,\n });\n if (installedBinary !== undefined) {\n return commandForBinary(installedBinary, paths);\n }\n\n const target = resolveBrokerNativeTarget(platform, arch);\n throw new MissingPlatformBrokerBinaryError(\n `unable to resolve OpenTray broker binary for ${platform}/${arch}; install ${target.packageName} or set OPENTRAY_BROKER_BIN`,\n platform,\n arch,\n { packageName: target.packageName },\n );\n};\n\nconst commandForBinary = (binary: string, paths: DaemonPaths, cwd?: string): BrokerCommand => {\n const command: BrokerCommand = {\n command: binary,\n args: [\n \"broker\",\n \"--endpoint\",\n paths.endpoint,\n \"--ready-file\",\n paths.readyFile,\n \"--package-version\",\n paths.packageVersion,\n \"--protocol-version\",\n `${paths.protocolVersion}`,\n \"--caller-label\",\n paths.callerLabel,\n ],\n };\n if (cwd !== undefined) {\n command.cwd = cwd;\n }\n return command;\n};\n\ninterface ResolveInstalledBrokerBinaryOptions {\n platform: NodeJS.Platform;\n arch: string;\n resolvePackageJson: (packageName: string) => string | undefined;\n}\n\nexport const resolveInstalledBrokerBinary = async ({\n platform,\n arch,\n resolvePackageJson,\n}: ResolveInstalledBrokerBinaryOptions): Promise<string | undefined> => {\n const target = resolveBrokerNativeTarget(platform, arch);\n const packageJsonPath = resolvePackageJson(target.packageName);\n if (packageJsonPath === undefined) {\n return undefined;\n }\n\n const binary = join(dirname(packageJsonPath), target.binaryRelativePath);\n if (!(await exists(binary))) {\n throw new MissingPlatformBrokerBinaryError(\n `OpenTray broker package ${target.packageName} is installed but missing ${target.binaryRelativePath}`,\n platform,\n arch,\n {\n packageName: target.packageName,\n binaryPath: binary,\n },\n );\n }\n\n if (platform !== \"win32\") {\n await chmod(binary, 0o755);\n }\n\n return binary;\n};\n\nconst resolvePackageJson = (packageName: string): string | undefined => {\n try {\n return requireFromSource.resolve(`${packageName}/package.json`);\n } catch (error) {\n if (isNodeError(error) && error.code === \"MODULE_NOT_FOUND\") {\n return undefined;\n }\n throw error;\n }\n};\n\nconst findWorkspaceRoot = async (start: string): Promise<string | undefined> => {\n let current = start;\n while (true) {\n if (await exists(join(current, \"Cargo.toml\"))) {\n if (await exists(join(current, \"crates\", \"opentray-bin\", \"Cargo.toml\"))) {\n return current;\n }\n }\n\n const parent = dirname(current);\n if (parent === current) {\n return undefined;\n }\n current = parent;\n }\n};\n\nexport const resolveDevBrokerBinaryPath = (\n workspaceRoot: string,\n platform: NodeJS.Platform = process.platform,\n): string =>\n join(workspaceRoot, \"target\", \"debug\", platform === \"win32\" ? \"opentray.exe\" : \"opentray\");\n\nexport const terminateWorkspaceDevBrokerProcess = async (\n workspaceRoot: string,\n platform: NodeJS.Platform = process.platform,\n): Promise<void> => {\n if (platform !== \"win32\") {\n return;\n }\n await terminateWindowsProcessByExecutable(resolveDevBrokerBinaryPath(workspaceRoot, platform));\n};\n\nconst ensureDevBrokerBinary = async (workspaceRoot: string): Promise<string> => {\n const binary = resolveDevBrokerBinaryPath(workspaceRoot);\n await terminateWorkspaceDevBrokerProcess(workspaceRoot);\n await runCargoBuild(workspaceRoot);\n return binary;\n};\n\nconst runCargoBuild = (workspaceRoot: string): Promise<void> =>\n new Promise((resolve, reject) => {\n const child = spawn(\"cargo\", [\"build\", \"-p\", \"opentray-bin\"], {\n cwd: workspaceRoot,\n stdio: process.env.OPENTRAY_BROKER_BUILD_LOGS === \"1\" ? \"inherit\" : \"ignore\",\n });\n child.once(\"error\", reject);\n child.once(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(new Error(`cargo build -p opentray-bin failed with code ${code ?? \"unknown\"}`));\n });\n });\n\nconst exists = async (path: string): Promise<boolean> => {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n};\n\nconst terminateWindowsProcessByExecutable = (binary: string): Promise<void> =>\n new Promise((resolve, reject) => {\n const script = String.raw`\n$ErrorActionPreference = 'Stop'\n$target = [System.IO.Path]::GetFullPath(${powerShellString(binary)})\n$processes = @(Get-CimInstance Win32_Process -Filter \"Name = 'opentray.exe'\" | Where-Object {\n $_.ExecutablePath -and ([System.IO.Path]::GetFullPath($_.ExecutablePath) -ieq $target)\n})\nforeach ($process in $processes) {\n Stop-Process -Id $process.ProcessId -Force -ErrorAction Stop\n}\nforeach ($process in $processes) {\n Wait-Process -Id $process.ProcessId -Timeout 5 -ErrorAction SilentlyContinue\n}\n`;\n const child = spawn(\n \"powershell.exe\",\n [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-Command\", script],\n { stdio: [\"ignore\", \"ignore\", \"pipe\"] },\n );\n let stderr = \"\";\n child.stderr?.on(\"data\", (chunk: Buffer | string) => {\n stderr += String(chunk);\n });\n child.once(\"error\", reject);\n child.once(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(new Error(`failed to stop running dev broker before cargo build: ${stderr.trim() || code}`));\n });\n });\n\nconst powerShellString = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\n\nconst isNodeError = (error: unknown): error is NodeJS.ErrnoException =>\n error instanceof Error && \"code\" in error;\n","import { constants } from \"node:fs\";\nimport { mkdir, open, readFile, rm, unlink, writeFile } from \"node:fs/promises\";\nimport { spawn } from \"node:child_process\";\n\nimport { resolveBrokerCommand } from \"./broker-command\";\nimport type { DaemonPaths } from \"./paths\";\n\nconst DAEMON_STDIO_ENV = \"OPENTRAY_DAEMON_STDIO\";\n\nexport type DaemonStartResult =\n | { status: \"started\"; pid: number; paths: DaemonPaths }\n | { status: \"already-running\"; pid: number; paths: DaemonPaths };\n\nexport type DaemonStopResult =\n | { status: \"stopped\"; pid: number; paths: DaemonPaths }\n | { status: \"not-running\"; paths: DaemonPaths };\n\nexport type DaemonInspectResult =\n | { status: \"running\"; pid: number; paths: DaemonPaths }\n | { status: \"not-running\"; paths: DaemonPaths; stalePid?: number };\n\nexport interface DaemonDriver {\n isAlive(pid: number): Promise<boolean>;\n spawnBroker(paths: DaemonPaths): Promise<number>;\n stop(pid: number): Promise<void>;\n}\n\nexport interface StartDaemonOptions {\n paths: DaemonPaths;\n driver: DaemonDriver;\n lockTimeoutMs?: number;\n}\n\nexport interface StopDaemonOptions {\n paths: DaemonPaths;\n driver: DaemonDriver;\n}\n\nexport interface InspectDaemonOptions {\n paths: DaemonPaths;\n driver: DaemonDriver;\n}\n\nexport const createNodeDaemonDriver = (cliEntrypoint: string): DaemonDriver => ({\n async isAlive(pid) {\n return isProcessAlive(pid);\n },\n async spawnBroker(paths) {\n const broker = await resolveBrokerCommand(paths);\n // The caller label flows to the broker via both a CLI flag and an env var.\n // The broker uses it to bind the per-caller endpoint and to set its own\n // process title so task managers show the owning application.\n const child = spawn(broker.command, broker.args, {\n cwd: broker.cwd,\n detached: true,\n env: {\n ...process.env,\n OPENTRAY_DAEMON_HOME: paths.homeDir,\n OPENTRAY_DAEMON_PACKAGE_VERSION: paths.packageVersion,\n OPENTRAY_DAEMON_CLI_ENTRYPOINT: cliEntrypoint,\n OPENTRAY_DAEMON_CALLER_LABEL: paths.callerLabel,\n },\n stdio: resolveBrokerStdio(process.env[DAEMON_STDIO_ENV]),\n });\n\n child.unref();\n return child.pid ?? 0;\n },\n async stop(pid) {\n process.kill(pid, \"SIGTERM\");\n },\n});\n\nexport const resolveBrokerStdio = (\n value: string | undefined,\n): \"ignore\" | \"inherit\" => {\n return value === \"inherit\" ? \"inherit\" : \"ignore\";\n};\n\nexport const startDaemon = async ({\n paths,\n driver,\n lockTimeoutMs = 1_000,\n}: StartDaemonOptions): Promise<DaemonStartResult> => {\n await mkdir(paths.runtimeDir, { recursive: true });\n\n const lock = await acquireLock(paths.lockFile, lockTimeoutMs);\n try {\n const existingPid = await readPid(paths.pidFile);\n if (existingPid !== undefined && (await driver.isAlive(existingPid))) {\n return { status: \"already-running\", pid: existingPid, paths };\n }\n\n await cleanupRuntimeFiles(paths);\n const pid = await driver.spawnBroker(paths);\n if (!Number.isInteger(pid) || pid <= 0) {\n throw new Error(\"daemon broker process did not expose a valid pid\");\n }\n await writeFile(paths.pidFile, `${pid}\\n`, \"utf8\");\n await waitForReadyFile(paths.readyFile, driver, pid);\n return { status: \"started\", pid, paths };\n } finally {\n await lock.release();\n }\n};\n\nexport const stopDaemon = async ({ paths, driver }: StopDaemonOptions): Promise<DaemonStopResult> => {\n const pid = await readPid(paths.pidFile);\n if (pid === undefined || !(await driver.isAlive(pid))) {\n await cleanupRuntimeFiles(paths);\n return { status: \"not-running\", paths };\n }\n\n await driver.stop(pid);\n await waitUntilStopped(driver, pid);\n await cleanupRuntimeFiles(paths);\n return { status: \"stopped\", pid, paths };\n};\n\nexport const restartDaemon = async (options: StartDaemonOptions): Promise<DaemonStartResult> => {\n await stopDaemon({ paths: options.paths, driver: options.driver });\n return startDaemon(options);\n};\n\nexport const inspectDaemon = async ({ paths, driver }: InspectDaemonOptions): Promise<DaemonInspectResult> => {\n const pid = await readPid(paths.pidFile);\n if (pid !== undefined && (await driver.isAlive(pid))) {\n return { status: \"running\", pid, paths };\n }\n\n await cleanupRuntimeFiles(paths);\n return pid === undefined\n ? { status: \"not-running\", paths }\n : { status: \"not-running\", paths, stalePid: pid };\n};\n\nconst readPid = async (pidFile: string): Promise<number | undefined> => {\n try {\n const content = await readFile(pidFile, \"utf8\");\n const pid = Number.parseInt(content.trim(), 10);\n return Number.isInteger(pid) && pid > 0 ? pid : undefined;\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return undefined;\n }\n throw error;\n }\n};\n\nconst cleanupRuntimeFiles = async (paths: DaemonPaths): Promise<void> => {\n await rm(paths.readyFile, { force: true });\n await rm(paths.pidFile, { force: true });\n if (process.platform !== \"win32\") {\n await rm(paths.endpoint, { force: true });\n }\n};\n\nconst waitUntilStopped = async (driver: DaemonDriver, pid: number): Promise<void> => {\n for (let attempt = 0; attempt < 20; attempt += 1) {\n if (!(await driver.isAlive(pid))) {\n return;\n }\n await sleep(50);\n }\n};\n\nconst waitForReadyFile = async (\n readyFile: string,\n driver: DaemonDriver,\n pid: number,\n): Promise<void> => {\n for (let attempt = 0; attempt < 40; attempt += 1) {\n try {\n await readFile(readyFile, \"utf8\");\n return;\n } catch (error) {\n if (!isNodeError(error) || error.code !== \"ENOENT\") {\n throw error;\n }\n if (!(await driver.isAlive(pid))) {\n throw new Error(\n `daemon broker exited before readiness: pid=${pid}; readyFile=${readyFile}; set ${DAEMON_STDIO_ENV}=inherit to inspect broker stderr`,\n );\n }\n await sleep(50);\n }\n }\n\n throw new Error(`timed out waiting for daemon readiness: ${readyFile}`);\n};\n\nconst acquireLock = async (\n lockFile: string,\n timeoutMs: number,\n): Promise<{\n release(): Promise<void>;\n}> => {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() <= deadline) {\n try {\n const handle = await open(lockFile, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY);\n await handle.writeFile(`${process.pid}\\n`, \"utf8\");\n return {\n async release() {\n await handle.close();\n await unlink(lockFile).catch((error: unknown) => {\n if (!isNodeError(error) || error.code !== \"ENOENT\") {\n throw error;\n }\n });\n },\n };\n } catch (error) {\n if (isNodeError(error) && error.code === \"EEXIST\") {\n await sleep(25);\n continue;\n }\n throw error;\n }\n }\n\n throw new Error(`timed out acquiring daemon lock: ${lockFile}`);\n};\n\nconst isProcessAlive = (pid: number): boolean => {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n};\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst isNodeError = (error: unknown): error is NodeJS.ErrnoException =>\n error instanceof Error && \"code\" in error;\n","import { readFile } from \"node:fs/promises\";\n\nexport const readPackageVersion = async (packageJsonUrl: URL): Promise<string> => {\n const value: unknown = JSON.parse(await readFile(packageJsonUrl, \"utf8\"));\n if (!isPackageJsonWithVersion(value)) {\n throw new Error(`package.json is missing a string version: ${packageJsonUrl.href}`);\n }\n\n return value.version;\n};\n\nconst isPackageJsonWithVersion = (value: unknown): value is { version: string } =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"version\" in value &&\n typeof value.version === \"string\";\n","import { createBrokerEndpointIdentity, formatUnixSocketPath, formatWindowsPipeName } from \"@opentray/spec\";\n\nexport interface DaemonPathOptions {\n homeDir: string;\n packageVersion: string;\n callerLabel?: string;\n platform?: NodeJS.Platform;\n}\n\nexport interface DaemonPaths {\n homeDir: string;\n packageVersion: string;\n callerLabel: string;\n protocolVersion: number;\n stateRoot: string;\n runtimeDir: string;\n endpoint: string;\n pidFile: string;\n lockFile: string;\n readyFile: string;\n}\n\nexport const resolveDaemonPaths = ({\n homeDir,\n packageVersion,\n callerLabel,\n platform = process.platform,\n}: DaemonPathOptions): DaemonPaths => {\n const identity = createBrokerEndpointIdentity(\n callerLabel === undefined ? { packageVersion } : { packageVersion, callerLabel },\n );\n const normalizedHome = homeDir.replace(/[\\\\/]+$/u, \"\");\n const stateRoot = `${normalizedHome}/.opentray/${identity.packageVersion}/${identity.callerLabel}`;\n const runtimeDir = `${stateRoot}/runtime`;\n const endpoint =\n platform === \"win32\" ? formatWindowsPipeName(identity) : formatUnixSocketPath(normalizedHome, identity);\n\n return {\n homeDir: normalizedHome,\n packageVersion: identity.packageVersion,\n callerLabel: identity.callerLabel,\n protocolVersion: identity.protocolVersion,\n stateRoot,\n runtimeDir,\n endpoint,\n pidFile: `${runtimeDir}/broker.pid`,\n lockFile: `${runtimeDir}/broker.lock`,\n readyFile: `${runtimeDir}/ready.json`,\n };\n};\n","import { createConnection, type Socket } from \"node:net\";\nimport { homedir } from \"node:os\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n PROTOCOL_VERSION,\n parseServerFrame,\n type BrokerEndpointIdentityOptions,\n type ClientRequestFrame,\n type RequestId,\n type ServerFrame,\n} from \"@opentray/spec\";\n\nimport type { OpenTrayTransport } from \"./client\";\nimport { resolveCallerLabel } from \"./daemon/caller-label\";\nimport { createNodeDaemonDriver, startDaemon, type DaemonDriver } from \"./daemon/lifecycle\";\nimport { readPackageVersion } from \"./daemon/package-version\";\nimport { resolveDaemonPaths } from \"./daemon/paths\";\n\nconst packageJsonUrl = new URL(\"../package.json\", import.meta.url);\n\nexport type BrokerEventFrame = Extract<ServerFrame, { type: \"event\" | \"ext-event\" }>;\n\nexport interface LocalBrokerClient extends OpenTrayTransport {\n readonly endpoint: string;\n readonly callerLabel: string;\n readonly sessionId: string;\n /** @deprecated Use `sessionId`. */\n readonly leaseId: string;\n onEvent(listener: (frame: BrokerEventFrame) => void): () => void;\n close(): Promise<void>;\n}\n\nexport interface ConnectLocalBrokerOptions extends Partial<BrokerEndpointIdentityOptions> {\n endpoint?: string;\n homeDir?: string;\n clientVersion?: string;\n autoStart?: boolean;\n daemonDriver?: DaemonDriver;\n cliEntrypoint?: string;\n callerLabel?: string;\n}\n\ninterface PendingRequest {\n resolve(frame: ServerFrame): void;\n reject(error: Error): void;\n}\n\ninterface BrokerSocket {\n setEncoding(encoding: BufferEncoding): void;\n on(event: \"data\", listener: (chunk: Buffer | string) => void): void;\n on(event: \"error\", listener: (error: Error) => void): void;\n on(event: \"close\", listener: () => void): void;\n once(event: \"connect\", listener: () => void): void;\n once(event: \"error\", listener: (error: Error) => void): void;\n off(event: \"error\", listener: (error: Error) => void): void;\n write(data: string): void;\n end(callback: () => void): void;\n}\n\nexport const connectLocalBroker = async (\n options: ConnectLocalBrokerOptions = {},\n): Promise<LocalBrokerClient> => {\n const packageVersion = options.packageVersion ?? (await readPackageVersion(packageJsonUrl));\n const clientVersion = options.clientVersion ?? packageVersion;\n const callerLabel =\n options.callerLabel ?? resolveCallerLabel();\n const paths = resolveDaemonPaths({\n homeDir: options.homeDir ?? process.env.OPENTRAY_HOME ?? homedir(),\n packageVersion,\n callerLabel,\n });\n const endpoint = options.endpoint ?? paths.endpoint;\n const autoStart = options.autoStart ?? endpoint === paths.endpoint;\n if (autoStart && endpoint !== paths.endpoint) {\n throw new Error(\"local broker autoStart requires the derived same-version endpoint\");\n }\n if (autoStart) {\n const cliEntrypoint = options.cliEntrypoint ?? resolveCliEntrypoint();\n const driver = options.daemonDriver ?? createNodeDaemonDriver(cliEntrypoint);\n await startDaemon({ paths, driver });\n }\n const socket = await connectSocket(endpoint);\n const connection = new LocalBrokerConnection(socket, endpoint, callerLabel);\n\n await connection.init(clientVersion, options.protocolVersion ?? PROTOCOL_VERSION);\n return connection;\n};\n\nclass LocalBrokerConnection implements LocalBrokerClient {\n readonly endpoint: string;\n readonly callerLabel: string;\n sessionId = \"\";\n /** @deprecated Use `sessionId`. */\n leaseId = \"\";\n\n private buffer = \"\";\n private readonly listeners = new Set<(frame: BrokerEventFrame) => void>();\n private readonly pending = new Map<RequestId, PendingRequest>();\n private ready:\n | {\n resolve(frame: Extract<ServerFrame, { type: \"ready\" }>): void;\n reject(error: Error): void;\n }\n | undefined;\n\n constructor(\n private readonly socket: BrokerSocket,\n endpoint: string,\n callerLabel: string,\n ) {\n this.endpoint = endpoint;\n this.callerLabel = callerLabel;\n socket.setEncoding(\"utf8\");\n socket.on(\"data\", (chunk: Buffer | string) => {\n this.consume(String(chunk));\n });\n socket.on(\"error\", (error) => {\n this.rejectAll(error);\n });\n socket.on(\"close\", () => {\n this.rejectAll(new Error(\"broker connection closed\"));\n });\n }\n\n async init(clientVersion: string, protocolVersion: number): Promise<void> {\n const ready = new Promise<Extract<ServerFrame, { type: \"ready\" }>>((resolve, reject) => {\n this.ready = { resolve, reject };\n });\n this.write({\n type: \"init\",\n protocolVersion,\n clientVersion,\n });\n const frame = await ready;\n this.sessionId = frame.sessionId;\n this.leaseId = frame.sessionId;\n }\n\n async request(frame: ClientRequestFrame): Promise<ServerFrame> {\n if (this.pending.has(frame.requestId)) {\n throw new Error(`duplicate requestId: ${frame.requestId}`);\n }\n\n const response = new Promise<ServerFrame>((resolve, reject) => {\n this.pending.set(frame.requestId, { resolve, reject });\n });\n this.write(frame);\n return response;\n }\n\n onEvent(listener: (frame: BrokerEventFrame) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n async close(): Promise<void> {\n this.write({ type: \"exit\" });\n await new Promise<void>((resolve) => {\n this.socket.end(resolve);\n });\n }\n\n private consume(chunk: string): void {\n this.buffer += chunk;\n while (true) {\n const newline = this.buffer.indexOf(\"\\n\");\n if (newline < 0) {\n return;\n }\n\n const line = this.buffer.slice(0, newline).trim();\n this.buffer = this.buffer.slice(newline + 1);\n if (line.length > 0) {\n this.dispatchLine(line);\n }\n }\n }\n\n private dispatchLine(line: string): void {\n const parsed = parseServerFrame(line);\n if (!parsed.ok || parsed.frame === undefined) {\n this.rejectAll(new Error(`${parsed.error ?? \"invalid server frame\"}: ${line}`));\n return;\n }\n\n this.dispatchFrame(parsed.frame);\n }\n\n private dispatchFrame(frame: ServerFrame): void {\n if (frame.type === \"ready\") {\n this.ready?.resolve(frame);\n this.ready = undefined;\n return;\n }\n\n if (frame.type === \"error\") {\n const error = new Error(`${frame.code}: ${frame.message}`);\n if (frame.requestId !== undefined) {\n this.pending.get(frame.requestId)?.reject(error);\n this.pending.delete(frame.requestId);\n return;\n }\n // An error with no requestId could not be correlated to a specific request.\n // If the handshake is still pending, reject it; otherwise reject every\n // pending request so callers fail loudly instead of hanging indefinitely.\n // (See issue #3: createTray never resolves on a malformed frame.)\n if (this.ready) {\n this.ready.reject(error);\n this.ready = undefined;\n return;\n }\n this.rejectAll(error);\n return;\n }\n\n const requestId = responseRequestId(frame);\n if (requestId !== undefined) {\n // Request responses and broker events are separate streams even on one socket.\n this.pending.get(requestId)?.resolve(frame);\n this.pending.delete(requestId);\n return;\n }\n\n if (frame.type === \"event\" || frame.type === \"ext-event\") {\n for (const listener of this.listeners) {\n listener(frame);\n }\n }\n }\n\n private write(frame: unknown): void {\n this.socket.write(`${JSON.stringify(frame)}\\n`);\n }\n\n private rejectAll(error: Error): void {\n this.ready?.reject(error);\n this.ready = undefined;\n for (const pending of this.pending.values()) {\n pending.reject(error);\n }\n this.pending.clear();\n }\n}\n\nconst connectSocket = (endpoint: string): Promise<BrokerSocket> =>\n new Promise((resolve, reject) => {\n const socket = createConnection(endpoint);\n socket.once(\"connect\", () => {\n socket.off(\"error\", reject);\n resolve(socket);\n });\n socket.once(\"error\", reject);\n });\n\nconst responseRequestId = (frame: ServerFrame): RequestId | undefined => {\n switch (frame.type) {\n case \"space-created\":\n case \"default-space\":\n case \"tray-created\":\n case \"tray-bounds\":\n case \"ack\":\n case \"ext-command-result\":\n case \"daemon-health\":\n return frame.requestId;\n case \"ready\":\n case \"event\":\n case \"ext-event\":\n case \"error\":\n return undefined;\n }\n};\n\nconst resolveCliEntrypoint = (): string => {\n const suffix = fileURLToPath(import.meta.url).endsWith(\".ts\") ? \"cli.ts\" : \"cli.mjs\";\n return fileURLToPath(new URL(`./${suffix}`, import.meta.url));\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,MAAa,sBAAsB,UAAqC,CAAC,MAAc;CACrF,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,MAAM,OAAO,QAAQ,QAAQ,QAAQ;CAErC,MAAM,aAAuB,CAAC;CAC9B,IAAI,QAAQ,aAAa,KAAA,KAAa,QAAQ,SAAS,SAAS,GAC9D,WAAW,KAAK,QAAQ,QAAQ;CAElC,MAAM,UAAU,QAAQ,kBAAkB,I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EAAE,SAAS,KAAK,IAAI,WAAW;CAC3E,OAAO,cAAc,IAAI,IAAI,KAAK,UAAU,OAAO,KAAK,GAAG,CAAC;AAC9D"}
|
package/dist/node.d.mts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { u as OpenTrayTransport } from "./client-C27qmRfr.mjs";
|
|
2
2
|
import { BrokerEndpointIdentityOptions, ServerFrame } from "@opentray/spec";
|
|
3
3
|
|
|
4
4
|
//#region src/daemon/paths.d.ts
|
|
5
5
|
interface DaemonPaths {
|
|
6
6
|
homeDir: string;
|
|
7
7
|
packageVersion: string;
|
|
8
|
+
callerLabel: string;
|
|
8
9
|
protocolVersion: number;
|
|
9
10
|
stateRoot: string;
|
|
10
11
|
runtimeDir: string;
|
|
@@ -27,6 +28,7 @@ type BrokerEventFrame = Extract<ServerFrame, {
|
|
|
27
28
|
}>;
|
|
28
29
|
interface LocalBrokerClient extends OpenTrayTransport {
|
|
29
30
|
readonly endpoint: string;
|
|
31
|
+
readonly callerLabel: string;
|
|
30
32
|
readonly sessionId: string;
|
|
31
33
|
/** @deprecated Use `sessionId`. */
|
|
32
34
|
readonly leaseId: string;
|
|
@@ -40,6 +42,7 @@ interface ConnectLocalBrokerOptions extends Partial<BrokerEndpointIdentityOption
|
|
|
40
42
|
autoStart?: boolean;
|
|
41
43
|
daemonDriver?: DaemonDriver;
|
|
42
44
|
cliEntrypoint?: string;
|
|
45
|
+
callerLabel?: string;
|
|
43
46
|
}
|
|
44
47
|
declare const connectLocalBroker: (options?: ConnectLocalBrokerOptions) => Promise<LocalBrokerClient>;
|
|
45
48
|
//#endregion
|
package/dist/node.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.d.mts","names":[],"sources":["../src/daemon/paths.ts","../src/daemon/lifecycle.ts","../src/local-broker.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"node.d.mts","names":[],"sources":["../src/daemon/paths.ts","../src/daemon/lifecycle.ts","../src/local-broker.ts"],"mappings":";;;;UASiB,WAAA;EACf,OAAA;EACA,cAAA;EACA,WAAA;EACA,eAAA;EACA,SAAA;EACA,UAAA;EACA,QAAA;EACA,OAAA;EACA,QAAA;EACA,SAAA;AAAA;;;UCEe,YAAA;EACf,OAAA,CAAQ,GAAA,WAAc,OAAA;EACtB,WAAA,CAAY,KAAA,EAAO,WAAA,GAAc,OAAA;EACjC,IAAA,CAAK,GAAA,WAAc,OAAA;AAAA;;;KCHT,gBAAA,GAAmB,OAAO,CAAC,WAAA;EAAe,IAAA;AAAA;AAAA,UAErC,iBAAA,SAA0B,iBAAA;EAAA,SAChC,QAAA;EAAA,SACA,WAAA;EAAA,SACA,SAAA;EFdT;EAAA,SEgBS,OAAA;EACT,OAAA,CAAQ,QAAA,GAAW,KAAA,EAAO,gBAAA;EAC1B,KAAA,IAAS,OAAA;AAAA;AAAA,UAGM,yBAAA,SAAkC,OAAA,CAAQ,6BAAA;EACzD,QAAA;EACA,OAAA;EACA,aAAA;EACA,SAAA;EACA,YAAA,GAAe,YAAA;EACf,aAAA;EACA,WAAA;AAAA;AAAA,cAoBW,kBAAA,GACX,OAAA,GAAS,yBAAA,KACR,OAAA,CAAQ,iBAAA"}
|
package/dist/node.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as connectLocalBroker } from "./local-broker-
|
|
1
|
+
import { t as connectLocalBroker } from "./local-broker-BMxjb-eO.mjs";
|
|
2
2
|
export { connectLocalBroker };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opentray",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Developer-facing OpenTray SDK and CLI package.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
],
|
|
29
29
|
"sideEffects": false,
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@opentray/spec": "0.
|
|
31
|
+
"@opentray/spec": "0.6.0"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
34
|
"tsdown": "^0.22.1",
|
|
@@ -36,12 +36,12 @@
|
|
|
36
36
|
"vitest": "^4.1.7"
|
|
37
37
|
},
|
|
38
38
|
"optionalDependencies": {
|
|
39
|
-
"@opentray/darwin-arm64": "0.
|
|
40
|
-
"@opentray/darwin-x64": "0.
|
|
41
|
-
"@opentray/linux-arm64": "0.
|
|
42
|
-
"@opentray/linux-x64": "0.
|
|
43
|
-
"@opentray/windows-arm64": "0.
|
|
44
|
-
"@opentray/windows-x64": "0.
|
|
39
|
+
"@opentray/darwin-arm64": "0.8.0",
|
|
40
|
+
"@opentray/darwin-x64": "0.8.0",
|
|
41
|
+
"@opentray/linux-arm64": "0.8.0",
|
|
42
|
+
"@opentray/linux-x64": "0.8.0",
|
|
43
|
+
"@opentray/windows-arm64": "0.8.0",
|
|
44
|
+
"@opentray/windows-x64": "0.8.0"
|
|
45
45
|
},
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "tsdown src/index.ts src/node.ts src/cli.ts --format esm --dts",
|
|
@@ -49,6 +49,9 @@
|
|
|
49
49
|
"example:basic": "bun run examples/basic-space.ts",
|
|
50
50
|
"example:daemon-lynx": "bun run examples/daemon-lynx.ts",
|
|
51
51
|
"example:daemon-tray": "bun run examples/daemon-tray.ts",
|
|
52
|
+
"example:mediaQuery": "bun run examples/media-query-panel.ts",
|
|
53
|
+
"example:badge": "bun run examples/badge-panel.ts",
|
|
54
|
+
"example:placement": "bun run examples/placement-panel.ts",
|
|
52
55
|
"example:tray-panel": "bun run examples/tray-panel.ts",
|
|
53
56
|
"example:webview-control": "bun run examples/webview-control.ts",
|
|
54
57
|
"test": "vitest run",
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
import { ClientFrame, ClientRequestFrame, RequestId, ServerFrame, SpaceOptions, SpaceRef, TrayBoundsResult, TrayId, TrayOptions } from "@opentray/spec";
|
|
2
|
-
|
|
3
|
-
//#region src/client.d.ts
|
|
4
|
-
interface OpenTrayTransport {
|
|
5
|
-
request(frame: ClientRequestFrame): Promise<ServerFrame>;
|
|
6
|
-
}
|
|
7
|
-
interface OpenTrayClient {
|
|
8
|
-
createSpace(options: SpaceOptions): Promise<SpaceHandle>;
|
|
9
|
-
resolveDefaultSpace(): Promise<SpaceHandle>;
|
|
10
|
-
/** @deprecated Use `createSpace`. */
|
|
11
|
-
createSurface(options: SpaceOptions): Promise<SpaceHandle>;
|
|
12
|
-
}
|
|
13
|
-
interface SpaceHandle {
|
|
14
|
-
space: SpaceRef;
|
|
15
|
-
createTray(options: TrayOptions): Promise<TrayHandle>;
|
|
16
|
-
}
|
|
17
|
-
/** @deprecated Use `SpaceHandle`. */
|
|
18
|
-
type SurfaceHandle = SpaceHandle;
|
|
19
|
-
interface TrayHandle {
|
|
20
|
-
space: SpaceRef;
|
|
21
|
-
trayId: TrayId;
|
|
22
|
-
getBounds(): Promise<TrayBoundsResult>;
|
|
23
|
-
loadExtension(options: ExtensionLoadOptions): Promise<void>;
|
|
24
|
-
commandExtension(ext: string, data: unknown): Promise<void>;
|
|
25
|
-
extend<TCapability extends object, TOptions = undefined>(extension: TrayExtension<TCapability, TOptions>, options?: TOptions): TrayHandle & TCapability;
|
|
26
|
-
destroy(): Promise<void>;
|
|
27
|
-
}
|
|
28
|
-
interface ExtensionLoadOptions {
|
|
29
|
-
name: string;
|
|
30
|
-
path: string;
|
|
31
|
-
mountId?: string;
|
|
32
|
-
}
|
|
33
|
-
interface TrayExtensionMountSpec {
|
|
34
|
-
name?: string;
|
|
35
|
-
path?: string;
|
|
36
|
-
mountId?: string;
|
|
37
|
-
}
|
|
38
|
-
interface TrayExtensionContext {
|
|
39
|
-
readonly name: string;
|
|
40
|
-
readonly path: string;
|
|
41
|
-
readonly mountId: string;
|
|
42
|
-
ensureLoaded(): Promise<void>;
|
|
43
|
-
command(data: unknown): Promise<void>;
|
|
44
|
-
}
|
|
45
|
-
interface TrayExtension<TCapability extends object, TOptions = undefined> {
|
|
46
|
-
readonly name: string;
|
|
47
|
-
readonly path: string;
|
|
48
|
-
resolveMount?(options: TOptions | undefined): TrayExtensionMountSpec;
|
|
49
|
-
extend(tray: TrayHandle, context: TrayExtensionContext, options: TOptions | undefined): TCapability;
|
|
50
|
-
}
|
|
51
|
-
declare const createInitFrame: (clientVersion: string) => ClientFrame;
|
|
52
|
-
interface CreateClientOptions {
|
|
53
|
-
requestIdPrefix?: string;
|
|
54
|
-
}
|
|
55
|
-
declare const createClient: (transport: OpenTrayTransport, options?: CreateClientOptions) => OpenTrayClient;
|
|
56
|
-
declare const createSpaceHandle: (transport: OpenTrayTransport, space: SpaceRef, nextRequestId?: () => RequestId) => SpaceHandle;
|
|
57
|
-
/** @deprecated Use `createSpaceHandle`. */
|
|
58
|
-
declare const createSurfaceHandle: (transport: OpenTrayTransport, space: SpaceRef, nextRequestId?: () => RequestId) => SpaceHandle;
|
|
59
|
-
declare const createTrayHandle: (transport: OpenTrayTransport, space: SpaceRef, trayId: TrayId, nextRequestId?: () => RequestId) => TrayHandle;
|
|
60
|
-
//#endregion
|
|
61
|
-
export { SpaceHandle as a, TrayExtensionContext as c, createClient as d, createInitFrame as f, createTrayHandle as h, OpenTrayTransport as i, TrayExtensionMountSpec as l, createSurfaceHandle as m, ExtensionLoadOptions as n, SurfaceHandle as o, createSpaceHandle as p, OpenTrayClient as r, TrayExtension as s, CreateClientOptions as t, TrayHandle as u };
|
|
62
|
-
//# sourceMappingURL=client-DQn3DLZw.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-DQn3DLZw.d.mts","names":[],"sources":["../src/client.ts"],"mappings":";;;UAaiB,iBAAA;EACf,OAAA,CAAQ,KAAA,EAAO,kBAAA,GAAqB,OAAA,CAAQ,WAAA;AAAA;AAAA,UAG7B,cAAA;EACf,WAAA,CAAY,OAAA,EAAS,YAAA,G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KACR,cAAA;AAAA,cA6BU,iBAAA,GACX,SAAA,EAAW,iBAAA,EACX,KAAA,EAAO,QAAA,EACP,aAAA,SAAqB,SAAA,KACpB,WAAA;;cAgBU,mBAAA,GAAmB,SAAA,EAnBnB,iBAAA,EAAiB,KAAA,EACrB,QAAA,EAAQ,aAAA,SACM,SAAA,KACpB,WAAA;AAAA,cAkBU,gBAAA,GACX,SAAA,EAAW,iBAAA,EACX,KAAA,EAAO,QAAA,EACP,MAAA,EAAQ,MAAA,EACR,aAAA,SAAqB,SAAA,KACpB,UAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"local-broker-C9siWyRh.mjs","names":["isNodeError"],"sources":["../src/daemon/native-target.ts","../src/daemon/broker-command.ts","../src/daemon/lifecycle.ts","../src/daemon/package-version.ts","../src/daemon/paths.ts","../src/local-broker.ts"],"sourcesContent":["export type BrokerPackageOs = \"darwin\" | \"linux\" | \"windows\";\nexport type BrokerArch = \"arm64\" | \"x64\";\n\nexport interface BrokerNativeTarget {\n packageName: string;\n binaryRelativePath: string;\n}\n\nexport const resolveBrokerNativeTarget = (\n platform: string = process.platform,\n arch: string = process.arch,\n): BrokerNativeTarget => {\n const packageOs = platformToPackageOs(platform);\n const nativeArch = normalizeArch(arch);\n return {\n packageName: `@opentray/${packageOs}-${nativeArch}`,\n binaryRelativePath: `bin/${packageOs === \"windows\" ? \"opentray.exe\" : \"opentray\"}`,\n };\n};\n\nconst platformToPackageOs = (platform: string): BrokerPackageOs => {\n switch (platform) {\n case \"darwin\":\n case \"linux\":\n return platform;\n case \"win32\":\n return \"windows\";\n default:\n throw new MissingPlatformBrokerBinaryError(\n `unsupported OpenTray broker platform: ${platform}`,\n platform,\n process.arch,\n );\n }\n};\n\nconst normalizeArch = (arch: string): BrokerArch => {\n switch (arch) {\n case \"arm64\":\n case \"x64\":\n return arch;\n default:\n throw new MissingPlatformBrokerBinaryError(\n `unsupported OpenTray broker architecture: ${arch}`,\n process.platform,\n arch,\n );\n }\n};\n\nexport class MissingPlatformBrokerBinaryError extends Error {\n readonly code = \"OPENTRAY_MISSING_PLATFORM_BROKER_BINARY\";\n readonly platform: string;\n readonly arch: string;\n readonly packageName: string | undefined;\n readonly binaryPath: string | undefined;\n\n constructor(\n message: string,\n platform: string,\n arch: string,\n options: {\n packageName?: string;\n binaryPath?: string;\n cause?: unknown;\n } = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = \"MissingPlatformBrokerBinaryError\";\n this.platform = platform;\n this.arch = arch;\n this.packageName = options.packageName;\n this.binaryPath = options.binaryPath;\n }\n}\n","import { access, chmod } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport { spawn } from \"node:child_process\";\n\nimport type { DaemonPaths } from \"./paths\";\nimport { MissingPlatformBrokerBinaryError, resolveBrokerNativeTarget } from \"./native-target\";\n\nexport interface BrokerCommand {\n command: string;\n args: string[];\n cwd?: string;\n}\n\nconst sourceUrl = import.meta.url;\nconst requireFromSource = createRequire(sourceUrl);\n\nexport interface ResolveBrokerCommandOptions {\n env?: NodeJS.ProcessEnv;\n platform?: NodeJS.Platform;\n arch?: string;\n sourceDir?: string;\n resolvePackageJson?: (packageName: string) => string | undefined;\n findWorkspaceRoot?: (start: string) => Promise<string | undefined>;\n ensureDevBrokerBinary?: (workspaceRoot: string) => Promise<string>;\n}\n\nexport const resolveBrokerCommand = async (\n paths: DaemonPaths,\n options: ResolveBrokerCommandOptions = {},\n): Promise<BrokerCommand> => {\n const env = options.env ?? process.env;\n const explicit = env.OPENTRAY_BROKER_BIN;\n if (explicit !== undefined && explicit.length > 0) {\n return commandForBinary(explicit, paths);\n }\n\n const sourceDir = options.sourceDir ?? dirname(fileURLToPath(sourceUrl));\n const workspaceRoot = await (options.findWorkspaceRoot ?? findWorkspaceRoot)(sourceDir);\n if (workspaceRoot !== undefined) {\n const binary = await (options.ensureDevBrokerBinary ?? ensureDevBrokerBinary)(workspaceRoot);\n return commandForBinary(binary, paths, workspaceRoot);\n }\n\n const platform = options.platform ?? process.platform;\n const arch = options.arch ?? process.arch;\n const installedBinary = await resolveInstalledBrokerBinary({\n platform,\n arch,\n resolvePackageJson: options.resolvePackageJson ?? resolvePackageJson,\n });\n if (installedBinary !== undefined) {\n return commandForBinary(installedBinary, paths);\n }\n\n const target = resolveBrokerNativeTarget(platform, arch);\n throw new MissingPlatformBrokerBinaryError(\n `unable to resolve OpenTray broker binary for ${platform}/${arch}; install ${target.packageName} or set OPENTRAY_BROKER_BIN`,\n platform,\n arch,\n { packageName: target.packageName },\n );\n};\n\nconst commandForBinary = (binary: string, paths: DaemonPaths, cwd?: string): BrokerCommand => {\n const command: BrokerCommand = {\n command: binary,\n args: [\n \"broker\",\n \"--endpoint\",\n paths.endpoint,\n \"--ready-file\",\n paths.readyFile,\n \"--package-version\",\n paths.packageVersion,\n \"--protocol-version\",\n `${paths.protocolVersion}`,\n ],\n };\n if (cwd !== undefined) {\n command.cwd = cwd;\n }\n return command;\n};\n\ninterface ResolveInstalledBrokerBinaryOptions {\n platform: NodeJS.Platform;\n arch: string;\n resolvePackageJson: (packageName: string) => string | undefined;\n}\n\nexport const resolveInstalledBrokerBinary = async ({\n platform,\n arch,\n resolvePackageJson,\n}: ResolveInstalledBrokerBinaryOptions): Promise<string | undefined> => {\n const target = resolveBrokerNativeTarget(platform, arch);\n const packageJsonPath = resolvePackageJson(target.packageName);\n if (packageJsonPath === undefined) {\n return undefined;\n }\n\n const binary = join(dirname(packageJsonPath), target.binaryRelativePath);\n if (!(await exists(binary))) {\n throw new MissingPlatformBrokerBinaryError(\n `OpenTray broker package ${target.packageName} is installed but missing ${target.binaryRelativePath}`,\n platform,\n arch,\n {\n packageName: target.packageName,\n binaryPath: binary,\n },\n );\n }\n\n if (platform !== \"win32\") {\n await chmod(binary, 0o755);\n }\n\n return binary;\n};\n\nconst resolvePackageJson = (packageName: string): string | undefined => {\n try {\n return requireFromSource.resolve(`${packageName}/package.json`);\n } catch (error) {\n if (isNodeError(error) && error.code === \"MODULE_NOT_FOUND\") {\n return undefined;\n }\n throw error;\n }\n};\n\nconst findWorkspaceRoot = async (start: string): Promise<string | undefined> => {\n let current = start;\n while (true) {\n if (await exists(join(current, \"Cargo.toml\"))) {\n if (await exists(join(current, \"crates\", \"opentray-bin\", \"Cargo.toml\"))) {\n return current;\n }\n }\n\n const parent = dirname(current);\n if (parent === current) {\n return undefined;\n }\n current = parent;\n }\n};\n\nconst ensureDevBrokerBinary = async (workspaceRoot: string): Promise<string> => {\n const binary = join(\n workspaceRoot,\n \"target\",\n \"debug\",\n process.platform === \"win32\" ? \"opentray.exe\" : \"opentray\",\n );\n await runCargoBuild(workspaceRoot);\n return binary;\n};\n\nconst runCargoBuild = (workspaceRoot: string): Promise<void> =>\n new Promise((resolve, reject) => {\n const child = spawn(\"cargo\", [\"build\", \"-p\", \"opentray-bin\"], {\n cwd: workspaceRoot,\n stdio: process.env.OPENTRAY_BROKER_BUILD_LOGS === \"1\" ? \"inherit\" : \"ignore\",\n });\n child.once(\"error\", reject);\n child.once(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(new Error(`cargo build -p opentray-bin failed with code ${code ?? \"unknown\"}`));\n });\n });\n\nconst exists = async (path: string): Promise<boolean> => {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n};\n\nconst isNodeError = (error: unknown): error is NodeJS.ErrnoException =>\n error instanceof Error && \"code\" in error;\n","import { constants } from \"node:fs\";\nimport { mkdir, open, readFile, rm, unlink, writeFile } from \"node:fs/promises\";\nimport { spawn } from \"node:child_process\";\n\nimport { resolveBrokerCommand } from \"./broker-command\";\nimport type { DaemonPaths } from \"./paths\";\n\nconst DAEMON_STDIO_ENV = \"OPENTRAY_DAEMON_STDIO\";\n\nexport type DaemonStartResult =\n | { status: \"started\"; pid: number; paths: DaemonPaths }\n | { status: \"already-running\"; pid: number; paths: DaemonPaths };\n\nexport type DaemonStopResult =\n | { status: \"stopped\"; pid: number; paths: DaemonPaths }\n | { status: \"not-running\"; paths: DaemonPaths };\n\nexport type DaemonInspectResult =\n | { status: \"running\"; pid: number; paths: DaemonPaths }\n | { status: \"not-running\"; paths: DaemonPaths; stalePid?: number };\n\nexport interface DaemonDriver {\n isAlive(pid: number): Promise<boolean>;\n spawnBroker(paths: DaemonPaths): Promise<number>;\n stop(pid: number): Promise<void>;\n}\n\nexport interface StartDaemonOptions {\n paths: DaemonPaths;\n driver: DaemonDriver;\n lockTimeoutMs?: number;\n}\n\nexport interface StopDaemonOptions {\n paths: DaemonPaths;\n driver: DaemonDriver;\n}\n\nexport interface InspectDaemonOptions {\n paths: DaemonPaths;\n driver: DaemonDriver;\n}\n\nexport const createNodeDaemonDriver = (cliEntrypoint: string): DaemonDriver => ({\n async isAlive(pid) {\n return isProcessAlive(pid);\n },\n async spawnBroker(paths) {\n const broker = await resolveBrokerCommand(paths);\n const child = spawn(broker.command, broker.args, {\n cwd: broker.cwd,\n detached: true,\n env: {\n ...process.env,\n OPENTRAY_DAEMON_HOME: paths.homeDir,\n OPENTRAY_DAEMON_PACKAGE_VERSION: paths.packageVersion,\n OPENTRAY_DAEMON_CLI_ENTRYPOINT: cliEntrypoint,\n },\n stdio: resolveBrokerStdio(process.env[DAEMON_STDIO_ENV]),\n });\n\n child.unref();\n return child.pid ?? 0;\n },\n async stop(pid) {\n process.kill(pid, \"SIGTERM\");\n },\n});\n\nexport const resolveBrokerStdio = (\n value: string | undefined,\n): \"ignore\" | \"inherit\" => {\n return value === \"inherit\" ? \"inherit\" : \"ignore\";\n};\n\nexport const startDaemon = async ({\n paths,\n driver,\n lockTimeoutMs = 1_000,\n}: StartDaemonOptions): Promise<DaemonStartResult> => {\n await mkdir(paths.runtimeDir, { recursive: true });\n\n const lock = await acquireLock(paths.lockFile, lockTimeoutMs);\n try {\n const existingPid = await readPid(paths.pidFile);\n if (existingPid !== undefined && (await driver.isAlive(existingPid))) {\n return { status: \"already-running\", pid: existingPid, paths };\n }\n\n await cleanupRuntimeFiles(paths);\n const pid = await driver.spawnBroker(paths);\n if (!Number.isInteger(pid) || pid <= 0) {\n throw new Error(\"daemon broker process did not expose a valid pid\");\n }\n await writeFile(paths.pidFile, `${pid}\\n`, \"utf8\");\n await waitForReadyFile(paths.readyFile, driver, pid);\n return { status: \"started\", pid, paths };\n } finally {\n await lock.release();\n }\n};\n\nexport const stopDaemon = async ({ paths, driver }: StopDaemonOptions): Promise<DaemonStopResult> => {\n const pid = await readPid(paths.pidFile);\n if (pid === undefined || !(await driver.isAlive(pid))) {\n await cleanupRuntimeFiles(paths);\n return { status: \"not-running\", paths };\n }\n\n await driver.stop(pid);\n await waitUntilStopped(driver, pid);\n await cleanupRuntimeFiles(paths);\n return { status: \"stopped\", pid, paths };\n};\n\nexport const restartDaemon = async (options: StartDaemonOptions): Promise<DaemonStartResult> => {\n await stopDaemon({ paths: options.paths, driver: options.driver });\n return startDaemon(options);\n};\n\nexport const inspectDaemon = async ({ paths, driver }: InspectDaemonOptions): Promise<DaemonInspectResult> => {\n const pid = await readPid(paths.pidFile);\n if (pid !== undefined && (await driver.isAlive(pid))) {\n return { status: \"running\", pid, paths };\n }\n\n await cleanupRuntimeFiles(paths);\n return pid === undefined\n ? { status: \"not-running\", paths }\n : { status: \"not-running\", paths, stalePid: pid };\n};\n\nconst readPid = async (pidFile: string): Promise<number | undefined> => {\n try {\n const content = await readFile(pidFile, \"utf8\");\n const pid = Number.parseInt(content.trim(), 10);\n return Number.isInteger(pid) && pid > 0 ? pid : undefined;\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return undefined;\n }\n throw error;\n }\n};\n\nconst cleanupRuntimeFiles = async (paths: DaemonPaths): Promise<void> => {\n await rm(paths.readyFile, { force: true });\n await rm(paths.pidFile, { force: true });\n if (process.platform !== \"win32\") {\n await rm(paths.endpoint, { force: true });\n }\n};\n\nconst waitUntilStopped = async (driver: DaemonDriver, pid: number): Promise<void> => {\n for (let attempt = 0; attempt < 20; attempt += 1) {\n if (!(await driver.isAlive(pid))) {\n return;\n }\n await sleep(50);\n }\n};\n\nconst waitForReadyFile = async (\n readyFile: string,\n driver: DaemonDriver,\n pid: number,\n): Promise<void> => {\n for (let attempt = 0; attempt < 40; attempt += 1) {\n try {\n await readFile(readyFile, \"utf8\");\n return;\n } catch (error) {\n if (!isNodeError(error) || error.code !== \"ENOENT\") {\n throw error;\n }\n if (!(await driver.isAlive(pid))) {\n throw new Error(\n `daemon broker exited before readiness: pid=${pid}; readyFile=${readyFile}; set ${DAEMON_STDIO_ENV}=inherit to inspect broker stderr`,\n );\n }\n await sleep(50);\n }\n }\n\n throw new Error(`timed out waiting for daemon readiness: ${readyFile}`);\n};\n\nconst acquireLock = async (\n lockFile: string,\n timeoutMs: number,\n): Promise<{\n release(): Promise<void>;\n}> => {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() <= deadline) {\n try {\n const handle = await open(lockFile, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY);\n await handle.writeFile(`${process.pid}\\n`, \"utf8\");\n return {\n async release() {\n await handle.close();\n await unlink(lockFile).catch((error: unknown) => {\n if (!isNodeError(error) || error.code !== \"ENOENT\") {\n throw error;\n }\n });\n },\n };\n } catch (error) {\n if (isNodeError(error) && error.code === \"EEXIST\") {\n await sleep(25);\n continue;\n }\n throw error;\n }\n }\n\n throw new Error(`timed out acquiring daemon lock: ${lockFile}`);\n};\n\nconst isProcessAlive = (pid: number): boolean => {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n};\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst isNodeError = (error: unknown): error is NodeJS.ErrnoException =>\n error instanceof Error && \"code\" in error;\n","import { readFile } from \"node:fs/promises\";\n\nexport const readPackageVersion = async (packageJsonUrl: URL): Promise<string> => {\n const value: unknown = JSON.parse(await readFile(packageJsonUrl, \"utf8\"));\n if (!isPackageJsonWithVersion(value)) {\n throw new Error(`package.json is missing a string version: ${packageJsonUrl.href}`);\n }\n\n return value.version;\n};\n\nconst isPackageJsonWithVersion = (value: unknown): value is { version: string } =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"version\" in value &&\n typeof value.version === \"string\";\n","import { createBrokerEndpointIdentity, formatUnixSocketPath, formatWindowsPipeName } from \"@opentray/spec\";\n\nexport interface DaemonPathOptions {\n homeDir: string;\n packageVersion: string;\n platform?: NodeJS.Platform;\n}\n\nexport interface DaemonPaths {\n homeDir: string;\n packageVersion: string;\n protocolVersion: number;\n stateRoot: string;\n runtimeDir: string;\n endpoint: string;\n pidFile: string;\n lockFile: string;\n readyFile: string;\n}\n\nexport const resolveDaemonPaths = ({\n homeDir,\n packageVersion,\n platform = process.platform,\n}: DaemonPathOptions): DaemonPaths => {\n const identity = createBrokerEndpointIdentity({ packageVersion });\n const normalizedHome = homeDir.replace(/[\\\\/]+$/u, \"\");\n const stateRoot = `${normalizedHome}/.opentray/${identity.packageVersion}`;\n const runtimeDir = `${stateRoot}/runtime`;\n const endpoint =\n platform === \"win32\" ? formatWindowsPipeName(identity) : formatUnixSocketPath(normalizedHome, identity);\n\n return {\n homeDir: normalizedHome,\n packageVersion: identity.packageVersion,\n protocolVersion: identity.protocolVersion,\n stateRoot,\n runtimeDir,\n endpoint,\n pidFile: `${runtimeDir}/broker.pid`,\n lockFile: `${runtimeDir}/broker.lock`,\n readyFile: `${runtimeDir}/ready.json`,\n };\n};\n","import { createConnection, type Socket } from \"node:net\";\nimport { homedir } from \"node:os\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n PROTOCOL_VERSION,\n parseServerFrame,\n type BrokerEndpointIdentityOptions,\n type ClientRequestFrame,\n type RequestId,\n type ServerFrame,\n} from \"@opentray/spec\";\n\nimport type { OpenTrayTransport } from \"./client\";\nimport { createNodeDaemonDriver, startDaemon, type DaemonDriver } from \"./daemon/lifecycle\";\nimport { readPackageVersion } from \"./daemon/package-version\";\nimport { resolveDaemonPaths } from \"./daemon/paths\";\n\nconst packageJsonUrl = new URL(\"../package.json\", import.meta.url);\n\nexport type BrokerEventFrame = Extract<ServerFrame, { type: \"event\" | \"ext-event\" }>;\n\nexport interface LocalBrokerClient extends OpenTrayTransport {\n readonly endpoint: string;\n readonly sessionId: string;\n /** @deprecated Use `sessionId`. */\n readonly leaseId: string;\n onEvent(listener: (frame: BrokerEventFrame) => void): () => void;\n close(): Promise<void>;\n}\n\nexport interface ConnectLocalBrokerOptions extends Partial<BrokerEndpointIdentityOptions> {\n endpoint?: string;\n homeDir?: string;\n clientVersion?: string;\n autoStart?: boolean;\n daemonDriver?: DaemonDriver;\n cliEntrypoint?: string;\n}\n\ninterface PendingRequest {\n resolve(frame: ServerFrame): void;\n reject(error: Error): void;\n}\n\ninterface BrokerSocket {\n setEncoding(encoding: BufferEncoding): void;\n on(event: \"data\", listener: (chunk: Buffer | string) => void): void;\n on(event: \"error\", listener: (error: Error) => void): void;\n on(event: \"close\", listener: () => void): void;\n once(event: \"connect\", listener: () => void): void;\n once(event: \"error\", listener: (error: Error) => void): void;\n off(event: \"error\", listener: (error: Error) => void): void;\n write(data: string): void;\n end(callback: () => void): void;\n}\n\nexport const connectLocalBroker = async (\n options: ConnectLocalBrokerOptions = {},\n): Promise<LocalBrokerClient> => {\n const packageVersion = options.packageVersion ?? (await readPackageVersion(packageJsonUrl));\n const clientVersion = options.clientVersion ?? packageVersion;\n const paths = resolveDaemonPaths({\n homeDir: options.homeDir ?? process.env.OPENTRAY_HOME ?? homedir(),\n packageVersion,\n });\n const endpoint = options.endpoint ?? paths.endpoint;\n const autoStart = options.autoStart ?? endpoint === paths.endpoint;\n if (autoStart && endpoint !== paths.endpoint) {\n throw new Error(\"local broker autoStart requires the derived same-version endpoint\");\n }\n if (autoStart) {\n const cliEntrypoint = options.cliEntrypoint ?? resolveCliEntrypoint();\n const driver = options.daemonDriver ?? createNodeDaemonDriver(cliEntrypoint);\n await startDaemon({ paths, driver });\n }\n const socket = await connectSocket(endpoint);\n const connection = new LocalBrokerConnection(socket, endpoint);\n\n await connection.init(clientVersion, options.protocolVersion ?? PROTOCOL_VERSION);\n return connection;\n};\n\nclass LocalBrokerConnection implements LocalBrokerClient {\n readonly endpoint: string;\n sessionId = \"\";\n /** @deprecated Use `sessionId`. */\n leaseId = \"\";\n\n private buffer = \"\";\n private readonly listeners = new Set<(frame: BrokerEventFrame) => void>();\n private readonly pending = new Map<RequestId, PendingRequest>();\n private ready:\n | {\n resolve(frame: Extract<ServerFrame, { type: \"ready\" }>): void;\n reject(error: Error): void;\n }\n | undefined;\n\n constructor(\n private readonly socket: BrokerSocket,\n endpoint: string,\n ) {\n this.endpoint = endpoint;\n socket.setEncoding(\"utf8\");\n socket.on(\"data\", (chunk: Buffer | string) => {\n this.consume(String(chunk));\n });\n socket.on(\"error\", (error) => {\n this.rejectAll(error);\n });\n socket.on(\"close\", () => {\n this.rejectAll(new Error(\"broker connection closed\"));\n });\n }\n\n async init(clientVersion: string, protocolVersion: number): Promise<void> {\n const ready = new Promise<Extract<ServerFrame, { type: \"ready\" }>>((resolve, reject) => {\n this.ready = { resolve, reject };\n });\n this.write({\n type: \"init\",\n protocolVersion,\n clientVersion,\n });\n const frame = await ready;\n this.sessionId = frame.sessionId;\n this.leaseId = frame.sessionId;\n }\n\n async request(frame: ClientRequestFrame): Promise<ServerFrame> {\n if (this.pending.has(frame.requestId)) {\n throw new Error(`duplicate requestId: ${frame.requestId}`);\n }\n\n const response = new Promise<ServerFrame>((resolve, reject) => {\n this.pending.set(frame.requestId, { resolve, reject });\n });\n this.write(frame);\n return response;\n }\n\n onEvent(listener: (frame: BrokerEventFrame) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n async close(): Promise<void> {\n this.write({ type: \"exit\" });\n await new Promise<void>((resolve) => {\n this.socket.end(resolve);\n });\n }\n\n private consume(chunk: string): void {\n this.buffer += chunk;\n while (true) {\n const newline = this.buffer.indexOf(\"\\n\");\n if (newline < 0) {\n return;\n }\n\n const line = this.buffer.slice(0, newline).trim();\n this.buffer = this.buffer.slice(newline + 1);\n if (line.length > 0) {\n this.dispatchLine(line);\n }\n }\n }\n\n private dispatchLine(line: string): void {\n const parsed = parseServerFrame(line);\n if (!parsed.ok || parsed.frame === undefined) {\n this.rejectAll(new Error(parsed.error ?? \"invalid server frame\"));\n return;\n }\n\n this.dispatchFrame(parsed.frame);\n }\n\n private dispatchFrame(frame: ServerFrame): void {\n if (frame.type === \"ready\") {\n this.ready?.resolve(frame);\n this.ready = undefined;\n return;\n }\n\n if (frame.type === \"error\") {\n const error = new Error(`${frame.code}: ${frame.message}`);\n if (frame.requestId !== undefined) {\n this.pending.get(frame.requestId)?.reject(error);\n this.pending.delete(frame.requestId);\n return;\n }\n this.ready?.reject(error);\n this.ready = undefined;\n return;\n }\n\n const requestId = responseRequestId(frame);\n if (requestId !== undefined) {\n // Request responses and broker events are separate streams even on one socket.\n this.pending.get(requestId)?.resolve(frame);\n this.pending.delete(requestId);\n return;\n }\n\n if (frame.type === \"event\" || frame.type === \"ext-event\") {\n for (const listener of this.listeners) {\n listener(frame);\n }\n }\n }\n\n private write(frame: unknown): void {\n this.socket.write(`${JSON.stringify(frame)}\\n`);\n }\n\n private rejectAll(error: Error): void {\n this.ready?.reject(error);\n this.ready = undefined;\n for (const pending of this.pending.values()) {\n pending.reject(error);\n }\n this.pending.clear();\n }\n}\n\nconst connectSocket = (endpoint: string): Promise<BrokerSocket> =>\n new Promise((resolve, reject) => {\n const socket = createConnection(endpoint);\n socket.once(\"connect\", () => {\n socket.off(\"error\", reject);\n resolve(socket);\n });\n socket.once(\"error\", reject);\n });\n\nconst responseRequestId = (frame: ServerFrame): RequestId | undefined => {\n switch (frame.type) {\n case \"space-created\":\n case \"default-space\":\n case \"tray-created\":\n case \"tray-bounds\":\n case \"ack\":\n case \"daemon-health\":\n return frame.requestId;\n case \"ready\":\n case \"event\":\n case \"ext-event\":\n case \"error\":\n return undefined;\n }\n};\n\nconst resolveCliEntrypoint = (): string => {\n const suffix = fileURLToPath(import.meta.url).endsWith(\".ts\") ? \"cli.ts\" : \"cli.mjs\";\n return fileURLToPath(new URL(`./${suffix}`, import.meta.url));\n};\n"],"mappings":";;;;;;;;;;AAQA,MAAa,6BACX,WAAmB,QAAQ,UAC3B,OAAe,QAAQ,SACA;CACvB,MAAM,YAAY,oBAAoB,QAAQ;CAE9C,OAAO;EACL,aAAa,aAAa,UAAU,GAFnB,cAAc,IAEiB;EAChD,oBAAoB,OAAO,cAAc,YAAY,iBAAiB;CACxE;AACF;AAEA,MAAM,uBAAuB,aAAsC;CACjE,QAAQ,UAAR;EACE,KAAK;EACL,KAAK,SACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,SACE,MAAM,IAAI,iCACR,yCAAyC,YACzC,UACA,QAAQ,IACV;CACJ;AACF;AAEA,MAAM,iBAAiB,SAA6B;CAClD,QAAQ,MAAR;EACE,KAAK;EACL,KAAK,OACH,OAAO;EACT,SACE,MAAM,IAAI,iCACR,6CAA6C,QAC7C,QAAQ,UACR,IACF;CACJ;AACF;AAEA,IAAa,mCAAb,cAAsD,MAAM;CAC1D,OAAgB;CAChB;CACA;CACA;CACA;CAEA,YACE,SACA,UACA,MACA,UAII,CAAC,GACL;EACA,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EACjF,KAAK,OAAO;EACZ,KAAK,WAAW;EAChB,KAAK,OAAO;EACZ,KAAK,cAAc,QAAQ;EAC3B,KAAK,aAAa,QAAQ;CAC5B;AACF;;;AC1DA,MAAM,YAAY,OAAO,KAAK;AAC9B,MAAM,oBAAoB,cAAc,SAAS;AAYjD,MAAa,uBAAuB,OAClC,OACA,UAAuC,CAAC,MACb;CAE3B,MAAM,YADM,QAAQ,OAAO,QAAQ,KACd;CACrB,IAAI,aAAa,KAAA,KAAa,SAAS,SAAS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