Compare commits

..

14 Commits

Author SHA1 Message Date
Josh Creek 669d0cdeaa Merge pull request #99 from jcreek/perf/pokedex-grid-transport
Perf/pokedex grid transport
2026-09-15 18:39:28 +01:00
Josh Creek 7373bf005d docs(performance): record the pokédex investigation and hosting evaluation
Keeps the measurements, the implementation notes and the hosting comparison next
to the code they justify.
2026-09-15 17:49:04 +01:00
Josh Creek 3ee69f0d04 refactor(api): drop the redundant setSession in export-integrations
requireAuth has already resolved the session on locals.supabase.
2026-09-15 17:49:04 +01:00
Josh Creek 0c1de9a93d fix(a11y): trap focus inside the pokédex modal
Tab moved to the page behind the open dialog and closing it left focus nowhere.
Keep Tab within the dialog, move focus to the close button on open, restore it
to the trigger on close, and give the dialog an accessible name.
2026-09-15 17:49:04 +01:00
Josh Creek 03b74089a0 feat(offline): open entry details from the saved snapshot
Opening an entry while offline needed a request that could not be made. Read it
from the snapshot claimed by the signed-in account instead, re-checking
ownership after the read so a sign-in mid-read cannot surface another account's
data, and let controls marked data-offline-action stay usable in read-only mode.
2026-09-15 17:48:57 +01:00
Josh Creek 56b676b04a perf(startup): defer offline sync and backup status until the grid is interactive
Both fired during hydration and competed with rendering the grid, and the layout
waited for the user store before it could show a signed-in shell even though the
server already knew who the user was.

Seed the user from the layout data, and queue the offline sync and backup
refresh behind the grid's interactive mark; an explicit refresh, a reconnect or
an edit still runs straight away. Backup refreshes now share one in-flight
request per generation, and a change of account cancels the pending startup
refresh and clears the stale status.
2026-09-15 17:48:49 +01:00
Josh Creek 19abb34693 fix(sync): keep queued catch-record writes from crossing an account change
The queue held whole records and flushed whatever was in it, so edits made
before a sign-out could be written against the account that signed in next.

Queue patches and merge them per key, so two edits to one entry combine instead
of one replacing the other; drop everything when the owning account is no longer
the current one; and stop scheduling flushes while offline, where they could only
fail and back off.
2026-09-15 17:48:34 +01:00
Josh Creek 54eaa6d776 fix(catch-records): stop bulk upserts clobbering fields a toggle never touched
Toggling one checkbox sent the whole record, so a stale copy of the other fields
could overwrite newer values. Send only the fields that changed, group rows by
the columns they carry, and upsert each group with defaultToNull: false so
omitted columns keep their stored value. Results are returned in the caller's
order rather than whatever order the groups came back in.
2026-09-15 17:48:34 +01:00
Josh Creek 2042e5a65a test(performance): add a local pokédex benchmark and run it in CI
Measures the pokédex load against a local Supabase with a generated fixture, and
compares runs so a regression shows up as a number rather than a hunch. Wired
into test:ci and given its own job so the artifacts survive a failure.
2026-09-15 17:47:21 +01:00
Josh Creek 2766e5ea67 build(cloudflare): add a Cloudflare preview build target
DEPLOY_TARGET now selects the adapter; Netlify stays the default and NODE_ADAPTER
keeps working. Cloudflare compresses in transit, so the Worker build aliases
$lib/server/compression to a pass-through that leaves the streaming body alone.

CI builds and dry-run deploys this target. That is compilation and packaging
coverage only, not a production compatibility gate: native sharp still blocks the
share-preview route in the Worker runtime.
2026-09-15 17:47:14 +01:00
Josh Creek b2b750115f perf(sprites): serve grid-sized thumbnails from an immutable URL space
Every grid cell downloaded the full detail sprite. Generate a smaller
/sprites-grid/v1/ set at build time and let the grid ask for those first,
falling back through the existing detail URLs when a thumbnail is missing so
detail resolution is unchanged. The new prefix is versioned, so it can be cached
forever, and the service worker recognises it alongside the other sprite roots.

The placeholder is now an empty box rather than a spinner: a thousand spinners
cost layout work and announced nothing useful.
2026-09-15 17:46:49 +01:00
Josh Creek 26b9e3b8c1 perf(pokedex): fetch dex scopes with the pokédex row
findById made a second round trip for scopes on every page load; embed
pokedex_dex_scopes in the select instead.
2026-09-15 17:46:23 +01:00
Josh Creek acaf760b36 perf(pokedex): send the box grid as packed rows with the page
The server load fetched a full combined-data page at a 9999 item page size,
carrying detail text and ownership fields the grid never renders, and the client
re-fetched the same payload after hydration.

