Open source personal finance application
docs: refresh reference and deployment docs, add performance guide (en+ru)
Ilya Komichevb5ec685dd2df
diff --git a/docs/content/en/2.development/05.deployment.md b/docs/content/en/2.development/05.deployment.mdindex b0d3cc21..8cb60d9a 100644--- a/docs/content/en/2.development/05.deployment.md+++ b/docs/content/en/2.development/05.deployment.md@@ -72,13 +72,35 @@ This way the app won't redeploy when only docs change, and vice versa.## Backend: Supabase + PowerSync-The Nuxt SPA is statically hosted on Vercel. The backend services are separate:+The Nuxt SPA is statically hosted (Vercel above, but any static host serving `.output/public` after `pnpm generate` works). The backend services are separate:- **Supabase** - hosted Supabase project (cloud or self-hosted) provides Postgres, Auth, and the PostgREST/supabase-js write path.-- **PowerSync** - a PowerSync service (self-hosted via Docker or a hosted option) handles offline-first sync by replicating from the Supabase Postgres via logical replication.+- **PowerSync** - a PowerSync service (cloud or self-hosted) handles offline-first sync by replicating from the Supabase Postgres via logical replication.Set the three `VITE_*` env vars in Vercel to point at your production Supabase project and PowerSync instance. See [Installation](/en/development/installation#env-variables) for the variable descriptions.+### Supabase (production project)++1. Create a Supabase project, link the repo and push the schema:++ ```bash [Terminal]+ cd app+ supabase link --project-ref <project-ref>+ supabase db push # applies supabase/migrations/ (tables, RLS, signup trigger)+ ```++2. Run `supabase/powersync_setup.sql` against the project database (SQL editor or `psql` over the **direct** connection string). It creates the `powersync_role` (REPLICATION + BYPASSRLS) and the `powersync` publication that the PowerSync service replicates from.+3. RLS policies and the `user_settings` signup trigger come with the migrations - nothing to configure manually.++### PowerSync (production service)++Two options; both replicate from the Supabase Postgres and validate Supabase JWTs via JWKS:++- **PowerSync Cloud** (managed): create an instance, point its source database at the Supabase **direct** connection string (not the pooler - logical replication needs a direct connection), enable Supabase auth, and paste the sync rules from `app/powersync/config/sync-config.yaml`.+- **Self-hosted**: `app/powersync/` (docker-compose + `config/service.yaml`) is the template, but it is **local-dev only** - its credentials are committed for a localhost stack. For production: move the replication URI, the bucket-storage Postgres URI, and the API token into secrets; point `client_auth.jwks_uri` at `https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json` and remove `allow_local_jwks`; give the service its own Postgres for bucket storage (it auto-migrates its schema); terminate TLS in front of port 8080.++`VITE_POWERSYNC_URL` is the public URL of that service.+## Google Sign-In (Production)In production the Google provider is configured in the **hosted Supabase dashboard**, not in `config.toml` (that file only drives the local stack).diff --git a/docs/content/en/2.development/09.troubleshooting.md b/docs/content/en/2.development/09.troubleshooting.mdindex d95c5674..7edc7b6a 100644--- a/docs/content/en/2.development/09.troubleshooting.md+++ b/docs/content/en/2.development/09.troubleshooting.md@@ -61,10 +61,10 @@ See `app/services/powersync/mutations.ts` for the full implementation.PowerSync requires an `id` primary key on every synced table. For `user_settings`, the `id` column holds the user's Supabase uid. This is how the table satisfies the requirement while having exactly one row per user.-## Auth cookie race condition+## Synchronous auth gate-The route guard in `app/app/middleware/auth.global.ts` is synchronous - it reads the `finapp.localAuthUid` cookie with no network call, so it works offline. This means the cookie **must be set before navigation happens after sign-in**.+The route guard in `app/app/middleware/auth.global.ts` is synchronous - it reads the persisted Supabase session from localStorage (`hasPersistedSession()`, `app/app/composables/useAuthSession.ts`) with no network call, so it works offline. There is no auth cookie.-The PowerSync plugin (`app/app/plugins/powersync.client.ts`) watches the reactive `uid` from `useSupabaseAuth()`. When `uid` resolves (Supabase session ready), it calls `setAuthCookie(userId)` and then `connectPowerSync(...)`. Navigation to the dashboard only happens after the session has resolved and the cookie is set.+supabase-js persists the session to localStorage itself as part of sign-in, so by the time login code navigates, the gate already passes. The PowerSync plugin separately watches the reactive `uid` from `useSupabaseAuth()` and connects/disconnects PowerSync as the session resolves - navigation does not wait for it.-If you move login flow logic around, make sure the cookie is always set from the resolved session before triggering any router navigation - otherwise the guard will redirect back to `/login`.+If you move login flow logic around, navigate only after the sign-in promise resolves (session persisted) - otherwise the guard will redirect back to `/login`.diff --git a/docs/content/en/3.reference/01.architecture.md b/docs/content/en/3.reference/01.architecture.mdindex 2c9294c7..b73e37ee 100644--- a/docs/content/en/3.reference/01.architecture.md+++ b/docs/content/en/3.reference/01.architecture.md@@ -17,25 +17,37 @@ app starts│ │ └── Read theme from localStorage → update appConfig│ └── powersync.client.ts│ ├── navigator.storage.persist() - protect IndexedDB from eviction-│ ├── setUploadErrorHandler → showErrorToast('sync.errors.uploadRejected')+│ ├── persisted session? → eager getPowerSyncDb().init() (overlaps app boot)+│ ├── setUploadErrorHandler → auto-reconcile fatal upload rejections│ └── watch uid (immediate)-│ ├── uid present → setAuthCookie(uid) + connectPowerSync(...)-│ └── uid absent → clearAuthCookie() + disconnectPowerSync()+│ ├── uid present → connectPowerSync(...)+│ └── auth resolved, no uid → disconnectPowerSync()├── app.vue│ ├── useHead() - theme CSS vars (tagPriority: -2)│ ├── useGuard() - auth redirect logic│ └── render layout + page-└── useInitApp (on authenticated page)- └── stores hydrate automatically via watchTable subscriptions- ├── useCurrenciesStore - watchTable('SELECT * FROM rates', ...)- ├── useUserStore - watchTable('SELECT * FROM user_settings', ...)- ├── useWalletsStore - watchTable('SELECT * FROM wallets', ...)- ├── useCategoriesStore - watchTable('SELECT * FROM categories', ...)- └── useTrnsStore - watchTable('SELECT * FROM trns', ...)+└── useInitApp().initApp() (default layout, via useAsyncData)+ ├── primeStoresFromCache() - per-user localforage snapshot → instant first paint+ ├── startWatches() - 5 watchTable subscriptions hydrate the stores+ │ ├── useCurrenciesStore - watchTable('SELECT * FROM rates', ...)+ │ ├── useUserStore - watchTable('SELECT * FROM user_settings', ...)+ │ ├── useWalletsStore - watchTable('SELECT * FROM wallets', ...)+ │ ├── useCategoriesStore - watchTable('SELECT * FROM categories', ...)+ │ └── useTrnsStore - watchTable('SELECT * FROM trns', ...)+ └── awaitInitialSync() - first server sync settles in the background (online only)```Each `watchTable` fires immediately with current local SQLite rows and again on every change (local write or incoming sync). There is no separate init + subscribe step.+### Cache-First Cold Start++The boot is cache-first - there is no splash screen:++- **Blob cache** (`app/app/composables/useStoreCache.ts`): one per-user localforage blob (`finapp.cache.<uid>`) holding the last session's store snapshot. It is read once at boot and primes all five stores before PowerSync's `db.init` + first SQLite scans finish. Writes are debounced (400 ms) read-modify-writes of touched slices. SQLite stays the source of truth; the blob is only a read cache.+- **Reconcile to truth**: the watches overwrite primed data with SQLite rows. An empty *first* emission keeps the primed cache (the first sync just hasn't landed yet on a fresh device); any later empty emission is a genuine wipe and applies.+- **Boot state** (`useInitApp.ts`): a single `bootState` computed - `'ready' | 'onboarding' | 'error'`. The dashboard shows a space-reserving skeleton (`StatPageSkeleton`) while stores hydrate; onboarding only renders once the first sync genuinely completed and the account is empty; the error screen (with retry) only when the sync failed and there is no local data to fall back to.+- **Instrumentation**: cold-start `performance.measure` marks - `cache:prime`, `ps:watch:<table>`, `trns:first-transform`. See [Performance](/en/reference/performance).+## Project Structure```@@ -58,10 +70,10 @@ Conventions worth knowing (not obvious from `tree`):All Pinia stores (`useTrnsStore`, `useWalletsStore`, `useCategoriesStore`, `useUserStore`, `useCurrenciesStore`) follow the same pattern:```-items: shallowRef<Map|null> # reactive state (shallow for performance)-watchTable subscription # fires on init + every local write or incoming sync-save({ id, values }) # optimistic write → upsertRow → rollback on error-delete(id) # optimistic write → deleteRow → rollback on error+items: shallowRef<Record<id, item> | null> # reactive state (shallow for performance)+watchTable subscription # fires on init + every local write or incoming sync+save({ id, values }) # optimistic write → upsertRow → rollback on error+delete(id) # optimistic write → deleteRow → rollback on error```### Data Flow (write)@@ -70,13 +82,13 @@ delete(id) # optimistic write → deleteRow → rollback on euser action→ save({ id, values })→ prev = snapshot of current items- → optimistic: items.value = new Map(...items, [id, values])+ → optimistic: items.value = { ...items, [id]: values }→ await upsertRow(table, id, row)→ success: watchTable fires → store refreshes from SQLite→ failure: items.value = prev + showErrorToast```-Write failure rollback handles local SQLite errors. Server-side rejection (RLS, constraint) is handled separately by the connector's upload-error handler (shows `sync.errors.uploadRejected` toast).+Write failure rollback handles local SQLite errors. Server-side rejection (RLS, constraint) is handled separately by the upload-error handler, which auto-reconciles: rejected INSERTs are reverted locally (`sync.errors.uploadReverted`), rejected UPDATE/DELETE offers a full re-sync (`sync.errors.uploadDiverged`). See [Offline-first](/en/reference/offline-first).### Data Flow (watchTable)@@ -84,7 +96,7 @@ Write failure rollback handles local SQLite errors. Server-side rejection (RLS,watchTable('SELECT * FROM trns', [], onRows, throttleMs)→ fires immediately with current local rows→ fires again on every table change (local write OR incoming PowerSync sync)- → onRows: rows → transform via rowToTrn() → items.value = new Map(...)+ → onRows: rows → transform via rowToTrn() → items.value = new object map````useTrnsStore` uses `reconcileTrns(prev, rows)` inside `onRows`: returns the same `prev` ref when nothing changed (suppresses the echo of the store's own optimistic write), and reuses unchanged row objects by `updatedAt` so `rowToTrn()` only runs for changed rows.@@ -152,7 +164,7 @@ Hard navigation instead of Vue Router - see [Technical Decisions](/en/reference/## PWA- Strategy: `generateSW` from `@vite-pwa/nuxt` (no custom service worker)-- Precaching: all build assets including `wasm` files; `maximumFileSizeToCacheInBytes: 3 MiB` so the wa-sqlite WASM files are precached for offline start+- Precaching: build assets plus exactly one WASM file - `wa-sqlite-async.<hash>.wasm`, the only variant the worker loads (the other emitted variants are cipher/sync builds the app never uses); `maximumFileSizeToCacheInBytes: 3 MiB` so it isn't dropped by the default 2 MiB cap- `navigateFallback: '/'` serves SPA shell for all navigation (offline support)- Runtime caching: Google Fonts, Iconify icons (CacheFirst)- Start URL: `/dashboard`@@ -182,7 +194,9 @@ The mobile transaction form uses a custom `BottomSheet` component with `useBotto| Theme logic | `app/app/plugins/theme.ts`, `app/app/app.vue` || PowerSync plugin | `app/app/plugins/powersync.client.ts` || Supabase client + auth | `app/app/composables/useSupabase.ts` |-| Auth cookie | `app/app/composables/useAuthCookie.ts` |+| Synchronous auth gate | `app/app/composables/useAuthSession.ts` |+| Boot state / init flow | `app/app/components/app/useInitApp.ts` |+| Cold-start blob cache | `app/app/composables/useStoreCache.ts` || Auth guard (middleware) | `app/app/middleware/auth.global.ts` || Guard logic (app.vue) | `app/app/components/user/useGuard.ts` || Store sync utils | `app/app/composables/useStoreSync.ts` |@@ -205,3 +219,4 @@ The mobile transaction form uses a custom `BottomSheet` component with `useBotto- [Sync](/en/reference/sync) - how PowerSync syncs data between server and local SQLite- [Offline-first](/en/reference/offline-first) - offline writes, upload queue, and error handling+- [Performance](/en/reference/performance) - cold-start budget, lazy chunks, and instrumentationdiff --git a/docs/content/en/3.reference/03.sync.md b/docs/content/en/3.reference/03.sync.mdindex 877f94f9..3a7bb6ba 100644--- a/docs/content/en/3.reference/03.sync.md+++ b/docs/content/en/3.reference/03.sync.md@@ -78,10 +78,13 @@ The connector runs as the authenticated Supabase user, so RLS policies apply on| Error class | Postgres codes | Behavior ||------------|----------------|----------|-| Fatal (data / constraint / RLS) | `22xxx`, `23xxx`, `42501` | Transaction **discarded** - queue unblocked; `setUploadErrorHandler` fires `sync.errors.uploadRejected` toast |+| Fatal (data / constraint / RLS) | `22xxx`, `23xxx`, `42501` | Transaction **discarded** - queue unblocked; the discarded ops are auto-reconciled (see below) || Retryable (network, timeout) | everything else | Error **rethrown** - PowerSync retries with backoff |-Discarding a fatal op means the local write and server have silently diverged for that row. The user sees a toast and can correct the data manually.+Discarded ops are classified by `planDivergence()` (`app/services/powersync/uploadReconcile.ts`) and reconciled automatically:++- **Rejected INSERTs** - the local rows are deleted (ids are client-generated, the server never accepted them), with a cascade to local trns referencing a reverted wallet/category. Toast: `sync.errors.uploadReverted`.+- **Rejected UPDATE/DELETE** - the server still holds a prior version that PowerSync can't re-pull per row, so the user is offered a full re-sync (wipe + re-pull). Toast: `sync.errors.uploadDiverged`.## Deletion Handling@@ -91,7 +94,7 @@ PowerSync syncs hard deletes natively - when a row is deleted on the server the## First Sync-`waitForFirstSync(timeoutMs=10000)` (`app/services/powersync/db.ts`) resolves once the initial server state has fully streamed into local SQLite (or times out). `useInitApp` waits for this before showing the main UI, ensuring the user never sees an empty app after login.+`waitForFirstSync(timeoutMs=30000)` (`app/services/powersync/db.ts`) resolves `true` once the initial server state has fully streamed into local SQLite, `false` on timeout. The boot does **not** block on it - cached/local data paints immediately and the first sync settles in the background (`awaitInitialSync` in `useInitApp.ts`). Its result only gates the onboarding/error screens, so a fresh login never flashes onboarding while data is still arriving.## Key Filesdiff --git a/docs/content/en/3.reference/04.offline-first.md b/docs/content/en/3.reference/04.offline-first.mdindex 5ecf11f1..0c6b6ef4 100644--- a/docs/content/en/3.reference/04.offline-first.md+++ b/docs/content/en/3.reference/04.offline-first.md@@ -41,9 +41,10 @@ No user action is needed to trigger sync after reconnect.### Fatal errors (discarded)-Postgres error classes `22xxx` (data exception), `23xxx` (integrity constraint violation), and `42501` (RLS - insufficient privilege) are treated as fatal. The failing op is **discarded** so it does not block the rest of the queue. The plugin surfaces the error via `showErrorToast('sync.errors.uploadRejected')`.+Postgres error classes `22xxx` (data exception), `23xxx` (integrity constraint violation), and `42501` (RLS - insufficient privilege) are treated as fatal. The failing op **and every op queued after it** are discarded so the queue is not blocked, then auto-reconciled by the plugin (`planDivergence`, `app/services/powersync/uploadReconcile.ts`):-A discarded op means the local SQLite and the server have silently diverged for that row. The user is notified via toast and can correct the data manually (e.g., re-edit and re-save the record).+- **Rejected INSERTs**: the local rows are deleted to converge (the server never accepted them). A reverted wallet/category cascades to local trns referencing it, so no orphans survive. Toast: `sync.errors.uploadReverted`.+- **Rejected UPDATE/DELETE**: the server still holds the prior version and PowerSync can't re-pull a single row, so the user is offered a destructive full re-sync (`forceResync`: wipe local SQLite + re-pull server truth). Toast: `sync.errors.uploadDiverged`.### Retryable errorsdiff --git a/docs/content/en/3.reference/08.performance.md b/docs/content/en/3.reference/08.performance.mdnew file mode 100644index 00000000..4dbf3a6c--- /dev/null+++ b/docs/content/en/3.reference/08.performance.md@@ -0,0 +1,58 @@+---+title: Performance+description: Cold-start budget, lazy chunks, icon bundling, and the built-in instrumentation marks.+navigation:+ icon: i-lucide-gauge+seo:+ title: Performance+ description: How Finapp keeps cold start fast - cache-first paint, lazy PowerSync/swiper/echarts chunks, icon bundling, narrowed SW precache, and performance marks.+---++What keeps the cold start fast, and how to measure it. Reference numbers below were taken on a prod build (`pnpm generate`) with a real account of ~8 000 transactions, desktop hardware, assets served from the service worker - treat them as relative, not absolute.++## Cold-Start Budget++The boot is dominated by JS execution, not network (everything is SW-cached). Two paths fill the stores:++| Path | Data on screen |+|------|----------------|+| Blob cache prime (`cache:prime`, ~70 ms read) | ~280 ms |+| First `trns` watch emission from SQLite | ~730 ms |++That ~450 ms gap is why the [blob cache](/en/reference/architecture#cache-first-cold-start) exists: its value is the early paint, not skipping the row transform (transforming 8k rows takes ~3 ms - the cost is the SQLite scan + worker transfer, not JS).++The five boot watches are **serialized** on the single PowerSync worker connection - their first emissions land stair-stepped (`user_settings` → `rates` → `categories` → `wallets` → `trns`), with the full-table `trns` scan dominating. Merging the four small queries would save little; windowing `trns` by date was rejected because wallet totals need full history (see [Technical Decisions](/en/reference/tech-decisions)).++## Bundle: What Loads When++- **`@powersync/web` is lazy.** `getPowerSyncDb()` (`app/services/powersync/db.ts`) dynamically imports the library, schema, and connector on first use, keeping ~230 KB out of the entry chunk - the login page and demo mode never parse it. Two details guard this: `uploadErrorHandler.ts` exists so the plugin's static import doesn't reach connector.ts, and `uploadReconcile.ts` compares op strings instead of importing the `UpdateType` enum.+- **swiper is lazy.** The transaction form (`LazyTrnFormBottom` / `LazyTrnFormSidebar` in the default layout) mounts after its first open; an idle prefetch keeps that first open instant.+- **echarts mounts on idle.** Charts are gated on `useIdleMount()` behind an equal-height placeholder (`stat/chart/Wrap.vue`), so the 450 KB echarts chunk never competes with the first paint.+- **Dashboard skeleton.** `StatPageSkeleton` reserves the page shape while stores hydrate, so arriving data doesn't shift the layout.+- **Icons are bundled.** All statically referenced icon names ship in the client bundle (`icon.clientBundle.icons` in `nuxt.config.ts`, including the `hugeicons` collection) - icons fetched from `api.iconify.design` at runtime pop in after first paint and shift layout (CLS). The icon scanner misses names inside dynamic ternaries, hence the explicit list. Only user-data icons (category/wallet icons outside the bundle) still fetch at runtime, cached by the SW (CacheFirst).+- **SW precache is narrowed.** Of the eight emitted wa-sqlite WASM variants, only `wa-sqlite-async.<hash>.wasm` (the one the worker actually loads - cipher builds need an `encryptionKey` we never pass) is precached, saving ~12 MB per service-worker install.++## Instrumentation++Cold-start marks are always on (they cost nothing). In the browser console after a reload:++```js+performance.getEntriesByType('measure')+ .filter(m => /^(ps:watch|cache:|trns:)/.test(m.name))+ .map(m => `${m.name}: ${Math.round(m.startTime)}ms +${Math.round(m.duration)}ms`)+```++| Mark | Meaning |+|------|---------|+| `cache:prime` | Blob cache read + store prime (cold-start paint path) |+| `ps:watch:<table>` | Subscribe → first SQLite emission per boot watch |+| `trns:first-transform` | Row → item transform cost of the first `trns` emission |++## Rejected Approaches++Documented so they aren't re-attempted without new data (details in [Technical Decisions](/en/reference/tech-decisions) and `todo.md`):++- **OPFS VFS** instead of `IDBBatchAtomicVFS` - cold start is bound by `db.init` + query serialization, not page I/O.+- **Date-windowed `trns` watch** - breaks wallet totals, which need full history.+- **Splitting vendor chunks via `manualChunks`** - fragmenting reka-ui breaks `inject`/`createContext` in production builds.+- **`Map`-based store items** - saves single-digit ms per write at 8k rows, but breaks every reader of the plain-object `items` shape.diff --git a/docs/content/ru/2.development/05.deployment.md b/docs/content/ru/2.development/05.deployment.mdindex df1a16c3..27e91ed9 100644--- a/docs/content/ru/2.development/05.deployment.md+++ b/docs/content/ru/2.development/05.deployment.md@@ -72,13 +72,35 @@ git diff --quiet HEAD^ HEAD -- docs## Бэкенд: Supabase + PowerSync-Nuxt SPA статически хостится на Vercel. Бэкенд-сервисы отдельные:+Nuxt SPA хостится статически (выше описан Vercel, но подойдёт любой статический хостинг, отдающий `.output/public` после `pnpm generate`). Бэкенд-сервисы отдельные:- **Supabase** - хостируемый проект Supabase (облачный или self-hosted) предоставляет Postgres, Auth и путь записи через PostgREST/supabase-js.-- **PowerSync** - сервис PowerSync (self-hosted через Docker или хостируемый вариант) обеспечивает offline-first синхронизацию, реплицируя данные из Supabase Postgres через логическую репликацию.+- **PowerSync** - сервис PowerSync (облачный или self-hosted) обеспечивает offline-first синхронизацию, реплицируя данные из Supabase Postgres через логическую репликацию.Установите три `VITE_*` переменные в Vercel, указывающие на продакшен-проект Supabase и экземпляр PowerSync. Описание переменных - в разделе [Установка](/ru/development/installation#переменные-окружения).+### Supabase (продакшен-проект)++1. Создайте проект Supabase, привяжите репозиторий и примените схему:++ ```bash [Terminal]+ cd app+ supabase link --project-ref <project-ref>+ supabase db push # applies supabase/migrations/ (tables, RLS, signup trigger)+ ```++2. Выполните `supabase/powersync_setup.sql` на базе проекта (SQL editor или `psql` по **прямой** строке подключения). Скрипт создаёт `powersync_role` (REPLICATION + BYPASSRLS) и публикацию `powersync`, из которой реплицирует сервис PowerSync.+3. RLS-политики и триггер `user_settings` при регистрации приходят вместе с миграциями - вручную ничего настраивать не нужно.++### PowerSync (продакшен-сервис)++Два варианта; оба реплицируют из Supabase Postgres и проверяют JWT Supabase через JWKS:++- **PowerSync Cloud** (управляемый): создайте инстанс, укажите в качестве исходной базы **прямую** строку подключения Supabase (не pooler - логической репликации нужно прямое подключение), включите Supabase auth и вставьте правила синхронизации из `app/powersync/config/sync-config.yaml`.+- **Self-hosted**: `app/powersync/` (docker-compose + `config/service.yaml`) - это шаблон, но он предназначен **только для локальной разработки** - его учётные данные закоммичены для localhost-стека. Для продакшена: вынесите URI репликации, Postgres URI bucket-хранилища и API-токен в секреты; укажите в `client_auth.jwks_uri` адрес `https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json` и уберите `allow_local_jwks`; выделите сервису собственный Postgres для bucket-хранилища (свою схему он мигрирует сам); терминируйте TLS перед портом 8080.++`VITE_POWERSYNC_URL` - публичный URL этого сервиса.+## Вход через Google (продакшен)В продакшене провайдер Google настраивается в **дашборде хостируемого Supabase**, а не в `config.toml` (этот файл управляет только локальным стеком).diff --git a/docs/content/ru/3.reference/01.architecture.md b/docs/content/ru/3.reference/01.architecture.mdindex 4740cec2..5e9d1353 100644--- a/docs/content/ru/3.reference/01.architecture.md+++ b/docs/content/ru/3.reference/01.architecture.md@@ -17,25 +17,37 @@ seo:│ │ └── Чтение темы из localStorage → обновление appConfig│ └── powersync.client.ts│ ├── navigator.storage.persist() - защита IndexedDB от вытеснения-│ ├── setUploadErrorHandler → showErrorToast('sync.errors.uploadRejected')+│ ├── сессия сохранена? → ранний getPowerSyncDb().init() (параллельно с загрузкой приложения)+│ ├── setUploadErrorHandler → авто-согласование фатальных отказов загрузки│ └── watch uid (immediate)-│ ├── uid есть → setAuthCookie(uid) + connectPowerSync(...)-│ └── uid нет → clearAuthCookie() + disconnectPowerSync()+│ ├── uid есть → connectPowerSync(...)+│ └── auth определён, uid нет → disconnectPowerSync()├── app.vue│ ├── useHead() - CSS-переменные темы (tagPriority: -2)│ ├── useGuard() - логика редиректа авторизации│ └── рендер layout + page-└── useInitApp (на авторизованной странице)- └── хранилища гидрируются автоматически через подписки watchTable- ├── useCurrenciesStore - watchTable('SELECT * FROM rates', ...)- ├── useUserStore - watchTable('SELECT * FROM user_settings', ...)- ├── useWalletsStore - watchTable('SELECT * FROM wallets', ...)- ├── useCategoriesStore - watchTable('SELECT * FROM categories', ...)- └── useTrnsStore - watchTable('SELECT * FROM trns', ...)+└── useInitApp().initApp() (дефолтный layout, через useAsyncData)+ ├── primeStoresFromCache() - снимок localforage пользователя → мгновенная первая отрисовка+ ├── startWatches() - 5 подписок watchTable гидрируют хранилища+ │ ├── useCurrenciesStore - watchTable('SELECT * FROM rates', ...)+ │ ├── useUserStore - watchTable('SELECT * FROM user_settings', ...)+ │ ├── useWalletsStore - watchTable('SELECT * FROM wallets', ...)+ │ ├── useCategoriesStore - watchTable('SELECT * FROM categories', ...)+ │ └── useTrnsStore - watchTable('SELECT * FROM trns', ...)+ └── awaitInitialSync() - первая серверная синхронизация завершается в фоне (только онлайн)```Каждый `watchTable` срабатывает немедленно с текущими локальными строками SQLite и повторно при каждом изменении (локальная запись или входящая синхронизация). Отдельного шага «инициализация + подписка» нет.+### Cache-first холодный старт++Загрузка идёт по принципу cache-first - сплеш-экрана нет:++- **Blob-кеш** (`app/app/composables/useStoreCache.ts`): один localforage-блоб на пользователя (`finapp.cache.<uid>`) со снимком хранилищ из последней сессии. Он читается один раз при загрузке и наполняет все пять хранилищ до завершения `db.init` PowerSync и первых сканов SQLite. Записи - дебаунс-обновления (400 мс) затронутых срезов по схеме read-modify-write. Источником истины остаётся SQLite; блоб - только кеш для чтения.+- **Согласование с истиной**: подписки перезаписывают данные из кеша строками SQLite. Пустая *первая* эмиссия сохраняет данные из кеша (на свежем устройстве первая синхронизация просто ещё не пришла); любая последующая пустая эмиссия - настоящая очистка и применяется.+- **Состояние загрузки** (`useInitApp.ts`): единый computed `bootState` - `'ready' | 'onboarding' | 'error'`. Дашборд показывает скелетон, резервирующий место (`StatPageSkeleton`), пока хранилища гидрируются; онбординг рендерится только когда первая синхронизация действительно завершилась и аккаунт пуст; экран ошибки (с повтором) - только когда синхронизация не удалась и локальных данных для отката нет.+- **Инструментирование**: метки `performance.measure` холодного старта - `cache:prime`, `ps:watch:<table>`, `trns:first-transform`. См. [Производительность](/ru/reference/performance).+## Структура проекта```@@ -58,10 +70,10 @@ i18n/locales/ # en-US.js, ru-RU.jsВсе Pinia-хранилища (`useTrnsStore`, `useWalletsStore`, `useCategoriesStore`, `useUserStore`, `useCurrenciesStore`) следуют одному паттерну:```-items: shallowRef<Map|null> # реактивное состояние (shallow для производительности)-подписка watchTable # срабатывает при инициализации + каждой записи или синхронизации-save({ id, values }) # оптимистичная запись → upsertRow → откат при ошибке-delete(id) # оптимистичная запись → deleteRow → откат при ошибке+items: shallowRef<Record<id, item> | null> # реактивное состояние (shallow для производительности)+подписка watchTable # срабатывает при инициализации + каждой записи или синхронизации+save({ id, values }) # оптимистичная запись → upsertRow → откат при ошибке+delete(id) # оптимистичная запись → deleteRow → откат при ошибке```### Поток данных (запись)@@ -70,13 +82,13 @@ delete(id) # оптимистичная запись → deleдействие пользователя→ save({ id, values })→ prev = снимок текущих items- → оптимистично: items.value = new Map(...items, [id, values])+ → оптимистично: items.value = { ...items, [id]: values }→ await upsertRow(table, id, row)→ успех: watchTable срабатывает → хранилище обновляется из SQLite→ ошибка: items.value = prev + showErrorToast```-Откат при ошибке записи обрабатывает ошибки локального SQLite. Отказ на стороне сервера (RLS, ограничение) обрабатывается отдельно обработчиком ошибок загрузки коннектора (показывает toast `sync.errors.uploadRejected`).+Откат при ошибке записи обрабатывает ошибки локального SQLite. Отказ на стороне сервера (RLS, ограничение) обрабатывается отдельно обработчиком ошибок загрузки, который выполняет авто-согласование: отклонённые INSERT откатываются локально (`sync.errors.uploadReverted`), при отклонённых UPDATE/DELETE предлагается полная повторная синхронизация (`sync.errors.uploadDiverged`). См. [Офлайн-first](/ru/reference/offline-first).### Поток данных (watchTable)@@ -84,7 +96,7 @@ delete(id) # оптимистичная запись → delewatchTable('SELECT * FROM trns', [], onRows, throttleMs)→ срабатывает немедленно с текущими локальными строками→ срабатывает снова при каждом изменении таблицы (локальная запись ИЛИ входящая синхронизация PowerSync)- → onRows: rows → трансформация через rowToTrn() → items.value = new Map(...)+ → onRows: rows → трансформация через rowToTrn() → items.value = новый объект-словарь````useTrnsStore` использует `reconcileTrns(prev, rows)` внутри `onRows`: возвращает тот же `prev`-ref, если ничего не изменилось (подавляет эхо от собственной оптимистичной записи хранилища), и переиспользует неизменённые объекты строк по `updatedAt`, так что `rowToTrn()` выполняется только для изменённых строк.@@ -152,7 +164,7 @@ signOut()## PWA- Стратегия: `generateSW` из `@vite-pwa/nuxt` (без кастомного service worker)-- Прекеширование: все ассеты сборки включая `wasm`-файлы; `maximumFileSizeToCacheInBytes: 3 МБ` - WASM-файлы wa-sqlite прекешируются для офлайн-запуска+- Прекеширование: ассеты сборки плюс ровно один WASM-файл - `wa-sqlite-async.<hash>.wasm`, единственный вариант, который загружает воркер (остальные эмитируемые варианты - cipher/sync-сборки, которые приложение не использует); `maximumFileSizeToCacheInBytes: 3 МБ`, чтобы он не отбрасывался дефолтным лимитом в 2 МБ- `navigateFallback: '/'` отдаёт SPA-оболочку для всех навигаций (офлайн-поддержка)- Runtime-кеширование: Google Fonts, иконки Iconify (CacheFirst)- Start URL: `/dashboard`@@ -182,7 +194,9 @@ signOut()| Логика темы | `app/app/plugins/theme.ts`, `app/app/app.vue` || Плагин PowerSync | `app/app/plugins/powersync.client.ts` || Supabase-клиент + авторизация | `app/app/composables/useSupabase.ts` |-| Cookie авторизации | `app/app/composables/useAuthCookie.ts` |+| Синхронный гейт авторизации | `app/app/composables/useAuthSession.ts` |+| Состояние загрузки / поток инициализации | `app/app/components/app/useInitApp.ts` |+| Blob-кеш холодного старта | `app/app/composables/useStoreCache.ts` || Защита авторизации (middleware) | `app/app/middleware/auth.global.ts` || Логика защиты (app.vue) | `app/app/components/user/useGuard.ts` || Утилиты синхронизации хранилищ | `app/app/composables/useStoreSync.ts` |@@ -205,3 +219,4 @@ signOut()- [Синхронизация](/ru/reference/sync) - как PowerSync синхронизирует данные между сервером и локальной SQLite- [Офлайн-first](/ru/reference/offline-first) - офлайн-записи, очередь загрузки и обработка ошибок+- [Производительность](/ru/reference/performance) - бюджет холодного старта, ленивые чанки и инструментированиеdiff --git a/docs/content/ru/3.reference/03.sync.md b/docs/content/ru/3.reference/03.sync.mdindex 1a44a2db..8b40123f 100644--- a/docs/content/ru/3.reference/03.sync.md+++ b/docs/content/ru/3.reference/03.sync.md@@ -78,10 +78,13 @@ SELECT * FROM rates| Класс ошибки | Коды Postgres | Поведение ||-------------|---------------|-----------|-| Фатальные (данные / ограничение / RLS) | `22xxx`, `23xxx`, `42501` | Транзакция **отбрасывается** - очередь разблокируется; `setUploadErrorHandler` показывает toast `sync.errors.uploadRejected` |+| Фатальные (данные / ограничение / RLS) | `22xxx`, `23xxx`, `42501` | Транзакция **отбрасывается** - очередь разблокируется; отброшенные операции авто-согласуются (см. ниже) || Повторяемые (сеть, таймаут) | всё остальное | Ошибка **пробрасывается** - PowerSync повторяет попытку с backoff |-Отбрасывание фатальной операции означает тихое расхождение локальной SQLite и сервера для этой строки. Пользователь получает уведомление через toast и может исправить данные вручную.+Отброшенные операции классифицируются `planDivergence()` (`app/services/powersync/uploadReconcile.ts`) и согласуются автоматически:++- **Отклонённые INSERT** - локальные строки удаляются (id генерируются на клиенте, сервер их так и не принял), с каскадом на локальные транзакции, ссылающиеся на отменённый кошелёк/категорию. Toast: `sync.errors.uploadReverted`.+- **Отклонённые UPDATE/DELETE** - на сервере осталась предыдущая версия, которую PowerSync не может повторно вытянуть для отдельной строки, поэтому пользователю предлагается полная повторная синхронизация (очистка + повторная загрузка). Toast: `sync.errors.uploadDiverged`.## Обработка удалений@@ -91,7 +94,7 @@ PowerSync синхронизирует жёсткие удаления нати## Первая синхронизация-`waitForFirstSync(timeoutMs=10000)` (`app/services/powersync/db.ts`) разрешается после полной передачи начального серверного состояния в локальную SQLite (или по таймауту). `useInitApp` ожидает этого перед показом основного UI, гарантируя, что пользователь не увидит пустое приложение после входа.+`waitForFirstSync(timeoutMs=30000)` (`app/services/powersync/db.ts`) разрешается в `true` после полной передачи начального серверного состояния в локальную SQLite и в `false` по таймауту. Загрузка **не** блокируется на нём - кешированные/локальные данные отрисовываются сразу, а первая синхронизация завершается в фоне (`awaitInitialSync` в `useInitApp.ts`). Его результат лишь определяет показ экранов онбординга/ошибки, поэтому при свежем входе онбординг никогда не мелькает, пока данные ещё приходят.## Ключевые файлыdiff --git a/docs/content/ru/3.reference/04.offline-first.md b/docs/content/ru/3.reference/04.offline-first.mdindex 30f28422..ce73719d 100644--- a/docs/content/ru/3.reference/04.offline-first.md+++ b/docs/content/ru/3.reference/04.offline-first.md@@ -41,9 +41,10 @@ seo:### Фатальные ошибки (отбрасываются)-Классы ошибок Postgres `22xxx` (исключение данных), `23xxx` (нарушение ограничения целостности) и `42501` (RLS - недостаточно прав) считаются фатальными. Неудавшаяся операция **отбрасывается**, чтобы не блокировать остальную очередь. Плагин выводит ошибку через `showErrorToast('sync.errors.uploadRejected')`.+Классы ошибок Postgres `22xxx` (исключение данных), `23xxx` (нарушение ограничения целостности) и `42501` (RLS - недостаточно прав) считаются фатальными. Неудавшаяся операция **и все операции в очереди после неё** отбрасываются, чтобы очередь не блокировалась, а затем автоматически согласуются плагином (`planDivergence`, `app/services/powersync/uploadReconcile.ts`):-Отброшенная операция означает тихое расхождение локальной SQLite и сервера для этой строки. Пользователь получает уведомление через toast и может исправить данные вручную (например, снова отредактировать и сохранить запись).+- **Отклонённые INSERT**: локальные строки удаляются для сходимости (сервер их так и не принял). Отмена кошелька/категории каскадно удаляет ссылающиеся на них локальные транзакции, поэтому осиротевших строк не остаётся. Toast: `sync.errors.uploadReverted`.+- **Отклонённые UPDATE/DELETE**: на сервере осталась предыдущая версия, а PowerSync не может повторно вытянуть отдельную строку, поэтому пользователю предлагается деструктивная полная повторная синхронизация (`forceResync`: очистка локальной SQLite + повторная загрузка серверной истины). Toast: `sync.errors.uploadDiverged`.### Повторяемые ошибкиdiff --git a/docs/content/ru/3.reference/08.performance.md b/docs/content/ru/3.reference/08.performance.mdnew file mode 100644index 00000000..2f1c153f--- /dev/null+++ b/docs/content/ru/3.reference/08.performance.md@@ -0,0 +1,58 @@+---+title: Производительность+description: Бюджет холодного старта, ленивые чанки, бандлинг иконок и встроенные метки инструментирования.+navigation:+ icon: i-lucide-gauge+seo:+ title: Производительность+ description: Как Финапка держит холодный старт быстрым - cache-first отрисовка, ленивые чанки PowerSync/swiper/echarts, бандлинг иконок, суженный прекеш SW и performance-метки.+---++Что держит холодный старт быстрым и как его измерять. Контрольные цифры ниже сняты на прод-сборке (`pnpm generate`) с реальным аккаунтом в ~8 000 транзакций, на десктопном железе, с ассетами из service worker - воспринимайте их как относительные, а не абсолютные.++## Бюджет холодного старта++В загрузке доминирует выполнение JS, а не сеть (всё закешировано в SW). Хранилища наполняются двумя путями:++| Путь | Данные на экране |+|------|------------------|+| Наполнение из blob-кеша (`cache:prime`, чтение ~70 мс) | ~280 мс |+| Первая эмиссия watch для `trns` из SQLite | ~730 мс |++Этот разрыв в ~450 мс - причина существования [blob-кеша](/ru/reference/architecture#cache-first-холодный-старт): его ценность в ранней отрисовке, а не в пропуске трансформации строк (трансформация 8k строк занимает ~3 мс - стоимость в скане SQLite + передаче из воркера, а не в JS).++Пять загрузочных подписок **сериализованы** на единственном worker-подключении PowerSync - их первые эмиссии приходят лесенкой (`user_settings` → `rates` → `categories` → `wallets` → `trns`), и доминирует скан всей таблицы `trns`. Слияние четырёх маленьких запросов дало бы мало; оконная выборка `trns` по дате отвергнута, потому что итогам кошельков нужна полная история (см. [Технические решения](/ru/reference/tech-decisions)).++## Бандл: что и когда загружается++- **`@powersync/web` ленивый.** `getPowerSyncDb()` (`app/services/powersync/db.ts`) динамически импортирует библиотеку, схему и коннектор при первом использовании, убирая ~230 КБ из входного чанка - страница логина и демо-режим его вообще не парсят. Это охраняют две детали: `uploadErrorHandler.ts` существует, чтобы статический импорт плагина не дотягивался до connector.ts, а `uploadReconcile.ts` сравнивает строки операций вместо импорта enum `UpdateType`.+- **swiper ленивый.** Форма транзакции (`LazyTrnFormBottom` / `LazyTrnFormSidebar` в дефолтном layout) монтируется после первого открытия; idle-префетч делает это первое открытие мгновенным.+- **echarts монтируется в idle.** Графики спрятаны за `useIdleMount()` с плейсхолдером равной высоты (`stat/chart/Wrap.vue`), поэтому чанк echarts в 450 КБ никогда не конкурирует с первой отрисовкой.+- **Скелетон дашборда.** `StatPageSkeleton` резервирует форму страницы, пока хранилища гидрируются, поэтому приходящие данные не сдвигают layout.+- **Иконки в бандле.** Все статически используемые имена иконок поставляются в клиентском бандле (`icon.clientBundle.icons` в `nuxt.config.ts`, включая коллекцию `hugeicons`) - иконки, загружаемые с `api.iconify.design` в рантайме, появляются после первой отрисовки и сдвигают layout (CLS). Сканер иконок не видит имена внутри динамических тернарников, отсюда явный список. Только иконки пользовательских данных (иконки категорий/кошельков вне бандла) по-прежнему загружаются в рантайме и кешируются SW (CacheFirst).+- **Прекеш SW сужен.** Из восьми эмитируемых WASM-вариантов wa-sqlite прекешируется только `wa-sqlite-async.<hash>.wasm` (тот, который воркер действительно загружает - cipher-сборкам нужен `encryptionKey`, который мы никогда не передаём), что экономит ~12 МБ на каждую установку service worker.++## Инструментирование++Метки холодного старта включены всегда (они ничего не стоят). В консоли браузера после перезагрузки:++```js+performance.getEntriesByType('measure')+ .filter(m => /^(ps:watch|cache:|trns:)/.test(m.name))+ .map(m => `${m.name}: ${Math.round(m.startTime)}ms +${Math.round(m.duration)}ms`)+```++| Метка | Значение |+|-------|----------|+| `cache:prime` | Чтение blob-кеша + наполнение хранилищ (путь отрисовки холодного старта) |+| `ps:watch:<table>` | Подписка → первая эмиссия SQLite для каждой загрузочной подписки |+| `trns:first-transform` | Стоимость трансформации строка → элемент для первой эмиссии `trns` |++## Отвергнутые подходы++Задокументированы, чтобы их не пробовали заново без новых данных (детали в [Технических решениях](/ru/reference/tech-decisions) и `todo.md`):++- **OPFS VFS** вместо `IDBBatchAtomicVFS` - холодный старт ограничен `db.init` + сериализацией запросов, а не страничным I/O.+- **Оконная подписка `trns` по дате** - ломает итоги кошельков, которым нужна полная история.+- **Разделение vendor-чанков через `manualChunks`** - фрагментация reka-ui ломает `inject`/`createContext` в продакшен-сборках.+- **Хранение items в `Map`** - экономит единицы миллисекунд на запись при 8k строк, но ломает всех читателей `items` как обычного объекта.