@cmdless/ui-runtime 0.0.0 → 0.0.5
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/LICENSE +21 -0
- package/README.md +13 -35
- package/out/main/bin.js +40 -0
- package/out/main/cleanup.js +20 -0
- package/out/main/host.js +79 -0
- package/out/main/hosting.js +448 -0
- package/out/preload/index.cjs +4601 -0
- package/out/renderer/assets/Card-BUDQ1UVY.js +15054 -0
- package/out/renderer/assets/Form-B5fhb-x2.css +1121 -0
- package/out/renderer/assets/Form-CE3B5mnl.js +26 -0
- package/out/renderer/assets/Mantine.context-oJEjRkJu.js +574 -0
- package/out/renderer/assets/MantineThemeProvider-DHX5fzKn.js +995 -0
- package/out/renderer/assets/SchemaInput-CACjraGT.js +69 -0
- package/out/renderer/assets/preload-helper-DVzrZ_Op.js +64 -0
- package/out/renderer/assets/use-media-query-d0EeyoH9.js +34 -0
- package/out/renderer/assets/validator-_xTzn1fv.js +31760 -0
- package/out/renderer/assets/view-Chm2p5Ws.js +20542 -0
- package/out/renderer/assets/view-DptMSuIE.css +10034 -0
- package/out/renderer/view.html +21 -0
- package/package.json +54 -7
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 cmdless
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,45 +1,23 @@
|
|
|
1
1
|
# @cmdless/ui-runtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The actual Electron app behind cmdless UI. Windows show the caller's own page (a URL or a file); cards and forms show the host's own page, which draws an [Adaptive Card](https://adaptivecards.io) or a JSON Schema form ([react-jsonschema-form](https://rjsf-team.github.io/react-jsonschema-form/), in Mantine).
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Normally you don't run this directly: `UIHost` in [`@cmdless/ui-sdk/node`](../../packages/ui-sdk) starts it, and [`@cmdless/ui`](../ui)'s one-shot commands go through `UIHost`. It's a separate package because it needs Electron itself.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
## Command
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
- `host` — run the host for an app. It takes no arguments: the app's name comes from `CMDLESS_APP` (left out, a throwaway one is made), the cmdless root from `CMDLESS_ROOT`, and where to report its address from `CMDLESS_SERVICE_SOCKET` (set by `waitForService`).
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
1. Configure OIDC trusted publishing for the package name `@cmdless/ui-runtime`
|
|
13
|
-
2. Enable secure, token-less publishing from CI/CD workflows
|
|
14
|
-
3. Establish provenance for packages published under this name
|
|
11
|
+
## How it hosts
|
|
15
12
|
|
|
16
|
-
|
|
13
|
+
Electron main is itself the host: it takes the app's single-instance lock, serves the `UIHost` protocol on a local socket, and reports the address to whoever started it. `UIHost`s connect there to open windows, dialogs, cards, forms, trays and notifications, each tracked as a handle that ends with a value.
|
|
17
14
|
|
|
18
|
-
|
|
15
|
+
- **One host per app name.** A host started for an app that's already running loses the lock and hands the running one a reply socket; the running host answers once its owner has connected, and the loser passes the address on to its own creator before quitting.
|
|
16
|
+
- **The owner decides its lifetime.** The first `UIHost` to connect — the one whose creator started the process that got the lock — owns the host, and the host quits when it disconnects. Everything another `UIHost` opened goes with it.
|
|
17
|
+
- **Throwaway hosts clean up after themselves.** An app with no name gets a throwaway one under temp; a small process (`cleanup.ts`) that outlives the host removes its `userData` once it's gone, however it ends.
|
|
18
|
+
- **The Dock icon** shows only while a window or dialog is open; trays live outside it.
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
- **Windows are sandboxed.** A window's page gets `window.cmdless` from the preload and nothing else. When it asks for its backend, the host asks the window's `UIHost`, which answers with a loopback WebSocket address and a token for one connection; the preload connects with it, and the page only ever sees a socket to send and hear messages on.
|
|
21
|
+
- **The host's own page** (`src/renderer`) draws cards and forms. Its content security policy allows no eval: the form validates with `@cfworker/json-schema` rather than ajv. It never navigates, links open in the browser, and Markdown in card text is rendered with raw HTML escaped. A card can hold a JSON Schema form as an input (`Input.JsonSchema`), which is how elicitation is asked. The page measures its content and the window fits its height to it.
|
|
21
22
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
|
|
25
|
-
2. Configure the trusted publisher (e.g., GitHub Actions)
|
|
26
|
-
3. Specify the repository and workflow that should be allowed to publish
|
|
27
|
-
4. Use the configured workflow to publish your actual package
|
|
28
|
-
|
|
29
|
-
## DO NOT USE THIS PACKAGE
|
|
30
|
-
|
|
31
|
-
This package is a placeholder for OIDC configuration only. It:
|
|
32
|
-
- Contains no executable code
|
|
33
|
-
- Provides no functionality
|
|
34
|
-
- Should not be installed as a dependency
|
|
35
|
-
- Exists only for administrative purposes
|
|
36
|
-
|
|
37
|
-
## More Information
|
|
38
|
-
|
|
39
|
-
For more details about npm's trusted publishing feature, see:
|
|
40
|
-
- [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
|
|
41
|
-
- [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
|
|
42
|
-
|
|
43
|
-
---
|
|
44
|
-
|
|
45
|
-
**Maintained for OIDC setup purposes only**
|
|
23
|
+
On macOS, as in Electron itself, a message box with no parent window runs synchronously: it holds up the whole host until it's answered, and can't be closed by code. One opened from a window is a sheet on it, and doesn't.
|
package/out/main/bin.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { spawn, execFileSync } from "node:child_process";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { Command } from "commander";
|
|
7
|
+
import { ensureElectron } from "@cmdless/ensure-electron";
|
|
8
|
+
import __cjs_mod__ from "node:module";
|
|
9
|
+
const __filename = import.meta.filename;
|
|
10
|
+
const __dirname = import.meta.dirname;
|
|
11
|
+
const require2 = __cjs_mod__.createRequire(import.meta.url);
|
|
12
|
+
const devDependencies = { "electron": "44.7.2" };
|
|
13
|
+
const pkg = {
|
|
14
|
+
devDependencies
|
|
15
|
+
};
|
|
16
|
+
const __dirname$1 = path.dirname(fileURLToPath(import.meta.url));
|
|
17
|
+
const hostEntry = path.join(__dirname$1, "host.js");
|
|
18
|
+
const electronVersion = pkg.devDependencies.electron;
|
|
19
|
+
function signForMacOS(execPath) {
|
|
20
|
+
if (process.platform !== "darwin") return;
|
|
21
|
+
const bundle = path.resolve(execPath, "../../..");
|
|
22
|
+
const marker = path.join(path.dirname(bundle), ".cmdless-signed");
|
|
23
|
+
if (fs.existsSync(marker)) return;
|
|
24
|
+
try {
|
|
25
|
+
execFileSync("codesign", ["--verify", "--deep", "--strict", bundle], { stdio: "ignore" });
|
|
26
|
+
} catch {
|
|
27
|
+
execFileSync("codesign", ["--force", "--deep", "--sign", "-", bundle], { stdio: "ignore" });
|
|
28
|
+
}
|
|
29
|
+
fs.writeFileSync(marker, "");
|
|
30
|
+
}
|
|
31
|
+
const program = new Command().name("ui-runtime");
|
|
32
|
+
program.command("host").description("Run the host for the app named in CMDLESS_APP (or a throwaway one)").action(async () => {
|
|
33
|
+
const execPath = await ensureElectron({ meta: import.meta, electronVersion, rebuild: true });
|
|
34
|
+
signForMacOS(execPath);
|
|
35
|
+
const child = spawn(execPath, [hostEntry], { stdio: "inherit" });
|
|
36
|
+
child.once("exit", (code) => {
|
|
37
|
+
process.exitCode = code ?? 1;
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
await program.parseAsync();
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
const SETTLE_MS = 500;
|
|
3
|
+
const RECHECK_MS = [2e3, 5e3];
|
|
4
|
+
const [userData] = process.argv.slice(2);
|
|
5
|
+
const remove = () => fs.promises.rm(userData, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {
|
|
6
|
+
});
|
|
7
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
8
|
+
process.stdin.on("end", async () => {
|
|
9
|
+
const { isEphemeralUserData } = await import("@cmdless/ui-sdk/node");
|
|
10
|
+
if (userData && isEphemeralUserData(userData)) {
|
|
11
|
+
await wait(SETTLE_MS);
|
|
12
|
+
await remove();
|
|
13
|
+
for (const ms of RECHECK_MS) {
|
|
14
|
+
await wait(ms);
|
|
15
|
+
if (fs.existsSync(userData)) await remove();
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
process.exit(0);
|
|
19
|
+
});
|
|
20
|
+
process.stdin.resume();
|
package/out/main/host.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { app } from "electron";
|
|
5
|
+
import { electronApp, optimizer } from "@electron-toolkit/utils";
|
|
6
|
+
import { rejectService, resolveCmdlessApp, isEphemeralCmdlessApp, listenOnce, resolveService, sendTo } from "@cmdless/ui-sdk/node";
|
|
7
|
+
import { Host } from "./hosting.js";
|
|
8
|
+
import "@cmdless/ui-sdk";
|
|
9
|
+
import "@cmdless/rpc-sdk";
|
|
10
|
+
import "@cmdless/rpc-sdk/node";
|
|
11
|
+
const cleanupEntry = path.join(path.dirname(fileURLToPath(import.meta.url)), "cleanup.js");
|
|
12
|
+
let cleaner;
|
|
13
|
+
function cleanUpWhenGone(userData) {
|
|
14
|
+
cleaner = spawn(process.execPath, [cleanupEntry, userData], {
|
|
15
|
+
env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
|
|
16
|
+
stdio: ["pipe", "ignore", "ignore"],
|
|
17
|
+
detached: true
|
|
18
|
+
});
|
|
19
|
+
cleaner.stdin?.on("error", () => {
|
|
20
|
+
});
|
|
21
|
+
cleaner.unref();
|
|
22
|
+
}
|
|
23
|
+
const OWNER_TIMEOUT_MS = 1e4;
|
|
24
|
+
async function main() {
|
|
25
|
+
process.on("SIGINT", () => app.quit());
|
|
26
|
+
process.on("SIGTERM", () => app.quit());
|
|
27
|
+
app.dock?.hide();
|
|
28
|
+
const appName = resolveCmdlessApp();
|
|
29
|
+
const ephemeral = isEphemeralCmdlessApp(appName);
|
|
30
|
+
const userData = path.join(app.getPath(ephemeral ? "temp" : "appData"), appName);
|
|
31
|
+
app.setName(appName);
|
|
32
|
+
app.setPath("userData", userData);
|
|
33
|
+
if (ephemeral) cleanUpWhenGone(userData);
|
|
34
|
+
const reply = await listenOnce();
|
|
35
|
+
if (!app.requestSingleInstanceLock({ reply: reply.socketPath })) {
|
|
36
|
+
try {
|
|
37
|
+
await resolveService(await reply.message);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
await rejectService(error).catch(() => {
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
return app.quit();
|
|
43
|
+
}
|
|
44
|
+
reply.close();
|
|
45
|
+
const ready = (async () => {
|
|
46
|
+
await app.whenReady();
|
|
47
|
+
electronApp.setAppUserModelId("dev.cmdless.ui");
|
|
48
|
+
app.on("browser-window-created", (_, window) => optimizer.watchWindowShortcuts(window));
|
|
49
|
+
app.on("window-all-closed", () => {
|
|
50
|
+
});
|
|
51
|
+
})();
|
|
52
|
+
const host = await Host.start({ appName, userData, ephemeral }, ready);
|
|
53
|
+
void host.ownerClosed.then(() => app.quit());
|
|
54
|
+
let docked = false;
|
|
55
|
+
host.onHandlesChanged((count) => {
|
|
56
|
+
if (count > 0 === docked) return;
|
|
57
|
+
docked = count > 0;
|
|
58
|
+
if (docked) void app.dock?.show();
|
|
59
|
+
else app.dock?.hide();
|
|
60
|
+
});
|
|
61
|
+
app.on("second-instance", async (_, __, ___, data) => {
|
|
62
|
+
try {
|
|
63
|
+
await host.owned;
|
|
64
|
+
await sendTo(data.reply, { type: "resolve", value: host.service });
|
|
65
|
+
} catch (error) {
|
|
66
|
+
console.error("ui-runtime: answering a second instance failed:", error);
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
await ready;
|
|
70
|
+
await resolveService(host.service);
|
|
71
|
+
const ownerTimeout = setTimeout(() => app.quit(), OWNER_TIMEOUT_MS);
|
|
72
|
+
void host.owned.then(() => clearTimeout(ownerTimeout));
|
|
73
|
+
}
|
|
74
|
+
void main().catch(async (error) => {
|
|
75
|
+
console.error(error);
|
|
76
|
+
await rejectService(error).catch(() => {
|
|
77
|
+
});
|
|
78
|
+
app.exit(1);
|
|
79
|
+
});
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { clipboard, shell, app, dialog, Tray, Menu, Notification, BrowserWindow, screen, nativeImage } from "electron";
|
|
4
|
+
import { cmdlessIPC, createElectronIPC, cmdlessViewIPC, createElectronViewIPC } from "@cmdless/ui-sdk";
|
|
5
|
+
import { getCmdlessUIVersion, getTmpSocketPath, UIHost } from "@cmdless/ui-sdk/node";
|
|
6
|
+
import { asElectronIPC } from "@cmdless/rpc-sdk";
|
|
7
|
+
import { startSocket } from "@cmdless/rpc-sdk/node";
|
|
8
|
+
import __cjs_mod__ from "node:module";
|
|
9
|
+
const __filename = import.meta.filename;
|
|
10
|
+
const __dirname = import.meta.dirname;
|
|
11
|
+
const require2 = __cjs_mod__.createRequire(import.meta.url);
|
|
12
|
+
const __dirname$1 = path.dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
const preloadPath = path.join(__dirname$1, "../preload/index.cjs");
|
|
14
|
+
const viewPath = path.join(__dirname$1, "../renderer/view.html");
|
|
15
|
+
async function openLink(url) {
|
|
16
|
+
const { protocol } = new URL(url);
|
|
17
|
+
if (!["http:", "https:", "mailto:"].includes(protocol)) throw new Error(`won't open a ${protocol} link`);
|
|
18
|
+
await shell.openExternal(url);
|
|
19
|
+
}
|
|
20
|
+
class UIHandle {
|
|
21
|
+
constructor(owner) {
|
|
22
|
+
this.owner = owner;
|
|
23
|
+
owner.add(this);
|
|
24
|
+
}
|
|
25
|
+
owner;
|
|
26
|
+
id = crypto.randomUUID();
|
|
27
|
+
disposed = false;
|
|
28
|
+
// what anything opened from it opens in front of - nothing, unless it's a
|
|
29
|
+
// window
|
|
30
|
+
get parent() {
|
|
31
|
+
return void 0;
|
|
32
|
+
}
|
|
33
|
+
// whether it's something the Dock icon is shown for - a window or a
|
|
34
|
+
// dialog; a tray lives outside the Dock. A getter, so it's already right
|
|
35
|
+
// while the base constructor adds it.
|
|
36
|
+
get showsInDock() {
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
// opens a window in front of this one, for the same UIHost
|
|
40
|
+
openWindow(params) {
|
|
41
|
+
return new WindowHandle(this.owner, params, this.parent);
|
|
42
|
+
}
|
|
43
|
+
// shows a dialog in front of this one, for the same UIHost
|
|
44
|
+
openDialog(params) {
|
|
45
|
+
return new DialogHandle(this.owner, params, this.parent);
|
|
46
|
+
}
|
|
47
|
+
// opens a card window in front of this one, for the same UIHost
|
|
48
|
+
openCard(params) {
|
|
49
|
+
return new CardHandle(this.owner, params, this.parent);
|
|
50
|
+
}
|
|
51
|
+
// opens a form window in front of this one, for the same UIHost
|
|
52
|
+
openForm(params) {
|
|
53
|
+
return new FormHandle(this.owner, params, this.parent);
|
|
54
|
+
}
|
|
55
|
+
// ends it, whoever asked - its UIHost, its renderer, the person closing
|
|
56
|
+
// it, or its connection going - telling its UIHost how it ended first
|
|
57
|
+
dispose(value, error) {
|
|
58
|
+
if (this.disposed) return;
|
|
59
|
+
this.disposed = true;
|
|
60
|
+
this.owner.remove(this, { id: this.id, value, error });
|
|
61
|
+
this.close();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
class ServerHandle {
|
|
65
|
+
constructor(server, isOwner, changed) {
|
|
66
|
+
this.server = server;
|
|
67
|
+
this.isOwner = isOwner;
|
|
68
|
+
this.changed = changed;
|
|
69
|
+
server.onClose(() => {
|
|
70
|
+
this.connected = false;
|
|
71
|
+
for (const handle of [...this.handles.values()]) handle.dispose();
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
server;
|
|
75
|
+
isOwner;
|
|
76
|
+
changed;
|
|
77
|
+
id = crypto.randomUUID();
|
|
78
|
+
handles = /* @__PURE__ */ new Map();
|
|
79
|
+
connected = true;
|
|
80
|
+
add(handle) {
|
|
81
|
+
this.handles.set(handle.id, handle);
|
|
82
|
+
this.changed();
|
|
83
|
+
}
|
|
84
|
+
remove(handle, closed) {
|
|
85
|
+
if (!this.handles.delete(handle.id)) return;
|
|
86
|
+
if (this.connected) this.server.notify.handleClosed(closed);
|
|
87
|
+
this.changed();
|
|
88
|
+
}
|
|
89
|
+
trayEvent(params) {
|
|
90
|
+
if (this.connected) this.server.notify.trayEvent(params);
|
|
91
|
+
}
|
|
92
|
+
cardEvent(params) {
|
|
93
|
+
if (this.connected) this.server.notify.cardEvent(params);
|
|
94
|
+
}
|
|
95
|
+
// a window's page asking for its backend: its UIHost says where, with a
|
|
96
|
+
// token for one connection
|
|
97
|
+
windowConnect(params) {
|
|
98
|
+
if (!this.connected) throw new Error("the window's UIHost has gone");
|
|
99
|
+
return this.server.request.windowConnect(params);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function createWindow(handle, { width, height, title } = {}, defaults, parent, preload, showWhenReady = true) {
|
|
103
|
+
const win = new BrowserWindow({
|
|
104
|
+
parent,
|
|
105
|
+
width: width ?? defaults.width,
|
|
106
|
+
height: height ?? defaults.height,
|
|
107
|
+
show: false,
|
|
108
|
+
autoHideMenuBar: true,
|
|
109
|
+
title: title ?? app.getName(),
|
|
110
|
+
webPreferences: {
|
|
111
|
+
preload: preload ? preloadPath : void 0,
|
|
112
|
+
contextIsolation: true,
|
|
113
|
+
nodeIntegration: false,
|
|
114
|
+
sandbox: true
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
win.on("closed", () => handle.dispose());
|
|
118
|
+
if (showWhenReady) win.on("ready-to-show", () => bringUp(win));
|
|
119
|
+
if (title) win.on("page-title-updated", (event) => event.preventDefault());
|
|
120
|
+
return win;
|
|
121
|
+
}
|
|
122
|
+
function bringUp(win) {
|
|
123
|
+
app.focus({ steal: true });
|
|
124
|
+
win.show();
|
|
125
|
+
}
|
|
126
|
+
const FIT_SCREEN_SHARE = 0.8;
|
|
127
|
+
const FIT_MIN_HEIGHT = 120;
|
|
128
|
+
function browserUserAgent() {
|
|
129
|
+
return app.userAgentFallback.replace(/ (?!Mozilla|AppleWebKit|Chrome|Safari)[\w.-]+\/[\w.-]+/g, "");
|
|
130
|
+
}
|
|
131
|
+
class WindowHandle extends UIHandle {
|
|
132
|
+
window;
|
|
133
|
+
constructor(owner, parameters, parent) {
|
|
134
|
+
super(owner);
|
|
135
|
+
const { type, source, redirect, window } = parameters;
|
|
136
|
+
const external = redirect !== void 0 || parameters.external === true;
|
|
137
|
+
const win = this.window = createWindow(this, window, { width: 900, height: 670 }, parent, !external);
|
|
138
|
+
if (redirect) {
|
|
139
|
+
const capture = (event, url) => {
|
|
140
|
+
if (!url.startsWith(redirect)) return;
|
|
141
|
+
event.preventDefault();
|
|
142
|
+
this.dispose(url);
|
|
143
|
+
};
|
|
144
|
+
win.webContents.on("will-redirect", capture);
|
|
145
|
+
win.webContents.on("will-navigate", capture);
|
|
146
|
+
}
|
|
147
|
+
if (external) {
|
|
148
|
+
const userAgent = browserUserAgent();
|
|
149
|
+
win.webContents.setUserAgent(userAgent);
|
|
150
|
+
win.webContents.setWindowOpenHandler(() => ({
|
|
151
|
+
action: "allow",
|
|
152
|
+
overrideBrowserWindowOptions: {
|
|
153
|
+
parent: win,
|
|
154
|
+
autoHideMenuBar: true,
|
|
155
|
+
webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true }
|
|
156
|
+
}
|
|
157
|
+
}));
|
|
158
|
+
win.webContents.on("did-create-window", (child) => child.webContents.setUserAgent(userAgent));
|
|
159
|
+
} else {
|
|
160
|
+
win.webContents.setWindowOpenHandler((details) => {
|
|
161
|
+
shell.openExternal(details.url);
|
|
162
|
+
return { action: "deny" };
|
|
163
|
+
});
|
|
164
|
+
const ipc = cmdlessIPC.createServer(createElectronIPC(asElectronIPC(win.webContents.ipc, win.webContents)));
|
|
165
|
+
ipc.onNotification.resolve(({ value, exitCode = 0 }) => exitCode === 0 ? this.dispose(value) : this.dispose(void 0, `the window exited with code ${exitCode}`));
|
|
166
|
+
ipc.onRequest.connect(() => owner.windowConnect({ id: this.id }));
|
|
167
|
+
ipc.listen();
|
|
168
|
+
}
|
|
169
|
+
const load = type === "url" ? win.loadURL(source) : loadFileWithHash(win, source);
|
|
170
|
+
load.catch((error) => this.dispose(void 0, String(error)));
|
|
171
|
+
}
|
|
172
|
+
get parent() {
|
|
173
|
+
return this.window;
|
|
174
|
+
}
|
|
175
|
+
close() {
|
|
176
|
+
if (!this.window.isDestroyed()) this.window.close();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
class ViewHandle extends UIHandle {
|
|
180
|
+
window;
|
|
181
|
+
view;
|
|
182
|
+
constructor(owner, props, { window }, parent) {
|
|
183
|
+
super(owner);
|
|
184
|
+
let fitting = window?.height === void 0;
|
|
185
|
+
const win = this.window = createWindow(this, window, { width: 520, height: 640 }, parent, true, !fitting);
|
|
186
|
+
win.on("will-resize", () => {
|
|
187
|
+
fitting = false;
|
|
188
|
+
});
|
|
189
|
+
win.webContents.setWindowOpenHandler(({ url }) => {
|
|
190
|
+
openLink(url).catch(() => {
|
|
191
|
+
});
|
|
192
|
+
return { action: "deny" };
|
|
193
|
+
});
|
|
194
|
+
win.webContents.on("will-navigate", (event) => event.preventDefault());
|
|
195
|
+
const view = this.view = cmdlessViewIPC.createServer(createElectronViewIPC(asElectronIPC(win.webContents.ipc, win.webContents)));
|
|
196
|
+
view.onRequest.props(() => props);
|
|
197
|
+
view.onNotification.close(({ value }) => this.dispose(value));
|
|
198
|
+
view.onNotification.resize(({ height }) => {
|
|
199
|
+
if (!fitting || win.isDestroyed()) return;
|
|
200
|
+
const [width] = win.getContentSize();
|
|
201
|
+
const { workArea } = screen.getDisplayMatching(win.getBounds());
|
|
202
|
+
const fitted = Math.max(FIT_MIN_HEIGHT, Math.min(Math.ceil(height), Math.floor(workArea.height * FIT_SCREEN_SHARE)));
|
|
203
|
+
win.setContentSize(width, fitted);
|
|
204
|
+
if (!win.isVisible()) {
|
|
205
|
+
win.center();
|
|
206
|
+
bringUp(win);
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
this.listen(view);
|
|
210
|
+
view.listen();
|
|
211
|
+
win.loadFile(viewPath).catch((error) => this.dispose(void 0, String(error)));
|
|
212
|
+
}
|
|
213
|
+
// what else this kind hears from its page
|
|
214
|
+
listen(_view) {
|
|
215
|
+
}
|
|
216
|
+
get parent() {
|
|
217
|
+
return this.window;
|
|
218
|
+
}
|
|
219
|
+
close() {
|
|
220
|
+
if (!this.window.isDestroyed()) this.window.close();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
class CardHandle extends ViewHandle {
|
|
224
|
+
constructor(owner, { card, hostConfig, window }, parent) {
|
|
225
|
+
super(owner, { view: "card", card, hostConfig }, { window }, parent);
|
|
226
|
+
}
|
|
227
|
+
listen(view) {
|
|
228
|
+
view.onNotification.event((event) => this.owner.cardEvent({ id: this.id, ...event }));
|
|
229
|
+
}
|
|
230
|
+
update({ card }) {
|
|
231
|
+
this.view.notify.update({ card });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
class FormHandle extends ViewHandle {
|
|
235
|
+
constructor(owner, { schema, uiSchema, formData, submitText, window }, parent) {
|
|
236
|
+
super(owner, { view: "form", schema, uiSchema, formData, submitText }, { window }, parent);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
function loadFileWithHash(win, source) {
|
|
240
|
+
const match = /^([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/.exec(source);
|
|
241
|
+
return win.loadFile(match[1], { search: match[2], hash: match[3] });
|
|
242
|
+
}
|
|
243
|
+
class DialogHandle extends UIHandle {
|
|
244
|
+
dismissed = new AbortController();
|
|
245
|
+
constructor(owner, params, parent) {
|
|
246
|
+
super(owner);
|
|
247
|
+
const { type, message, detail, buttons, defaultId, cancelId } = params;
|
|
248
|
+
const options = { type, message, detail, buttons, defaultId, cancelId, signal: this.dismissed.signal };
|
|
249
|
+
if (!parent) app.focus({ steal: true });
|
|
250
|
+
const shown = parent ? dialog.showMessageBox(parent, options) : dialog.showMessageBox(options);
|
|
251
|
+
shown.then(
|
|
252
|
+
({ response, checkboxChecked }) => this.dispose({ response, checkboxChecked }),
|
|
253
|
+
(error) => this.dispose(void 0, String(error))
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
close() {
|
|
257
|
+
this.dismissed.abort();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
class TrayHandle extends UIHandle {
|
|
261
|
+
tray;
|
|
262
|
+
constructor(owner, params) {
|
|
263
|
+
const image = trayImage(params.icon);
|
|
264
|
+
super(owner);
|
|
265
|
+
this.tray = new Tray(image);
|
|
266
|
+
this.tray.on("click", () => owner.trayEvent({ id: this.id, event: "click" }));
|
|
267
|
+
this.update({ ...params, icon: void 0 });
|
|
268
|
+
}
|
|
269
|
+
// changes what was given, and leaves the rest
|
|
270
|
+
update({ icon, tooltip, title, menu }) {
|
|
271
|
+
if (icon !== void 0) this.tray.setImage(trayImage(icon));
|
|
272
|
+
if (tooltip !== void 0) this.tray.setToolTip(tooltip);
|
|
273
|
+
if (title !== void 0) this.tray.setTitle(title);
|
|
274
|
+
if (menu !== void 0) this.tray.setContextMenu(this.buildMenu(menu));
|
|
275
|
+
}
|
|
276
|
+
buildMenu(menu) {
|
|
277
|
+
return Menu.buildFromTemplate(menu.map((item) => {
|
|
278
|
+
switch (item.type) {
|
|
279
|
+
case "separator":
|
|
280
|
+
return { type: "separator" };
|
|
281
|
+
case "submenu":
|
|
282
|
+
return { label: item.label, enabled: item.enabled, submenu: this.buildMenu(item.submenu) };
|
|
283
|
+
default:
|
|
284
|
+
return {
|
|
285
|
+
type: item.type ?? "normal",
|
|
286
|
+
label: item.label,
|
|
287
|
+
checked: item.checked,
|
|
288
|
+
enabled: item.enabled,
|
|
289
|
+
click: () => this.owner.trayEvent({ id: this.id, event: "menu-item", item: item.id })
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
}));
|
|
293
|
+
}
|
|
294
|
+
get showsInDock() {
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
close() {
|
|
298
|
+
if (!this.tray.isDestroyed()) this.tray.destroy();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
class NotificationHandle extends UIHandle {
|
|
302
|
+
notification;
|
|
303
|
+
constructor(owner, params) {
|
|
304
|
+
if (!Notification.isSupported()) throw new Error("notifications aren't supported here");
|
|
305
|
+
super(owner);
|
|
306
|
+
const notification = this.notification = new Notification({ title: params.title, body: params.body });
|
|
307
|
+
notification.on("click", () => this.dispose("click"));
|
|
308
|
+
notification.on("close", () => this.dispose());
|
|
309
|
+
notification.on("failed", (_, error) => this.dispose(void 0, `the notification couldn't be shown: ${error}`));
|
|
310
|
+
notification.show();
|
|
311
|
+
}
|
|
312
|
+
get showsInDock() {
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
close() {
|
|
316
|
+
this.notification.close();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
function trayImage(icon) {
|
|
320
|
+
const image = nativeImage.createFromPath(icon);
|
|
321
|
+
if (image.isEmpty()) throw new Error(`no image at ${icon}`);
|
|
322
|
+
return image;
|
|
323
|
+
}
|
|
324
|
+
class Host {
|
|
325
|
+
constructor(service, owned) {
|
|
326
|
+
this.service = service;
|
|
327
|
+
this.owned = owned;
|
|
328
|
+
this.ownerClosed = owned.then((owner) => new Promise((resolve) => owner.server.onClose(resolve)));
|
|
329
|
+
}
|
|
330
|
+
service;
|
|
331
|
+
servers = /* @__PURE__ */ new Map();
|
|
332
|
+
// settles once the owner has connected, and once it has gone
|
|
333
|
+
owned;
|
|
334
|
+
ownerClosed;
|
|
335
|
+
handlesListeners = /* @__PURE__ */ new Set();
|
|
336
|
+
// how many windows and dialogs are open, across every UIHost - what the
|
|
337
|
+
// Dock icon is shown for (trays aren't)
|
|
338
|
+
get shownCount() {
|
|
339
|
+
let count = 0;
|
|
340
|
+
for (const server of this.servers.values())
|
|
341
|
+
for (const handle of server.handles.values()) if (handle.showsInDock) count++;
|
|
342
|
+
return count;
|
|
343
|
+
}
|
|
344
|
+
onHandlesChanged(listener) {
|
|
345
|
+
this.handlesListeners.add(listener);
|
|
346
|
+
return { dispose: () => {
|
|
347
|
+
this.handlesListeners.delete(listener);
|
|
348
|
+
} };
|
|
349
|
+
}
|
|
350
|
+
handlesChanged() {
|
|
351
|
+
const count = this.shownCount;
|
|
352
|
+
for (const listener of [...this.handlesListeners]) listener(count);
|
|
353
|
+
}
|
|
354
|
+
// listens on a fresh local address and serves UIHosts there. `ready` is
|
|
355
|
+
// whatever has to be done before a UIHost is answered (Electron's own
|
|
356
|
+
// readiness, for one) - connecting doesn't wait on it, initializing does.
|
|
357
|
+
static async start(info, ready) {
|
|
358
|
+
const sdkVersion = await getCmdlessUIVersion();
|
|
359
|
+
let ownerConnected;
|
|
360
|
+
const owned = new Promise((resolve) => ownerConnected = resolve);
|
|
361
|
+
let hasOwner = false;
|
|
362
|
+
const address = getTmpSocketPath(`cmdless-ui-host-${crypto.randomUUID()}`);
|
|
363
|
+
const host = new Host({ address }, owned);
|
|
364
|
+
const { accept } = await UIHost.protocol.defineHost({
|
|
365
|
+
configure: (server) => {
|
|
366
|
+
let handle;
|
|
367
|
+
const initialized = () => {
|
|
368
|
+
if (!handle) throw new Error("initialize first");
|
|
369
|
+
return handle;
|
|
370
|
+
};
|
|
371
|
+
server.onRequest.init(async (params) => {
|
|
372
|
+
await ready;
|
|
373
|
+
if (handle) throw new Error("already initialized");
|
|
374
|
+
if (params.sdkVersion !== sdkVersion)
|
|
375
|
+
throw new Error(`${info.appName} is running @cmdless/ui-sdk ${sdkVersion}, not ${params.sdkVersion} - close it to use ${params.sdkVersion}`);
|
|
376
|
+
const owner = !hasOwner;
|
|
377
|
+
hasOwner = true;
|
|
378
|
+
const current = handle = new ServerHandle(server, owner, () => host.handlesChanged());
|
|
379
|
+
host.servers.set(current.id, current);
|
|
380
|
+
server.onClose(() => host.servers.delete(current.id));
|
|
381
|
+
if (owner) ownerConnected(current);
|
|
382
|
+
const result = { ...info, sdkVersion, hasSingleInstanceLock: owner };
|
|
383
|
+
return result;
|
|
384
|
+
});
|
|
385
|
+
const opener = (parent) => {
|
|
386
|
+
if (parent === void 0) return void 0;
|
|
387
|
+
const from = initialized().handles.get(parent);
|
|
388
|
+
if (!from) throw new Error(`no handle ${parent}`);
|
|
389
|
+
return from;
|
|
390
|
+
};
|
|
391
|
+
server.onRequest.windowOpen(({ parent, ...params }) => {
|
|
392
|
+
const from = opener(parent);
|
|
393
|
+
return { id: (from ? from.openWindow(params) : new WindowHandle(initialized(), params)).id };
|
|
394
|
+
});
|
|
395
|
+
server.onRequest.dialogOpen(({ parent, ...params }) => {
|
|
396
|
+
const from = opener(parent);
|
|
397
|
+
return { id: (from ? from.openDialog(params) : new DialogHandle(initialized(), params)).id };
|
|
398
|
+
});
|
|
399
|
+
server.onRequest.cardOpen(({ parent, ...params }) => {
|
|
400
|
+
const from = opener(parent);
|
|
401
|
+
return { id: (from ? from.openCard(params) : new CardHandle(initialized(), params)).id };
|
|
402
|
+
});
|
|
403
|
+
server.onRequest.cardUpdate(({ id, card }) => {
|
|
404
|
+
const found = initialized().handles.get(id);
|
|
405
|
+
if (!(found instanceof CardHandle)) throw new Error(`no card ${id}`);
|
|
406
|
+
found.update({ card });
|
|
407
|
+
});
|
|
408
|
+
server.onRequest.formOpen(({ parent, ...params }) => {
|
|
409
|
+
const from = opener(parent);
|
|
410
|
+
return { id: (from ? from.openForm(params) : new FormHandle(initialized(), params)).id };
|
|
411
|
+
});
|
|
412
|
+
server.onRequest.trayCreate((params) => ({ id: new TrayHandle(initialized(), params).id }));
|
|
413
|
+
server.onRequest.notificationShow((params) => ({ id: new NotificationHandle(initialized(), params).id }));
|
|
414
|
+
server.onRequest.trayUpdate(({ id, ...params }) => {
|
|
415
|
+
const found = initialized().handles.get(id);
|
|
416
|
+
if (!(found instanceof TrayHandle)) throw new Error(`no tray ${id}`);
|
|
417
|
+
found.update(params);
|
|
418
|
+
});
|
|
419
|
+
server.onRequest.shellOpenExternal(async ({ url }) => {
|
|
420
|
+
initialized();
|
|
421
|
+
await openLink(url);
|
|
422
|
+
});
|
|
423
|
+
server.onRequest.clipboardWriteText(({ text }) => {
|
|
424
|
+
initialized();
|
|
425
|
+
clipboard.writeText(text);
|
|
426
|
+
});
|
|
427
|
+
server.onRequest.handleClose(({ id, value }) => {
|
|
428
|
+
const found = initialized().handles.get(id);
|
|
429
|
+
if (!found) throw new Error(`no handle ${id}`);
|
|
430
|
+
found.dispose(value);
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
})();
|
|
434
|
+
await startSocket({ accept, options: { path: address } });
|
|
435
|
+
return host;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
export {
|
|
439
|
+
CardHandle,
|
|
440
|
+
DialogHandle,
|
|
441
|
+
FormHandle,
|
|
442
|
+
Host,
|
|
443
|
+
NotificationHandle,
|
|
444
|
+
ServerHandle,
|
|
445
|
+
TrayHandle,
|
|
446
|
+
UIHandle,
|
|
447
|
+
WindowHandle
|
|
448
|
+
};
|