@witchcraft/nuxt-electron 0.4.4 → 0.4.6

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
@@ -138,7 +138,7 @@ Add the following to the package.json:
138
138
  "description": "Your app description",
139
139
  "author": "Your Name",
140
140
  "repository" :"...",
141
- "main": ".dist/electron/build/main.cjs",
141
+ "main": ".dist/electron/build/main.mjs",
142
142
  "scripts": {
143
143
  "dev": "nuxi dev",
144
144
  "build": "nuxi build",
@@ -147,9 +147,11 @@ Add the following to the package.json:
147
147
  "dev:electron": "AUTO_OPEN=electron pnpm dev",
148
148
  "launch:electron": "electron .",
149
149
  "launch:electron:dev": "LOG_LEVEL=trace OVERRIDE_PUBLIC_SERVER_URL=http://localhost:3000 electron .",
150
- // Use a custom env like "PRODUCTION_BUILD" to control the baking of env variables in the nuxt.config
150
+ // release build
151
+ // use a custom env like "PRODUCTION_BUILD" to control the baking of the "baked" production env
151
152
  "build:electron": "PRODUCTION_BUILD=true BUILD_ELECTRON=true pnpm build",
152
153
  "build:electron:pack": "APP_VERSION=0.0.0 electron-builder --config electron-builder-config.js",
154
+ // local dev build, could be used for testing (note the lack of the baked env control)
153
155
  "build:electron:no-pack": "APP_VERSION=0.0.0 SKIP_ELECTRON_PACK=true BUILD_ELECTRON=true nuxi build",
154
156
  // write a dev desktop file for linux, see below
155
157
  "preview:electron:dev": "concurrently --kill-others \"pnpm preview\" \"sleep 2 && pnpm launch:electron:dev\"",
@@ -165,9 +167,9 @@ Run `pnpm dev:electron`. This will both launch nuxt and open electron.
165
167
 
166
168
  Alternatively, run the server and electron seperately:
167
169
 
168
- Run `pnpm dev` to start the nuxt dev server. The dev version of the app will be written to `.dist/electron/build/main.cjs`.
170
+ Run `pnpm dev` to start the nuxt dev server. The dev version of the app will be written to `.dist/electron/build/main.mjs`.
169
171
 
170
- In a seperate terminal run `pnpm launch:electron` to start the electron app (this will do `electron .` which will run the configured `main` property, aka `.dist/electron/build/main.cjs`).
172
+ In a seperate terminal run `pnpm launch:electron` to start the electron app (this will do `electron .` which will run the configured `main` property, aka `.dist/electron/build/main.mjs`).
171
173
 
172
174
  #### Notes
173
175
  By default the module will not open electron. You must set `process.env.AUTO_OPEN` to include the string `electron` or set `autoOpen `in the options to true, hence the seperate `dev:electron` script.
@@ -178,7 +180,7 @@ The idea is if you use other platform modules as well, you'd do `AUTO_OPEN=elect
178
180
 
179
181
  Build the regular nuxt app with `pnpm build` then build the electron app with `pnpm build:electron` or `pnpm build:electron:no-pack` (if you just want to test, you can skip the packing).
180
182
 
181
- In this case, the build written to `.dist/electron/build/main.cjs` is the **production** build.
183
+ In this case, the build written to `.dist/electron/build/main.mjs` is the **production** build.
182
184
 
183
185
  To run the built production server and the production app proxied to this server, use `pnpm preview:electron:dev`.
184
186
 
@@ -226,14 +228,13 @@ export default defineNuxtConfig({
226
228
  },
227
229
  electron: {
228
230
  additionalElectronVariables: {
229
- // this will hardcode `process.env.PUBLIC_SERVER_URL` to the server url in production
231
+ // this will hardcode `process.env.PUBLIC_SERVER_URL` to the server url
230
232
  // this means getPaths().publicServerUrl will always return your site url (see getPaths) unless you allow getPaths an override (see it for details)
231
- publicServerUrl: process.env.NODE_ENV === "production"
232
233
  // note the quotes for strings! this is a literal replacement that happens
233
234
  // you also cannot access process.env dynamically if you want this to work (e.g. process.env[name])
234
- ? `"https://yoursite.com"`
235
- : `undefined`,
236
- // This bakes "process.env.BAKED_IS_PRODUCTION" for use where runtime overriding should not be allowed
235
+ publicServerUrl: `"https://yoursite.com"`,
236
+ // this bakes the flag so it is available as `process.env.BAKED_IS_PRODUCTION`, pass `process.env.BAKED_IS_PRODUCTION === "true"` to getPaths as `isProduction` for use where runtime overriding should not be allowed
237
+ // the controlling env name and the baked name are just suggestions
237
238
  bakedIsProduction: process.env.PRODUCTION_BUILD === "true" ? `"true"` : `"false"`
238
239
  },
239
240
  // the module will set this to prerender: true
@@ -248,6 +249,30 @@ export default defineNuxtConfig({
248
249
 
249
250
  Proxying server only page routes seems possible but complicated because each route's resource calls must also be proxied. I don't think it's worth the pain. It's easier to make sure the electron app never access server only routes.
250
251
 
252
+ #### Baked Production Flag
253
+
254
+ Apps cannot tell when they are in production unless you bake an env. I suggest something like `BAKED_IS_PRODUCTION`. A flag like this is useful for controlling whether url overrides are allowed (e.g. for testing purposes) or not.
255
+
256
+ ```ts [nuxt.config.ts]
257
+ electron: {
258
+ additionalElectronVariables: {
259
+ bakedIsProduction: process.env.PRODUCTION_BUILD === "true" ? `"true"` : `"false"`
260
+ }
261
+ }
262
+ ```
263
+
264
+
265
+ Pass the flag to `getPaths` as `isProduction` and gate any overrides you want to gate.
266
+
267
+ ```ts [app-electron/main.ts]
268
+ const paths = getPaths(protocolName, {
269
+ publicServerUrl: process.env.OVERRIDE_PUBLIC_SERVER_URL,
270
+ ...(process.env.BAKED_IS_PRODUCTION === "true"
271
+ ? {}
272
+ : { windowUrl: process.env.OVERRIDE_WINDOW_URL })
273
+ }, process.env.BAKED_IS_PRODUCTION === "true")
274
+ ```
275
+
251
276
  ### Runtime Config
252
277
 
253
278
  Anywhere in electron's main files you can also now use nuxt's public runtime config using the special version from the module (only the public part, you don't want to expose your server secrets to the electron app at all). Module does some magic to strinfigy it into the `ELECTRON_RUNTIME_CONFIG` env variable and read it back out:
@@ -301,7 +326,7 @@ DEBUG=true LOG_LEVEL=trace nix run "github:thiagokokada/nix-alien#nix-alien" --
301
326
 
302
327
  Apart from that nix has some additional goodies.
303
328
 
304
- First there flake with a devenv based shell and direnv support. If you have direnv run `direnv allow .` in the project root. Otherwise run `nix develop`.
329
+ First there is a devenv based shell. Run `devenv shell` in the project root. Otherwise run `nix develop`.
305
330
 
306
331
  Nearly everything should work, except the build electron-builder builds. You can do `nix run` instead.
307
332
 
package/dist/module.d.mts CHANGED
@@ -70,6 +70,16 @@ interface ModuleOptions {
70
70
  * Note that `build.emptyOutDir` cannot be changed, it must be false for the reloading to work.
71
71
  */
72
72
  electronViteOptions: ElectronOptions["vite"];
73
+ /**
74
+ * Deps to leave external in the electron main build. Receives the names derived from your package.json dependencies, optionalDependencies and peerDependencies, and returns the names (or regexes) to use. Names get a subpath matcher generated, regexes are passed through.
75
+ *
76
+ * Can be used to filter (and therefore bundle) some deps that are normally externalized.
77
+ *
78
+ * The module always removes itself from this list so it can be bundled (as it relies on the bundling to bake the STATIC runtime paths.
79
+ *
80
+ * Cannot be used in combination with `electronViteOptions.build.rollupOptions.external`. Only one or the other can be used.
81
+ */
82
+ externalDeps?: (derivedNames: string[]) => (string | RegExp)[];
73
83
  notBundleOptions: Parameters<typeof notBundle>[0];
74
84
  /**
75
85
  * Additional variables to "bake" into the electron build. Note these must be quoted if they are strings.
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "electron",
3
3
  "configKey": "electron",
4
- "version": "0.4.4",
4
+ "version": "0.4.6",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -58,6 +58,9 @@ const module$1 = defineNuxtModule({
58
58
  }
59
59
  const moduleName = "@witchcraft/nuxt-electron";
60
60
  const logger = useLogger(moduleName);
61
+ if (options.externalDeps !== void 0 && options.electronViteOptions?.build?.rollupOptions?.external !== void 0) {
62
+ logger.error(`[${moduleName}]: externalDeps and electronViteOptions.build.rollupOptions.external can't be used at the same time, the rollup option always wins. Set one or the other but not both.`);
63
+ }
61
64
  const { resolvePath, resolve } = createResolver(import.meta.url);
62
65
  addComponentsDir({
63
66
  global: true,
@@ -154,9 +157,20 @@ const module$1 = defineNuxtModule({
154
157
  const viteConfig = await viteConfigPromise;
155
158
  const externalDeps = [];
156
159
  const appPackageJson = JSON.parse(await fs.readFile(path.join(nuxt.options.rootDir, "package.json"), "utf8"));
160
+ const dependentNames = [];
157
161
  for (const depSection of ["dependencies", "optionalDependencies", "peerDependencies"]) {
158
162
  for (const dep of Object.keys(appPackageJson[depSection] ?? {})) {
159
- externalDeps.push(dep, new RegExp(`^${dep}(?:/.+)?$`));
163
+ if (dep === moduleName || dependentNames.includes(dep)) {
164
+ continue;
165
+ }
166
+ dependentNames.push(dep);
167
+ }
168
+ }
169
+ for (const entry of options.externalDeps?.(dependentNames) ?? dependentNames) {
170
+ if (typeof entry === "string") {
171
+ externalDeps.push(entry, new RegExp(`^${entry.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:/.+)?$`));
172
+ } else {
173
+ externalDeps.push(entry);
160
174
  }
161
175
  }
162
176
  const electronRuntimeConfig = defu(
@@ -216,10 +230,7 @@ const module$1 = defineNuxtModule({
216
230
  {
217
231
  build: {
218
232
  outDir: electronBuildDir,
219
- minify: false,
220
- rollupOptions: {
221
- external: externalDeps
222
- }
233
+ minify: false
223
234
  },
224
235
  define: electronVariables,
225
236
  resolve: {
@@ -228,6 +239,8 @@ const module$1 = defineNuxtModule({
228
239
  }
229
240
  }
230
241
  );
242
+ electronViteOptions.build.rollupOptions ??= {};
243
+ electronViteOptions.build.rollupOptions.external ??= externalDeps;
231
244
  const electronCliArgs = [
232
245
  ".",
233
246
  ...process.env.NODE_ENV !== "production" && devUserDataDir ? [
@@ -4,14 +4,16 @@
4
4
  *
5
5
  * Paths are not overridable in production unless you pass the variables that can override them.
6
6
  *
7
+ * Whether the app is considered to be in production is determined by the optional isProduction parameter. It should be set to something like the example baked production env in the readme.
8
+ *
7
9
  * ```ts
8
10
  * const paths = getPaths("app", {
9
11
  * windowUrl: process.env.OVERRIDE_WINDOW_URL,
10
12
  * publicServerUrl: process.env.OVERRIDE_PUBLIC_SERVER_URL
11
- * })
13
+ * }, process.env.BAKED_IS_PRODUCTION === "true")
12
14
  * ```
13
15
  */
14
- export declare function getPaths(protocolName?: string, overridingEnvs?: Record<string, string | undefined>): {
16
+ export declare function getPaths(protocolName?: string, overridingEnvs?: Record<string, string | undefined>, isProduction?: boolean): {
15
17
  windowUrl: string;
16
18
  publicServerUrl: string;
17
19
  nuxtPublicDir: string;
@@ -5,7 +5,7 @@ import { STATIC } from "../static.js";
5
5
  export function getPaths(protocolName = "app", overridingEnvs = {
6
6
  windowUrl: void 0,
7
7
  publicServerUrl: void 0
8
- }) {
8
+ }, isProduction) {
9
9
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
10
  const nuxtPublicDir = path.join(__dirname, STATIC.ELECTRON_NUXT_PUBLIC_DIR);
11
11
  const preloadPath = path.join(__dirname, STATIC.ELECTRON_BUILD_DIR, "./preload.cjs");
@@ -23,7 +23,7 @@ export function getPaths(protocolName = "app", overridingEnvs = {
23
23
  windowUrl: `${overridingEnvs.windowUrl}${STATIC.ELECTRON_ROUTE}`
24
24
  };
25
25
  }
26
- if (process.env.NODE_ENV !== "production" && process.env.VITE_DEV_SERVER_URL) {
26
+ if (!isProduction && process.env.VITE_DEV_SERVER_URL) {
27
27
  return {
28
28
  ...base,
29
29
  windowUrl: `${process.env.VITE_DEV_SERVER_URL}${STATIC.ELECTRON_ROUTE}`
@@ -0,0 +1,3 @@
1
+ export { launchElectron } from "./launchElectron.js";
2
+ export { localhostUrl } from "./localhostUrl.js";
3
+ export { waitUntilAtPath } from "./waitUntilAtPath.js";
@@ -0,0 +1,3 @@
1
+ export { launchElectron } from "./launchElectron.js";
2
+ export { localhostUrl } from "./localhostUrl.js";
3
+ export { waitUntilAtPath } from "./waitUntilAtPath.js";
@@ -0,0 +1,54 @@
1
+ import { type ElectronApplication, type Page } from "@playwright/test";
2
+ import type { Cookie } from "electron";
3
+ /**
4
+ * Creates a Playwright test object with an Electron app and its window wired in. The app launches on first use and closes when the test ends.
5
+ *
6
+ * Without arguments the page is the window the app opens at launch. Pass another prefix to waitForWindow after an action that opens a different window.
7
+ */
8
+ export declare function launchElectron({ appDir, userDataDir, serverUrl, useDevMode, bundlePrefix, env, extraArgs, windowTimeout }: {
9
+ /** Points the app at serverUrl with VITE_DEV_SERVER_URL instead of at its bundlePrefix. Only works when the app leaves the windowUrl override open, so a baked production flag must be false. */
10
+ useDevMode?: boolean;
11
+ /** Directory the app is launched from, becomes the electron process cwd. A module playground passes its playground dir, an app passes its repo root. */
12
+ appDir: string;
13
+ /** Profile directory, it will be wiped before every launch. Point it somewhere gitignored. Must be within appDir for safety. */
14
+ userDataDir: string;
15
+ /** Server the app talks to when proxying. Is used to launch electron with OVERRIDE_PUBLIC_SERVER_URL and VITE_DEV_SERVER_URL as needed. */
16
+ serverUrl: string;
17
+ /** How long to wait for the matching window before throwing. */
18
+ windowTimeout?: number;
19
+ /** The app's bundle url prefix, e.g. "app://bundle". Only needed in bundled mode, dev uses serverUrl. */
20
+ bundlePrefix?: string;
21
+ /** Extra env to run the app with. */
22
+ env?: Record<string, string>;
23
+ /** Extra args for the electron process. */
24
+ extraArgs?: string[];
25
+ }): import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & {
26
+ app: ElectronApplication;
27
+ page: Page;
28
+ /**
29
+ * Waits for a window whose url starts with the prefix and returns it.
30
+ *
31
+ * Without arguments it waits for the launch prefix, which is the app bundle normally and the server url in dev. Pass another prefix after an action that opens a different window, such as switching user. Already open windows are checked first, then new arrivals, and navigation is awaited since the url is not set yet when the window event fires. Throws listing the urls it saw on timeout.
32
+ */
33
+ waitForWindow: (prefix?: string, timeout?: number) => Promise<Page>;
34
+ /**
35
+ * Returns the next window the app opens, for example after switching user.
36
+ *
37
+ * Unlike waitForWindow it does not match by url, it takes whatever non-first window arrives next. An event that fired before the caller asks is not missed, and it waits until only one window is listed since the app closes the old window asynchronously.
38
+ */
39
+ getPageFromWindow: () => Promise<Page>;
40
+ /**
41
+ * Cancels the given window's session requests (http/https only by default), so proxied calls fail instead of being answered to simulate the server being unavailable. You can also pass a custom list of urls (which can contain globs, see win.webContents.session.webRequest.onBeforeRequest).
42
+ */
43
+ blockNetwork: (page: Page, urls?: string[]) => Promise<void>;
44
+ /**
45
+ * Lets all the given window's requests through again, after blockNetwork.
46
+ */
47
+ unblockNetwork: (page: Page) => Promise<void>;
48
+ /**
49
+ * Reads the cookies of the given window's session, all of them or the ones named.
50
+ *
51
+ * The window is matched by its position among the app's windows, which share creation order on both sides.
52
+ */
53
+ getWindowCookies: (page: Page, name?: string) => Promise<Cookie[]>;
54
+ }, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
@@ -0,0 +1,152 @@
1
+ import { _electron as electron, expect, test as base } from "@playwright/test";
2
+ import { rm } from "node:fs/promises";
3
+ import path from "node:path";
4
+ export function launchElectron({
5
+ appDir,
6
+ userDataDir,
7
+ serverUrl,
8
+ useDevMode = false,
9
+ bundlePrefix,
10
+ env = {},
11
+ extraArgs = [],
12
+ windowTimeout = 3e4
13
+ }) {
14
+ if (!useDevMode && !bundlePrefix) {
15
+ throw new Error("launchElectron: pass bundlePrefix, the app's bundle url prefix, or run in dev with useDevMode.");
16
+ }
17
+ const launchPrefix = useDevMode ? serverUrl : bundlePrefix;
18
+ return base.extend({
19
+ browser: async ({ browser }, use) => {
20
+ const marked = browser;
21
+ if (!marked.isTestContextMarked) {
22
+ marked.isTestContextMarked = true;
23
+ const newContext = browser.newContext.bind(browser);
24
+ browser.newContext = async (options) => {
25
+ const context = await newContext(options);
26
+ await context.addInitScript(() => {
27
+ window.__IS_TEST = true;
28
+ });
29
+ return context;
30
+ };
31
+ }
32
+ await use(browser);
33
+ },
34
+ // eslint-disable-next-line no-empty-pattern
35
+ app: async ({}, use) => {
36
+ const relative = path.relative(path.resolve(appDir), path.resolve(userDataDir));
37
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
38
+ throw new Error(`userDataDir must be inside appDir, got ${userDataDir}.`);
39
+ }
40
+ await rm(userDataDir, { recursive: true, force: true });
41
+ const app = await electron.launch({
42
+ // launched as an app directory so `app.getAppPath()` is the app root, which is where
43
+ // @witchcraft/nuxt-logger resolves pino's workers from
44
+ args: [".", "--no-sandbox", "--ignore-certificate-errors", `--user-data-dir=${userDataDir}`, ...extraArgs],
45
+ cwd: appDir,
46
+ env: {
47
+ ...process.env,
48
+ ...env,
49
+ DISABLE_AUTO_UPDATES: "true",
50
+ OVERRIDE_PUBLIC_SERVER_URL: serverUrl,
51
+ ...useDevMode ? { VITE_DEV_SERVER_URL: serverUrl } : {}
52
+ }
53
+ });
54
+ await use(app);
55
+ await app.close();
56
+ },
57
+ page: async ({ waitForWindow }, use) => {
58
+ await use(await waitForWindow());
59
+ },
60
+ waitForWindow: async ({ app }, use) => {
61
+ const isAppWindow = (candidate) => !candidate.url().startsWith("devtools://");
62
+ await use(async (prefix = launchPrefix, timeout = windowTimeout) => {
63
+ const deadline = Date.now() + timeout;
64
+ const watched = /* @__PURE__ */ new Map();
65
+ let page;
66
+ while (!page && Date.now() < deadline) {
67
+ const next = await Promise.race([
68
+ // watches windows already open until their url matches, the url is not set yet when a window appears
69
+ ...app.windows().filter(isAppWindow).map((candidate) => {
70
+ let pending = watched.get(candidate);
71
+ if (!pending) {
72
+ pending = candidate.waitForURL((url) => url.toString().startsWith(prefix), { timeout: Math.max(deadline - Date.now(), 1) }).then(() => candidate).catch(() => void 0);
73
+ watched.set(candidate, pending);
74
+ }
75
+ return pending;
76
+ }),
77
+ // notices each newly opening window, matched or not
78
+ app.waitForEvent("window", { timeout: Math.max(deadline - Date.now(), 1) }).then((window2) => isAppWindow(window2) ? window2 : void 0).catch(() => void 0)
79
+ ]);
80
+ if (next && next.url().startsWith(prefix)) page = next;
81
+ }
82
+ if (!page) {
83
+ const seen = app.windows().map((candidate) => candidate.url());
84
+ throw new Error(`No window with url starting with ${prefix}, saw: ${seen.join(", ") || "no windows"}.`);
85
+ }
86
+ return page;
87
+ });
88
+ },
89
+ getPageFromWindow: async ({ app }, use) => {
90
+ const isAppWindow = (candidate) => !candidate.url().startsWith("devtools://");
91
+ const deadline = Date.now() + windowTimeout;
92
+ let first = app.windows().find(isAppWindow);
93
+ while (!first && Date.now() < deadline) {
94
+ const candidate = await app.waitForEvent("window", { timeout: Math.max(deadline - Date.now(), 1) }).catch(() => void 0);
95
+ if (candidate && isAppWindow(candidate)) first = candidate;
96
+ }
97
+ if (!first) throw new Error("getPageFromWindow: no app window opened.");
98
+ const pending = app.windows().filter((candidate) => candidate !== first && isAppWindow(candidate));
99
+ const waiting = [];
100
+ app.on("window", (window2) => {
101
+ if (window2 === first || !isAppWindow(window2)) return;
102
+ pending.push(window2);
103
+ waiting.shift()?.();
104
+ });
105
+ await use(async () => {
106
+ if (pending.length === 0) await new Promise((resolve) => waiting.push(resolve));
107
+ const next = pending.shift();
108
+ await next.waitForLoadState("load", { timeout: windowTimeout });
109
+ await expect.poll(() => app.evaluate((electron2) => electron2.BrowserWindow.getAllWindows().length), { timeout: windowTimeout }).toBe(1);
110
+ return next;
111
+ });
112
+ },
113
+ blockNetwork: async ({ app }, use) => {
114
+ await use(async (page, urls = ["http://*/*", "https://*/*"]) => {
115
+ const index = app.windows().filter((candidate) => {
116
+ return !candidate.url().startsWith("devtools://");
117
+ }).indexOf(page);
118
+ if (index === -1) throw new Error("blockNetwork: the page does not belong to this app.");
119
+ await app.evaluate((electron2, { windowIndex, patterns }) => {
120
+ const win = electron2.BrowserWindow.getAllWindows()[windowIndex];
121
+ if (!win) throw new Error("blockNetwork: no window at that index.");
122
+ win.webContents.session.webRequest.onBeforeRequest(
123
+ { urls: patterns },
124
+ (_details, callback) => callback({ cancel: true })
125
+ );
126
+ }, { windowIndex: index, patterns: urls });
127
+ });
128
+ },
129
+ unblockNetwork: async ({ app }, use) => {
130
+ await use(async (page) => {
131
+ const index = app.windows().filter((candidate) => !candidate.url().startsWith("devtools://")).indexOf(page);
132
+ if (index === -1) throw new Error("unblockNetwork: the page does not belong to this app.");
133
+ await app.evaluate((electron2, windowIndex) => {
134
+ const win = electron2.BrowserWindow.getAllWindows()[windowIndex];
135
+ if (!win) throw new Error("unblockNetwork: no window at that index.");
136
+ win.webContents.session.webRequest.onBeforeRequest(null);
137
+ }, index);
138
+ });
139
+ },
140
+ getWindowCookies: async ({ app }, use) => {
141
+ await use(async (page, name) => {
142
+ const index = app.windows().filter((candidate) => !candidate.url().startsWith("devtools://")).indexOf(page);
143
+ if (index === -1) throw new Error("getWindowCookies: the page does not belong to this app.");
144
+ return app.evaluate((electron2, { windowIndex, cookieName }) => {
145
+ const win = electron2.BrowserWindow.getAllWindows()[windowIndex];
146
+ if (!win) throw new Error("getWindowCookies: no window at that index.");
147
+ return win.webContents.session.cookies.get(cookieName ? { name: cookieName } : {});
148
+ }, { windowIndex: index, cookieName: name });
149
+ });
150
+ }
151
+ });
152
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The url the local dev server is reached on. https is used if LOCALHOST_KEY_PEM and LOCALHOST_PEM are set.
3
+ *
4
+ * Defaults to `http://localhost:${NUXT_POST ?? 3000}`
5
+ *
6
+ */
7
+ export declare function localhostUrl(port?: string | number): string;
@@ -0,0 +1,4 @@
1
+ export function localhostUrl(port = process.env.NUXT_PORT ?? "3000") {
2
+ const certs = process.env.LOCALHOST_KEY_PEM && process.env.LOCALHOST_PEM;
3
+ return `${certs ? "https" : "http"}://localhost:${port}`;
4
+ }
@@ -0,0 +1,5 @@
1
+ import type { Page } from "@playwright/test";
2
+ /**
3
+ * Waits until the page is on the route path, whatever the scheme and host are. The same route is app://bundle/authed in the bundle and http://localhost/authed in dev, so matching the pathname is what keeps one assertion working in both.
4
+ */
5
+ export declare function waitUntilAtPath(page: Page, routePath: string, timeout?: number): Promise<void>;
@@ -0,0 +1,9 @@
1
+ export async function waitUntilAtPath(page, routePath, timeout) {
2
+ await page.waitForURL((url) => {
3
+ try {
4
+ return new URL(url).pathname === routePath;
5
+ } catch {
6
+ return false;
7
+ }
8
+ }, { timeout });
9
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@witchcraft/nuxt-electron",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "description": "Nuxt module for working with electron.",
5
5
  "repository": "https://github.com/witchcraftjs/nuxt-electron",
6
6
  "license": "MIT",
@@ -27,6 +27,10 @@
27
27
  "types": "./dist/runtime/electron/renderer/index.d.ts",
28
28
  "import": "./dist/runtime/electron/renderer/index.js"
29
29
  },
30
+ "./electron/test": {
31
+ "types": "./dist/runtime/electron/test/index.d.ts",
32
+ "import": "./dist/runtime/electron/test/index.js"
33
+ },
30
34
  "./electron/*": {
31
35
  "types": "./dist/runtime/electron/*.d.ts",
32
36
  "import": "./dist/runtime/electron/*.js"
@@ -46,7 +50,7 @@
46
50
  "@witchcraft/nuxt-utils": "^0.3.18",
47
51
  "@witchcraft/ui": "^0.5.12",
48
52
  "defu": "^6.1.4",
49
- "electron": "^37.10.3",
53
+ "electron": "^44.0.0",
50
54
  "es-toolkit": "^1.44.0",
51
55
  "vite-plugin-electron": "^0.29.0"
52
56
  },
@@ -70,6 +74,8 @@
70
74
  "@nuxt/module-builder": "^1.0.3",
71
75
  "@nuxt/schema": "^4.3.1",
72
76
  "@nuxt/test-utils": "^3.23.0",
77
+ "@playwright/test": "=1.65.0",
78
+ "playwright-core": "=1.65.0",
73
79
  "@types/node": "latest",
74
80
  "changelogen": "^0.6.2",
75
81
  "eslint": "^9.39.2",
@@ -103,6 +109,11 @@
103
109
  "lint": "pnpm lint:eslint && pnpm lint:types",
104
110
  "lint:eslint": "eslint \"{src,test,playground/app}/**/*.{ts,vue}\" \"*.{js,cjs,mjs,ts}\"",
105
111
  "lint:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
106
- "test": "echo \"No tests\""
112
+ "test": "pnpm test:electron",
113
+ "test:electron": "pnpm --dir playground test:electron",
114
+ "test:electron:only": "pnpm --dir playground test:electron:only",
115
+ "test:electron:dev": "pnpm --dir playground test:electron:dev",
116
+ "test:ci": "pnpm --dir playground test:ci",
117
+ "test:server": "pnpm --dir playground test:server"
107
118
  }
108
119
  }
package/src/module.ts CHANGED
@@ -105,6 +105,16 @@ export interface ModuleOptions {
105
105
  */
106
106
  // importing the type from vite is causing build issues :/
107
107
  electronViteOptions: ElectronOptions["vite"]
108
+ /**
109
+ * Deps to leave external in the electron main build. Receives the names derived from your package.json dependencies, optionalDependencies and peerDependencies, and returns the names (or regexes) to use. Names get a subpath matcher generated, regexes are passed through.
110
+ *
111
+ * Can be used to filter (and therefore bundle) some deps that are normally externalized.
112
+ *
113
+ * The module always removes itself from this list so it can be bundled (as it relies on the bundling to bake the STATIC runtime paths.
114
+ *
115
+ * Cannot be used in combination with `electronViteOptions.build.rollupOptions.external`. Only one or the other can be used.
116
+ */
117
+ externalDeps?: (derivedNames: string[]) => (string | RegExp)[]
108
118
  notBundleOptions: Parameters<typeof notBundle>[0]
109
119
  /**
110
120
  * Additional variables to "bake" into the electron build. Note these must be quoted if they are strings.
@@ -185,6 +195,13 @@ export default defineNuxtModule<ModuleOptions>({
185
195
  if (!options.enable) { return }
186
196
  const moduleName = "@witchcraft/nuxt-electron"
187
197
  const logger = useLogger(moduleName)
198
+
199
+ if (
200
+ options.externalDeps !== undefined
201
+ && options.electronViteOptions?.build?.rollupOptions?.external !== undefined
202
+ ) {
203
+ logger.error(`[${moduleName}]: externalDeps and electronViteOptions.build.rollupOptions.external can't be used at the same time, the rollup option always wins. Set one or the other but not both.`)
204
+ }
188
205
  const { resolvePath, resolve } = createResolver(import.meta.url)
189
206
 
190
207
  addComponentsDir({
@@ -309,9 +326,19 @@ export default defineNuxtModule<ModuleOptions>({
309
326
 
310
327
  const externalDeps: (string | RegExp)[] = []
311
328
  const appPackageJson = JSON.parse(await fs.readFile(path.join(nuxt.options.rootDir, "package.json"), "utf8"))
329
+ const dependentNames: string[] = []
312
330
  for (const depSection of ["dependencies", "optionalDependencies", "peerDependencies"] as const) {
313
331
  for (const dep of Object.keys(appPackageJson[depSection] ?? {})) {
314
- externalDeps.push(dep, new RegExp(`^${dep}(?:/.+)?$`))
332
+ // this module is always bundled so its baked values survive
333
+ if (dep === moduleName || dependentNames.includes(dep)) { continue }
334
+ dependentNames.push(dep)
335
+ }
336
+ }
337
+ for (const entry of options.externalDeps?.(dependentNames) ?? dependentNames) {
338
+ if (typeof entry === "string") {
339
+ externalDeps.push(entry, new RegExp(`^${entry.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:/.+)?$`))
340
+ } else {
341
+ externalDeps.push(entry)
315
342
  }
316
343
  }
317
344
 
@@ -375,10 +402,7 @@ export default defineNuxtModule<ModuleOptions>({
375
402
  {
376
403
  build: {
377
404
  outDir: electronBuildDir,
378
- minify: false,
379
- rollupOptions: {
380
- external: externalDeps
381
- }
405
+ minify: false
382
406
  },
383
407
  define: electronVariables,
384
408
  resolve: {
@@ -386,6 +410,9 @@ export default defineNuxtModule<ModuleOptions>({
386
410
  extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"]
387
411
  }
388
412
  })
413
+ // set after the merge, defu would union it with a value set in electronViteOptions
414
+ electronViteOptions.build!.rollupOptions ??= {}
415
+ electronViteOptions.build!.rollupOptions.external ??= externalDeps
389
416
 
390
417
  const electronCliArgs = [
391
418
  ".",
@@ -10,11 +10,13 @@ import { STATIC } from "../static.js"
10
10
  *
11
11
  * Paths are not overridable in production unless you pass the variables that can override them.
12
12
  *
13
+ * Whether the app is considered to be in production is determined by the optional isProduction parameter. It should be set to something like the example baked production env in the readme.
14
+ *
13
15
  * ```ts
14
16
  * const paths = getPaths("app", {
15
17
  * windowUrl: process.env.OVERRIDE_WINDOW_URL,
16
18
  * publicServerUrl: process.env.OVERRIDE_PUBLIC_SERVER_URL
17
- * })
19
+ * }, process.env.BAKED_IS_PRODUCTION === "true")
18
20
  * ```
19
21
  */
20
22
  export function getPaths(
@@ -22,7 +24,8 @@ export function getPaths(
22
24
  overridingEnvs: Record<string, string | undefined> = {
23
25
  windowUrl: undefined,
24
26
  publicServerUrl: undefined
25
- }
27
+ },
28
+ isProduction?: boolean
26
29
  ): {
27
30
  windowUrl: string
28
31
  publicServerUrl: string
@@ -56,7 +59,7 @@ export function getPaths(
56
59
  }
57
60
  }
58
61
 
59
- if (process.env.NODE_ENV !== "production" && process.env.VITE_DEV_SERVER_URL) {
62
+ if (!isProduction && process.env.VITE_DEV_SERVER_URL) {
60
63
  return {
61
64
  ...base,
62
65
  windowUrl: `${process.env.VITE_DEV_SERVER_URL}${STATIC.ELECTRON_ROUTE}`
@@ -0,0 +1,3 @@
1
+ export { launchElectron } from "./launchElectron.js"
2
+ export { localhostUrl } from "./localhostUrl.js"
3
+ export { waitUntilAtPath } from "./waitUntilAtPath.js"
@@ -0,0 +1,216 @@
1
+ import { _electron as electron, type ElectronApplication, expect, type Page, test as base } from "@playwright/test"
2
+ import type { Cookie } from "electron"
3
+ import { rm } from "node:fs/promises"
4
+ import path from "node:path"
5
+
6
+ // playwright's window list includes devtools, getAllWindows does not, so devtools is filtered out of every window list the fixture reads
7
+
8
+ /**
9
+ * Creates a Playwright test object with an Electron app and its window wired in. The app launches on first use and closes when the test ends.
10
+ *
11
+ * Without arguments the page is the window the app opens at launch. Pass another prefix to waitForWindow after an action that opens a different window.
12
+ */
13
+ export function launchElectron({
14
+ appDir,
15
+ userDataDir,
16
+ serverUrl,
17
+ useDevMode = false,
18
+ bundlePrefix,
19
+ env = {},
20
+ extraArgs = [],
21
+ windowTimeout = 30_000
22
+ }: {
23
+ /** Points the app at serverUrl with VITE_DEV_SERVER_URL instead of at its bundlePrefix. Only works when the app leaves the windowUrl override open, so a baked production flag must be false. */
24
+ useDevMode?: boolean
25
+ /** Directory the app is launched from, becomes the electron process cwd. A module playground passes its playground dir, an app passes its repo root. */
26
+ appDir: string
27
+ /** Profile directory, it will be wiped before every launch. Point it somewhere gitignored. Must be within appDir for safety. */
28
+ userDataDir: string
29
+ /** Server the app talks to when proxying. Is used to launch electron with OVERRIDE_PUBLIC_SERVER_URL and VITE_DEV_SERVER_URL as needed. */
30
+ serverUrl: string
31
+ /** How long to wait for the matching window before throwing. */
32
+ windowTimeout?: number
33
+ /** The app's bundle url prefix, e.g. "app://bundle". Only needed in bundled mode, dev uses serverUrl. */
34
+ bundlePrefix?: string
35
+ /** Extra env to run the app with. */
36
+ env?: Record<string, string>
37
+ /** Extra args for the electron process. */
38
+ extraArgs?: string[]
39
+ }) {
40
+ if (!useDevMode && !bundlePrefix) {
41
+ throw new Error("launchElectron: pass bundlePrefix, the app's bundle url prefix, or run in dev with useDevMode.")
42
+ }
43
+ const launchPrefix = useDevMode ? serverUrl : bundlePrefix as string
44
+ return base.extend<{
45
+ app: ElectronApplication
46
+ page: Page
47
+ /**
48
+ * Waits for a window whose url starts with the prefix and returns it.
49
+ *
50
+ * Without arguments it waits for the launch prefix, which is the app bundle normally and the server url in dev. Pass another prefix after an action that opens a different window, such as switching user. Already open windows are checked first, then new arrivals, and navigation is awaited since the url is not set yet when the window event fires. Throws listing the urls it saw on timeout.
51
+ */
52
+ waitForWindow: (prefix?: string, timeout?: number) => Promise<Page>
53
+ /**
54
+ * Returns the next window the app opens, for example after switching user.
55
+ *
56
+ * Unlike waitForWindow it does not match by url, it takes whatever non-first window arrives next. An event that fired before the caller asks is not missed, and it waits until only one window is listed since the app closes the old window asynchronously.
57
+ */
58
+ getPageFromWindow: () => Promise<Page>
59
+ /**
60
+ * Cancels the given window's session requests (http/https only by default), so proxied calls fail instead of being answered to simulate the server being unavailable. You can also pass a custom list of urls (which can contain globs, see win.webContents.session.webRequest.onBeforeRequest).
61
+ */
62
+ blockNetwork: (page: Page, urls?: string[]) => Promise<void>
63
+ /**
64
+ * Lets all the given window's requests through again, after blockNetwork.
65
+ */
66
+ unblockNetwork: (page: Page) => Promise<void>
67
+ /**
68
+ * Reads the cookies of the given window's session, all of them or the ones named.
69
+ *
70
+ * The window is matched by its position among the app's windows, which share creation order on both sides.
71
+ */
72
+ getWindowCookies: (page: Page, name?: string) => Promise<Cookie[]>
73
+ }>({
74
+ browser: async ({ browser }, use) => {
75
+ // every context a test creates carries __IS_TEST from the first load, app code reads it while booting
76
+ const marked = browser as typeof browser & { isTestContextMarked?: boolean }
77
+ if (!marked.isTestContextMarked) {
78
+ marked.isTestContextMarked = true
79
+ const newContext = browser.newContext.bind(browser)
80
+ browser.newContext = async options => {
81
+ const context = await newContext(options)
82
+ await context.addInitScript(() => { (window as any).__IS_TEST = true })
83
+ return context
84
+ }
85
+ }
86
+ await use(browser)
87
+ },
88
+ // eslint-disable-next-line no-empty-pattern
89
+ app: async ({}, use) => {
90
+ const relative = path.relative(path.resolve(appDir), path.resolve(userDataDir))
91
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
92
+ throw new Error(`userDataDir must be inside appDir, got ${userDataDir}.`)
93
+ }
94
+ await rm(userDataDir, { recursive: true, force: true })
95
+
96
+ const app = await electron.launch({
97
+ // launched as an app directory so `app.getAppPath()` is the app root, which is where
98
+ // @witchcraft/nuxt-logger resolves pino's workers from
99
+ args: [".", "--no-sandbox", "--ignore-certificate-errors", `--user-data-dir=${userDataDir}`, ...extraArgs],
100
+ cwd: appDir,
101
+ env: {
102
+ ...process.env,
103
+ ...env,
104
+ DISABLE_AUTO_UPDATES: "true",
105
+ OVERRIDE_PUBLIC_SERVER_URL: serverUrl,
106
+ ...(useDevMode ? { VITE_DEV_SERVER_URL: serverUrl } : {})
107
+ } as Record<string, string>
108
+ })
109
+ await use(app)
110
+ await app.close()
111
+ },
112
+ page: async ({ waitForWindow }, use) => {
113
+ await use(await waitForWindow())
114
+ },
115
+
116
+ waitForWindow: async ({ app }, use) => {
117
+ const isAppWindow = (candidate: Page) => !candidate.url().startsWith("devtools://")
118
+ await use(async (prefix = launchPrefix, timeout = windowTimeout): Promise<Page> => {
119
+ const deadline = Date.now() + timeout
120
+ const watched = new Map<Page, Promise<Page | undefined>>()
121
+ let page: Page | undefined
122
+ while (!page && Date.now() < deadline) {
123
+ const next = await Promise.race([
124
+ // watches windows already open until their url matches, the url is not set yet when a window appears
125
+ ...app.windows().filter(isAppWindow).map((candidate: Page): Promise<Page | undefined> => {
126
+ let pending: Promise<Page | undefined> | undefined = watched.get(candidate)
127
+ if (!pending) {
128
+ pending = candidate.waitForURL(url => url.toString().startsWith(prefix), { timeout: Math.max(deadline - Date.now(), 1) }).then(() => candidate).catch(() => undefined)
129
+ watched.set(candidate, pending)
130
+ }
131
+ return pending
132
+ }),
133
+ // notices each newly opening window, matched or not
134
+ app.waitForEvent("window", { timeout: Math.max(deadline - Date.now(), 1) }).then(window => isAppWindow(window) ? window : undefined).catch(() => undefined)
135
+ ])
136
+ // keeps only winners whose url matches
137
+ if (next && next.url().startsWith(prefix)) page = next
138
+ }
139
+ if (!page) {
140
+ const seen = app.windows().map(candidate => candidate.url())
141
+ throw new Error(`No window with url starting with ${prefix}, saw: ${seen.join(", ") || "no windows"}.`)
142
+ }
143
+ return page
144
+ })
145
+ },
146
+
147
+ getPageFromWindow: async ({ app }, use) => {
148
+ const isAppWindow = (candidate: Page) => !candidate.url().startsWith("devtools://")
149
+ // the first window is not a reopen, and its event has already fired by the time this runs
150
+ const deadline = Date.now() + windowTimeout
151
+ let first = app.windows().find(isAppWindow)
152
+ while (!first && Date.now() < deadline) {
153
+ const candidate = await app.waitForEvent("window", { timeout: Math.max(deadline - Date.now(), 1) }).catch(() => undefined)
154
+ if (candidate && isAppWindow(candidate)) first = candidate
155
+ }
156
+ if (!first) throw new Error("getPageFromWindow: no app window opened.")
157
+ const pending: Page[] = app.windows().filter(candidate => candidate !== first && isAppWindow(candidate))
158
+ const waiting: (() => void)[] = []
159
+ app.on("window", window => {
160
+ if (window === first || !isAppWindow(window)) return
161
+ pending.push(window)
162
+ waiting.shift()?.()
163
+ })
164
+ await use(async () => {
165
+ // the event can have fired before the caller asks, so the queue is the only source, never waitForEvent
166
+ if (pending.length === 0) await new Promise<void>(resolve => waiting.push(resolve))
167
+ const next = pending.shift()!
168
+ await next.waitForLoadState("load", { timeout: windowTimeout })
169
+ // the app closes the old window asynchronously, so it can still be listed while the new one loads
170
+ await expect.poll(() => app.evaluate(electron => electron.BrowserWindow.getAllWindows().length), { timeout: windowTimeout }).toBe(1)
171
+ return next
172
+ })
173
+ },
174
+ blockNetwork: async ({ app }, use) => {
175
+ await use(async (page: Page, urls: string[] = ["http://*/*", "https://*/*"]) => {
176
+ const index = app.windows()
177
+ .filter(candidate => {
178
+ return !candidate.url().startsWith("devtools://")
179
+ })
180
+ .indexOf(page)
181
+
182
+ if (index === -1) throw new Error("blockNetwork: the page does not belong to this app.")
183
+ await app.evaluate((electron, { windowIndex, patterns }) => {
184
+ const win = electron.BrowserWindow.getAllWindows()[windowIndex]
185
+ if (!win) throw new Error("blockNetwork: no window at that index.")
186
+ win.webContents.session.webRequest.onBeforeRequest(
187
+ { urls: patterns },
188
+ (_details, callback) => callback({ cancel: true })
189
+ )
190
+ }, { windowIndex: index, patterns: urls })
191
+ })
192
+ },
193
+ unblockNetwork: async ({ app }, use) => {
194
+ await use(async (page: Page) => {
195
+ const index = app.windows().filter(candidate => !candidate.url().startsWith("devtools://")).indexOf(page)
196
+ if (index === -1) throw new Error("unblockNetwork: the page does not belong to this app.")
197
+ await app.evaluate((electron, windowIndex) => {
198
+ const win = electron.BrowserWindow.getAllWindows()[windowIndex]
199
+ if (!win) throw new Error("unblockNetwork: no window at that index.")
200
+ win.webContents.session.webRequest.onBeforeRequest(null)
201
+ }, index)
202
+ })
203
+ },
204
+ getWindowCookies: async ({ app }, use) => {
205
+ await use(async (page: Page, name?: string) => {
206
+ const index = app.windows().filter(candidate => !candidate.url().startsWith("devtools://")).indexOf(page)
207
+ if (index === -1) throw new Error("getWindowCookies: the page does not belong to this app.")
208
+ return app.evaluate((electron, { windowIndex, cookieName }) => {
209
+ const win = electron.BrowserWindow.getAllWindows()[windowIndex]
210
+ if (!win) throw new Error("getWindowCookies: no window at that index.")
211
+ return win.webContents.session.cookies.get(cookieName ? { name: cookieName } : {})
212
+ }, { windowIndex: index, cookieName: name })
213
+ })
214
+ }
215
+ })
216
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The url the local dev server is reached on. https is used if LOCALHOST_KEY_PEM and LOCALHOST_PEM are set.
3
+ *
4
+ * Defaults to `http://localhost:${NUXT_POST ?? 3000}`
5
+ *
6
+ */
7
+ export function localhostUrl(port: string | number = process.env.NUXT_PORT ?? "3000"): string {
8
+ const certs = process.env.LOCALHOST_KEY_PEM && process.env.LOCALHOST_PEM
9
+ return `${certs ? "https" : "http"}://localhost:${port}`
10
+ }
@@ -0,0 +1,14 @@
1
+ import type { Page } from "@playwright/test"
2
+
3
+ /**
4
+ * Waits until the page is on the route path, whatever the scheme and host are. The same route is app://bundle/authed in the bundle and http://localhost/authed in dev, so matching the pathname is what keeps one assertion working in both.
5
+ */
6
+ export async function waitUntilAtPath(page: Page, routePath: string, timeout?: number): Promise<void> {
7
+ await page.waitForURL(url => {
8
+ try {
9
+ return new URL(url).pathname === routePath
10
+ } catch {
11
+ return false
12
+ }
13
+ }, { timeout })
14
+ }