@torpor/adapter-electron 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # torpor/adapter-electron
2
+
3
+ A @torpor/build adapter for building desktop apps with [Electron](https://www.electronjs.org/).
4
+
5
+ 🚧 WARNING: WORK IN PROGRESS 🚧
6
+
7
+ ## Installation
8
+
9
+ Install the adapter and Electron using `npm` (or your preferred package manager):
10
+
11
+ ```bash
12
+ npm install @torpor/adapter-electron
13
+ npm install -D electron
14
+ ```
15
+
16
+ Then use the adapter in your `site.config`:
17
+
18
+ ```javascript
19
+ import { electron } from "@torpor/adapter-electron";
20
+ import { Site } from "@torpor/build";
21
+
22
+ const site: Site = new Site();
23
+ site.adapter = electron();
24
+ ```
25
+
26
+ ## Commands
27
+
28
+ - `tb --dev` builds the site and opens an Electron window against the Vite dev
29
+ server, with HMR. The dev server is still available in the browser.
30
+ - `tb --build` writes the desktop app to `dist/electron`.
31
+ - `tb --preview` builds and launches the built app.
32
+
33
+ ## How it works
34
+
35
+ The generated app runs the site's server **in the Electron main process** on
36
+ Node, and serves it over a loopback HTTP server (`127.0.0.1`), which the
37
+ `BrowserWindow` loads. Because requests are real HTTP requests, cookies,
38
+ sessions, `flash` messages and redirects behave exactly as they do with
39
+ `@torpor/adapter-node` -- and Chromium's session cookie store persists them for
40
+ you across launches (see **Sessions** below).
41
+
42
+ `dist/electron` contains:
43
+
44
+ - `main.mjs` -- the Electron main process (starts the server, opens the window)
45
+ - `preload.cjs` -- a context-isolated preload
46
+ - `electron.json` -- the adapter options (host, port, partition, window)
47
+ - `package.json` -- a minimal Electron app manifest
48
+
49
+ ## Sessions and auth
50
+
51
+ The adapter uses a persistent session partition (`persist:torpor` by default),
52
+ so Torpor's signed session cookie survives restarts with no extra work.
53
+ Cookies are scoped to the host, not the port, so this holds even though the
54
+ default port is ephemeral.
55
+
56
+ For a "remember me" token that outlives the session, use Electron's
57
+ [`safeStorage`](https://www.electronjs.org/docs/latest/api/safe-storage) to
58
+ encrypt it with the OS keychain (macOS Keychain, Windows DPAPI, Linux Secret
59
+ Service) and write it under `app.getPath("userData")`. Never store passwords or
60
+ tokens in `localStorage` or the renderer.
61
+
62
+ ## Options
63
+
64
+ ```javascript
65
+ site.adapter = electron({
66
+ partition: "persist:torpor", // session partition (cookies/web storage)
67
+ host: "127.0.0.1", // loopback host for the server
68
+ port: 0, // 0 = ephemeral; pin a port to keep web storage stable
69
+ window: { width: 1280, height: 800, title: "Flub" },
70
+ dev: true, // set false to skip the desktop window in dev
71
+ });
72
+ ```
73
+
74
+ Cookies persist across launches regardless of the port. Web storage
75
+ (`localStorage`, `IndexedDB`) is origin-scoped, so pin `port` if the app relies
76
+ on it staying put.
77
+
78
+ ## Packaging
79
+
80
+ The emitted `dist/electron` app is a normal Electron app; package it with
81
+ [electron-builder](https://www.electron.build/) or
82
+ [Electron Forge](https://forge.electron.build/) by pointing the app directory at
83
+ `dist/electron`. Include the site's `node_modules` (or add the emitted app's
84
+ runtime dependencies to the builder config) so `@torpor/adapter-electron` and
85
+ `@torpor/build` resolve. With pnpm, a hoisted `node-linker` is easiest.
@@ -0,0 +1,69 @@
1
+ // The dev counterpart of main.mjs: opens a window against the Vite dev server
2
+ // (which the framework's Node dev plugin serves) instead of a built output, so
3
+ // HMR works. Launched by the adapter's dev plugin with TORPOR_ELECTRON_URL set.
4
+ import { app, BrowserWindow, session, shell } from "electron";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ const dir = path.dirname(fileURLToPath(import.meta.url));
9
+ const url = process.env.TORPOR_ELECTRON_URL ?? "http://localhost:7059";
10
+ const config = process.env.TORPOR_ELECTRON_CONFIG
11
+ ? JSON.parse(process.env.TORPOR_ELECTRON_CONFIG)
12
+ : {};
13
+ const partition = config.partition ?? "persist:torpor";
14
+ const origin = new URL(url).origin;
15
+
16
+ function createWindow() {
17
+ const win = new BrowserWindow({
18
+ width: 1100,
19
+ height: 800,
20
+ show: false,
21
+ backgroundColor: "#ffffff",
22
+ ...config.window,
23
+ webPreferences: {
24
+ preload: path.join(dir, "preload.cjs"),
25
+ contextIsolation: true,
26
+ nodeIntegration: false,
27
+ sandbox: true,
28
+ session: session.fromPartition(partition),
29
+ },
30
+ });
31
+
32
+ // Open external links in the user's browser; deny everything else
33
+ win.webContents.setWindowOpenHandler(({ url: target }) => {
34
+ if (/^https?:/.test(target) && !target.startsWith(origin)) void shell.openExternal(target);
35
+ return { action: "deny" };
36
+ });
37
+
38
+ win.once("ready-to-show", () => win.show());
39
+ void loadWithRetry(win);
40
+ }
41
+
42
+ // The dev server may still be starting when Electron launches, so retry
43
+ async function loadWithRetry(win) {
44
+ for (let attempt = 0; attempt < 40; attempt++) {
45
+ try {
46
+ await win.loadURL(url);
47
+ return;
48
+ } catch {
49
+ await new Promise((resolve) => setTimeout(resolve, 250));
50
+ }
51
+ }
52
+ console.error(`[torpor] Could not load ${url} in Electron`);
53
+ }
54
+
55
+ app
56
+ .whenReady()
57
+ .then(createWindow)
58
+ .catch((error) => {
59
+ console.error("[torpor] Failed to start:", error);
60
+ app.quit();
61
+ });
62
+
63
+ app.on("window-all-closed", () => {
64
+ if (process.platform !== "darwin") app.quit();
65
+ });
66
+
67
+ app.on("activate", () => {
68
+ if (BrowserWindow.getAllWindows().length === 0) createWindow();
69
+ });
@@ -0,0 +1,22 @@
1
+ import { n as ElectronWindowOptions, t as ElectronOptions } from "./types-Ce9F9DiP.mjs";
2
+ import { Adapter } from "@torpor/build";
3
+ //#region src/adapter.d.ts
4
+ /**
5
+ * A @torpor/build adapter for desktop apps.
6
+ *
7
+ * Builds emit an Electron app into `dist/electron` (a main process that serves
8
+ * the site over a loopback HTTP server, a context-isolated preload, and a
9
+ * manifest); preview launches it, and dev opens a window against the Vite dev
10
+ * server. Requests run in the Electron main process on Node, so cookies,
11
+ * sessions and redirects behave exactly as on a normal Node server.
12
+ *
13
+ * ```ts
14
+ * import { electron } from "@torpor/adapter-electron";
15
+ *
16
+ * site.adapter = electron();
17
+ * ```
18
+ */
19
+ declare function electron(options?: ElectronOptions): Adapter;
20
+ //#endregion
21
+ export { type ElectronOptions, type ElectronWindowOptions, electron };
22
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/adapter.ts"],"mappings":";;;;;;;;;;;;;;;;;;iBAwBwB,SAAS,UAAS,kBAAuB"}
package/dist/index.mjs ADDED
@@ -0,0 +1,198 @@
1
+ import { createRequire } from "node:module";
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, promises, realpathSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { nodeDev } from "@torpor/build/node-dev";
6
+ import { fileURLToPath } from "node:url";
7
+ //#region src/electronBinary.ts
8
+ /**
9
+ * Resolves the Electron executable to run, preferring the copy installed in
10
+ * the site's node_modules (`require("electron")` resolves to the binary path)
11
+ * and falling back to `electron` on PATH. The package may not be installed --
12
+ * e.g. a CI build that only builds the site -- in which case launching is
13
+ * skipped and callers report how to install it.
14
+ */
15
+ function electronBinary(siteRoot) {
16
+ try {
17
+ const resolved = createRequire(path.join(siteRoot, "package.json"))("electron");
18
+ return typeof resolved === "string" ? resolved : "electron";
19
+ } catch {
20
+ return "electron";
21
+ }
22
+ }
23
+ //#endregion
24
+ //#region src/sourceMode.ts
25
+ /**
26
+ * Whether the framework is symlinked into the app from outside node_modules
27
+ * (workspace links and `link:` overrides), meaning tb runs it from source via
28
+ * the `development` export conditions. Registry installs always run dist.
29
+ */
30
+ function detectSourceMode(siteRoot) {
31
+ if (process.env.TORPOR_SOURCE_DEV) return true;
32
+ return ["@torpor/build", "@torpor/view"].every((pkg) => {
33
+ try {
34
+ const dist = path.resolve(siteRoot, "node_modules", pkg, "dist/index.mjs");
35
+ return !realpathSync(dist).includes("node_modules");
36
+ } catch {
37
+ return false;
38
+ }
39
+ });
40
+ }
41
+ //#endregion
42
+ //#region src/electronDev.ts
43
+ /**
44
+ * Dev support: the framework's default Node dev runtime (which serves SSR off
45
+ * the Vite dev server) plus a launcher that opens an Electron window pointed at
46
+ * it. Without `nodeDev`, providing `Adapter.dev` would replace the Node
47
+ * runtime entirely, which Electron doesn't need -- it runs on Node.
48
+ */
49
+ function electronDev(site, options) {
50
+ return [nodeDev(site, detectSourceMode(site.root)), electronLauncher(site, options)];
51
+ }
52
+ function electronLauncher(site, options) {
53
+ let child;
54
+ let quitting = false;
55
+ const stopChild = () => {
56
+ child?.kill();
57
+ child = void 0;
58
+ };
59
+ return {
60
+ name: "torpor-electron-dev",
61
+ configureServer(server) {
62
+ if (options.dev === false || process.env.TORPOR_ELECTRON === "0") return;
63
+ const start = () => {
64
+ const url = devServerUrl(server);
65
+ if (!url) return;
66
+ stopChild();
67
+ quitting = false;
68
+ const proc = launch(site, url, options);
69
+ child = proc;
70
+ proc.once("exit", () => {
71
+ if (quitting) return;
72
+ quitting = true;
73
+ server.close();
74
+ });
75
+ };
76
+ const httpServer = server.httpServer;
77
+ if (httpServer?.listening) start();
78
+ else httpServer?.once("listening", start);
79
+ httpServer?.once("close", () => {
80
+ quitting = true;
81
+ stopChild();
82
+ });
83
+ process.once("exit", stopChild);
84
+ }
85
+ };
86
+ }
87
+ function launch(site, url, options) {
88
+ const adapterFolder = path.dirname(fileURLToPath(import.meta.url));
89
+ const entry = path.join(adapterFolder, "dev-main.mjs");
90
+ const config = {
91
+ partition: options.partition ?? "persist:torpor",
92
+ window: options.window ?? {}
93
+ };
94
+ const child = spawn(electronBinary(site.root), [entry], {
95
+ cwd: site.root,
96
+ stdio: "inherit",
97
+ env: {
98
+ ...process.env,
99
+ TORPOR_ELECTRON_URL: url,
100
+ TORPOR_ELECTRON_CONFIG: JSON.stringify(config)
101
+ }
102
+ });
103
+ child.on("error", (error) => {
104
+ if (error.code === "ENOENT") console.warn("[torpor] Electron is not installed, so dev is running in the browser only. Install it with `npm install -D electron` to open a desktop window.");
105
+ else console.warn(`[torpor] Could not launch Electron: ${error.message}`);
106
+ });
107
+ return child;
108
+ }
109
+ function devServerUrl(server) {
110
+ const local = server.resolvedUrls?.local?.[0];
111
+ if (local) return local;
112
+ const address = server.httpServer?.address();
113
+ if (address && typeof address === "object") return `${server.config.server.https ? "https" : "http"}://${address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.address}:${address.port}`;
114
+ }
115
+ //#endregion
116
+ //#region src/postbuild.ts
117
+ const RUNTIME_FILES = ["main.mjs", "preload.cjs"];
118
+ async function postbuild(site, options) {
119
+ const sourceFolder = path.dirname(fileURLToPath(import.meta.url));
120
+ const outputFolder = path.join(site.root, "dist", "electron");
121
+ await promises.mkdir(outputFolder, { recursive: true });
122
+ for (const file of RUNTIME_FILES) await promises.copyFile(path.join(sourceFolder, file), path.join(outputFolder, file));
123
+ const config = {
124
+ host: options.host ?? "127.0.0.1",
125
+ port: options.port ?? 0,
126
+ partition: options.partition ?? "persist:torpor",
127
+ window: options.window ?? {}
128
+ };
129
+ await promises.writeFile(path.join(outputFolder, "electron.json"), JSON.stringify(config, null, " "));
130
+ const { name, version } = await sitePackage(site.root);
131
+ await promises.writeFile(path.join(outputFolder, "package.json"), JSON.stringify({
132
+ name: `${name}-electron`,
133
+ productName: name,
134
+ version,
135
+ private: true,
136
+ type: "module",
137
+ main: "main.mjs",
138
+ scripts: { start: "electron ." }
139
+ }, null, " "));
140
+ }
141
+ async function sitePackage(root) {
142
+ try {
143
+ const pkg = JSON.parse(await promises.readFile(path.join(root, "package.json"), "utf-8"));
144
+ return {
145
+ name: typeof pkg.name === "string" ? pkg.name.replace(/^@[^/]+\//, "") : "torpor-app",
146
+ version: typeof pkg.version === "string" ? pkg.version : "1.0.0"
147
+ };
148
+ } catch {
149
+ return {
150
+ name: "torpor-app",
151
+ version: "1.0.0"
152
+ };
153
+ }
154
+ }
155
+ //#endregion
156
+ //#region src/adapter.ts
157
+ /**
158
+ * A @torpor/build adapter for desktop apps.
159
+ *
160
+ * Builds emit an Electron app into `dist/electron` (a main process that serves
161
+ * the site over a loopback HTTP server, a context-isolated preload, and a
162
+ * manifest); preview launches it, and dev opens a window against the Vite dev
163
+ * server. Requests run in the Electron main process on Node, so cookies,
164
+ * sessions and redirects behave exactly as on a normal Node server.
165
+ *
166
+ * ```ts
167
+ * import { electron } from "@torpor/adapter-electron";
168
+ *
169
+ * site.adapter = electron();
170
+ * ```
171
+ */
172
+ function electron(options = {}) {
173
+ return {
174
+ dev: (site) => electronDev(site, options),
175
+ postbuild: (site) => postbuild(site, options),
176
+ serve: (_server, site) => serve(site)
177
+ };
178
+ }
179
+ function serve(site) {
180
+ const appFolder = path.join(site.root, "dist", "electron");
181
+ if (!existsSync(path.join(appFolder, "main.mjs"))) throw new Error("Electron output not found. Run a build first (dist/electron/main.mjs is missing).");
182
+ const child = spawn(electronBinary(site.root), [appFolder], {
183
+ cwd: site.root,
184
+ stdio: "inherit"
185
+ });
186
+ child.on("error", (error) => {
187
+ if (error.code === "ENOENT") {
188
+ console.error("[torpor] Electron is not installed. Install it with `npm install -D electron`.");
189
+ process.exit(1);
190
+ }
191
+ throw error;
192
+ });
193
+ child.on("exit", (code) => process.exit(code ?? 0));
194
+ }
195
+ //#endregion
196
+ export { electron };
197
+
198
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["fs"],"sources":["../src/electronBinary.ts","../src/sourceMode.ts","../src/electronDev.ts","../src/postbuild.ts","../src/adapter.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\n/**\n * Resolves the Electron executable to run, preferring the copy installed in\n * the site's node_modules (`require(\"electron\")` resolves to the binary path)\n * and falling back to `electron` on PATH. The package may not be installed --\n * e.g. a CI build that only builds the site -- in which case launching is\n * skipped and callers report how to install it.\n */\nexport default function electronBinary(siteRoot: string): string {\n\ttry {\n\t\tconst require = createRequire(path.join(siteRoot, \"package.json\"));\n\t\tconst resolved: unknown = require(\"electron\");\n\t\treturn typeof resolved === \"string\" ? resolved : \"electron\";\n\t} catch {\n\t\treturn \"electron\";\n\t}\n}\n","import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n// Mirrors the entry-path logic in @torpor/build's `utils/entryPaths.ts` (kept\n// local so the adapter stays compatible with older @torpor/build installs).\n\n/**\n * Whether the framework is symlinked into the app from outside node_modules\n * (workspace links and `link:` overrides), meaning tb runs it from source via\n * the `development` export conditions. Registry installs always run dist.\n */\nexport default function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n","import { type Site } from \"@torpor/build\";\nimport { nodeDev } from \"@torpor/build/node-dev\";\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport electronBinary from \"./electronBinary\";\nimport detectSourceMode from \"./sourceMode\";\nimport type { ElectronOptions } from \"./types\";\n\n/**\n * Dev support: the framework's default Node dev runtime (which serves SSR off\n * the Vite dev server) plus a launcher that opens an Electron window pointed at\n * it. Without `nodeDev`, providing `Adapter.dev` would replace the Node\n * runtime entirely, which Electron doesn't need -- it runs on Node.\n */\nexport default function electronDev(site: Site, options: ElectronOptions): Plugin[] {\n\treturn [nodeDev(site, detectSourceMode(site.root)), electronLauncher(site, options)];\n}\n\nfunction electronLauncher(site: Site, options: ElectronOptions): Plugin {\n\tlet child: ChildProcess | undefined;\n\tlet quitting = false;\n\n\tconst stopChild = (): void => {\n\t\tchild?.kill();\n\t\tchild = undefined;\n\t};\n\n\treturn {\n\t\tname: \"torpor-electron-dev\",\n\t\tconfigureServer(server: ViteDevServer) {\n\t\t\tif (options.dev === false || process.env.TORPOR_ELECTRON === \"0\") return;\n\n\t\t\tconst start = (): void => {\n\t\t\t\tconst url = devServerUrl(server);\n\t\t\t\tif (!url) return;\n\t\t\t\tstopChild();\n\t\t\t\tquitting = false;\n\n\t\t\t\tconst proc = launch(site, url, options);\n\t\t\t\tchild = proc;\n\n\t\t\t\t// When the user quits the app (Cmd+Q, or closing the window),\n\t\t\t\t// stop the dev server too, so `tb --dev` exits with the desktop\n\t\t\t\t// app. A failed launch emits \"error\", not \"exit\", so browser-only\n\t\t\t\t// dev is unaffected\n\t\t\t\tproc.once(\"exit\", () => {\n\t\t\t\t\tif (quitting) return;\n\t\t\t\t\tquitting = true;\n\t\t\t\t\tvoid server.close();\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst httpServer = server.httpServer;\n\t\t\tif (httpServer?.listening) {\n\t\t\t\tstart();\n\t\t\t} else {\n\t\t\t\thttpServer?.once(\"listening\", start);\n\t\t\t}\n\n\t\t\t// Vite is shutting down (Ctrl+C, a restart, or close() from the\n\t\t\t// handler above): kill the window without re-closing the server\n\t\t\thttpServer?.once(\"close\", () => {\n\t\t\t\tquitting = true;\n\t\t\t\tstopChild();\n\t\t\t});\n\n\t\t\tprocess.once(\"exit\", stopChild);\n\t\t},\n\t};\n}\n\nfunction launch(site: Site, url: string, options: ElectronOptions): ChildProcess {\n\tconst adapterFolder = path.dirname(fileURLToPath(import.meta.url));\n\tconst entry = path.join(adapterFolder, \"dev-main.mjs\");\n\n\tconst config = {\n\t\tpartition: options.partition ?? \"persist:torpor\",\n\t\twindow: options.window ?? {},\n\t};\n\n\tconst child = spawn(electronBinary(site.root), [entry], {\n\t\tcwd: site.root,\n\t\tstdio: \"inherit\",\n\t\tenv: {\n\t\t\t...process.env,\n\t\t\tTORPOR_ELECTRON_URL: url,\n\t\t\tTORPOR_ELECTRON_CONFIG: JSON.stringify(config),\n\t\t},\n\t});\n\n\tchild.on(\"error\", (error: NodeJS.ErrnoException) => {\n\t\tif (error.code === \"ENOENT\") {\n\t\t\tconsole.warn(\n\t\t\t\t\"[torpor] Electron is not installed, so dev is running in the browser only. \" +\n\t\t\t\t\t\"Install it with `npm install -D electron` to open a desktop window.\",\n\t\t\t);\n\t\t} else {\n\t\t\tconsole.warn(`[torpor] Could not launch Electron: ${error.message}`);\n\t\t}\n\t});\n\n\treturn child;\n}\n\nfunction devServerUrl(server: ViteDevServer): string | undefined {\n\tconst local = server.resolvedUrls?.local?.[0];\n\tif (local) return local;\n\n\tconst address = server.httpServer?.address();\n\tif (address && typeof address === \"object\") {\n\t\tconst protocol = server.config.server.https ? \"https\" : \"http\";\n\t\tconst host =\n\t\t\taddress.address === \"::\" || address.address === \"0.0.0.0\" ? \"localhost\" : address.address;\n\t\treturn `${protocol}://${host}:${address.port}`;\n\t}\n\n\treturn undefined;\n}\n","import type { Site } from \"@torpor/build\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ElectronOptions } from \"./types\";\n\n// The Electron main and preload scripts, copied verbatim from the adapter's\n// dist into the site's dist/electron output\nconst RUNTIME_FILES = [\"main.mjs\", \"preload.cjs\"];\n\nexport default async function postbuild(site: Site, options: ElectronOptions): Promise<void> {\n\tconst sourceFolder = path.dirname(fileURLToPath(import.meta.url));\n\tconst outputFolder = path.join(site.root, \"dist\", \"electron\");\n\n\tawait fs.mkdir(outputFolder, { recursive: true });\n\tfor (const file of RUNTIME_FILES) {\n\t\tawait fs.copyFile(path.join(sourceFolder, file), path.join(outputFolder, file));\n\t}\n\n\tconst config = {\n\t\thost: options.host ?? \"127.0.0.1\",\n\t\tport: options.port ?? 0,\n\t\tpartition: options.partition ?? \"persist:torpor\",\n\t\twindow: options.window ?? {},\n\t};\n\tawait fs.writeFile(path.join(outputFolder, \"electron.json\"), JSON.stringify(config, null, \"\\t\"));\n\n\t// A minimal Electron app manifest. Run it with `electron dist/electron`\n\t// (see the adapter README for packaging with electron-builder/forge)\n\tconst { name, version } = await sitePackage(site.root);\n\tawait fs.writeFile(\n\t\tpath.join(outputFolder, \"package.json\"),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\tname: `${name}-electron`,\n\t\t\t\tproductName: name,\n\t\t\t\tversion,\n\t\t\t\tprivate: true,\n\t\t\t\ttype: \"module\",\n\t\t\t\tmain: \"main.mjs\",\n\t\t\t\tscripts: { start: \"electron .\" },\n\t\t\t},\n\t\t\tnull,\n\t\t\t\"\\t\",\n\t\t),\n\t);\n}\n\nasync function sitePackage(root: string): Promise<{ name: string; version: string }> {\n\ttry {\n\t\tconst pkg = JSON.parse(await fs.readFile(path.join(root, \"package.json\"), \"utf-8\"));\n\t\tconst name = typeof pkg.name === \"string\" ? pkg.name.replace(/^@[^/]+\\//, \"\") : \"torpor-app\";\n\t\tconst version = typeof pkg.version === \"string\" ? pkg.version : \"1.0.0\";\n\t\treturn { name, version };\n\t} catch {\n\t\treturn { name: \"torpor-app\", version: \"1.0.0\" };\n\t}\n}\n","import { type Adapter, type Site } from \"@torpor/build\";\nimport { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport electronBinary from \"./electronBinary\";\nimport electronDev from \"./electronDev\";\nimport postbuild from \"./postbuild\";\nimport type { ElectronOptions } from \"./types\";\n\n/**\n * A @torpor/build adapter for desktop apps.\n *\n * Builds emit an Electron app into `dist/electron` (a main process that serves\n * the site over a loopback HTTP server, a context-isolated preload, and a\n * manifest); preview launches it, and dev opens a window against the Vite dev\n * server. Requests run in the Electron main process on Node, so cookies,\n * sessions and redirects behave exactly as on a normal Node server.\n *\n * ```ts\n * import { electron } from \"@torpor/adapter-electron\";\n *\n * site.adapter = electron();\n * ```\n */\nexport default function electron(options: ElectronOptions = {}): Adapter {\n\treturn {\n\t\tdev: (site: Site) => electronDev(site, options),\n\t\tpostbuild: (site: Site) => postbuild(site, options),\n\t\tserve: (_server, site: Site) => serve(site),\n\t};\n}\n\nfunction serve(site: Site): void {\n\tconst appFolder = path.join(site.root, \"dist\", \"electron\");\n\tif (!existsSync(path.join(appFolder, \"main.mjs\"))) {\n\t\tthrow new Error(\n\t\t\t\"Electron output not found. Run a build first (dist/electron/main.mjs is missing).\",\n\t\t);\n\t}\n\n\tconst child = spawn(electronBinary(site.root), [appFolder], {\n\t\tcwd: site.root,\n\t\tstdio: \"inherit\",\n\t});\n\n\tchild.on(\"error\", (error: NodeJS.ErrnoException) => {\n\t\tif (error.code === \"ENOENT\") {\n\t\t\tconsole.error(\n\t\t\t\t\"[torpor] Electron is not installed. Install it with `npm install -D electron`.\",\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tthrow error;\n\t});\n\n\tchild.on(\"exit\", (code) => process.exit(code ?? 0));\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAwB,eAAe,UAA0B;CAChE,IAAI;EAEH,MAAM,WADU,cAAc,KAAK,KAAK,UAAU,cAAc,CAChC,CAAC,CAAC,UAAU;EAC5C,OAAO,OAAO,aAAa,WAAW,WAAW;CAClD,QAAQ;EACP,OAAO;CACR;AACD;;;;;;;;ACPA,SAAwB,iBAAiB,UAA2B;CACnE,IAAI,QAAQ,IAAI,mBAAmB,OAAO;CAE1C,OAAO,CADW,iBAAiB,cACrB,CAAC,CAAC,OAAO,QAAQ;EAC9B,IAAI;GACH,MAAM,OAAO,KAAK,QAAQ,UAAU,gBAAgB,KAAK,gBAAgB;GAEzE,OAAO,CADM,aAAa,IACf,CAAC,CAAC,SAAS,cAAc;EACrC,QAAQ;GACP,OAAO;EACR;CACD,CAAC;AACF;;;;;;;;;ACPA,SAAwB,YAAY,MAAY,SAAoC;CACnF,OAAO,CAAC,QAAQ,MAAM,iBAAiB,KAAK,IAAI,CAAC,GAAG,iBAAiB,MAAM,OAAO,CAAC;AACpF;AAEA,SAAS,iBAAiB,MAAY,SAAkC;CACvE,IAAI;CACJ,IAAI,WAAW;CAEf,MAAM,kBAAwB;EAC7B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EAAE,IAAI;GAEjE,SADC,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU;EACzC;CACxB,QAAQ;EACP,OAAO;GAAE,MAAM;GAAc,SAAS;EAAQ;CAC/C;AACD;;;;;;;;;;;;;;;;;;ACjCA,SAAwB,SAAS,UAA2B,CAAC,GAAY;CACxE,OAAO;EACN,MAAM,SAAe,YAAY,MAAM,OAAO;EAC9C,YAAY,SAAe,UAAU,MAAM,OAAO;EAClD,QAAQ,SAAS,SAAe,MAAM,IAAI;CAC3C;AACD;AAEA,SAAS,MAAM,MAAkB;CAChC,MAAM,YAAY,KAAK,KAAK,KAAK,MAAM,QAAQ,UAAU;CACzD,IAAI,CAAC,WAAW,KAAK,KAAK,WAAW,UAAU,CAAC,GAC/C,MAAM,IAAI,MACT,mFACD;CAGD,MAAM,QAAQ,MAAM,eAAe,KAAK,IAAI,GAAG,CAAC,SAAS,GAAG;EAC3D,KAAK,KAAK;EACV,OAAO;CACR,CAAC;CAED,MAAM,GAAG,UAAU,UAAiC;EACnD,IAAI,MAAM,SAAS,UAAU;GAC5B,QAAQ,MACP,gFACD;GACA,QAAQ,KAAK,CAAC;EACf;EACA,MAAM;CACP,CAAC;CAED,MAAM,GAAG,SAAS,SAAS,QAAQ,KAAK,QAAQ,CAAC,CAAC;AACnD"}
package/dist/main.mjs ADDED
@@ -0,0 +1,87 @@
1
+ // This file is copied into <site>/dist/electron by @torpor/adapter-electron.
2
+ // It serves the built site over a loopback HTTP server and shows it in a
3
+ // BrowserWindow. Requests run here, in the main process, so cookies, sessions
4
+ // and redirects behave exactly as on a Node server.
5
+ import { app, BrowserWindow, session, shell } from "electron";
6
+ import { readFileSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { startServer } from "@torpor/adapter-electron/runtime";
10
+
11
+ const dir = path.dirname(fileURLToPath(import.meta.url));
12
+ const root = path.resolve(dir, "..", "..");
13
+ const config = JSON.parse(readFileSync(path.join(dir, "electron.json"), "utf-8"));
14
+ const partition = config.partition ?? "persist:torpor";
15
+
16
+ let server;
17
+ let origin = "";
18
+
19
+ async function createWindow() {
20
+ const win = new BrowserWindow({
21
+ width: 1100,
22
+ height: 800,
23
+ show: false,
24
+ backgroundColor: "#ffffff",
25
+ ...config.window,
26
+ webPreferences: {
27
+ preload: path.join(dir, "preload.cjs"),
28
+ contextIsolation: true,
29
+ nodeIntegration: false,
30
+ sandbox: true,
31
+ session: session.fromPartition(partition),
32
+ },
33
+ });
34
+
35
+ // Open external links in the user's browser; deny everything else
36
+ win.webContents.setWindowOpenHandler(({ url }) => {
37
+ if (/^https?:/.test(url) && !url.startsWith(origin)) void shell.openExternal(url);
38
+ return { action: "deny" };
39
+ });
40
+
41
+ win.once("ready-to-show", () => win.show());
42
+ await win.loadURL(`${server.url}/`);
43
+ }
44
+
45
+ app
46
+ .whenReady()
47
+ .then(async () => {
48
+ server = await startServer(root, { host: config.host, port: config.port });
49
+ origin = server.url;
50
+ await createWindow();
51
+
52
+ app.on("activate", () => {
53
+ if (BrowserWindow.getAllWindows().length === 0) void createWindow();
54
+ });
55
+ })
56
+ .catch((error) => {
57
+ console.error("[torpor] Failed to start:", error);
58
+ app.quit();
59
+ });
60
+
61
+ app.on("window-all-closed", () => {
62
+ if (process.platform !== "darwin") app.quit();
63
+ });
64
+
65
+ // Flush cookies (so the session survives) and stop the server before quitting.
66
+ // A stuck flush or socket must never stop the app from quitting, so the
67
+ // shutdown work is raced against a short timeout
68
+ let shuttingDown = false;
69
+ app.on("before-quit", (event) => {
70
+ if (shuttingDown) return;
71
+ event.preventDefault();
72
+ shuttingDown = true;
73
+
74
+ let timer;
75
+ const timeout = new Promise((resolve) => {
76
+ timer = setTimeout(resolve, 1500);
77
+ });
78
+ void Promise.race([
79
+ Promise.all([session.fromPartition(partition).cookies.flushStore(), server?.close()]),
80
+ timeout,
81
+ ])
82
+ .catch(() => {})
83
+ .finally(() => {
84
+ clearTimeout(timer);
85
+ app.quit();
86
+ });
87
+ });
@@ -0,0 +1,12 @@
1
+ // Runs in an isolated world before the page loads. Keep this surface as small
2
+ // as possible, and never expose Node or Electron modules to the renderer.
3
+ const { contextBridge } = require("electron");
4
+
5
+ contextBridge.exposeInMainWorld("electronAPI", {
6
+ platform: process.platform,
7
+ versions: {
8
+ chrome: process.versions.chrome,
9
+ electron: process.versions.electron,
10
+ node: process.versions.node,
11
+ },
12
+ });
@@ -0,0 +1,25 @@
1
+ import { i as StartServerOptions, r as RunningServer } from "./types-Ce9F9DiP.mjs";
2
+ //#region src/runtime.d.ts
3
+ /**
4
+ * Loads a `.env` file from the site root into `process.env`, when the runtime's
5
+ * Node version supports `process.loadEnvFile` (20.12+). Mirrors the CLI, which
6
+ * loads `.env` for dev and preview.
7
+ */
8
+ declare function loadEnv(root: string): void;
9
+ /**
10
+ * Builds a Fetch API handler for a built site: it serves everything under
11
+ * `dist/client` statically and routes the rest through `dist/server`'s
12
+ * `serverEntry.load`. Replaces `runPreview`'s Server setup, which isn't
13
+ * exported from @torpor/build.
14
+ */
15
+ declare function createRequestHandler(root: string): Promise<(request: Request) => Promise<Response>>;
16
+ /**
17
+ * Starts the loopback HTTP server for a built site. Requests are handled in
18
+ * the Electron main process (Node), so cookies, sessions and redirects behave
19
+ * exactly as they do on a normal Node server -- Chromium's session cookie
20
+ * store handles persistence across launches.
21
+ */
22
+ declare function startServer(root: string, options?: StartServerOptions): Promise<RunningServer>;
23
+ //#endregion
24
+ export { createRequestHandler, loadEnv, startServer };
25
+ //# sourceMappingURL=runtime.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/runtime.ts"],"mappings":";;;;;;;iBAcgB,QAAQ;;;;;;;iBAkBF,qBACrB,eACE,SAAS,SAAS,YAAY,QAAQ;;;;;;;iBAkCnB,YACrB,cACA,UAAS,qBACP,QAAQ"}
@@ -0,0 +1,178 @@
1
+ import { existsSync, promises } from "node:fs";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { createNodeServer } from "@torpor/adapter-node";
5
+ import { Server } from "@torpor/build/server";
6
+ //#region src/contentType.ts
7
+ function contentType(extension) {
8
+ return types[extension] || "application/octet-stream";
9
+ }
10
+ const types = {
11
+ ".aac": "audio/aac",
12
+ ".apng": "image/apng",
13
+ ".avif": "image/avif",
14
+ ".bin": "application/octet-stream",
15
+ ".bmp": "image/bmp",
16
+ ".css": "text/css",
17
+ ".csv": "text/csv",
18
+ ".eot": "application/vnd.ms-fontobject",
19
+ ".gif": "image/gif",
20
+ ".htm": "text/html",
21
+ ".html": "text/html",
22
+ ".ico": "image/vnd.microsoft.icon",
23
+ ".jpeg": "image/jpeg",
24
+ ".jpg": "image/jpeg",
25
+ ".js": "text/javascript",
26
+ ".json": "application/json",
27
+ ".jsonld": "application/ld+json",
28
+ ".mjs": "text/javascript",
29
+ ".mp3": "audio/mpeg",
30
+ ".mp4": "video/mp4",
31
+ ".ogg": "audio/ogg",
32
+ ".ogv": "video/ogg",
33
+ ".opus": "audio/ogg",
34
+ ".otf": "font/otf",
35
+ ".pdf": "application/pdf",
36
+ ".png": "image/png",
37
+ ".svg": "image/svg+xml",
38
+ ".tar": "application/x-tar",
39
+ ".txt": "text/plain",
40
+ ".ttf": "font/ttf",
41
+ ".wasm": "application/wasm",
42
+ ".wav": "audio/wav",
43
+ ".webm": "video/webm",
44
+ ".webp": "image/webp",
45
+ ".woff": "font/woff",
46
+ ".woff2": "font/woff2",
47
+ ".xml": "application/xml",
48
+ ".zip": "application/zip"
49
+ };
50
+ //#endregion
51
+ //#region src/prepareTemplate.ts
52
+ function prepareTemplate(template, clientScript) {
53
+ let result = template;
54
+ const headStart = result.indexOf("</head>");
55
+ if (headStart === -1) throw new Error(`Couldn't find <head> end tag`);
56
+ result = result.substring(0, headStart) + "%COMPONENT_HEAD%" + result.substring(headStart);
57
+ const divMatchStart = regexIndexOf(result, /<div\s+id=("app"|'app'|app)[\s>]/);
58
+ if (divMatchStart === -1) throw new Error(`Couldn't find <div id="app"></div>`);
59
+ const bodyStart = result.indexOf(">", divMatchStart) + 1;
60
+ const bodyEnd = result.indexOf("</div>", bodyStart);
61
+ if (bodyEnd === -1) throw new Error(`Couldn't find <div id="app"></div>`);
62
+ result = result.substring(0, bodyStart) + "%COMPONENT_BODY%" + result.substring(bodyEnd);
63
+ result += `<script type="module" src="${clientScript}"><\/script>`;
64
+ return result;
65
+ }
66
+ function regexIndexOf(string, regex, position) {
67
+ const indexOf = string.substring(position || 0).search(regex);
68
+ return indexOf >= 0 ? indexOf + (position || 0) : indexOf;
69
+ }
70
+ //#endregion
71
+ //#region src/runtime.ts
72
+ /**
73
+ * Loads a `.env` file from the site root into `process.env`, when the runtime's
74
+ * Node version supports `process.loadEnvFile` (20.12+). Mirrors the CLI, which
75
+ * loads `.env` for dev and preview.
76
+ */
77
+ function loadEnv(root) {
78
+ const file = path.join(root, ".env");
79
+ if (!existsSync(file)) return;
80
+ const loader = process.loadEnvFile;
81
+ if (typeof loader !== "function") return;
82
+ try {
83
+ loader.call(process, file);
84
+ } catch {}
85
+ }
86
+ /**
87
+ * Builds a Fetch API handler for a built site: it serves everything under
88
+ * `dist/client` statically and routes the rest through `dist/server`'s
89
+ * `serverEntry.load`. Replaces `runPreview`'s Server setup, which isn't
90
+ * exported from @torpor/build.
91
+ */
92
+ async function createRequestHandler(root) {
93
+ const clientFolder = path.join(root, "dist", "client");
94
+ const serverFolder = path.join(root, "dist", "server");
95
+ const template = await loadTemplate(clientFolder);
96
+ const serverEntry = pathToFileURL(path.join(serverFolder, "serverEntry.js")).href;
97
+ const server = new Server();
98
+ server.use({ enter: async (ev) => serveStatic(clientFolder, ev.request) });
99
+ server.add("*", async (ev) => {
100
+ try {
101
+ const { load } = await import(serverEntry);
102
+ return await load(ev, template);
103
+ } catch (error) {
104
+ console.error("[torpor] Unhandled error while rendering:", error);
105
+ return new Response(null, { status: 500 });
106
+ }
107
+ });
108
+ return (request) => server.fetch(request);
109
+ }
110
+ /**
111
+ * Starts the loopback HTTP server for a built site. Requests are handled in
112
+ * the Electron main process (Node), so cookies, sessions and redirects behave
113
+ * exactly as they do on a normal Node server -- Chromium's session cookie
114
+ * store handles persistence across launches.
115
+ */
116
+ async function startServer(root, options = {}) {
117
+ loadEnv(root);
118
+ globalThis.adapter = { env: process.env };
119
+ const handler = await createRequestHandler(root);
120
+ const server = createNodeServer(handler);
121
+ const host = options.host ?? "127.0.0.1";
122
+ const port = options.port ?? 0;
123
+ await new Promise((resolve, reject) => {
124
+ server.once("error", reject);
125
+ server.listen(port, host, () => resolve());
126
+ });
127
+ const address = server.address();
128
+ const boundPort = typeof address === "object" && address ? address.port : port;
129
+ return {
130
+ url: `http://${host}:${boundPort}`,
131
+ host,
132
+ port: boundPort,
133
+ close: () => new Promise((resolve, reject) => {
134
+ server.close((error) => error ? reject(error) : resolve());
135
+ server.closeAllConnections();
136
+ })
137
+ };
138
+ }
139
+ async function loadTemplate(clientFolder) {
140
+ const siteHtml = path.join(clientFolder, "site.html");
141
+ if (!existsSync(siteHtml)) return void 0;
142
+ const assets = path.join(clientFolder, "assets");
143
+ const clientScript = (await promises.readdir(assets)).find((file) => file.startsWith("clientEntry-"));
144
+ if (!clientScript) throw new Error("clientEntry not found in dist/client/assets");
145
+ return prepareTemplate(await promises.readFile(siteHtml, "utf-8"), `/assets/${clientScript}`);
146
+ }
147
+ async function serveStatic(clientFolder, request) {
148
+ if (request.method !== "GET" && request.method !== "HEAD") return void 0;
149
+ let pathname;
150
+ try {
151
+ pathname = decodeURIComponent(new URL(request.url).pathname);
152
+ } catch {
153
+ return;
154
+ }
155
+ const root = path.resolve(clientFolder);
156
+ const file = path.resolve(root, "." + pathname);
157
+ if (file !== root && !file.startsWith(root + path.sep)) return void 0;
158
+ let stats;
159
+ try {
160
+ stats = await promises.stat(file);
161
+ } catch {
162
+ return;
163
+ }
164
+ if (!stats.isFile()) return void 0;
165
+ const headers = { "Content-Type": contentType(path.extname(file)) };
166
+ if (request.method === "HEAD") return new Response(null, {
167
+ status: 200,
168
+ headers
169
+ });
170
+ return new Response(await promises.readFile(file), {
171
+ status: 200,
172
+ headers
173
+ });
174
+ }
175
+ //#endregion
176
+ export { createRequestHandler, loadEnv, startServer };
177
+
178
+ //# sourceMappingURL=runtime.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.mjs","names":["fs"],"sources":["../src/contentType.ts","../src/prepareTemplate.ts","../src/runtime.ts"],"sourcesContent":["// Kept local so the adapter doesn't depend on @torpor/build internals.\n// From https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n\nexport default function contentType(extension: string): string {\n\treturn types[extension] || \"application/octet-stream\";\n}\n\nconst types: Record<string, string> = {\n\t\".aac\": \"audio/aac\",\n\t\".apng\": \"image/apng\",\n\t\".avif\": \"image/avif\",\n\t\".bin\": \"application/octet-stream\",\n\t\".bmp\": \"image/bmp\",\n\t\".css\": \"text/css\",\n\t\".csv\": \"text/csv\",\n\t\".eot\": \"application/vnd.ms-fontobject\",\n\t\".gif\": \"image/gif\",\n\t\".htm\": \"text/html\",\n\t\".html\": \"text/html\",\n\t\".ico\": \"image/vnd.microsoft.icon\",\n\t\".jpeg\": \"image/jpeg\",\n\t\".jpg\": \"image/jpeg\",\n\t\".js\": \"text/javascript\",\n\t\".json\": \"application/json\",\n\t\".jsonld\": \"application/ld+json\",\n\t\".mjs\": \"text/javascript\",\n\t\".mp3\": \"audio/mpeg\",\n\t\".mp4\": \"video/mp4\",\n\t\".ogg\": \"audio/ogg\",\n\t\".ogv\": \"video/ogg\",\n\t\".opus\": \"audio/ogg\",\n\t\".otf\": \"font/otf\",\n\t\".pdf\": \"application/pdf\",\n\t\".png\": \"image/png\",\n\t\".svg\": \"image/svg+xml\",\n\t\".tar\": \"application/x-tar\",\n\t\".txt\": \"text/plain\",\n\t\".ttf\": \"font/ttf\",\n\t\".wasm\": \"application/wasm\",\n\t\".wav\": \"audio/wav\",\n\t\".webm\": \"video/webm\",\n\t\".webp\": \"image/webp\",\n\t\".woff\": \"font/woff\",\n\t\".woff2\": \"font/woff2\",\n\t\".xml\": \"application/xml\",\n\t\".zip\": \"application/zip\",\n};\n","// Mirrors @torpor/build's `run/prepareTemplate.ts` (kept local so the adapter\n// stays compatible with older @torpor/build installs).\n\nexport default function prepareTemplate(template: string, clientScript: string): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tconst headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tconst divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tconst bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tconst bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number): number {\n\tconst indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { createNodeServer } from \"@torpor/adapter-node\";\nimport { Server } from \"@torpor/build/server\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport contentType from \"./contentType\";\nimport prepareTemplate from \"./prepareTemplate\";\nimport type { RunningServer, StartServerOptions } from \"./types\";\n\n/**\n * Loads a `.env` file from the site root into `process.env`, when the runtime's\n * Node version supports `process.loadEnvFile` (20.12+). Mirrors the CLI, which\n * loads `.env` for dev and preview.\n */\nexport function loadEnv(root: string): void {\n\tconst file = path.join(root, \".env\");\n\tif (!existsSync(file)) return;\n\tconst loader = (process as { loadEnvFile?: (file: string) => void }).loadEnvFile;\n\tif (typeof loader !== \"function\") return;\n\ttry {\n\t\tloader.call(process, file);\n\t} catch {\n\t\t// A malformed .env shouldn't take the app down; the CLI reports it in dev\n\t}\n}\n\n/**\n * Builds a Fetch API handler for a built site: it serves everything under\n * `dist/client` statically and routes the rest through `dist/server`'s\n * `serverEntry.load`. Replaces `runPreview`'s Server setup, which isn't\n * exported from @torpor/build.\n */\nexport async function createRequestHandler(\n\troot: string,\n): Promise<(request: Request) => Promise<Response>> {\n\tconst clientFolder = path.join(root, \"dist\", \"client\");\n\tconst serverFolder = path.join(root, \"dist\", \"server\");\n\tconst template = await loadTemplate(clientFolder);\n\tconst serverEntry = pathToFileURL(path.join(serverFolder, \"serverEntry.js\")).href;\n\n\tconst server = new Server();\n\n\t// Serve anything that exists under dist/client (assets, favicon.ico,\n\t// robots.txt, public files, ...) before falling through to the app\n\tserver.use({\n\t\tenter: async (ev) => serveStatic(clientFolder, ev.request),\n\t});\n\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Node caches the module, so this is only read once\n\t\t\tconst { load } = await import(serverEntry);\n\t\t\treturn await load(ev, template);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[torpor] Unhandled error while rendering:\", error);\n\t\t\treturn new Response(null, { status: 500 });\n\t\t}\n\t});\n\n\treturn (request) => server.fetch(request);\n}\n\n/**\n * Starts the loopback HTTP server for a built site. Requests are handled in\n * the Electron main process (Node), so cookies, sessions and redirects behave\n * exactly as they do on a normal Node server -- Chromium's session cookie\n * store handles persistence across launches.\n */\nexport async function startServer(\n\troot: string,\n\toptions: StartServerOptions = {},\n): Promise<RunningServer> {\n\tloadEnv(root);\n\n\t// Adapters may have added the `adapter` property to globalThis; torpor's\n\t// env() reads it (see @torpor/build/env)\n\t(globalThis as { adapter?: { env: NodeJS.ProcessEnv } }).adapter = { env: process.env };\n\n\tconst handler = await createRequestHandler(root);\n\tconst server = createNodeServer(handler);\n\n\tconst host = options.host ?? \"127.0.0.1\";\n\tconst port = options.port ?? 0;\n\n\tawait new Promise<void>((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(port, host, () => resolve());\n\t});\n\n\tconst address = server.address();\n\tconst boundPort = typeof address === \"object\" && address ? address.port : port;\n\n\treturn {\n\t\turl: `http://${host}:${boundPort}`,\n\t\thost,\n\t\tport: boundPort,\n\t\tclose: () =>\n\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\t// Force-destroy any remaining sockets (keep-alive, SSE from\n\t\t\t\t// `$stream`, etc). `close()` alone waits for connections to end,\n\t\t\t\t// so a long-lived one would keep it from calling back and hang\n\t\t\t\t// the app's shutdown\n\t\t\t\tserver.close((error) => (error ? reject(error) : resolve()));\n\t\t\t\tserver.closeAllConnections();\n\t\t\t}),\n\t};\n}\n\nasync function loadTemplate(clientFolder: string): Promise<string | undefined> {\n\t// An endpoints-only site has no site.html, and no template is needed\n\tconst siteHtml = path.join(clientFolder, \"site.html\");\n\tif (!existsSync(siteHtml)) return undefined;\n\n\tconst assets = path.join(clientFolder, \"assets\");\n\tconst clientScript = (await fs.readdir(assets)).find((file) => file.startsWith(\"clientEntry-\"));\n\tif (!clientScript) {\n\t\tthrow new Error(\"clientEntry not found in dist/client/assets\");\n\t}\n\n\treturn prepareTemplate(await fs.readFile(siteHtml, \"utf-8\"), `/assets/${clientScript}`);\n}\n\nasync function serveStatic(clientFolder: string, request: Request): Promise<Response | undefined> {\n\tif (request.method !== \"GET\" && request.method !== \"HEAD\") return undefined;\n\n\tlet pathname: string;\n\ttry {\n\t\tpathname = decodeURIComponent(new URL(request.url).pathname);\n\t} catch {\n\t\treturn undefined;\n\t}\n\n\t// Resolve within clientFolder, rejecting any path that escapes it\n\tconst root = path.resolve(clientFolder);\n\tconst file = path.resolve(root, \".\" + pathname);\n\tif (file !== root && !file.startsWith(root + path.sep)) return undefined;\n\n\tlet stats: Awaited<ReturnType<typeof fs.stat>>;\n\ttry {\n\t\tstats = await fs.stat(file);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!stats.isFile()) return undefined;\n\n\tconst headers = { \"Content-Type\": contentType(path.extname(file)) };\n\tif (request.method === \"HEAD\") {\n\t\treturn new Response(null, { status: 200, headers });\n\t}\n\treturn new Response(await fs.readFile(file), { status: 200, headers });\n}\n"],"mappings":";;;;;;AAGA,SAAwB,YAAY,WAA2B;CAC9D,OAAO,MAAM,cAAc;AAC5B;AAEA,MAAM,QAAgC;CACrC,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,OAAO;CACP,SAAS;CACT,WAAW;CACX,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,SAAS;CACT,UAAU;CACV,QAAQ;CACR,QAAQ;AACT;;;AC3CA,SAAwB,gBAAgB,UAAkB,cAA8B;CACvF,IAAI,SAAS;CAIb,MAAM,YAAY,OAAO,QAAQ,SAAS;CAC1C,IAAI,cAAc,IACjB,MAAM,IAAI,MAAM,8BAA8B;CAE/C,SAAS,OAAO,UAAU,GAAG,SAAS,IAAI,qBAAqB,OAAO,UAAU,SAAS;CAIzF,MAAM,gBAAgB,aAAa,QAAQ,kCAAkC;CAC7E,IAAI,kBAAkB,IACrB,MAAM,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,IAAI;CACJ,IAAI;EACH,WAAW,mBAAmB,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC,QAAQ;CAC5D,QAAQ;EACP;CACD;CAGA,MAAM,OAAO,KAAK,QAAQ,YAAY;CACtC,MAAM,OAAO,KAAK,QAAQ,MAAM,MAAM,QAAQ;CAC9C,IAAI,SAAS,QAAQ,CAAC,KAAK,WAAW,OAAO,KAAK,GAAG,GAAG,OAAO,KAAA;CAE/D,IAAI;CACJ,IAAI;EACH,QAAQ,MAAMA,SAAG,KAAK,IAAI;CAC3B,QAAQ;EACP;CACD;CACA,IAAI,CAAC,MAAM,OAAO,GAAG,OAAO,KAAA;CAE5B,MAAM,UAAU,EAAE,gBAAgB,YAAY,KAAK,QAAQ,IAAI,CAAC,EAAE;CAClE,IAAI,QAAQ,WAAW,QACtB,OAAO,IAAI,SAAS,MAAM;EAAE,QAAQ;EAAK;CAAQ,CAAC;CAEnD,OAAO,IAAI,SAAS,MAAMA,SAAG,SAAS,IAAI,GAAG;EAAE,QAAQ;EAAK;CAAQ,CAAC;AACtE"}
@@ -0,0 +1,75 @@
1
+ //#region src/types.d.ts
2
+ /**
3
+ * A serializable subset of Electron's `BrowserWindowConstructorOptions`.
4
+ * Only values that survive a JSON round-trip can be used, because the options
5
+ * are written to `dist/electron/electron.json` at build time and read by the
6
+ * Electron main process at launch.
7
+ */
8
+ interface ElectronWindowOptions {
9
+ width?: number;
10
+ height?: number;
11
+ minWidth?: number;
12
+ minHeight?: number;
13
+ maxWidth?: number;
14
+ maxHeight?: number;
15
+ title?: string;
16
+ backgroundColor?: string;
17
+ show?: boolean;
18
+ resizable?: boolean;
19
+ fullscreen?: boolean;
20
+ fullscreenable?: boolean;
21
+ autoHideMenuBar?: boolean;
22
+ alwaysOnTop?: boolean;
23
+ transparent?: boolean;
24
+ }
25
+ interface ElectronOptions {
26
+ /**
27
+ * Options merged into every `new BrowserWindow(...)`. The adapter's own
28
+ * secure defaults (`contextIsolation`, `sandbox`, no `nodeIntegration`)
29
+ * always win over `webPreferences` passed here, which cannot be set.
30
+ */
31
+ window?: ElectronWindowOptions;
32
+ /**
33
+ * The Electron session partition used for the window, e.g.
34
+ * `session.fromPartition(partition)`. Defaults to `"persist:torpor"`, so
35
+ * cookies -- including Torpor's signed session cookie -- and web storage
36
+ * survive restarts. Use a name without the `persist:` prefix for an
37
+ * in-memory partition, or any other name to isolate profiles/users.
38
+ */
39
+ partition?: string;
40
+ /**
41
+ * The host the loopback HTTP server binds to. Defaults to `127.0.0.1`.
42
+ * Binding to anything else exposes the app's server to the network.
43
+ */
44
+ host?: string;
45
+ /**
46
+ * The port for the loopback HTTP server. Defaults to `0` (an ephemeral
47
+ * port, chosen by the OS).
48
+ *
49
+ * Cookies are scoped to the host, not the port, so sessions persist across
50
+ * launches regardless. Web storage (`localStorage`, `IndexedDB`) *is*
51
+ * origin-scoped, though, so pin a stable port if the app relies on it
52
+ * staying put between launches.
53
+ */
54
+ port?: number;
55
+ /**
56
+ * Set to `false` to skip auto-launching an Electron window in dev, leaving
57
+ * `tb --dev` to serve the app in the browser.
58
+ */
59
+ dev?: boolean;
60
+ }
61
+ interface StartServerOptions {
62
+ host?: string;
63
+ port?: number;
64
+ }
65
+ interface RunningServer {
66
+ /** The `http://host:port` origin the window should load. */
67
+ url: string;
68
+ host: string;
69
+ port: number;
70
+ /** Stops the loopback server. */
71
+ close: () => Promise<void>;
72
+ }
73
+ //#endregion
74
+ export { StartServerOptions as i, ElectronWindowOptions as n, RunningServer as r, ElectronOptions as t };
75
+ //# sourceMappingURL=types-Ce9F9DiP.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-Ce9F9DiP.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;;;UAMiB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGgB;;;;;;EAMhB,SAAS;;;;;;;;EAQT;;;;;EAKA;;;;;;;;;;EAUA;;;;;EAKA;;UAGgB;EAChB;EACA;;UAGgB;;EAEhB;EACA;EACA;;EAEA,aAAa"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@torpor/adapter-electron",
3
+ "version": "1.1.0",
4
+ "description": "A @torpor/build adapter for building desktop apps with Electron",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.mts",
9
+ "import": "./dist/index.mjs"
10
+ },
11
+ "./runtime": {
12
+ "types": "./dist/runtime.d.mts",
13
+ "import": "./dist/runtime.mjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "scripts": {
23
+ "check": "tsgo --noEmit && pnpm dlx oxlint --type-aware",
24
+ "build": "tsgo --noEmit && vp pack",
25
+ "build:watch": "vp pack --watch"
26
+ },
27
+ "keywords": [],
28
+ "author": "",
29
+ "license": "ISC",
30
+ "dependencies": {
31
+ "@torpor/adapter-node": "workspace:^",
32
+ "@torpor/build": "workspace:^",
33
+ "vite": "catalog:"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^26.1.2",
37
+ "@typescript/native-preview": "7.0.0-dev.20260707.2",
38
+ "typescript": "^7.0.2",
39
+ "vite-plus": "catalog:"
40
+ }
41
+ }