@cossackframework/desktop 0.8.3 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,36 +5,98 @@ the renderer and local Cossack SSR/RPC over the private `cossack://app` origin,
5
5
  injecting `ASSETS` and a window-scoped `COSSACK_DESKTOP` shell into request
6
6
  bindings.
7
7
 
8
+ The generated `src/desktop/index.ts` exports its application and bootstrap so
9
+ `desktop:dev` can load server modules through Vite inside Electron:
10
+
8
11
  ```ts
9
- import { createDesktopApp } from '@cossackframework/desktop';
12
+ import { app, createDesktopApp, electronRuntimeAdapter } from '@cossackframework/desktop';
13
+ import { createApp } from '@cossackframework/framework/router';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { App } from '../App';
16
+ import { template } from '../root';
17
+
18
+ export function createEnv(variables: Record<string, string | undefined> = process.env) {
19
+ return { ...variables };
20
+ }
21
+ export const env = import.meta.env.DEV ? {} : createEnv();
22
+ export const frameworkApp = createApp({
23
+ AppComponent: App,
24
+ htmlTemplate: template,
25
+ runtimeAdapter: electronRuntimeAdapter,
26
+ });
10
27
 
11
- async function main() {
12
- await createDesktopApp({
28
+ export async function startDesktop(createApplication = createDesktopApp) {
29
+ const desktop = await createApplication({
13
30
  identifier: 'dev.cossack.my-app',
14
31
  productName: 'My App',
15
- assetsRoot: new URL('../../client/', import.meta.url).pathname,
16
- fetch: (request, env) => app.fetch(request, env),
32
+ assetsRoot: fileURLToPath(new URL('../client/', import.meta.url)),
33
+ env,
34
+ fetch: (request, bindings) => frameworkApp.fetch(request, bindings),
17
35
  });
36
+ // Set up native menus, trays and close behavior here.
37
+ return desktop;
18
38
  }
19
39
 
20
- void main();
40
+ if (!import.meta.env.DEV) {
41
+ void startDesktop().catch(error => { console.error(error); app.exit(1); });
42
+ }
21
43
  ```
22
44
 
23
- Do not top-level `await` `createDesktopApp()` in an ESM entry. Electron fires
24
- `ready` after the main module's first event-loop tick completes, while Desktop
25
- creation waits for `ready`; start an async function without awaiting it at the
26
- module's top level as shown above.
45
+ Do not top-level `await` `createDesktopApp()` in an ESM entry. Electron emits
46
+ `ready` after the main module's first event-loop tick. Desktop creation waits
47
+ for that event. Development calls the exported bootstrap once. Production starts
48
+ it through the guarded call above.
49
+
50
+ `pnpm desktop:dev` requires Vite 8.1.4 or later in the 8.x series. The CLI
51
+ supervises Electron, which runs the development module loader and asset server.
52
+ Pages retain the private origin and native request checks. Source edits reload
53
+ managed windows. Changes under `src/desktop/`, to the Vite configuration, or to
54
+ root `.env*` files restart Electron. Reloads do not undo application side effects.
55
+ Development passes only declared bindings: the `env` given to
56
+ `createDesktopApp()` and the bootstrap's `env` export, or the result of an
57
+ exported `createEnv(variables)`, which receives the root `.env*` values for the
58
+ `desktop` mode and the process variables. Other host variables are not exposed.
59
+ Page syntax errors remain visible and source repair can recover without
60
+ restarting the CLI.
61
+
62
+ Keep `ssr.noExternal: true` restricted to production Desktop builds:
63
+ `mode === 'desktop' && command === 'build'`. Development needs normal external
64
+ package resolution. Do not register another server that exposes native handlers
65
+ on HTTP. Enable `developmentTraces: true` in `cossackPages()` to use the shared
66
+ inspector and CLI/MCP capture readers.
67
+
68
+ `createDesktopApp()` serves only hashed build output under `/assets/` before
69
+ the application, with `Cache-Control: public, max-age=31536000, immutable` for
70
+ hashed names. A missing `/assets/` file continues to the application. Every
71
+ other request, including `public/` files, goes to the application. The
72
+ framework serves those files from `ASSETS` after global and page policies, with
73
+ `Cache-Control: public, max-age=0, must-revalidate`.
74
+
75
+ The optional `assets.fetch(request)` provider on `createDesktopApp()` replaces
76
+ filesystem lookup in `assetsRoot`. The runtime asks it for `/assets/*` before
77
+ the application and cancels the body of a 404. It is also the application's
78
+ `ASSETS` binding. The development runner supplies a Vite provider. It sends
79
+ requests for `publicDir` files to the application, so their policies run, and
80
+ lets Vite answer its client and modules first. Ordinary packaged apps use
81
+ `assetsRoot`. Native proof headers are stripped before either provider or
82
+ application code receives a request.
27
83
 
