mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-19 05:26:47 +00:00
1b60de27f443c27d9babd4e62b77a6cf46e5ddfb
344 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
1b60de27f4 |
ci(client): lint:warnings fails an inline rule config comment
A block comment such as /* eslint @typescript-eslint/no-explicit-any: off */ turns a rule off for its file without leaving a message behind, neither among the warnings nor among the suppressed ones, so a new file could switch any warning rule off and the ratchet stayed green. eslint-disable comments were already counted under "suppressed"; this was the way around them. lintClient now reads the block comments of every file ESLint linted from the TypeScript parser, so the same text in a string, a template or a regex does not count, and the tally reports each config comment as an error. Nothing in the client uses one today, so the check is zero tolerance. The tests baseline drops by one no-unused-vars warning that is gone. |
||
|
|
9d596d9916 |
ci(client): lint:size measures the Playwright specs and fixtures too
The size check walked src/ and tests/ only, while lint:format and lint:skips already cover e2e/. The help center fixtures under e2e/help/fixtures.ts hold 2291 wrapped lines, past the 2000 a test may reach, and could grow without bound. e2e/ is now measured with the test limit; fixtures.ts enters the baseline at its current size, every other file there is within the limit. |
||
|
|
3e37dcfb45 |
fix(client): lint:layers holds src/types.ts to the rules of types
A file's layer was the first path segment under src/, so src/types.ts, the shared types module every layer imports as '../types', got the layer "types.ts" and no rule at all, while the imports into it already resolved to "types". It could import a component or a page unnoticed. A file directly in src/ is now the layer of its name without the extension, for the importer and the import alike. No file changes its count: types.ts imports only @trek/shared today. |
||
|
|
ead327be73 |
ci(client): lint:format covers the Playwright specs and the client scripts
The check only looked at src/ and tests/, so a new spec under e2e/ or a new script under scripts/ could land unformatted, and the ratchet scripts themselves did (fixed in the previous commit). It now walks e2e/ and scripts/ too and takes .mjs alongside .ts, .tsx and .css. The 58 files there that were unformatted before this branch (the e2e specs and help guides, the older build and lint scripts) join the baseline, which keeps only shrinking; JSON baselines stay out of scope. |
||
|
|
17b72ff778 |
ci(client): lint:layers rules help/ and vacay/ as helper layers
help/ holds the help center's screen registry and vacay/ a few date helpers; both are plain data and code like utils/, yet without an entry in RULES they could import any view unseen. Neither does today, so ruling them costs nothing in the baseline. managed/ stays free and the comment now says why: it is the slot an operator fills with whole screens at build time. |
||
|
|
ae84f8859f |
fix(client): lint:skips counts skips with any title and Playwright's fixme
A skip only counted when its first argument was a string or template literal; anything else was taken for a Playwright run-time condition. So it.skip(name, fn) in a table loop, describe.skip(TITLE, fn) or test.skip(true, 'why') switched tests off without the baseline noticing, and test.fixme was not matched at all. The condition form is now recognised in Playwright specs under e2e/ only, and even there a call counts when it declares a test (a body as second argument), is called bare inside a test or group, or has the literal true as its condition. Under vitest every .skip counts. fixme is a skip. Nothing in the tree uses these shapes today, so the baseline stays at 35. |
||
|
|
7ac20a0b59 |
test(client): pin the exit codes of the ratchet commands
Every ratchet command hands its check to runCli, which sets the exit code from the check's result and turns a failure of the check itself (a missing or broken baseline, a directory that is not there) into a printed FAIL and exit 1. The test runs runCli in a separate node process, as CI does, and also pins that an unexpected exception still ends the run with a non-zero code. |
||
|
|
724cdd1c0e |
test(client): keep the sign-in background work out of the auth specs
login, completeMfaLogin and register start tripSyncManager.syncAll() and the system notice fetch without waiting for them, and every sign-in, loadUser included, registers the sync triggers with their 30 s heartbeat. #2613 stubbed the sync in the push spec after it was caught logging while the worker shut down ("Closing rpc while onUserConsoleLog was pending"); the same shape was left in the other specs that sign in for real. authStore.test.ts ran the real sync on every successful sign-in and logged DatabaseClosedError from it, and its notice fetch went past MSW to the network and logged a failed fetch, both after the tests that started them. The sync is now stubbed there, and the login, MFA and register tests assert that it was started. The notice store is reset before each test, since FE-STORE-AUTH-024 left a stubbed fetch behind. LoginPage.test.tsx signs in through the form, and AccountTab.test.tsx and MSettingsAccount.test.tsx reload the user after an MFA change; they now stub the sync triggers (and the login spec the trip sync), which none of them is about. GET /api/system-notices/active gets a default MSW handler returning no notices, so a login or a mounted notice host anywhere in the suite settles that fetch in the test instead of on the network. The notice store's own tests still override it. |
||
|
|
0f1020cb80 |
ci(client): lint:skips forbids .only and ratchets skipped tests
JourneyDetailPage.test.tsx has carried 35 describe.skip blocks since April, for contributors, trip linking and the map view, features that were reworked rather than removed. Nothing stops the next skip, and nothing stops a stray .only from passing CI while the rest of its file never runs. lint:skips reads every vitest file under src/ and tests/ and every Playwright spec under e2e/ from its syntax tree. A .only on any runner fails the check, always. Skipped and todo tests (it.skip, describe.skip, test.todo, the x-shorthands, skip.each) are counted per file against scripts/skip-baseline.json, which only lowers. A skip that decides at run time is not a declaration and is not counted: skipIf, runIf, Playwright's test.skip(condition, 'why') and a bare test.skip() inside a test. |
||
|
|
07f35d8b81 |
ci(client): lint:warnings ratchets the ESLint warning counts per rule
eslint.config.mjs keeps most rules at warn so that CI stayed green on a codebase that was never linted, and CI runs eslint without --max-warnings. Warnings therefore only ever accumulated: 1218 today, among them 194 unused variables and 144 missing effect dependencies in app code, the kind behind the stale closures #2610 chased. lint:warnings runs ESLint over the client with its own config and counts the warnings per rule, separately for app code and for tests, so the headroom from fixing a test cannot be spent in app code. Messages that an eslint-disable comment silenced are counted as a third group, so an inline disable is no way past the ratchet either. No count may pass its entry in scripts/eslint-baseline.json, and --update only lowers. Any error, a parse failure included, fails the check too, so it can replace the plain lint:check step in CI instead of running ESLint twice. |
||
|
|
7a7903a799 |
ci(client): lint:offline stops new views from calling the API directly
The offline core only works when the views go through it: component, feature hook, store, repo, then api or Dexie, with writes through the mutation queue. A view that imports src/api/ skips the cache, the optimistic write and the idempotent replay. client/CLAUDE.md said so and noted that no ratchet held the line, and the number of view files importing api/client grew from 161 to 190 in two months. lint:offline lists the 213 files under components/, mobile/, pages/ and hooks/ that import anything from src/api/ for more than types (api/client, the websocket, the per-domain modules) in scripts/offline-baseline.json. No other view file may, and a listed file that stops leaves the list through --update, so the next file at that path does not inherit the exemption. Type-only imports do not count: they carry no request. client/CLAUDE.md describes the rule next to the data-flow section, including that an online-only domain puts its calls in a store or repo. |
||
|
|
798553b13b |
ci(client): lint:layers holds the import direction between src/ trees
Components reach up into pages/ for models and helpers (28 imports in 25 files: the journey detail helpers, the collections, atlas and dashboard models) and sideways into mobile/ for phone hooks and sheets (36 in 30 files), and a few stores and a repo import from components/. Nothing stopped the next one, and every such import ties two trees together that should move and split independently. lint:layers reads each source file's imports from its syntax tree (multi-line imports, re-exports, import() and type imports included, nothing inside comments or strings) and checks them against a small rule table: a component imports neither pages/ nor mobile/, a shared hook no view, nothing under the views (store, repo, sync, api, db, utils and the other helpers) any view, a repo no store, and the Dexie schema none of the layers above it. mobile/ and pages/ stay free, since the phone screens reuse the page hooks by design. The 80 imports that break a rule today are counted per file in scripts/layers-baseline.json, and a file may hold no more than its entry. Type imports count: a type the lower layer needs belongs below it. Tests are not checked. |
||
|
|
37d386178b |
ci(client): lint:format keeps new client code Prettier-formatted
client/package.json has had a format:check script, but no workflow runs it, and 2144 of the 2171 .ts, .tsx and .css files under src/ and tests/ differ from what .prettierrc asks for. Without a formatter gate the line count in lint:size could also be gamed, and every new file picked its own layout. Formatting everything in one commit would bury the history, so lint:format lists today's unformatted files in scripts/format-baseline.json and only lets the list shrink: a file outside it, any new file in particular, must be formatted, and a listed file that has been formatted must leave the list (--update takes it off and never adds one). A stale entry fails the check, since it would let the next file at that path in unformatted. The check runs Prettier through its API with the config that applies to each file and reads the text with LF line ends, so a Windows checkout agrees with CI about endOfLine. A file Prettier cannot parse counts as unformatted, and a missing config stops the run. |
||
|
|
658807b1ac |
ci(client): lint:rtl fails closed and counts its disable markers
rtl-lint compared its own path with argv[1] to decide whether it was
the command being run. Started through a symlink or with a path that
differs in its form, it printed nothing and exited 0. The check now
lives in scripts/lib/rtl.mjs and the command file always runs it.
A broken rtl-baseline.json read as empty, so --update would have
written {} over it. It now stops the run with its reason, like
size-baseline.json.
The rtl-lint-disable marker skipped a line wherever it appeared, inside
a string literal too, and nothing bounded how often it was used. It is
now honoured only inside a comment, and the marked lines are counted
per file against scripts/rtl-disable-baseline.json. Today that is the
four map overlay positions in PlanMapStage.tsx. A side that is geometry
on purpose still gets its marker, but its entry is raised by hand, where
review sees it, instead of the marker quietly replacing the logical
forms.
|
||
|
|
2f54f04380 |
ci(client): lint:size counts wrapped lines and covers tests and stylesheets
lint:size counted newlines, so a file could stay under its entry by joining lines, and the trip planner page already carried one JSX element on a single 3760 character line. A line now counts once per 120 characters it spans, the printWidth in .prettierrc, so formatted code measures what it shows and packed code measures what it holds. The check also covered only .ts and .tsx sources. Stylesheets now share the 1000 line limit, and tests get a limit of their own at 2000: they mirror the component they cover and carry fixtures, but the largest are past 5000 lines and growing with the god components. The baseline is measured again with the new rule and keyed by the path from client/, since it now spans src/ and tests/. Entries are higher in number than before because the metric changed, not because a file grew; every file is held at exactly what it holds today. New entries are the ten largest tests, index.css and studio.css, the generated countryShapes.ts (305 lines of 2600 characters each) and JourneyDetailPageEntryEditor.tsx, which was just under the old count. The scanning, baseline reading and lowering move to scripts/lib/ so the next ratchets share them. A baseline that is missing or misshapen, a directory that is not there and a scan that finds nothing now fail the run instead of reading as empty, and the command file always runs its check: there is no entry point guard left that could skip it. |
||
|
|
48b1e879d2 |
fix(offline): an online edit waits behind an older queued write to the same entity
Holding later queued writes behind a parked one only ordered writes that were in the queue. Online, the repos send an edit straight to the server, so an edit made while an older write to the same visit, tour or driving settings was backing off or parked landed first, and Try again (or the next flush) then replayed the older write over it. Those writes carry no version token, so nothing refused the stale replay. The repos of visits, day clears, tours and driving settings now ask the queue before an online write. While an older write to the same entity is pending, in flight, parked or a conflict, the new write is queued too, with the same optimistic Dexie write as offline, and a flush is started so it goes out as soon as the one ahead of it does. When the driving settings left the cache since the older write, they are read in first. Places and packing items keep their direct online path: they send the base token, so a stale replay is refused with a 409 and becomes a conflict. What this does not cover, and the docs now say so: a collaborator's change to a token-less entity is overwritten by the retried write, as by any replayed offline write of those resources, and the planner's two time edits that call the API directly are not held. The wording of the parking commit also named budget items, which never go through the queue. |
||
|
|
b61a55f037 |
fix(offline): archived trips on the device follow the eviction rules again
Keeping archived trips stopped the sync from wiping them, but left nothing that ever took one off the device. The trip sync never refreshes an archived trip, and the 7-day rule and the per-trip switch only looked at the active list, so an archived trip stayed until Clear cache however long ago it ended. The stale and switched-off rules now also run over the archived trips that are stored here, with the same eviction as an active trip: its rows go, its parked changes stay. The offline settings list the stored trips the server's list leaves out, so an archived trip gets a switch the user can turn off; before, the switches came from the active list only and could not reach it. |
||
|
|
e132d1529f |
fix(offline): a tab waits for the flush lock instead of skipping its flush
The cross-tab lock was taken with ifAvailable, so a tab that found another tab replaying returned from flush() at once. Its callers read that as "the queue is sent": the online trigger then re-seeds every trip from the server and rehydrates the open ones, and the socket refetches after its pre-reconnect flush. All tabs see the online event together, so the tabs that lost the race laid the server's rows from before the replay over the shared Dexie, and over the optimistic edits still on their way, while the winning tab was mid-flush. The lock is now requested without ifAvailable. A tab that finds it held waits, then runs its own pass, which finds nothing or what the holder left behind, so flush() resolves only after the replay and the re-seed chained onto it reads the state after it. The holder's requests are bounded by the client timeout, so the wait is too. |
||
|
|
f5339307b2 |
fix(offline): only one tab flushes the queue at a time
Every open tab shares the account's queue and runs its own flush triggers, and the _flushing flag only guards its own tab. Two tabs read the same pending rows and both replayed them, so correctness rested on the server's replay cache answering the second request, and each tab ran the temp id remap and the Dexie write a second time. The flush now takes a Web Lock named after the account's database, with ifAvailable, so a tab that finds it taken skips the run the way a busy flush in the same tab always has; the holder picks the rows up. The lock is released with the tab, so a tab killed mid-flush cannot strand it. Where the API is missing or refuses the request, the flush runs as before under the flag alone. |
||
|
|
b4f705a049 |
fix(offline): a parked write holds back the later writes to the same entity
Parking a write the server keeps failing on unblocked its trip, so a later queued edit of the same budget item, visit, tour or driving settings went through while the older one waited. Try again then replayed the older write last and it silently overwrote the newer one: only places and packing items send a token the server could refuse it with. Before the parking change a 5xx stopped the whole flush, so this order was never at risk. The flush now holds back every pending write whose entity has an older write parked as failed or waiting as a conflict, and a write that parks during the pass holds back the rest of that pass too. Other entities and other trips keep syncing. Try again therefore replays the parked write first and the held ones after it, Keep mine does the same for a conflict, and Discard or Keep theirs flush right away so the held writes go out without waiting for the next trigger. Writes queued against an offline create that got parked now wait for it instead of failing as an unresolved temp id. |
||
|
|
237f82c0b6 |
fix(offline): an archived trip is not a deleted one, and eviction keeps parked changes
The trip sync clears every cached trip the server no longer lists, but it read only GET /trips, which leaves archived trips out. Every sync (login, reconnect, the periodic run) therefore wiped every archived trip from the device, pinned ones included, and with it their parked failed changes. A trip now only counts as gone when it is missing from both the active and the archived list, and when the archived list cannot be read nothing is treated as gone that round. clearTripData no longer deletes 'failed' rows. Stale eviction, a trip switched off in the storage settings and a trip that is really gone all go through it, and none of them is the user deciding to give up a change. A parked change of a deleted trip, or one the user was removed from, now stays in the queue: Settings > Offline counts it under failed changes and offers Try again (the server answers 403/404, so it parks again) or Discard. Dropping it silently would lose the only copy of an edit the user may still want to look at or redo elsewhere, and keeping it costs nothing more than a counter the user can clear in one tap. |
||
|
|
395a7f41fe |
test(client): keep the login's background trip sync out of the push spec
A successful login starts tripSyncManager.syncAll() without waiting for it. In authStore.push.test.ts that sync was real and could still be logging when the worker shut down, which vitest reports as an unhandled "Closing rpc while onUserConsoleLog was pending" and fails the coverage job although every test passed. The spec is about push, so the sync is stubbed. |
||
|
|
8e2a2725f0 |
refactor(client): the stop rows move to RoadtripSidebarStopRows and share one badge row
ServiceStop, RouteViaStop and Stop leave RoadtripSidebar.tsx for their own module and are imported back by name; effectiveFill goes with them unexported, and the imports only they used leave the sidebar. The badge row under a stop's name was written out twice, once in each stop shape. It is now the local StopBadgeRow, which both render in its place. It returns the same span with nothing around it, so the markup is unchanged, and it reads the fill setting and the vehicle the two shapes used to read themselves. Those are plain store reads, so moving them one component down changes nothing either. The code moves as it was otherwise. The note on the stop kind table now sits at the lookup it describes, the comment on the two settings says where they are read now, and the dashes in the moved comments become colons, commas and full stops; each theme-lint-disable stays on the line of its style. Nothing renders differently. New tests render the rows on their own: a plugin halt with and without its name and stay, the kind picker on a pause and on a numbered stop by click, Enter and Space, the drive findings and the walk from the road on both shapes, including the range and unknown findings the rail never draws, and the fill badge with the traveller's default. |
||
|
|
97a93bb719 |
refactor(client): the stop badges and the arrival clock move to RoadtripSidebarBadges
OffRoadBadge, FillBadge, NightCheckIn, StayBadge, DriveFindingBadge, DayCarry, Arrival and LateBadge leave RoadtripSidebar.tsx for their own module and are imported back by name. The code moves as it was. The doc blocks that sat stranded above other functions now stand above the badge they describe, StayBadge's two notes as one, and the dashes in the moved comments become colons and commas. Nothing renders differently. New tests render each badge on its own, including the walk from the road and the range and unknown arms of the drive finding, which the rail never reaches. |
||
|
|
bee500880e |
fix(i18n): every language says one file and five files its own way
Finishes the plural work the previous wip commit started. t() picks a count string's form by the language's own Intl.PluralRules, and every locale now spells out the forms its language reaches with whole numbers, about 160 count strings in all: one, few and many in Russian, Ukrainian and Polish, one and few in Czech and Slovak, five forms in Arabic, one in the others, none in Japanese, Korean, Chinese, Thai, Vietnamese and Indonesian. Each language was translated and then reviewed on its own. English no longer reads "1 files", "1 updates available" or "photo(s)". Count labels shown next to a number now take that number too: the atlas and admin statistics, the trip cards, journey and shared trip pills, packing templates, receipts, storage usage, the Studio export note. A heading that shared its key with a counted label keeps a key of its own (the boarding pass heading, the Bookings tab), so languages that put a noun after a number in the singular keep a plural heading. The plugin hosts chip passed its count through .replace() after t() and never got a form; three toasts sent the count as text. Mail and push texts for shared photos and suppressed storage failures pick their form in code through pluralForm. A whole number sent as text counts too, which is how in-app notification params arrive, and the plural rule follows the language of the strings on screen while another one still loads. The parity check knows which forms each language needs and refuses missing and impossible ones. It also reads keys that contain a colon now: it skipped them, which hid 58 missing plugin permission texts in Catalan and 35 in Vietnamese, both translated. The client parity test covers every language of the registry instead of a hand-kept list of 19, and the placeholder spec lets a form spell its number out only where its category is that one number. Brazilian Portuguese error screens were in Breton, and an Arabic dashboard label held Hebrew text. |
||
|
|
d4eccb39a3 |
fix(client): three more places follow the reading direction in Arabic
On a phone in Arabic every system notice, the release notes included, opened as an empty sheet: its three-slot strip is shifted to show the middle slot, and in a right-to-left row that shift moved all three out of view. The shifts point the other way in a right-to-left page now, which the swipe handling already assumed. The budget's total amount kept its parts in order but sat on the opposite edge from its label, because the whole row was made left to right. Only the amount itself is now. The phone chat's bubble tails were still physical corners while the desktop ones follow the row; both use logical corners now. lint:rtl takes comments from the TypeScript parser instead of scanning lines, so a "/*" inside a string (accept="image/*") no longer hides the lines after it. |
||
|
|
0126ef3401 |
fix(client): the version notice asks about a change during the session only
Three gaps in the notice from the previous commit, found in review. A page served from the network and claimed later by its own build's worker counted as already taken over, so Reload went to that worker, got the old build again and spent the session's reload: no notice and no new build until the next start. Only a worker that replaced the one that served the page skips the handover now, as at launch. A reload that came before the new worker could take over (a slow precache, a failed update, an install gone redundant) also spent that guard, so the launch behind it could no longer finish the handover with its own reload. That reload leaves the guard alone now. An install whose server never reports the bundle's version (a hand-set APP_VERSION) showed the notice in every session, and Reload could not clear it. The store keeps the first version a page hears of, from the app config at launch, and the notice only asks when a later report differs: a different build at launch is the launch handover's to fix. The server's wire-envelope test pins the welcome frame's fields and now expects the version beside the socket id. The wiki's update page says what an open tab shows after an update. |
||
|
|
a094f79efa |
feat(client): offer the new version when a release lands during a session
A tab kept open across a deploy ran the previous build until its next start. The server now names its version in the realtime welcome frame, which every open client reads again when it reconnects after the restart a deploy brings. When that version is not the build the page runs, a notice offers to reload. The reload goes through the same service worker handover a launch uses: it waits for the new worker to take over, or for a short timeout, and records the version only when the takeover happened. The notice reads the error boundary's texts for the same situation, so every language has it already. It is one component for both shells, sits above the offline pill, stays away offline and after a reload for that version that did not bring it, and can be closed for the session. |
||
|
|
ba70ad28b8 |
fix(client): spacing and alignment follow the reading direction
Arabic runs the app right to left, but margins, paddings, insets, text alignment, borders and corner radii were written for the left side, so icons sat against the wrong edge of their labels, indents and badges pointed the wrong way and amount columns aligned left. They now use the logical forms (ms-, ps-, start-, text-start, marginInlineStart, insetInlineEnd and their CSS equivalents), which are the very same sides in a left to right language. Geometry stays physical on purpose: maps, positions measured from the pointer or a bounding box, time axes, sliders, transforms and print output. Amounts drawn as several spans keep their order in a right to left row, the time picker keeps hours before minutes, and two switches whose thumb slid out of its track in Arabic now move the right way. lint:rtl counts what is still physical per file against a baseline that may only shrink (1512 uses in 370 files before, 319 in 113 now), and CI runs it, so new code reaches for the logical forms. |
||
|
|
de128cc4ae |
wip(i18n): plural forms through Intl.PluralRules
Unfinished, continued in the next session: t() resolves key.one/.few/... by the language's own plural rule, the parity check knows which forms a language needs, 16 singular/plural key pairs are merged in every locale and every count === 1 branch in the client uses the plural form. Still open: the forms each locale needs for the remaining count strings, the two new labels in every locale, and 35 tests that expect the old English wording. |
||
|
|
ab343b0a7b |
fix(client): a phone turned sideways stays in the phone layout
The phone shell was chosen by width alone, and most phones are wider than 767px in landscape, so turning one swapped the whole route tree for the desktop planner and an open sheet, its input and the map position were lost. The phone query now also covers a touch screen under 500px tall, which no tablet is. It lives in one place: the shell, the planner and todo hooks, the warnings banner, dialog focus and the stylesheets read it, and six components that measured the window once on mount now follow it. |
||
|
|
e0efa0314a |
feat(tours): tours read and write through the offline core
A tourRepo replaces the direct toursApi calls: reads fall back to a new Dexie tours table, and a tour saved or edited offline is written there and queued like a place, under one temporary id for the place and its facet. The queue moves both to the real id on replay and drops both when the server refuses the create. Trip sync caches each trip's tours while the addon is on, so a tour no longer reads as a plain place offline. The tour metrics move to shared so the offline copy shows the server's numbers, and useTourPlaceIds keeps one Set per change as intended. |
||
|
|
f7edd849ab |
fix(tours): one tour type catalogue, and no column nothing writes
tour_types now holds every key the shared contract accepts, all but hike disabled, and create and edit turn a disabled type away with a 400 instead of failing on the foreign key. tours.tour_group_id is dropped: nothing ever wrote or read it. difficulty and wanderer_ref stay for the Wanderer import. |
||
|
|
57df945318 | style: plain punctuation in the new comments and test names | ||
|
|
e4ed4bfc7b |
fix(mobile): the booking, transport and place sheets ask before dropping what was typed
On the phone a flick of the sheet's top edge, a tap on the scrim or Escape closed the booking, transport and place forms and threw away whatever had been typed, without a word; the desktop dialogs have asked since #2253. The question moves into a shared hook that DialogShell and MSheet both use, and the three sheets pass their form state to it. |
||
|
|
c60277c4d2 |
fix(tours): a tour another member creates is a tour on the phone too
The list read marked tour places with tour_place_id, but the single-place read behind place:created and place:updated did not, and the phone's places browser kept a second tour list of its own that no realtime event updated. A tour another member made, or one imported from GPX, showed as an ordinary place on the phone until the screen remounted, and every tour did offline. The single read carries the mark now, the browser asks the planner, and the tour id set is memoised instead of rebuilt on every render. |
||
|
|
461a63fc86 |
fix(auth): send the queued changes before a logout deletes the offline database
Logging out deleted this user's offline database straight away, so a change made offline and not yet sent was lost without a word. With a connection, the logout now flushes the queue first, for at most five seconds. |
||
|
|
38656eeffd |
fix(offline): let the cache drop what was deleted elsewhere
The trip sync and every repo list only ever upserted, so a place a collaborator deleted while this device was offline came back on the next offline read, and a trip the user had been removed from stayed on the device. A sync and a full list now replace the trip's rows, keeping only the ones created offline that have not synced yet, and a cached trip the server no longer lists is cleared. |
||
|
|
f092e7a95f |
fix(offline): a write the server keeps failing on no longer blocks every other write
A queued change the server answered with a 5xx was put back at the head of the line and the whole flush stopped, every 30 seconds, forever: one bad payload held every later change of every trip. Now only its own trip waits, with gaps doubling from 30 s, and after eight failures it is parked as failed. A DELETE answered 404 counts as done instead of showing as a failed sync. Settings > Offline offers to try parked changes again or discard them. |
||
|
|
3f9b751ee3 |
fix(realtime): open no socket after a logout, and reconnect as soon as the network is back
A connect still waiting for its ws token when the user logged out went on to open a socket authenticated as that user, which the next login on the same browser then reused. And a socket in its reconnect backoff waited up to 30 s after the network came back or the tab became visible. Both events now reconnect right away. |
||
|
|
c956fe92ba |
Merge dev into feat/tours and port Tours onto MikroORM
dev now runs on MikroORM, so the positional migrations, seeds.ts and DatabaseService the Tours server side was built on are gone. Behaviour is unchanged; persistence moves onto dev's architecture: - one MikroORM migration for tour_types, tours and tour_waypoints, idempotent so instances that ran the old positional steps keep their data; the hike tour type is seeded inside it, the addon row in the AddonSeeder - entities and repositories for the three tables, tours domain on repositories and UnitOfWork - tour facet joins in places, assignments and days re-applied on the repository code Fixes found while porting: - GPX import checks addon, trip access and permission in the handler instead of guards, so a refused upload gets a 403/404 instead of a connection reset - copying a trip copies its tours and waypoints - a tour cannot be moved onto a day that already has it - updateTour checks existence inside its transaction Adds tours e2e tests and rewrites the tours unit tests onto the migrated test database. |
||
|
|
de8caa81a2 |
Feat/orm : mikroorm (#2416)
* base entities
* update deps
* fix date as string
* rename entities
* migrations + seeders
* feat(db): DbTimestampType keeps DATETIME columns as the CURRENT_TIMESTAMP text
* feat(db): discover entities from an explicit list instead of a glob
* test(db): createTestOrm binds an ORM to a suite's own SQLite handle
* feat(db): dialect helper is the one place SQL functions are spelled
* test(db): dialect helper refuses malformed column references and day counts
* feat(db): snake_case entity shape and the first three repositories (Days, DayNotes, Trips)
* fix(db): repositories mirror the statement's column set and guard their row types
* feat(db): request-context and unit-of-work helpers for the ORM, with concurrency tests
* test(server): integration suites boot on the migrated schema snapshot
* test(server): snapshot harness keeps the legacy id semantics
* fix(test): route MikroORM's dynamic imports through vitest from the setup file, not the ORM config
* test(db): coverage ratchet entries for the ORM foundation
* test(server): websocket suites boot on the migrated schema snapshot
* test(server): coverage's uncovered-file pass goes through the SWC transform
* fix(db): dialect helpers dispatch on the platform; lint gate for the repository layer
* test(server): ORM suites open the schema snapshot; RESET_TABLES derived from the schema
* chore(server): promise safety net and sweep tooling for the async migration
* refactor(realtime, systemNotices, addons, airports, audit, categories, permissions, query-helpers, tags, transit, trip-membership): async DB-touching methods; transactions through UnitOfWork
* fix(server): observe every promise the async sweep left unobserved (timer, handshake, plugin-runtime test)
* test(doc-sync): unit suites await the methods the async sweep made async
* refactor(atlas, school-holidays, settings): async DB-touching methods; transactions through UnitOfWork
* chore(server): lint rule refusing a Promise used as a plain value, and the misses it found
* test(server): suites await the methods Task 1's forced edits made async
* refactor(budget, common, day-notes, days): async DB-touching methods; transactions through UnitOfWork
* test(oauth): controller suite awaits the async service
* chore(server): db-call-graph --unawaited lists calls to async methods whose result is used without await
* refactor(llm-parse, mcp-shared, oauth, place-shadow, route-usage, storage, todo, trip-invite): async DB-touching methods; transactions through UnitOfWork
* refactor(plugins): async DB-touching methods; transactions through UnitOfWork
* chore(server): db-call-graph --sync stops its transitive walk at an async callee
* chore(plugins): drop gate-only asyncs; observe the scheduler's rejection; async event-sink stub
* refactor(notifications, place-photos, backup): async DB-touching methods; transactions through UnitOfWork
* refactor(auth, files): async DB-touching methods; transactions through UnitOfWork
* test(server): suites await the methods earlier sweep groups made async
* refactor(tokens): async DB-touching methods; the auth token handlers await them
* test(files): upload filters fail closed on an excluded or unresolvable type
* refactor(collab, collections, maps): async DB-touching methods; transactions through UnitOfWork
* refactor(memories, photos, packing, share): async DB-touching methods; transactions through UnitOfWork
* chore(server): lint rule also refuses a Promise handed to expect() without resolves/rejects
* refactor(vacay, admin, doc-sync): async DB-touching methods; transactions through UnitOfWork
* fix(vacay): type the loop accumulators the async sweep introduced
* refactor(journey, oidc, place-enrichment, tokens, trip-members): async DB-touching methods; transactions through UnitOfWork
* fix(server): the journey hooks are awaited by their callers, not detached
* refactor(assignments, public-api, accommodations, places): async DB-touching methods; transactions through UnitOfWork
* refactor(trips): rewrite AccommodationsService.createAccommodation .bind alias
Recipe R4 trap named in the Task 12 brief: a .bind alias of an
AssignmentsService/AccommodationsService method is typed any and hides a
missing await from tsc and the promise lint rules. createAccommodation
belongs to this task's group, so rewritten as an arrow forwarding to the
method instead of a bound reference.
* refactor(assignments): drop the unused Trip type alias
* refactor(reservations, booking-import, calendar, integrations, roadtrip): async DB-touching methods; transactions through UnitOfWork
* refactor(roadtrip, reservations): return await on transactional; document the single-flight promises
* refactor(trip-read-model, trips, feeds): async DB-touching methods; transactions through UnitOfWork
* refactor(server): remove DatabaseService.transaction — every transaction runs through UnitOfWork
* refactor(trips, feeds): drop added return annotations; no double await on the feed guard
* fix(server): phase 1 review follow-ups — awaited returns, logged upload-filter rejections, covered handshake/notice branches, call-graph gate in CI, dead test imports
* fix(server): upload filters answer multer once on a throwing callback; positive call-graph gate test
* test(db): entity metadata must match the migrated schema; fix the four drifts it found
* feat(db): primary-relation entities proven (BudgetCategoryOrder, VacayUserSettings)
* test(db): parity gate also holds declared pivot entities; per-field column types; missing-set ratchets both ways
* test(db): numeric ids for the primary-relation spike
* feat(db): re-runnable entity generator encoding the snake_case/DbTimestampType rules
* fix(db): generator guard rails — validation cannot mask hidden()/index loss; typed JSON; loud failures
* fix(db): generator keeps NOT NULL boolean defaults; fails if a JSON interface import survives
* refactor(db): every entity in the snake_case shape; document-sync entities added; one repository per entity
* fix(db): no NaN class-field initialisers; entity generator --check gate in CI; parity normaliser keeps literal case
* chore(db): entity --check reports stray files; class-field census is a ratchet; migrate-encryption typechecked
* feat(db): AppSettings and Users repositories; forFeature wiring pattern
* refactor(permissions): permission flags through AppSettingsRepository
* fix(server): boot-time settings read runs inside an explicit ORM request context
* refactor(audit): audit log writes through AuditLogRepository
* fix(db): PK reads refresh past the identity map; typed owned-lookup generics; e2e ORM module mirrors production config
* docs(db): owned-lookup call-site convention; refresh side effect; e2e ORM module spread notes
* fix(audit): audit rows are native inserts, not a unit-of-work flush; closed test ORMs
* fix(server): non-HTTP entrypoints run inside an ORM request context; permission loads fail closed on context errors
* refactor(categories, tags): repositories replace raw SQL
* refactor(addons): addon catalog and photo providers through repositories
* fix(db): generator captures inline UNIQUE constraints
SqliteSchemaHelper.getIndexes() drops every unnamed sqlite_autoindex_
entry before entity-generator ever sees it, so a table-level
UNIQUE(...) constraint with no separate named CREATE UNIQUE INDEX
(settings' UNIQUE(user_id, key) among ~40 others) never reached the
generated entity's uniques: metadata. Adds a general
RULE9_addImplicitUniqueConstraints (skips a column set identical to
the table's own primary key — AppSettings.key/Addons.id noise) fed by
a PRAGMA index_list/index_info scan, and regenerates every entity.
* chore(addons): well-known gate wraps only the addon read in a request context; drop unused test factories
* fix(platform): well-known gate tolerates a synchronous addon read from the context helper
* fix(db): PK lookups inside patch refresh past the identity map; corrected identity-map notes
* refactor(settings): user and instance settings through repositories
SettingsRepository (getForUser/upsertForUser/getOne/deleteForUser) replaces
the per-user settings table's raw SQL; SettingsService drops DatabaseService
entirely. instance-api-keys.ts's readInstanceApiKey/writeInstanceApiKey/
resolveApiKey take an explicit AppSettingsRepository/UsersRepository instead
of a raw connection.
An earlier version resolved those two repositories itself from the active
MikroORM request context, so none of its six callers needed to change. That
worked in production and e2e (always inside a real request) but broke
service construction in plain unit tests across every calling domain
(addons, auth x2, maps, transit, unsplash - 185 failures on a full run),
since none of them wrap a request context. Each of those six services now
injects its own AppSettingsRepository/UsersRepository and passes them
through explicitly, matching how every other converted repository in this
migration is consumed; their own SQL is untouched (outside Plan 3a).
* test(server): harness constructors follow the Task 5 repository signatures; one test ORM per handle in the plugin host
* fix(db): generator names relation properties in captured UNIQUE constraints
* fix(settings): drop dead wiring and the speculative deleteForUser; strict row assertions
* fix(server): plan 3a review follow-ups — fail closed without an ORM at every choke point; seam and D5 ratchet tests; dead method and DDL copies removed
* fix(server): plan 3a re-review follow-ups — plugin boot activation and the airports backfill inside a request context; the supervisor answers the child before failing closed; BOOT-SWEEP-001 drives the real boot hooks; ws adapter seam pinned
* feat(db): generated entities declare their repository type; test casts dropped
* fix(server): plan 3a re-review 2 follow-ups — absent-ORM boot branch pinned; airports boot hook never rejects; BOOT-SWEEP-001 asserts the seven routes; duplicate comment removed
* feat(server): pre-init photo route and WS handshake run in a request context; InviteTokensRepository
* refactor(auth): users table through UsersRepository; JWT and MFA lookups repository-backed
* refactor(tokens): MCP and API tokens through McpTokensRepository
* refactor(auth): passkeys and registration invites through repositories
* fix(db): row-out repository reads bypass the identity map — stale write-back over nativeUpdate at flush; insertUser via em.insert; settings round-trip pinned
* fix(server): non-numeric route ids answer the legacy not-found, never NaN (tokens, categories, tags); mint path back to two statements; identity-map regression pinned
* refactor(oauth): OAuth server tables through repositories
OauthClientsRepository/OauthTokensRepository/OauthConsentsRepository
replace OauthService's raw SQL (OA1-OA33). revokeChain's recursive CTE
and the oauth_clients join (its FK actually targets client_id, not the
row id the generated relation assumes) go through em.getKysely();
OA19's chain revoke is one nativeUpdate($in); OA12's consent grant is
em.upsert on the (client, user) unique key. revokeAllForUser built now
for Task 5. Every row-out read is disableIdentityMap: true; inserts go
through em.insert.
* fix(auth): non-numeric passkey and invite ids answer the legacy 404, never NaN; invite join type pinned
* fix(db): generator emits the referenced column for non-PK foreign keys; OAuth client joins through the relation; FK parity un-skipped
* refactor(db): TrekRepository base — every repository path validates the request context and reads bypass the identity map by default
* refactor(auth): AuthService and account cleanup through repositories
* refactor(oidc): OIDC identities and settings through repositories
* fix(auth): invite validation keeps expires_at null on the wire; password transaction scopes and reset-token burn pinned
* fix(server): plan 3b close-out — case folding on both sides for identifier lookups (non-ASCII login regression); coverage ratchet restored; repository scaffold and instanceof ratchet on TrekRepository; D-shape tests load-bearing
* refactor(server): trip-access primitives async at every caller
* refactor(trips): trip access through TripsRepository; demo seed in a request context; dialect helpers for the trips cluster
* refactor(days): days and day notes through repositories
* refactor(assignments): day assignments through repositories
* refactor(server): trip-membership, place-shadow, place-enrichment, place-photos and query helpers through repositories
* refactor(trip-members): membership, guests and the trip read model through repositories
* refactor(places): places, tags, ratings and place images through repositories
* fix(server): place-shadow source counts ordered in SQL; identity-map ratchets load-bearing; photo-cache race pinned
* refactor(places): import paths through repositories
* refactor(trips): trips through repositories
* fix(server): trip ids parsed once at the gate for places and assignments; NUL-safe value quoting on the SQLite platform; places parity tests completed
* refactor(trips): trip copy through repositories for the owned tables
* fix(server): plan 3c close-out — non-finite ids bound as NULL, trip id parsed once at every places/days/ws gate
Platform: NulSafeSqlitePlatform now renders a bound NaN as NULL and
+/-Infinity as 9e999/-9e999, matching better-sqlite3's own legacy binding
(rule 22 extension) — the program-wide fail-safe for any caller that still
passes an unguarded Number(untrusted) into a converted statement.
PlacesService.verifyTripAccess and RealtimeGateway.handleJoin stop doing
that: verifyTripAccess parses once with toRowId and threads the parsed id
through create/import/bulk/rating/export.gpx (deleting the seven
toRowId(tripId) ?? -1 sites), and handleJoin gets a Number.isFinite guard.
DaysService gets the same treatment across list/create/getDay/reorder/
insert/resyncAccommodationDays, closing the gap where a hex-spelled trip id
could renumber a real trip's days while the raw-bind inverted-accommodation
guard silently matched nothing.
DatabaseService.getTripTitle is deleted; PlacesService injects
TripsRepository directly and calls getTitle itself.
Template/cheap-item cleanup: DayAssignmentsRepository.listForTimeSort uses
$castTo instead of an unknown bridge; the duplicated TagRow interface in
Places.repository.ts is now imported from Tags.repository.ts;
AssignmentWithPlaceRow extends the guarded DayAssignmentRow instead of
restating its columns; PlaceShadowPicksRepository.totals drops its
unreachable ??-fallback branch; Places.repository.ts's updatePlace types
the NOT NULL name column as string; trip-members.service.ts's
transferOwnership threads one parsed trip id through all three writes and
corrects two stale "raw-bind seam" docstrings that were actually Number()
seams; a dead canAccessTrip mock is removed from reservations.e2e.test.ts.
Tests: the 23 new no-explicit-any warnings in TRIP-SVC-069 are typed
(lint back to 2416); HTTP and WS regression coverage for the non-finite
and non-canonical id shapes across places/days routes, mutation-proved;
TRIP-JOIN-005 asserts the exact concurrent-join settlement instead of
>= 1; a new tests/unit/db/transaction-yield.test.ts pins rule 24's
measured transaction-yield/dirty-read/nested-BEGIN behaviour.
* test(server): plan 3c close-out — copy-source full-row parity, Kysely rollback proofs, identity-map relabels, trips e2e on the snapshot DB
* fix(server): plan 3c close-out — days create/insert answer the guard 404 for non-canonical trip ids instead of 500; exact settlement and cross-request yield ratchets
* feat(server): plan 3d groundwork — dialect helpers, visibility predicate, feed and cron context ratchets
* refactor(roadtrip): roadtrip tables through repositories
* refactor(reservations): reservations, endpoints and travelers through repositories
* refactor(feeds): ICS feed tokens and anonymous feeds through repositories
* refactor(accommodations): stays through repositories inside the existing transactions
* test(server): plan 3d — MCP test helper constructors follow the accommodations and days services
* refactor(trips): trip copy through repositories for the roadtrip, accommodation and reservation tables
* refactor(calendar): calendar reads and reservation visibility through one predicate
* feat(server): plan 3e groundwork — packing visibility predicate, memories access-gate audit
* fix(server): plan 3d close-out — legacy text shape for stored accommodation ids restores the date-change restamp; reservation ids parsed once at the gate; parity tests for the reservation repositories
* refactor(photos): trek photos, memories access and cache sweeps through repositories
* refactor(files): trip files and file links through repositories, with transactions added
* test(server): plan 3e — hand-built FilesService, FilesRpc and AllowedFileTypesService calls follow the repository constructors
* refactor(memories): unified, immich and synology photo sync through repositories
* refactor(collab): notes, polls, messages and links through repositories
* refactor(budget): budget items, members, payers and settlements through repositories
* refactor(todo): todo items through repositories
* refactor(packing): packing items, bags and templates through repositories
* feat(server): plan 3f groundwork — systemNotices DI shape, TRAVELER_OWNS predicate, ntfy/storage-health specs, composite-PK pins
* refactor(school-holidays): country and region catalog through repositories
* refactor(notifications): in-app notifications and channel preferences through repositories
* refactor(notifications): reminder crons, mailer, ntfy and webhook transports through repositories
* fix(server): plan 3e close-out — repository registrations restore the boot; packing assignee and bag updates parse and no-op as legacy; coverage and scoping ratchets for the budget, packing and collab repositories
* refactor(vacay): vacation plans, entries, shares and holiday calendars through repositories
* refactor(system-notices): notice dismissals through a Nest provider and repository
* refactor(atlas): visited countries, regions and bucket list through repositories
* feat(server): plan 3g groundwork — GALLERY_CHRONOLOGICAL_ORDER Kysely ordering, unixEpochToIsoKysely helper, composite-PK DDL pins, JB5/R7 confirmations
* refactor(journey): journey and trip access control, CRUD and the trip-sync engine through repositories
* feat(server): plan 3h groundwork — date-offset dialect helpers, entity/repository fitness confirmations, pre-init and encryption pattern confirmations, survivor re-grep
* fix(server): plan 3f close-out — ntfy operator-scope test on the live send path; vacay date-offset and shift-order parity; todo reminder window; coverage and parity ratchets for the atlas and vacay repositories
* refactor(journey): journey stats, entries, photos, contributors and suggestions through repositories
* refactor(journey): public share links, TREK Studio books and the journal facades through repositories
* refactor(collections): access model, hydration, export/import and list CRUD through repositories
* refactor(server): journey-table survivors in trips, photos, memories, auth-cleanup and plugin-contributions through repositories
* refactor(integrations): dawarich connection, sync, tracks and review-flow through repositories
* refactor(collections): saved places, copy-to-trip, labels and invitations through repositories
* refactor(integrations,booking-import,airports,maps,route-usage): airtrail, booking import, airport backfill, maps cache and route-usage counters through repositories
* refactor(doc-sync): connections, reconciler and controller-SQL relocation through repositories
* test(integrations): add AirTrail saveSettings tx-asymmetry ratchet (Plan 3h Task 4 addendum)
* fix(server): plan 3g close-out — transactional book first-save, skeleton reconcile and share-link create; unknown-key entry patches are no-ops again; parity and authorization pins for the journey repositories
* feat(server): plan 3i groundwork — AuditLogRepository's reserved methods, the demo connection-swap spike, repository-fitness confirmations
* feat(server): plan 3j groundwork — scheduler onto CronRegistrarService, SDK-contract confirmation, repository fitness
* refactor(storage): backend/category config and usage stats through AppSettingsRepository; fix the seed-file test race and the shared-replica migration-flip gap
* refactor(share): public share links, the pre-init photo fallback, and collection-places survivors through repositories
* feat(server): plan 3j — the withCamelCase utility, unwired, pending a contract decision
* refactor(admin): user CRUD, stats, audit log, version check and addon config through repositories
* test(admin): pin createUser's pre-existing non-transactional uniqueness-check race (AD2-4)
* refactor(plugins): the trip-write role gate through a repository, in isolation
* refactor(demo,backup): seed and reset through DemoRepository, live-connection backup statements through MaintenanceRepository, isDemoUserId through an injected DemoService
* fix(server): plan 3h close-out — new-value-wins COALESCE restores stay/reservation propagation; doc-sync state filter truthiness; request-context and parity ratchets for share, doc-sync and the integrations
* refactor(plugins): runtime lifecycle, config CRUD and the uninstall cascade through repositories
* fix(server): plan 3i close-out — DemoModule imported where its service is consumed (e2e restored); admin addons list selects the provider relation; saveDemoBaseline awaited; backup tests on the maintenance repository
* refactor(plugins): outbound OAuth tokens and per-user plugin settings through repositories
* refactor(plugins): install-time gates, the capability-audit hash chain and the registry through repositories
* refactor(plugins): contribution-hook controllers, the small plugin controllers and the plugins-table survivors through repositories
* test(server): plan 4 — collapse mcp tool test harnesses onto the ORM snapshot
* test(server): plan 4 — collapse nest service test harnesses onto the ORM snapshot
* fix(server): plan 3j close-out — serialized audit-chain appends, atomic metadata and scheduler limits, rollback and race proofs for the plugin repositories
* refactor(server): plan 4 — convert the program's orphaned raw-SQL callers
* fix(server): plan 4 — un-skip PARITY-009 (FK deleteRule and index-name parity)
* refactor(server): plan 4 — inline canAccessTrip/isOwner off DatabaseService (trip-domain services)
* refactor(server): plan 4 — inline canAccessTrip/isOwner off DatabaseService (plugins + MCP surfaces)
* fix(server): plan 4 — RULE12 paren-count scanner ignores string literals
The entity generator's RULE12_fixGarbledCheckExpressions CHECK-expression
paren-balance scanner counted every `(`/`)` character regardless of
whether it fell inside a single-quoted SQL string literal. A CHECK
expression like `status IN ('confirmed)', 'tentative')` has a literal `)`
inside its first string value; the scanner would hit depth 0 at that
in-string character and truncate the expression, losing its own real
closing paren. The scanner now tracks single-quote string state (handling
the doubled `''` SQLite escape) and skips parens while inside one.
Latent-bug fix — no shipped entity's CHECK expression has hit this shape
yet (3d's ledger: "nothing affected today").
* refactor(server): plan 4 — unify the trip-access predicate's Kysely copies
TripsRepository.findForViewer/listForUser/activeTrip each hand-wrote the
identical trip-access boolean (t.user_id = ? OR m.user_id IS NOT NULL)
through the Kysely expression builder. Task 7's security review (M1)
evaluated a shared helper and set it aside for time, falling back to the
TRIPREPO-041 cross-method parity test as a regression guard instead.
Extracted the boolean into one generic helper, tripAccessExpr
(_shared/trip-access.ts), following the reservation-visibility.ts
publicReservationExpr precedent: fully generic over <DB, TB> since the
predicate has no correlated subquery, so it composes across
TripSelectKyselyDB and ActiveTripKyselyDB without needing a narrower
fixed-alias shape. The LEFT JOIN itself stays hand-written at each call
site — tripSelectQuery's own docstring already explains why a shared join
helper can't be typed across these differently-joined outer queries.
feeds.service.ts and memories-access.service.ts no longer duplicate this
predicate at all (Task 2's facade-inline sweep already converted both onto
TripsRepository.findAccessible/getFeedTokenIfReachable/
listReachableActiveTrips, which read through the canonical MikroORM
QueryBuilder form, accessibleTripsQuery) — the remaining duplication this
task closes is the three Kysely copies inside this file.
TRIPREPO-041 (64/64 in the file) stays green as the unification's own
regression guard.
* fix(server): plan 4 — trek_photo_cache_meta.cache_key NOT NULL
The column was a bare TEXT PRIMARY KEY, which SQLite does not implicitly
make NOT NULL (unlike an INTEGER PRIMARY KEY rowid alias). Every writer
(TrekPhotoCacheMetaRepository.upsertMeta, the table's only INSERT path)
has always bound a real string — 3e's R5 confirmed this. Appends a new
migration rebuilding the table with cache_key NOT NULL (SQLite has no
ALTER COLUMN, so this follows the same rebuild recipe
Migration20200101020000 uses in the opposite direction) and updates the
entity/generated metadata to match. Schema tightening, not a behaviour
change.
* refactor(server): plan 4 — retire the safely-convertible string-form where conditions (rule 23)
Places.repository.ts's existsInTrip/findInTrip/findRaw/reclaimInputs/
listByTripAndIds and Trips.repository.ts's findPublicForShare all took a
raw `.where('col = ?', [v])` string condition even though their id/trip_id
parameters were already plain `number` (or, for findPublicForShare,
narrowed to `number` here after confirming its one caller,
share.service.ts#getSharedTripData, only ever passes a number sourced
from a Kysely-typed share_tokens row, never an unconverted URL param) —
converted all six to MikroORM's typed `.where({...})` filter object.
The remaining raw string-form conditions in src/db/repositories/** are
NOT converted here: they are the `number | string` raw-bind seam
findAccessible/isOwner's own docstrings describe (trip_id/id threaded
through unconverted from req.params), which structurally requires the
deferred guard-level single toRowId parse to land first — narrowing any
of those methods' signatures now would either break the '0x10'/'007' id
parity those docstrings warn about, or duplicate the deferred item's own
work ahead of it landing.
* refactor(server): plan 4 — trek-photos.repository.ts finishes its rename
3e Task 6 renamed the CLASS (TrekPhotosRepository -> TrekPhotoRegistrationService,
since the name collided with the generated ORM TrekPhotos.repository.ts) but
left the FILE and its test file's names unchanged. Renames both to
trek-photo-registration.service.ts / .test.ts.
The old path is kept as a thin re-export stub (the src/websocket.ts shape)
rather than repointed at every one of its ~20 importers in this pass: several
of those files sit in two sibling tasks' exclusively-owned windows on this
shared branch (Task 3's budget/packing/todo/accommodations/places ripple,
reached through tests/helpers/plugin-host.ts and mcp-test-controllers.ts;
Task 5c's held-back tests/unit/services/{trekPhotoMedia,conflictUpdate}.test.ts)
and are off limits here. Flagged for a follow-up once those tasks land: delete
the stub and repoint every remaining importer at ./trek-photo-registration.service.
* fix(server): plan 4 — plugin discovery's delete+reinsert pairs are atomic
install/discovery.ts#upsert refreshed a plugin's actions and settings-field
descriptors as two independent delete-then-reinsert pairs (DI5-DI8) with no
transaction spanning either pair, let alone both: a crash between a delete
and its own reinsert left that plugin with an EMPTY actions or
settings-field set until the next discovery run, instead of its previous
still-valid rows. Wraps both pairs in one uow.transactional, so a discovery
refresh for a plugin's descriptors is now all-or-nothing.
Deliberate behaviour change, named for the user per the task brief.
DiscoveryRepos grows a UnitOfWork; PluginRegistryService (the other
production caller, registry.service.ts) picks it up the same @Optional()
way PluginRuntimeService already does, with the same guard-throw. Updates
the two hand-constructed test call sites that actually exercise discovery
(discovery.test.ts, registry.test.ts) to pass a real UnitOfWork.
* refactor(server): plan 4 — facade inline sweep part B (rosterUserIds/getPlaceWithTags)
Inline DatabaseService.rosterUserIds onto TripMembersRepository.rosterUserIds
directly in budget.service.ts, budget.mcp.ts and todo.service.ts, and
DatabaseService.getPlaceWithTags onto PlacesRepository.findWithTagsAndRatings
in accommodations.service.ts (placesRepo was already injected there).
BudgetService/BudgetMcp/TodoService collapse their constructors, dropping
the now-fully-unused DatabaseService param (budget.module.ts/todo.module.ts
register TripMembers on forFeature). PackingService keeps DatabaseService as
a vestigial param behind an optional TripMembersRepository with a fallback
in tripRosterIds: an in-flight Task 5c file
(tests/unit/services/conflictUpdate.test.ts) hand-constructs PackingService
positionally without the new repository, so its arity cannot change this
task; the fallback keeps that file's DatabaseService.rosterUserIds spy
working until Task 4 drops the param with the class itself.
* test(server): plan 4 — constructor ripple for the rosterUserIds/getPlaceWithTags inline
Hand-built BudgetService/BudgetMcp/TodoService call sites drop the removed
DatabaseService constructor arg (budgetRepoArgs() now appends a
TripMembersRepository so most spread call sites need no other change);
budget.service.test.ts's rosterHas() helper and svc() factory move from a
spied DatabaseService to a stubbed TripMembersRepository. The
AccommodationsService helper (tests/helpers/accommodations-service.ts) and
its two direct callers drop the same arg. PackingService call sites are
untouched (its new param is optional, so every existing hand-built instance
still resolves rosterUserIds through the DatabaseService fallback).
* fix(server): plan 4 — thread the discovery UnitOfWork through PluginRuntimeService too
Complements the just-landed discovery atomicity fix (DiscoveryRepos.uow):
PluginRuntimeService's own discoveryRepos getter still built the bundle
without a uow field. Threads its already-injected, @Optional() uow through
so its own onApplicationBootstrap/reload/dev-link discovery calls also get
the transactional DI5-DI8 refresh, not just PluginRegistryService's.
No throwing guard here, unlike PluginRegistryService's: several hand-built
partial-DI-graph test instances of this class (boot-registry-order.test.ts,
in a sibling task's held file window) construct it with uow omitted and
exercise onApplicationBootstrap's discovery call directly. Discovery must
never refuse outright just because a test built a partial graph, so it
degrades to the pre-existing untransacted sequence when uow is absent
(DiscoveryRepos.uow's own docstring covers this), the same "boot must
never block app init" defensiveness this file already applies elsewhere.
* fix(server): plan 4 — guard-level single parse: verify + correct the overclaiming verifyTripAccess docstring (L-2)
TripAccessGuard/TripOwnerGuard already parse :tripId exactly once
(Number(), guarded by Number.isFinite) and hand the resolved TripAccess
row to the handler via request[TRIP_REQUEST_KEY], TripOwnerGuard reusing
TripAccessGuard's own lookup when both are on the same route rather than
re-querying — verified by reading both guards directly, no change needed
there.
PlacesService.verifyTripAccess's own docstring separately claimed its
returned `tid` gets "returned... for every downstream call to reuse
(never re-parsing)" (3c's Task 9 review, L-2, carried to Plan 4). Reading
every call site (not assumed) shows this is false: `.tid` has exactly one
reader (PlacesController.requireTrip itself), which discards it — none of
requireTrip's 13 callers read `.tid` off the trip it returns; each passes
the original raw tripId string on to the write/read method it calls next,
which toRowId-parses it again itself. That second parse cannot be
eliminated by this gate alone: the same service methods are called
directly by places.mcp.ts too, an entry point with no requireTrip gate at
all (its own numeric tripId is re-stringified, String(tripId), to call
them), so each method owns its own id validation regardless of entry
point. Threading `tid` all the way through would mean giving every one of
~15 methods a second, number-only call shape for the REST path alone to
use — a real refactor, out of this docstring fix's own scope. Corrected
the docstring to say so plainly instead of repeating the false claim.
* refactor(server): plan 4 — relocate JS7/10/13/14 off the journey-share fallback stub
JourneyShareTokensRepository's own JS7/JS10/JS13/JS14 Kysely reads were a
3g Task 3 fallback (Task 2's JourneyPhotosRepository/JourneyEntriesRepository/
JourneyEntryPhotosRepository were still mid-flight). Now that those
repositories are stable, relocate: JS7/JS10 (photo/asset validation joins)
onto JourneyPhotosRepository (already injected into JourneyShareService as
photosRepo, no constructor change); JS13 (public entry list) onto
JourneyEntriesRepository.listPublicEntries; JS14 (public per-entry photo
read) onto JourneyEntryPhotosRepository.listForPublicJourney, deduped
against that repository's own JP_COLUMNS select list instead of a
hand-duplicated copy. JourneyShareService gains two new @InjectRepository
params (both already registered in journey-domain.module.ts's forFeature),
rippled through mcp-test-controllers.ts and journey-share.service.test.ts
(P04/P05 parity tests now pin the new homes).
* refactor(server): plan 4 — document unreachable ?? default arms after single-row aggregates
3f Task 7's fix wave flagged a cluster of `row?.x ?? default` arms after
unqualified, ungrouped aggregate reads (MAX/COUNT/COALESCE(SUM,0)) as
"same class as OauthClients:147" but left them unexamined per-site. Decided
per site: document, don't delete — TypeScript still types
executeTakeFirst()'s result as `| undefined` even though SQL guarantees
exactly one row for these unqualified aggregates, so the optional chain
can't be removed without a non-null assertion (worse, not safer). Six
sites: JourneyEntries.repository.ts (maxSortOrderForDate JG42,
countStatsPlaces JG67), JourneyEntryPhotos.repository.ts
(maxSortOrderForEntry JG91), JourneyPhotos.repository.ts (maxSortOrder
JG88/JG99), VacayEntries.repository.ts (sumFraction VC1, sumCompFraction
VC2). No behavior change — comments only.
* refactor(server): plan 4 — unify the two user-data-erasure enqueue paths
UserCleanupService.erasePluginUserData (the account-deletion transaction's
own UC2/UC3 enqueue) and PluginRuntimeService.enqueueUserErasure (the
emitUserDeleted sink's post-commit enqueue) independently walked the
identical SELECT id, permissions FROM plugins + JSON.parse + hook:user-data
filter + INSERT OR IGNORE — and both genuinely run for every account
deletion, since every emitUserDeleted call site (auth.service.ts,
admin.service.ts, trip-members.service.ts's guest removal) fires
immediately after deleteUserCompletely.
Extracted the shared filter into enqueueHookUserDataErasures
(nest/plugins/user-erasure-enqueue.ts) and pointed both call sites at it.
UC2/UC3 also come off DatabaseService onto PluginsRepository/
PluginUserErasureQueueRepository in the same change (they were the last
raw statements standing in the way of sharing one implementation) — this
narrows the Plan 3b Task 5 "stays raw, owned by Plan 3j" ruling to UC1
only (plugin_user_config/plugin_oauth_tokens/plugin_oauth_state), which
still stays raw, unaffected. UserCleanupService's orphan-data-directory
scan (a plugin uninstalled with data retained) has no equivalent on the
enqueueUserErasure side and stays there, now via the same repository.
Both enqueue calls still run per deletion (INSERT OR IGNORE keeps this
idempotent) — this unifies the IMPLEMENTATION, not the call count; not
touching the emitUserDeleted event-sink wiring itself was a deliberate,
smaller-blast-radius choice for this task.
* refactor(server): plan 4 — narrow TripMembersRepository.remove/TripsRepository.setOwner to number
Both accepted trip_id: number | string per 3c's carry note (their "stays
loose for other callers" reasoning), pending the guard-level single parse
landing first. Re-checked every caller directly: setOwner's one production
caller (trip-members.service.ts#transferOwnership) already passes trip.id,
a real number resolved earlier in the same transaction; remove's callers
are trips.rpc.ts (num(), already a validated number), trips.mcp.ts (Zod-
typed tool input, already a number) and TripMembersController.removeMember
(the one genuine raw-string caller, :id off the route with no class-level
TripAccessGuard on this controller by design).
TripMembersController.removeMember now parses :id once (toRowId, not
Number() — rule 15's NaN-into-SQL trap) and threads the parsed number to
both its own access check and removeMember, instead of passing the raw
string through twice. TripMembersService.removeMember and both repository
methods narrow to number accordingly; setOwner's WHERE also moves off its
raw-bind escape hatch onto nativeUpdate now that trip_id is typed, and
remove's trip_id half moves onto a typed .where({ trip: trip_id }) filter
(user_id keeps its own raw bind — a different, still-live NaN-safety seam,
unrelated to this narrowing).
TRIPREPO-018 and TMEMREPO-023, which pinned the retired string-bind seam
on setOwner/remove, no longer typecheck against the narrowed signatures
and are removed with an explanatory comment in their place.
* refactor(server): plan 4 — U6 gate-level id parsing for todo item ids
Rule 21's carry from 3e Task 8's review: TodoController.update/.remove
passed the raw :id route string all the way to TodoItemsRepository,
relying on SQLite's column-affinity CAST to match it instead of a typed
filter. Parse :id ONCE at the controller (toRowId, matching Task 8a's
TripAccessGuard/removeMember shape), 404 on a non-canonical id, and thread
the number down through TodoService.updateItem/deleteItem into
TodoItemsRepository.findInTrip/existsInTrip/update/deleteById, all
narrowed from number | string to number. todo.rpc.ts's num()-derived
todoId no longer needs its String() wrapper. tripId stays string | number
— a separate, already-accepted carry (
|
||
|
|
8739b4c74d | fix(tours): restrict permanent deletion to tours workspace | ||
|
|
af7dbce105 | fix(tours): prevent duplicate day assignments | ||
|
|
2ec5ae7e4d | merge: update Tours branch with current Places filters | ||
|
|
4b263c8e4b |
fix(mobile): align the places browser's filter panel with the map control
The panel button is named "Filters" like the map control, its badge counts kinds of filter through countActivePlacesFilters (the pool, shown as chips above it, stays out), and picking a rating floor clears the selection as picking a pool does. |
||
|
|
3d99e569ea | test(map): keep the places filter on a road trip's plan map without Dawarich | ||
|
|
db3c9d660e |
fix(mobile): announce which Show and rating chip is chosen
MChip only showed its state through colour. A pressable option renders aria-pressed from active; the places filter's Show and rating floor chips use it, and the tests now check the chosen chip by its pressed state. |
||
|
|
3951e8cc9a |
fix(map): announce the places filter control as opening a dialog
MapTogglePill always set aria-pressed, so the phone map's Filters control read as a toggle although it opens a sheet. An opensDialog option drops aria-pressed for aria-haspopup="dialog"; the other map toggles are unchanged. |
||
|
|
a9f7adf99b |
fix(map): move the tracks filter fallback to the always-mounted planner hook
The fallback from "Tracks" to "All" once the last track disappears lived in the desktop sidebar and the phone places browser, neither of which is mounted while the phone map is in front: the map could sit empty under a filter no control offers any more. useTripPlanner now owns it, once, for every screen. |