Skip to content

A local-first personal finance app

[AI] api: make the browser build work in consumer production bundles (#8289)

Matiss Janis Aboltins8ad218b7d980
diff --git a/.gitignore b/.gitignore
index 0931dff9cf..a5a699e6ed 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,6 +18,7 @@ node_modules
packages/api/app/bundle.api.js
packages/api/app/stats.json
packages/api/dist
+packages/api/e2e/consumer/dist
packages/api/@types
packages/api/test-results
packages/api/playwright-report
@@ -85,6 +86,9 @@ build/
# .d.ts files aren't type-checked with skipLibCheck set to true
*.d.ts
+# ...except hand-written ambient declarations that must be committed
+!packages/api/virtual-modules.d.ts
+!packages/loot-core/default-filesystem.d.ts
# Lage cache
.lage/
diff --git a/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch b/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch
new file mode 100644
index 0000000000..2a159bd5a9
--- /dev/null
+++ b/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch
@@ -0,0 +1,14 @@
+diff --git a/dist/index.js b/dist/index.js
+index d6e9f17f6dd411a3259651c361418f9f36456f6e..fe28345f90820b856fd708fd4788037e4057e4d0 100644
+--- a/dist/index.js
++++ b/dist/index.js
+@@ -194,6 +194,9 @@ const q = [
+ ...Object.keys(f).length > 0 && v ? { transform: { inject: f } } : {}
+ }
+ },
++ // PATCH: also inject node globals into Vite worker sub-builds, which
++ // read `worker.rollupOptions` rather than `build.rollupOptions`.
++ ...Object.keys(f).length > 0 && v ? { worker: { rollupOptions: { transform: { inject: f } } } } : {},
+ optimizeDeps: {
+ exclude: [
+ ...h
diff --git a/package.json b/package.json
index d885b3d86e..1fd0469bbe 100644
--- a/package.json
+++ b/package.json
@@ -113,6 +113,7 @@
"[email protected]": "3.1.5",
"serialize-javascript": "^7.0.5",
"socks": ">=2.8.3",
+ "vite-plugin-node-polyfills": "patch:vite-plugin-node-polyfills@npm%3A0.28.0#~/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch",
"webpackbar": "^7.0.0"
},
"browserslist": [
diff --git a/packages/api/browser-worker.ts b/packages/api/browser-worker.ts
index b47a7f5d12..5953811231 100644
--- a/packages/api/browser-worker.ts
+++ b/packages/api/browser-worker.ts
@@ -1,20 +1,72 @@
// Web Worker entry for the browser build; owns the real loot-core backend.
+//
+// Fully self-contained: the sql.js wasm and the default filesystem data
+// (migrations + default budget DB) are embedded at build time. The worker
+// performs NO `PUBLIC_URL` asset fetches, so a consumer needs to serve no extra
+// files and configure no bundler — just `import` the package and `init()`.
import * as connection from '@actual-app/core/platform/server/connection';
+import { setWasmBinary } from '@actual-app/core/platform/server/sqlite';
import { handlers, init } from '@actual-app/core/server/main';
import type { InitConfig } from '@actual-app/core/server/main';
+// Runtime assets, base64-embedded at build time so the worker is fully
+// self-contained (no PUBLIC_URL fetches). The bytes come from loot-core's
+// `default-filesystem` helper via the `actual-embedded-assets` Vite plugin, so
+// they can never drift from what the Node build ships.
+import {
+ dataFiles,
+ dataIndex,
+ wasmBase64,
+} from 'virtual:actual-embedded-assets';
+
+function base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {
+ const bin = atob(b64);
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i += 1) bytes[i] = bin.charCodeAt(i);
+ return bytes;
+}
+
+setWasmBinary(base64ToBytes(wasmBase64));
+
+// loot-core fetches the default filesystem from `PUBLIC_URL + 'data-file-index.txt'`
+// and `PUBLIC_URL + 'data/<file>'`. Point PUBLIC_URL at a sentinel origin and
+// answer those requests from the embedded bytes; everything else (server sync)
+// falls through to the real fetch.
+const EMBEDDED_BASE = 'https://actual-embedded.invalid/';
+process.env.PUBLIC_URL = EMBEDDED_BASE;
+
+const realFetch = self.fetch.bind(self);
+self.fetch = function patchedFetch(
+ input: RequestInfo | URL,
+ fetchInit?: RequestInit,
+): Promise<Response> {
+ const url =
+ typeof input === 'string'
+ ? input
+ : input instanceof URL
+ ? input.href
+ : input.url;
+ if (url.startsWith(EMBEDDED_BASE)) {
+ const rel = url.slice(EMBEDDED_BASE.length);
+ if (rel === 'data-file-index.txt') {
+ return Promise.resolve(new Response(dataIndex));
+ }
+ if (rel.startsWith('data/')) {
+ const b64 = dataFiles[rel.slice('data/'.length)];
+ if (b64 != null) {
+ return Promise.resolve(new Response(base64ToBytes(b64)));
+ }
+ }
+ return Promise.resolve(new Response(null, { status: 404 }));
+ }
+ return realFetch(input, fetchInit);
+} as typeof fetch;
// Worker-local handler, not part of the shared Handlers type.
(handlers as Record<string, (args?: unknown) => Promise<unknown>>)[
'api-browser/init'
] = async function (args?: unknown) {
- const { config, assetsBaseUrl } = (args ?? {}) as {
- config?: InitConfig;
- assetsBaseUrl?: string;
- };
- if (assetsBaseUrl) {
- process.env.PUBLIC_URL = assetsBaseUrl;
- }
+ const { config } = (args ?? {}) as { config?: InitConfig };
await init(config ?? {});
};
diff --git a/packages/api/e2e/consumer.test.ts b/packages/api/e2e/consumer.test.ts
new file mode 100644
index 0000000000..28101ad75a
--- /dev/null
+++ b/packages/api/e2e/consumer.test.ts
@@ -0,0 +1,14 @@
+import { expect, test } from '@playwright/test';
+
+// Loads the consumer fixture's production build (built in global-setup.ts,
+// served by serve-dist.mjs with COOP/COEP). On master this fails: the consumer
+// bundler re-bundles the prebuilt worker and `init` throws a structured-clone
+// error. With the self-contained build it passes with no consumer config.
+test('a consumer production build boots the worker and seeds a budget', async ({
+ page,
+}) => {
+ await page.goto('/e2e/consumer/dist/index.html');
+ const out = page.locator('#out');
+ await expect(out).toHaveAttribute('data-state', 'ok', { timeout: 60_000 });
+ await expect(out).toContainText('Checking');
+});
diff --git a/packages/api/e2e/consumer/index.html b/packages/api/e2e/consumer/index.html
new file mode 100644
index 0000000000..16c893cce8
--- /dev/null
+++ b/packages/api/e2e/consumer/index.html
@@ -0,0 +1,11 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>@actual-app/api consumer build e2e</title>
+ </head>
+ <body>
+ <pre id="out" data-state="pending">pending</pre>
+ <script type="module" src="/main.ts"></script>
+ </body>
+</html>
diff --git a/packages/api/e2e/consumer/main.ts b/packages/api/e2e/consumer/main.ts
new file mode 100644
index 0000000000..d5cb4e33c7
--- /dev/null
+++ b/packages/api/e2e/consumer/main.ts
@@ -0,0 +1,27 @@
+// A minimal third-party consumer of @actual-app/api. It does nothing special:
+// just `import` the package and `init()`. The only host requirement is COOP/COEP
+// headers, which serve-dist.mjs sets. This fixture is bundled for production by
+// global-setup.ts, exercising a consumer bundler processing dist/browser.js.
+import * as api from '@actual-app/api';
+
+const out = document.getElementById('out');
+if (out == null) {
+ throw new Error('Missing `#out` element in consumer fixture');
+}
+function report(state: 'ok' | 'error', detail: unknown) {
+ out.textContent = JSON.stringify(detail);
+ out.setAttribute('data-state', state);
+}
+
+async function run() {
+ await api.init({ dataDir: '/documents' });
+ await api.runImport('Consumer E2E', async () => {
+ await api.createAccount({ name: 'Checking', offbudget: false }, 12345);
+ });
+ const accounts = await api.getAccounts();
+ report('ok', { accounts: accounts.map(a => a.name) });
+}
+
+run().catch(err =>
+ report('error', err instanceof Error ? err.message : String(err)),
+);
diff --git a/packages/api/e2e/global-setup.mjs b/packages/api/e2e/global-setup.mjs
new file mode 100644
index 0000000000..12f75b09de
--- /dev/null
+++ b/packages/api/e2e/global-setup.mjs
@@ -0,0 +1,24 @@
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { build } from 'vite';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+
+// Build the consumer fixture (e2e/consumer) for production with Vite, exactly
+// as a third-party app would. serve-dist.mjs then serves the output (with the
+// COOP/COEP headers) at /e2e/consumer/dist/. This is the coverage the
+// verbatim-dist harness can't give: a consumer bundler processing browser.js.
+// Playwright's globalSetup contract requires a default export.
+// oxlint-disable-next-line import/no-default-export
+export default async function globalSetup() {
+ await build({
+ root: path.join(here, 'consumer'),
+ base: './',
+ logLevel: 'warn',
+ // The workspace package keeps a dev-only `development` export condition; a
+ // published consumer has none. Drop it so `browser` (dist/browser.js) wins.
+ resolve: { conditions: ['browser', 'module', 'default'] },
+ build: { outDir: path.join(here, 'consumer', 'dist'), emptyOutDir: true },
+ });
+}
diff --git a/packages/api/index.browser.ts b/packages/api/index.browser.ts
index 737385a862..feeb7c8a71 100644
--- a/packages/api/index.browser.ts
+++ b/packages/api/index.browser.ts
@@ -2,6 +2,8 @@ import { startBackendWorker } from '@actual-app/core/platform/client/backend-wor
import { send } from '@actual-app/core/platform/client/connection';
import type { InitConfig } from '@actual-app/core/server/main';
+import InlineWorker from './browser-worker?worker&inline';
+
export * from './methods';
export * as utils from './utils';
@@ -10,15 +12,10 @@ let worker: Worker | null = null;
export async function init(
config: InitConfig = {},
): Promise<{ send: typeof send }> {
- // Non-literal so bundlers don't pre-bundle ./worker.js, which only exists
- // next to the built file.
- const rel = './worker.js';
- worker = new Worker(new URL(rel, import.meta.url), { type: 'module' });
+ worker = new InlineWorker();
- // Not `new URL('.', import.meta.url)` — consumer asset analyzers rewrite it.
- const assetsBaseUrl = import.meta.url.replace(/[^/]+$/, '');
try {
- await startBackendWorker(worker, config, assetsBaseUrl);
+ await startBackendWorker(worker, config);
} catch (error) {
worker.terminate();
worker = null;
diff --git a/packages/api/package.json b/packages/api/package.json
index 6064f63c34..86849923e1 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -49,7 +49,7 @@
}
},
"scripts": {
- "build": "vite build && tsgo --emitDeclarationOnly && vite build --config vite.browser-worker.config.mts && vite build --config vite.browser.config.mts",
+ "build": "vite build && tsgo --emitDeclarationOnly && vite build --config vite.browser.config.mts",
"test": "vitest --run",
"e2e": "playwright test",
"typecheck": "tsgo -b && tsc-strict"
@@ -68,7 +68,7 @@
"rollup-plugin-visualizer": "^7.0.1",
"typescript-strict-plugin": "^2.4.4",
"vite": "^8.0.16",
- "vite-plugin-node-polyfills": "^0.28.0",
+ "vite-plugin-node-polyfills": "patch:vite-plugin-node-polyfills@npm%3A0.28.0#~/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch",
"vitest": "^4.1.8"
},
"engines": {
diff --git a/packages/api/playwright.config.ts b/packages/api/playwright.config.ts
index 246ad7361b..ccd85ec73a 100644
--- a/packages/api/playwright.config.ts
+++ b/packages/api/playwright.config.ts
@@ -1,9 +1,11 @@
import { defineConfig } from '@playwright/test';
export default defineConfig({
- timeout: 60_000,
+ timeout: 120_000,
retries: process.env.CI ? 1 : 0,
testDir: 'e2e/',
+ // Builds the consumer fixture (e2e/consumer) once before the tests run.
+ globalSetup: './e2e/global-setup.mjs',
reporter: [['list']],
use: {
browserName: 'chromium',
diff --git a/packages/api/virtual-modules.d.ts b/packages/api/virtual-modules.d.ts
new file mode 100644
index 0000000000..a4659df956
--- /dev/null
+++ b/packages/api/virtual-modules.d.ts
@@ -0,0 +1,18 @@
+// Ambient declarations for the browser build's Vite imports.
+
+// Vite's inlined-worker import (`?worker&inline`): a Blob-URL Worker ctor.
+declare module '*?worker&inline' {
+ const workerConstructor: new () => Worker;
+ export default workerConstructor;
+}
+
+// Runtime assets emitted by the `actual-embedded-assets` plugin
+// (vite.browser.config.mts), sourced from loot-core's `default-filesystem`.
+declare module 'virtual:actual-embedded-assets' {
+ /** base64 of sql.js' sql-wasm.wasm */
+ export const wasmBase64: string;
+ /** contents of data-file-index.txt */
+ export const dataIndex: string;
+ /** base64 of each default filesystem file, keyed by its data/ wire name */
+ export const dataFiles: Record<string, string>;
+}
diff --git a/packages/api/vite.browser-worker.config.mts b/packages/api/vite.browser-worker.config.mts
deleted file mode 100644
index 6025a828f4..0000000000
--- a/packages/api/vite.browser-worker.config.mts
+++ /dev/null
@@ -1,54 +0,0 @@
-import path from 'path';
-
-import { peggyLoader } from '@actual-app/vite-plugin-peggy';
-import { defineConfig } from 'vite';
-import { nodePolyfills } from 'vite-plugin-node-polyfills';
-
-const distDir = path.resolve(__dirname, 'dist');
-
-// Worker bundle: full loot-core + sql.js + absurd-sql.
-export default defineConfig({
- define: {
- // Other env vars (PUBLIC_URL etc.) are set at runtime via the process shim.
- 'process.env.NODE_ENV': JSON.stringify('production'),
- },
- build: {
- target: 'esnext',
- outDir: distDir,
- emptyOutDir: false,
- sourcemap: true,
- lib: {
- entry: path.resolve(__dirname, 'browser-worker.ts'),
- formats: ['es'],
- fileName: () => 'worker.js',
- },
- rollupOptions: {
- output: {
- codeSplitting: false,
- },
- },
- },
- plugins: [
- peggyLoader(),
- nodePolyfills({
- include: [
- 'process',
- 'buffer',
- 'stream',
- 'path',
- 'crypto',
- 'timers',
- 'util',
- 'zlib',
- 'fs',
- 'assert',
- ],
- globals: {
- process: true,
- Buffer: true,
- global: true,
- },
- }),
- ],
- // No resolve.conditions: ['api'] — loot-core uses its default (browser) files.
-});
diff --git a/packages/api/vite.browser.config.mts b/packages/api/vite.browser.config.mts
index 3c6f083abe..4a0522e04f 100644
--- a/packages/api/vite.browser.config.mts
+++ b/packages/api/vite.browser.config.mts
@@ -1,11 +1,71 @@
import path from 'path';
+import { collectEmbeddedAssets } from '@actual-app/core/default-filesystem';
+import { peggyLoader } from '@actual-app/vite-plugin-peggy';
import { defineConfig } from 'vite';
+import type { Plugin } from 'vite';
+import { nodePolyfills } from 'vite-plugin-node-polyfills';
const distDir = path.resolve(__dirname, 'dist');
-// Main-thread facade bundle — the backend never enters it.
+// Embed loot-core's default filesystem (wasm + default DB + migrations) into
+// the worker as a virtual module, so the browser build performs no PUBLIC_URL
+// asset fetches and consumers serve no extra files. loot-core owns the bytes
+// and the wire format; this just inlines them.
+function embeddedAssets(): Plugin {
+ const id = 'virtual:actual-embedded-assets';
+ const resolved = '\0' + id;
+ return {
+ name: 'actual-embedded-assets',
+ resolveId(source) {
+ return source === id ? resolved : undefined;
+ },
+ load(thisId) {
+ if (thisId !== resolved) return undefined;
+ const { wasmBase64, dataFiles, index } = collectEmbeddedAssets();
+ return [
+ `export const wasmBase64 = ${JSON.stringify(wasmBase64)};`,
+ `export const dataIndex = ${JSON.stringify(index)};`,
+ `export const dataFiles = ${JSON.stringify(dataFiles)};`,
+ ].join('\n');
+ },
+ };
+}
+
+// Main-thread facade bundle. The worker (browser-worker.ts) is imported with
+// `?worker&inline`, so Vite builds it as an IIFE sub-bundle and inlines it as a
+// Blob URL inside browser.js — consumer bundlers never see a worker entry to
+// re-bundle. `nodePolyfills` sits at the top level so its node-stdlib aliases
+// and (via our patch) its global-shim injection reach the worker sub-build.
export default defineConfig({
+ define: {
+ 'process.env.NODE_ENV': JSON.stringify('production'),
+ },
+ plugins: [
+ nodePolyfills({
+ include: [
+ 'process',
+ 'buffer',
+ 'stream',
+ 'path',
+ 'crypto',
+ 'timers',
+ 'util',
+ 'zlib',
+ 'fs',
+ 'assert',
+ ],
+ globals: {
+ process: true,
+ Buffer: true,
+ global: true,
+ },
+ }),
+ ],
+ worker: {
+ format: 'iife',
+ plugins: () => [embeddedAssets(), peggyLoader()],
+ },
build: {
target: 'esnext',
outDir: distDir,
diff --git a/packages/api/vite.config.mts b/packages/api/vite.config.mts
index 9c0c3c884f..b25877c0e8 100644
--- a/packages/api/vite.config.mts
+++ b/packages/api/vite.config.mts
@@ -1,12 +1,15 @@
import fs from 'fs';
import path from 'path';
+import {
+ defaultDbPath,
+ migrationsDir,
+} from '@actual-app/core/default-filesystem';
import { peggyLoader } from '@actual-app/vite-plugin-peggy';
import { visualizer } from 'rollup-plugin-visualizer';
import { defineConfig } from 'vite';
import { configDefaults } from 'vitest/config';
-const lootCoreRoot = path.resolve(__dirname, '../loot-core');
const distDir = path.resolve(__dirname, 'dist');
const typesDir = path.resolve(__dirname, '@types');
@@ -20,63 +23,18 @@ function cleanOutputDirs() {
};
}
-function copyMigrationsAndDefaultDb() {
+// The Node build reads migrations + the default DB from disk at runtime (see
+// fs.migrationsPath / bundledDatabasePath in loot-core), so copy them next to
+// the bundle. The browser build embeds its own copies, so nothing else needs to
+// be on disk.
+function copyNodeRuntimeAssets() {
return {
- name: 'copy-migrations-and-default-db',
+ name: 'copy-node-runtime-assets',
closeBundle() {
- const migrationsSrc = path.join(lootCoreRoot, 'migrations');
- const defaultDbPath = path.join(lootCoreRoot, 'default-db.sqlite');
-
- if (!fs.existsSync(migrationsSrc)) {
- throw new Error(`migrations directory not found at ${migrationsSrc}`);
- }
- const migrationsStat = fs.statSync(migrationsSrc);
- if (!migrationsStat.isDirectory()) {
- throw new Error(`migrations path is not a directory: ${migrationsSrc}`);
- }
-
- const migrationsDest = path.join(distDir, 'migrations');
- fs.mkdirSync(migrationsDest, { recursive: true });
- for (const name of fs.readdirSync(migrationsSrc)) {
- if (name.endsWith('.sql') || name.endsWith('.js')) {
- fs.copyFileSync(
- path.join(migrationsSrc, name),
- path.join(migrationsDest, name),
- );
- }
- }
-
- if (!fs.existsSync(defaultDbPath)) {
- throw new Error(`default-db.sqlite not found at ${defaultDbPath}`);
- }
+ fs.cpSync(migrationsDir, path.join(distDir, 'migrations'), {
+ recursive: true,
+ });
fs.copyFileSync(defaultDbPath, path.join(distDir, 'default-db.sqlite'));
-
- // Ship sql.js' WASM next to the bundle so consumers serve it same-origin.
- const sqlJsWasm = require.resolve('@jlongster/sql.js/dist/sql-wasm.wasm');
- fs.copyFileSync(sqlJsWasm, path.join(distDir, 'sql-wasm.wasm'));
-
- // Runtime data files for the browser worker. JS migrations get a `.data`
- // suffix so consumer bundlers don't import-analyze them.
- const dataDir = path.join(distDir, 'data');
- const dataMigrationsDir = path.join(dataDir, 'migrations');
- fs.mkdirSync(dataMigrationsDir, { recursive: true });
-
- fs.copyFileSync(defaultDbPath, path.join(dataDir, 'default-db.sqlite'));
- const migrationNames: string[] = [];
- for (const name of fs.readdirSync(migrationsDest)) {
- const wireName = name.endsWith('.js') ? `${name}.data` : name;
- fs.copyFileSync(
- path.join(migrationsDest, name),
- path.join(dataMigrationsDir, wireName),
- );
- migrationNames.push(`migrations/${wireName}`);
- }
- migrationNames.sort();
-
- fs.writeFileSync(
- path.join(distDir, 'data-file-index.txt'),
- ['default-db.sqlite', ...migrationNames].join('\n') + '\n',
- );
},
};
}
@@ -105,7 +63,7 @@ export default defineConfig({
plugins: [
cleanOutputDirs(),
peggyLoader(),
- copyMigrationsAndDefaultDb(),
+ copyNodeRuntimeAssets(),
visualizer({ template: 'raw-data', filename: 'app/stats.json' }),
],
resolve: {
diff --git a/packages/desktop-client/vite.config.mts b/packages/desktop-client/vite.config.mts
index 7148d40e72..974564e62f 100644
--- a/packages/desktop-client/vite.config.mts
+++ b/packages/desktop-client/vite.config.mts
@@ -5,6 +5,11 @@ import { cp, mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
import * as path from 'path';
import { fileURLToPath } from 'url';
+import {
+ defaultDbPath,
+ migrationsDir,
+ sqlWasmPath,
+} from '@actual-app/core/default-filesystem';
import babel from '@rolldown/plugin-babel';
import inject from '@rollup/plugin-inject';
import basicSsl from '@vitejs/plugin-basic-ssl';
@@ -78,10 +83,6 @@ const injectShims = (): Plugin[] => {
const lootCoreRoot = path.resolve(__dirname, '../loot-core');
const lootCoreOutDir = path.resolve(lootCoreRoot, 'lib-dist/browser');
const lootCoreConfig = path.resolve(lootCoreRoot, 'vite.config.mts');
-const sqlWasmSrc = path.resolve(
- __dirname,
- '../../node_modules/@jlongster/sql.js/dist/sql-wasm.wasm',
-);
const publicDir = path.resolve(__dirname, 'public');
const publicDataDir = path.resolve(publicDir, 'data');
const publicKcabDir = path.resolve(publicDir, 'kcab');
@@ -124,14 +125,9 @@ async function stagePublicData(): Promise<void> {
await mkdir(publicDataDir, { recursive: true });
await rm(migrationsDest, { recursive: true, force: true });
await Promise.all([
- cp(path.resolve(lootCoreRoot, 'migrations'), migrationsDest, {
- recursive: true,
- }),
- cp(
- path.resolve(lootCoreRoot, 'default-db.sqlite'),
- path.resolve(publicDataDir, 'default-db.sqlite'),
- ),
- cp(sqlWasmSrc, path.resolve(publicDir, 'sql-wasm.wasm')),
+ cp(migrationsDir, migrationsDest, { recursive: true }),
+ cp(defaultDbPath, path.resolve(publicDataDir, 'default-db.sqlite')),
+ cp(sqlWasmPath, path.resolve(publicDir, 'sql-wasm.wasm')),
]);
const entries = await readdir(publicDataDir, {
diff --git a/packages/docs/docs/api/index.md b/packages/docs/docs/api/index.md
index d1ff598ece..cbaa577452 100644
--- a/packages/docs/docs/api/index.md
+++ b/packages/docs/docs/api/index.md
@@ -108,6 +108,12 @@ await api.shutdown();
Behind the scenes, `init` starts a Web Worker running the same budget engine the Actual web app uses, backed by SQLite compiled to WebAssembly. Your budget data is stored in the browser's IndexedDB and stays on the device.
+The browser build is fully self-contained: the Web Worker and its WebAssembly and data files are inlined into the package. There are no extra files to copy or serve, and no bundler configuration is required (no `optimizeDeps` tweaks, no worker or asset plugins). Importing the package and calling `init()` is all that's needed.
+
+:::caution Cross-origin isolation is required
+The engine uses `SharedArrayBuffer`, so the page that runs the API must be served **cross-origin isolated**: over HTTPS, with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`. This is a hosting/server requirement (it cannot be bundled away). See [Enabling SharedArrayBuffer Access](../troubleshooting/shared-array-buffer.md). In local development, set the same headers on your dev server (for example via a small Vite middleware plugin).
+:::
+
## Writing Data Importers
If you are using another app, like YNAB or Mint, you might want to migrate your data into Actual. Right now, Actual officially supports [importing YNAB4 data](../migration/ynab4.md) and [importing nYNAB data](../migration/nynab.md) (and it works very well). But if you want to import all of your data into Actual, you can write a custom importer.
diff --git a/packages/loot-core/default-filesystem.d.ts b/packages/loot-core/default-filesystem.d.ts
new file mode 100644
index 0000000000..d5af5ff714
--- /dev/null
+++ b/packages/loot-core/default-filesystem.d.ts
@@ -0,0 +1,18 @@
+// Type declarations for ./default-filesystem.mjs (a Node-only build helper).
+
+/** Absolute path to loot-core's bundled migrations directory. */
+export const migrationsDir: string;
+/** Absolute path to loot-core's default budget database. */
+export const defaultDbPath: string;
+/** Absolute path to the sql.js wasm binary loot-core depends on. */
+export const sqlWasmPath: string;
+
+/** The `data-file-index.txt` manifest listing every file under `data/`. */
+export function buildDataFileIndex(names?: string[]): string;
+
+/** The base64-encoded assets a self-contained browser worker embeds. */
+export function collectEmbeddedAssets(): {
+ wasmBase64: string;
+ dataFiles: Record<string, string>;
+ index: string;
+};
diff --git a/packages/loot-core/default-filesystem.mjs b/packages/loot-core/default-filesystem.mjs
new file mode 100644
index 0000000000..747b8d140a
--- /dev/null
+++ b/packages/loot-core/default-filesystem.mjs
@@ -0,0 +1,59 @@
+// Build-time source of truth for the "default filesystem" that loot-core's
+// populateDefaultFilesystem() restores at startup: the sql.js wasm, the default
+// budget DB, and the migration files, plus the `data-file-index.txt` wire
+// format. loot-core owns these files and the protocol, so consumers should read
+// them from here rather than reaching into loot-core's tree themselves.
+//
+// Consumers:
+// - @actual-app/api embeds them into its self-contained browser worker, and
+// copies the migrations + default DB next to its Node build.
+// - @actual-app/web serves them as static files from `public/`.
+
+import fs from 'node:fs';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+const require = createRequire(import.meta.url);
+
+export const migrationsDir = path.join(root, 'migrations');
+export const defaultDbPath = path.join(root, 'default-db.sqlite');
+export const sqlWasmPath =
+ require.resolve('@jlongster/sql.js/dist/sql-wasm.wasm');
+
+function migrationFileNames() {
+ return fs
+ .readdirSync(migrationsDir)
+ .filter(name => name.endsWith('.sql') || name.endsWith('.js'));
+}
+
+/**
+ * The newline-delimited manifest fetched from
+ * `PUBLIC_URL + 'data-file-index.txt'`, listing every file under `data/`.
+ */
+export function buildDataFileIndex(names = migrationFileNames()) {
+ const migrations = names.map(name => `migrations/${name}`).sort();
+ return ['default-db.sqlite', ...migrations].join('\n') + '\n';
+}
+
+/**
+ * Everything the browser worker inlines, base64-encoded for embedding as a
+ * string. `dataFiles` is keyed by the `data/<key>` name fetched at runtime.
+ */
+export function collectEmbeddedAssets() {
+ const names = migrationFileNames();
+ const dataFiles = {
+ 'default-db.sqlite': fs.readFileSync(defaultDbPath).toString('base64'),
+ };
+ for (const name of names) {
+ dataFiles[`migrations/${name}`] = fs
+ .readFileSync(path.join(migrationsDir, name))
+ .toString('base64');
+ }
+ return {
+ wasmBase64: fs.readFileSync(sqlWasmPath).toString('base64'),
+ dataFiles,
+ index: buildDataFileIndex(names),
+ };
+}
diff --git a/packages/loot-core/package.json b/packages/loot-core/package.json
index 3614da0698..6597a5a5c3 100644
--- a/packages/loot-core/package.json
+++ b/packages/loot-core/package.json
@@ -14,6 +14,8 @@
"migrations",
"typings",
"default-db.sqlite",
+ "default-filesystem.mjs",
+ "default-filesystem.d.ts",
"!src/**/*.test.ts",
"!src/**/__tests__/**",
"!src/**/__snapshots__/**",
@@ -171,7 +173,11 @@
"./types/models": "./src/types/models/index.ts",
"./types/*": "./src/types/*.ts",
"./typings/*": "./typings/*.ts",
- "./lib-dist/electron/bundle.desktop.js": "./lib-dist/electron/bundle.desktop.js"
+ "./lib-dist/electron/bundle.desktop.js": "./lib-dist/electron/bundle.desktop.js",
+ "./default-filesystem": {
+ "types": "./default-filesystem.d.ts",
+ "default": "./default-filesystem.mjs"
+ }
},
"scripts": {
"build:node": "cross-env NODE_ENV=production vite build --config ./vite.desktop.config.mts",
@@ -228,7 +234,7 @@
"typescript-strict-plugin": "^2.4.4",
"util": "^0.12.5",
"vite": "^8.0.16",
- "vite-plugin-node-polyfills": "^0.28.0",
+ "vite-plugin-node-polyfills": "patch:vite-plugin-node-polyfills@npm%3A0.28.0#~/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch",
"vitest": "^4.1.8",
"yargs": "^18.0.0"
}
diff --git a/packages/loot-core/src/platform/client/backend-worker.ts b/packages/loot-core/src/platform/client/backend-worker.ts
index 47bd40b32d..d76c298e18 100644
--- a/packages/loot-core/src/platform/client/backend-worker.ts
+++ b/packages/loot-core/src/platform/client/backend-worker.ts
@@ -8,13 +8,12 @@ import type { InitConfig } from '#server/main';
export async function startBackendWorker(
worker: Worker,
config: InitConfig,
- assetsBaseUrl: string,
): Promise<void> {
initBackend(worker);
await connection.init(worker);
// Worker-local handler, not part of the shared Handlers union.
await (connection.send as (name: string, args?: unknown) => Promise<unknown>)(
'api-browser/init',
- { config, assetsBaseUrl },
+ { config },
);
}
diff --git a/packages/loot-core/src/platform/server/sqlite/index.electron.ts b/packages/loot-core/src/platform/server/sqlite/index.electron.ts
index 0cd8f0de36..bec7169b69 100644
--- a/packages/loot-core/src/platform/server/sqlite/index.electron.ts
+++ b/packages/loot-core/src/platform/server/sqlite/index.electron.ts
@@ -21,6 +21,13 @@ export async function init() {
// No need to initialise on electron
}
+// Parity with the browser sqlite backend (which instantiates sql.js from an
+// embedded wasm binary). better-sqlite3 has no wasm, so this is a no-op; it
+// exists so callers can reference `setWasmBinary` regardless of platform.
+export function setWasmBinary(_binary: ArrayBuffer | Uint8Array) {
+ // no-op on native sqlite
+}
+
export function prepare(db, sql) {
return db.prepare(sql);
}
diff --git a/packages/loot-core/src/platform/server/sqlite/index.ts b/packages/loot-core/src/platform/server/sqlite/index.ts
index 575daaa4de..64d2a4d154 100644
--- a/packages/loot-core/src/platform/server/sqlite/index.ts
+++ b/packages/loot-core/src/platform/server/sqlite/index.ts
@@ -31,14 +31,26 @@ export type SqlJsModule = SqlJsStatic & {
let SQL: SqlJsModule | null = null;
+// Opt-in: when set, the wasm is instantiated from these bytes instead of being
+// fetched via `locateFile`. The browser build of `@actual-app/api` uses this to
+// ship a fully self-contained worker (no `sql-wasm.wasm` request). Dormant for
+// every other consumer (web app and Node build never call `setWasmBinary`).
+let wasmBinaryOverride: ArrayBuffer | Uint8Array | undefined;
+
+export function setWasmBinary(binary: ArrayBuffer | Uint8Array) {
+ wasmBinaryOverride = binary;
+}
+
export async function init({
baseURL = process.env.PUBLIC_URL,
-}: { baseURL?: string } = {}) {
+ wasmBinary = wasmBinaryOverride,
+}: { baseURL?: string; wasmBinary?: ArrayBuffer | Uint8Array } = {}) {
// `initSqlJS` doesn't actually return a real promise, so make sure
// we're returning a real one for correct semantics
return new Promise((resolve, reject) => {
initSqlJS({
locateFile: file => baseURL + file,
+ ...(wasmBinary ? { wasmBinary: wasmBinary as ArrayBuffer } : {}),
}).then(
sql => {
SQL = sql as SqlJsModule;
diff --git a/upcoming-release-notes/api-browser-self-contained.md b/upcoming-release-notes/api-browser-self-contained.md
new file mode 100644
index 0000000000..416c221f16
--- /dev/null
+++ b/upcoming-release-notes/api-browser-self-contained.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [MatissJanis]
+---
+
+api: the browser version of the API now works out of the box in any web app, with no extra setup.
diff --git a/yarn.lock b/yarn.lock
index 806174a081..a44625854f 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -27,7 +27,7 @@ __metadata:
typescript-strict-plugin: "npm:^2.4.4"
uuid: "npm:^14.0.1"
vite: "npm:^8.0.16"
- vite-plugin-node-polyfills: "npm:^0.28.0"
+ vite-plugin-node-polyfills: "patch:vite-plugin-node-polyfills@npm%3A0.28.0#~/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch"
vitest: "npm:^4.1.8"
languageName: unknown
linkType: soft
@@ -140,7 +140,7 @@ __metadata:
util: "npm:^0.12.5"
uuid: "npm:^14.0.1"
vite: "npm:^8.0.16"
- vite-plugin-node-polyfills: "npm:^0.28.0"
+ vite-plugin-node-polyfills: "patch:vite-plugin-node-polyfills@npm%3A0.28.0#~/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch"
vitest: "npm:^4.1.8"
xml2js: "npm:^0.6.2"
yargs: "npm:^18.0.0"
@@ -27185,7 +27185,7 @@ __metadata:
languageName: node
linkType: hard
-"vite-plugin-node-polyfills@npm:^0.28.0":
+"vite-plugin-node-polyfills@npm:0.28.0":
version: 0.28.0
resolution: "vite-plugin-node-polyfills@npm:0.28.0"
dependencies:
@@ -27197,6 +27197,18 @@ __metadata:
languageName: node
linkType: hard
+"vite-plugin-node-polyfills@patch:vite-plugin-node-polyfills@npm%3A0.28.0#~/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch":
+ version: 0.28.0
+ resolution: "vite-plugin-node-polyfills@patch:vite-plugin-node-polyfills@npm%3A0.28.0#~/.yarn/patches/vite-plugin-node-polyfills-npm-0.28.0-bac39616ee.patch::version=0.28.0&hash=9ecd80"
+ dependencies:
+ "@rollup/plugin-inject": "npm:^5.0.5"
+ node-stdlib-browser: "npm:^1.3.1"
+ peerDependencies:
+ vite: ^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
+ checksum: 10/0a903d9626f4c961aa156324aa048416ca385e0ba657ddf250f34caac03351d65c768777b779b72c542ab6262d310efbe60252812287155bc407b43f427f98ac
+ languageName: node
+ linkType: hard
+
"vite-plugin-pwa@npm:^1.3.0":
version: 1.3.0
resolution: "vite-plugin-pwa@npm:1.3.0"