28
84
  `createDesktopApp()` forces context isolation and renderer sandboxing, with Node
29
85
  integration and preload bridges disabled. Only same-origin navigation is
30
- allowed; valid HTTP(S) popups are opened in the operating-system browser.
31
- Desktop pages currently require `@Page({ transport: 'http' })`.
86
+ allowed. Valid HTTP(S) popups are opened in the operating-system browser.
87
+ Desktop pages require `@Page({ transport: 'http' })`.
32
88
 
33
- On Linux, `desktop:dev` checks Electron's local `chrome-sandbox` helper. pnpm's
89
+ Use Electron 43.7+ in the 43.x series, or 44.4+. The runtime enforces native
90
+ request initiators and managed window identity before dispatching local actions.
91
+ Cossack reserves the `persist:cossack.<identifier>` session and its
92
+ `onBeforeSendHeaders` hook. Default-session cookies/storage are not migrated.
93
+ Keep the identifier stable. Native app files retain their existing paths.
94
+
95
+ On Linux, `desktop:dev` inspects Electron's local `chrome-sandbox` helper. pnpm's
34
96
  download is normally user-owned rather than root-owned/setuid, so the runner
35
97
  prints a warning and applies Electron's testing-only `--no-sandbox` flag to the
36
98
  development process. Forge packages and installed DEB applications do not use
37
- this fallback; the DEB installs its helper with the required permissions.
99
+ this fallback. The DEB installs its helper with the required permissions.
38
100
  For Wayland sessions that expose XWayland, the development runner selects X11
39
101
  to avoid Chromium's current Wayland/Vulkan incompatibility and hides nonfatal
40
102
  GPU probe noise. Set `COSSACK_DESKTOP_OZONE_PLATFORM=wayland` to force native
@@ -43,13 +105,13 @@ Desktop lifecycle tracing.
43
105
 
44
106
  The generated Linux desktop entry also starts the installed DEB through
45
107
  XWayland so Electron can register its tray with GNOME's StatusNotifier host.
46
- An unpacked Forge executable bypasses that desktop entry; launch it with both
47
- `--no-sandbox` and `--ozone-platform=x11` when testing directly from `out/`.
108
+ An unpacked Forge executable bypasses that desktop entry. Launch it with both
109
+ `--no-sandbox` and `--ozone-platform=x11` when you test it directly from `out/`.
48
110
  The sandbox flag is only appropriate for that uninstalled test package.
49
111
 
50
112
  Node 22 or 24 LTS is recommended for Forge packaging. Node 26 is supported, but
51
113
  the current Forge/Packager ZIP stack can extract Electron pathologically slowly
52
- there; generated Desktop projects declare `node: ">=22"`.
114
+ there. Generated Desktop projects declare `node: ">=22"`.
53
115
 
54
116
  Use Electron APIs in the bootstrap or through ordinary `@Server()` methods via
55
117
  `this.env.COSSACK_DESKTOP`. There is deliberately no renderer client or generic
@@ -79,6 +141,12 @@ const close = configureDesktopClose({
79
141
  });
