Skip to content

A local-first personal finance app

8.6 KB
Raw Blame
import { startBrowserBackend } from '@actual-app/core/platform/client/browser-preload';
import * as Platform from '@actual-app/core/shared/platform';
import { registerSW } from 'virtual:pwa-register';

// oxlint-disable-next-line typescript-paths/absolute-parent-import
import packageJson from '../package.json';

import SharedBrowserServerWorker from './shared-browser-server.ts?sharedworker';
import { computeClientVersion } from './util/versions';

const backendWorkerUrl = new URL('./browser-server.js', import.meta.url);

// This file installs global variables that the app expects.
// Normally these are already provided by electron, but in a real
// browser environment this is where we initialize the backend and
// everything else.

const IS_DEV = import.meta.env.DEV;
const ACTUAL_VERSION = computeClientVersion({
  isPlaywright: Platform.isPlaywright,
  reviewId: import.meta.env.REACT_APP_REVIEW_ID,
  commitRef: import.meta.env.REACT_APP_COMMIT_REF,
  packageVersion: packageJson.version,
});

// The OIDC callback (/openid-cb) is reached via a full-page navigation back
// from the OpenID provider. Routing it through the SharedWorker coordinator is
// unreliable: the returning tab can be left UNASSIGNED (no leader/backend), so
// the token write hangs and login silently fails (worst on iOS/iPad, where the
// pre-redirect tab never reports closing). It's a transient pre-login page with
// no budget open, so it doesn't need multi-tab coordination — give it a direct
// Worker so the token write resolves and login can complete. Once the user
// opens a budget the app navigates and the next page load rejoins the
// coordinator normally.
const isOpenIdCallback = window.location.pathname
  .replace(/\/+$/, '')
  .endsWith('/openid-cb');

// *** Start the backend ***
//
// The multi-tab coordinator (leader/follower over SharedWorker), the direct
// Worker fallback, and the absurd-sql worker bridge now all live in loot-core
// (packages/loot-core/src/platform/client/browser-preload). We only hand it
// the desktop-specific inputs: the worker asset URL, a SharedWorker factory,
// and the init payload.
const worker = startBrowserBackend({
  backendWorkerUrl,
  initPayload: {
    version: ACTUAL_VERSION,
    isDev: IS_DEV,
    publicUrl: import.meta.env.BASE_URL.slice(0, -1),
    hash: import.meta.env.REACT_APP_BACKEND_WORKER_HASH,
  },
  createSharedWorker: () =>
    new SharedBrowserServerWorker({ name: 'actual-backend' }),
  forceDirectWorker:
    Platform.isPlaywright ||
    Platform.isIOS ||
    Platform.isAndroid ||
    isOpenIdCallback,
});

// Ask the browser to exclude this origin's storage (the local budget database
// in IndexedDB) from automatic eviction under storage pressure. Without this,
// the browser is allowed to silently delete all local data, forcing a full
// re-download of the budget and losing any changes not yet synced.
if (navigator.storage?.persist) {
  void navigator.storage
    .persist()
    .then(persisted => {
      if (!persisted) {
        console.warn(
          'Persistent storage was not granted; the browser may evict local budget data under storage pressure.',
        );
      }
    })
    .catch(error => {
      console.warn('Persistent storage request failed:', error);
    });
}

let isUpdateReadyForDownload = false;
let markUpdateReadyForDownload;
const isUpdateReadyForDownloadPromise = new Promise(resolve => {
  markUpdateReadyForDownload = () => {
    isUpdateReadyForDownload = true;
    resolve(true);
  };
});
// Skip SW registration in dev so stale cached assets don't override edits
// between page loads, and in the native mobile apps, whose assets ship in the
// app bundle and update via the app stores. Plugin code that needs a SW can
// register one itself. Without a SW, applyAppUpdate() falls back to a plain
// reload so callers don't hang on its never-resolving promise.
const updateSW =
  IS_DEV || Platform.isNativeMobileApp
    ? () => window.location.reload()
    : registerSW({
        immediate: true,
        onNeedRefresh: markUpdateReadyForDownload,
      });

