Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Replace eight source-text checks with tests that run the real thing (#5192)

Nick Gomez6fe38839dd6e
diff --git a/packages/app/src/build/app-version.test.ts b/packages/app/src/build/app-version.test.ts
index 75a1a64b8..67a01862d 100644
--- a/packages/app/src/build/app-version.test.ts
+++ b/packages/app/src/build/app-version.test.ts
@@ -2,7 +2,8 @@ import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { CLIENT_RUNTIME_VERSION_FALLBACK } from '@inkeep/open-knowledge-core';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { loadConfigFromFile } from 'vite';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
APP_VERSION_ENV_VAR,
APP_VERSION_UNKNOWN,
@@ -48,3 +49,20 @@ describe('injectAppVersionEnv', () => {
expect(process.env[APP_VERSION_ENV_VAR]).toBe(appPkgVersion);
});
});
+
+describe('build-path version injection', () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ test('vite.config.ts injects the app package version while loading', async () => {
+ const configPath = resolve(here, '../..', 'vite.config.ts');
+ vi.stubEnv(APP_VERSION_ENV_VAR, undefined);
+ vi.stubEnv('LINGUI_CONFIG', undefined);
+ const result = await loadConfigFromFile(
+ { command: 'build', mode: 'production' },
+ configPath,
+ dirname(configPath),
+ );
+ expect(result).not.toBeNull();
+ expect(process.env[APP_VERSION_ENV_VAR]).toBe(appPkgVersion);
+ });
+});
diff --git a/packages/app/src/build/app-version.uncached.test.ts b/packages/app/src/build/app-version.uncached.test.ts
deleted file mode 100644
index 60264021b..000000000
--- a/packages/app/src/build/app-version.uncached.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { dirname, resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { describe, expect, test } from 'vitest';
-
-const here = dirname(fileURLToPath(import.meta.url));
-
-describe('build-path wiring (R-3)', () => {
- const repoConfigs = [
- resolve(here, '..', '..', 'vite.config.ts'),
- resolve(here, '..', '..', '..', 'desktop', 'electron.vite.config.ts'),
- ];
- for (const configPath of repoConfigs) {
- test(`${configPath.split('/packages/')[1]} calls injectAppVersionEnv()`, () => {
- const src = readFileSync(configPath, 'utf-8');
- expect(src).toContain('injectAppVersionEnv()');
- });
- }
-});
diff --git a/packages/app/src/build/electron-mode-class.dom.test.ts b/packages/app/src/build/electron-mode-class.dom.test.ts
new file mode 100644
index 000000000..4239f0bc6
--- /dev/null
+++ b/packages/app/src/build/electron-mode-class.dom.test.ts
@@ -0,0 +1,63 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+
+const html = readFileSync(resolve(import.meta.dirname, '../../index.html'), 'utf8');
+const originalMatchMedia = window.matchMedia;
+
+const PLATFORMS = ['darwin', 'win32', 'linux', undefined] as const;
+const THEME_STATES = [
+ { theme: 'dark', osDark: false, dark: true },
+ { theme: 'light', osDark: true, dark: false },
+ { theme: 'system', osDark: true, dark: true },
+ { theme: 'system', osDark: false, dark: false },
+] as const;
+const CASES = PLATFORMS.flatMap((platform) =>
+ THEME_STATES.map((state) => ({ ...state, platform, surface: platform ?? 'web' })),
+);
+
+function stubOsDarkPreference(osDark: boolean): void {
+ window.matchMedia = ((query: string) =>
+ ({
+ matches: osDark && query.includes('dark'),
+ media: query,
+ addEventListener() {},
+ removeEventListener() {},
+ addListener() {},
+ removeListener() {},
+ onchange: null,
+ dispatchEvent: () => false,
+ }) as unknown as MediaQueryList) as typeof window.matchMedia;
+}
+
+describe('desktop pre-paint classes', () => {
+ afterEach(() => {
+ Reflect.deleteProperty(window, 'okDesktop');
+ window.matchMedia = originalMatchMedia;
+ document.documentElement.className = '';
+ document.body.className = '';
+ localStorage.clear();
+ });
+
+ test.each(CASES)(
+ 'paints $surface under the $theme theme with a dark OS preference $osDark',
+ ({ platform, theme, osDark, dark }) => {
+ if (platform)
+ Object.defineProperty(window, 'okDesktop', { value: { platform }, configurable: true });
+ stubOsDarkPreference(osDark);
+ const page = new DOMParser().parseFromString(html, 'text/html');
+ const script = [...page.head.querySelectorAll('script:not([src]):not([type])')].find(
+ (element) => element.textContent?.includes('ok-color-theme-pair-v1'),
+ );
+ expect(script).toBeDefined();
+ localStorage.setItem('ok-theme-v1', theme);
+ new Function(script?.textContent ?? '')();
+ const expected = [
+ ...(dark ? ['dark'] : []),
+ ...(platform ? ['electron-mode', `electron-platform-${platform}`] : []),
+ ];
+ expect([...document.documentElement.classList].sort()).toEqual(expected.sort());
+ expect(document.body.classList.contains('electron-mode')).toBe(false);
+ },
+ );
+});
diff --git a/packages/app/src/build/electron-mode-class.test.ts b/packages/app/src/build/electron-mode-class.test.ts
index d235c8846..c5e4dc76d 100644
--- a/packages/app/src/build/electron-mode-class.test.ts
+++ b/packages/app/src/build/electron-mode-class.test.ts
@@ -4,32 +4,7 @@ import { describe, expect, test } from 'vitest';
const HTML = readFileSync(join(__dirname, '..', '..', 'index.html'), 'utf8');
-describe('index.html FOUC inline script — electron-mode class', () => {
- test('inline FOUC script adds the electron-mode class to documentElement when window.okDesktop is present', () => {
- expect(HTML).toMatch(
- /if\s*\(\s*window\.okDesktop\s*\)\s*\{\s*document\.documentElement\.classList\.add\(\s*['"]electron-mode['"]\s*\)/,
- );
- });
-
- test('inline FOUC script also stamps the per-platform class (win/linux chrome CSS keys off it)', () => {
- expect(HTML).toMatch(
- /classList\.add\(\s*`electron-platform-\$\{window\.okDesktop\.platform\}`\s*\)/,
- );
- });
-
- test('class addition lives in the same <script> block as the existing dark-mode FOUC', () => {
- const themeFoucScript = HTML.match(
- /<script>\(\(\) => \{[^<]*classList\.add\(['"]dark['"]\)[^<]*\}\)\(\);<\/script>/,
- );
- expect(themeFoucScript).not.toBeNull();
- expect(themeFoucScript?.[0]).toContain('electron-mode');
- });
-
- test('class is added on documentElement (html), not body — matches globals.css scope', () => {
- expect(HTML).toMatch(/document\.documentElement\.classList\.add\(['"]electron-mode['"]\)/);
- expect(HTML).not.toMatch(/document\.body\.classList\.add\(['"]electron-mode['"]\)/);
- });
-
+describe('index.html inline scripts', () => {
test('FOUC inline script body remains single-line (no inner newlines — biome HTML formatter constraint)', () => {
const inlineScripts = HTML.match(/<script>[^<]+<\/script>/g) ?? [];
for (const tag of inlineScripts) {
@@ -37,10 +12,4 @@ describe('index.html FOUC inline script — electron-mode class', () => {
expect(body).not.toMatch(/\n/);
}
});
-
- test('class name matches the CSS selector exactly (electron-mode, not electron / desktop / okDesktop)', () => {
- expect(HTML).toContain("'electron-mode'");
- expect(HTML).not.toMatch(/classList\.add\(\s*['"]electron['"]\s*\)/);
- expect(HTML).not.toMatch(/classList\.add\(\s*['"]okDesktop['"]\s*\)/);
- });
});
diff --git a/packages/app/src/lib/color-themes.test.ts b/packages/app/src/lib/color-themes.test.ts
index a888d4bfb..a72182784 100644
--- a/packages/app/src/lib/color-themes.test.ts
+++ b/packages/app/src/lib/color-themes.test.ts
@@ -1,12 +1,7 @@
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import {
- BASE16_SLOTS,
- ConfigSchema,
- resolveLeafSchema,
- THEME_ID_PATTERN,
-} from '@inkeep/open-knowledge-core';
+import { BASE16_SLOTS, ConfigSchema, resolveLeafSchema } from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
import {
base16ToTokens,
@@ -210,11 +205,6 @@ describe('registry stays in sync with its consumers', () => {
expect(ConfigSchema.safeParse({ appearance: { colorTheme: 'custom' } }).success).toBe(true);
});
- test('the pre-paint FOUC script validates ids with the config fields grammar', () => {
- const html = readFileSync(resolve(here, '../../index.html'), 'utf8');
- expect(html).toContain(THEME_ID_PATTERN.source);
- });
-
test('every base16 slot is settable under appearance.customTheme', () => {
for (const slot of BASE16_SLOTS) {
expect(
diff --git a/packages/app/src/lib/fouc-prepaint.dom.test.ts b/packages/app/src/lib/fouc-prepaint.dom.test.ts
index 1ecb15da7..d3afc96ed 100644
--- a/packages/app/src/lib/fouc-prepaint.dom.test.ts
+++ b/packages/app/src/lib/fouc-prepaint.dom.test.ts
@@ -1,6 +1,7 @@
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { ConfigSchema } from '@inkeep/open-knowledge-core';
import { beforeAll, beforeEach, describe, expect, test } from 'vitest';
import {
COLOR_THEMES,
@@ -242,3 +243,53 @@ describe('pre-paint FOUC script', () => {
expect(state()).toEqual({ attr: null, dark: false });
});
});
+
+const THEME_ID_CORPUS = [
+ 'a',
+ '0',
+ '-',
+ 'a0-z9',
+ 'a'.repeat(31),
+ 'a'.repeat(32),
+ '',
+ 'a'.repeat(33),
+ 'A',
+ 'has_underscore',
+ 'two words',
+ 'é',
+ 'a.b',
+ 'a/b',
+ 'a\n',
+ '\na',
+ 'a\r',
+ 'a\t',
+ 'a"',
+ "a'",
+ 'a]',
+ 'a[',
+];
+
+describe('pre-paint and ConfigSchema theme-id grammar', () => {
+ beforeEach(reset);
+
+ test.each(THEME_ID_CORPUS)('agrees on %j in both slots and the legacy cache', (id) => {
+ const admissions = ['colorTheme', 'colorThemeLight', 'colorThemeDark'].map(
+ (field) => ConfigSchema.safeParse({ appearance: { [field]: id } }).success,
+ );
+ expect(new Set(admissions).size).toBe(1);
+ const expected = admissions[0] ? id : null;
+ for (const mode of ['light', 'dark'] as const) {
+ reset();
+ seed({ light: 'catppuccin-latte', dark: 'dracula' }, mode, mode);
+ const cache = JSON.parse(localStorage.getItem(COLOR_THEME_PAIR_STORAGE_KEY) ?? '{}');
+ cache[mode].id = id;
+ localStorage.setItem(COLOR_THEME_PAIR_STORAGE_KEY, JSON.stringify(cache));
+ runPrePaint(mode === 'dark');
+ expect(document.documentElement.getAttribute('data-color-theme'), mode).toBe(expected);
+ }
+ reset();
+ localStorage.setItem(COLOR_THEME_STORAGE_KEY, id);
+ runPrePaint(false);
+ expect(document.documentElement.getAttribute('data-color-theme'), 'legacy').toBe(expected);
+ });
+});
diff --git a/packages/cli/src/tsdown-bundle-coverage.test.ts b/packages/cli/src/tsdown-bundle-coverage.test.ts
index 541ce3088..dcc53f059 100644
--- a/packages/cli/src/tsdown-bundle-coverage.test.ts
+++ b/packages/cli/src/tsdown-bundle-coverage.test.ts
@@ -1,55 +1,98 @@
import { readFileSync } from 'node:fs';
-import { dirname, resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
+import { resolve } from 'node:path';
+import type { UserConfig } from 'tsdown';
import { describe, expect, test } from 'vitest';
+import cliConfig from '../tsdown.config';
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const cliRoot = resolve(__dirname, '..');
-const cliPkgJsonPath = resolve(cliRoot, 'package.json');
-const tsdownConfigPath = resolve(cliRoot, 'tsdown.config.ts');
-
-const cliPkg = JSON.parse(readFileSync(cliPkgJsonPath, 'utf8')) as {
- dependencies?: Record<string, string>;
+const cliRoot = resolve(import.meta.dirname, '..');
+const cliPkg = JSON.parse(readFileSync(resolve(cliRoot, 'package.json'), 'utf8')) as {
+ dependencies: Record<string, string>;
};
-const declaredDeps = Object.keys(cliPkg.dependencies ?? {}).sort();
-
-const configSource = readFileSync(tsdownConfigPath, 'utf8');
-
-function extractBlock(name: 'alwaysBundlePureJsDeps' | 'nativeAddonNeverBundle'): string {
- const match = configSource.match(new RegExp(`const ${name}\\s*=\\s*\\[([\\s\\S]*?)\\n\\];`));
- return match?.[1] ?? '';
+const declaredDeps = Object.keys(cliPkg.dependencies).sort();
+const nativeDeps = ['@parcel/watcher', '@napi-rs/keyring', '@inkeep/open-knowledge-native-config'];
+const fileTypeClosure = [
+ '@borewit/text-codec',
+ '@tokenizer/inflate',
+ '@tokenizer/token',
+ 'file-type',
+ 'ieee754',
+ 'strtok3',
+ 'token-types',
+ 'uint8array-extras',
+];
+
+const serverInlinedClosure = ['sirv', 'just-bash', 'shell-quote', 'picomatch'];
+function matchesBundleRule(rules: unknown, id: string): boolean {
+ if (!Array.isArray(rules) || !rules.every((rule: unknown) => rule instanceof RegExp)) {
+ throw new TypeError(`alwaysBundle for ${id} must be an array of RegExp rules`);
+ }
+ return rules.some((rule) => new RegExp(rule).test(id));
}
-function stripLineComments(block: string): string {
- return block
- .split('\n')
- .filter((line) => !/^\s*\/\//.test(line))
- .join('\n');
+function buildFor(entry: string): UserConfig {
+ const matches = cliConfig.filter(
+ (config) =>
+ typeof config.entry === 'object' &&
+ config.entry !== null &&
+ Object.hasOwn(config.entry, entry),
+ );
+ expect(matches, `Expected exactly one tsdown build for ${entry}`).toHaveLength(1);
+ const config = matches[0];
+ if (!config) throw new Error(`Missing build for ${entry}`);
+ return config;
}
-const alwaysBundleBlock = stripLineComments(extractBlock('alwaysBundlePureJsDeps'));
-const neverBundleBlock = stripLineComments(extractBlock('nativeAddonNeverBundle'));
-const neverBundleNames = [...neverBundleBlock.matchAll(/'([^']+)'/g)].map((m) => m[1] as string);
+function bundleDiagnostic(dep: string, entry: string): string {
+ const context = fileTypeClosure.includes(dep)
+ ? "It is in the file-type closure used by the server's upload MIME sniff. "
+ : serverInlinedClosure.includes(dep)
+ ? 'It is inlined through server/core, not a cli package.json dependency. '
+ : '';
+ return (
+ `Add /^${dep}(\\/|$)/ to packages/cli/tsdown.config.ts alwaysBundle for ${entry}. ` +
+ context +
+ `A bare import '${dep}' fails with ERR_MODULE_NOT_FOUND from app.asar.unpacked/ in the packaged app.`
+ );
+}
describe('tsdown alwaysBundle covers every cli runtime dep', () => {
- test('cli package.json + tsdown.config.ts both load (premise check)', () => {
+ test('cli package.json and both build configs load', () => {
expect(declaredDeps.length).toBeGreaterThan(0);
- expect(alwaysBundleBlock.length).toBeGreaterThan(0);
+ expect(cliConfig).toHaveLength(2);
+ expect(buildFor('cli').entry).toHaveProperty('parse-worker');
+ expect(buildFor('index').entry).not.toHaveProperty('cli');
+ });
+
+ test.each([
+ ...new Set([
+ ...declaredDeps.filter((dep) => !nativeDeps.includes(dep)),
+ ...fileTypeClosure,
+ ...serverInlinedClosure,
+ ]),
+ ])('bundles %s in the standalone build and non-yjs library closure', (dep) => {
+ for (const entry of dep === 'yjs' ? ['cli'] : ['cli', 'index']) {
+ const config = buildFor(entry);
+ const diagnostic = bundleDiagnostic(dep, entry);
+ expect(matchesBundleRule(config.deps?.alwaysBundle, dep), diagnostic).toBe(true);
+ expect(matchesBundleRule(config.deps?.alwaysBundle, `${dep}/subpath`), diagnostic).toBe(true);
+ for (const unrelated of [`${dep}-unrelated`, `x-${dep}`]) {
+ expect(
+ matchesBundleRule(config.deps?.alwaysBundle, unrelated),
+ `Anchor the ${dep} alwaysBundle rule to the package root or a subpath. ${diagnostic}`,
+ ).toBe(false);
+ }
+ }
});
- for (const dep of declaredDeps.filter((name) => !neverBundleNames.includes(name))) {
- test(`alwaysBundle covers '${dep}'`, () => {
- const escaped = dep.replace(/[\\^$*+?.()|[\]{}-]/g, '\\$&').replace(/\//g, '\\\\?/');
- const pattern = new RegExp(`\\^${escaped}\\(`);
+ test.each(['cli', 'index'])('%s keeps native addons external', (entry) => {
+ const config = buildFor(entry);
+ expect(config.deps?.neverBundle).toEqual(expect.arrayContaining(nativeDeps));
+ for (const dep of nativeDeps)
expect(
- pattern.test(alwaysBundleBlock),
- `Add /^${dep}(\\/|$)/ to packages/cli/tsdown.config.ts \`alwaysBundle\`. ` +
- `Without it, the bundled CLI keeps a bare \`import '${dep}'\` that ` +
- `fails to resolve from app.asar.unpacked/ in the packaged DMG ` +
- `(ERR_MODULE_NOT_FOUND).`,
- ).toBe(true);
- });
- }
+ matchesBundleRule(config.deps?.alwaysBundle, dep),
+ `${entry} must not inline native addon ${dep}`,
+ ).toBe(false);
+ });
});
describe('yjs split-bundling policy', () => {
@@ -57,60 +100,23 @@ describe('yjs split-bundling policy', () => {
expect(declaredDeps).toContain('yjs');
});
- test('standalone build inlines yjs (alwaysBundle covers it)', () => {
- expect(/\^yjs\\?\(/.test(alwaysBundleBlock)).toBe(true);
+ test('the library externalizes yjs without force-inlining it', () => {
+ const config = buildFor('index');
+ expect(
+ config.deps?.neverBundle,
+ 'Add yjs to the library neverBundle list so consumers share one Yjs instance.',
+ ).toEqual(expect.arrayContaining(['yjs']));
+ expect(
+ matchesBundleRule(config.deps?.alwaysBundle, 'yjs'),
+ 'Remove yjs from the library alwaysBundle rules so consumers share one Yjs instance.',
+ ).toBe(false);
+ expect(
+ matchesBundleRule(config.deps?.alwaysBundle, 'yjs/subpath'),
+ 'Keep Yjs subpaths external in the library build to avoid a second Yjs instance.',
+ ).toBe(false);
+ expect(
+ buildFor('cli').deps?.neverBundle,
+ 'The standalone CLI needs yjs inlined because its packaged output has no adjacent node_modules.',
+ ).not.toEqual(expect.arrayContaining(['yjs']));
});
-
- test('library build externalizes yjs (its neverBundle lists it)', () => {
- expect(configSource).toMatch(/neverBundle:\s*\[\.\.\.nativeAddonNeverBundle,\s*'yjs'\]/);
- });
-
- test('library build does not force-inline yjs (alwaysBundle filtered)', () => {
- expect(configSource).toMatch(/alwaysBundlePureJsDeps\.filter\(\(re\) => !re\.test\('yjs'\)\)/);
- });
-});
-
-describe('tsdown alwaysBundle covers the file-type transitive closure', () => {
- const fileTypeClosure = [
- '@borewit/text-codec',
- '@tokenizer/inflate',
- '@tokenizer/token',
- 'file-type',
- 'ieee754',
- 'strtok3',
- 'token-types',
- 'uint8array-extras',
- ];
-
- for (const dep of fileTypeClosure) {
- test(`alwaysBundle covers transitive dep '${dep}'`, () => {
- const escaped = dep.replace(/[\\^$*+?.()|[\]{}-]/g, '\\$&').replace(/\//g, '\\\\?/');
- const pattern = new RegExp(`\\^${escaped}\\(`);
- expect(
- pattern.test(alwaysBundleBlock),
- `Add /^${dep}(\\/|$)/ to packages/cli/tsdown.config.ts \`alwaysBundle\`. ` +
- `It is a pure-JS transitive dep of file-type (the server's upload ` +
- `MIME-sniff); externalized, it leaves a bare \`import '${dep}'\` that ` +
- `crashes packaged-app uploads with ERR_MODULE_NOT_FOUND.`,
- ).toBe(true);
- });
- }
-});
-
-describe('tsdown alwaysBundle covers server/core-inlined transitive deps', () => {
- const serverInlinedClosure = ['sirv', 'just-bash', 'shell-quote', 'picomatch'];
-
- for (const dep of serverInlinedClosure) {
- test(`alwaysBundle covers transitive dep '${dep}'`, () => {
- const escaped = dep.replace(/[\\^$*+?.()|[\]{}-]/g, '\\$&').replace(/\//g, '\\\\?/');
- const pattern = new RegExp(`\\^${escaped}\\(`);
- expect(
- pattern.test(alwaysBundleBlock),
- `Add /^${dep}(\\/|$)/ to packages/cli/tsdown.config.ts \`alwaysBundle\`. ` +
- `It is a pure-JS transitive dep inlined via @inkeep/open-knowledge-server ` +
- `/ -core (NOT a cli package.json dep); externalized, it leaves a bare ` +
- `\`import '${dep}'\` that crashes the packaged app with ERR_MODULE_NOT_FOUND.`,
- ).toBe(true);
- });
- }
});
diff --git a/packages/desktop/tests/unit/desktop-variant-config.test.ts b/packages/desktop/tests/unit/desktop-variant-config.test.ts
index f35f1d682..f2ec58033 100644
--- a/packages/desktop/tests/unit/desktop-variant-config.test.ts
+++ b/packages/desktop/tests/unit/desktop-variant-config.test.ts
@@ -1,7 +1,18 @@
-import { readFileSync } from 'node:fs';
-import { dirname, resolve } from 'node:path';
+import { type ChildProcess, spawn } from 'node:child_process';
+import {
+ copyFileSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, test } from 'vitest';
+import { parse as parseYaml } from 'yaml';
import {
betaBuildVersion,
createLocalEntitlements,
@@ -12,9 +23,129 @@ import {
createVariantPostRemove,
parseBuilderConfig,
} from '../../scripts/desktop-variant-config.ts';
+import { DESKTOP_VARIANTS } from '../../src/shared/desktop-variant.ts';
+import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper';
const desktopRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
+const fixtures: string[] = [];
+const children = new Map<ChildProcess, Promise<void>>();
+
+afterEach(async () => {
+ for (const [child, closed] of children) {
+ if (child.pid !== undefined && child.exitCode === null && child.signalCode === null)
+ child.kill();
+ await closed;
+ }
+ children.clear();
+ for (const fixture of fixtures.splice(0)) removeTempDirBestEffort(fixture);
+});
+
+async function runBuilder(
+ args: string[],
+ status = 0,
+ signal = false,
+ platform: NodeJS.Platform = process.platform,
+ variant = 'stable',
+) {
+ const fixture = mkdtempSync(join(tmpdir(), 'ok-builder-wrapper-'));
+ fixtures.push(fixture);
+ for (const file of [
+ 'scripts/run-electron-builder.mjs',
+ 'scripts/desktop-variant-config.ts',
+ 'src/shared/desktop-variant.ts',
+ 'package.json',
+ 'electron-builder.yml',
+ 'build/installer.nsh',
+ 'build/deb-postinst.sh',
+ 'build/deb-postrm.sh',
+ 'build/entitlements.mac.plist',
+ 'build/helper-bundle/Info.plist',
+ ]) {
+ const target = join(fixture, file);
+ mkdirSync(dirname(target), { recursive: true });
+ copyFileSync(join(desktopRoot, file), target);
+ }
+ for (const dep of ['yaml', '@inkeep/open-knowledge-core']) {
+ const target = join(fixture, 'node_modules', dep);
+ mkdirSync(dirname(target), { recursive: true });
+ symlinkSync(realpathSync(join(desktopRoot, 'node_modules', dep)), target, 'junction');
+ }
+ const builderDir = join(fixture, 'node_modules/electron-builder');
+ mkdirSync(builderDir, { recursive: true });
+ writeFileSync(
+ join(builderDir, 'package.json'),
+ JSON.stringify({ name: 'electron-builder', type: 'module' }),
+ );
+ writeFileSync(
+ join(builderDir, 'cli.js'),
+ `
+ import { writeFileSync } from 'node:fs';
+ writeFileSync('invocation.json', JSON.stringify({
+ execPath: process.execPath,
+ args: process.argv.slice(2),
+ entry: process.argv[1],
+ cwd: process.cwd(),
+ marker: process.env.OK_BUILDER_TEST_MARKER,
+ }));
+ process.exit(Number(process.env.OK_BUILDER_TEST_STATUS));
+ `,
+ );
+ const preload = join(fixture, 'platform.mjs');
+ writeFileSync(
+ preload,
+ `
+ import childProcess from 'node:child_process';
+ import { writeFileSync } from 'node:fs';
+ import { syncBuiltinESMExports } from 'node:module';
+ Object.defineProperty(process, 'platform', { value: process.env.OK_BUILDER_TEST_PLATFORM });
+ const spawnSync = childProcess.spawnSync;
+ childProcess.spawnSync = (command, args, options) => {
+ writeFileSync('spawn.json', JSON.stringify({ command, args, shell: options?.shell ?? false, platform: process.platform }));
+ return process.env.OK_BUILDER_TEST_SIGNAL === '1'
+ ? { status: null, signal: 'SIGTERM' }
+ : spawnSync(command, args, options);
+ };
+ syncBuiltinESMExports();
+ `,
+ );
+ const child = spawn(
+ process.execPath,
+ ['--import', preload, join(fixture, 'scripts/run-electron-builder.mjs'), ...args],
+ {
+ cwd: fixture,
+ env: {
+ ...process.env,
+ PATH: '',
+ CSC_LINK: '',
+ CSC_KEYCHAIN: '',
+ OK_DESKTOP_VARIANT: variant,
+ OK_BUILDER_TEST_MARKER: 'forwarded',
+ OK_BUILDER_TEST_STATUS: String(status),
+ OK_BUILDER_TEST_SIGNAL: signal ? '1' : '0',
+ OK_BUILDER_TEST_PLATFORM: platform,
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ },
+ );
+ children.set(child, new Promise<void>((resolve) => child.once('close', () => resolve())));
+ let stderr = '';
+ child.stdout.resume();
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk: string) => {
+ stderr += chunk;
+ });
+ const result = await new Promise<{
+ status: number | null;
+ signal: NodeJS.Signals | null;
+ stderr: string;
+ }>((resolve, reject) => {
+ child.once('error', reject);
+ child.once('close', (status, signal) => resolve({ status, signal, stderr }));
+ });
+ return { fixture: realpathSync(fixture), result };
+}
+
const configSource = `
appId: com.inkeep.open-knowledge
productName: OpenKnowledge
@@ -276,19 +407,73 @@ describe('desktop variant builder config', () => {
/bundle identifier/,
);
});
+});
+
+const WRAPPER_CELLS = Object.keys(DESKTOP_VARIANTS).flatMap((variant) =>
+ ['--linux', '--win', '--mac'].flatMap((target) =>
+ (['darwin', 'win32', 'linux'] as const).map((platform) => ({ variant, target, platform })),
+ ),
+);
+
+describe('electron-builder wrapper execution', () => {
+ const baseRebuild = parseYaml(
+ readFileSync(join(desktopRoot, 'electron-builder.yml'), 'utf8'),
+ ).npmRebuild;
+
+ test.each(WRAPPER_CELLS)(
+ 'runs $variant $target on $platform through Node with the target rebuild policy',
+ async ({ variant, target, platform }) => {
+ const { fixture, result } = await runBuilder(
+ [target, '--publish', 'never'],
+ 0,
+ false,
+ platform,
+ variant,
+ );
+ expect(result.status, result.stderr).toBe(0);
+ const entry = join(fixture, 'node_modules/electron-builder/cli.js');
+ const args = [
+ target,
+ '--publish',
+ 'never',
+ '--config',
+ '.variant-build/electron-builder.yml',
+ ];
+ expect(JSON.parse(readFileSync(join(fixture, 'spawn.json'), 'utf8'))).toEqual({
+ command: process.execPath,
+ args: [entry, ...args],
+ shell: false,
+ platform,
+ });
+ expect(JSON.parse(readFileSync(join(fixture, 'invocation.json'), 'utf8'))).toEqual({
+ execPath: process.execPath,
+ entry,
+ args,
+ cwd: fixture,
+ marker: 'forwarded',
+ });
+ const generated = parseYaml(
+ readFileSync(join(fixture, '.variant-build/electron-builder.yml'), 'utf8'),
+ );
+ expect(generated.npmRebuild).toBe(target === '--linux' ? false : baseRebuild);
+ },
+ );
- test('invokes the builder JavaScript entrypoint without a Windows command shim', () => {
- const wrapper = readFileSync(resolve(desktopRoot, 'scripts/run-electron-builder.mjs'), 'utf8');
- expect(wrapper).toContain("require.resolve('electron-builder/cli.js')");
- expect(wrapper).toMatch(/spawnSync\(\s*process\.execPath/);
- expect(wrapper).not.toContain('pnpm.cmd');
- expect(wrapper).toMatch(/electron-builder terminated by \$\{result\.signal\}/);
+ test('forwards a failing builder exit status', async () => {
+ const { result } = await runBuilder(['--linux'], 7);
+ expect(result.status, result.stderr).toBe(7);
});
- test('keeps direct and generated Linux configs aligned on the rebuild policy', () => {
- const wrapper = readFileSync(resolve(desktopRoot, 'scripts/run-electron-builder.mjs'), 'utf8');
- const overlay = readFileSync(resolve(desktopRoot, 'electron-builder.linux.yml'), 'utf8');
- expect(wrapper).toContain("if (args.includes('--linux')) config.npmRebuild = false;");
- expect(overlay).toMatch(/^npmRebuild:\s*false$/m);
+ test('reports a signaled builder as failure', async () => {
+ const { result } = await runBuilder(['--linux'], 0, true);
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('electron-builder terminated by SIGTERM');
+ });
+
+ test('the direct Linux overlay disables native rebuilds as well', () => {
+ const overlay = parseYaml(
+ readFileSync(join(desktopRoot, 'electron-builder.linux.yml'), 'utf8'),
+ );
+ expect(overlay.npmRebuild).toBe(false);
});
});
diff --git a/packages/desktop/tests/unit/electron-vite-app-version.test.ts b/packages/desktop/tests/unit/electron-vite-app-version.test.ts
new file mode 100644
index 000000000..1c01b9fd4
--- /dev/null
+++ b/packages/desktop/tests/unit/electron-vite-app-version.test.ts
@@ -0,0 +1,30 @@
+import { readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { loadConfigFromFile } from 'vite';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { APP_VERSION_ENV_VAR } from '../../../app/src/build/app-version';
+
+const desktopRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
+const appPkgVersion = (
+ JSON.parse(readFileSync(resolve(desktopRoot, '../app/package.json'), 'utf-8')) as {
+ version: string;
+ }
+).version;
+
+describe('desktop build version injection', () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ test('electron.vite.config.ts injects the app package version while loading', async () => {
+ const configPath = resolve(desktopRoot, 'electron.vite.config.ts');
+ vi.stubEnv(APP_VERSION_ENV_VAR, undefined);
+ vi.stubEnv('LINGUI_CONFIG', undefined);
+ const result = await loadConfigFromFile(
+ { command: 'build', mode: 'production' },
+ configPath,
+ desktopRoot,
+ );
+ expect(result).not.toBeNull();
+ expect(process.env[APP_VERSION_ENV_VAR]).toBe(appPkgVersion);
+ });
+});
diff --git a/packages/desktop/tests/unit/playwright-packaged-config.test.ts b/packages/desktop/tests/unit/playwright-packaged-config.test.ts
index b2f826b55..7cdb55fcf 100644
--- a/packages/desktop/tests/unit/playwright-packaged-config.test.ts
+++ b/packages/desktop/tests/unit/playwright-packaged-config.test.ts
@@ -1,14 +1,48 @@
-import { readFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { describe, expect, it } from 'vitest';
+import { isAbsolute, relative, resolve, sep } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import packagedConfig, {
PACKAGED_JSON_REPORT_PATH,
PACKAGED_SMOKE_SUBSET,
} from '../../playwright.packaged.config';
-const DESKTOP_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
-const unpackagedSource = readFileSync(join(DESKTOP_ROOT, 'playwright.config.ts'), 'utf8');
+const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
+const DESKTOP_ROOT = resolve(import.meta.dirname, '../..');
+const UNPACKAGED_JSON_REPORT = resolve(DESKTOP_ROOT, 'test-results/desktop-smoke-results.json');
+const PACKAGED_REPORT = resolve(DESKTOP_ROOT, PACKAGED_JSON_REPORT_PATH);
+const CONFIG_STATES = (['darwin', 'win32', 'linux'] as const).flatMap((platform) =>
+ [false, true].map((ci) => ({ platform, ci })),
+);
+
+function outputTree(outputDir: string | undefined): string {
+ return resolve(DESKTOP_ROOT, outputDir ?? 'test-results');
+}
+
+function containsPath(outer: string, inner: string): boolean {
+ const path = relative(outer, inner);
+ return path === '' || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path));
+}
+
+function configStrings(value: unknown, seen = new WeakSet<object>()): string[] {
+ if (typeof value === 'string') return [value];
+ if (value === null || typeof value !== 'object' || seen.has(value)) return [];
+ seen.add(value);
+ return Object.values(value).flatMap((item) => configStrings(item, seen));
+}
+
+function jsonReportPaths(reporter: unknown): string[] {
+ if (!Array.isArray(reporter)) return [];
+ return reporter.flatMap((entry) =>
+ Array.isArray(entry) && entry[0] === 'json' && typeof entry[1]?.outputFile === 'string'
+ ? [resolve(DESKTOP_ROOT, entry[1].outputFile)]
+ : [],
+ );
+}
+
+afterEach(() => {
+ if (platformDescriptor) Object.defineProperty(process, 'platform', platformDescriptor);
+ vi.unstubAllEnvs();
+ vi.resetModules();
+});
describe('playwright.packaged.config', () => {
it('selects exactly the FR5a subset', () => {
@@ -32,12 +66,10 @@ describe('playwright.packaged.config', () => {
it('omits the stale-build guard, which cannot describe a packaged bundle', () => {
expect(packagedConfig.globalSetup).toBeUndefined();
- expect(unpackagedSource).toContain('stale-build-guard');
});
it('writes its JSON report to a path the unpackaged tier does not use', () => {
expect(PACKAGED_JSON_REPORT_PATH).not.toBe('test-results/desktop-smoke-results.json');
- expect(unpackagedSource).not.toContain(PACKAGED_JSON_REPORT_PATH);
const json = (packagedConfig.reporter as [string, Record<string, unknown>][]).find(
([name]) => name === 'json',
);
@@ -46,11 +78,42 @@ describe('playwright.packaged.config', () => {
it('writes its per-test artifacts to a tree the unpackaged tier does not share', () => {
expect(packagedConfig.outputDir).toBe('test-results-packaged');
- expect(unpackagedSource).not.toContain('test-results-packaged');
});
it('leaves the required desktop-smoke check untouched', () => {
- expect(unpackagedSource).not.toMatch(/^\s*projects:/m);
expect(packagedConfig.projects).toBeUndefined();
});
});
+
+describe('unpackaged Playwright config in every platform and CI state', () => {
+ it.each(CONFIG_STATES)(
+ 'keeps setup and output isolation on $platform with CI $ci',
+ async ({ platform, ci }) => {
+ Object.defineProperty(process, 'platform', { value: platform });
+ vi.stubEnv('CI', ci ? 'true' : '');
+ vi.resetModules();
+ const { default: unpackagedConfig } = await import('../../playwright.config');
+ const packagedTree = outputTree(packagedConfig.outputDir);
+ expect(resolve(DESKTOP_ROOT, String(unpackagedConfig.globalSetup))).toBe(
+ resolve(DESKTOP_ROOT, 'tests/smoke/_helpers/stale-build-guard.ts'),
+ );
+ expect(jsonReportPaths(unpackagedConfig.reporter)).toContain(UNPACKAGED_JSON_REPORT);
+ for (const value of configStrings(unpackagedConfig)) {
+ const path = resolve(DESKTOP_ROOT, value);
+ expect(path, `the unpackaged config value ${value} targets the packaged report`).not.toBe(
+ PACKAGED_REPORT,
+ );
+ expect(
+ containsPath(packagedTree, path),
+ `the unpackaged config value ${value} resolves into ${packagedTree}`,
+ ).toBe(false);
+ }
+ const unpackagedTree = outputTree(unpackagedConfig.outputDir);
+ expect(
+ containsPath(unpackagedTree, packagedTree) || containsPath(packagedTree, unpackagedTree),
+ `the unpackaged tree ${unpackagedTree} and the packaged tree ${packagedTree} must not nest`,
+ ).toBe(false);
+ expect(unpackagedConfig.projects).toBeUndefined();
+ },
+ );
+});
diff --git a/packages/server/src/parse-worker-bundle.uncached.test.ts b/packages/server/src/parse-worker-bundle.uncached.test.ts
index 816599982..c6d369652 100644
--- a/packages/server/src/parse-worker-bundle.uncached.test.ts
+++ b/packages/server/src/parse-worker-bundle.uncached.test.ts
@@ -2,18 +2,27 @@ import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'vitest';
+import cliConfig from '../../cli/tsdown.config';
+import serverConfig from '../tsdown.config';
const __dirname = dirname(fileURLToPath(import.meta.url));
describe('worker entry ships in every bundle shape', () => {
test('server tsdown config emits the parse-worker entry', () => {
- const config = readFileSync(resolve(__dirname, '../tsdown.config.ts'), 'utf8');
- expect(config).toMatch(/'parse-worker':\s*'src\/parse-worker\.ts'/);
+ expect(serverConfig.entry).toMatchObject({ 'parse-worker': 'src/parse-worker.ts' });
});
test('cli tsdown config emits the parse-worker entry next to dist/cli.mjs', () => {
- const config = readFileSync(resolve(__dirname, '../../cli/tsdown.config.ts'), 'utf8');
- expect(config).toMatch(/'parse-worker':\s*'src\/parse-worker\.ts'/);
+ const standalone = cliConfig.find(
+ (config) =>
+ typeof config.entry === 'object' &&
+ config.entry !== null &&
+ Object.hasOwn(config.entry, 'cli'),
+ );
+ expect(standalone?.entry).toMatchObject({
+ cli: 'src/cli.ts',
+ 'parse-worker': 'src/parse-worker.ts',
+ });
});
test('server package.json exports the parse-worker subpath for both conditions', () => {
diff --git a/packages/server/src/tsdown-bundle-coverage.test.ts b/packages/server/src/tsdown-bundle-coverage.test.ts
index a0f7efbd7..4508a76a6 100644
--- a/packages/server/src/tsdown-bundle-coverage.test.ts
+++ b/packages/server/src/tsdown-bundle-coverage.test.ts
@@ -1,47 +1,30 @@
-import { readFileSync } from 'node:fs';
-import { dirname, resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'vitest';
+import serverConfig from '../tsdown.config';
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const serverRoot = resolve(__dirname, '..');
-const tsdownConfigPath = resolve(serverRoot, 'tsdown.config.ts');
-
-const configSource = readFileSync(tsdownConfigPath, 'utf8');
-
-function extractBlock(name: 'alwaysBundle' | 'neverBundle'): string {
- const match = configSource.match(new RegExp(`${name}:\\s*\\[([\\s\\S]*?)\\]`));
- return match?.[1] ?? '';
-}
+const MUST_INLINE_DEPS = ['pino', 'pino-pretty'] as const;
-function stripLineComments(block: string): string {
- return block
- .split('\n')
- .map((line) => line.replace(/\/\/.*$/, ''))
- .join('\n');
+function matchesBundleRule(rules: unknown, id: string): boolean {
+ if (!Array.isArray(rules) || !rules.every((rule: unknown) => rule instanceof RegExp)) {
+ throw new TypeError(`alwaysBundle for ${id} must be an array of RegExp rules`);
+ }
+ return rules.some((rule) => new RegExp(rule).test(id));
}
-const alwaysBundleBlock = stripLineComments(extractBlock('alwaysBundle'));
-
-const MUST_INLINE_DEPS = ['pino', 'pino-pretty'] as const;
-
describe('tsdown alwaysBundle covers server logger deps', () => {
- test('tsdown.config.ts loads (premise check)', () => {
- expect(alwaysBundleBlock.length).toBeGreaterThan(0);
- });
-
- for (const dep of MUST_INLINE_DEPS) {
- test(`alwaysBundle covers '${dep}'`, () => {
- const escaped = dep.replace(/[\\^$*+?.()|[\]{}-]/g, '\\$&').replace(/\//g, '\\\\?/');
- const pattern = new RegExp(`\\^${escaped}\\(`);
+ test.each(MUST_INLINE_DEPS)('bundles %s and its subpaths', (dep) => {
+ const diagnostic =
+ `Add /^${dep}(\\/|$)/ to packages/server/tsdown.config.ts alwaysBundle. ` +
+ `A bare import '${dep}' fails with ERR_MODULE_NOT_FOUND from app.asar.unpacked/ ` +
+ 'in the packaged app if the server is relocated, the same bug class as #1389.';
+ expect(matchesBundleRule(serverConfig.deps?.alwaysBundle, dep), diagnostic).toBe(true);
+ expect(matchesBundleRule(serverConfig.deps?.alwaysBundle, `${dep}/subpath`), diagnostic).toBe(
+ true,
+ );
+ for (const unrelated of [`${dep}-unrelated`, `x-${dep}`]) {
expect(
- pattern.test(alwaysBundleBlock),
- `Add /^${dep}(\\/|$)/ to packages/server/tsdown.config.ts \`alwaysBundle\`. ` +
- `Without it, the bundled server keeps a bare \`import '${dep}'\` that ` +
- `would fail to resolve from app.asar.unpacked/ in the packaged DMG ` +
- `(ERR_MODULE_NOT_FOUND) if electron-builder ever relocates this ` +
- `package — same bug class as #1389.`,
- ).toBe(true);
- });
- }
+ matchesBundleRule(serverConfig.deps?.alwaysBundle, unrelated),
+ `Anchor the ${dep} alwaysBundle rule to the package root or a subpath. ${diagnostic}`,
+ ).toBe(false);
+ }
+ });
});