80
142
  ```
81
143
 
144
+ `desktop.mainWindow` is a live getter. It changes when the main window closes
145
+ while another managed window stays open, and when macOS activation, a second
146
+ instance or `desktop.show()` must create a new window. `desktop.shell` is
147
+ stable and its window methods always target the current main window. A close
148
+ policy applies to the window it was given.
149
+
82
150
  `quit` closes the application, `hide-to-tray` hides only while its tray is
83
151
  alive and otherwise quits, and `confirm-quit` uses an asynchronous native
84
152
  dialog. Linux tray activation varies by desktop host, so prefer
@@ -1,4 +1,3 @@
1
- export declare function isSuccessfulBuildOutput(value: string): boolean;
2
1
  export interface SandboxHelperMetadata {
3
2
  uid: number;
4
3
  mode: number;
package/dist/dev.js CHANGED
@@ -3,8 +3,9 @@ import { spawn as e } from "node:child_process";
3
3
  import t from "node:path";
4
4
  import { statSync as n } from "node:fs";
5
5
  import { createRequire as r } from "node:module";
6
+ import { fileURLToPath as i } from "node:url";
6
7
  //#region src/platform.ts
7
- function i(e, t, n = "auto") {
8
+ function a(e, t, n = "auto") {
8
9
  if (e !== "linux") return;
9
10
  if (n !== "auto") return n;
10
11
  let r = t.COSSACK_DESKTOP_OZONE_PLATFORM;
@@ -13,103 +14,57 @@ function i(e, t, n = "auto") {
13
14
  }
14
15
  //#endregion
15
16
  //#region src/dev-signals.ts
16
- function a(e) {
17
- return /built in \d|built in [\d.]+s/i.test(e);
18
- }
19
17
  function o(e, t) {
20
18
  return e === "linux" ? t?.uid === 0 && t.mode & 2048 ? [] : ["--no-sandbox"] : [];
21
19
  }
22
20
  function s(e, t) {
23
21
  if (e !== "linux") return [];
24
- let n = [], r = i(e, t);
22
+ let n = [], r = a(e, t);
25
23
  return r && n.push(`--ozone-platform=${r}`), t.COSSACK_DESKTOP_DEBUG !== "1" && n.push("--log-level=3"), n;
26
24
  }
27
25
  //#endregion
28
26
  //#region src/dev.ts
29
- var c = process.cwd(), l = r(t.join(c, "package.json")), u = t.join(t.dirname(l.resolve("vite/package.json")), "bin", "vite.js"), d = l("electron"), f = t.resolve(c, "dist/desktop/index.js"), p;
27
+ var c = process.cwd(), l = r(t.join(c, "package.json"))("electron"), u;
30
28
  try {
31
- let e = n(t.join(t.dirname(d), "chrome-sandbox"));
32
- p = {
29
+ let e = n(t.join(t.dirname(l), "chrome-sandbox"));
30
+ u = {
33
31
  uid: e.uid,
34
32
  mode: e.mode
35
33
  };
36
34
  } catch {}
37
- var m = [...o(process.platform, p), ...s(process.platform, process.env)];
38
- m.includes("--no-sandbox") && process.stderr.write("[desktop] Linux SUID sandbox helper is not root-owned with mode 4755; using Electron --no-sandbox for desktop:dev only. Packaged installers remain sandboxed.\n");
39
- var h, g = !1, _ = !1, v = !1, y = !1;
40
- function b(e, t, n) {
41
- e.stdout?.on("data", (e) => {
42
- let r = e.toString();
43
- process.stdout.write(`[${t}] ${r}`), a(r) && n();
44
- }), e.stderr?.on("data", (e) => {
45
- let r = e.toString();
46
- process.stderr.write(`[${t}] ${r}`), a(r) && n();
47
- }), e.on("exit", (e) => {
48
- !v && e !== 0 && w(e ?? 1);
49
- });
35
+ var d = [...o(process.platform, u), ...s(process.platform, process.env)];
36
+ d.includes("--no-sandbox") && process.stderr.write("[desktop] Using the development-only Linux --no-sandbox fallback for an unconfigured SUID helper.\n");
37
+ var f, p = !1, m = !1, h;
38
+ function g(e = 0) {
39
+ p || (p = !0, process.exitCode = e, f?.kill("SIGTERM"), f && (h = setTimeout(() => f?.kill("SIGKILL"), 6e3)));
50
40
  }
51
- function x() {
52
- !g || !_ || v || (h = e(d, [...m, f], {
41
+ var _ = process.argv.slice(2);
42
+ _[0] === "--" && _.shift();
43
+ function v() {
44
+ f = e(l, [
45
+ ...d,
46
+ ..._,
47
+ t.join(t.dirname(i(import.meta.url)), "development-runtime.js")
48
+ ], {
53
49
  cwd: c,
54
50
  stdio: [
55
- "inherit",
51
+ "ignore",
56
52
  "inherit",
57
53
  "inherit",
58
54
  "ipc"
59
- ]
60
- }), h.on("exit", (e, t) => {
61
- let n = y;
62
- y = !1, h = void 0, !v && (n ? x() : w(e ?? +!!t));
63
- }));
64
- }
65
- function S() {
66
- if (!h) return x();
67
- y = !0, h.kill();
68
- }
69
- function C() {
70
- h?.connected ? h.send?.({ type: "cossack:renderer-reload" }) : x();
71
- }
72
- function w(e = 0) {
73
- v || (v = !0, T.kill(), E.kill(), h?.kill(), process.exitCode = e);
55
+ ],
56
+ env: {
57
+ ...process.env,
58
+ NODE_ENV: "development",
59
+ ELECTRON_RUN_AS_NODE: ""
60
+ }
61
+ }), f.once("error", (e) => {
62
+ console.error("[desktop]", e), g(1);
63
+ }), f.on("message", (e) => {
64
+ !p && e?.type === "cossack:desktop-restart" && (m = !0, f?.kill("SIGTERM"), h ??= setTimeout(() => f?.kill("SIGKILL"), 6e3));
65
+ }), f.once("exit", (e, t) => {
66
+ clearTimeout(h), h = void 0, f = void 0, !p && (m ? (m = !1, v()) : g(e ?? +!!t));
67
+ });
74
68
  }
75
- var T = e(process.execPath, [
76
- u,
77
- "build",
78
- "--watch"
79
- ], {
80
- cwd: c,
81
- stdio: [
82
- "ignore",
83
- "pipe",
84
- "pipe"
85
- ]
86
- }), E = e(process.execPath, [
87
- u,
88
- "build",
89
- "--mode",
90
- "desktop",
91
- "--ssr",
92
- "src/desktop/index.ts",
93
- "--outDir",
94
- "dist/desktop",
95
- "--watch",
96
- "--minify",
97
- "false"
98
- ], {
99
- cwd: c,
100
- stdio: [
101
- "ignore",
102
- "pipe",
103
- "pipe"
104
- ]
105
- });
106
- b(T, "renderer", () => {
107
- let e = !g;
108
- g = !0, e ? x() : C();
109
- }), b(E, "main", () => {
110
- let e = !_;
111
- _ = !0, e ? x() : S();
112
- }), process.once("SIGINT", () => w(130)), process.once("SIGTERM", () => w(143)), process.once("exit", () => {
113
- v = !0, T.kill(), E.kill(), h?.kill();
114
- });
69
+ process.once("SIGINT", () => g()), process.once("SIGTERM", () => g()), process.once("exit", () => f?.kill("SIGTERM")), v();
115
70
  //#endregion
@@ -0,0 +1,7 @@
1
+ /**
2
+ * True when Vite would answer this request with a plain file from `publicDir`.
3
+ * Desktop development sends these requests through the application, so global
4
+ * and page policies run before the file is served, as in production. Vite
5
+ * still answers its client, modules and other requests first.
6
+ */
7
+ export declare function isPublicFileRequest(request: Request, publicDir: string): Promise<boolean>;
@@ -0,0 +1,2 @@
1
+ /** Keep Vite connected after a source error without injecting exception text as HTML. */
2
+ export declare function desktopDevelopmentError(error: unknown): Response;
@@ -0,0 +1,2 @@
1
+ /** Inject Vite into document responses without consuming opaque RPC/API bodies. */
2
+ export declare function transformDesktopDocument(request: Request, response: Response, transform: (pathname: string, html: string) => Promise<string>): Promise<Response>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,196 @@
1
+ import { c as e, o as t, t as n } from "./src-LxY0vJPo.js";
2
+ import { stat as r } from "node:fs/promises";
3
+ import i, { relative as a } from "node:path";
4
+ import { createServer as o, isRunnableDevEnvironment as s, loadEnv as c } from "vite";
5
+ import { createServer as l } from "node:http";
6
+ //#region src/development-error.ts
7
+ function u(e) {
8
+ let t = (e instanceof Error ? e.stack ?? e.message : String(e)).slice(0, 8192).replace(/[&<>"']/g, (e) => ({
9
+ "&": "&amp;",
10
+ "<": "&lt;",
11
+ ">": "&gt;",
12
+ "\"": "&quot;",
13
+ "'": "&#39;"
14
+ })[e]);
15
+ return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>Desktop development error</title></head><body><h1>Desktop source could not load</h1><pre id="cossack-development-error">${t}</pre><script type="module" src="/@vite/client"><\/script></body></html>`, {
16
+ status: 500,
17
+ headers: {
18
+ "Content-Type": "text/html; charset=utf-8",
19
+ "Cache-Control": "no-store"
20
+ }
21
+ });
22
+ }
23
+ //#endregion
24
+ //#region src/development-assets.ts
25
+ var d = /(?:\?|&)import=?(?:&|$)/, f = /(?:\?|&)url(?:&|$)/, p = /^\/@(?:fs\/|id\/|vite\/client|vite\/env)/;
26
+ async function m(e, t) {
27
+ if (!t || e.method !== "GET" && e.method !== "HEAD") return !1;
28
+ let n = new URL(e.url), a = n.pathname + n.search;
29
+ if (d.test(a) || f.test(a) || p.test(n.pathname)) return !1;
30
+ let o;
31
+ try {
32
+ o = decodeURI(n.pathname);
33
+ } catch {
34
+ return !1;
35
+ }
36
+ let s = i.resolve(t), c = i.resolve(s, `.${o}`);
37
+ if (!c.startsWith(s + i.sep)) return !1;
38
+ try {
39
+ return (await r(c)).isFile();
40
+ } catch {
41
+ return !1;
42
+ }
43
+ }
44
+ //#endregion
45
+ //#region src/development-response.ts
46
+ async function h(e, t, n) {
47
+ if (e.method !== "GET" || !e.headers.get("accept")?.includes("text/html") || t.headers.get("X-Cossack-Rpc-Response") === "native" || !t.body || !t.headers.get("content-type")?.includes("text/html")) return t;
48
+ let r = await n(new URL(e.url).pathname, await t.text()), i = new Headers(t.headers);
49
+ return i.delete("content-length"), new Response(r, {
50
+ status: t.status,
51
+ statusText: t.statusText,
52
+ headers: i
53
+ });
54
+ }
55
+ //#endregion
56
+ //#region src/development-runtime.ts
57
+ var g = "/@cossack-desktop/startup-recovered.html";
58
+ async function _() {
59
+ let r, i, d, f, p = !1, _ = !1, v = 0, y, b = !1, x = () => {
60
+ t.exit(0);
61
+ };
62
+ process.once("SIGINT", () => x()), process.once("SIGTERM", () => x()), process.once("disconnect", () => x());
63
+ let S = () => {
64
+ process.connected ? process.send?.({ type: "cossack:desktop-restart" }) : console.error("[desktop] Native configuration changed; restart desktop:dev to apply it.");
65
+ }, C = () => p ? Promise.reject(/* @__PURE__ */ Error("Desktop development is closing")) : d ? Promise.resolve(d) : f ??= (async () => {
66
+ let e = r.environments.ssr;
67
+ if (!s(e)) throw Error("Desktop requires a runnable Vite SSR environment");
68
+ for (; !p;) {
69
+ let t = v;
70
+ _ &&= (e.moduleGraph.invalidateAll(), e.runner.clearCache(), !1);
71
+ let n = await e.runner.import("/src/desktop/index.ts");
72
+ if (typeof n.startDesktop != "function" || typeof n.frameworkApp?.fetch != "function") throw TypeError("Desktop entry must export startDesktop(factory) and frameworkApp.fetch. Apply the Desktop bootstrap migration.");
73
+ let r = (n.createEnv ? await n.createEnv(k) : n.env) ?? {};
74
+ if (t === v) return d = {
75
+ entry: n,
76
+ env: r
77
+ }, d;
78
+ }
79
+ throw Error("Desktop development is closing");
80
+ })().finally(() => {
81
+ f = void 0;
82
+ }), w = (e) => r.config.logger.error(`[desktop] ${e instanceof Error ? e.stack : e}`), T = {
83
+ name: "cossack-desktop-development",
84
+ enforce: "post",
85
+ hotUpdate({ file: e }) {
86
+ let t = a(r.config.root, e).replaceAll("\\", "/");
87
+ if (!(!(t.startsWith("src/") && /\.(?:[cm]?[jt]sx?|mdx?)$/.test(t)) && !r.environments.ssr.moduleGraph.getModulesByFile(e)?.size)) return this.environment.name === "ssr" ? t.startsWith("src/desktop/") ? (S(), []) : (d = void 0, _ = !0, v++, (i ? C().then(() => {
88
+ for (let e of n.getAllWindows()) e.webContents.getURL().startsWith("cossack://app/") && e.webContents.reload();
89
+ }) : N()).catch(w), []) : [];
90
+ }
91
+ }, E = l((e, t) => {
92
+ r ? r.middlewares(e, t) : t.writeHead(503).end();
93
+ });
94
+ await new Promise((e, t) => {
95
+ E.once("error", t), E.listen(0, "127.0.0.1", e);
96
+ });
97
+ let D = E.address();
98
+ if (!D || typeof D == "string") throw Error("Desktop development could not bind its asset server");
99
+ let O = `http://127.0.0.1:${D.port}`;
100
+ r = await o({
101
+ root: process.cwd(),
102
+ mode: "desktop",
103
+ appType: "custom",
104
+ plugins: [T],
105
+ server: {
106
+ host: "127.0.0.1",
107
+ middlewareMode: !0,
108
+ ws: {
109
+ server: E,
110
+ host: "127.0.0.1",
111
+ protocol: "ws",
112
+ clientPort: D.port
113
+ }
114
+ },
115
+ environments: { ssr: { resolve: {
116
+ external: ["electron", "@cossackframework/desktop"],
117
+ noExternal: [
118
+ "@cossackframework/core",
119
+ "@cossackframework/renderer",
120
+ "@cossackframework/framework"
121
+ ]
122
+ } } }
123
+ });
124
+ let k = {
125
+ ...c(r.config.mode, r.config.envDir, ""),
126
+ ...process.env
127
+ }, A = (e) => {
128
+ let t = a(r.config.root, e).replaceAll("\\", "/");
129
+ (e === r.config.configFile || /^\.env(?:\.[^/]+)?$/.test(t)) && S();
130
+ };
131
+ r.watcher.on("change", A).on("add", A).on("unlink", A);
132
+ let j = { async fetch(e) {
133
+ if (e.method !== "GET" && e.method !== "HEAD") return new Response(null, { status: 404 });
134
+ let t = new URL(e.url), n = await fetch(O + t.pathname + t.search, {
135
+ method: e.method,
136
+ signal: e.signal
137
+ }), r = new Headers(n.headers);
138
+ return r.delete("content-encoding"), r.delete("content-length"), r.delete("transfer-encoding"), new Response(n.body, {
139
+ status: n.status,
140
+ statusText: n.statusText,
141
+ headers: r
142
+ });
143
+ } }, M = (t) => e({
144
+ ...t,
145
+ assets: j,
146
+ fetch: async (e, t) => {
147
+ let n = await m(e, r.config.publicDir);
148
+ if (!n) {
149
+ let t = await j.fetch(e);
150
+ if (t.status !== 404) return t;
151
+ await t.body?.cancel();
152
+ }
153
+ try {
154
+ let { entry: i, env: a } = await C(), o = await i.frameworkApp.fetch(e, {
155
+ ...t,
156
+ ...a,
157
+ ASSETS: t?.ASSETS,
158
+ COSSACK_DESKTOP: t?.COSSACK_DESKTOP
159
+ });
160
+ return n ? o : await h(e, o, (e, t) => r.transformIndexHtml(e, t));
161
+ } catch (e) {
162
+ return w(e), u(e);
163
+ }
164
+ }
165
+ });
166
+ function N() {
167
+ return y ??= C().then(async ({ entry: e }) => {
168
+ !p && !i && (b && r.ws.send({
169
+ type: "full-reload",
170
+ path: g
171
+ }), b = !1, i = await e.startDesktop(M), console.log(`[desktop] Development ready at cossack://app (assets ${O})`));
172
+ }).catch((e) => {
173
+ throw b = !0, e;
174
+ }).finally(() => {
175
+ y = void 0;
176
+ });
177
+ }
178
+ let P, F = () => P ??= (async () => {
179
+ p = !0;
180
+ let e = setTimeout(() => t.exit(1), 5e3);
181
+ try {
182
+ await r.close(), E.closeAllConnections(), await new Promise((e) => E.close(() => e())), t.exit(0);
183
+ } finally {
184
+ clearTimeout(e);
185
+ }
186
+ })();
187
+ t.on("before-quit", (e) => {
188
+ e.preventDefault(), F();
189
+ }), x = () => {
190
+ F();
191
+ }, await N().catch(w);
192
+ }
193
+ _().catch((e) => {
194
+ console.error("[desktop] Development startup failed", e), t.exit(1);
195
+ });
196
+ //#endregion
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import electron from 'electron';
2
2
  import type { BrowserWindowConstructorOptions, MessageBoxOptions, NativeImage, WebPreferences } from 'electron';