Load a trimmed grid row instead and pack it as positional tuples so field names
are not repeated for every one of a thousand-plus entries. Entry detail is
fetched on demand from the new per-entry endpoint when a cell is opened, and the
grid marks itself interactive so other page-start work can queue behind it.
2026-09-15 17:46:19 +01:00
Josh Creek 4c268ba15c feat(pokedex): add opt-in Server-Timing for the pokédex load
POKEDEX_PERFORMANCE=true reports auth, ownership, scopes, entries and catches
with fixed labels only: no IDs, query strings, cookies or entry content ever
reach the header. Auth is measured in the hook, where the session is actually
resolved, and handed to the page load through locals.
2026-09-15 17:46:07 +01:00
61 changed files with 8920 additions and 555 deletions
+2
View File
@@ -11,3 +11,5 @@ node_modules
pnpm-lock.yaml pnpm-lock.yaml
package-lock.json package-lock.json
yarn.lock yarn.lock
.wrangler/
+41
View File
@@ -144,3 +144,44 @@ jobs:
if-no-files-found: ignore if-no-files-found: ignore
- if: always() - if: always()
run: npx supabase stop run: npx supabase stop
pokedex-performance:
runs-on: ubuntu-latest
timeout-minutes: 20
env:
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER: 'true'
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 24
cache: npm
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npx supabase start
- run: npm run test:performance
- uses: actions/upload-artifact@v6
if: always()
with:
name: pokedex-performance
path: test-results/performance/
if-no-files-found: ignore
- if: always()
run: npx supabase stop
cloudflare-preview-build:
runs-on: ubuntu-latest
timeout-minutes: 15
env:
WRANGLER_SEND_METRICS: 'false'
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 24
cache: npm
- run: npm ci
- run: npm run build:cloudflare
- run: npm run check:cloudflare
# This is compilation/package coverage, not a production compatibility gate.
# Native sharp still blocks the share-preview route in the Worker runtime.
+3
View File
@@ -15,3 +15,6 @@ vite.config.ts.timestamp-*
coverage coverage
playwright-report playwright-report
test-results test-results
/static/sprites-grid/
.wrangler/
+4
View File
@@ -13,3 +13,7 @@ static/sprites-small/manifest.json
# Machine-local editor and tool settings. # Machine-local editor and tool settings.
**/*.local.json **/*.local.json
# Generated grid artwork and local Worker runtime output.
static/sprites-grid/
.wrangler/
+3
View File
@@ -0,0 +1,3 @@
/sprites-grid/v1/*
Cache-Control: public, max-age=31536000, immutable
+6 -15
View File
@@ -2,20 +2,11 @@ import process from 'node:process';
import AdapterNode from '@sveltejs/adapter-node'; import AdapterNode from '@sveltejs/adapter-node';
import AdapterNetlify from '@sveltejs/adapter-netlify'; import AdapterNetlify from '@sveltejs/adapter-netlify';
export const nodeAdapter = process.env.NODE_ADAPTER === 'true'; export const nodeAdapter =
process.env.NODE_ADAPTER === 'true' || process.env.DEPLOY_TARGET === 'node';
// Netlify is the deployment target; the node adapter exists so the service worker export const cloudflareAdapter = process.env.DEPLOY_TARGET === 'cloudflare';
// build tests can check the `build/client` layout a Node server produces, and so Lighthouse CI
// can audit a production build. Netlify's CDN compresses responses, so precompress here to match.
export const adapter = nodeAdapter export const adapter = nodeAdapter
? AdapterNode({ precompress: true }) ? AdapterNode({ precompress: true })
: AdapterNetlify({ : cloudflareAdapter
// if true, will create a Netlify Edge Function rather ? (await import('@sveltejs/adapter-cloudflare')).default()
// than using standard Node-based functions : AdapterNetlify({ edge: false, split: false });
edge: false,
// if true, will split your app into multiple functions
// instead of creating a single one for the entire app.
// if `edge` is true, this option cannot be used
split: false
});
@@ -0,0 +1,57 @@
# Hosting evaluation: retain Netlify pending deployed evidence
Date: 15 September 2026. This is an interim decision report. **Do not cut over to Cloudflare yet.** The application improvements and selectable preview build are implemented, but the agreed real-host comparison cannot be completed with the current access and compatibility state.
## Evidence and decision
| Item | Observed result | Consequence |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Production Netlify site | `livingdextracker`, `www.dextracker.uk`; published revision inspected: `31fd959350962c1f1b973a06ecd5cf4eeef86514` | This is the existing deployment, not this working tree |
| Function/database regions | Netlify `us-east-1`; linked Supabase `eu-north-1`; production public database URL matches that project | Cross-region round trips are a plausible contributor; their latency share is unmeasured |
| Node production checks | Compact SSR, details, status writes, offline behavior and rendering budgets exercised locally | Application evidence only |
| Cloudflare build | Adapter 7.2.9, Wrangler 4.131.2, compatibility date 2026-09-15, `nodejs_compat`; build and dry-run passed | Packaging is viable |
| Final Worker artifact | Approximately 1,876 KiB uncompressed / 336 KiB gzip; 9,621 static assets | Within published size/count limits; re-audit after renderer changes |
| Actual local workerd | Home, authenticated dex and public share page returned 200 | Basic runtime support demonstrated |
| Share image in workerd | `/shared/:token/preview.png` returned 500; `sharp` native module dynamic require is unsupported | **Compatibility gate failed**; see separate renderer proposal below |
| Remote preview access | Netlify CLI authenticated; Wrangler not authenticated; equivalent staging fixtures/accounts not supplied | No paired deployed samples collected |
No production deployment, DNS change, database migration or region change was performed. Retaining Netlify now is a decision under incomplete evidence and a failed compatibility gate, not evidence that Netlify is faster.
Netlify supports streaming; the investigation's buffering describes the installed adapter/runtime combination, not the entire platform. Cloudflare's supported SvelteKit adapter and partial Node compatibility do not imply support for native `sharp`. Sources: [Netlify streaming](https://docs.netlify.com/build/functions/lambda-compatibility/), [SvelteKit Cloudflare adapter](https://svelte.dev/docs/kit/adapter-cloudflare), [Cloudflare Node compatibility](https://developers.cloudflare.com/workers/runtime-apis/nodejs/).
## Build and environment requirements
- Default builds remain Netlify. `NODE_ADAPTER=true` or `DEPLOY_TARGET=node` selects Node. `npm run build:cloudflare` selects Workers with Static Assets; `npm run check:cloudflare` checks packaging; `npm run preview:cloudflare` runs workerd locally. Do not run builds concurrently.
- Cloudflare uses platform compression rather than the Node compression implementation. Verify actual deployed content encoding for HTML, SvelteKit data and JSON responses.
- Supply public Supabase URL/anon key at build time, and private Supabase/export/OAuth secrets through platform bindings. Preview secrets must belong to the same staging project on both hosts. Keep provider redirect allowlists and cookie/domain settings explicit.
- Authenticate Wrangler and select the intended account before creating a remote preview. Build/dry-run success does not authorize production routing.
- Current documented limits include 128 MB memory, one-second startup, 64 MiB uncompressed Worker size and 20,000/100,000 static files on Free/Paid. Each static file must be at most 25 MiB. Free CPU allowance is only 10 ms per invocation; do not assume the app or renderer fits it. Measure CPU/memory/startup under actual workerd and deployment. [Workers limits](https://developers.cloudflare.com/workers/platform/limits/)
## Separate proposal: Worker-compatible share-image renderer
This is the concrete implementation proposal required by the migration gate. It is **not implemented** in this change.
1. Extract the existing SVG construction, XML escaping and text truncation into a platform-neutral module. Preserve the endpoint, 1,200 × 630 dimensions, progress values, privacy behavior and cache headers.
2. Keep a Node renderer using `sharp`. Add a Cloudflare renderer using `@resvg/resvg-wasm`, selected through the same build-time platform alias pattern as compression. Pin a verified version in the renderer change; exclude native `sharp` from the Worker dependency graph.
3. Bundle the renderer's WASM as a module and initialize lazily once per isolate through a shared promise. Import a compiled WebAssembly module using the supported Workers approach, rather than assuming a browser-style URL fetch loader works. Release per-render allocations after producing a PNG byte array. [Workers WASM support](https://developers.cloudflare.com/workers/runtime-apis/webassembly/javascript/), [resvg WASM package](https://github.com/thx/resvg-js/tree/main/wasm)
4. Bundle licensed regular/bold fonts, for example Noto Sans with its license. Explicitly map SVG weights to those fonts; do not rely on operating-system fonts. Verify accented Pokémon names, punctuation, long descriptions and the intended non-Latin fallback policy. Font appearance will need review against existing PNGs.
5. Add golden-image/metadata tests for empty/long names, XML special characters, all badges and 0/100% progress. Exercise concurrent requests, first invocation, repeated renders and error recovery in built workerd. Require HTTP 200, PNG signature/dimensions, correct sharing access and no private notes.
6. Re-audit bundle/assets, CPU, memory and startup after adding WASM/fonts. Run the deployed share-image test and backup/export/auth matrix before setting compatibility to passed. If this renderer exceeds operating constraints, compare a separately hosted image service in a new proposal; do not silently redirect rendering to production Netlify.
## Remaining deployed benchmark
1. Supply equivalent staging credentials and disposable national/scoped-form fixtures, then publish this exact code to both preview hosts. Preserve actual deployed revision and environment metadata.
2. Establish improved Netlify document/data baselines. Consider a separate region-aligned Netlify preview as an additional experiment; do not change the primary paired comparison mid-run.
3. Exercise sign-in, token refresh, account switching, Google/Dropbox OAuth and refresh, export generation, public shares/images, compression, secrets/bindings, static cache headers, service-worker install/update/offline routing and custom preview domains on both real hosts.
4. Use the [comparison harness](pokedex-implementation.md#instrumentation-and-comparison-harness) for at least 30 warm samples per host × fixture × direct/client navigation. Keep code, Supabase project, fixtures, browser settings and client locations identical. Run additional deliberately idled samples and record the idle duration separately; first-observed is not a cold-start claim.
5. Recommend migration only when overall first-interactive p75 improves by **both 20% and 200 ms**, no fixture/navigation combination regresses by more than 10%, and functional checks pass. Include costs and operating requirements before making the final decision.
## Cost projection and operations
Actual monthly traffic, CPU usage and the account's current Netlify billing arrangement are not available, so no savings claim is justified.
Cloudflare Paid has a $5/month minimum, includes 10 million dynamic requests and 30 million CPU-ms, then charges $0.30/million requests and $0.02/million CPU-ms. Direct static asset requests are free; requests served through Workers Caching have different billing. Illustrative direct-static configuration: 1 million dynamic requests at 20 ms CPU each remains within $5; 10 million at 20 ms is approximately $8.40. These exclude other services and are assumptions, not measured app CPU. [Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/)
For credit-based Netlify plans, estimate credits as `15 × production deploys + 10 × compute GB-hours + 20 × bandwidth GB + 2 × requests/10,000`. Confirm whether this account uses credit-based or legacy billing and apply its actual plan/allowance. Thumbnail byte savings affect bandwidth, while increased first-party sprite requests affect request metering. [Netlify pricing](https://www.netlify.com/pricing/)
Before a qualifying cutover: move database migrations out of host builds into one serialized CI release step; provision secrets and OAuth redirects; validate the custom domain and cookies; monitor error/latency/export metrics; retain the working Netlify deployment and a documented DNS rollback. These production changes remain conditional on completing the gates above.
+115
View File
@@ -0,0 +1,115 @@
# Pokédex performance implementation
Status: application changes implemented; hosting comparison remains gated. Measurements below are local production-build evidence, not deployed latency improvements. See [hosting evaluation](pokedex-hosting-evaluation.md) for the migration decision and remaining work.
## Application changes
- Ownership and saved scope links are read together. Scoped entry retrieval is shared by rows/count consumers; the full grid performs no count query. Catch joins use ID maps. Scope deduplication, named default forms, supplements and ordering remain covered by repository tests.
- The page awaits the entire compact grid and renders initial boxes on the server. Authentication state reaches SSR through the validated layout user. Successful navigation needs no grid API request; failed grid loads expose retry.
- `PokedexGridRow` contains identity, sprite resolution fields and catch flags. The page and authenticated `/api/pokedexes/[id]/grid` endpoint transport named tuples defined in `PokedexGridRow.ts`; `packGrid`/`unpackGrid` keep that wire format out of components. Instructions, notes, origin games and repeated owner/dex IDs are absent. Existing full combined-data consumers retain their contracts.
- The detail endpoint verifies ownership and membership before returning one full `CombinedData` row. The modal opens immediately with identity and full artwork, then loads editable details. Its account/dex/entry cache, abort/sequence checks and pending-patch merge protect rapid selection changes and optimistic edits.
- Status writes send changed fields. Bulk writes group records by supplied columns, preserving omitted notes and flags; explicit empty notes clear them. New records use database defaults. Full-record callers and exports remain supported. Bulk box actions still target all original 30 slots, including dimmed entries.
- Grid placeholders preserve geometry; visible boxes and one row of overscan mount populated cells. Focused boxes remain mounted, keyboard navigation crosses boundaries, modal close restores focus, and an accessible render-all option exposes the complete document. Each Pokémon uses one button with identity/status and a noninteractive tooltip.
- Density is persisted in a cookie for stable SSR geometry and in local storage. Resize/density changes preserve the current box anchor. Existing local-storage-only preferences are replaced by the cookie after choosing a density.
- Automatic snapshot/backup work starts at the interactive/idle boundary with a five-second fallback. Concurrent backup refreshes coalesce. Explicit sync and edit/account/reconnect invalidations retain freshness behavior. Backup-status GET no longer revalidates via `setSession`.
- Complete offline snapshot format 2 is retained. Offline modal details come only from the matching account snapshot; missing copies report unavailable details. Offline details are read-only, as before for offline mutations.
## Artwork and build behavior
`npm run sprites:grid` generates 3,170 first-party WebP thumbnails, at most 128 pixels per side, quality 80. Builds run this automatically. Generated assets live in ignored `static/sprites-grid/v1/`; the generator emits a manifest. Originals remain 512 pixels for details and explicit full-artwork downloads.
The generated catalog is 10,007,504 bytes versus 53,659,230 bytes for the source WebP catalog (81.4% smaller). Shiny, female and named-form resolution uses the existing key/fallback chain. The service worker recognizes versioned grid sprites in the existing artwork cache; neither thumbnail nor original catalogs are blanket precached. Root `_headers` supplies immutable caching on Netlify/Cloudflare. Bump the URL version whenever generation settings or source images change; generation skips existing files within a version.
## Local acceptance evidence
Fixtures: national (1,025 entries), Scarlet/Paldea forms (439 entries), mixed catch flags and nonempty notes. Integration tests additionally cover missing catches and overlapping scopes through repository tests. Browser viewport: 1,350 × 940, comfortable density, Chromium, local Node production build and local seeded Supabase.
The packed grid is approximately 81 KB national and 36 KB scoped, versus the investigation's approximately 593 KB and 255 KB full-data JSON. The same-fixture integration assertion separately verifies at least 60% reduction against full combined rows. These are serialized row sizes, not compressed HTML document sizes.
The local browser checks verify at most 180 populated mounted cells, fewer than 2,500 DOM elements and CLS at most 0.1; observed initial population is 120 cells. Density/mobile checks include all three densities at 1,350 and 390 pixels. Detail artwork is asserted to load at 512 pixels. No redundant grid request is allowed; intentional detail requests are allowed.
Warm results from the corrected harness (30 samples per row; [sanitized summary](pokedex-local-results.json)):
| Fixture | Navigation | First visible p75 | First interactive p75 | Decoded response bytes p75 | Maximum DOM |
| ------------ | ---------- | ----------------: | --------------------: | -------------------------: | ----------: |
| National | Direct | 123.5 ms | 145.4 ms | 248,668 | 2,088 |
| National | Client | 495.6 ms | 494.1 ms | 102,687 | 2,090 |
| Scoped forms | Direct | 114.5 ms | 133.1 ms | 203,601 | 2,073 |
| Scoped forms | Client | 491.7 ms | 490.6 ms | 45,645 | 2,075 |
Every warm sample had 120 populated cells, zero observed CLS, zero redundant grid requests and a measured response size. Direct response bytes include SSR markup and SvelteKit data; client bytes are SvelteKit data responses, not just the packed rows. Interactive marks can precede the next animation-frame visibility observation by a few milliseconds. Client timings include Playwright click overhead, as explained below. This benchmark preceded the final account-switch backup invalidation guard; the final production smoke suite also passed after that guard.
### Validation completed
| Check | Result |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| Svelte/TypeScript | 0 errors; one existing `Tooltip.svelte` CSS `@apply` warning |
| Unit tests | 193 passed |
| Data tests | 18 passed |
| Coverage | Existing thresholds passed: 66.81% lines/statements, 88.79% branches, 90.99% functions |
| Local Supabase integration | 16 passed, including same-fixture payload reduction and note preservation |
| Authenticated browser regressions | 53 passed, including mock Google/Dropbox OAuth, exports and service-worker/offline flows |
| Build matrix | Four checks in each of Netlify/Node × generateSW/injectManifest passed |
| Production performance/behavior | Both fixtures, all densities/mobile, resize anchor, focus/keyboard, modal race, full artwork and offline snapshot isolation passed |
| Cloudflare | Final build and Wrangler dry-run passed; local workerd share-image generation failed as documented in the hosting report |
| Formatting/lint | All changed/new implementation files pass Prettier; ESLint and `git diff --check` pass |
Repository-wide `npm run lint` also scans the pre-existing untracked `dex.har` and `POKEDEX_PERFORMANCE_PROMPT.md`; those two files have formatting warnings and were intentionally left untouched. No coverage threshold was lowered. Disposable performance accounts and local test servers were cleaned up.
### Reproduce
```sh
npm ci
npx supabase start
npx playwright install chromium
npm run check
npm run test:unit
npm run test:integration
npm run test:build
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER=true npm run test:bdd
npm run test:performance
PERF_BENCHMARK=true npm run test:performance
```
Run builds sequentially: they share `.svelte-kit` and `build`. Performance tests create a disposable local-only account, use private temporary session files, clean up afterward, and copy sanitized reports/screenshots to ignored `test-results/performance/`. Cleanup failures retain recovery files. Never commit session/configuration files.
## Instrumentation and comparison harness
Set `POKEDEX_PERFORMANCE=true` on a preview to emit fixed-label `Server-Timing` stages: auth, ownership, scopes, entries, catches, preparation and total. Timings do not include IDs, cookies, notes or query text. Authentication includes the request hook's validation. Total measures the page/service span, not total platform request lifetime; stages may therefore not sum to total.
The browser harness measures first visible cells via animation frames and first interactive cells via `pokedex:first-interactive`, independently of response completion. It collects DOM/cells, layout shifts, intentional/redundant API counts and response sizes. For Chromium service-worker responses where Playwright cannot read the body, decoded Resource Timing bytes are used; absent measurements stay null. Decoded, encoded and transferred bytes are distinguished.
`benchmark.mjs` requires at least 30 warm samples per fixture/navigation combination. It records the first observed run separately; that is **not** evidence of a cold start or first-after-idle run. For real-host work, collect deliberately idled runs separately and record the idle interval. Client timing starts before Playwright's click, so includes its actionability overhead; preserve identical tooling/settings between hosts and report this limitation.
Private configuration example (replace all placeholders):
```json
{
"samples": 30,
"revision": "exact-deployed-commit",
"databaseLabel": "same-staging-project",
"clientLocation": "London-fixed-runner",
"environment": "deployed",
"compatibilityPassed": false,
"hosts": [
{
"label": "netlify",
"url": "https://NETLIFY-PREVIEW",
"storageState": "/PRIVATE/netlify-session.json",
"fixtures": [
{ "id": "NATIONAL-ID", "name": "Performance National", "label": "national" },
{ "id": "SCOPED-ID", "name": "Performance Scarlet Forms", "label": "scoped-forms" }
]
}
]
}
```
Add an equivalent `cloudflare` host using the same database and fixtures. Run:
```sh
node scripts/performance/benchmark.mjs /PRIVATE/config.json /PRIVATE/results.json
node scripts/performance/compare.mjs /PRIVATE/results.json
```
The comparison refuses insufficient samples and retains Netlify unless deployed evidence, compatibility and the agreed improvement thresholds all pass. Human review must still establish costs, environment equivalence and deployment prerequisites.
+227
View File
@@ -0,0 +1,227 @@
# Signed-in Pokédex performance investigation
Investigated 1415 September 2026 at commit `31fd959350962c1f1b973a06ecd5cf4eeef86514`.
## Findings
The production capture establishes a server-response bottleneck: **3,506 ms waiting versus 261 ms receiving** the Pokédex data response. The current loading design exposes all entry work to that wait on the installed Netlify adapter. It requests practically the entire dex, and the adapter buffers the response before returning it. Independently, mounting the entire grid causes avoidable browser work.
Local measurements confirm the request sequence, duplicate game-scoped queries, large payload and rendering cost. **They do not explain the exact allocation of production's 3.5 seconds.** Regions, function startup and production query timings remain unverified. At the user's direction, no further production/dashboard access was attempted; subsequent measurements used local Supabase.
No performance fixes, migrations, deployment settings, public APIs or types were changed. Temporary instrumentation and the diagnostic rendering cap were removed. Full-resolution artwork must remain available when a user opens a Pokémon's detail view.
The numerical evidence, including individual runs and sanitized server traces, is in [pokedex-results.json](pokedex-results.json).
## Production evidence and its limits
| Evidence | Result | Interpretation |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| Supplied `dex.har`, data navigation | Wait 3,506.100 ms; receive 260.671 ms; 401,199 uncompressed bytes | Waiting dominates transfer. This includes server and network effects; it is not a database timer. |
| Response headers | Brotli; `private,no-store`; Netlify request ID present | Compression already exists. User-specific content is not served as a public CDN cache hit. |
| HAR content | Response text absent | Cannot measure production field sizes or infer the dex's form/scope configuration from this file. |
| HAR sprites | 36 requests, 531,086 bytes total, `max-age=300` | Visible artwork has a substantial transfer cost independent of entry data. |
| Supplied Lighthouse summary | Root response 3,373 ms; about 386 KB serialized inline data; 10,442 DOM elements; 1.9 s rendering; CLS 0.127 | Corroborates both server wait and browser cost. These are user-supplied findings, not a new run. |
The HAR contains only one application request plus the 36 sprite requests. It does **not** contain the offline-snapshot or backup-status requests; their production sizes/durations come from the supplied Lighthouse summary. Extension findings were excluded.
### Why streaming currently fails to hide the work
[The server load](../../src/routes/pokedex/[id]/+page.server.ts) returns an unresolved `initialCombinedData` promise, but `INITIAL_PAGE_SIZE` is **9,999**, matching the client. Its `.then()` discards the count/pagination metadata after the shared service has calculated it.
[adapter.mjs](../../adapter.mjs) selects standard Netlify functions (`edge: false`), except for Node test builds. Installed `@sveltejs/adapter-netlify` **4.4.2**, in `node_modules/@sveltejs/adapter-netlify/files/esm/serverless.js`, awaits `response.text()` for text responses and `response.arrayBuffer()` for binary responses. Both buffer the body before the handler returns. This proves the behavior of the installed adapter; the exact deployed package/build was not accessible. The HAR's long wait is consistent with it.
[Compression](../../src/lib/server/compression.ts) already skips application compression in Lambda because Netlify handles it. Enabling more compression would not fix this buffering boundary. The page also assigns its entries client-side, so even genuine transport streaming does not mean the grid is server-rendered and interactive immediately.
An isolated local identity-encoding stream probe received first bytes before completion:
| Dex | First-byte median | Complete-body median |
| ------------- | ----------------: | -------------------: |
| National | 48.3 ms | 104.7 ms |
| Scarlet forms | 36.8 ms | 72.5 ms |
These are Vite measurements, not evidence that Netlify streams.
## Server request map and timings
Sources: [session hook](../../src/hooks.server.ts), [ownership repository](../../src/lib/repositories/PokedexRepository.ts), [scope service](../../src/lib/services/PokedexDexScopeService.ts), [combined-data service](../../src/lib/services/CombinedDataService.ts), [combined-data repository](../../src/lib/repositories/CombinedDataRepository.ts).
For an unexpired authenticated session, both measured dexes make **eight Supabase HTTP requests per page/data request**:
| Stage | National: 1,025 entries | Scarlet Paldea forms: 439 entries |
| ---------------------------------------- | ------------------------------------------ | ------------------------------------------ |
| Authentication | 1 `getUser` | 1 `getUser` |
| Ownership, then scope links | 1 `pokedexes`, then 1 `pokedex_dex_scopes` | Same |
| Entry branch | 2 sequential entry pages: 1,000 + 25 | 1 game-dex query, then 1 forms query |
| Count branch, parallel with entry branch | 1 HEAD exact-count query | Repeats the game-dex query and forms query |
| Catches, after entry retrieval | 2 sequential chunks: 1,000 + 25 | 1 chunk: 439 |
| Total / longest chain of requests | **8 / 7** | **8 / 6** |
The game query returns 400 rows. The named-form query returns 45 rows; six are already represented, leaving 39 supplements and 439 unique entries. The count branch repeats both reads, transferring another **277,047 bytes** from Supabase just to count those entries. The two branches run concurrently: eliminating duplication reduces work and traffic, but does not necessarily remove their summed durations from the critical path.
General case:
- National path: `3 + entry-page requests + 1 count + catch chunks`. Pagination continues until a short/empty batch or the requested limit. An exact multiple of 1,000 may require an empty terminal request. Catch chunks use at most 1,000 IDs.
- Explicit game scopes: `3 + 2 × (dex-page requests + applicable form-page requests) + catch chunks`. Counting fetches the full scope even when the requested page is small. Deduplication and slicing happen in JavaScript.
- A game scope without saved dex scopes adds two sequential reads (`games`, then `game_dexes`). National dexes still pay the scope-link query even though scope resolution itself returns immediately.
- Token refresh can add an authentication request. A separate probe using an expired saved cookie produced nine requests; the reported baseline was rerun with a fresh session. Replaying that stale cookie every time was a probe artifact, not normal browser session behavior.
- `safeGetSession` is shared within a request, not across navigation and background requests.
### Isolated local server timings
Five warm requests per dex, one first run excluded. Queries were instrumented at the Supabase fetch boundary, including response-body completion; repository methods were timed separately. The cloned response used for instrumentation adds overhead. All values below are medians, so columns are not additive.
| Measure | National | Scarlet forms |
| --------------------------------------------------- | -------: | ------------: |
| Auth `getUser` HTTP duration | 35.5 ms | 25.3 ms |
| Ownership + scope-link HTTP durations | 8.0 ms | 7.2 ms |
| `findCombinedData`, including entries and catches | 50.7 ms | 33.3 ms |
| `countCombinedData`, concurrent with find | 6.6 ms | 25.6 ms |
| Catch retrieval, included within find | 16.4 ms | 6.5 ms |
| Sum of all query durations | 92.9 ms | 86.0 ms |
| Elapsed request time to final query-body completion | 87.6 ms | 64.1 ms |
| Complete HTTP response | 104.7 ms | 72.5 ms |
| Supabase response-body bytes, summed | 917,728 | 709,996 |
The difference between summed query durations and elapsed completion reflects concurrency. Repository work, serialization, streaming and measurement overhead sit outside or between query timings. Do not subtract these local medians from production TTFB to invent a region/startup estimate.
### Query plans and indexes
`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` ran under the local `authenticated` role with the fixture user's JWT subject. These are SQL execution times, excluding HTTP, PostgREST JSON serialization and function/network latency.
| Query shape | Median of five warm executions |
| ------------------------------------------------- | -----------------------------: |
| National ordered entries, first 1,000 | 5.557 ms |
| National ordered entries, offset 1,000 | 5.866 ms |
| National exact count through the view | 2.484 ms |
| Scarlet game-dex detail rows | 10.706 ms |
| Named forms available in Scarlet | 2.934 ms |
| Catch query with the actual first 1,000 entry IDs | 0.476 ms |
The entry view joins and aggregates origin-game data before returning rows. The game-dex plan aggregates 1,390 Pokémon before joining the 400 scoped entries. The offset query repeats aggregation/sorting for the last 25 rows. These are real work amplification, but small absolute local costs.
The game membership index and existing catch-record dex index are used. The exact catch query is already sub-millisecond locally. **No new index is justified by these measurements.** Prefer avoiding duplicate/full-view work before speculative indexing. The evidence JSON also retains an earlier catch-plan probe with an ID subquery; the literal-ID result above is the closer match to the application.
## Payload and browser measurements
### Method and fixtures
- Existing local Supabase seed: 1,390 catalog entries, 1,025 default forms. No reset or migration was run.
- Dedicated disposable account: national living dex with 1,025 catch records; Scarlet/Paldea form dex with 1,390 seeded catch records, of which 439 match this view. Mixed deterministic statuses and empty personal notes. Existing user data was preserved.
- Headless Playwright Chromium, 1,350 × 940 viewport, device scale 1, no extensions, no CPU/network throttling. Vite 5.4.21 development server, Node 24.18.0, same-origin sprites.
- One first run plus five warm runs for each navigation/dex combination. Client navigation clicks the real card's View button from My Pokédexes. Each client sample starts from a loaded list page with a 1.1-second settling period.
- “Visible cells” uses Playwright's first-cell visibility check and includes automation overhead. Response completion is network response completion, not full page idle. Layout/style time is CDP `LayoutDuration + RecalcStyleDuration` over the sample and 1.5-second follow-up; it is not Lighthouse's entire rendering category.
| Dex / navigation | First-run visible | Five warm visible times | Median TTFB | Median response complete | Median visible | DOM |
| ---------------------- | ----------------: | -------------------------- | ----------: | -----------------------: | -------------: | -----: |
| National / direct | 798 ms | 549, 986, 519, 474, 432 ms | 84 ms | 268 ms | **519 ms** | 10,236 |
| National / client | 407 ms | 322, 335, 369, 423, 381 ms | 63 ms | 133 ms | **369 ms** | 10,236 |
| Scarlet forms / direct | 462 ms | 309, 278, 299, 312, 317 ms | 68 ms | 148 ms | **309 ms** | 4,476 |
| Scarlet forms / client | 224 ms | 272, 227, 233, 363, 274 ms | 59 ms | 111 ms | **272 ms** | 4,476 |
These development results must not be equated with optimized production performance. Local full-dataset fixture content, development scripts/styles and serialized session metadata differ from the production capture. The initial Vite dependency-optimization failure was resolved before collecting this matrix. One first-run streamed response could not be read through Chromium's body-capture API; its bytes are recorded as null, not zero.
### What is needed at first paint
At this viewport the national dex mounts 35 boxes and 1,025 populated cells, with only **60 cells visible**. Scarlet mounts 15 boxes and 439 cells, also with 60 visible. The national grid is 10,532 px tall. IntersectionObserver already defers distant sprite downloads; it does not prevent mounting those cells, tooltip components and loading spinners. There were 73 image elements, not 1,025 downloaded sprites.
The box and tooltip need identity/name/form/number/sprite key and catch-status flags. Evolution/catch instructions, origin games, dex notes and personal notes belong to the detail workflow. Repeated catch `userId`/`pokedexId` values are also expensive in ordinary JSON. The page still needs global totals and stable placement, so simply lowering the limit would break existing behavior.
| JSON measurement | National | Scarlet forms |
| ------------------------------------------------- | --------: | ------------: |
| Full combined rows | 592,997 B | 255,319 B |
| Display-only rows for every entry | 170,636 B | 74,154 B |
| Display-only first 60 entries | 9,751 B | 10,757 B |
| Detail-only Pokémon fields, separately serialized | 214,064 B | 91,887 B |
“Display-only” is a sizing experiment, **not a proposed drop-in API**: it excludes identifiers/fields that writes and details currently need. JSON partitions are serialized separately and are not additive. Actual SvelteKit data responses use a different serialization format: warm client response medians were 518,649 B and 222,892 B. Direct development documents were about 686 KB and 375 KB; their largest inline scripts were 545,897 B and 235,175 B.
### Controlled rendering comparison
A temporary diagnostic changed only the rendered box loop to its first two boxes, leaving the fetched full dataset intact. Both comparisons blocked the two background endpoints, used the existing offline worker, and measured five warm direct loads plus 2.5 seconds after visibility. The full loop was restored afterward.
| Measure | All 35 boxes | First 2 boxes only |
| ----------------------------------------------- | -----------: | -----------------: |
| Mounted populated cells | 1,025 | 60 |
| DOM elements | 10,236 | 728 |
| Median time to visible cells | 464 ms | 318 ms |
| Median layout/style work | 63.9 ms | 13.4 ms |
| Median main-thread task time during observation | 1,124 ms | 82.8 ms |
| Median accumulated long-task duration | 147 ms | 0 ms |
This isolates a substantial browser cost from mounting the full view; it does not demonstrate a complete virtualization implementation or guarantee the same production savings. Off-screen spinner components remain mounted in the full view, but this experiment does not separately attribute their cost.
Direct-load layout-shift observations varied (roughly 0.0820.657), with footer/content shifts recorded. Client-click samples recorded zero, partly because recent-input shifts are excluded. These short development observations are not interchangeable with production's Lighthouse CLS of 0.127. Reserve appropriate loading geometry when redesigning rendering.
## Background requests and artwork
[Offline synchronization](../../src/lib/stores/offlineSync.ts) schedules startup after one second and reuses a matching format-2 snapshot younger than 15 minutes. Explicit edits, retry, account changes and reconnect trigger a fresh copy. [The snapshot endpoint](../../src/routes/api/offline-snapshot/+server.ts) loads every owned dex in parallel, including full entry/detail/catch data. For this account that is ten Supabase calls with a fresh token, independent of the page's eight.
A separate local comparison activated the existing offline worker and controlled metadata age in the disposable browser cache. Five warm direct loads per condition:
| Condition | Median visible cells | Snapshot requests per load | Backup requests per load |
| -------------------------------------- | -------------------: | -------------------------: | -----------------------: |
| Fresh snapshot, enabled | 449 ms | 0 | 1 |
| Stale snapshot, enabled | 431 ms | 1 | 1 |
| Stale snapshot, both endpoints blocked | 464 ms | 0 completed | 0 completed |
The stale snapshot was **849,107 B**, typically around 130160 ms locally. It started around 1.2 seconds after navigation, after cells were visible. Backup status began around 0.20.3 seconds, overlapping rendering. Blocking requests did **not** improve time to visible cells consistently in these runs. Thus background work is a secondary bandwidth/CPU/DB contention concern, not a demonstrated explanation of initial local TTFB. An already-running snapshot could overlap a later client navigation; the production HAR cannot establish that.
[Backup status GET](../../src/routes/api/export-integrations/+server.ts) calls `requireAuth`, reads the memoized session, then calls `supabase.auth.setSession(session)`. Instrumentation observed **two `GET /auth/v1/user` requests plus one integration query**. Memoizing `safeGetSession` does not eliminate validation triggered by this separate `setSession` call.
The worker stores snapshot data without automatically fetching all artwork; artwork fetches are cached as viewed, and full artwork download is explicit. The initial dev navigation matrix had no registered worker, so its snapshot requests did not establish cache-reuse behavior; that is why the separate worker-enabled comparison was necessary.
### Preserve detail-image resolution
[Sprite URL resolution](../../src/lib/utils/spriteUrl.ts) selects local assets only when `PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER` is `true`; otherwise it uses GitHub raw URLs. The HAR confirms the latter for production. Local `home/1.webp` and `home/shiny/1.webp` are both 512 × 512. In-memory 128 px WebP experiments at quality 80 reduced 13,530 → 2,726 B and 12,634 → 2,522 B (about 80%). Two samples are not a catalog-wide saving estimate.
**Retain the 512 px originals for the clicked Pokémon detail view.** If pursuing this optimization, introduce separate grid thumbnails and retain full-resolution detail URLs, with fallback coverage for shiny, female and named forms. Update manifest/cache versioning deliberately; replacing assets at existing URLs conflicts with the worker's cache-forever assumption. The sprite build script currently defaults `SPRITE_MAX_SIZE` to zero, so “sprites-small” does not imply smaller dimensions. No sprite files were changed.
## Ranked recommendations
| Priority | Recommended next change | Evidence / confidence | Effort and risk |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 1 | Stop computing an unused count in the page preload; share one ordered scoped-entry retrieval when rows and count are both needed. Combine ownership and scope retrieval where practical. | Confirmed redundant work: one national count or two full scoped queries, plus serial metadata reads. High confidence in work reduction; production milliseconds unknown. | Lowmedium. Preserve ownership/RLS, scope deduplication, named default forms and ordering. |
| 2 | Reduce initial data and the number of mounted boxes together. Evaluate viewport rendering with reserved space, lightweight global totals/order, and on-demand detail data. | Only 60/1,025 cells visible; capped rendering reduced visible time 31%, layout/style work 79%, DOM 93%. Display-only JSON is about 71% smaller. | Mediumhigh. Preserve box numbering, scroll/keyboard access, global filters/counts, bulk edits, navigation races and offline details. Do not just change `9999` to `60`. |
| 3 | Resolve the Netlify buffering constraint as part of the loading design. Validate a supported streaming-capable adapter/runtime in a future deployment, or make the initial response intentionally small without relying on deferred promises. | Installed adapter demonstrably buffers. High confidence in the constraint; no deployed streaming alternative verified. | Medium. Keep Netlify as target; test both document and data navigation. A shell alone is not an interactive grid. |
| 4 | Remove redundant backup-session validation if authentication remains guaranteed; schedule nonessential background work after critical page work while preserving snapshot freshness and explicit syncs. | Three backup calls confirmed; stale snapshot 849 KB. No consistent local first-visibility gain when blocked. | Lowmedium. Verify reconnect status and account isolation; do not disable offline support. |
| 5 | Serve separate grid thumbnails, retaining full-resolution detail artwork. Evaluate first-party hosting/cache headers for those assets. | Two samples about 80% smaller; production HAR sprite transfer 531 KB. | Medium. Preserve all variants and offline cache behavior. Requires separate thumbnail URLs, not destructive resizing. |
| 6 | Replace per-entry linear catch lookup with a map when touching repository joins. | `.find()` per row has quadratic scaling, but current local processing is small. | Low. Lower priority than network, payload and DOM work. |
Do not propose a database index or a region move as an established fix from the available evidence. Production-specific stage instrumentation and region verification remain future work requiring access.
### Regression coverage and secondary findings
[Lighthouse CI](../../lighthouserc.cjs) audits only five signed-out pages using the Node adapter. [Signed-in BDD scenarios](../../tests/bdd/features/performance.feature) allow five seconds for direct load and three seconds per switch, assert first-cell visibility and prohibit a separate entry request. Those checks do not exercise Netlify's response buffering, assert authenticated data/DOM sizes, or distinguish shell, first cells and completed loading.
Future checks should use a full national fixture and a scoped form fixture, measure document and client navigation separately, and track response bytes, mounted cells, first useful view and background request counts. Preserve ordering, overlapping dex deduplication, named default forms, missing catches, filters, bulk status updates, modal notes, shiny/female artwork, account changes and fresh/stale offline behavior. A deliberate loading redesign may require replacing the “no separate entry request” assertion with a user-visible timing/data budget. Deployment checks must exercise actual Netlify responses, not infer parity from Node CI.
The nested `<button>` in [Tooltip](../../src/lib/components/Tooltip.svelte) is confirmed by source inside each Pokémon button. Address its accessible name and invalid nesting in follow-up UI work. Contrast, target-size and missing-meta-description findings are secondary to the performance diagnosis; contrast/target size require rendered theme/mobile verification, while the missing page description is visible in source. Preserve detail-view artwork quality as requested.
## Reproduction and cleanup
Raw captures, disposable credentials and diagnostic scripts are local-only under `/tmp/pokedex-perf-investigation` (directory mode 700); they are not included in the repository evidence. The evidence JSON omits sessions, fixture IDs, personal data and full query filters. The original `dex.har` and prompt remain untouched and untracked.
The seeded stack was already running. Instead of resetting it or invoking Tailwind output generation, the investigation used the project's loopback-checked Supabase environment wrapper and the same Vite dev server used by `dev:supabase`:
```sh
# From the repository root; these diagnostic scripts are retained locally, not installed tooling.
node /tmp/pokedex-perf-investigation/setup.mjs
node scripts/run-with-local-supabase.mjs node /tmp/pokedex-perf-investigation/seed.mjs
node scripts/run-with-local-supabase.mjs node /tmp/pokedex-perf-investigation/auth.mjs
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER=true node scripts/run-with-local-supabase.mjs npx vite dev --host 127.0.0.1 --port 4173 > /tmp/pokedex-perf-investigation/dev.log 2>&1
# In another terminal, after Vite dependency optimization has settled:
node /tmp/pokedex-perf-investigation/measure.mjs
node /tmp/pokedex-perf-investigation/background.mjs
node /tmp/pokedex-perf-investigation/server-probe.mjs
node /tmp/pokedex-perf-investigation/analyze-server.mjs
node /tmp/pokedex-perf-investigation/explain.mjs
node /tmp/pokedex-perf-investigation/catch-plan.mjs
# After stopping the dev server and restoring the instrumented files:
node scripts/run-with-local-supabase.mjs node /tmp/pokedex-perf-investigation/cleanup.mjs
```
The rendering-cap experiment temporarily changed `{#each boxNumbers as boxNumber}` to `{#each boxNumbers.slice(0, 2) as boxNumber}`, then ran `PERF_VARIANT=grid-cap node /tmp/pokedex-perf-investigation/grid-cap.mjs` and restored the file. Run comparisons sequentially, discard the first run and keep viewport/cache/fixture settings equal. The full methodology and sanitized per-run evidence above remain usable if the temporary scripts are later removed.
At completion, original application files were restored byte-for-byte, the investigation server was stopped, and only the dedicated fixture account and its cascading test records were deleted. Existing database data and production configuration were unchanged. No commit was created.
@@ -0,0 +1,60 @@
{
"capturedAt": "2026-09-15T16:28:41.386Z",
"environment": "local-node",
"revision": "local-working-tree",
"clientLocation": "local-loopback",
"groups": [
{
"fixture": "national",
"navigation": "direct",
"samples": 30,
"visibleP75": 123.5,
"interactiveP75": 145.40000009536743,
"responseBytesP75": 248668,
"missingBytes": 0,
"maxDOM": 2088,
"maxCells": 120,
"maxCLS": 0,
"gridRequests": 0
},
{
"fixture": "national",
"navigation": "client",
"samples": 30,
"visibleP75": 495.59999990463257,
"interactiveP75": 494.09999990463257,
"responseBytesP75": 102687,
"missingBytes": 0,
"maxDOM": 2090,
"maxCells": 120,
"maxCLS": 0,
"gridRequests": 0
},
{
"fixture": "scoped-forms",
"navigation": "direct",
"samples": 30,
"visibleP75": 114.5,
"interactiveP75": 133.10000014305115,
"responseBytesP75": 203601,
"missingBytes": 0,
"maxDOM": 2073,
"maxCells": 120,
"maxCLS": 0,
"gridRequests": 0
},
{
"fixture": "scoped-forms",
"navigation": "client",
"samples": 30,
"visibleP75": 491.7000000476837,
"interactiveP75": 490.60000014305115,
"responseBytesP75": 45645,
"missingBytes": 0,
"maxDOM": 2075,
"maxCells": 120,
"maxCLS": 0,
"gridRequests": 0
}
]
}
File diff suppressed because it is too large Load Diff
+1565 -20
View File
File diff suppressed because it is too large Load Diff
+16 -9
View File
@@ -8,12 +8,12 @@
"dev-generate-suppress-w": "GENERATE_SW=true SUPPRESS_WARNING=true npx tailwindcss -i ./static/input.css -o ./static/output.css && vite dev", "dev-generate-suppress-w": "GENERATE_SW=true SUPPRESS_WARNING=true npx tailwindcss -i ./static/input.css -o ./static/output.css && vite dev",
"sprites:build": "node scripts/optimize-sprites.mjs", "sprites:build": "node scripts/optimize-sprites.mjs",
"sprites:manifest": "node scripts/sprite-manifest.mjs", "sprites:manifest": "node scripts/sprite-manifest.mjs",
"build-generate-sw": "npm run tailwind && GENERATE_SW=true vite build", "build-generate-sw": "npm run sprites:grid && npm run tailwind && GENERATE_SW=true vite build",
"build-generate-sw-node": "npm run tailwind && NODE_ADAPTER=true GENERATE_SW=true vite build", "build-generate-sw-node": "npm run sprites:grid && npm run tailwind && NODE_ADAPTER=true GENERATE_SW=true vite build",
"build": "npm run tailwind && vite build", "build": "npm run sprites:grid && npm run tailwind && vite build",
"build-inject-manifest": "npm run tailwind && vite build", "build-inject-manifest": "npm run sprites:grid && npm run tailwind && vite build",
"build-inject-manifest-node": "npm run tailwind && NODE_ADAPTER=true vite build", "build-inject-manifest-node": "npm run sprites:grid && npm run tailwind && NODE_ADAPTER=true vite build",
"build-self-destroying": "npm run tailwind && SELF_DESTROYING_SW=true vite build", "build-self-destroying": "npm run sprites:grid && npm run tailwind && SELF_DESTROYING_SW=true vite build",
"preview": "vite preview --port=4173", "preview": "vite preview --port=4173",
"preview-node": "PORT=4173 node build", "preview-node": "PORT=4173 node build",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
@@ -36,7 +36,7 @@
"test:build:inject-static": "npm run build-inject-manifest && vitest run --config vitest.build.config.mts", "test:build:inject-static": "npm run build-inject-manifest && vitest run --config vitest.build.config.mts",
"test:build:inject-node": "npm run build-inject-manifest-node && NODE_ADAPTER=true vitest run --config vitest.build.config.mts", "test:build:inject-node": "npm run build-inject-manifest-node && NODE_ADAPTER=true vitest run --config vitest.build.config.mts",
"test:build": "npm run test:build:generate-static && npm run test:build:generate-node && npm run test:build:inject-static && npm run test:build:inject-node", "test:build": "npm run test:build:generate-static && npm run test:build:generate-node && npm run test:build:inject-static && npm run test:build:inject-node",
"test:ci": "npm run test:fast && npm run test:integration && npm run test:build && npm run test:bdd", "test:ci": "npm run test:fast && npm run test:integration && npm run test:build && npm run test:bdd && npm run test:performance",
"test": "npm run test:ci", "test": "npm run test:ci",
"supabase:start": "supabase start", "supabase:start": "supabase start",
"supabase:stop": "supabase stop", "supabase:stop": "supabase stop",
@@ -44,12 +44,18 @@
"supabase:studio": "supabase studio", "supabase:studio": "supabase studio",
"migrate:convert-tsv": "node scripts/convert-tsv-to-sql.js", "migrate:convert-tsv": "node scripts/convert-tsv-to-sql.js",
"dev:local": "./scripts/dev-local.sh && npm run dev", "dev:local": "./scripts/dev-local.sh && npm run dev",
"dev:supabase": "supabase start && npm run dev" "dev:supabase": "supabase start && npm run dev",
"sprites:grid": "node scripts/grid-thumbnails.mjs",
"build:cloudflare": "DEPLOY_TARGET=cloudflare npm run build",
"preview:cloudflare": "wrangler dev",
"check:cloudflare": "wrangler deploy --dry-run",
"test:performance": "node scripts/run-with-local-supabase.mjs node scripts/performance/run-local.mjs"
}, },
"devDependencies": { "devDependencies": {
"@lhci/cli": "^0.15.1", "@lhci/cli": "^0.15.1",
"@playwright/test": "1.55.1", "@playwright/test": "1.55.1",
"@sveltejs/adapter-auto": "^3.0.0", "@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/adapter-cloudflare": "7.2.9",
"@sveltejs/adapter-netlify": "^4.1.0", "@sveltejs/adapter-netlify": "^4.1.0",
"@sveltejs/adapter-node": "^2.0.0", "@sveltejs/adapter-node": "^2.0.0",
"@sveltejs/adapter-static": "^3.0.0", "@sveltejs/adapter-static": "^3.0.0",
@@ -77,7 +83,8 @@
"tailwindcss": "^3.4.3", "tailwindcss": "^3.4.3",
"tslib": "^2.6.2", "tslib": "^2.6.2",
"typescript": "^5.3.3", "typescript": "^5.3.3",
"vitest": "^1.0.4" "vitest": "^1.0.4",
"wrangler": "4.131.2"
}, },
"type": "module", "type": "module",
"dependencies": { "dependencies": {
+35
View File
@@ -0,0 +1,35 @@
import { readdir, mkdir, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';
// Bump the URL version whenever dimensions, quality or source artwork changes.
const source = 'static/sprites-small/home';
const destination = 'static/sprites-grid/v1/home';
const files = [];
async function walk(relative = '') {
for (const entry of await readdir(path.join(source, relative), { withFileTypes: true })) {
const name = path.join(relative, entry.name);
if (entry.isDirectory()) await walk(name);
else if (entry.name.endsWith('.webp')) files.push(name);
}
}
await walk();
const manifest = [];
for (const relative of files.sort()) {
const target = path.join(destination, relative);
await mkdir(path.dirname(target), { recursive: true });
try {
await stat(target);
} catch {
await sharp(path.join(source, relative))
.resize(128, 128, { fit: 'inside', withoutEnlargement: true })
.webp({ quality: 80 })
.toFile(target);
}
manifest.push({ path: relative.split(path.sep).join('/'), bytes: (await stat(target)).size });
}
await writeFile(
'static/sprites-grid/v1/manifest.json',
JSON.stringify({ version: 1, width: 128, quality: 80, files: manifest })
);
console.log(`Prepared ${files.length} versioned grid thumbnails; originals preserved.`);
+181
View File
@@ -0,0 +1,181 @@
import { chromium } from '@playwright/test';
import { readFile, writeFile } from 'node:fs/promises';
// Configuration holds session-file paths, never passwords. Keep it outside the repository.
const [configPath, outputPath] = process.argv.slice(2);
if (!configPath || !outputPath)
throw new Error('Usage: node scripts/performance/benchmark.mjs CONFIG.json RESULTS.json');
const config = JSON.parse(await readFile(configPath, 'utf8'));
const samples = config.samples ?? 30;
if (samples < 30)
throw new Error('Host decisions require at least 30 warm samples per fixture/navigation');
if (!config.revision || !config.databaseLabel || !config.clientLocation)
throw new Error('Record revision, databaseLabel and clientLocation for comparable results');
const browser = await chromium.launch();
const results = [];
try {
for (const host of config.hosts) {
for (const fixture of host.fixtures) {
for (const navigation of ['direct', 'client']) {
const context = await browser.newContext({
baseURL: host.url,
storageState: host.storageState,
viewport: { width: 1350, height: 940 },
deviceScaleFactor: 1
});
await context.addInitScript(() => {
window.__perfShifts = [];
new PerformanceObserver((list) => {
for (const entry of list.getEntries())
if (!entry.hadRecentInput)
window.__perfShifts.push({ value: entry.value, time: entry.startTime });
}).observe({ type: 'layout-shift', buffered: true });
window.__watchGrid = () => {
window.__perfVisible = null;
function check() {
const cell = document.querySelector('[data-entry-index]');
if (
location.pathname.startsWith('/pokedex/') &&
cell &&
cell.getBoundingClientRect().top < innerHeight &&
cell.getBoundingClientRect().height > 0
) {
window.__perfVisible = performance.now();
performance.mark('pokedex:first-visible');
} else requestAnimationFrame(check);
}
requestAnimationFrame(check);
};
window.__watchGrid();
});
const page = await context.newPage();
for (let index = 0; index <= samples; index++) {
if (navigation === 'client') {
await page.goto('/my-pokedexes');
await page.getByText(fixture.name, { exact: true }).first().waitFor();
} else if (index > 0) await page.goto('about:blank');
const bodies = [];
const requests = { grid: 0, details: 0, snapshot: 0, backup: 0 };
const onRequest = (request) => {
const path = new URL(request.url()).pathname;
if (/\/pokedexes\/[^/]+\/(grid|combined-data)$/.test(path)) requests.grid++;
if (/\/pokedexes\/[^/]+\/entries\//.test(path)) requests.details++;
if (path === '/api/offline-snapshot') requests.snapshot++;
if (path === '/api/export-integrations') requests.backup++;
};
const onResponse = (response) => {
const path = new URL(response.url()).pathname;
if (!path.startsWith(`/pokedex/${fixture.id}`)) return;
bodies.push(
(async () => {
// Chromium may not expose bodies routed through a service worker.
const body = await response.body().catch(() => null);
return {
url: response.url(),
bytes: body?.length ?? null,
status: response.status(),
fromServiceWorker: response.fromServiceWorker(),
timings: response.request().timing(),
serverTiming: response.headers()['server-timing'] ?? null
};
})()
);
};
page.on('request', onRequest);
page.on('response', onResponse);
let started = 0;
if (navigation === 'direct')
await page.goto(`/pokedex/${fixture.id}`, { waitUntil: 'domcontentloaded' });
else {
started = await page.evaluate(() => {
performance.clearMarks('pokedex:first-interactive');
window.__watchGrid();
return performance.now();
});
await page
.locator('.card')
.filter({ hasText: fixture.name })
.first()
.getByRole('button', { name: 'View', exact: true })
.click();
}
await page.waitForSelector('[data-grid-interactive]');
await page.waitForFunction(
() =>
window.__perfVisible !== null &&
performance.getEntriesByName('pokedex:first-interactive').length > 0
);
await page.waitForTimeout(1500);
const browserData = await page.evaluate(
(start) => ({
visibleMs: window.__perfVisible - start,
interactiveMs:
performance.getEntriesByName('pokedex:first-interactive').at(-1).startTime - start,
cells: document.querySelectorAll('[data-entry-index]').length,
dom: document.querySelectorAll('*').length,
cls: window.__perfShifts
.filter((entry) => entry.time >= start)
.reduce((total, entry) => total + entry.value, 0)
}),
started
);
page.off('request', onRequest);
page.off('response', onResponse);
const resources = await page.evaluate(() =>
performance.getEntriesByType('resource').map((entry) => ({
url: entry.name,
decodedBytes: entry.decodedBodySize,
encodedBytes: entry.encodedBodySize,
transferBytes: entry.transferSize
}))
);
const responses = (await Promise.all(bodies)).map(({ url, ...response }) => {
const resource = resources.findLast((entry) => entry.url === url);
return {
...response,
bytes: response.bytes ?? (resource?.decodedBytes || null),
byteSource: response.bytes !== null ? 'response-body' : 'resource-timing',
encodedBytes: resource?.encodedBytes ?? null,
transferBytes: resource?.transferBytes ?? null
};
});
results.push({
host: host.label,
fixture: fixture.label,
navigation,
run: index === 0 ? 'first-observed' : 'warm',
...browserData,
requests,
responses
});
}
await context.close();
console.log(
`Completed ${host.label}/${fixture.label}/${navigation}: ${samples} warm samples.`
);
}
}
}
await writeFile(
outputPath,
JSON.stringify(
{
version: 1,
capturedAt: new Date().toISOString(),
revision: config.revision,
databaseLabel: config.databaseLabel,
clientLocation: config.clientLocation,
environment: config.environment ?? 'deployed',
compatibilityPassed: config.compatibilityPassed ?? false,
results
},
null,
2
)
);
console.log(
`Recorded ${results.length} samples; first-observed runs are excluded from warm statistics.`
);
} finally {
await browser.close();
}
+46
View File
@@ -0,0 +1,46 @@
import { readFile } from 'node:fs/promises';
const data = JSON.parse(await readFile(process.argv[2], 'utf8'));
const warm = data.results.filter((row) => row.run === 'warm');
const p75 = (values) => [...values].sort((a, b) => a - b)[Math.ceil(values.length * 0.75) - 1];
const groups = [...new Set(warm.map((row) => `${row.fixture}/${row.navigation}`))];
const paired = groups.map((group) => {
const rows = (host) =>
warm.filter((row) => `${row.fixture}/${row.navigation}` === group && row.host === host);
for (const host of ['netlify', 'cloudflare'])
if (rows(host).length < 30) throw new Error(`Insufficient ${host} warm samples for ${group}`);
return {
group,
netlify: p75(rows('netlify').map((row) => row.interactiveMs)),
cloudflare: p75(rows('cloudflare').map((row) => row.interactiveMs))
};
});
if (groups.length !== 4)
throw new Error(
'Expected national and scoped-form fixtures, each with direct and client navigation'
);
const netlify = p75(warm.filter((row) => row.host === 'netlify').map((row) => row.interactiveMs));
const cloudflare = p75(
warm.filter((row) => row.host === 'cloudflare').map((row) => row.interactiveMs)
);
const improvement = netlify - cloudflare;
const passes =
improvement >= 200 &&
improvement / netlify >= 0.2 &&
paired.every((row) => row.cloudflare <= row.netlify * 1.1);
console.log(
JSON.stringify(
{
overallP75: { netlify, cloudflare },
improvementMs: improvement,
improvementPercent: (100 * improvement) / netlify,
groups: paired,
performanceGatePassed: passes,
recommendation:
passes && data.compatibilityPassed && data.environment === 'deployed'
? 'Cloudflare qualifies for a migration proposal; review operating cost before cutover.'
: 'Retain Netlify: performance, deployed evidence or compatibility gate is unmet.'
},
null,
2
)
);
+113
View File
@@ -0,0 +1,113 @@
import { createClient } from '@supabase/supabase-js';
import { createServerClient } from '@supabase/ssr';
import { mkdir, readFile, writeFile, unlink } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
const directory = process.env.PERF_FIXTURE_DIR ?? '/tmp/livingdex-grid-performance';
const url = process.env.PUBLIC_SUPABASE_URL;
if (!url || !['localhost', '127.0.0.1', '[::1]'].includes(new URL(url).hostname))
throw new Error('Fixtures require the local Supabase wrapper');
const admin = createClient(url, process.env.SUPABASE_SERVICE_ROLE_KEY, {
auth: { persistSession: false }
});
const check = ({ data, error }) => {
if (error) throw error;
return data;
};
await mkdir(directory, { recursive: true, mode: 0o700 });
const fixturePath = `${directory}/fixture.json`;
if (process.argv.includes('--cleanup')) {
const fixture = JSON.parse(await readFile(fixturePath, 'utf8'));
const { user } = check(await admin.auth.admin.getUserById(fixture.userId));
if (user.email !== fixture.email || !user.email.startsWith('grid-performance-'))
throw new Error('Refusing to remove a non-fixture account');
check(await admin.auth.admin.deleteUser(fixture.userId));
await unlink(fixturePath);
await unlink(`${directory}/storage-state.json`).catch(() => {});
console.log('Removed disposable performance account and session.');
process.exit(0);
}
try {
await readFile(fixturePath);
throw new Error('An existing fixture needs cleanup first');
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
const email = `grid-performance-${randomUUID()}@example.test`;
const password = randomUUID() + 'aA1!';
const { user } = check(await admin.auth.admin.createUser({ email, password, email_confirm: true }));
const fixture = { userId: user.id, email, password, dexes: [] };
await writeFile(fixturePath, JSON.stringify(fixture), { mode: 0o600 });
fixture.dexes = check(
await admin
.from('pokedexes')
.insert([
{ userId: user.id, name: 'Performance National', isLivingDex: true, isFormDex: false },
{
userId: user.id,
name: 'Performance Scarlet Forms',
isLivingDex: true,
isFormDex: true,
gameScope: 'Scarlet'
}
])
.select()
);
const game = fixture.dexes.find((dex) => dex.gameScope);
check(
await admin.from('pokedex_dex_scopes').insert({ pokedexId: game.id, dexId: 'scarlet-paldea' })
);
const entries = [];
for (let from = 0; ; from += 1000) {
const page = check(
await admin
.from('pokemon')
.select('id,isDefaultForm')
.order('id')
.range(from, from + 999)
);
entries.push(...page);
if (page.length < 1000) break;
}
for (const dex of fixture.dexes) {
const selected = entries.filter((entry) => dex.isFormDex || entry.isDefaultForm);
for (let from = 0; from < selected.length; from += 500) {
check(
await admin.from('catch_records').insert(
selected.slice(from, from + 500).map((entry, index) => ({
userId: user.id,
pokedexId: dex.id,
pokemonId: entry.id,
caught: (from + index) % 3 === 0,
haveToEvolve: (from + index) % 3 === 1,
inHome: (from + index) % 7 === 0,
personalNotes: index === 0 ? 'Performance fixture note: preserve me' : ''
}))
)
);
}
}
await writeFile(fixturePath, JSON.stringify(fixture), { mode: 0o600 });
const cookies = [];
const client = createServerClient(url, process.env.PUBLIC_SUPABASE_ANON_KEY, {
cookies: { getAll: () => [], setAll: (values) => cookies.push(...values) }
});
check(await client.auth.signInWithPassword({ email, password }));
const base = new URL(process.env.PERF_BASE_URL ?? 'http://127.0.0.1:4173');
await writeFile(
`${directory}/storage-state.json`,
JSON.stringify({
cookies: cookies.map(({ name, value }) => ({
name,
value,
domain: base.hostname,
path: '/',
httpOnly: false,
secure: base.protocol === 'https:',
sameSite: 'Lax'
})),
origins: []
}),
{ mode: 0o600 }
);
console.log('Prepared national and scoped-form fixtures and a private browser session.');
+105
View File
@@ -0,0 +1,105 @@
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, cp, rm, readFile, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
const directory = await mkdtemp(path.join(os.tmpdir(), 'livingdex-grid-tests-'));
const port = process.env.PERF_PORT ?? '4185';
const env = {
...process.env,
NODE_ADAPTER: 'true',
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER: 'true',
POKEDEX_PERFORMANCE: 'true',
PERF_FIXTURE_DIR: directory,
PERF_BASE_URL: `http://127.0.0.1:${port}`,
PORT: port,
HOST: '127.0.0.1'
};
function run(command, args) {
return new Promise((resolve, reject) => {
const process = spawn(command, args, { env, stdio: 'inherit' });
process.once('error', reject);
process.once('exit', (code) =>
code === 0 ? resolve() : reject(new Error(`${command} failed (${code})`))
);
});
}
let server;
let fixture = false;
try {
await run('npm', ['run', 'build-inject-manifest-node']);
fixture = true;
await run('node', ['scripts/performance/fixture.mjs']);
server = spawn('node', ['build'], { env, stdio: 'inherit' });
await new Promise((resolve, reject) => {
const timer = setInterval(async () => {
try {
if ((await fetch(env.PERF_BASE_URL)).ok) {
clearInterval(timer);
clearTimeout(timeout);
resolve();
}
} catch {}
}, 200);
const timeout = setTimeout(() => {
clearInterval(timer);
reject(new Error('Local production server did not start'));
}, 15000);
server.once('error', (error) => {
clearInterval(timer);
clearTimeout(timeout);
reject(error);
});
server.once('exit', (code) => {
clearInterval(timer);
clearTimeout(timeout);
reject(new Error(`Local server exited (${code})`));
});
});
if (process.env.PERF_BENCHMARK === 'true') {
const data = JSON.parse(await readFile(path.join(directory, 'fixture.json'), 'utf8'));
await writeFile(
path.join(directory, 'benchmark-config.json'),
JSON.stringify({
samples: 30,
revision: process.env.PERF_REVISION ?? 'local-working-tree',
databaseLabel: 'local-seeded-supabase',
clientLocation: 'local-loopback',
environment: 'local-node',
hosts: [
{
label: 'node',
url: env.PERF_BASE_URL,
storageState: path.join(directory, 'storage-state.json'),
fixtures: data.dexes.map((dex) => ({
id: dex.id,
name: dex.name,
label: dex.gameScope ? 'scoped-forms' : 'national'
}))
}
]
})
);
await run('node', [
'scripts/performance/benchmark.mjs',
path.join(directory, 'benchmark-config.json'),
path.join(directory, 'benchmark.json')
]);
await mkdir('test-results/performance', { recursive: true });
await cp(path.join(directory, 'benchmark.json'), 'test-results/performance/benchmark.json');
}
await run('node', ['scripts/performance/verify.mjs']);
await run('node', ['scripts/performance/verify-behavior.mjs']);
await mkdir('test-results/performance', { recursive: true });
for (const file of ['verification.json', 'behavior.json', 'national.png', 'scoped.png'])
await cp(path.join(directory, file), path.join('test-results/performance', file));
} finally {
server?.kill('SIGTERM');
if (fixture)
await run('node', ['scripts/performance/fixture.mjs', '--cleanup']).catch((error) => {
throw new Error(`Fixture cleanup failed; retained recovery files in ${directory}`, {
cause: error
});
});
await rm(directory, { recursive: true, force: true });
}
+165
View File
@@ -0,0 +1,165 @@
import { chromium } from '@playwright/test';
import { readFile, writeFile } from 'node:fs/promises';
import assert from 'node:assert/strict';
const dir = process.env.PERF_FIXTURE_DIR ?? '/tmp/livingdex-grid-performance';
const fixture = JSON.parse(await readFile(`${dir}/fixture.json`, 'utf8'));
const browser = await chromium.launch();
const context = await browser.newContext({
baseURL: process.env.PERF_BASE_URL ?? 'http://127.0.0.1:4173',
storageState: `${dir}/storage-state.json`,
viewport: { width: 1350, height: 940 }
});
await context.addInitScript(() => {
window.__cls = 0;
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) if (!entry.hadRecentInput) window.__cls += entry.value;
}).observe({ type: 'layout-shift', buffered: true });
});
const page = await context.newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const national = fixture.dexes.find((dex) => !dex.gameScope);
const scoped = fixture.dexes.find((dex) => dex.gameScope);
const results = [];
try {
await page.goto(`/pokedex/${national.id}`);
await page.waitForSelector('[data-grid-interactive]');
for (const width of [1350, 390]) {
await page.setViewportSize({ width, height: 940 });
for (const density of ['comfortable', 'compact', 'ultra']) {
await page.getByLabel('Choose box view layout density').selectOption(density);
await page.reload();
await page.waitForSelector('[data-grid-interactive]');
await page.waitForTimeout(350);
assert.equal(await page.getByLabel('Choose box view layout density').inputValue(), density);
const geometry = await page.evaluate(() => {
const cell = document.querySelector('[data-entry-index="0"]').getBoundingClientRect();
const shell = document.querySelector('[data-box-number="1"]').getBoundingClientRect();
return {
cellWidth: cell.width,
cellHeight: cell.height,
cls: window.__cls,
horizontalOverflow: document.documentElement.scrollWidth > innerWidth,
shellHeight: shell.height
};
});
assert.ok(Math.abs(geometry.cellWidth - geometry.cellHeight) < 1, JSON.stringify(geometry));
assert.ok(!geometry.horizontalOverflow, `Horizontal overflow at ${width}/${density}`);
assert.ok(geometry.cls <= 0.1, `CLS ${geometry.cls} at ${width}/${density}`);
results.push({ width, density, ...geometry });
}
}
await page.setViewportSize({ width: 1350, height: 940 });
await page.getByLabel('Choose box view layout density').selectOption('comfortable');
await page.getByLabel('Not caught', { exact: true }).check();
assert.equal(await page.locator('[data-entry-index="0"]').getAttribute('aria-disabled'), 'true');
assert.equal(await page.locator('[data-entry-index="0"]').getAttribute('data-entry-id'), '1');
await page.getByLabel('Not caught', { exact: true }).uncheck();
// Resizing across the mobile breakpoint keeps the same box at the scroll anchor.
await page.locator('[data-box-number="15"]').evaluate((node) => node.scrollIntoView());
await page.waitForTimeout(100);
const anchorTop = await page
.locator('[data-box-number="15"]')
.evaluate((node) => node.getBoundingClientRect().top);
await page.setViewportSize({ width: 390, height: 940 });
await page.waitForTimeout(200);
const resizedTop = await page
.locator('[data-box-number="15"]')
.evaluate((node) => node.getBoundingClientRect().top);
assert.ok(
Math.abs(anchorTop - resizedTop) < 2,
`Scroll anchor moved: ${anchorTop} to ${resizedTop}`
);
await page.setViewportSize({ width: 1350, height: 940 });
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForSelector('[data-entry-index="1024"]');
assert.ok((await page.locator('[data-entry-index]').count()) < 300);
await page.locator('[data-entry-index="1024"]').focus();
await page.keyboard.press('ArrowRight');
assert.equal(
await page.evaluate(() => document.activeElement.getAttribute('data-entry-index')),
'1024'
);
await page.evaluate(() => window.scrollTo(0, 0));
await page.waitForSelector('[data-entry-index="0"]');
// Closing an in-flight modal must prevent its response from replacing the next selection.
let release;
const held = new Promise((resolve) => {
release = resolve;
});
await page.route(`**/api/pokedexes/${national.id}/entries/1`, async (route) => {
await held;
await route.continue().catch(() => {});
});
await page.locator('[data-entry-index="0"]').click();
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
await page.locator('[data-entry-index="1"]').click();
release();
await page.getByRole('dialog').getByLabel('Notes:', { exact: true }).waitFor();
assert.equal(
await page.getByRole('dialog').getByRole('heading', { name: 'Ivysaur', exact: true }).count(),
1
);
assert.equal(
await page.getByRole('dialog').getByRole('heading', { name: 'Bulbasaur', exact: true }).count(),
0
);
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
await page.unrouteAll({ behavior: 'wait' });
// Navigate through actual list cards, preserving fixture-specific totals and positions.
await page.getByRole('link', { name: 'My Pokédexes' }).click();
await page
.locator('.card')
.filter({ hasText: scoped.name })
.first()
.getByRole('button', { name: 'View', exact: true })
.click();
await page.waitForSelector('[data-grid-interactive]');
assert.ok((await page.locator('body').innerText()).includes('Showing 439 of 439'));
await page.goBack();
await page
.locator('.card')
.filter({ hasText: national.name })
.first()
.getByRole('button', { name: 'View', exact: true })
.click();
await page.waitForSelector('[data-grid-interactive]');
// Wait for the existing worker's full snapshot, then read an uncached detail without a network.
await page.waitForFunction(
async () => {
const meta = await (
await caches.open('livingdex-offline-meta-v1')
).match('/__offline/current');
return !!(await meta?.json())?.dataCache;
},
{ timeout: 15000 }
);
await context.setOffline(true);
await page.locator('[data-entry-index="5"]').click();
await page.waitForFunction(() =>
document.querySelector('[role="dialog"]')?.textContent.includes('Where to catch:')
);
assert.equal(await page.getByRole('dialog').locator('textarea').count(), 0);
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
// A mismatched cache owner is never used as fallback.
await page.evaluate(async () => {
const cache = await caches.open('livingdex-offline-meta-v1');
const response = await cache.match('/__offline/current');
const meta = await response.json();
await cache.put(
'/__offline/current',
new Response(JSON.stringify({ ...meta, userId: 'other-account' }))
);
});
await page.locator('[data-entry-index="6"]').click();
await page.getByRole('alert').filter({ hasText: 'not saved for offline use' }).waitFor();
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
assert.deepEqual(errors, []);
await writeFile(`${dir}/behavior.json`, JSON.stringify(results, null, 2));
console.log(
'Passed density/mobile geometry, filtered placement, virtual boundaries, modal races, client navigation and isolated offline details.'
);
console.log(JSON.stringify(results, null, 2));
} finally {
await browser.close();
}
+129
View File
@@ -0,0 +1,129 @@
import { chromium } from '@playwright/test';
import { readFile, writeFile } from 'node:fs/promises';
import assert from 'node:assert/strict';
const directory = process.env.PERF_FIXTURE_DIR ?? '/tmp/livingdex-grid-performance';
const fixture = JSON.parse(await readFile(`${directory}/fixture.json`, 'utf8'));
const baseURL = process.env.PERF_BASE_URL ?? 'http://127.0.0.1:4173';
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
baseURL,
storageState: `${directory}/storage-state.json`,
viewport: { width: 1350, height: 940 }
});
await context.addInitScript(() => {
window.__layoutShifts = [];
window.__firstVisible = null;
new PerformanceObserver((list) => {
for (const entry of list.getEntries())
if (!entry.hadRecentInput) window.__layoutShifts.push(entry.value);
}).observe({ type: 'layout-shift', buffered: true });
function visible() {
const cell = document.querySelector('[data-entry-index]');
if (
cell &&
cell.getBoundingClientRect().height > 0 &&
cell.getBoundingClientRect().top < innerHeight
)
window.__firstVisible ??= performance.now();
if (window.__firstVisible === null) requestAnimationFrame(visible);
}
requestAnimationFrame(visible);
});
const page = await context.newPage();
const readJson = (path) =>
page.evaluate(async (path) => {
const response = await fetch(path);
if (!response.ok) throw new Error(`Fixture API failed: ${response.status}`);
return response.json();
}, path);
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const requests = [];
page.on('request', (request) => requests.push(new URL(request.url()).pathname));
const results = [];
try {
for (const dex of fixture.dexes) {
requests.length = 0;
const response = await page.goto(`/pokedex/${dex.id}`);
assert.equal(response.status(), 200);
const html = await response.text();
assert.ok(/data-entry-index=["']?0["'\s>]/.test(html), 'Initial cells must be server rendered');
await page.waitForSelector('[data-grid-interactive]');
await page.waitForTimeout(1000);
const stats = await page.evaluate(() => ({
cells: document.querySelectorAll('[data-entry-index]').length,
dom: document.querySelectorAll('*').length,
cls: window.__layoutShifts.reduce((sum, value) => sum + value, 0),
firstVisible: window.__firstVisible,
interactive: performance.getEntriesByName('pokedex:first-interactive').at(-1)?.startTime
}));
assert.ok(stats.cells <= 180, `Mounted cells: ${stats.cells}`);
assert.ok(stats.dom < 2500, `DOM elements: ${stats.dom}`);
assert.ok(stats.cls <= 0.1, `CLS: ${stats.cls}`);
assert.equal(
requests.filter((path) => /\/api\/pokedexes\/[^/]+\/(grid|combined-data)$/.test(path)).length,
0
);
assert.equal(await page.locator('button button').count(), 0);
await page.screenshot({ path: `${directory}/${dex.gameScope ? 'scoped' : 'national'}.png` });
const first = page.locator('[data-entry-index="0"]');
const entryId = await first.getAttribute('data-entry-id');
const notes = await readJson(`/api/pokedexes/${dex.id}/entries/${entryId}`);
await first.click();
const modal = page.getByRole('dialog', { name: 'Pokémon details' });
await modal.getByLabel('Notes:', { exact: true }).waitFor();
assert.equal(
await modal.getByLabel('Notes:', { exact: true }).inputValue(),
notes.catchRecord.personalNotes
);
const image = modal.locator('img').first();
await image.waitFor();
await page.waitForFunction(
() => document.querySelector('[role="dialog"] img')?.naturalWidth > 0
);
assert.equal(await image.evaluate((node) => node.naturalWidth), 512);
assert.ok(!(await image.getAttribute('src')).includes('sprites-grid'));
await modal.getByRole('button', { name: 'Close', exact: true }).click();
assert.equal(await first.evaluate((node) => document.activeElement === node), true);
// Reopening uses cached details; bulk edits must retain the unloaded personal notes.
const detailCalls = () =>
requests.filter((path) => path.endsWith(`/entries/${entryId}`)).length;
const before = detailCalls();
await first.click();
await modal.getByLabel('Notes:', { exact: true }).waitFor();
assert.equal(detailCalls(), before);
await modal.getByRole('button', { name: 'Close', exact: true }).click();
await page.getByRole('button', { name: 'Open bulk actions menu' }).first().click();
await page.getByRole('button', { name: 'Mark box as In HOME', exact: true }).click();
await page.waitForResponse(
(r) =>
r.url().endsWith(`/pokedexes/${dex.id}/catch-records`) && r.request().method() === 'POST'
);
const after = await readJson(`/api/pokedexes/${dex.id}/entries/${entryId}`);
assert.equal(after.catchRecord.personalNotes, notes.catchRecord.personalNotes);
assert.equal(after.catchRecord.inHome, true);
// Focus navigation must reach entries that were not initially mounted.
await page.locator('[data-entry-index="29"]').focus();
for (let index = 0; index < 22; index++) await page.keyboard.press('ArrowDown');
assert.equal(
await page.evaluate(() => document.activeElement?.getAttribute('data-entry-index')),
'161'
);
await page.getByLabel('Render all boxes').check();
const grid = await readJson(`/api/pokedexes/${dex.id}/grid`);
assert.equal(await page.locator('[data-entry-index]').count(), grid.grid.length);
await page.getByLabel('Render all boxes').uncheck();
results.push({
fixture: dex.gameScope ? 'scoped-forms' : 'national',
...stats,
documentBytes: Buffer.byteLength(html),
gridBytes: Buffer.byteLength(JSON.stringify(grid))
});
}
assert.deepEqual(errors, [], 'Browser errors');
await writeFile(`${directory}/verification.json`, JSON.stringify(results, null, 2));
console.log(JSON.stringify(results, null, 2));
} finally {
await browser.close();
}
+1
View File
@@ -13,6 +13,7 @@ declare global {
// interface Error {} // interface Error {}
interface Locals { interface Locals {
supabase: SupabaseClient; supabase: SupabaseClient;
pokedexAuthMs?: number;
safeGetSession(): Promise<{ session: Session | null; user: User | null }>; safeGetSession(): Promise<{ session: Session | null; user: User | null }>;
userid: string; userid: string;
buildDate: string; buildDate: string;
+3
View File
@@ -30,17 +30,20 @@ export const handle: Handle = async ({ event, resolve }) => {
let sessionPromise: ReturnType<App.Locals['safeGetSession']> | null = null; let sessionPromise: ReturnType<App.Locals['safeGetSession']> | null = null;
event.locals.safeGetSession = () => { event.locals.safeGetSession = () => {
sessionPromise ??= (async () => { sessionPromise ??= (async () => {
const authStarted = performance.now();
const { const {
data: { user }, data: { user },
error error
} = await event.locals.supabase.auth.getUser(); } = await event.locals.supabase.auth.getUser();
if (error) { if (error) {
event.locals.pokedexAuthMs = performance.now() - authStarted;
return { session: null, user: null }; return { session: null, user: null };
} }
const { const {
data: { session } data: { session }
} = await event.locals.supabase.auth.getSession(); } = await event.locals.supabase.auth.getSession();
event.locals.pokedexAuthMs = performance.now() - authStarted;
return { session, user }; return { session, user };
})(); })();
return sessionPromise; return sessionPromise;
+39 -10
View File
@@ -1,7 +1,40 @@
<script lang="ts"> <script lang="ts">
import { PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER } from '$env/static/public'; import { PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER } from '$env/static/public';
import { inView } from '$lib/actions/inView'; import { inView } from '$lib/actions/inView';
import { resolveSpriteUrl } from '$lib/utils/spriteUrl'; import { resolveSpriteUrl, resolveGridSpriteUrl } from '$lib/utils/spriteUrl';
export let variant: 'detail' | 'grid' = 'detail';
let failedPaths = new Set<string>();
let fallbackIndex = 0;
let candidates: string[] = [];
$: {
const entry = { pokedexNumber: Number(pokedexNumber), form, spriteKey };
const full = resolveSpriteUrl(
entry,
!!shiny,
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER === 'true'
);
candidates = [
...new Set([
...(variant === 'grid' ? [resolveGridSpriteUrl(entry, !!shiny)] : []),
full,
resolveSpriteUrl(
{ ...entry, form: form?.replace(/^female[-\s]*/i, '') },
!!shiny,
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER === 'true'
),
resolveSpriteUrl(
{ pokedexNumber: Number(pokedexNumber) },
!!shiny,
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER === 'true'
)
])
];
fallbackIndex = candidates.findIndex((url) => !failedPaths.has(url));
}
function imageFailed() {
failedPaths = new Set([...failedPaths, imagePath!]);
}
export let pokemonName: string; export let pokemonName: string;
export let pokedexNumber: string | number; export let pokedexNumber: string | number;
@@ -21,14 +54,9 @@
form form
}); });
} }
imagePath = resolveSpriteUrl(
{ pokedexNumber: Number(pokedexNumber), form, spriteKey },
!!shiny,
PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER === 'true'
);
} }
$: imagePath = candidates[fallbackIndex] ?? null;
$: if (loadingStrategy !== 'inView') { $: if (loadingStrategy !== 'inView') {
isInView = true; isInView = true;
} }
@@ -50,16 +78,17 @@
}} }}
> >
{#if loadingStrategy === 'inView' && !isInView} {#if loadingStrategy === 'inView' && !isInView}
<span class="loading loading-spinner loading-xs"></span> <span class="inline-block w-full h-full" aria-hidden="true"></span>
{:else} {:else}
<img <img
src={imagePath} src={imagePath}
alt="sprite" alt=""
on:error={imageFailed}
loading={loadingStrategy === 'lazy' ? 'lazy' : 'eager'} loading={loadingStrategy === 'lazy' ? 'lazy' : 'eager'}
decoding="async" decoding="async"
/> />
{/if} {/if}
</span> </span>
{:else} {:else}
<span class="loading loading-spinner loading-xs"></span> <span class="inline-block w-full h-full" aria-hidden="true"></span>
{/if} {/if}
@@ -38,9 +38,9 @@
value: string | CatchInformationItem value: string | CatchInformationItem
): value is CatchInformationItem => typeof value !== 'string'; ): value is CatchInformationItem => typeof value !== 'string';
function updateCatchRecord(source: UpdateCatchSource) { function updateCatchRecord(source: UpdateCatchSource, changes?: Partial<CatchRecord>) {
if (readOnly) return; if (readOnly) return;
dispatch('updateCatch', { pokedexEntry, catchRecord, source }); dispatch('updateCatch', { pokedexEntry, catchRecord, source, changes });
} }
function onCaughtChange() { function onCaughtChange() {
@@ -50,7 +50,10 @@
if (catchRecord.caught) { if (catchRecord.caught) {
catchRecord.haveToEvolve = false; catchRecord.haveToEvolve = false;
} }
updateCatchRecord('toggle'); updateCatchRecord('toggle', {
caught: catchRecord.caught,
haveToEvolve: catchRecord.haveToEvolve
});
} }
function onNeedsToEvolveChange() { function onNeedsToEvolveChange() {
@@ -60,7 +63,10 @@
if (catchRecord.haveToEvolve) { if (catchRecord.haveToEvolve) {
catchRecord.caught = false; catchRecord.caught = false;
} }
updateCatchRecord('toggle'); updateCatchRecord('toggle', {
caught: catchRecord.caught,
haveToEvolve: catchRecord.haveToEvolve
});
} }
</script> </script>
@@ -154,7 +160,7 @@
type="checkbox" type="checkbox"
bind:checked={catchRecord.inHome} bind:checked={catchRecord.inHome}
class="checkbox checkbox-primary" class="checkbox checkbox-primary"
on:change={() => updateCatchRecord('toggle')} on:change={() => updateCatchRecord('toggle', { inHome: catchRecord?.inHome })}
/> />
</label> </label>
</div> </div>
@@ -168,7 +174,8 @@
type="checkbox" type="checkbox"
bind:checked={catchRecord.hasGigantamaxed} bind:checked={catchRecord.hasGigantamaxed}
class="checkbox checkbox-primary" class="checkbox checkbox-primary"
on:change={() => updateCatchRecord('toggle')} on:change={() =>
updateCatchRecord('toggle', { hasGigantamaxed: catchRecord?.hasGigantamaxed })}
/> />
</label> </label>
</div> </div>
+39 -8
View File
@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { onMount, onDestroy } from 'svelte'; import { onMount } from 'svelte';
export let isOpen: boolean; export let isOpen: boolean;
export let onClose: () => void; export let onClose: () => void;
@@ -14,24 +14,55 @@
} }
} }
let dialog: HTMLDivElement;
onMount(() => { onMount(() => {
window.addEventListener('keydown', handleKeyDown); const previous = document.activeElement as HTMLElement | null;
}); const close = dialog.querySelector<HTMLButtonElement>('.close-button');
close?.focus();
onDestroy(() => { const trapFocus = (event: KeyboardEvent) => {
window.removeEventListener('keydown', handleKeyDown); handleKeyDown(event);
if (event.key !== 'Tab') return;
const nodes = Array.from(
dialog.querySelectorAll<HTMLElement>(
'button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href]'
)
).filter((node) => node.getClientRects().length);
const first = nodes[0],
last = nodes.at(-1);
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last?.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first?.focus();
}
};
window.addEventListener('keydown', trapFocus);
return () => {
window.removeEventListener('keydown', trapFocus);
if (previous?.isConnected) previous.focus();
};
}); });
</script> </script>
{#if isOpen} {#if isOpen}
<div class="modal modal-open" role="dialog" aria-modal="true"> <div
bind:this={dialog}
class="modal modal-open"
role="dialog"
aria-label="Pokémon details"
aria-modal="true"
>
<div class="modal-box-custom bg-primary text-primary-content"> <div class="modal-box-custom bg-primary text-primary-content">
<button class="close-button" on:click={onClose} aria-label="Close"></button> <button data-offline-action class="close-button" on:click={onClose} aria-label="Close">
</button>
<div class="modal-content"> <div class="modal-content">
<slot /> <slot />
</div> </div>
</div> </div>
<button <button
data-offline-action
type="button" type="button"
class="modal-backdrop bg-black/50" class="modal-backdrop bg-black/50"
aria-label="Close modal" aria-label="Close modal"
@@ -1,15 +1,109 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount, tick } from 'svelte';
import type { CatchRecord } from '$lib/models/CatchRecord';
import type { CombinedData } from '$lib/models/CombinedData';
import type { SharedCatchStatus, SharedCombinedData } from '$lib/models/SharedPokedex';
import { calculateBoxPlacement } from '$lib/utils/boxPlacement'; import { calculateBoxPlacement } from '$lib/utils/boxPlacement';
import PokemonSprite from '$lib/components/PokemonSprite.svelte'; import PokemonSprite from '$lib/components/PokemonSprite.svelte';
import Tooltip from '$lib/components/Tooltip.svelte'; import type { SharedCombinedData } from '$lib/models/SharedPokedex';
import type { PokedexGridRow } from '$lib/models/PokedexGridRow';
import { markGridInteractive } from '$lib/utils/criticalPageWork';
export let virtualize = false;
export let retryLoad: (() => void) | null = null;
let renderAll = false;
let visibleBoxes = new Set([1, 2, 3, 4]);
let focusedBox: number | null = null;
let grid: HTMLDivElement;
const shells = new Map<number, HTMLElement>();
let viewportFrame = 0;
let mounted = false;
export let gridKey = '';
let markedKey: string | null = null;
let scrollAnchor: { number: number; top: number } | null = null;
function measureViewport() {
viewportFrame = 0;
const next = new Set<number>();
scrollAnchor = null;
for (const [number, node] of shells) {
const rect = node.getBoundingClientRect();
if (!scrollAnchor && rect.bottom > 0) scrollAnchor = { number, top: rect.top };
const overscan = rect.height + 16;
if (rect.bottom >= -overscan && rect.top <= window.innerHeight + overscan) next.add(number);
}
visibleBoxes = next;
}
function resizeViewport() {
if (scrollAnchor && window.scrollY > 0) {
const node = shells.get(scrollAnchor.number);
if (node) window.scrollBy(0, node.getBoundingClientRect().top - scrollAnchor.top);
}
scheduleViewport();
}
function trackFocus(event: FocusEvent) {
const target = event.target instanceof Element ? event.target : null;
if (!target?.closest('[data-box-number], [role="dialog"]')) focusedBox = null;
}
function scheduleViewport() {
if (!viewportFrame) viewportFrame = requestAnimationFrame(measureViewport);
}
function boxShell(node: HTMLElement, number: number) {
shells.set(number, node);
scheduleViewport();
return {
destroy() {
shells.delete(number);
}
};
}
async function focusEntry(index: number) {
if (!combinedData || index < 0 || index >= combinedData.length) return;
focusedBox = Math.floor(index / 30) + 1;
await tick();
grid.querySelector<HTMLElement>(`[data-entry-index="${index}"]`)?.focus();
}
function navigateEntry(event: KeyboardEvent, index: number) {
const offset = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -6, ArrowDown: 6 }[event.key];
if (offset !== undefined) {
event.preventDefault();
void focusEntry(index + offset);
} else if (event.key === 'Tab') {
const next = index + (event.shiftKey ? -1 : 1);
if (
next >= 0 &&
next < (combinedData?.length ?? 0) &&
!grid.querySelector(`[data-entry-index="${next}"]`)
) {
event.preventDefault();
void focusEntry(next);
}
}
}
$: if (mounted && combinedData && gridKey !== markedKey) {
markedKey = gridKey;
grid?.removeAttribute('data-grid-interactive');
void tick().then(() => {
if (virtualize) markGridInteractive();
});
}
onMount(() => {
mounted = true;
const observer = new ResizeObserver(resizeViewport);
if (grid) observer.observe(grid);
window.addEventListener('scroll', scheduleViewport, { passive: true });
window.addEventListener('resize', resizeViewport);
window.addEventListener('focusin', trackFocus);
measureViewport();
return () => {
observer.disconnect();
cancelAnimationFrame(viewportFrame);
window.removeEventListener('scroll', scheduleViewport);
window.removeEventListener('resize', resizeViewport);
window.removeEventListener('focusin', trackFocus);
};
});
export let showShiny = false; export let showShiny = false;
type DisplayData = CombinedData | SharedCombinedData; type DisplayData = PokedexGridRow | SharedCombinedData;
type DisplayStatus = CatchRecord | SharedCatchStatus | null; type DisplayStatus = DisplayData['catchRecord'];
export let combinedData: DisplayData[] | null; export let combinedData: DisplayData[] | null;
export let readOnly = false; export let readOnly = false;
@@ -119,21 +213,21 @@
const BOX_VIEW_LAYOUT_STORAGE_KEY = 'livingdex:boxViewLayout:v1'; const BOX_VIEW_LAYOUT_STORAGE_KEY = 'livingdex:boxViewLayout:v1';
type BoxViewLayout = 'comfortable' | 'compact' | 'ultra'; type BoxViewLayout = 'comfortable' | 'compact' | 'ultra';
let boxViewLayout: BoxViewLayout = 'comfortable'; export let initialLayout: BoxViewLayout = 'comfortable';
let boxViewLayout: BoxViewLayout = initialLayout;
onMount(() => {
try {
const stored = localStorage.getItem(BOX_VIEW_LAYOUT_STORAGE_KEY);
if (stored === 'comfortable' || stored === 'compact' || stored === 'ultra') {
boxViewLayout = stored;
}
} catch {
// ignore (privacy mode / disabled storage)
}
});
function persistBoxViewLayout(next: BoxViewLayout) { function persistBoxViewLayout(next: BoxViewLayout) {
const anchor = [...shells.entries()].find(
([, node]) => node.getBoundingClientRect().bottom > 0
);
const top = anchor?.[1].getBoundingClientRect().top;
boxViewLayout = next; boxViewLayout = next;
document.cookie = `boxViewLayout=${next};path=/;max-age=31536000;SameSite=Lax`;
void tick().then(() => {
if (anchor && top !== undefined && window.scrollY > 0)
window.scrollBy(0, anchor[1].getBoundingClientRect().top - top);
measureViewport();
});
try { try {
localStorage.setItem(BOX_VIEW_LAYOUT_STORAGE_KEY, next); localStorage.setItem(BOX_VIEW_LAYOUT_STORAGE_KEY, next);
} catch { } catch {
@@ -202,7 +296,7 @@
</script> </script>
<main class="flex-1 p-4 w-full"> <main class="flex-1 p-4 w-full">
<div class="max-w-fit mx-auto"> <div class="max-w-[1440px] w-full mx-auto">
{#if combinedData && combinedData.length > 0} {#if combinedData && combinedData.length > 0}
<div class="container mx-auto"> <div class="container mx-auto">
<div class="card bg-base-100 shadow mb-4"> <div class="card bg-base-100 shadow mb-4">
@@ -212,6 +306,7 @@
<span class="label-text font-semibold">Box view layout</span> <span class="label-text font-semibold">Box view layout</span>
</label> </label>
<select <select
data-offline-action
id="box-view-layout" id="box-view-layout"
class="select select-bordered select-sm" class="select select-bordered select-sm"
bind:value={boxViewLayout} bind:value={boxViewLayout}
@@ -222,6 +317,16 @@
<option value="compact">Compact (3 boxes/row)</option> <option value="compact">Compact (3 boxes/row)</option>
<option value="ultra">Ultra (4 boxes/row)</option> <option value="ultra">Ultra (4 boxes/row)</option>
</select> </select>
{#if virtualize}
<label class="label cursor-pointer gap-2"
><input
data-offline-action
type="checkbox"
class="checkbox checkbox-sm"
bind:checked={renderAll}
/>Render all boxes</label
>
{/if}
<div class="flex flex-wrap items-center gap-2 text-sm"> <div class="flex flex-wrap items-center gap-2 text-sm">
<span class="font-semibold">Legend:</span> <span class="font-semibold">Legend:</span>
@@ -288,6 +393,7 @@
<span class="font-semibold">Filters:</span> <span class="font-semibold">Filters:</span>
<label class="label cursor-pointer gap-2 p-0"> <label class="label cursor-pointer gap-2 p-0">
<input <input
data-offline-action
type="checkbox" type="checkbox"
class="checkbox checkbox-sm" class="checkbox checkbox-sm"
bind:checked={filterNotCaught} bind:checked={filterNotCaught}
@@ -296,6 +402,7 @@
</label> </label>
<label class="label cursor-pointer gap-2 p-0"> <label class="label cursor-pointer gap-2 p-0">
<input <input
data-offline-action
type="checkbox" type="checkbox"
class="checkbox checkbox-sm" class="checkbox checkbox-sm"
bind:checked={filterNeedsToEvolve} bind:checked={filterNeedsToEvolve}
@@ -304,6 +411,7 @@
</label> </label>
<label class="label cursor-pointer gap-2 p-0"> <label class="label cursor-pointer gap-2 p-0">
<input <input
data-offline-action
type="checkbox" type="checkbox"
class="checkbox checkbox-sm" class="checkbox checkbox-sm"
bind:checked={filterInHome} bind:checked={filterInHome}
@@ -313,6 +421,7 @@
</label> </label>
<label class="label cursor-pointer gap-2 p-0"> <label class="label cursor-pointer gap-2 p-0">
<input <input
data-offline-action
type="checkbox" type="checkbox"
class="checkbox checkbox-sm" class="checkbox checkbox-sm"
bind:checked={filterNotInHome} bind:checked={filterNotInHome}
@@ -350,13 +459,18 @@
</div> </div>
<div <div
bind:this={grid}
class="boxes-grid" class="boxes-grid"
style="--boxes-per-row: {boxesPerRow}; --cell-padding: {cellPaddingRem}rem; --sprite-size: {spriteSizePx}px;" style="--boxes-per-row: {boxesPerRow}; --cell-padding: {cellPaddingRem}rem; --sprite-size: {spriteSizePx}px;"
> >
{#each boxNumbers as boxNumber} {#each boxNumbers as boxNumber (boxNumber)}
{@const bulkMenuId = `box-${boxNumber}-bulk-menu`} {@const bulkMenuId = `box-${boxNumber}-bulk-menu`}
<div class="mb-8"> <div class="box-shell" use:boxShell={boxNumber} data-box-number={boxNumber}>
<div class="flex flex-wrap items-center justify-between gap-3 mb-4 relative z-20"> {#if !virtualize || renderAll || visibleBoxes.has(boxNumber) || focusedBox === boxNumber}
<div class="box-content">
<div
class="box-heading flex items-center justify-between gap-3 mb-4 relative z-20"
>
<h2 class="text-xl font-bold">Box {boxNumber}</h2> <h2 class="text-xl font-bold">Box {boxNumber}</h2>
{#if !readOnly}<div class="relative"> {#if !readOnly}<div class="relative">
<button <button
@@ -368,7 +482,8 @@
aria-expanded={openBulkMenuForBox === boxNumber} aria-expanded={openBulkMenuForBox === boxNumber}
on:click={(event) => { on:click={(event) => {
event.stopPropagation(); event.stopPropagation();
openBulkMenuForBox = openBulkMenuForBox === boxNumber ? null : boxNumber; openBulkMenuForBox =
openBulkMenuForBox === boxNumber ? null : boxNumber;
}} }}
on:keydown={(event) => { on:keydown={(event) => {
if (event.key === 'Escape') openBulkMenuForBox = null; if (event.key === 'Escape') openBulkMenuForBox = null;
@@ -458,16 +573,21 @@
: 'hover:scale-105 hover:shadow-lg hover:z-50'} transition-all cursor-pointer relative" : 'hover:scale-105 hover:shadow-lg hover:z-50'} transition-all cursor-pointer relative"
style="grid-column-start: {placement.column}; grid-row-start: {placement.row}; style="grid-column-start: {placement.column}; grid-row-start: {placement.row};
{cellBackgroundColourStyle(globalIndex, catchRecord)}" {cellBackgroundColourStyle(globalIndex, catchRecord)}"
data-offline-action
data-entry-index={globalIndex}
data-entry-id={pokedexEntry._id}
on:focus={() => (focusedBox = boxNumber)}
on:keydown={(event) => navigateEntry(event, globalIndex)}
aria-disabled={isFilteredOut} aria-disabled={isFilteredOut}
on:click={() => { on:click={() => {
if (!isFilteredOut) onPokemonClick({ pokedexEntry, catchRecord }); if (!isFilteredOut) onPokemonClick(entry);
}} }}
aria-label="View details for {pokedexEntry.pokemon}. Status: {statusLabel( aria-label="View details for {pokedexEntry.pokemon}{pokedexEntry.form
catchRecord ? ` (${pokedexEntry.form})`
)}" : ''}. Status: {statusLabel(catchRecord)}"
> >
<Tooltip> <span class="cell-tooltip">
<div slot="hover-target" class="w-full h-full"> <span class="block w-full h-full">
{#if catchRecord?.caught} {#if catchRecord?.caught}
<span <span
class="status-badge status-badge--caught absolute left-0.5 status-badge-top z-10" class="status-badge status-badge--caught absolute left-0.5 status-badge-top z-10"
@@ -537,10 +657,11 @@
form={pokedexEntry.form} form={pokedexEntry.form}
spriteKey={pokedexEntry.spriteKey} spriteKey={pokedexEntry.spriteKey}
shiny={showShiny} shiny={showShiny}
variant="grid"
/> />
</div> </div>
</div> </span>
<div slot="tooltip"> <span class="cell-tooltip-text" role="tooltip">
<div class="font-bold"> <div class="font-bold">
{pokedexEntry.pokemon} {pokedexEntry.pokemon}
{pokedexEntry.form ? `(${pokedexEntry.form})` : ''} {pokedexEntry.form ? `(${pokedexEntry.form})` : ''}
@@ -548,12 +669,14 @@
<div>{pokedexEntry.pokedexNumber.toString().padStart(3, '0')}</div> <div>{pokedexEntry.pokedexNumber.toString().padStart(3, '0')}</div>
<div> <div>
Caught: {catchRecord?.caught ? 'Yes' : 'No'} <br /> Caught: {catchRecord?.caught ? 'Yes' : 'No'} <br />
Caught but needs to Evolve: {catchRecord?.haveToEvolve ? 'Yes' : 'No'} Caught but needs to Evolve: {catchRecord?.haveToEvolve
? 'Yes'
: 'No'}
<br /> <br />
In Home: {catchRecord?.inHome ? 'Yes' : 'No'} In Home: {catchRecord?.inHome ? 'Yes' : 'No'}
</div> </div>
</div> </span>
</Tooltip> </span>
</button> </button>
{:else} {:else}
<button <button
@@ -572,11 +695,16 @@
{/each} {/each}
</div> </div>
</div> </div>
{/if}
</div>
{/each} {/each}
</div> </div>
</div> </div>
{:else if failedToLoad} {:else if failedToLoad}
{#if creatingRecords && totalRecordsCreated > 0} {#if retryLoad}
<p role="alert">Unable to load Pokédex.</p>
<button class="btn" on:click={retryLoad}>Retry loading Pokédex</button>
{:else if creatingRecords && totalRecordsCreated > 0}
<p>Processed {totalRecordsCreated} Pokédex entries so far...</p> <p>Processed {totalRecordsCreated} Pokédex entries so far...</p>
<p>Please be patient, this may take some time.</p> <p>Please be patient, this may take some time.</p>
{:else if creatingRecords} {:else if creatingRecords}
@@ -592,6 +720,8 @@
<button class="btn" on:click={createCatchRecords}>Create Pokédex data</button> <button class="btn" on:click={createCatchRecords}>Create Pokédex data</button>
{/if} {/if}
{/if} {/if}
{:else if combinedData}
<p>No entries match this Pokédex.</p>
{:else} {:else}
<div class="min-w-max mx-auto"> <div class="min-w-max mx-auto">
<h1>Loading Pokédex</h1> <h1>Loading Pokédex</h1>
@@ -602,6 +732,43 @@
</main> </main>
<style> <style>
.box-shell {
position: relative;
min-width: 0;
}
.box-shell::before {
content: '';
display: block;
padding-top: calc(83.333333% + 80px);
}
.box-content {
position: absolute;
inset: 0 0 32px;
}
.box-heading {
height: 32px;
}
.cell-tooltip {
display: block;
width: 100%;
height: 100%;
}
.cell-tooltip-text {
display: none;
position: absolute;
z-index: 100;
pointer-events: none;
background: #1f2937;
color: white;
border-radius: 4px;
padding: 8px;
width: 13rem;
}
.pokemon-box:hover .cell-tooltip-text,
.pokemon-box:focus-visible .cell-tooltip-text {
display: block;
}
/* /*
Theme-aware backgrounds for non-caught box slots. Theme-aware backgrounds for non-caught box slots.
- Light mode (`pokeball`) keeps the original exact colors. - Light mode (`pokeball`) keeps the original exact colors.
+58
View File
@@ -0,0 +1,58 @@
import type { PokedexEntry } from './PokedexEntry';
import type { CatchRecord } from './CatchRecord';
/** Complete ordering/status data, without detail text or repeated ownership fields. */
export type PokedexGridRow = {
pokedexEntry: Pick<
PokedexEntry,
'_id' | 'pokemon' | 'pokedexNumber' | 'form' | 'spriteKey' | 'canGigantamax'
>;
catchRecord: Pick<
CatchRecord,
'_id' | 'caught' | 'haveToEvolve' | 'inHome' | 'hasGigantamaxed'
> | null;
};
export type CatchRecordPatch = Partial<CatchRecord> &
Pick<CatchRecord, 'userId' | 'pokedexId' | 'pokemonId'>;
/** Version 1 transport rows: avoid repeating field names 1,000+ times. IDs remain available. */
export type PackedGridRow = [
entryId: string,
number: number,
name: string,
form: string,
spriteKey: string,
canGigantamax: boolean,
catchId: string | null,
status: number
];
export function packGrid(rows: PokedexGridRow[]): PackedGridRow[] {
return rows.map(({ pokedexEntry: e, catchRecord: c }) => [
e._id,
e.pokedexNumber,
e.pokemon,
e.form,
e.spriteKey,
e.canGigantamax,
c?._id ?? null,
(c?.caught ? 1 : 0) |
(c?.haveToEvolve ? 2 : 0) |
(c?.inHome ? 4 : 0) |
(c?.hasGigantamaxed ? 8 : 0)
]);
}
export function unpackGrid(rows: PackedGridRow[]): PokedexGridRow[] {
return rows.map(([id, number, name, form, spriteKey, canGigantamax, catchId, status]) => ({
pokedexEntry: { _id: id, pokedexNumber: number, pokemon: name, form, spriteKey, canGigantamax },
catchRecord:
catchId === null
? null
: {
_id: catchId,
caught: !!(status & 1),
haveToEvolve: !!(status & 2),
inHome: !!(status & 4),
hasGigantamaxed: !!(status & 8)
}
}));
}
+17 -9
View File
@@ -90,19 +90,27 @@ class CatchRecordRepository {
return mapped; return mapped;
}); });
const { data: result, error } = await this.supabase const groups = new Map<string, Partial<CatchRecordDB>[]>();
for (const row of dbRows) {
const key = Object.keys(row).sort().join(',');
const group = groups.get(key) ?? [];
group.push(row);
groups.set(key, group);
}
const saved: CatchRecord[] = [];
for (const group of groups.values()) {
const { data, error } = await this.supabase
.from('catch_records') .from('catch_records')
.upsert(dbRows, { .upsert(group, {
onConflict: '"userId","pokedexId","pokemonId"' onConflict: '"userId","pokedexId","pokemonId"',
defaultToNull: false
}) })
.select(); .select();
if (error) throw new Error(`Failed to bulk upsert catch records: ${error.message}`);
if (error) { saved.push(...(data ?? []).map((row) => this.transformCatchRecord(row)));
console.error('Supabase error bulk upserting catch records:', error);
throw new Error(`Failed to bulk upsert catch records: ${error.message}`);
} }
const byPokemon = new Map(saved.map((row) => [row.pokemonId, row]));
return (result ?? []).map((row) => this.transformCatchRecord(row)); return records.map((row) => byPokemon.get(row.pokemonId)!);
} }
async findById(id: string): Promise<CatchRecord | null> { async findById(id: string): Promise<CatchRecord | null> {
+101 -25
View File
@@ -1,3 +1,4 @@
import type { PokedexGridRow } from '$lib/models/PokedexGridRow';
import { type PokedexEntry, type PokedexEntryDB } from '$lib/models/PokedexEntry'; import { type PokedexEntry, type PokedexEntryDB } from '$lib/models/PokedexEntry';
import { type CatchRecord, type CatchRecordDB } from '$lib/models/CatchRecord'; import { type CatchRecord, type CatchRecordDB } from '$lib/models/CatchRecord';
import { type CombinedData } from '$lib/models/CombinedData'; import { type CombinedData } from '$lib/models/CombinedData';
@@ -20,9 +21,17 @@ class CombinedDataRepository {
constructor( constructor(
private supabase: SupabaseClient, private supabase: SupabaseClient,
private userId: string | null, private userId: string | null,
private pokedexId: string | null private pokedexId: string | null,
private compact = false
) {} ) {}
private scopedEntries = new Map<string, Promise<PokedexEntryDB[]>>();
private get entryColumns() {
return this.compact
? 'id,pokedexNumber,pokemon,form,spriteKey,canGigantamax,unownSortOrder,formSortBucket,formSortRegionOrder,formSortRegionalSub,formSortLabel'
: '*';
}
// Transform Supabase data to match frontend expectations (minimal transformation) // Transform Supabase data to match frontend expectations (minimal transformation)
private transformPokedexEntry(entry: PokedexEntryDB): PokedexEntry { private transformPokedexEntry(entry: PokedexEntryDB): PokedexEntry {
return { return {
@@ -57,7 +66,7 @@ class CombinedDataRepository {
} }
private buildEntriesQuery(enableForms: boolean, region: string, game: string) { private buildEntriesQuery(enableForms: boolean, region: string, game: string) {
let query = this.supabase.from('pokedex_entries').select('*'); let query = this.supabase.from('pokedex_entries').select(this.entryColumns);
if (!enableForms) { if (!enableForms) {
// Filter to base forms only. Gendered species (form='male') and Unown ('A') are // Filter to base forms only. Gendered species (form='male') and Unown ('A') are
@@ -86,7 +95,10 @@ class CombinedDataRepository {
} }
private buildDexEntriesQuery(dexScopes: string[], enableForms: boolean, region: string) { private buildDexEntriesQuery(dexScopes: string[], enableForms: boolean, region: string) {
let query = this.supabase.from('game_pokedex_entry_details').select('*').in('dexId', dexScopes); let query = this.supabase
.from('game_pokedex_entry_details')
.select(this.compact ? `${this.entryColumns},dexNumber,dexSortOrder` : '*')
.in('dexId', dexScopes);
if (!enableForms) { if (!enableForms) {
// Filter to base forms only. Gendered species (form='male') and Unown ('A') are // Filter to base forms only. Gendered species (form='male') and Unown ('A') are
@@ -128,7 +140,10 @@ class CombinedDataRepository {
for (;;) { for (;;) {
const end = start + maxRows - 1; const end = start + maxRows - 1;
let query = this.supabase.from('pokedex_entries').select('*').not('form', 'is', null); let query = this.supabase
.from('pokedex_entries')
.select(this.entryColumns)
.not('form', 'is', null);
if (game) { if (game) {
query = query.contains('gamesToCatchIn', [game]); query = query.contains('gamesToCatchIn', [game]);
@@ -140,13 +155,12 @@ class CombinedDataRepository {
const { data, error } = await query.order('id', { ascending: true }).range(start, end); const { data, error } = await query.order('id', { ascending: true }).range(start, end);
if (error) { if (error) {
console.error('Error fetching forms for game:', error); throw new Error('Unable to load form entries');
return [];
} }
if (!data || data.length === 0) break; if (!data || data.length === 0) break;
allForms.push(...(data as PokedexEntryDB[]).filter((e) => !excludeIds.has(e.id))); allForms.push(...(data as unknown as PokedexEntryDB[]).filter((e) => !excludeIds.has(e.id)));
if (data.length < maxRows) break; if (data.length < maxRows) break;
start = end + 1; start = end + 1;
@@ -155,7 +169,17 @@ class CombinedDataRepository {
return allForms; return allForms;
} }
private async fetchAllDexEntries( private fetchAllDexEntries(dexScopes: string[], enableForms: boolean, region: string, game = '') {
const key = JSON.stringify([dexScopes, enableForms, region, game]);
let entries = this.scopedEntries.get(key);
if (!entries) {
entries = this.readAllDexEntries(dexScopes, enableForms, region, game);
this.scopedEntries.set(key, entries);
}
return entries;
}
private async readAllDexEntries(
dexScopes: string[], dexScopes: string[],
enableForms: boolean, enableForms: boolean,
region: string, region: string,
@@ -175,15 +199,14 @@ class CombinedDataRepository {
); );
if (error) { if (error) {
console.error('Error finding dex-scoped combined data:', error); throw new Error('Unable to load dex entries');
return [];
} }
if (!data || data.length === 0) { if (!data || data.length === 0) {
break; break;
} }
entries.push(...(data as RawDexEntry[])); entries.push(...(data as unknown as RawDexEntry[]));
if (data.length < maxRows) { if (data.length < maxRows) {
break; break;
@@ -283,15 +306,14 @@ class CombinedDataRepository {
); );
if (error) { if (error) {
console.error('Error finding paginated combined data:', error); throw new Error('Unable to load dex entries');
return [];
} }
if (!data || data.length === 0) { if (!data || data.length === 0) {
break; break;
} }
entries.push(...data); entries.push(...(data as unknown as PokedexEntryDB[]));
if (data.length < end - start + 1) { if (data.length < end - start + 1) {
break; break;
@@ -320,15 +342,14 @@ class CombinedDataRepository {
); );
if (error) { if (error) {
console.error('Error finding combined data:', error); throw new Error('Unable to load dex entries');
return [];
} }
if (!data || data.length === 0) { if (!data || data.length === 0) {
break; break;
} }
entries.push(...data); entries.push(...(data as unknown as PokedexEntryDB[]));
if (data.length < maxRows) { if (data.length < maxRows) {
break; break;
@@ -351,24 +372,79 @@ class CombinedDataRepository {
const chunk = entryIds.slice(i, i + chunkSize); const chunk = entryIds.slice(i, i + chunkSize);
const { data, error } = await this.supabase const { data, error } = await this.supabase
.from('catch_records') .from('catch_records')
.select('*') .select(this.compact ? 'id,pokemonId,caught,haveToEvolve,inHome,hasGigantamaxed' : '*')
.eq('userId', userId) .eq('userId', userId)
.eq('pokedexId', this.pokedexId) .eq('pokedexId', this.pokedexId)
.in('pokemonId', chunk); .in('pokemonId', chunk);
if (error) { if (error) {
console.error('Error loading catch records:', error); throw new Error('Unable to load catch records');
continue;
} }
if (data) { if (data) {
records.push(...data); records.push(...(data as unknown as CatchRecordDB[]));
} }
} }
return records; return records;
} }
async findGridEntries(enableForms: boolean, game: string, dexScopes: string[]) {
if (!this.compact) throw new Error('Grid reads require a compact repository');
const entries = dexScopes.length
? this.dedupeEntries(await this.fetchAllDexEntries(dexScopes, enableForms, '', game))
: await this.fetchAllEntries(enableForms, '', game);
return entries;
}
async joinGridCatches(entries: PokedexEntryDB[]): Promise<PokedexGridRow[]> {
const catches = new Map(
(
await this.fetchCatchRecords(
entries.map((e) => e.id),
this.userId!
)
).map((r) => [r.pokemonId, r])
);
return entries.map((e) => {
const c = catches.get(e.id);
return {
pokedexEntry: {
_id: String(e.id),
pokemon: e.pokemon,
pokedexNumber: e.pokedexNumber,
form: e.form || '',
spriteKey: e.spriteKey || '',
canGigantamax: e.canGigantamax
},
catchRecord: c
? {
_id: c.id,
caught: c.caught,
haveToEvolve: c.haveToEvolve,
inHome: c.inHome,
hasGigantamaxed: c.hasGigantamaxed
}
: null
};
});
}
async findEntryDetail(entryId: number): Promise<CombinedData | null> {
const { data, error } = await this.supabase
.from('pokedex_entries')
.select('*')
.eq('id', entryId)
.maybeSingle();
if (error) throw new Error('Unable to load entry details');
if (!data) return null;
const catches = await this.fetchCatchRecords([entryId], this.userId!);
return {
pokedexEntry: this.transformPokedexEntry(data),
catchRecord: catches[0] ? this.transformCatchRecord(catches[0]) : null
};
}
async findAllCombinedData( async findAllCombinedData(
userId: string, userId: string,
enableForms: boolean = true, enableForms: boolean = true,
@@ -392,9 +468,9 @@ class CombinedDataRepository {
catchRecords = await this.fetchCatchRecords(entryIds, userId); catchRecords = await this.fetchCatchRecords(entryIds, userId);
} }
// Combine the data exactly like master branch const catchesById = new Map(catchRecords.map((record) => [record.pokemonId, record]));
const combinedData = entries.map((entry) => { const combinedData = entries.map((entry) => {
const userCatchRecord = catchRecords.find((record) => record.pokemonId === entry.id) || null; const userCatchRecord = catchesById.get(entry.id) || null;
const transformedEntry = this.transformPokedexEntry(entry); const transformedEntry = this.transformPokedexEntry(entry);
const transformedCatchRecord = userCatchRecord const transformedCatchRecord = userCatchRecord
@@ -440,9 +516,9 @@ class CombinedDataRepository {
catchRecords = await this.fetchCatchRecords(entryIds, userId); catchRecords = await this.fetchCatchRecords(entryIds, userId);
} }
// Combine the data exactly like master branch const catchesById = new Map(catchRecords.map((record) => [record.pokemonId, record]));
const combinedData = entries.map((entry) => { const combinedData = entries.map((entry) => {
const userCatchRecord = catchRecords.find((record) => record.pokemonId === entry.id) || null; const userCatchRecord = catchesById.get(entry.id) || null;
const transformedEntry = this.transformPokedexEntry(entry); const transformedEntry = this.transformPokedexEntry(entry);
const transformedCatchRecord = userCatchRecord const transformedCatchRecord = userCatchRecord
+5 -3
View File
@@ -55,14 +55,16 @@ class PokedexRepository {
async findById(id: string): Promise<Pokedex | null> { async findById(id: string): Promise<Pokedex | null> {
const { data, error } = await this.supabase const { data, error } = await this.supabase
.from('pokedexes') .from('pokedexes')
.select('*') .select('*, pokedex_dex_scopes(dexId)')
.eq('id', id) .eq('id', id)
.eq('userId', this.userId) .eq('userId', this.userId)
.single(); .single();
if (error || !data) return null; if (error || !data) return null;
const dexScopesMap = await this.fetchDexScopesMap([data.id]); return this.transform(
return this.transform(data, dexScopesMap.get(data.id) || []); data,
(data.pokedex_dex_scopes ?? []).map((scope: { dexId: string }) => scope.dexId)
);
} }
async findAll(): Promise<Pokedex[]> { async findAll(): Promise<Pokedex[]> {
+4
View File
@@ -0,0 +1,4 @@
/** Cloudflare performs transport compression; preserve the streaming Response body. */
export function compressResponse(_request: Request, response: Response): Response {
return response;
}
+37
View File
@@ -0,0 +1,37 @@
import { env } from '$env/dynamic/private';
/** Opt-in, fixed labels only: never log IDs, query strings, cookies or entry content. */
export class PokedexPerformance {
private started = performance.now();
private durations: Record<string, number> = {};
readonly enabled = env.POKEDEX_PERFORMANCE === 'true';
async measure<T>(
stage: 'auth' | 'ownership' | 'scopes' | 'entries' | 'catches',
run: () => Promise<T>
): Promise<T> {
const start = performance.now();
try {
return await run();
} finally {
if (this.enabled) this.durations[stage] = performance.now() - start;
}
}
recordAuth(duration: number | undefined) {
if (this.enabled && duration !== undefined) this.durations.auth = duration;
}
prepare<T>(run: () => T): T {
const start = performance.now();
try {
return run();
} finally {
if (this.enabled) this.durations.prepare = performance.now() - start;
}
}
finish(): string | undefined {
if (!this.enabled) return undefined;
this.durations.total = performance.now() - this.started;
return Object.entries(this.durations)
.map(([name, duration]) => `${name};dur=${duration.toFixed(1)}`)
.join(', ');
}
}
+38
View File
@@ -0,0 +1,38 @@
import type { SupabaseClient } from '@supabase/supabase-js';
import type { Pokedex } from '$lib/models/Pokedex';
import CombinedDataRepository from '$lib/repositories/CombinedDataRepository';
import { resolveDexScopes } from './PokedexDexScopeService';
import type { PokedexPerformance } from '$lib/server/pokedexPerformance';
export async function loadPokedexGrid(
supabase: SupabaseClient,
userId: string,
pokedex: Pokedex,
timings?: PokedexPerformance
) {
const measure = <T>(stage: 'scopes' | 'entries' | 'catches', run: () => Promise<T>) =>
timings ? timings.measure(stage, run) : run();
const scopes = await measure('scopes', () => resolveDexScopes(supabase, pokedex));
const repo = new CombinedDataRepository(supabase, userId, pokedex._id, true);
const entries = await measure('entries', () =>
repo.findGridEntries(pokedex.isFormDex, pokedex.gameScope || '', scopes)
);
return measure('catches', () => repo.joinGridCatches(entries));
}
export async function loadPokedexEntryDetail(
supabase: SupabaseClient,
userId: string,
pokedex: Pokedex,
entryId: number
) {
const scopes = await resolveDexScopes(supabase, pokedex);
const membership = new CombinedDataRepository(supabase, userId, pokedex._id, true);
const entries = await membership.findGridEntries(
pokedex.isFormDex,
pokedex.gameScope || '',
scopes
);
if (!entries.some((entry) => entry.id === entryId)) return null;
return new CombinedDataRepository(supabase, userId, pokedex._id).findEntryDetail(entryId);
}
+13 -1
View File
@@ -24,7 +24,19 @@ export function setBackupStatus(integrations: IntegrationSummary[]): void {
backupsNeedingReconnect.set(integrations.filter((i) => !i.enabled).map((i) => i.provider)); backupsNeedingReconnect.set(integrations.filter((i) => !i.enabled).map((i) => i.provider));
} }
export async function refreshBackupStatus(): Promise<void> { let refreshInFlight: { generation: number; promise: Promise<void> } | null = null;
export function refreshBackupStatus(): Promise<void> {
if (refreshInFlight?.generation === mutationGeneration) return refreshInFlight.promise;
const generation = mutationGeneration;
const promise = performRefresh().finally(() => {
if (refreshInFlight?.promise === promise) refreshInFlight = null;
});
refreshInFlight = { generation, promise };
return promise;
}
async function performRefresh(): Promise<void> {
if (typeof window === 'undefined' || !navigator.onLine) return; if (typeof window === 'undefined' || !navigator.onLine) return;
const sequence = ++refreshSequence; const sequence = ++refreshSequence;
const generation = mutationGeneration; const generation = mutationGeneration;
+31 -2
View File
@@ -1,3 +1,4 @@
import { afterCriticalPageWork } from '$lib/utils/criticalPageWork';
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import { PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER } from '$env/static/public'; import { PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER } from '$env/static/public';
import type { OfflineSnapshot } from '$lib/models/OfflineSnapshot'; import type { OfflineSnapshot } from '$lib/models/OfflineSnapshot';
@@ -246,17 +247,45 @@ export function startOfflineSync(getUserId: () => string | null): () => void {
}, 1_000); }, 1_000);
}; };
// Explicit requests (edits, Retry, a new sign-in) and reconnecting always fetch a new copy. // Explicit requests (edits, Retry, a new sign-in) and reconnecting always fetch a new copy.
const schedule = () => scheduleSync(false); const schedule = () => {
cancelStartup();
scheduleSync(false);
};
// Best effort: ask the browser not to evict the offline artwork cache under storage pressure. // Best effort: ask the browser not to evict the offline artwork cache under storage pressure.
void navigator.storage?.persist?.().catch(() => undefined); void navigator.storage?.persist?.().catch(() => undefined);
window.addEventListener(SYNC_EVENT, schedule); window.addEventListener(SYNC_EVENT, schedule);
window.addEventListener('online', schedule); window.addEventListener('online', schedule);
scheduleSync(true); const cancelStartup = afterCriticalPageWork(() => scheduleSync(true));
return () => { return () => {
stopped = true; stopped = true;
cancelStartup();
if (timer !== null) window.clearTimeout(timer); if (timer !== null) window.clearTimeout(timer);
window.removeEventListener(SYNC_EVENT, schedule); window.removeEventListener(SYNC_EVENT, schedule);
window.removeEventListener('online', schedule); window.removeEventListener('online', schedule);
}; };
} }
/** Read details only from the snapshot currently claimed by this account. */
export async function readOfflineEntry(userId: string, pokedexId: string, entryId: string) {
if (typeof window === 'undefined' || !('caches' in window)) return null;
const meta = (await readOfflineMeta()) as (OfflineMeta & { dataCache?: string }) | null;
if (
meta?.userId !== userId ||
meta.format !== OFFLINE_META_FORMAT ||
!meta.dataCache?.startsWith(`${OFFLINE_CACHE_PREFIX}data-v1-${userId}-`)
)
return null;
const response = await (
await caches.open(meta.dataCache)
).match(`/__offline/snapshot/${encodeURIComponent(userId)}`);
const snapshot = (await response?.json()) as OfflineSnapshot | undefined;
const current = await readOfflineMeta();
if (current?.userId !== userId || snapshot?.userId !== userId || snapshot.version !== 1)
return null;
return (
snapshot.pokedexes
.find((dex) => dex.pokedex._id === pokedexId)
?.entries.find((row) => row.pokedexEntry._id === entryId) ?? null
);
}
+19 -8
View File
@@ -1,5 +1,5 @@
import { writable, type Readable } from 'svelte/store'; import { writable, type Readable } from 'svelte/store';
import type { CatchRecord } from '$lib/models/CatchRecord'; import type { CatchRecordPatch } from '$lib/models/PokedexGridRow';
export type CatchRecordWriteQueueStatus = { export type CatchRecordWriteQueueStatus = {
pending: number; pending: number;
@@ -10,7 +10,7 @@ export type CatchRecordWriteQueueStatus = {
}; };
type QueueItem = { type QueueItem = {
record: CatchRecord; record: CatchRecordPatch;
attempts: number; attempts: number;
notBefore: number; // unix ms notBefore: number; // unix ms
debounceTimer: ReturnType<typeof setTimeout> | null; debounceTimer: ReturnType<typeof setTimeout> | null;
@@ -31,6 +31,8 @@ export type CreateCatchRecordWriteQueueOptions = {
batchSize?: number; batchSize?: number;
/** Max number of concurrent in-flight requests. */ /** Max number of concurrent in-flight requests. */
concurrency?: number; concurrency?: number;
/** Prevent queued work from crossing an account change. */
isCurrentUser?: () => boolean;
}; };
export type EnqueueCatchRecordWriteOptions = { export type EnqueueCatchRecordWriteOptions = {
@@ -53,7 +55,7 @@ export type FlushOptions = {
limit?: number; limit?: number;
}; };
function keyFor(record: CatchRecord): string { function keyFor(record: CatchRecordPatch): string {
return `${record.userId}:${record.pokedexId}:${record.pokemonId}`; return `${record.userId}:${record.pokedexId}:${record.pokemonId}`;
} }
@@ -66,11 +68,12 @@ function backoffMs(attempts: number): number {
} }
export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueueOptions): { export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueueOptions): {
enqueue: (record: CatchRecord, opts?: EnqueueCatchRecordWriteOptions) => void; enqueue: (record: CatchRecordPatch, opts?: EnqueueCatchRecordWriteOptions) => void;
flushNow: (opts?: FlushOptions) => Promise<void>; flushNow: (opts?: FlushOptions) => Promise<void>;
getStatus: Readable<CatchRecordWriteQueueStatus>; getStatus: Readable<CatchRecordWriteQueueStatus>;
getPendingCount: () => number; getPendingCount: () => number;
clearError: () => void; clearError: () => void;
getPendingPatch: (pokemonId: string) => CatchRecordPatch | undefined;
} { } {
const { endpointUrl, fetchFn, batchSize = 100, concurrency = 1 } = options; const { endpointUrl, fetchFn, batchSize = 100, concurrency = 1 } = options;
@@ -109,7 +112,7 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
} }
function scheduleFlush() { function scheduleFlush() {
if (scheduled) return; if (scheduled || (typeof navigator !== 'undefined' && navigator.onLine === false)) return;
const next = computeNextWakeup(); const next = computeNextWakeup();
if (next === null) return; if (next === null) return;
const delay = Math.max(0, next - Date.now()); const delay = Math.max(0, next - Date.now());
@@ -120,6 +123,12 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
} }
async function flushBatch(opts?: FlushOptions): Promise<void> { async function flushBatch(opts?: FlushOptions): Promise<void> {
if (options.isCurrentUser && !options.isCurrentUser()) {
for (const item of items.values()) if (item.debounceTimer) clearTimeout(item.debounceTimer);
items.clear();
updateStatus({ lastError: null });
return;
}
if (typeof navigator !== 'undefined' && navigator.onLine === false) { if (typeof navigator !== 'undefined' && navigator.onLine === false) {
// Stay queued; caller can retry when online. // Stay queued; caller can retry when online.
return; return;
@@ -206,7 +215,7 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
scheduleFlush(); scheduleFlush();
} }
function enqueue(record: CatchRecord, opts?: EnqueueCatchRecordWriteOptions) { function enqueue(record: CatchRecordPatch, opts?: EnqueueCatchRecordWriteOptions) {
const k = keyFor(record); const k = keyFor(record);
const now = Date.now(); const now = Date.now();
const existing = items.get(k); const existing = items.get(k);
@@ -232,7 +241,7 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
} }
items.set(k, { items.set(k, {
record, record: { ...existing?.record, ...record },
attempts: existing?.attempts ?? 0, attempts: existing?.attempts ?? 0,
notBefore, notBefore,
debounceTimer, debounceTimer,
@@ -255,6 +264,8 @@ export function createCatchRecordWriteQueue(options: CreateCatchRecordWriteQueue
flushNow, flushNow,
getStatus: { subscribe: statusStore.subscribe }, getStatus: { subscribe: statusStore.subscribe },
getPendingCount, getPendingCount,
clearError clearError,
getPendingPatch: (pokemonId: string) =>
[...items.values()].find((item) => item.record.pokemonId === pokemonId)?.record
}; };
} }
+50
View File
@@ -0,0 +1,50 @@
/** Shared scheduling boundary for optional page-start work. Explicit refreshes bypass it. */
const READY_EVENT = 'livingdex:grid-interactive';
export function markGridInteractive() {
if (typeof window === 'undefined') return;
if (!document.querySelector('[data-entry-index]')) return;
if (!document.querySelector('[data-grid-interactive]')) {
performance.mark('pokedex:first-interactive');
}
document
.querySelector('[data-entry-index]')
?.closest('.boxes-grid')
?.setAttribute('data-grid-interactive', 'true');
window.dispatchEvent(new Event(READY_EVENT));
}
export function afterCriticalPageWork(run: () => void): () => void {
let cancelled = false;
let scheduled = false;
let idle: number | undefined;
let frame: number | undefined;
const perform = () => {
if (cancelled) return;
cancel();
run();
};
const schedule = () => {
if (scheduled || cancelled) return;
scheduled = true;
frame = requestAnimationFrame(() => {
if ('requestIdleCallback' in window)
idle = window.requestIdleCallback(perform, { timeout: 5000 });
else frame = requestAnimationFrame(perform);
});
};
const fallback = window.setTimeout(perform, 5000);
const cancel = () => {
cancelled = true;
window.clearTimeout(fallback);
window.removeEventListener(READY_EVENT, schedule);
if (idle !== undefined) window.cancelIdleCallback(idle);
if (frame !== undefined) cancelAnimationFrame(frame);
};
window.addEventListener(READY_EVENT, schedule);
if (
!location.pathname.startsWith('/pokedex/') ||
document.querySelector('[data-grid-interactive]')
)
schedule();
return cancel;
}
+11
View File
@@ -46,3 +46,14 @@ export function resolveSpriteUrl(
if (/^female\b/i.test(form)) root += '/female'; if (/^female\b/i.test(form)) root += '/female';
return `${root}/${key}.webp`; return `${root}/${key}.webp`;
} }
/** Grid assets use a separate immutable URL space; detail resolution is unchanged. */
export function resolveGridSpriteUrl(
entry: { pokedexNumber: number; form?: string; spriteKey?: string },
shiny: boolean
): string {
return resolveSpriteUrl(entry, shiny, true).replace(
'/sprites-small/home/',
'/sprites-grid/v1/home/'
);
}
+17 -7
View File
@@ -2,6 +2,7 @@
// The only app stylesheet: Vite bundles, minifies and content-hashes it so it is cached for good. // The only app stylesheet: Vite bundles, minifies and content-hashes it so it is cached for good.
// static/output.css is built separately for the credential-free offline.html page only. // static/output.css is built separately for the credential-free offline.html page only.
import '../app.css'; import '../app.css';
import { afterCriticalPageWork } from '$lib/utils/criticalPageWork';
import { onDestroy, onMount } from 'svelte'; import { onDestroy, onMount } from 'svelte';
import { user } from '$lib/stores/user.js'; import { user } from '$lib/stores/user.js';
import { type User } from '@supabase/auth-js'; import { type User } from '@supabase/auth-js';
@@ -27,18 +28,21 @@
let { supabase } = data; let { supabase } = data;
$: ({ supabase } = data); $: ({ supabase } = data);
let localUser = null as User | null; let localUser: User | null = data.user ?? null;
let userStoreReady = false;
const unsubscribe = user.subscribe((value) => { const unsubscribe = user.subscribe((value) => {
localUser = value; if (userStoreReady) localUser = value;
}); });
onDestroy(unsubscribe); onDestroy(unsubscribe);
let authSubscription: { unsubscribe: () => void } | null = null; let authSubscription: { unsubscribe: () => void } | null = null;
let cancelBackupStartup: (() => void) | null = null;
let stopOfflineSync: (() => void) | null = null; let stopOfflineSync: (() => void) | null = null;
let isOnline = true; let isOnline = true;
let signOutError = ''; let signOutError = '';
onMount(() => { onMount(() => {
userStoreReady = true;
isOnline = navigator.onLine; isOnline = navigator.onLine;
const updateOnlineState = () => { const updateOnlineState = () => {
isOnline = navigator.onLine; isOnline = navigator.onLine;
@@ -48,6 +52,7 @@
if (navigator.onLine) return; if (navigator.onLine) return;
const target = event.target instanceof Element ? event.target : null; const target = event.target instanceof Element ? event.target : null;
if (!target?.closest('button, input, textarea, select, form')) return; if (!target?.closest('button, input, textarea, select, form')) return;
if (target.closest('[data-offline-action]')) return;
event.preventDefault(); event.preventDefault();
event.stopImmediatePropagation(); event.stopImmediatePropagation();
}; };
@@ -60,7 +65,9 @@
void getUser() void getUser()
.then(async () => { .then(async () => {
if (localUser) { if (localUser) {
void refreshBackupStatus(); cancelBackupStartup = afterCriticalPageWork(() => {
if (localUser) void refreshBackupStatus();
});
await claimOfflineData(localUser.id); await claimOfflineData(localUser.id);
} }
stopOfflineSync = startOfflineSync(() => localUser?.id ?? null); stopOfflineSync = startOfflineSync(() => localUser?.id ?? null);
@@ -77,6 +84,8 @@
// SIGNED_IN also fires when a tab regains focus, so only a change of account fetches a new // SIGNED_IN also fires when a tab regains focus, so only a change of account fetches a new
// offline copy. Page loads and token refreshes reuse the saved one while it is fresh. // offline copy. Page loads and token refreshes reuse the saved one while it is fresh.
if (event === 'SIGNED_IN' && session.user.id !== previousUserId) { if (event === 'SIGNED_IN' && session.user.id !== previousUserId) {
cancelBackupStartup?.();
clearBackupStatus();
void claimOfflineData(session.user.id) void claimOfflineData(session.user.id)
.then(requestOfflineSync) .then(requestOfflineSync)
.catch((error) => console.error('Unable to claim offline data', error)); .catch((error) => console.error('Unable to claim offline data', error));
@@ -96,6 +105,7 @@
return () => { return () => {
authSubscription?.unsubscribe(); authSubscription?.unsubscribe();
stopOfflineSync?.(); stopOfflineSync?.();
cancelBackupStartup?.();
window.removeEventListener('online', updateOnlineState); window.removeEventListener('online', updateOnlineState);
window.removeEventListener('offline', updateOnlineState); window.removeEventListener('offline', updateOnlineState);
for (const name of ['click', 'submit', 'input', 'change', 'keydown']) { for (const name of ['click', 'submit', 'input', 'change', 'keydown']) {
@@ -304,10 +314,10 @@
</div> </div>
<style> <style>
:global(.offline-readonly button), :global(.offline-readonly button:not([data-offline-action])),
:global(.offline-readonly input), :global(.offline-readonly input:not([data-offline-action])),
:global(.offline-readonly textarea), :global(.offline-readonly textarea:not([data-offline-action])),
:global(.offline-readonly select) { :global(.offline-readonly select:not([data-offline-action])) {
pointer-events: none; pointer-events: none;
opacity: 0.65; opacity: 0.65;
} }
+1
View File
@@ -60,6 +60,7 @@ export const load: LayoutLoad = async ({ fetch, data, depends }) => {
return { return {
supabase, supabase,
session, session,
user: data.user,
recoveryIntent: !!session && (hashRecoveryCallback || recoveryExchangeSucceeded) recoveryIntent: !!session && (hashRecoveryCallback || recoveryExchangeSucceeded)
}; };
}; };
@@ -7,11 +7,6 @@ export const GET = async (event: RequestEvent) => {
try { try {
const userId = await requireAuth(event); const userId = await requireAuth(event);
const { session } = await event.locals.safeGetSession();
if (session) {
await event.locals.supabase.auth.setSession(session);
}
const repo = new PokedexExportIntegrationRepository(event.locals.supabase, userId, null); const repo = new PokedexExportIntegrationRepository(event.locals.supabase, userId, null);
const integrations = await repo.listAll(); const integrations = await repo.listAll();
@@ -0,0 +1,18 @@
import { error, json } from '@sveltejs/kit';
import { requireAuth } from '$lib/utils/auth';
import PokedexRepository from '$lib/repositories/PokedexRepository';
import { loadPokedexEntryDetail } from '$lib/services/PokedexGridService';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async (event) => {
const userId = await requireAuth(event);
const entryId = Number(event.params.entryId);
if (!Number.isSafeInteger(entryId) || entryId < 1) throw error(400, 'Invalid entry');
const pokedex = await new PokedexRepository(event.locals.supabase, userId).findById(
event.params.id
);
if (!pokedex) throw error(404, 'Pokédex not found');
const detail = await loadPokedexEntryDetail(event.locals.supabase, userId, pokedex, entryId);
if (!detail) throw error(404, 'Entry not found');
return json(detail, { headers: { 'cache-control': 'private, no-store' } });
};
@@ -0,0 +1,29 @@
import { packGrid } from '$lib/models/PokedexGridRow';
import { error, json } from '@sveltejs/kit';
import { requireAuth } from '$lib/utils/auth';
import PokedexRepository from '$lib/repositories/PokedexRepository';
import { loadPokedexGrid } from '$lib/services/PokedexGridService';
import { PokedexPerformance } from '$lib/server/pokedexPerformance';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async (event) => {
const timings = new PokedexPerformance();
const userId = await timings.measure('auth', () => requireAuth(event));
const pokedex = await timings.measure('ownership', () =>
new PokedexRepository(event.locals.supabase, userId).findById(event.params.id)
);
if (!pokedex) throw error(404, 'Pokédex not found');
const grid = await loadPokedexGrid(event.locals.supabase, userId, pokedex, timings);
const packed = timings.prepare(() => packGrid(grid));
timings.recordAuth(event.locals.pokedexAuthMs);
const timing = timings.finish();
return json(
{ grid: packed },
{
headers: {
'cache-control': 'private, no-store',
...(timing ? { 'server-timing': timing } : {})
}
}
);
};
+26 -40
View File
@@ -1,47 +1,33 @@
import { packGrid } from '$lib/models/PokedexGridRow';
import { error, redirect } from '@sveltejs/kit'; import { error, redirect } from '@sveltejs/kit';
import PokedexRepository from '$lib/repositories/PokedexRepository'; import PokedexRepository from '$lib/repositories/PokedexRepository';
import { loadCombinedDataPage } from '$lib/services/CombinedDataService'; import { loadPokedexGrid } from '$lib/services/PokedexGridService';
import { PokedexPerformance } from '$lib/server/pokedexPerformance';
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
// Must match the page's itemsPerPage: the box view needs the whole dex in one page. export const load: PageServerLoad = async ({ locals, params, setHeaders, cookies }) => {
const INITIAL_PAGE_SIZE = 9999; const timings = new PokedexPerformance();
const { session, user } = await timings.measure('auth', () => locals.safeGetSession());
export const load: PageServerLoad = async ({ locals, params }) => { if (!session || !user) throw redirect(303, '/signin');
const { safeGetSession, supabase } = locals; const pokedex = await timings.measure('ownership', () =>
const { session, user } = await safeGetSession(); new PokedexRepository(locals.supabase, user.id).findById(params.id)
);
// Require authentication if (!pokedex) throw error(404, 'Pokédex not found');
if (!session || !user) { let grid = null;
throw redirect(303, '/signin'); try {
grid = await loadPokedexGrid(locals.supabase, user.id, pokedex, timings);
} catch {
console.error('Unable to load Pokédex grid');
} }
const packed = timings.prepare(() => (grid ? packGrid(grid) : null));
const { id } = params; timings.recordAuth(locals.pokedexAuthMs);
const timing = timings.finish();
// Fetch pokédex to verify ownership (RLS will also block, but we want a proper 404) setHeaders({
const repo = new PokedexRepository(supabase, user.id); 'cache-control': 'private, no-store',
const pokedex = await repo.findById(id); ...(timing ? { 'server-timing': timing } : {})
if (!pokedex) {
// Either doesn't exist or user doesn't own it
throw error(404, 'Pokédex not found');
}
// Streamed rather than awaited: the page shell renders straight away and the entries arrive in
// the same response, instead of the browser requesting them after hydration. A failure resolves
// to null so the page falls back to fetching (and reporting) through the API.
const initialCombinedData = loadCombinedDataPage(supabase, user.id, pokedex, {
page: 1,
limit: INITIAL_PAGE_SIZE,
enableForms: pokedex.isFormDex
})
.then((result) => result.combinedData)
.catch((err) => {
console.error('Unable to preload combined data', err);
return null;
}); });
const layout = cookies.get('boxViewLayout');
return { const boxViewLayout: 'comfortable' | 'compact' | 'ultra' =
pokedex, layout === 'compact' || layout === 'ultra' ? layout : 'comfortable';
initialCombinedData return { pokedex, grid: packed, boxViewLayout };
};
}; };
+250 -121
View File
@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { onDestroy, onMount } from 'svelte'; import { onDestroy, onMount, tick } from 'svelte';
import { user } from '$lib/stores/user.js'; import { user } from '$lib/stores/user.js';
import { type User } from '@supabase/auth-js'; import { type User } from '@supabase/auth-js';
import { type CombinedData } from '$lib/models/CombinedData'; import { type CombinedData } from '$lib/models/CombinedData';
@@ -16,7 +16,7 @@
import PokedexEntryCatchRecord from '$lib/components/pokedex/PokedexEntryCatchRecord.svelte'; import PokedexEntryCatchRecord from '$lib/components/pokedex/PokedexEntryCatchRecord.svelte';
import type { Pokedex } from '$lib/models/Pokedex'; import type { Pokedex } from '$lib/models/Pokedex';
import type { PageData } from './$types'; import type { PageData } from './$types';
import { requestOfflineSync } from '$lib/stores/offlineSync'; import { readOfflineEntry, requestOfflineSync } from '$lib/stores/offlineSync';
import { get } from 'svelte/store'; import { get } from 'svelte/store';
import { import {
PROVIDER_LABELS, PROVIDER_LABELS,
@@ -25,7 +25,12 @@
refreshBackupStatus refreshBackupStatus
} from '$lib/stores/backupStatus'; } from '$lib/stores/backupStatus';
import type { ExportProvider } from '$lib/models/PokedexExportIntegration'; import type { ExportProvider } from '$lib/models/PokedexExportIntegration';
import type { SharedCombinedData } from '$lib/models/SharedPokedex'; import {
unpackGrid,
type PokedexGridRow,
type CatchRecordPatch
} from '$lib/models/PokedexGridRow';
import PokemonSprite from '$lib/components/PokemonSprite.svelte';
export let data: PageData; export let data: PageData;
@@ -42,19 +47,17 @@
} }
} }
let combinedData = null as CombinedData[] | null; let combinedData: PokedexGridRow[] | null = null;
let currentPage = 1 as number;
// Box view requires the full dataset for correct box numbering/placement.
// If/when a paginated list view is introduced, this can be lowered and paired with UI controls.
let itemsPerPage = 9999 as number;
type CatchUpdateEvent = CustomEvent<{ type CatchUpdateEvent = CustomEvent<{
catchRecord: CatchRecord; catchRecord: CatchRecord;
source: 'toggle' | 'notes' | 'notes-blur'; source: 'toggle' | 'notes' | 'notes-blur';
changes?: Partial<CatchRecord>;
}>; }>;
let creatingRecords = false; let creatingRecords = false;
let totalRecordsCreated = 0; let totalRecordsCreated = 0;
let failedToLoad = false; let failedToLoad = false;
let localUser: User | null; let localUser: User | null = data.user ?? null;
let userStoreReady = false;
let boxNumbers: number[] = []; let boxNumbers: number[] = [];
let showModal = false; let showModal = false;
let selectedPokemon: CombinedData | null = null; let selectedPokemon: CombinedData | null = null;
@@ -62,6 +65,7 @@
let shareUrl = ''; let shareUrl = '';
let shareFeedback = ''; let shareFeedback = '';
let nativeShareSupported = false; let nativeShareSupported = false;
let online = true;
let catchWriteQueue: ReturnType<typeof createCatchRecordWriteQueue> | null = null; let catchWriteQueue: ReturnType<typeof createCatchRecordWriteQueue> | null = null;
let catchWriteQueueKey: string | null = null; let catchWriteQueueKey: string | null = null;
@@ -170,9 +174,13 @@
$: showShiny = !!pokedex?.isShinyDex; $: showShiny = !!pokedex?.isShinyDex;
const unsubscribe = user.subscribe((value) => { const unsubscribe = user.subscribe((value) => {
localUser = value; if (userStoreReady) localUser = value;
}); });
onDestroy(unsubscribe); onDestroy(unsubscribe);
onDestroy(() => {
detailRequest++;
detailAbort?.abort();
});
onDestroy(() => { onDestroy(() => {
catchWriteQueueUnsubscribe?.(); catchWriteQueueUnsubscribe?.();
catchWriteQueueUnsubscribe = null; catchWriteQueueUnsubscribe = null;
@@ -181,9 +189,74 @@
resetExportState(); resetExportState();
}); });
function openPokemonModal(pokemon: CombinedData | SharedCombinedData) { let selectedSummary: PokedexGridRow | null = null;
selectedPokemon = pokemon as CombinedData; let detailError = '';
let detailRequest = 0;
let detailAbort: AbortController | null = null;
let returnFocus: HTMLElement | null = null;
const detailCache = new Map<string, CombinedData>();
let detailOwner = '';
$: if (localUser?.id !== detailOwner) {
detailOwner = localUser?.id ?? '';
detailCache.clear();
closePokemonModal();
}
async function openPokemonModal(pokemon: PokedexGridRow) {
if (!showModal) returnFocus = document.activeElement as HTMLElement;
selectedSummary = pokemon;
selectedPokemon = null;
detailError = '';
showModal = true; showModal = true;
const request = ++detailRequest;
detailAbort?.abort();
detailAbort = new AbortController();
const id = pokedexId;
const owner = localUser?.id || '';
const entryId = pokemon.pokedexEntry._id;
const key = `${owner}:${id}:${entryId}`;
try {
let detail = detailCache.get(key);
if (!detail) {
if (!navigator.onLine) detail = (await readOfflineEntry(owner, id, entryId)) ?? undefined;
else {
const response = await fetch(`/api/pokedexes/${id}/entries/${entryId}`, {
signal: detailAbort.signal
});
if (!response.ok) throw new Error('Unable to load details. Please retry.');
detail = await response.json();
}
}
if (request !== detailRequest || id !== pokedexId || owner !== localUser?.id) return;
if (!detail) throw new Error('These details are not saved for offline use.');
detailCache.set(key, detail);
// A detail response must not undo status changes made while it was in flight.
const current = combinedData?.find((row) => row.pokedexEntry._id === entryId)?.catchRecord;
const pending = catchWriteQueue?.getPendingPatch(entryId);
selectedPokemon = {
...detail,
catchRecord:
detail.catchRecord || current || pending
? {
_id: '',
userId: owner,
pokedexId: id,
pokemonId: entryId,
caught: false,
haveToEvolve: false,
inHome: false,
hasGigantamaxed: false,
personalNotes: '',
...detail.catchRecord,
...current,
...pending
}
: null
};
} catch (error) {
if (request !== detailRequest || id !== pokedexId || owner !== localUser?.id) return;
detailError = error instanceof Error ? error.message : 'Unable to load details.';
}
} }
function openShareModal() { function openShareModal() {
@@ -223,15 +296,24 @@
} }
function closePokemonModal() { function closePokemonModal() {
detailRequest++;
detailAbort?.abort();
showModal = false; showModal = false;
selectedPokemon = null; selectedPokemon = null;
selectedSummary = null;
if (browser && returnFocus) {
const target = returnFocus;
void tick().then(() => target.isConnected && target.focus());
}
returnFocus = null;
} }
function ensureCatchWriteQueue() { function ensureCatchWriteQueue() {
if (!browser) return; if (!browser) return;
if (!pokedexId) return; if (!pokedexId) return;
if (!localUser?.id) return; if (!localUser?.id) return;
const desiredKey = `${localUser.id}:${pokedexId}`; const ownerId = localUser.id;
const desiredKey = `${ownerId}:${pokedexId}`;
if (catchWriteQueue && catchWriteQueueKey === desiredKey) return; if (catchWriteQueue && catchWriteQueueKey === desiredKey) return;
resetExportState(); resetExportState();
@@ -244,7 +326,8 @@
endpointUrl: `/api/pokedexes/${pokedexId}/catch-records`, endpointUrl: `/api/pokedexes/${pokedexId}/catch-records`,
fetchFn: fetch, fetchFn: fetch,
batchSize: 200, batchSize: 200,
concurrency: 1 concurrency: 1,
isCurrentUser: () => get(user)?.id === ownerId
}); });
catchWriteQueueKey = desiredKey; catchWriteQueueKey = desiredKey;
@@ -271,67 +354,93 @@
}); });
} }
function applyOptimisticCatchRecordUpdate(next: CatchRecord) { let editGeneration = 0;
function applyOptimisticCatchRecordUpdate(next: CatchRecordPatch) {
if (!combinedData) return; if (!combinedData) return;
const idx = combinedData.findIndex((cd) => cd.pokedexEntry._id === next.pokemonId); editGeneration++;
if (idx === -1) return; combinedData = combinedData.map((row) =>
// Replace the catchRecord entry with the updated version. row.pokedexEntry._id === next.pokemonId
const current = combinedData[idx]; ? {
const patched: CombinedData = { ...row,
...current,
catchRecord: { catchRecord: {
...(current.catchRecord ?? next), _id: '',
caught: false,
haveToEvolve: false,
inHome: false,
hasGigantamaxed: false,
...row.catchRecord,
...next
}
}
: row
);
const key = `${next.userId}:${next.pokedexId}:${next.pokemonId}`;
const cached = detailCache.get(key);
if (cached)
detailCache.set(key, {
...cached,
catchRecord: {
_id: '',
caught: false,
haveToEvolve: false,
inHome: false,
hasGigantamaxed: false,
personalNotes: '',
...cached.catchRecord,
...next
}
});
if (selectedPokemon?.pokedexEntry._id === next.pokemonId)
selectedPokemon = {
...selectedPokemon,
catchRecord: {
_id: '',
caught: false,
haveToEvolve: false,
inHome: false,
hasGigantamaxed: false,
personalNotes: '',
...selectedPokemon.catchRecord,
...next ...next
} }
}; };
combinedData = [...combinedData.slice(0, idx), patched, ...combinedData.slice(idx + 1)];
if (selectedPokemon?.pokedexEntry._id === next.pokemonId) {
selectedPokemon = patched;
}
} }
async function handleModalCatchUpdate(event: CatchUpdateEvent) { async function handleModalCatchUpdate(event: CatchUpdateEvent) {
await updateACatch(event); await updateACatch(event);
} }
type GetDataOptions = { let gridRequest = 0;
page?: number; async function getData({ setCombinedDataToNull = true } = {}) {
perPage?: number; const id = pokedexId;
setCombinedDataToNull?: boolean; const owner = localUser?.id;
}; const request = ++gridRequest;
const generation = editGeneration;
async function getData({ if (setCombinedDataToNull) combinedData = null;
page = currentPage, failedToLoad = false;
perPage = itemsPerPage, try {
setCombinedDataToNull = true const response = await fetch(`/api/pokedexes/${id}/grid`);
}: GetDataOptions = {}) { if (!response.ok) throw new Error('Unable to load grid');
if (!pokedex || !pokedexId) return; const result = await response.json();
if (setCombinedDataToNull) { if (
combinedData = null; request !== gridRequest ||
} id !== pokedexId ||
const effectivePage = Math.max(1, page); owner !== localUser?.id ||
const effectivePerPage = Math.max(1, perPage); generation !== editGeneration
// Use new pokédex-scoped endpoint )
const endpoint = `/api/pokedexes/${pokedexId}/combined-data?page=${effectivePage}&limit=${effectivePerPage}&enableForms=${pokedex.isFormDex}`;
const response = await fetch(endpoint);
const fetchedData = await response.json();
if (fetchedData.error) {
failedToLoad = true;
return; return;
} combinedData = unpackGrid(result.grid);
combinedData = fetchedData.combinedData; detailCache.clear();
// Always extract box numbers for box view } catch {
if (combinedData) { if (request === gridRequest && id === pokedexId && owner === localUser?.id)
boxNumbers = calculateBoxNumbers(combinedData.length); failedToLoad = true;
} }
} }
async function updateACatch(event: CatchUpdateEvent) { async function updateACatch(event: CatchUpdateEvent) {
if (!pokedexId) return; if (!pokedexId) return;
ensureCatchWriteQueue(); ensureCatchWriteQueue();
const { catchRecord, source } = event.detail; const { catchRecord, source, changes } = event.detail;
// Enforce mutual exclusivity (should be impossible to have both true). // Enforce mutual exclusivity (should be impossible to have both true).
const sanitizedCatchRecord: CatchRecord = { ...catchRecord }; const sanitizedCatchRecord: CatchRecord = { ...catchRecord };
if (sanitizedCatchRecord.caught) { if (sanitizedCatchRecord.caught) {
@@ -346,11 +455,25 @@
} }
// Optimistic UI: update local state immediately. // Optimistic UI: update local state immediately.
applyOptimisticCatchRecordUpdate(sanitizedCatchRecord); const patch: CatchRecordPatch = {
userId: localUser.id,
pokedexId,
pokemonId: sanitizedCatchRecord.pokemonId,
...(changes ??
(source === 'toggle'
? {
caught: sanitizedCatchRecord.caught,
haveToEvolve: sanitizedCatchRecord.haveToEvolve,
inHome: sanitizedCatchRecord.inHome,
hasGigantamaxed: sanitizedCatchRecord.hasGigantamaxed
}
: { personalNotes: sanitizedCatchRecord.personalNotes }))
};
applyOptimisticCatchRecordUpdate(patch);
// Queue a background write with coalescing. // Queue a background write with coalescing.
const debounceMs = source === 'notes' ? 650 : 0; const debounceMs = source === 'notes' ? 650 : 0;
catchWriteQueue?.enqueue(sanitizedCatchRecord, { catchWriteQueue?.enqueue(patch, {
debounceMs, debounceMs,
flushSoon: true flushSoon: true
}); });
@@ -375,37 +498,14 @@
if (!pokedexId) return; if (!pokedexId) return;
ensureCatchWriteQueue(); ensureCatchWriteQueue();
const catchRecordsToUpdate: CatchRecord[] = combinedData const catchRecordsToUpdate: CatchRecordPatch[] = combinedData
.filter((_, index) => calculateBoxPlacement(index).box === boxNumber) .filter((_, index) => calculateBoxPlacement(index).box === boxNumber)
.map(({ pokedexEntry, catchRecord }) => { .map(({ pokedexEntry }) => ({
// Create default record if null
const baseRecord: CatchRecord = catchRecord ?? {
_id: '',
userId: localUser?.id || '', userId: localUser?.id || '',
pokedexId,
pokemonId: pokedexEntry._id, pokemonId: pokedexEntry._id,
pokedexId: pokedexId, ...(inHome !== null ? { inHome } : { caught, haveToEvolve: needsToEvolve })
haveToEvolve: false, }));
caught: false,
inHome: false,
hasGigantamaxed: false,
personalNotes: ''
};
let updatedRecord: CatchRecord = { ...baseRecord };
if (inHome !== null) {
updatedRecord = {
...updatedRecord,
inHome
};
} else {
updatedRecord = {
...updatedRecord,
caught,
haveToEvolve: needsToEvolve
};
}
return updatedRecord;
});
// Optimistic patch: apply locally first. // Optimistic patch: apply locally first.
for (const record of catchRecordsToUpdate) { for (const record of catchRecordsToUpdate) {
@@ -498,42 +598,25 @@
creatingRecords = false; creatingRecords = false;
failedToLoad = false; failedToLoad = false;
await getData({ page: currentPage, perPage: itemsPerPage }); await getData();
}); });
} }
// Show data whenever the dex or pagination changes (client-side only). The first page is streamed let shownData: PageData | undefined;
// from the server load, so it only needs fetching when that failed or the page changes. $: if (data !== shownData) {
let shownKey = ''; shownData = data;
function showPage( localUser = data.user ?? null;
id: string, gridRequest++;
page: number, closePokemonModal();
perPage: number, detailCache.clear();
initial: Promise<CombinedData[] | null> | undefined combinedData = data.grid ? unpackGrid(data.grid) : null;
) { failedToLoad = data.grid === null;
const key = `${id}:${page}:${perPage}`;
if (key === shownKey) return;
shownKey = key;
if (page !== 1 || !initial) {
void getData({ page, perPage });
return;
} }
combinedData = null; $: boxNumbers = calculateBoxNumbers(combinedData?.length ?? 0);
void initial.then((rows) => {
if (shownKey !== key) return;
if (!rows) {
void getData({ page, perPage });
return;
}
combinedData = rows;
boxNumbers = calculateBoxNumbers(rows.length);
});
}
$: if (browser && pokedexId)
showPage(pokedexId, currentPage, itemsPerPage, data?.initialCombinedData);
onMount(() => { onMount(() => {
if (!browser) return; if (!browser) return;
userStoreReady = true;
nativeShareSupported = typeof navigator.share === 'function'; nativeShareSupported = typeof navigator.share === 'function';
const flushKeepalive = () => { const flushKeepalive = () => {
@@ -546,7 +629,15 @@
if (document.visibilityState === 'hidden') flushKeepalive(); if (document.visibilityState === 'hidden') flushKeepalive();
}; };
const onOnline = () => void catchWriteQueue?.flushNow(); online = navigator.onLine;
const onOffline = () => {
online = false;
};
const onOnline = () => {
online = true;
void catchWriteQueue?.flushNow();
};
window.addEventListener('offline', onOffline);
window.addEventListener('pagehide', flushKeepalive); window.addEventListener('pagehide', flushKeepalive);
document.addEventListener('visibilitychange', onVisibilityChange); document.addEventListener('visibilitychange', onVisibilityChange);
@@ -557,13 +648,14 @@
if (!pokedexId) return; if (!pokedexId) return;
if (creatingRecords) return; if (creatingRecords) return;
if (catchWriteStatus.pending > 0 || catchWriteStatus.inFlight > 0) return; if (catchWriteStatus.pending > 0 || catchWriteStatus.inFlight > 0) return;
void getData({ page: currentPage, perPage: itemsPerPage, setCombinedDataToNull: false }); void getData({ setCombinedDataToNull: false });
}, 60_000); }, 60_000);
return () => { return () => {
window.removeEventListener('pagehide', flushKeepalive); window.removeEventListener('pagehide', flushKeepalive);
document.removeEventListener('visibilitychange', onVisibilityChange); document.removeEventListener('visibilitychange', onVisibilityChange);
window.removeEventListener('online', onOnline); window.removeEventListener('online', onOnline);
window.removeEventListener('offline', onOffline);
window.clearInterval(reconcileInterval); window.clearInterval(reconcileInterval);
}; };
}); });
@@ -767,7 +859,7 @@
<!-- Box View --> <!-- Box View -->
<PokedexViewBoxes <PokedexViewBoxes
{showShiny} {showShiny}
bind:combinedData {combinedData}
bind:boxNumbers bind:boxNumbers
bind:creatingRecords bind:creatingRecords
{totalRecordsCreated} {totalRecordsCreated}
@@ -778,12 +870,20 @@
{markBoxAsInHome} {markBoxAsInHome}
{markBoxAsNotInHome} {markBoxAsNotInHome}
{createCatchRecords} {createCatchRecords}
onPokemonClick={openPokemonModal} retryLoad={() => getData()}
virtualize={true}
gridKey={pokedexId}
initialLayout={data.boxViewLayout}
onPokemonClick={(row) => {
const own = combinedData?.find((entry) => entry.pokedexEntry._id === row.pokedexEntry._id);
if (own) void openPokemonModal(own);
}}
/> />
</div> </div>
{#if showModal && selectedPokemon} {#if showModal && selectedSummary}
<PokedexModal isOpen={showModal} onClose={closePokemonModal}> <PokedexModal isOpen={showModal} onClose={closePokemonModal}>
{#if selectedPokemon}
<PokedexEntryCatchRecord <PokedexEntryCatchRecord
pokedexEntry={selectedPokemon.pokedexEntry} pokedexEntry={selectedPokemon.pokedexEntry}
bind:catchRecord={selectedPokemon.catchRecord} bind:catchRecord={selectedPokemon.catchRecord}
@@ -793,7 +893,36 @@
userId={localUser?.id} userId={localUser?.id}
{pokedexId} {pokedexId}
on:updateCatch={handleModalCatchUpdate} on:updateCatch={handleModalCatchUpdate}
readOnly={!online}
sharedCatchStatus={selectedPokemon.catchRecord}
/> />
{#if !online && selectedPokemon.catchRecord?.personalNotes}<p class="p-6">
Notes: {selectedPokemon.catchRecord.personalNotes}
</p>{/if}
{:else}
<div class="p-6" aria-busy={!detailError}>
<h2 class="text-xl font-bold">{selectedSummary.pokedexEntry.pokemon}</h2>
<div class="w-64 h-64">
<PokemonSprite
pokemonName={selectedSummary.pokedexEntry.pokemon}
pokedexNumber={selectedSummary.pokedexEntry.pokedexNumber}
form={selectedSummary.pokedexEntry.form}
spriteKey={selectedSummary.pokedexEntry.spriteKey}
shiny={showShiny}
loadingStrategy="eager"
/>
</div>
{#if detailError}
<p role="alert">{detailError}</p>
<button
class="btn"
data-offline-action
on:click={() => selectedSummary && openPokemonModal(selectedSummary)}
>Retry details</button
>
{:else}<p role="status">Loading details…</p>{/if}
</div>
{/if}
</PokedexModal> </PokedexModal>
{/if} {/if}
+6 -1
View File
@@ -83,7 +83,12 @@
showShiny={shared.isShinyDex} showShiny={shared.isShinyDex}
combinedData={shared.combinedData} combinedData={shared.combinedData}
{boxNumbers} {boxNumbers}
onPokemonClick={handlePokemonClick} onPokemonClick={(row) => {
const full = shared.combinedData.find(
(entry) => entry.pokedexEntry._id === row.pokedexEntry._id
);
if (full) handlePokemonClick(full);
}}
/> />
</div> </div>
+1 -1
View File
@@ -74,7 +74,7 @@ async function missingSprites(cache, root) {
// Covers both the local `/sprites-small/...` folder and the GitHub-hosted copy of it. // Covers both the local `/sprites-small/...` folder and the GitHub-hosted copy of it.
function isSpriteUrl(url) { function isSpriteUrl(url) {
return /\/sprites(-small)?\//.test(url.pathname) && url.pathname.endsWith('.webp'); return /\/sprites(?:-small|-grid\/v1)?\//.test(url.pathname) && url.pathname.endsWith('.webp');
} }
async function currentOfflineMeta() { async function currentOfflineMeta() {
+1 -1
View File
@@ -10,7 +10,7 @@ const config = {
preprocess: vitePreprocess(), preprocess: vitePreprocess(),
kit: { kit: {
// Netlify by default, or the node adapter when NODE_ADAPTER=true. See adapter.mjs. // Netlify by default; DEPLOY_TARGET selects the Cloudflare preview or Node test build.
adapter, adapter,
serviceWorker: { serviceWorker: {
// VitePWA owns registration. Registering here as well requests SvelteKit's default // VitePWA owns registration. Registering here as well requests SvelteKit's default
+1 -1
View File
@@ -12,7 +12,7 @@ Feature: Signed-in page speed
Scenario: A Pokédex opens without a second round trip for its entries Scenario: A Pokédex opens without a second round trip for its entries
When I load the Pokédex page directly When I load the Pokédex page directly
Then its entries appear within 5 seconds Then its entries appear within 5 seconds
And the browser did not request the entries separately And the browser did not request the grid separately
Scenario: Moving between my Pokédex list and a Pokédex is quick Scenario: Moving between my Pokédex list and a Pokédex is quick
When I switch between my Pokédex list and the Pokédex When I switch between my Pokédex list and the Pokédex
+4 -3
View File
@@ -23,7 +23,8 @@ When('I load the Pokédex page directly', async ({ page, state }) => {
// Only requests made while the page first loads matter; the page's 60s reconciliation refetch // Only requests made while the page first loads matter; the page's 60s reconciliation refetch
// can't fire within this window. // can't fire within this window.
const countEntryRequests = (request: { url(): string }) => { const countEntryRequests = (request: { url(): string }) => {
if (/\/api\/pokedexes\/[^/]+\/combined-data/.test(request.url())) record.entryRequests++; if (/\/api\/pokedexes\/[^/]+\/(?:grid|combined-data)/.test(request.url()))
record.entryRequests++;
}; };
page.on('request', countEntryRequests); page.on('request', countEntryRequests);
@@ -40,8 +41,8 @@ Then('its entries appear within {int} seconds', async ({ page }, seconds: number
expect(entriesMs!).toBeLessThan(seconds * 1000); expect(entriesMs!).toBeLessThan(seconds * 1000);
}); });
Then('the browser did not request the entries separately', async ({ page }) => { Then('the browser did not request the grid separately', async ({ page }) => {
// The server load streams the first page of entries with the HTML, so the page must not make // The server load includes the compact grid with the HTML, so the page must not make
// the old hydrate-then-fetch round trip. // the old hydrate-then-fetch round trip.
expect(timings.get(page)?.entryRequests).toBe(0); expect(timings.get(page)?.entryRequests).toBe(0);
}); });
@@ -0,0 +1,132 @@
import { packGrid, unpackGrid } from '$lib/models/PokedexGridRow';
import { createClient, type SupabaseClient } from '@supabase/supabase-js';
import { beforeAll, afterAll, describe, expect, it } from 'vitest';
import { requireLoopbackUrl } from '../support/loopback';
import PokedexRepository from '$lib/repositories/PokedexRepository';
import CombinedDataRepository from '$lib/repositories/CombinedDataRepository';
import CatchRecordRepository from '$lib/repositories/CatchRecordRepository';
import { loadPokedexGrid, loadPokedexEntryDetail } from '$lib/services/PokedexGridService';
import type { Pokedex } from '$lib/models/Pokedex';
const url = requireLoopbackUrl(
process.env.TEST_SUPABASE_URL ?? 'http://127.0.0.1:54321',
'TEST_SUPABASE_URL'
);
const serviceKey = process.env.E2E_SERVICE_ROLE_KEY ?? process.env.SUPABASE_SERVICE_ROLE_KEY;
const anonKey = process.env.TEST_SUPABASE_ANON_KEY;
describe('compact Pokédex and partial catch writes', () => {
let admin: SupabaseClient;
let client: SupabaseClient;
let owner = '';
let national: Pokedex;
let scoped: Pokedex;
let firstId: string;
let secondId: string;
beforeAll(async () => {
if (!serviceKey || !anonKey) throw new Error('Use npm run test:integration');
admin = createClient(url, serviceKey, { auth: { persistSession: false } });
const email = `grid-${crypto.randomUUID()}@example.test`;
const password = crypto.randomUUID();
const created = await admin.auth.admin.createUser({ email, password, email_confirm: true });
if (created.error) throw created.error;
owner = created.data.user.id;
client = createClient(url, anonKey, { auth: { persistSession: false } });
const signed = await client.auth.signInWithPassword({ email, password });
if (signed.error) throw signed.error;
const repo = new PokedexRepository(client, owner);
national = await repo.create({ name: 'Grid national', isFormDex: false });
scoped = await repo.create({ name: 'Grid forms', isFormDex: true, gameScope: 'Scarlet' });
const links = await client
.from('pokedex_dex_scopes')
.insert({ pokedexId: scoped._id, dexId: 'scarlet-paldea' });
if (links.error) throw links.error;
scoped = (await repo.findById(scoped._id))!;
const grid = await loadPokedexGrid(client, owner, national);
[firstId, secondId] = grid.slice(0, 2).map((row) => row.pokedexEntry._id);
});
afterAll(async () => {
if (owner) await admin.auth.admin.deleteUser(owner);
});
it('loads saved scopes with ownership and prevents cross-account reads', async () => {
expect(scoped.dexScopes).toEqual(['scarlet-paldea']);
const other = new PokedexRepository(client, crypto.randomUUID());
expect(await other.findById(scoped._id)).toBeNull();
});
it('matches full ordering and statuses while reducing serialized rows by at least 60%', async () => {
for (const dex of [national, scoped]) {
const initial = await loadPokedexGrid(client, owner, dex);
const catches = new CatchRecordRepository(client, owner, dex._id);
for (let offset = 0; offset < initial.length - 1; offset += 500)
await catches.bulkUpsert(
initial.slice(offset, Math.min(offset + 500, initial.length - 1)).map((row, index) => ({
pokemonId: row.pokedexEntry._id,
caught: index % 3 === 0,
inHome: index % 7 === 0,
personalNotes: ''
}))
);
const grid = await loadPokedexGrid(client, owner, dex);
const full = await new CombinedDataRepository(client, owner, dex._id).findAllCombinedData(
owner,
dex.isFormDex,
'',
dex.gameScope || '',
dex.dexScopes
);
expect(grid.map((row) => row.pokedexEntry._id)).toEqual(
full.map((row) => row.pokedexEntry._id)
);
expect(grid.length).toBeGreaterThan(400);
expect(unpackGrid(packGrid(grid))).toEqual(grid);
expect(JSON.stringify(packGrid(grid)).length).toBeLessThan(JSON.stringify(full).length * 0.4);
expect(JSON.stringify(grid)).not.toContain('personalNotes');
expect(JSON.stringify(grid)).not.toContain('catchInformation');
}
});
it('preserves omitted notes and statuses in mixed partial bulk writes, including new records', async () => {
const repo = new CatchRecordRepository(client, owner, national._id);
await repo.bulkUpsert([
{ pokemonId: firstId, personalNotes: 'Keep this note', caught: true, inHome: true }
]);
await repo.bulkUpsert([
{ pokemonId: firstId, haveToEvolve: true, caught: false },
{ pokemonId: secondId, personalNotes: 'New record' }
]);
expect(await repo.findByUserAndPokemon(owner, firstId, national._id)).toMatchObject({
personalNotes: 'Keep this note',
caught: false,
haveToEvolve: true,
inHome: true
});
expect(await repo.findByUserAndPokemon(owner, secondId, national._id)).toMatchObject({
personalNotes: 'New record',
caught: false
});
await repo.bulkUpsert([{ pokemonId: firstId, personalNotes: '' }]);
expect(await repo.findByUserAndPokemon(owner, firstId, national._id)).toMatchObject({
personalNotes: '',
inHome: true,
haveToEvolve: true
});
});
it('returns full details only for members of this dex', async () => {
const detail = await loadPokedexEntryDetail(client, owner, national, Number(firstId));
expect(detail?.pokedexEntry).toHaveProperty('catchInformation');
expect(detail?.catchRecord).toHaveProperty('personalNotes');
expect(await loadPokedexEntryDetail(client, owner, national, 999999)).toBeNull();
const forms = await loadPokedexGrid(client, owner, scoped);
const base = new Set(
(await loadPokedexGrid(client, owner, national)).map((row) => row.pokedexEntry._id)
);
const formOnly = forms.find((row) => !base.has(row.pokedexEntry._id));
expect(formOnly).toBeDefined();
expect(
await loadPokedexEntryDetail(client, owner, national, Number(formOnly!.pokedexEntry._id))
).toBeNull();
});
});
+13 -1
View File
@@ -112,13 +112,25 @@ describe('refreshBackupStatus', () => {
const json = (body: unknown) => new Response(JSON.stringify(body)); const json = (body: unknown) => new Response(JSON.stringify(body));
it('ignores a response overtaken by a newer refresh', async () => { it('coalesces concurrent refreshes for the same account state', async () => {
const slow = deferredResponse();
fetchMock.mockReturnValueOnce(slow.promise);
const first = refreshBackupStatus();
const second = refreshBackupStatus();
expect(second).toBe(first);
expect(fetchMock).toHaveBeenCalledTimes(1);
slow.resolve(json([]));
await Promise.all([first, second]);
});
it('ignores a response overtaken by a new account refresh', async () => {
const slow = deferredResponse(); const slow = deferredResponse();
fetchMock fetchMock
.mockReturnValueOnce(slow.promise) .mockReturnValueOnce(slow.promise)
.mockResolvedValueOnce(json([{ provider: 'google_drive', enabled: true }])); .mockResolvedValueOnce(json([{ provider: 'google_drive', enabled: true }]));
const first = refreshBackupStatus(); const first = refreshBackupStatus();
clearBackupStatus();
await refreshBackupStatus(); await refreshBackupStatus();
slow.resolve(json([{ provider: 'google_drive', enabled: false }])); slow.resolve(json([{ provider: 'google_drive', enabled: false }]));
await first; await first;
+36
View File
@@ -28,6 +28,27 @@ describe('createCatchRecordWriteQueue()', () => {
vi.unstubAllGlobals(); vi.unstubAllGlobals();
}); });
it('merges partial notes/status patches without inventing omitted fields', async () => {
const fetchFn = vi.fn(async () => new Response('[]'));
const queue = createCatchRecordWriteQueue({ endpointUrl: '/api/catches', fetchFn });
const identity = { userId: 'u', pokedexId: 'd', pokemonId: '1' };
queue.enqueue({ ...identity, personalNotes: 'Keep' }, { flushSoon: false });
queue.enqueue({ ...identity, inHome: true }, { flushSoon: false });
expect(queue.getPendingPatch('1')).toEqual({
...identity,
personalNotes: 'Keep',
inHome: true
});
await queue.flushNow();
const payload = JSON.parse(
String((fetchFn.mock.calls[0] as unknown as [string, RequestInit])[1].body)
);
expect(payload).toEqual([{ ...identity, personalNotes: 'Keep', inHome: true }]);
queue.enqueue({ ...identity, personalNotes: '' }, { flushSoon: false });
expect(queue.getPendingPatch('1')?.personalNotes).toBe('');
await queue.flushNow();
});
it('coalesces multiple updates for the same key and flushes only the latest state', async () => { it('coalesces multiple updates for the same key and flushes only the latest state', async () => {
const fetchFn = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { const fetchFn = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
return new Response(init?.body as string, { status: 200 }); return new Response(init?.body as string, { status: 200 });
@@ -141,6 +162,21 @@ describe('createCatchRecordWriteQueue()', () => {
expect(queue.getPendingCount()).toBe(1); expect(queue.getPendingCount()).toBe(1);
}); });
it('discards queued edits after the owning account changes', async () => {
const fetchFn = vi.fn<typeof fetch>();
let current = true;
const queue = createCatchRecordWriteQueue({
endpointUrl: '/catch-records',
fetchFn,
isCurrentUser: () => current
});
queue.enqueue(mkRecord(), { debounceMs: 100, flushSoon: false });
current = false;
await queue.flushNow();
expect(fetchFn).not.toHaveBeenCalled();
expect(queue.getPendingCount()).toBe(0);
});
it('does not discard a newer version enqueued during an in-flight request', async () => { it('does not discard a newer version enqueued during an in-flight request', async () => {
let resolveFirst: ((response: Response) => void) | undefined; let resolveFirst: ((response: Response) => void) | undefined;
const firstResponse = new Promise<Response>((resolve) => (resolveFirst = resolve)); const firstResponse = new Promise<Response>((resolve) => (resolveFirst = resolve));
+122 -3
View File
@@ -11,7 +11,9 @@ type TableQuery = { table: string; calls: Call[] };
* `await query` / `await query.range(...)` resolve like a real PostgREST response. Returning * `await query` / `await query.range(...)` resolve like a real PostgREST response. Returning
* an empty data set keeps the repository's paging loops to a single iteration. * an empty data set keeps the repository's paging loops to a single iteration.
*/ */
function createSupabaseStub() { function createSupabaseStub(
resultFor: (table: string) => unknown = () => ({ data: [], error: null, count: 0 })
) {
const queries: TableQuery[] = []; const queries: TableQuery[] = [];
const from = (table: string) => { const from = (table: string) => {
@@ -23,8 +25,7 @@ function createSupabaseStub() {
{ {
get(_target, prop: string) { get(_target, prop: string) {
if (prop === 'then') { if (prop === 'then') {
return (resolve: (value: unknown) => unknown) => return (resolve: (value: unknown) => unknown) => resolve(resultFor(table));
resolve({ data: [], error: null, count: 0 });
} }
return (...args: unknown[]) => { return (...args: unknown[]) => {
record.calls.push({ method: prop, args }); record.calls.push({ method: prop, args });
@@ -115,3 +116,121 @@ describe('CombinedDataRepository base-form filtering', () => {
expect(mentionsIsDefaultForm(supplement)).toBe(false); expect(mentionsIsDefaultForm(supplement)).toBe(false);
}); });
}); });
describe('compact grid reads', () => {
const entry = {
id: 1,
pokedexNumber: 1,
pokemon: 'Bulbasaur',
form: null,
spriteKey: '1',
canGigantamax: false
};
it('joins catch flags by ID and retains entries without catches', async () => {
const { supabase } = createSupabaseStub((table) => ({
data:
table === 'catch_records'
? [{ id: 'catch', pokemonId: 1, caught: true, personalNotes: 'private' }]
: [entry, { ...entry, id: 2 }],
error: null
}));
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
const rows = await repo.joinGridCatches(await repo.findGridEntries(false, '', []));
expect(rows[0].catchRecord).toMatchObject({ _id: 'catch', caught: true });
expect(rows[0].catchRecord).not.toHaveProperty('personalNotes');
expect(rows[1].catchRecord).toBeNull();
});
it('deduplicates overlapping scopes without dropping named form supplements', async () => {
const base = { ...entry, pokemon: 'Rotom', form: 'Lightbulb', dexNumber: 1, dexSortOrder: 1 };
const { supabase } = createSupabaseStub((table) => ({
data:
table === 'game_pokedex_entry_details' ? [base, base] : [{ ...base, id: 2, form: 'Heat' }],
error: null
}));
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
const rows = await repo.findGridEntries(true, 'Black', ['one', 'two']);
expect(rows.map((row) => [row.id, row.form])).toEqual([
[1, 'Lightbulb'],
[2, 'Heat']
]);
});
it.each([[[]], [['scope']]])(
'reports entry query failure instead of an empty grid (%j)',
async (scopes) => {
const { supabase } = createSupabaseStub(() => ({
data: null,
error: { message: 'unavailable' }
}));
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
await expect(repo.findGridEntries(false, '', scopes)).rejects.toThrow('Unable to load');
}
);
it('reports catch failure instead of displaying everything as uncaught', async () => {
const { supabase } = createSupabaseStub((table) =>
table === 'catch_records'
? { data: null, error: { message: 'unavailable' } }
: { data: [entry], error: null }
);
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
await expect(repo.joinGridCatches(await repo.findGridEntries(false, '', []))).rejects.toThrow(
'Unable to load catch records'
);
});
it('keeps a failed detail read distinct from a missing entry', async () => {
const missing = createSupabaseStub(() => ({ data: null, error: null }));
expect(
await new CombinedDataRepository(missing.supabase, 'owner', 'dex').findEntryDetail(1)
).toBeNull();
const failed = createSupabaseStub(() => ({ data: null, error: { message: 'unavailable' } }));
await expect(
new CombinedDataRepository(failed.supabase, 'owner', 'dex').findEntryDetail(1)
).rejects.toThrow('Unable to load entry details');
});
it.each([false, true])(
'returns full instructions with optional catch notes (caught: %s)',
async (caught) => {
const { supabase } = createSupabaseStub((table) => ({
data:
table === 'catch_records'
? caught
? [
{
id: 'catch',
pokemonId: 1,
userId: 'owner',
pokedexId: 'dex',
personalNotes: 'Saved note'
}
]
: []
: { ...entry, catchInformation: 'Full instructions' },
error: null
}));
const result = await new CombinedDataRepository(supabase, 'owner', 'dex').findEntryDetail(1);
expect(result?.pokedexEntry.catchInformation).toBe('Full instructions');
if (caught) expect(result?.catchRecord?.personalNotes).toBe('Saved note');
else expect(result?.catchRecord).toBeNull();
}
);
it('shares a scoped read between simultaneous rows and count requests', async () => {
const { supabase, queries } = createSupabaseStub();
const repo = new CombinedDataRepository(supabase, 'owner', 'dex');
await Promise.all([
repo.findCombinedData('owner', 1, 30, true, '', 'Scarlet', ['scarlet-paldea']),
repo.countCombinedData(true, '', 'Scarlet', ['scarlet-paldea'])
]);
expect(queryFor(queries, 'game_pokedex_entry_details')).toHaveLength(1);
expect(queryFor(queries, 'pokedex_entries')).toHaveLength(1);
});
it('selects compact columns and does not count the full grid', async () => {
const { supabase, queries } = createSupabaseStub();
const repo = new CombinedDataRepository(supabase, 'owner', 'dex', true);
await repo.joinGridCatches(await repo.findGridEntries(false, '', []));
expect(queries).toHaveLength(1);
const selection = queries[0].calls.find((call) => call.method === 'select');
expect(selection?.args[0]).not.toContain('*');
expect(selection?.args[0]).not.toContain('notes');
expect(selection?.args[0]).not.toContain('Information');
expect(selection?.args).toHaveLength(1);
});
});
+103
View File
@@ -0,0 +1,103 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { afterCriticalPageWork, markGridInteractive } from '$lib/utils/criticalPageWork';
describe('optional work scheduling', () => {
let events: EventTarget & Record<string, unknown>;
let idle: (() => void) | undefined;
beforeEach(() => {
vi.useFakeTimers();
events = Object.assign(new EventTarget(), {
setTimeout,
clearTimeout,
requestIdleCallback: vi.fn((callback: () => void) => {
idle = callback;
return 1;
}),
cancelIdleCallback: vi.fn()
});
idle = undefined;
vi.stubGlobal('window', events);
vi.stubGlobal('location', { pathname: '/pokedex/example' });
vi.stubGlobal('document', { querySelector: () => null });
vi.stubGlobal('requestAnimationFrame', (callback: () => void) => setTimeout(callback, 16));
vi.stubGlobal('cancelAnimationFrame', clearTimeout);
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('waits for interactive cells, coalesces events, then runs at idle once', () => {
const run = vi.fn();
afterCriticalPageWork(run);
vi.advanceTimersByTime(1000);
expect(run).not.toHaveBeenCalled();
events.dispatchEvent(new Event('livingdex:grid-interactive'));
events.dispatchEvent(new Event('livingdex:grid-interactive'));
vi.advanceTimersByTime(16);
expect(events.requestIdleCallback).toHaveBeenCalledTimes(1);
expect(run).not.toHaveBeenCalled();
idle!();
vi.advanceTimersByTime(5000);
expect(run).toHaveBeenCalledTimes(1);
});
it('falls back after five seconds if no grid becomes interactive', () => {
const run = vi.fn();
afterCriticalPageWork(run);
vi.advanceTimersByTime(4999);
expect(run).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(run).toHaveBeenCalledTimes(1);
});
it('cancels work after navigation or an explicit refresh takes over', () => {
const run = vi.fn();
const cancel = afterCriticalPageWork(run);
events.dispatchEvent(new Event('livingdex:grid-interactive'));
vi.advanceTimersByTime(16);
cancel();
idle!();
vi.advanceTimersByTime(5000);
expect(run).not.toHaveBeenCalled();
});
it('does not announce a grid with no populated cells', () => {
const listener = vi.fn();
events.addEventListener('livingdex:grid-interactive', listener);
markGridInteractive();
expect(listener).not.toHaveBeenCalled();
});
it('schedules other pages without waiting for a grid, even without idle callbacks', () => {
vi.stubGlobal('location', { pathname: '/backup-settings' });
delete events.requestIdleCallback;
const run = vi.fn();
afterCriticalPageWork(run);
vi.advanceTimersByTime(32);
expect(run).toHaveBeenCalledTimes(1);
});
it('marks populated cells once and allows work registered after hydration', () => {
let ready = false;
const grid = {
setAttribute: () => {
ready = true;
}
};
const cell = { closest: () => grid };
vi.stubGlobal('document', {
querySelector: (selector: string) =>
selector === '[data-entry-index]' ? cell : ready ? grid : null
});
const mark = vi.fn();
vi.stubGlobal('performance', { mark });
markGridInteractive();
markGridInteractive();
expect(mark).toHaveBeenCalledTimes(1);
const run = vi.fn();
afterCriticalPageWork(run);
vi.advanceTimersByTime(16);
idle!();
expect(run).toHaveBeenCalledTimes(1);
});
it('does not access the DOM during SSR', () => {
vi.stubGlobal('window', undefined);
expect(() => markGridInteractive()).not.toThrow();
});
});
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest';
import { resolveGridSpriteUrl, resolveSpriteUrl } from '$lib/utils/spriteUrl';
describe('versioned grid artwork', () => {
it('separates grid and detail URLs for shiny, female and named forms', () => {
for (const form of ['', 'Female', 'Alolan', 'Female Mega']) {
for (const shiny of [false, true]) {
const entry = { pokedexNumber: 25, form, spriteKey: '25' };
const grid = resolveGridSpriteUrl(entry, shiny);
expect(grid).toBe(
resolveSpriteUrl(entry, shiny, true).replace(
'/sprites-small/home/',
'/sprites-grid/v1/home/'
)
);
expect(resolveSpriteUrl(entry, shiny, true)).not.toContain('sprites-grid');
}
}
});
// Source-to-output consistency is checked when artifacts are built, not required for a fresh unit-only checkout.
it('keeps the grid sprite URL version explicit', () => {
expect(resolveGridSpriteUrl({ pokedexNumber: 1 }, false)).toBe('/sprites-grid/v1/home/1.webp');
});
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, it, expect } from 'vitest';
import { packGrid, unpackGrid, type PokedexGridRow } from '$lib/models/PokedexGridRow';
describe('grid transport', () => {
it('round-trips missing catches and every flag combination', () => {
const rows: PokedexGridRow[] = Array.from({ length: 17 }, (_, flags) => ({
pokedexEntry: {
_id: String(flags),
pokedexNumber: 25,
pokemon: 'Pikachu',
form: 'Female',
spriteKey: '25',
canGigantamax: true
},
catchRecord:
flags === 16
? null
: {
_id: `catch-${flags}`,
caught: !!(flags & 1),
haveToEvolve: !!(flags & 2),
inHome: !!(flags & 4),
hasGigantamaxed: !!(flags & 8)
}
}));
expect(unpackGrid(packGrid(rows))).toEqual(rows);
});
});
+58
View File
@@ -0,0 +1,58 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('$env/static/public', () => ({ PUBLIC_USE_LOCAL_POKEMON_SPRITE_FOLDER: 'true' }));
import { readOfflineEntry } from '$lib/stores/offlineSync';
describe('offline detail snapshots', () => {
const row = {
pokedexEntry: { _id: '1', catchInformation: 'Full instructions' },
catchRecord: { personalNotes: 'Saved note' }
};
function snapshot(owner = 'owner', ageMs = 0, includeEntry = true) {
const meta = {
userId: owner,
format: 2,
dataCache: `livingdex-offline-data-v1-${owner}-copy`,
generatedAt: new Date(Date.now() - ageMs).toISOString()
};
const cache = {
keys: async () => ['livingdex-offline-meta-v1', meta.dataCache],
open: async (name: string) => ({
match: async () =>
new Response(
JSON.stringify(
name === 'livingdex-offline-meta-v1'
? meta
: {
userId: owner,
version: 1,
pokedexes: [{ pokedex: { _id: 'dex' }, entries: includeEntry ? [row] : [] }]
}
)
)
})
};
vi.stubGlobal('window', { caches: cache });
vi.stubGlobal('caches', cache);
}
afterEach(() => vi.unstubAllGlobals());
it.each([0, 60 * 60 * 1000])(
'uses a matching full snapshot offline even when %i ms old',
async (age) => {
snapshot('owner', age);
expect(await readOfflineEntry('owner', 'dex', '1')).toEqual(row);
}
);
it('never reads another account snapshot', async () => {
snapshot('other');
expect(await readOfflineEntry('owner', 'dex', '1')).toBeNull();
});
it('reports missing entries and dexes without fabricating details', async () => {
snapshot('owner', 0, false);
expect(await readOfflineEntry('owner', 'dex', '1')).toBeNull();
expect(await readOfflineEntry('owner', 'missing', '1')).toBeNull();
});
it('works without Cache Storage', async () => {
vi.stubGlobal('window', {});
expect(await readOfflineEntry('owner', 'dex', '1')).toBeNull();
});
});
+36
View File
@@ -0,0 +1,36 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { PokedexPerformance } from '$lib/server/pokedexPerformance';
afterEach(() => vi.unstubAllEnvs());
describe('opt-in stage timing', () => {
it('emits no timing header without explicit opt-in', async () => {
vi.stubEnv('POKEDEX_PERFORMANCE', 'false');
const timing = new PokedexPerformance();
expect(await timing.measure('entries', async () => 'result')).toBe('result');
expect(timing.prepare(() => 3)).toBe(3);
timing.recordAuth(10);
expect(timing.finish()).toBeUndefined();
});
it('records failed stages without exposing exception content', async () => {
vi.stubEnv('POKEDEX_PERFORMANCE', 'true');
const timing = new PokedexPerformance();
await expect(
timing.measure('catches', async () => {
throw new Error('private note');
})
).rejects.toThrow('private note');
expect(() =>
timing.prepare(() => {
throw new Error('private ID');
})
).toThrow('private ID');
timing.recordAuth(undefined);
timing.recordAuth(12.34);
const header = timing.finish()!;
expect(header).toContain('auth;dur=12.3');
expect(header).toMatch(/catches;dur=\d+\.\d/);
expect(header).toMatch(/prepare;dur=\d+\.\d/);
expect(header).toMatch(/total;dur=\d+\.\d/);
expect(header).not.toContain('private');
});
});
+13 -2
View File
@@ -1,10 +1,21 @@
import { sveltekit } from '@sveltejs/kit/vite'; import { sveltekit } from '@sveltejs/kit/vite';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
import { SvelteKitPWA } from '@vite-pwa/sveltekit'; import { SvelteKitPWA } from '@vite-pwa/sveltekit';
// you don't need to do this if you're using generateSW strategy in your app // you don't need to do this if you're using generateSW strategy in your app
import { generateSW } from './pwa.mjs'; import { generateSW } from './pwa.mjs';
export default defineConfig({ export default defineConfig({
resolve: {
alias:
process.env.DEPLOY_TARGET === 'cloudflare'
? {
'$lib/server/compression': fileURLToPath(
new URL('./src/lib/server/compression.cloudflare.ts', import.meta.url)
)
}
: {}
},
plugins: [ plugins: [
sveltekit(), sveltekit(),
SvelteKitPWA({ SvelteKitPWA({
@@ -46,11 +57,11 @@ export default defineConfig({
}, },
injectManifest: { injectManifest: {
globPatterns: ['client/**/*.{html,js,css,ico,png,svg,webp,woff,woff2,webmanifest}'], globPatterns: ['client/**/*.{html,js,css,ico,png,svg,webp,woff,woff2,webmanifest}'],
globIgnores: ['**/sprites/**', '**/sprites-small/**'] globIgnores: ['**/sprites/**', '**/sprites-small/**', '**/sprites-grid/**']
}, },
workbox: { workbox: {
globPatterns: ['client/**/*.{html,js,css,ico,png,svg,webp,woff,woff2,webmanifest}'], globPatterns: ['client/**/*.{html,js,css,ico,png,svg,webp,woff,woff2,webmanifest}'],
globIgnores: ['**/sprites/**', '**/sprites-small/**'], globIgnores: ['**/sprites/**', '**/sprites-small/**', '**/sprites-grid/**'],
// Shared message/fetch handling keeps generateSW and injectManifest behavior equal. // Shared message/fetch handling keeps generateSW and injectManifest behavior equal.
importScripts: ['/offline-worker.js'] importScripts: ['/offline-worker.js']
}, },
+13
View File
@@ -0,0 +1,13 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "livingdextracker-preview",
"main": ".svelte-kit/cloudflare/_worker.js",
"compatibility_date": "2026-09-15",
"compatibility_flags": ["nodejs_compat"],
"assets": {
"directory": ".svelte-kit/cloudflare",
"binding": "ASSETS"
},
"observability": { "enabled": true },
"vars": { "POKEDEX_PERFORMANCE": "true" }
}