Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,16 @@ PostgreSQL via Drizzle ORM; schema in `src/lib/server/schema.ts` (better-auth ta

For **new features**, do not add data migrations or legacy-data compatibility paths unless persisted data or an external consumer already exists and requires it. Ask if unclear.

### Browser Storage

`localStorage` holds per-browser UI state and is treated as a disposable cache. Data that must survive a device switch or cleared site data belongs in PostgreSQL.

- Access it only through `$lib/client/local-storage` (enforced by ESLint). Browsers that block site data throw on any access, and a throw during hydration takes down the whole app; the helpers fail silently instead.
- Read JSON only through a zod schema (`readStorageJson`, `loadFromStorage`), never with `as`. Data that doesn't match is dropped and the caller falls back to its defaults.
- Types that exist only for storage are derived from their schema (`z.infer`). Domain types that are also stored (e.g. `StorageOperation`) get a round-trip test with a `Required<T>` fixture, so a field the schema would strip fails the test.
- Changing a stored shape: adding optional fields or removing fields needs nothing. For a new required field use `.default()`. Otherwise losing old entries is fine for UI state. Only data users would miss gets a lazy conversion: write to a new key with a version suffix (`…_v2`), read the old key if the new one is missing, convert, write the new one and remove the old one. Test it against an old-format fixture and remove it after two releases.
- No global storage version and no migration step at startup.

### Feature Flags and Configuration

Environment variables are parsed with zod at startup using the helpers in `src/lib/env-schema.ts`; invalid values stop the server. Feature toggles and other settings live in separate modules:
Expand All @@ -144,7 +154,7 @@ Document new variables in `README.md` and `.env.example`; don't read `env` ad ho

`src/lib/components/` is split by what a component depends on. Each layer may only use the layers above it:

1. **`ui/`** — generic building blocks (`Modal`, `TooltipTrigger`, `TabBar`, ...). Data comes in through props, results go out through callbacks or `bind:`. They may import Svelte, icons, Paraglide messages, `$lib/types` and other `ui/` components, nothing else (enforced by ESLint).
1. **`ui/`** — generic building blocks (`Modal`, `TooltipTrigger`, `TabBar`, ...). Data comes in through props, results go out through callbacks or `bind:`. They may import Svelte, icons, Paraglide messages, `$lib/types`, the storage helpers in `$lib/client/local-storage` and other `ui/` components, nothing else (enforced by ESLint).
2. **Top level and `layout/`** — app-wide components that know the app (stores, routes, session), e.g. `ErrorPanel`, `ToastHost`, the header and sidebar.
3. **`<module>/`** — feature components. Pieces shared only within one module go into `<module>/shared/`; move them to `ui/` once a second module needs them and they have no module dependencies.

Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

### Fixed

- The app no longer fails to load when the browser blocks site data (local storage). UI settings such as the theme, panel widths and editor tabs are then kept only until the page is reloaded.

## [26.11.0] - 2026-11-20

## [26.11.0-rc1] - 2026-11-19
Expand Down
64 changes: 64 additions & 0 deletions e2e/blocked-storage.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { test, expect } from './support/fixtures.js';
import { waitForHydration } from './support/helpers';

// Browsers that block site data throw a SecurityError on merely reading `localStorage`. The app
// must still hydrate and work, only without persisting UI state.
test.describe('Blocked site data', () => {
test.use({ locale: 'en-US' });

let pageErrors: Error[];

test.beforeEach(async ({ page }) => {
pageErrors = [];
page.on('pageerror', (err) => pageErrors.push(err));
await page.addInitScript(() => {
for (const name of ['localStorage', 'sessionStorage']) {
Object.defineProperty(window, name, {
configurable: true,
get() {
throw new DOMException('The operation is insecure.', 'SecurityError');
}
});
}
});
});

test.afterEach(() => {
expect(pageErrors.map((e) => e.message)).toEqual([]);
});

test('app shell hydrates and the theme toggle works', async ({ page }) => {
// Firefox is slower to hydrate; triple the default timeout.
test.slow();
await page.goto('/');
await waitForHydration(page);

const html = page.locator('html');
await expect(html).toHaveAttribute('data-theme', /^(light|dark)$/);
const initialTheme = await html.getAttribute('data-theme');

await page.getByRole('button', { name: /switch to (light|dark) mode/i }).click();
await expect(html).not.toHaveAttribute('data-theme', initialTheme ?? '');
});

test('Trino page hydrates and warns that tabs are not saved', async ({ page }) => {
test.slow();
await page.goto('/trino');
await waitForHydration(page);

await expect(page.getByRole('tab')).toHaveCount(1);
await page.getByRole('button', { name: 'New Tab' }).click();
await expect(page.getByRole('tab')).toHaveCount(2);
await expect(
page.getByRole('alert').filter({ hasText: "Tabs can't be saved in this browser." })
).toBeVisible();
});

test('storage page hydrates', async ({ page }) => {
test.slow();
await page.goto('/storage');
await waitForHydration(page);

await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
});
});
44 changes: 42 additions & 2 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,29 @@ export default defineConfig(
files: ['src/lib/components/ui/Modal.svelte'],
rules: { 'svelte/no-restricted-html-elements': 'off' }
},
{
// Touching Web Storage throws when the browser blocks site data, and a throw during hydration
// takes down the whole app. The helpers in local-storage.ts catch that.
files: ['src/**/*.{ts,svelte}'],
ignores: ['src/lib/client/local-storage.ts', 'src/**/*.{test,spec}.ts', 'src/test/**'],
rules: {
'no-restricted-globals': [
'error',
...['localStorage', 'sessionStorage'].map((name) => ({
name,
message: 'Use the helpers in $lib/client/local-storage instead.'
}))
],
'no-restricted-properties': [
'error',
...['localStorage', 'sessionStorage'].map((property) => ({
object: 'window',
property,
message: 'Use the helpers in $lib/client/local-storage instead.'
}))
]
}
},
{
// Generic building blocks: everything comes in through props, so they must not depend on app
// state, routing or feature modules (see "Component Layers" in AGENTS.md).
Expand All @@ -187,8 +210,25 @@ export default defineConfig(
{
patterns: [
{
group: ['$lib/*', '!$lib/paraglide', '!$lib/types', '!$lib/components'],
message: 'ui/ components may only import Paraglide messages, shared types and ui/.'
group: [
'$lib/*',
'!$lib/paraglide',
'!$lib/types',
'!$lib/components',
'!$lib/client'
],
message:
'ui/ components may only import Paraglide messages, shared types, the storage helpers and ui/.'
},
{
// The storage helpers are framework-free and fail silently, so generic components
// can persist their own state.
group: [
'$lib/client/*',
'!$lib/client/local-storage',
'!$lib/client/local-storage.js'
],
message: 'ui/ components may only import the storage helpers from $lib/client.'
},
{
group: ['$lib/components/*', '!$lib/components/ui'],
Expand Down
2 changes: 1 addition & 1 deletion messages/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@
"trino_tab_default_name": "Unbenannt",
"trino_tab_rename": "Tab umbenennen",
"trino_tab_list": "Abfrage-Tabs",
"trino_tabs_persist_error": "Tab-Inhalt zu groß zum Speichern. Einige Änderungen gehen beim Neuladen möglicherweise verloren.",
"trino_tabs_persist_error": "Tabs können in diesem Browser nicht gespeichert werden. Änderungen gehen beim Neuladen möglicherweise verloren.",
"trino_editor_char_limit_reached": "Abfrage überschreitet {limit} Zeichen und wird nicht zwischen Sitzungen gespeichert",
"trino_run_at_cursor": "Ausführen",
"trino_run_all": "Alle ausführen",
Expand Down
2 changes: 1 addition & 1 deletion messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@
"trino_tab_default_name": "Untitled",
"trino_tab_rename": "Rename tab",
"trino_tab_list": "Query tabs",
"trino_tabs_persist_error": "Tab content too large to save. Some changes may be lost on reload.",
"trino_tabs_persist_error": "Tabs can't be saved in this browser. Changes may be lost on reload.",
"trino_editor_char_limit_reached": "Query exceeds {limit} characters and will not be saved between sessions",
"trino_run_at_cursor": "Run",
"trino_run_all": "Run all",
Expand Down
11 changes: 9 additions & 2 deletions src/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script>
(function () {
// localStorage throws when site data is blocked; fall back to the defaults then.
var savedTheme = null;
var savedWidth = null;
try {
savedTheme = localStorage.getItem('theme');
savedWidth = localStorage.getItem('storage_sidebar_width');
} catch (e) {}

var theme =
localStorage.getItem('theme') ||
savedTheme ||
(window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', theme);

var savedWidth = localStorage.getItem('storage_sidebar_width');
if (savedWidth) {
var w = parseInt(savedWidth, 10);
if (!isNaN(w) && w >= 120 && w <= 480) {
Expand Down
103 changes: 103 additions & 0 deletions src/lib/client/local-storage.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { z } from 'zod';
import {
loadFromStorage,
persistToStorage,
readStorage,
readStorageJson,
removeStorage,
writeStorage
} from './local-storage';

const original = Object.getOwnPropertyDescriptor(globalThis, 'localStorage');

function installStorage(getter: () => Storage) {
Object.defineProperty(globalThis, 'localStorage', { configurable: true, get: getter });
}

function memoryStorage(): Storage {
const data = new Map<string, string>();
return {
get length() {
return data.size;
},
clear: () => data.clear(),
getItem: (key) => data.get(key) ?? null,
key: (i) => [...data.keys()][i] ?? null,
removeItem: (key) => void data.delete(key),
setItem: (key, value) => void data.set(key, value)
};
}

// The helpers only touch storage in a browser, which they detect by `window`.
beforeEach(() => {
vi.stubGlobal('window', globalThis);
});

afterEach(() => {
vi.unstubAllGlobals();
if (original) Object.defineProperty(globalThis, 'localStorage', original);
else Reflect.deleteProperty(globalThis, 'localStorage');
});

describe('with working storage', () => {
beforeEach(() => {
const storage = memoryStorage();
installStorage(() => storage);
});

it('round-trips values', () => {
expect(writeStorage('k', 'v')).toBe(true);
expect(readStorage('k')).toBe('v');
removeStorage('k');
expect(readStorage('k')).toBeNull();
});

it('returns validated JSON and null for corrupt or mismatching data', () => {
const schema = z.object({ a: z.number() });
writeStorage('ok', '{"a":1}');
writeStorage('corrupt', '{');
writeStorage('old-shape', '{"a":"1"}');
expect(readStorageJson('ok', schema)).toEqual({ a: 1 });
expect(readStorageJson('corrupt', schema)).toBeNull();
expect(readStorageJson('old-shape', schema)).toBeNull();
expect(readStorageJson('missing', schema)).toBeNull();
});

it('drops array entries that do not match the schema', () => {
persistToStorage('list', [1, 'two', 3]);
expect(loadFromStorage('list', z.number())).toEqual([1, 3]);
});
});

describe('when the browser blocks site data', () => {
// Browsers throw a SecurityError on merely reading the `localStorage` global.
beforeEach(() => {
installStorage(() => {
throw new DOMException('The operation is insecure.', 'SecurityError');
});
});

it('fails silently', () => {
expect(readStorage('k')).toBeNull();
expect(readStorageJson('k', z.unknown())).toBeNull();
expect(writeStorage('k', 'v')).toBe(false);
expect(() => removeStorage('k')).not.toThrow();
expect(loadFromStorage('k', z.number())).toEqual([]);
expect(() => persistToStorage('k', [1])).not.toThrow();
});
});

describe('when storage is full', () => {
beforeEach(() => {
const storage = memoryStorage();
storage.setItem = () => {
throw new DOMException('Quota exceeded', 'QuotaExceededError');
};
installStorage(() => storage);
});

it('reports the failed write', () => {
expect(writeStorage('k', 'v')).toBe(false);
});
});
Loading
Loading