3
- import type { CossackRuntimeAdapter } from '@cossackframework/framework/runtime-adapter';
3
+ import type { CossackRuntimeAdapter } from '@cossackframework/core';
4
4
  export declare const app: Electron.App, BrowserWindow: typeof electron.BrowserWindow, dialog: Electron.Dialog, Menu: typeof electron.Menu, nativeImage: typeof Electron.NativeImage, Notification: typeof electron.Notification, protocol: Electron.Protocol, electronShell: Electron.Shell, Tray: typeof electron.Tray;
5
5
  export { DesktopUnavailableError } from './error.js';
6
6
  export { electronShell as shell };
@@ -21,17 +21,39 @@ export type SafeBrowserWindowOptions = Omit<BrowserWindowConstructorOptions, 'we
21
21
  export interface CreateDesktopAppOptions {
22
22
  identifier: string;
23
23
  productName: string;
24
+ /** Client build output (`dist/client`), read when `assets` is not given. */
24
25
  assetsRoot: string;
26
+ /**
27
+ * Optional asset provider that replaces filesystem lookup in `assetsRoot`.
28
+ * It answers hashed build output under `/assets/` before the application,
29
+ * and it is the application's `ASSETS` binding, which serves every other
30
+ * file after global and page policies. Return 404 for a missing file.
31
+ */
32
+ assets?: {
33
+ fetch(request: Request): Response | Promise<Response>;
34
+ };
25
35
  fetch: DesktopFetch;
26
36
  env?: Record<string, unknown>;
27
37
  startPath?: string;
28
38
  window?: SafeBrowserWindowOptions;
39
+ /**
40
+ * Electron permissions the app's own pages may use besides the defaults
41
+ * (`DESKTOP_DEFAULT_PERMISSIONS`: copying to the clipboard and fullscreen),
42
+ * such as `media` (camera and microphone), `geolocation` or `notifications`.
43
+ * Every other permission request and check is denied, and so is any request
44
+ * from a page outside `cossack://app`.
45
+ */
46
+ permissions?: readonly string[];
29
47
  }