global.Actual = {
  IS_DEV,
  ACTUAL_VERSION,

  logToTerminal: (...args) => {
    console.log(...args);
  },

  relaunch: () => {
    window.location.reload();
  },

  reload: () => {
    if (window.navigator.serviceWorker == null) return;

    // Unregister the service worker handling routing and then reload. This should force the reload
    // to query the actual server rather than delegating to the worker
    return window.navigator.serviceWorker
      .getRegistration('/')
      .then(registration => {
        if (registration == null) return;
        return registration.unregister();
      })
      .then(() => {
        window.location.reload();
      });
  },

  startSyncServer: () => {
    // Only for electron app
  },

  stopSyncServer: () => {
    // Only for electron app
  },

  isSyncServerRunning: () => false,

  startOAuthServer: () => {
    return '';
  },

  restartElectronServer: () => {
    // Only for electron app
  },

  openFileDialog: async ({ filters = [] }) => {
    const FILE_ACCEPT_OVERRIDES = {
      // Safari on iOS requires explicit MIME/UTType values for some extensions to allow selection.
      qfx: [
        'application/vnd.intu.qfx',
        'application/x-qfx',
        'application/qfx',
        'application/ofx',
        'application/x-ofx',
        'application/octet-stream',
        'com.intuit.qfx',
      ],
    };

    return new Promise(resolve => {
      let createdElement = false;
      // Attempt to reuse an already-created file input.
      let input = document.body.querySelector(
        'input[id="open-file-dialog-input"]',
      );
      if (!input) {
        createdElement = true;
        input = document.createElement('input');
      }

      input.type = 'file';
      input.id = 'open-file-dialog-input';
      input.value = null;

      const filter = filters.find(filter => filter.extensions);
      if (filter) {
        input.accept = filter.extensions
          .flatMap(ext => {
            const normalizedExt = ext.startsWith('.')
              ? ext.toLowerCase()
              : `.${ext.toLowerCase()}`;
            const overrides = FILE_ACCEPT_OVERRIDES[ext.toLowerCase()] ?? [];
            return [normalizedExt, ...overrides];
          })
          .join(',');
      }

      input.style.position = 'absolute';
      input.style.top = '0px';
      input.style.left = '0px';
      input.style.display = 'none';

      input.onchange = e => {
        const file = e.target.files[0];
        const filename = file.name.replace(/.*(\.[^.]*)/, 'file$1');

        if (file) {
          const reader = new FileReader();
          reader.readAsArrayBuffer(file);
          reader.onload = async function (ev) {
            const filepath = `/uploads/${filename}`;

            void window.__actionsForMenu
              .uploadFile(filename, ev.target.result)
              .then(() => resolve([filepath]));
          };
          reader.onerror = function () {
            alert('Error reading file');
          };
        }
      };

      // In Safari the file input has to be in the DOM for change events to
      // reliably fire.
      if (createdElement) {
        document.body.appendChild(input);
      }

      input.click();
    });
  },

  saveFile: (contents, defaultFilename) => {
    const temp = document.createElement('a');
    temp.style = 'display: none';
    temp.download = defaultFilename;
    temp.rel = 'noopener';

    const blob = new Blob([contents]);
    temp.href = URL.createObjectURL(blob);
    temp.dispatchEvent(new MouseEvent('click'));
  },

  openURLInBrowser: url => {
    window.open(url, '_blank');
  },
  openInFileManager: () => {
    // File manager not available in browser
  },
  onEventFromMain: () => {
    // Only for electron app
  },
  isUpdateReadyForDownload: () => isUpdateReadyForDownload,
  waitForUpdateReadyForDownload: () => isUpdateReadyForDownloadPromise,
  applyAppUpdate: async () => {
    updateSW();

    // Wait for the service worker swap to reload the page. If the new worker
    // never takes control (e.g. the server is mid-update), force a reload so
    // the "Update now" button doesn't hang forever with no feedback.
    await new Promise(() => {
      setTimeout(() => window.location.reload(), 15000);
    });
  },

  ipcConnect: () => {
    // Only for electron app
  },
  getServerSocket: async () => {
    return worker;
  },

  setTheme: theme => {
    window.__actionsForMenu.saveGlobalPrefs({ prefs: { theme } });
  },

  moveBudgetDirectory: () => {
    // Only for electron app
  },

  setDocumentDir: async () => {
    throw new Error(
      'Changing the data folder is only available in the desktop app',
    );
  },
};