30
48
  export interface CreateDesktopWindowOptions extends SafeBrowserWindowOptions {
31
49
  path?: string;
32
50
  }
33
51
  export interface DesktopShell {
34
52
  readonly app: typeof app;
53
+ /**
54
+ * The window this shell controls. For `DesktopApplication.shell` it always
55
+ * resolves to the application's current main window.
56
+ */
35
57
  readonly window: BrowserWindow;
36
58
  readonly Menu: typeof Menu;
37
59
  readonly Tray: typeof Tray;
@@ -49,7 +71,13 @@ export interface DesktopShell {
49
71
  }
50
72
  export interface DesktopApplication {
51
73
  readonly app: typeof app;
74
+ /**
75
+ * The current main window. It is replaced when the main window closes while
76
+ * another managed window stays open, and when activation (macOS) or a second
77
+ * instance needs a new window. Read it when needed instead of caching it.
78
+ */
52
79
  readonly mainWindow: BrowserWindow;
80
+ /** A stable shell whose window methods always target the current main window. */
53
81
  readonly shell: DesktopShell;
54
82
  readonly quitting: boolean;
55
83
  createWindow(options?: CreateDesktopWindowOptions): BrowserWindow;
@@ -85,4 +113,11 @@ export declare function createDesktopShell(options?: {
85
113
  window?: BrowserWindow;
86
114
  }): DesktopShell;
87
115
  /** Initialize the process-wide Desktop application exactly once. */
116
+ /**
117
+ * Permissions every app page has without naming them: writing to the clipboard
118
+ * (copy buttons) and fullscreen (video, `requestFullscreen`). Opening external
119
+ * protocol handlers (`openExternal`) is not among them: http(s) links already
120
+ * open in the browser, and other schemes need the app to name it.
121
+ */
122
+ export declare const DESKTOP_DEFAULT_PERMISSIONS: readonly string[];
88
123
  export declare function createDesktopApp(options: CreateDesktopAppOptions): Promise<DesktopApplication>;