mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
Merge dev into feat/native-apps
Brings the native apps branch up to dev (NestJS-only server, MikroORM
repositories, tracked sessions, per-domain locales, the lint ratchets) and
ports its new code onto that architecture:
- server: /api/auth/native moves onto injected services. The session is
minted by the auth domain's new LoginSessionService (login bookkeeping and
SessionsService.issue in one transaction), the one-time codes live behind a
NativeHandoffStore port with a capped in-memory implementation that drops
expired codes on write instead of running a timer, both routes declare
response contracts, and the exchange answers { success: true }. Unit and
e2e suites run on createTestModule and the ORM factories.
- shared: native strings for az, et, sk and th, native wired into every
locale, the address placeholder as a full URL.
- client: the account and export changes go into dev's shared hooks
(useAccountSettings, useTripExport), the native server card is a
desktop/phone pair on useNativeServer, the hand-off call moves out of the
page hook into native/, best-effort native failures go through
reportError instead of the console, and the address screen is known to
knip and lint:i18n-keys.
- package-lock.json regenerated on Linux.
This commit is contained in:
+55
-3
@@ -24,6 +24,7 @@ ALLOWED_ORIGINS=https://trek.example.com # Comma-separated origins for CORS and
|
||||
FORCE_HTTPS=false # Optional. When true: HTTPS redirect + HSTS + CSP upgrade-insecure-requests + secure cookies. Only behind a TLS proxy.
|
||||
# HSTS_INCLUDE_SUBDOMAINS=false # When true: adds includeSubDomains to the HSTS header. Only effective when HSTS is active (FORCE_HTTPS=true or NODE_ENV=production). Leave false if you run other services on sibling subdomains over plain HTTP.
|
||||
COOKIE_SECURE=true # Auto-derived (true when NODE_ENV=production or FORCE_HTTPS=true). Set false to force cookies over plain HTTP.
|
||||
# HTTP_KEEP_ALIVE_TIMEOUT_MS=95000 # How long an idle keep-alive connection stays open. Keep it above your reverse proxy's upstream idle timeout (60 s for nginx and most load balancers, 90 s for Traefik) or the proxy answers some requests with a 502. 1000 to 290000. (default: 95000)
|
||||
TRUST_PROXY=1 # Trusted proxy hops (parseInt or 1). Active in production by default; off in dev unless set. Needed for FORCE_HTTPS.
|
||||
ALLOW_INTERNAL_NETWORK=false # Allow outbound requests to private/RFC1918 IPs (e.g. Immich hosted on your LAN). Loopback and link-local addresses are always blocked.
|
||||
# ALLOW_LINK_LOCAL_IPS=169.254.1.2 # Single link-local addresses TREK may reach after all, comma-separated, e.g. the host gateway of a rootless Podman container. OIDC reaches a listed address directly; other integrations also need ALLOW_INTERNAL_NETWORK=true. 169.254.169.x and 169.254.170.x (cloud metadata) cannot be listed.
|
||||
@@ -37,34 +38,85 @@ OIDC_DISPLAY_NAME=SSO # Label shown on the SSO login button
|
||||
OIDC_ONLY=true # Disable local password auth entirely (SSO only). Equivalent to setting password_login=false and password_registration=false in Admin > Settings.
|
||||
OIDC_ADMIN_CLAIM=groups # OIDC claim used to identify admin users
|
||||
OIDC_ADMIN_VALUE=app-trek-admins # Value of the OIDC claim that grants admin role
|
||||
OIDC_USERNAME_CLAIM= # Claim a new account's username comes from, e.g. preferred_username. Unset: name, then preferred_username
|
||||
OIDC_DISCOVERY_URL= # Override the auto-constructed OIDC discovery endpoint. Useful for providers (e.g. Authentik) that expose it at a non-standard path. Example: https://auth.example.com/application/o/trek/.well-known/openid-configuration
|
||||
OIDC_SCOPE=openid email profile # Fully overrides the default. Add extra scopes as needed (e.g. add groups if using OIDC_ADMIN_CLAIM)
|
||||
|
||||
DEMO_MODE=false # Demo mode - resets data hourly
|
||||
DEMO_MODE=false # Demo mode: resets data hourly
|
||||
# DEMO_ADMIN_USER=admin # Username of the admin account a demo instance seeds on its first start. (default: admin)
|
||||
# DEMO_ADMIN_EMAIL=admin@trek.app # Email of that seeded demo admin. (default: admin@trek.app)
|
||||
# DEMO_ADMIN_PASS=admin12345 # Initial password of that seeded demo admin. Change it on a public demo. (default: admin12345)
|
||||
|
||||
# RESTORE_FROM_BACKUP=/app/data/backup.zip # Restore this backup on the first start, before any setup. Ignored once a database exists.
|
||||
# FILE_UPLOAD_LIMIT_MB=50 # Max size (MB) of a file uploaded to a trip, a booking or a note. Videos keep their own 500 MB cap. Raise your reverse proxy's upload limit too.
|
||||
# BACKUP_MAX_DECOMPRESSED_MB=5120 # Max size (MB) a restore archive may unpack to, on both restore paths: the zip-bomb guard. Raise it if a large backup is refused with "Backup exceeds the maximum decompressed size". (default: 5120)
|
||||
# BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size).
|
||||
|
||||
# TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot.
|
||||
# TREK_DB_PRE_MIGRATE_SNAPSHOT=true # Copy the database to data/pre-migrate-<schema>-<time>.db before a startup migrates it, so the previous image can run on the copy again. A copy that cannot be written stops the startup; false migrates without one.
|
||||
# TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP=3 # How many pre-migrate copies to keep, newest first (1 to 100). (default: 3)
|
||||
# TREK_DB_SYNCHRONOUS=NORMAL # How hard SQLite flushes to disk (OFF, NORMAL, FULL, EXTRA). Defaults to NORMAL under WAL and FULL under any other journal mode — leave it alone unless you know why you want otherwise. Both variables fall back to their default (with a warning in the log) if the value is not a mode SQLite knows.
|
||||
|
||||
# MCP_RATE_LIMIT=300 # Max MCP API requests per user per minute (default: 300)
|
||||
# MCP_MAX_SESSION_PER_USER=20 # Max concurrent MCP sessions per user (default: 20)
|
||||
# MCP_SESSION_TTL=3600 # Idle timeout of an MCP session in seconds, at most 86400. (default: 3600)
|
||||
# MCP_SSE_KEEPALIVE=25 # Seconds between keep-alive pings on an open MCP event stream, so a reverse proxy does not cut it. 0 turns the pings off. (default: 25)
|
||||
# IDEMPOTENCY_TTL_SECONDS=2592000 # How long the server remembers an X-Idempotency-Key. The offline client replays queued changes with their key on reconnect, so keep this longer than the longest time a device stays offline. (default: 2592000, 30 days)
|
||||
|
||||
# NOMINATIM_URL=https://nominatim.openstreetmap.org # Custom HTTP(S) Nominatim base URL for every geocoding call the server makes: place search, reverse lookup, place details and the Atlas region fill. When set it REPLACES the public service with no fallback, so whatever answers has to speak the Nominatim API (/search, /reverse, /lookup) and hold the coverage you expect. TREK keeps its ~1 request per second spacing whichever instance answers. Unset/blank uses the public default.
|
||||
|
||||
# OVERPASS_URL= # Custom Overpass endpoint(s) for the map POI "explore" search, comma-separated. When set, REPLACES the bundled public mirrors — point it at an internal/self-hosted Overpass instance when the public ones are unreachable from your network. Non-http(s) entries are ignored. If you don't self-host Overpass but the public mirrors throttle you, setting APP_URL also gives outbound requests a unique User-Agent the mirrors rate-limit less.
|
||||
# OVERPASS_TIMEOUT_MS=25000 # Per-endpoint timeout (ms) for Overpass POI requests; slower endpoints are abandoned so a faster mirror wins. The query itself gives Overpass 20 seconds of work, so a lower value hangs up on answers that were still coming. Raise it for a slow self-hosted instance. (default: 25000)
|
||||
# OVERPASS_TIMEOUT_MS=25000 # Per-endpoint timeout (ms) for Overpass POI requests; slower endpoints are abandoned so a faster mirror wins. The query itself gives Overpass 20 seconds of work, so a lower value hangs up on answers that were still coming. Raise it for a slow self-hosted instance. The Tours search along a tour does not read it: it gives Overpass 10 seconds of work and waits 12. (default: 25000)
|
||||
|
||||
# TREK_PLACES_ENABLED=false # Whether place search asks the TREK Places API at https://places.liketrek.com: suggestions, the full search, the category buttons on the map, the Road trip search along the route, import geocoding and offline downloads. It is on by default and has no switch in the admin panel, because whether searches leave the instance is a deployment decision. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing to that host. (default: true)
|
||||
# TREK_PLACES_ENABLED=false # Whether place search asks the TREK Places API at https://places.liketrek.com: suggestions, the full search, the category buttons on the map, the Road trip search along the route, import geocoding, offline downloads, and the OpenStreetMap ways and horse routes Tours reads. It is on by default and has no switch in the admin panel, because whether searches leave the instance is a deployment decision. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing to that host. (default: true)
|
||||
# TREK_PLACES_URL=https://places.liketrek.com # Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from configuration rather than typed by a user, so an address on your LAN or Docker network works without ALLOW_INTERNAL_NETWORK. (default: https://places.liketrek.com)
|
||||
|
||||
# PLACES_API_KEY= # Google Maps API key (Places API (New) enabled) for place search, photos, details and Google transit. Overrides the key set in Admin > Settings > API Keys, whose field then shows this variable read-only. The value never reaches the browser.
|
||||
# GOOGLE_LIST_DATA_BASE= # Optional HTTP(S) base URL of a list-data service, e.g. https://maps.example.com. Paste a URL beginning with this base to fetch and parse it directly. Unset keeps the original Google list import flow.
|
||||
|
||||
# AMAP_API_KEY= # Amap (高德地图) Web 服务 key for place search and geocoding inside mainland China. Overrides the key set in Admin > Settings > API Keys. A Web 端 (JS API) key is a different credential and is rejected with INVALID_USER_KEY.
|
||||
# AMAP_API_SECRET= # The private secret (数字签名) of that key. Required exactly when the key was created with signing enabled, because such a key rejects every unsigned request. Leave unset otherwise.
|
||||
# AMAP_API_BASE=https://restapi.amap.com # Send the Amap calls through an egress proxy, a cache or a gateway that speaks the same API instead of restapi.amap.com directly. (default: https://restapi.amap.com)
|
||||
|
||||
# TRANSIT_API_URL=https://api.transitous.org # Base URL of the transit routing API the server proxies to. Point it at your own MOTIS instance to keep transit searches off third-party servers. A trailing slash is stripped. (default: https://api.transitous.org)
|
||||
|
||||
# TREK_PLACE_PHOTO_DIR= # Directory for cached Google place photos, e.g. a dedicated volume. Unset, they live in uploads/photos/google. Read once at startup. (default: uploads/photos/google)
|
||||
|
||||
# KITINERARY_EXTRACTOR_PATH= # Full path to the kitinerary-extractor binary. Unset, TREK searches /usr/lib/*/libexec/kf6/ and then PATH; the official image pins it. Set it to run a newer extractor than your distribution packages — the version in use is in the startup log and in GET /api/admin/system-info. (default: auto-detected)
|
||||
|
||||
# LLM_TIMEOUT_MS=900000 # Ceiling (ms) for one AI-parsing call before it is abandoned. One value for every provider, and the underlying HTTP client is held to it too. Generous by default so heavier parsing work fits without a code change; lower it on a cloud provider to fail fast. (default: 900000)
|
||||
# LLM_MAX_OUTPUT_TOKENS=8192 # Longest answer (tokens) one AI-parsing call may ask for. Raise it when a document with many bookings comes back cut off; keep prompt plus cap inside your model's context. (default: 4096 for OpenAI-compatible, 8192 for Anthropic)
|
||||
|
||||
# VAPID_PUBLIC_KEY= # Web Push: the public half of the key pair browsers subscribe with (base64url, 65 bytes). Leave both halves unset and TREK generates a pair on first start and keeps it in the database, so it travels with every backup. Set both to use a pair of your own, e.g. printed by `npx web-push generate-vapid-keys`. Changing the pair later means every device has to turn push on again.
|
||||
# VAPID_PRIVATE_KEY= # Web Push: the private half (base64url, 32 bytes). Only used together with VAPID_PUBLIC_KEY; a pair whose halves do not belong together, or only one half, turns push off with an error in the log until the pair is fixed. A pair stored in the database is not used in its place, and every device stays registered.
|
||||
# VAPID_SUBJECT=mailto:admin@example.com # Web Push: the contact push services see with every message, a mailto: address or an https:// URL. Unset, TREK uses APP_URL when it is https, else the TREK project page.
|
||||
|
||||
# SMTP_HOST=smtp.example.com # Outgoing mail server. SMTP_HOST, SMTP_PORT and SMTP_FROM are all needed for email; each SMTP_* variable overrides its field in Admin > Settings > Notifications.
|
||||
# SMTP_PORT=587 # Port 465 uses implicit TLS; every other port uses STARTTLS or plain.
|
||||
# SMTP_USER= # SMTP login, if the server wants one.
|
||||
# SMTP_PASS= # SMTP password, if the server wants one.
|
||||
# SMTP_FROM=TREK <noreply@example.com> # Sender address of every email TREK sends.
|
||||
# SMTP_SKIP_TLS_VERIFY=false # true accepts a self-signed certificate on an internal relay. Not for production.
|
||||
|
||||
# WEBAUTHN_RP_ID=trek.example.com # The domain passkeys are bound to. Overrides the setting in the admin panel; unset, it comes from the hostname of APP_URL. An IP address is refused.
|
||||
# WEBAUTHN_ORIGINS=https://trek.example.com # Comma-separated origins allowed for passkey sign-in. Overrides the setting in the admin panel; unset, the origin of APP_URL is used.
|
||||
|
||||
# TREK_API_DOCS_ENABLED=false # Serve the OpenAPI docs at /api/docs (raw spec at /api/docs-json). Off by default because the spec lists every route, the admin ones included.
|
||||
|
||||
# TREK_PLUGINS_ENABLED=true # false turns the whole plugin system off: no plugin runs and the admin panel says so. (default: true)
|
||||
# TREK_PLUGINS_DIR= # Where installed plugin code is kept. Persist it as a volume if you use plugins. (default: data/plugins)
|
||||
# TREK_PLUGINS_DATA_DIR= # Where each plugin keeps its own data. Persist it too. (default: data/plugins-data)
|
||||
# TREK_PLUGIN_REGISTRY_URL=https://raw.githubusercontent.com/liketrek/TREK-Plugins/main/dist/index.json # The plugin index the Discover tab browses. Point it at your own mirror or fork.
|
||||
# TREK_PLUGIN_PERMISSIONS=true # false takes plugin processes out of Node's OS permission sandbox. Not recommended. (default: true)
|
||||
# TREK_PLUGIN_ALLOW_PRIVATE_EGRESS=false # true lets a plugin's declared hosts resolve to private addresses, e.g. a service on your LAN. (default: false)
|
||||
# TREK_PLUGINS_IGNORE_TREK_RANGE=false # true turns the plugin TREK-version check into a warning, so a plugin outside its declared range can be installed anyway. (default: false)
|
||||
# TREK_PLUGINS_DEV_LINK=false # true shows "Link a local plugin" in the admin panel, for plugin authors. Development only. (default: false)
|
||||
# TREK_PLUGIN_MAX_RSS_MB=300 # Memory ceiling of one plugin process in MB; a plugin past it is stopped. (default: 300)
|
||||
# TREK_PLUGIN_RPC_BURST=60 # Host calls a plugin may make back to back before the per-second limit applies. (default: 60)
|
||||
# TREK_PLUGIN_RPC_PER_SEC=20 # Sustained host calls per second per plugin. (default: 20)
|
||||
# TREK_PLUGIN_RPC_INFLIGHT=16 # Host calls one plugin may have running at once. (default: 16)
|
||||
# TREK_PLUGIN_LOG_BURST=50 # Log lines a plugin may write back to back before the per-second limit applies. (default: 50)
|
||||
# TREK_PLUGIN_LOG_PER_SEC=10 # Sustained log lines per second per plugin. (default: 10)
|
||||
|
||||
# UNSPLASH_ACCESS_KEY= # Optional Unsplash Access Key for trip-cover and place-image search. Without one, TREK uses Unsplash's unauthenticated endpoint, which some datacenter/VPS IPs get blocked from (#1449). Get a free key at unsplash.com/developers. Overrides any key set per-admin in Admin > Settings. Can also be configured there instead of here.
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Written by scripts/generate-entities.ts and held byte for byte to its output
|
||||
# by check:entities, so Prettier must not rewrite them.
|
||||
src/db/entities/
|
||||
+2
-1
@@ -14,5 +14,6 @@
|
||||
"importOrderParserPlugins": [
|
||||
"typescript",
|
||||
"decorators-legacy"
|
||||
]
|
||||
],
|
||||
"importOrderSideEffects": false
|
||||
}
|
||||
|
||||
+92
-17
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
// Fixture project for the RuleTester in tests/unit/eslint-rules/. It exists so
|
||||
// typescript-eslint can build a real program for the virtual `file.ts` the
|
||||
// tester feeds it. Kept outside src/ and tests/ on purpose: files here must not
|
||||
// reach `tsc --noEmit`, `tsc -p tsconfig.tests.json` or the type-aware lint
|
||||
// blocks, since the invalid cases are deliberately broken code.
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2022"],
|
||||
"strict": false,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["file.ts"]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
// Second fixture project, identical but with strictNullChecks ON. The server
|
||||
// compiles with `strict: false`, where `Promise<T> | null` collapses to
|
||||
// `Promise<T>` and the rule's nullable exemptions are unreachable — this one
|
||||
// exists so those branches (`p ?? x`, `p === null`) are actually exercised.
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2022"],
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["strict.ts"]
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
/**
|
||||
* trek/no-promise-as-value — the blind spot the compiler cannot see.
|
||||
*
|
||||
* Phase 1 of the ORM migration turns hundreds of DB-touching methods `async`.
|
||||
* TypeScript catches a missed `await` only when the promise is used in a way it
|
||||
* can type-check: `promise.foo` (TS2339), a floating statement
|
||||
* (no-floating-promises), a condition (no-misused-promises). It catches NOTHING
|
||||
* when the promise is used as a plain value, because this project compiles with
|
||||
* `strict: false` / `noImplicitAny: false`:
|
||||
*
|
||||
* settings['metric'] // element access on a promise -> `any`
|
||||
* if (svc.get(id) === 'x') // always false, no error
|
||||
* `${svc.count(id)}` // "[object Promise]"
|
||||
* Object.keys(svc.all()) // []
|
||||
* JSON.stringify(svc.row(id)) // "{}"
|
||||
* for (const r of svc.rows()) // not iterable, at runtime only
|
||||
*
|
||||
* This rule reports those shapes. It is DELIBERATELY CONSERVATIVE and has no
|
||||
* fixer: it fires only when the resolved type is the global `Promise`/
|
||||
* `PromiseLike` itself (never a merely-thenable library type such as MikroORM's
|
||||
* QueryBuilder or supertest's Test, both of which are chained on purpose), only
|
||||
* when every non-nullish member of a union is one, and never inside
|
||||
* `Promise.all`/`allSettled`/`race`/`any`, on `.then`/`.catch`/`.finally`, on
|
||||
* `expect(p).resolves`/`.rejects`, or in an existence/identity check
|
||||
* (`p === undefined`, `p === null`, `p ?? q`, `a === b` between two promises) —
|
||||
* see isExistenceOrIdentityCheck below. A finding is a bug: add the `await`.
|
||||
*
|
||||
* It also reports a bare `expect(p)` (never `expect.soft`/other wrappers)
|
||||
* whose argument is a Promise, unless the call is immediately the object of a
|
||||
* `.resolves`/`.rejects` access, of `.toBeInstanceOf(Promise)` (asking
|
||||
* whether the value itself is a Promise IS the assertion, not a missing
|
||||
* await), or of `.toBe(otherPromise)` where the argument is itself
|
||||
* Promise-typed — the same in-flight-map identity idiom
|
||||
* isExistenceOrIdentityCheck exempts for `===`, just spelled with a matcher
|
||||
* (trek-photo-cache's stampede guard: `expect(svc.getInFlight(k)).toBe(fetch)`
|
||||
* — awaiting would compare the resolved buffer to the unawaited Promise `fetch`
|
||||
* and always fail). `expect(p).toBe(x)` is otherwise a vacuous assertion (it
|
||||
* always passes: a Promise object is never `=== x`), same bug class as the
|
||||
* rest of this rule but with its own message since the fix is either
|
||||
* `expect(await p)` or `await expect(p).resolves…`, not a bare `await`.
|
||||
*/
|
||||
import ts from 'typescript';
|
||||
|
||||
const NULLISH_FLAGS = ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void;
|
||||
const PASSTHROUGH_PROPS = new Set(['then', 'catch', 'finally', 'resolves', 'rejects']);
|
||||
const COMBINATORS = new Set(['all', 'allSettled', 'race', 'any']);
|
||||
const EQUALITY_OPERATORS = new Set(['==', '!=', '===', '!==']);
|
||||
// Callbacks whose result is consumed as a value, where a promise is always a bug
|
||||
// (every promise is truthy, so the predicate degenerates). `.map`/`.reduce` are
|
||||
// excluded on purpose: returning promises there feeds Promise.all legitimately.
|
||||
const PREDICATE_METHODS = new Set([
|
||||
'filter',
|
||||
'find',
|
||||
'findLast',
|
||||
'findIndex',
|
||||
'findLastIndex',
|
||||
'some',
|
||||
'every',
|
||||
'sort',
|
||||
]);
|
||||
const OBJECT_CONSUMERS = new Set(['keys', 'values', 'entries', 'assign', 'fromEntries']);
|
||||
|
||||
/** `String(p)` / `Number(p)` / `Object.keys(p)` / `JSON.stringify(p)` / `Array.isArray(p)`. */
|
||||
function isValueConsumerCall(callee) {
|
||||
if (callee.type === 'Identifier') return callee.name === 'String' || callee.name === 'Number';
|
||||
if (callee.type !== 'MemberExpression' || callee.computed) return false;
|
||||
const { object, property } = callee;
|
||||
if (object.type !== 'Identifier' || property.type !== 'Identifier') return false;
|
||||
if (object.name === 'Object') return OBJECT_CONSUMERS.has(property.name);
|
||||
if (object.name === 'JSON') return property.name === 'stringify';
|
||||
if (object.name === 'Array') return property.name === 'isArray';
|
||||
return false;
|
||||
}
|
||||
|
||||
function isCombinatorCall(node) {
|
||||
const callee = node.callee;
|
||||
return (
|
||||
callee.type === 'MemberExpression' &&
|
||||
!callee.computed &&
|
||||
callee.object.type === 'Identifier' &&
|
||||
callee.object.name === 'Promise' &&
|
||||
callee.property.type === 'Identifier' &&
|
||||
COMBINATORS.has(callee.property.name)
|
||||
);
|
||||
}
|
||||
|
||||
/** Inside `Promise.all([...])` a promise IS the value; stop at the function boundary. */
|
||||
function isInsideCombinator(node) {
|
||||
for (let cur = node.parent; cur; cur = cur.parent) {
|
||||
if (cur.type === 'CallExpression' && isCombinatorCall(cur)) return true;
|
||||
if (cur.type.includes('Function')) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isNullLiteral(node) {
|
||||
return (node.type === 'Literal' && node.value === null) || (node.type === 'Identifier' && node.name === 'undefined');
|
||||
}
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description:
|
||||
'Disallow using a Promise as a plain value (element access, comparison, interpolation, spread, iteration) — the missing-await shapes the compiler cannot see with strict mode off.',
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
promiseAsValue: 'Promise used as a value (missing await?): {{ text }}',
|
||||
expectPromise: 'Promise passed to expect() without .resolves/.rejects (missing await?)',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const services = context.sourceCode.parserServices;
|
||||
if (!services?.program || !services.esTreeNodeToTSNodeMap) return {};
|
||||
const checker = services.program.getTypeChecker();
|
||||
const reported = new WeakSet();
|
||||
|
||||
const isNullish = (type) => (type.flags & NULLISH_FLAGS) !== 0;
|
||||
|
||||
function isPromiseType(type, tsNode) {
|
||||
if (!type) return false;
|
||||
if (type.isUnion()) {
|
||||
const parts = type.types.filter((t) => !isNullish(t));
|
||||
return parts.length > 0 && parts.every((t) => isPromiseType(t, tsNode));
|
||||
}
|
||||
const symbol = type.getSymbol() ?? type.aliasSymbol;
|
||||
const name = symbol?.getName();
|
||||
if (name !== 'Promise' && name !== 'PromiseLike') return false;
|
||||
const then = type.getProperty('then');
|
||||
if (!then) return false;
|
||||
return checker.getTypeOfSymbolAtLocation(then, tsNode).getCallSignatures().length > 0;
|
||||
}
|
||||
|
||||
function typeOf(node) {
|
||||
if (!node || node.type === 'AwaitExpression' || node.type === 'PrivateIdentifier') return null;
|
||||
const tsNode = services.esTreeNodeToTSNodeMap.get(node);
|
||||
return tsNode ? { type: checker.getTypeAtLocation(tsNode), tsNode } : null;
|
||||
}
|
||||
|
||||
function isPromise(node) {
|
||||
const resolved = typeOf(node);
|
||||
return !!resolved && isPromiseType(resolved.type, resolved.tsNode);
|
||||
}
|
||||
|
||||
function report(node) {
|
||||
if (!node || reported.has(node) || isInsideCombinator(node)) return;
|
||||
reported.add(node);
|
||||
const raw = context.sourceCode.getText(node).replace(/\s+/g, ' ');
|
||||
const text = raw.length > 60 ? `${raw.slice(0, 57)}...` : raw;
|
||||
context.report({ node, messageId: 'promiseAsValue', data: { text } });
|
||||
}
|
||||
|
||||
function check(node) {
|
||||
if (isPromise(node)) report(node);
|
||||
}
|
||||
|
||||
function reportExpect(node) {
|
||||
if (!node || reported.has(node)) return;
|
||||
reported.add(node);
|
||||
context.report({ node, messageId: 'expectPromise' });
|
||||
}
|
||||
|
||||
/** Bare `expect(...)` only — `expect.soft(...)` and other wrappers are untouched. */
|
||||
function isBareExpectCall(node) {
|
||||
return node.callee.type === 'Identifier' && node.callee.name === 'expect';
|
||||
}
|
||||
|
||||
/** `expect(p).resolves` / `expect(p).rejects`, however it is chained further from there. */
|
||||
function isResolvesOrRejectsAccess(node) {
|
||||
const parent = node.parent;
|
||||
return (
|
||||
!!parent &&
|
||||
parent.type === 'MemberExpression' &&
|
||||
parent.object === node &&
|
||||
!parent.computed &&
|
||||
parent.property.type === 'Identifier' &&
|
||||
(parent.property.name === 'resolves' || parent.property.name === 'rejects')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `expect(p).toBeInstanceOf(Promise)` asks whether the VALUE ITSELF is a
|
||||
* Promise object — that is the assertion, not a missing await, and
|
||||
* awaiting it would change what the test checks. Exempt only that literal
|
||||
* shape: the argument must resolve to the global `Promise` constructor, so
|
||||
* `expect(f()).toBeInstanceOf(SomeOtherClass)` is still a reported bug.
|
||||
*/
|
||||
function isInstanceOfPromiseCheck(node) {
|
||||
const memberParent = node.parent;
|
||||
if (
|
||||
!memberParent ||
|
||||
memberParent.type !== 'MemberExpression' ||
|
||||
memberParent.object !== node ||
|
||||
memberParent.computed ||
|
||||
memberParent.property.type !== 'Identifier' ||
|
||||
memberParent.property.name !== 'toBeInstanceOf'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const callParent = memberParent.parent;
|
||||
if (!callParent || callParent.type !== 'CallExpression' || callParent.callee !== memberParent) return false;
|
||||
const arg = callParent.arguments[0];
|
||||
const resolved = arg && typeOf(arg);
|
||||
if (!resolved) return false;
|
||||
const symbol = resolved.type.getSymbol();
|
||||
return symbol?.getName() === 'PromiseConstructor';
|
||||
}
|
||||
|
||||
/**
|
||||
* `expect(p).toBe(otherPromise)` — an identity check between two Promise
|
||||
* references (the in-flight-map stampede guard), not a resolved-value
|
||||
* comparison. Mirrors isExistenceOrIdentityCheck's "both sides are
|
||||
* promises" branch for `===`.
|
||||
*/
|
||||
function isPromiseIdentityToBe(node) {
|
||||
const memberParent = node.parent;
|
||||
if (
|
||||
!memberParent ||
|
||||
memberParent.type !== 'MemberExpression' ||
|
||||
memberParent.object !== node ||
|
||||
memberParent.computed ||
|
||||
memberParent.property.type !== 'Identifier' ||
|
||||
memberParent.property.name !== 'toBe'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const callParent = memberParent.parent;
|
||||
if (!callParent || callParent.type !== 'CallExpression' || callParent.callee !== memberParent) return false;
|
||||
const arg = callParent.arguments[0];
|
||||
return !!arg && isPromise(arg);
|
||||
}
|
||||
|
||||
/**
|
||||
* `p === undefined` / `p === null` is how this codebase asks whether an
|
||||
* in-flight promise is already parked in a map — a truthiness test there is
|
||||
* what no-misused-promises rejects, so the explicit comparison IS the
|
||||
* correct idiom (weather, collab, maps, exchange-rates, idempotency, the
|
||||
* plugin drain, atlas). `chains.get(userId) === next` likewise asks whether
|
||||
* the promise it stored is still the current one. Neither can be told apart
|
||||
* from a missing await by type alone — with strictNullChecks off `Map.get()`
|
||||
* is not even typed as nullable — so equality against nullish, and equality
|
||||
* between two promises, are both exempt. `p === 'x'` still reports.
|
||||
*/
|
||||
function isExistenceOrIdentityCheck(node) {
|
||||
if (isNullLiteral(node.left) || isNullLiteral(node.right)) return true;
|
||||
return isPromise(node.left) && isPromise(node.right);
|
||||
}
|
||||
|
||||
return {
|
||||
MemberExpression(node) {
|
||||
const key =
|
||||
node.property.type === 'Identifier' && !node.computed
|
||||
? node.property.name
|
||||
: node.property.type === 'Literal'
|
||||
? node.property.value
|
||||
: undefined;
|
||||
if (typeof key === 'string' && PASSTHROUGH_PROPS.has(key)) return;
|
||||
check(node.object);
|
||||
},
|
||||
|
||||
BinaryExpression(node) {
|
||||
// `p instanceof Promise` is the legitimate way to ask.
|
||||
if (node.operator === 'instanceof') return;
|
||||
if (EQUALITY_OPERATORS.has(node.operator) && isExistenceOrIdentityCheck(node)) return;
|
||||
check(node.left);
|
||||
check(node.right);
|
||||
},
|
||||
|
||||
LogicalExpression(node) {
|
||||
// `p ?? x` is the same existence check as `p === undefined`, and with
|
||||
// strictNullChecks off the type cannot say whether it is a real one.
|
||||
if (node.operator === '??') return;
|
||||
// Only the left operand of `&&`/`||`: it is the one evaluated as a test,
|
||||
// where a promise is unconditionally truthy. The right operand IS the
|
||||
// expression's value and gets caught at whatever consumes it.
|
||||
check(node.left);
|
||||
},
|
||||
|
||||
TemplateLiteral(node) {
|
||||
node.expressions.forEach(check);
|
||||
},
|
||||
|
||||
SpreadElement(node) {
|
||||
check(node.argument);
|
||||
},
|
||||
|
||||
UnaryExpression(node) {
|
||||
if (node.operator === 'typeof') check(node.argument);
|
||||
},
|
||||
|
||||
ForOfStatement(node) {
|
||||
if (!node.await) check(node.right);
|
||||
},
|
||||
|
||||
ForInStatement(node) {
|
||||
check(node.right);
|
||||
},
|
||||
|
||||
CallExpression(node) {
|
||||
if (
|
||||
isBareExpectCall(node) &&
|
||||
node.arguments.length > 0 &&
|
||||
node.arguments[0].type !== 'SpreadElement' &&
|
||||
!isResolvesOrRejectsAccess(node) &&
|
||||
!isInstanceOfPromiseCheck(node) &&
|
||||
!isPromiseIdentityToBe(node) &&
|
||||
isPromise(node.arguments[0])
|
||||
) {
|
||||
reportExpect(node.arguments[0]);
|
||||
return;
|
||||
}
|
||||
if (isValueConsumerCall(node.callee)) {
|
||||
node.arguments.forEach((arg) => {
|
||||
if (arg.type !== 'SpreadElement') check(arg);
|
||||
});
|
||||
return;
|
||||
}
|
||||
const callee = node.callee;
|
||||
if (
|
||||
callee.type !== 'MemberExpression' ||
|
||||
callee.computed ||
|
||||
callee.property.type !== 'Identifier' ||
|
||||
!PREDICATE_METHODS.has(callee.property.name)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
for (const arg of node.arguments) {
|
||||
if (arg.type !== 'ArrowFunctionExpression' && arg.type !== 'FunctionExpression') continue;
|
||||
const resolved = typeOf(arg);
|
||||
if (!resolved) continue;
|
||||
const signatures = resolved.type.getCallSignatures();
|
||||
if (
|
||||
signatures.length > 0 &&
|
||||
signatures.every((sig) => isPromiseType(checker.getReturnTypeOfSignature(sig), resolved.tsNode))
|
||||
) {
|
||||
report(arg.body.type === 'BlockStatement' ? arg : arg.body);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
+378
-58
@@ -4,6 +4,163 @@ import gitignore from 'eslint-config-flat-gitignore';
|
||||
import eslintConfigPrettier from 'eslint-config-prettier';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
import noPromiseAsValue from './eslint-rules/no-promise-as-value.mjs';
|
||||
|
||||
// Local rules live in eslint-rules/ and are exposed under the `trek/` prefix.
|
||||
const trek = { rules: { 'no-promise-as-value': noPromiseAsValue } };
|
||||
|
||||
// The calls the outbound-timeout selectors below look at: the platform fetch and
|
||||
// the SSRF-guarded wrappers whose init is passed on to it. safeFetchLlm is not
|
||||
// one of them; its deadline is the LLM_TIMEOUT_MS setting, applied inside.
|
||||
const FETCH_CALLEE = '/^(fetch|safeFetch|safeFetchFollow|safeFetchAdminConfigured)$/';
|
||||
|
||||
// The no-restricted-syntax selector groups. A flat-config block's options REPLACE
|
||||
// those of an earlier block for the same files rather than adding to them, so a
|
||||
// block that adds one group has to restate the others; naming them once keeps
|
||||
// the restatements identical.
|
||||
const ENV_SELECTORS = [
|
||||
{
|
||||
selector: "MemberExpression[object.name='process'][property.name='env']",
|
||||
message:
|
||||
'Read configuration via src/app-config (readEnv()/derive/tokens), not process.env. Exemptions: eslint.config.mjs + src/app-config/README.md.',
|
||||
},
|
||||
{
|
||||
// Bracket-notation variant (process['env']): the property is a Literal
|
||||
// node (.value), so the selector above can't match it.
|
||||
selector: "MemberExpression[object.name='process'][property.value='env']",
|
||||
message:
|
||||
'Read configuration via src/app-config (readEnv()/derive/tokens), not process.env. Exemptions: eslint.config.mjs + src/app-config/README.md.',
|
||||
},
|
||||
];
|
||||
|
||||
const RAW_SQL_SELECTORS = [
|
||||
{
|
||||
selector: "CallExpression[callee.name='raw']",
|
||||
message:
|
||||
'Dialect SQL goes through src/db/dialect/sql-functions.ts, which dispatches on the live MikroORM platform. A repository must not spell raw SQL.',
|
||||
},
|
||||
{
|
||||
selector: "TaggedTemplateExpression[tag.name='sql']",
|
||||
message:
|
||||
'Dialect SQL goes through src/db/dialect/sql-functions.ts, which dispatches on the live MikroORM platform. A repository must not spell raw SQL.',
|
||||
},
|
||||
];
|
||||
|
||||
// Kysely fills InsertResult.insertId from SQLite's last_insert_rowid. Postgres
|
||||
// has no such value, so there it is undefined and Number(result.insertId) is
|
||||
// NaN: an insert that needs the new id reads it with .returning('id').
|
||||
const INSERT_ID_MESSAGE =
|
||||
"InsertResult.insertId is SQLite's last_insert_rowid and undefined on Postgres. Read the new id with .returning('id').executeTakeFirstOrThrow().";
|
||||
const INSERT_ID_SELECTORS = [
|
||||
{ selector: "MemberExpression[property.name='insertId']", message: INSERT_ID_MESSAGE },
|
||||
{ selector: "ObjectPattern > Property[key.name='insertId']", message: INSERT_ID_MESSAGE },
|
||||
];
|
||||
|
||||
// A guarded call whose options object (third argument) sets `timeoutMs` has a
|
||||
// deadline over the whole exchange, so it does not need a signal in the init.
|
||||
// esquery only resolves `:nth-child` inside `:has` when each step is its own
|
||||
// nested `:has`, hence the shape.
|
||||
const FETCH_CALL = `CallExpression[callee.name=${FETCH_CALLEE}]:not(:has(> ObjectExpression.arguments:nth-child(3):has(> Property[key.name='timeoutMs'])))`;
|
||||
|
||||
// An argument that stands for "no init": undefined, null or void 0, also behind an `as` cast.
|
||||
const NO_INIT = [
|
||||
"Identifier[name='undefined']",
|
||||
"Literal[raw='null']",
|
||||
"UnaryExpression[operator='void']",
|
||||
// esquery compares String(value), so a missing `name` would read as 'undefined':
|
||||
// the cast's inner node type is pinned first.
|
||||
"TSAsExpression[expression.type='Identifier'][expression.name='undefined']",
|
||||
"TSAsExpression[expression.type='Literal'][expression.raw='null']",
|
||||
"TSAsExpression[expression.type='UnaryExpression'][expression.operator='void']",
|
||||
].join(', ');
|
||||
|
||||
const FETCH_TIMEOUT_MESSAGE =
|
||||
'Outbound fetch needs a timeout: pass { signal: AbortSignal.timeout(ms) }, or { timeoutMs } in the options of safeFetch/safeFetchFollow.';
|
||||
|
||||
const FETCH_SELECTORS = [
|
||||
{
|
||||
// Every outbound fetch needs a timeout (server/CLAUDE.md): a provider
|
||||
// that takes the connection and goes quiet otherwise holds the request
|
||||
// for undici's 300 s default. An init built elsewhere (a variable or a
|
||||
// spread) is trusted to carry its own signal. The SSRF-guarded
|
||||
// wrappers in utils/ssrfGuard.ts are held to the same rule: they hand
|
||||
// the platform a spread init, so the rule cannot see through them, and
|
||||
// their own fallback only bounds the wait for the headers.
|
||||
selector: `${FETCH_CALL}[arguments.length=1]`,
|
||||
message: FETCH_TIMEOUT_MESSAGE,
|
||||
},
|
||||
{
|
||||
selector: `${FETCH_CALL} > ObjectExpression.arguments:nth-child(2):not(:has(Property[key.name='signal'])):not(:has(SpreadElement))`,
|
||||
message: FETCH_TIMEOUT_MESSAGE,
|
||||
},
|
||||
{
|
||||
// `safeFetch(url, undefined, options)` is the same call without an init.
|
||||
selector: `${FETCH_CALL} > :matches(${NO_INIT}).arguments:nth-child(2)`,
|
||||
message: FETCH_TIMEOUT_MESSAGE,
|
||||
},
|
||||
];
|
||||
|
||||
// The statements a SQL string starts with. Matching on the text rather than on
|
||||
// the method name keeps `qb.execute('run')` (a result mode, not SQL) legal.
|
||||
const SQL_TEXT = String.raw`/^\s*(SELECT|INSERT|UPDATE|DELETE|REPLACE|WITH|PRAGMA|VACUUM|CREATE|DROP|ALTER|ATTACH|BEGIN|COMMIT)\b/i`;
|
||||
const SQL_STRING_MESSAGE =
|
||||
'A SQL string handed to the connection is raw SQL too. Build it with the query builder (this.kysely(), em.createQueryBuilder) and route dialect functions through src/db/dialect/sql-functions.ts.';
|
||||
|
||||
const STRING_SQL_SELECTORS = [
|
||||
{
|
||||
selector: `CallExpression[callee.property.name=/^(execute|run|all|get)$/] > Literal.arguments:first-child[value=${SQL_TEXT}]`,
|
||||
message: SQL_STRING_MESSAGE,
|
||||
},
|
||||
{
|
||||
selector: `CallExpression[callee.property.name=/^(execute|run|all|get)$/] > TemplateLiteral.arguments:first-child[quasis.0.value.raw=${SQL_TEXT}]`,
|
||||
message: SQL_STRING_MESSAGE,
|
||||
},
|
||||
];
|
||||
|
||||
// An instance setting is named through the typed register in
|
||||
// src/nest/common/app-settings.registry.ts (readAppSetting/resolveAppSetting),
|
||||
// which checks the key and owns the env override, never as a string handed to
|
||||
// AppSettingsRepository.getValue. The register itself passes a variable, and a
|
||||
// key built from parts (`admin_notif_pref_${event}_${channel}`) names a family
|
||||
// the register does not list one by one.
|
||||
const APP_SETTING_MESSAGE =
|
||||
"Read an app setting through readAppSetting()/resolveAppSetting() from src/nest/common/app-settings.registry.ts, not getValue('<key>'): the register types the key and owns its env override.";
|
||||
const APP_SETTING_SELECTORS = [
|
||||
{ selector: "CallExpression[callee.property.name='getValue'] > Literal.arguments:first-child", message: APP_SETTING_MESSAGE },
|
||||
{ selector: "CallExpression[callee.property.name='getValue'] > TemplateLiteral.arguments:first-child[expressions.length=0]", message: APP_SETTING_MESSAGE },
|
||||
];
|
||||
|
||||
// The demo-mode write block runs once, in the MCP registry (trekDemoToolGate in
|
||||
// src/mcp/nest-mcp-policy.ts). A tool asking for itself again is a second copy
|
||||
// that drifts: it was 196 of them before the gate moved.
|
||||
const DEMO_GATE_MESSAGE =
|
||||
'MCP tools do not check demo mode themselves: the registry gate (trekDemoToolGate) refuses every tool not annotated read-only. Annotate the tool instead.';
|
||||
const MCP_DEMO_SELECTORS = [
|
||||
{ selector: "CallExpression[callee.property.name=/^isDemoUser(Id)?$/]", message: DEMO_GATE_MESSAGE },
|
||||
{ selector: "CallExpression[callee.name='demoDenied']", message: DEMO_GATE_MESSAGE },
|
||||
];
|
||||
|
||||
// XML is read in exactly two places: the GPX and KML codecs of place-import, and
|
||||
// the WebDAV client (PROPFIND answers). One parser setup per format instead of
|
||||
// one per caller is what keeps a GPX read in one module the same as in another.
|
||||
const XML_PARSER_PATH = {
|
||||
name: 'fast-xml-parser',
|
||||
message:
|
||||
'XML is parsed in src/nest/place-import (gpx.codec.ts, kml.codec.ts) and the WebDAV client only. Read GPX/KML through PlaceImportService instead of configuring another parser.',
|
||||
};
|
||||
|
||||
const DRIVER_PATH = {
|
||||
name: 'better-sqlite3',
|
||||
message:
|
||||
'The SQLite driver is an implementation detail of src/db. Go through the ORM (src/db/entities + src/db/repositories) or UnitOfWork; the handle itself is owned by src/db/database.ts.',
|
||||
};
|
||||
|
||||
const SERVICES_WALL = {
|
||||
group: ['**/services/*', '**/services/**/*'],
|
||||
message:
|
||||
'src/services/ is deleted. New backend code goes to src/nest/<domain>/ (service + controller + module, registered in app.module.ts). See src/nest/README.md.',
|
||||
};
|
||||
|
||||
export default tseslint.config(
|
||||
gitignore({ strict: false }),
|
||||
{
|
||||
@@ -25,9 +182,55 @@ export default tseslint.config(
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
eslintConfigPrettier,
|
||||
{
|
||||
files: ['src/**/*.ts'],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
// Type-aware linting for src/: the project service asks TypeScript which
|
||||
// config owns a file, the way an editor does, so there is no `project`
|
||||
// array to keep in sync. Every file under src/ is in tsconfig.json's
|
||||
// `include`, so the service resolves them all.
|
||||
projectService: true,
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
// tests/ needs the classic `project` instead. The project service looks for
|
||||
// the tsconfig.json nearest the file and refuses a file that config does not
|
||||
// include ("was not found by the project service"); tsconfig.json includes
|
||||
// only `src`, and its `allowDefaultProject` escape hatch rejects any glob
|
||||
// containing `**`, so it cannot cover a tree this size. `tsconfig.tests.json`
|
||||
// (the one `npm run typecheck:tests` uses) includes src + tests, which is
|
||||
// exactly the program these files need.
|
||||
files: ['tests/**/*.ts'],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.tests.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/**/*.ts', 'tests/**/*.ts'],
|
||||
plugins: { trek },
|
||||
rules: {
|
||||
// trek/no-promise-as-value closes the hole the two rules below leave open:
|
||||
// with `strict: false`, a promise used as a plain VALUE (element access,
|
||||
// comparison, interpolation, spread, iteration, Object.keys/JSON.stringify)
|
||||
// type-checks clean and silently produces `any`, `false` or `[object
|
||||
// Promise]`. See eslint-rules/no-promise-as-value.mjs.
|
||||
'trek/no-promise-as-value': 'error',
|
||||
// --- The promise safety net for the Phase 1 async sweep (ORM migration) ---
|
||||
// Turning a DB-touching method `async` makes every unawaited call site a
|
||||
// silently reordered write, and every `if (svc.exists(id))` permanently
|
||||
// true — neither of which the type checker reports. These two rules are
|
||||
// the only thing that catches them, so they are errors, not warnings.
|
||||
'@typescript-eslint/no-floating-promises': ['error', { ignoreVoid: true }],
|
||||
'@typescript-eslint/no-misused-promises': [
|
||||
'error',
|
||||
{ checksConditionals: true, checksVoidReturn: false, checksSpreads: true },
|
||||
],
|
||||
// --- Severities tuned to keep CI green on a codebase that was never linted ---
|
||||
// (each rule below has pre-existing violations; surfaced as warnings, not blockers)
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
@@ -42,6 +245,13 @@ export default tseslint.config(
|
||||
'no-empty': 'warn',
|
||||
'no-useless-escape': 'warn',
|
||||
'prefer-const': 'warn',
|
||||
// Held per rule by lint:warnings (scripts/eslint-baseline.json), so their
|
||||
// count may only fall: sequential awaits in a loop (N round trips where
|
||||
// one batch would do), `!` assertions that strict null checks would have
|
||||
// to prove instead, and console output that bypasses the audit logger.
|
||||
'no-await-in-loop': 'warn',
|
||||
'@typescript-eslint/no-non-null-assertion': 'warn',
|
||||
'no-console': 'warn',
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -65,21 +275,16 @@ export default tseslint.config(
|
||||
'src/nest/plugins/host/plugin-audit.ts',
|
||||
],
|
||||
rules: {
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
{
|
||||
selector: "MemberExpression[object.name='process'][property.name='env']",
|
||||
message:
|
||||
'Read configuration via src/app-config (readEnv()/derive/tokens), not process.env. Exemptions: eslint.config.mjs + src/app-config/README.md.',
|
||||
},
|
||||
{
|
||||
// Bracket-notation variant (process['env']) — property is a Literal
|
||||
// node (.value), so the selector above can't match it.
|
||||
selector: "MemberExpression[object.name='process'][property.value='env']",
|
||||
message:
|
||||
'Read configuration via src/app-config (readEnv()/derive/tokens), not process.env. Exemptions: eslint.config.mjs + src/app-config/README.md.',
|
||||
},
|
||||
],
|
||||
'no-restricted-syntax': ['error', ...ENV_SELECTORS, ...FETCH_SELECTORS, ...APP_SETTING_SELECTORS],
|
||||
},
|
||||
},
|
||||
{
|
||||
// Restates the config-access and app-setting guards above for *.mcp.ts
|
||||
// (a later block's options replace an earlier one's) and adds the
|
||||
// demo-gate wall.
|
||||
files: ['src/**/*.mcp.ts'],
|
||||
rules: {
|
||||
'no-restricted-syntax': ['error', ...ENV_SELECTORS, ...FETCH_SELECTORS, ...APP_SETTING_SELECTORS, ...MCP_DEMO_SELECTORS],
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -107,56 +312,171 @@ export default tseslint.config(
|
||||
},
|
||||
},
|
||||
{
|
||||
// The plugin RPC decorator kit is written to stay extractable into its own
|
||||
// package, so its dependencies are pinned to Nest plus the two host modules it
|
||||
// genuinely needs. See src/nest/plugins/host/rpc-kit/README.md for what an
|
||||
// extraction would cost, and why the envelope import is the deliberate exception.
|
||||
files: ['src/nest/plugins/host/rpc-kit/**/*.ts'],
|
||||
// D4: the driver is an implementation detail of src/db. Nothing else in
|
||||
// src/ names `better-sqlite3` — a domain module that imports it is coupled
|
||||
// to the engine the ORM exists to abstract, and (for the value import)
|
||||
// reaches a connection the DI graph never handed it.
|
||||
//
|
||||
// `no-restricted-imports` is repeated rather than added to the src/services
|
||||
// block above because ESLint flat config REPLACES a rule's options with the
|
||||
// last matching config object's — a block that set only the driver path
|
||||
// would silently drop the services wall for every file it matches.
|
||||
files: ['src/**/*.ts'],
|
||||
ignores: [
|
||||
// The connection and the ORM's bound driver: this is where the engine lives.
|
||||
'src/db/database.ts',
|
||||
// openDatabase(): every better-sqlite3 handle the server opens (#2518).
|
||||
'src/db/connection.ts',
|
||||
'src/db/orm-driver.ts',
|
||||
'src/db/durability.ts',
|
||||
// The plugin sandbox opens its own per-plugin database files, deliberately
|
||||
// outside the app's ORM and connection.
|
||||
'src/nest/plugins/host/plugin-data.service.ts',
|
||||
// Frozen forever (ruling 7): invoked from inside numbered, already-shipped
|
||||
// MikroORM migrations: rewriting it onto the ORM would change what a
|
||||
// re-run of an old migration against an old schema snapshot produces,
|
||||
// which is never done to a landed migration. Not Plan 4's or any future
|
||||
// plan's to touch.
|
||||
'src/db/reseat-booked-nights.ts',
|
||||
],
|
||||
rules: {
|
||||
'no-restricted-imports': ['error', { paths: [DRIVER_PATH, XML_PARSER_PATH], patterns: [SERVICES_WALL] }],
|
||||
},
|
||||
},
|
||||
{
|
||||
// The files the block above leaves out for the driver still may not parse
|
||||
// XML: restated with XML_PARSER_PATH and the services wall only.
|
||||
files: [
|
||||
'src/db/database.ts',
|
||||
'src/db/connection.ts',
|
||||
'src/db/orm-driver.ts',
|
||||
'src/db/durability.ts',
|
||||
'src/nest/plugins/host/plugin-data.service.ts',
|
||||
'src/db/reseat-booked-nights.ts',
|
||||
],
|
||||
rules: {
|
||||
'no-restricted-imports': ['error', { paths: [XML_PARSER_PATH], patterns: [SERVICES_WALL] }],
|
||||
},
|
||||
},
|
||||
{
|
||||
// The two homes of the XML parser (see XML_PARSER_PATH). Restated without
|
||||
// it, for the same flat-config reason as above: this block's options
|
||||
// replace the previous block's for the files it matches.
|
||||
files: ['src/nest/place-import/**/*.ts', 'src/nest/doc-sync/providers/webdav.client.ts'],
|
||||
rules: {
|
||||
'no-restricted-imports': ['error', { paths: [DRIVER_PATH], patterns: [SERVICES_WALL] }],
|
||||
},
|
||||
},
|
||||
{
|
||||
// D4/D10: a repository is dialect-neutral. It talks to the ORM through
|
||||
// @mikro-orm/core and @mikro-orm/sql — never to a concrete driver package,
|
||||
// never to better-sqlite3 (the driver is wired once, in src/db/orm-driver.ts)
|
||||
// — and it never spells raw SQL inline: every database function goes through
|
||||
// src/db/dialect/sql-functions.ts, which dispatches on the live platform.
|
||||
//
|
||||
// Both rules restate the blocks above for the same flat-config reason: the
|
||||
// last matching config object's options REPLACE, not extend, the earlier
|
||||
// ones, so dropping either restatement would open a hole under
|
||||
// src/db/repositories/ only.
|
||||
files: ['src/db/repositories/**/*.ts'],
|
||||
rules: {
|
||||
// Written as a deny list rather than an allow list on purpose: these patterns
|
||||
// are gitignore-style, and a leading '**' would exclude the parent directory of
|
||||
// every allowed path, which makes the '!' re-includes silently ineffective.
|
||||
'no-restricted-imports': [
|
||||
'error',
|
||||
{
|
||||
paths: [
|
||||
{
|
||||
name: '@mikro-orm/sqlite',
|
||||
message:
|
||||
'Repositories are dialect-neutral: import from @mikro-orm/sql / @mikro-orm/core. The driver lives in src/db/orm-driver.ts.',
|
||||
},
|
||||
{
|
||||
name: '@mikro-orm/postgresql',
|
||||
message:
|
||||
'Repositories are dialect-neutral: import from @mikro-orm/sql / @mikro-orm/core. The driver lives in src/db/orm-driver.ts.',
|
||||
},
|
||||
{
|
||||
name: 'better-sqlite3',
|
||||
message:
|
||||
'Repositories are dialect-neutral: import from @mikro-orm/sql / @mikro-orm/core. The driver lives in src/db/orm-driver.ts.',
|
||||
},
|
||||
XML_PARSER_PATH,
|
||||
],
|
||||
patterns: [
|
||||
{
|
||||
group: [
|
||||
// The host modules next door.
|
||||
'../rpc-host',
|
||||
'../rpc-errors',
|
||||
'../rpc-params',
|
||||
'../rate-limit',
|
||||
'../daily-budget',
|
||||
'../plugin-audit',
|
||||
'../plugin-jobs',
|
||||
'../plugin-guards.service',
|
||||
'../plugin-host-*',
|
||||
// Everything one level up, in plugins/ itself.
|
||||
'../../*.service',
|
||||
'../../*.module',
|
||||
'../../*.controller',
|
||||
'../../dependencies',
|
||||
'../../dev-link',
|
||||
'../../kill-switch',
|
||||
'../../paths',
|
||||
'../../plugin-backup',
|
||||
'../../signature-status',
|
||||
'../../text-sanitize',
|
||||
'../../install/**',
|
||||
'../../registry/**',
|
||||
'../../runtime/**',
|
||||
'../../supervisor/**',
|
||||
// The wire protocol, except the one file the kit validates against.
|
||||
'../../protocol/*',
|
||||
'!../../protocol/envelope',
|
||||
// Anything outside the plugin subtree, and the rest of the app.
|
||||
'../../../**',
|
||||
'@trek/**',
|
||||
'node:*',
|
||||
],
|
||||
group: ['**/services/*', '**/services/**/*'],
|
||||
message:
|
||||
'rpc-kit stays extractable: it may import @nestjs/common, @nestjs/core, its own files, and type-only from ../../protocol/envelope and ../plugin-data.service. See rpc-kit/README.md.',
|
||||
'src/services/ is deleted. New backend code goes to src/nest/<domain>/ (service + controller + module, registered in app.module.ts). See src/nest/README.md.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
...ENV_SELECTORS,
|
||||
...RAW_SQL_SELECTORS,
|
||||
...FETCH_SELECTORS,
|
||||
...INSERT_ID_SELECTORS,
|
||||
...APP_SETTING_SELECTORS,
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// RAW_SQL_SELECTORS only see `raw()` and the `sql` tag. A SQL string
|
||||
// handed straight to the connection
|
||||
// (`em.getConnection().execute('INSERT OR IGNORE ...')`) is raw SQL all the
|
||||
// same and passed unseen, in the seeders too, which no repository rule
|
||||
// reached. The files below already hold such strings and are named one by
|
||||
// one, so the list can only shrink: MaintenanceRepository is the SQLite
|
||||
// maintenance adapter (PRAGMA, VACUUM INTO), and AdminSeeder and
|
||||
// CategorySeeder still write their rows as SQL text. A new seeder starts on
|
||||
// the query builder.
|
||||
// tests/unit/eslint-rules/restricted-syntax-selectors.test.ts pins how many
|
||||
// SQL strings each of them holds, so new SQL text in an exempt file fails
|
||||
// there, and a file with none left has to leave this list.
|
||||
files: ['src/db/repositories/**/*.ts', 'src/db/seeders/**/*.ts'],
|
||||
ignores: [
|
||||
'src/db/repositories/MaintenanceRepository.ts',
|
||||
'src/db/seeders/AdminSeeder.ts',
|
||||
'src/db/seeders/CategorySeeder.ts',
|
||||
],
|
||||
rules: {
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
...ENV_SELECTORS,
|
||||
...RAW_SQL_SELECTORS,
|
||||
...FETCH_SELECTORS,
|
||||
...STRING_SQL_SELECTORS,
|
||||
...INSERT_ID_SELECTORS,
|
||||
...APP_SETTING_SELECTORS,
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// The plugin RPC decorator kit is written to stay extractable into its own
|
||||
// package, so its dependencies are pinned to Nest plus the two plugin-domain
|
||||
// files it genuinely needs. See src/nest-rpc/rpc-kit/README.md for what an
|
||||
// extraction would cost, and why the envelope import is the deliberate exception.
|
||||
files: ['src/nest-rpc/rpc-kit/**/*.ts'],
|
||||
rules: {
|
||||
'no-restricted-imports': [
|
||||
'error',
|
||||
{
|
||||
// Restated for the flat-config reason above: without them the kit
|
||||
// would drop the driver and XML walls every other src file holds.
|
||||
paths: [DRIVER_PATH, XML_PARSER_PATH],
|
||||
patterns: [
|
||||
{
|
||||
// A regex rather than gitignore-style groups: the two allowed files sit
|
||||
// under directories the rest of the rule excludes, and a gitignore
|
||||
// re-include cannot reach into an excluded directory.
|
||||
regex: String.raw`^\.\./(?!\.\./nest/plugins/protocol/envelope$|\.\./nest/plugins/host/plugin-data\.service$)`,
|
||||
message:
|
||||
'rpc-kit stays extractable: it may import @nestjs/common, @nestjs/core, its own files, and type-only from nest/plugins/protocol/envelope and nest/plugins/host/plugin-data.service. See rpc-kit/README.md.',
|
||||
},
|
||||
{
|
||||
group: ['@trek/**', 'node:*'],
|
||||
message:
|
||||
'rpc-kit stays extractable: it may import @nestjs/common, @nestjs/core, its own files, and type-only from nest/plugins/protocol/envelope and nest/plugins/host/plugin-data.service. See rpc-kit/README.md.',
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
+86
-57
@@ -1,6 +1,9 @@
|
||||
{
|
||||
"name": "@trek/server",
|
||||
"version": "4.3.1",
|
||||
"version": "5.0.0",
|
||||
"engines": {
|
||||
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
|
||||
},
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
"start": "node --require tsconfig-paths/register dist/index.js",
|
||||
@@ -10,11 +13,34 @@
|
||||
"reset-admin": "node reset-admin.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck:tests": "tsc -p tsconfig.tests.json --noEmit",
|
||||
"typecheck:scripts": "tsc -p tsconfig.scripts.json --noEmit",
|
||||
"db:call-graph": "node scripts/db-call-graph.mjs",
|
||||
"lint:size": "node scripts/size-lint.mjs",
|
||||
"lint:warnings": "node scripts/eslint-ratchet.mjs",
|
||||
"lint:format": "node scripts/format-lint.mjs",
|
||||
"lint:strict": "node scripts/strict-lint.mjs",
|
||||
"lint:boundaries": "node scripts/import-boundaries.mjs",
|
||||
"lint:dialect": "node scripts/dialect-lint.mjs",
|
||||
"lint:tx": "node scripts/tx-writes.mjs",
|
||||
"lint:test-sql": "node scripts/test-sql-ratchet.mjs",
|
||||
"lint:test-mocks": "node scripts/test-mocks-ratchet.mjs",
|
||||
"lint:test-new-service": "node scripts/test-new-service-ratchet.mjs",
|
||||
"lint:query-api": "node scripts/query-api-ratchet.mjs",
|
||||
"lint:mcp-zod": "node scripts/mcp-inline-zod.mjs",
|
||||
"lint:service-http": "node scripts/service-http-ratchet.mjs",
|
||||
"lint:response-contracts": "node scripts/response-contract-ratchet.mjs",
|
||||
"contracts:dto-open": "node scripts/dto-open-shapes.mjs",
|
||||
"gen:plugin-facts": "node --import tsx scripts/gen-plugin-facts.ts",
|
||||
"check:plugin-facts": "node --import tsx scripts/gen-plugin-facts.ts --check",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"format:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"gen:entities": "node --import tsx scripts/generate-entities.ts",
|
||||
"check:entities": "node --import tsx scripts/generate-entities.ts --check",
|
||||
"gen:db-types": "node --import tsx scripts/generate-db-types.ts",
|
||||
"check:db-types": "node --import tsx scripts/generate-db-types.ts --check",
|
||||
"probe:pg": "node --import tsx scripts/pg-probe.ts",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"tests/**/*.ts\"",
|
||||
"format:check": "prettier --check \"src/**/*.ts\" \"tests/**/*.ts\"",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"lint:check": "eslint .",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
@@ -24,98 +50,101 @@
|
||||
"test:e2e": "vitest run tests/e2e",
|
||||
"test:coverage": "vitest run --coverage"
|
||||
},
|
||||
"mikro-orm": {
|
||||
"configPaths": [
|
||||
"./src/mikro-orm.config.ts",
|
||||
"./dist/mikro-orm.config.js"
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-lite/client": "^0.23.7",
|
||||
"@aws-lite/s3": "^0.2.7",
|
||||
"@modelcontextprotocol/sdk": "^1.30.0",
|
||||
"@nestjs/common": "^11.1.24",
|
||||
"@mikro-orm/cli": "^7.2.1",
|
||||
"@mikro-orm/core": "^7.2.1",
|
||||
"@mikro-orm/migrations": "^7.2.1",
|
||||
"@mikro-orm/nestjs": "^7.1.0",
|
||||
"@mikro-orm/seeder": "^7.2.1",
|
||||
"@mikro-orm/sql": "^7.2.1",
|
||||
"@mikro-orm/sqlite": "^7.2.1",
|
||||
"@modelcontextprotocol/sdk": "^1.32.1",
|
||||
"@nestjs/common": "^11.2.5",
|
||||
"@nestjs/config": "^4.0.4",
|
||||
"@nestjs/core": "^11.1.24",
|
||||
"@nestjs/platform-express": "^11.1.24",
|
||||
"@nestjs/platform-ws": "^11.1.29",
|
||||
"@nestjs/core": "^11.2.5",
|
||||
"@nestjs/platform-express": "^11.2.5",
|
||||
"@nestjs/platform-ws": "^11.2.5",
|
||||
"@nestjs/schedule": "^6.1.3",
|
||||
"@nestjs/swagger": "^11.4.5",
|
||||
"@nestjs/websockets": "^11.1.29",
|
||||
"@simplewebauthn/server": "^13.3.2",
|
||||
"@nestjs/swagger": "^11.4.7",
|
||||
"@nestjs/websockets": "^11.2.5",
|
||||
"@simplewebauthn/server": "^13.3.3",
|
||||
"@trek/shared": "*",
|
||||
"archiver": "^6.0.1",
|
||||
"archiver": "^6.0.2",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"better-sqlite3": "^13.0.3",
|
||||
"compression": "^1.8.0",
|
||||
"compression": "^1.8.2",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"cors": "^2.8.5",
|
||||
"cors": "^2.8.6",
|
||||
"cron": "^4.4.0",
|
||||
"dotenv": "^16.4.1",
|
||||
"dotenv": "^16.6.1",
|
||||
"exifr": "7.1.3",
|
||||
"express": "^4.18.3",
|
||||
"fast-xml-parser": "^5.5.10",
|
||||
"helmet": "^8.1.0",
|
||||
"express": "^4.22.3",
|
||||
"fast-xml-parser": "^5.11.1",
|
||||
"helmet": "^8.3.0",
|
||||
"jimp": "^1.6.1",
|
||||
"json5": "^2.2.3",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"kysely": "^0.29.6",
|
||||
"multer": "^2.5.0",
|
||||
"nestjs-zod": "^5.5.0",
|
||||
"nodemailer": "^9.1.1",
|
||||
"nodemailer": "^10.1.4",
|
||||
"otplib": "^12.0.1",
|
||||
"pdf-parse": "^2.4.5",
|
||||
"qrcode": "^1.5.4",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2",
|
||||
"semver": "^7.7.4",
|
||||
"semver": "^7.8.5",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.2",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^6.0.3",
|
||||
"tz-lookup": "^6.1.25",
|
||||
"undici": "^7.29.0",
|
||||
"unzipper": "^0.12.3",
|
||||
"uuid": "^14.0.0",
|
||||
"ws": "^8.21.0",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"overrides": {
|
||||
"hono": "^4.12.16",
|
||||
"@hono/node-server": "^1.19.13",
|
||||
"picomatch": "^4.0.4",
|
||||
"ip-address": "^10.1.1",
|
||||
"multer": "^2.3.0",
|
||||
"ws": "^8.21.0",
|
||||
"qs": "^6.15.2",
|
||||
"file-type": "^21.3.4"
|
||||
"undici": "^7.30.1",
|
||||
"unzipper": "^0.12.5",
|
||||
"uuid": "^14.0.2",
|
||||
"ws": "^8.21.3",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@aws-lite/s3-types": "^0.2.8",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@nestjs/testing": "^11.1.24",
|
||||
"@swc/core": "^1.15.40",
|
||||
"@mikro-orm/entity-generator": "^7.2.1",
|
||||
"@mikro-orm/postgresql": "^7.2.1",
|
||||
"@nestjs/testing": "^11.2.5",
|
||||
"@swc/core": "^1.16.2",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||
"@types/archiver": "^7.0.0",
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/compression": "^1.8.0",
|
||||
"@types/compression": "^1.8.1",
|
||||
"@types/cookie-parser": "^1.4.10",
|
||||
"@types/cors": "^2.8.19",
|
||||
"@types/express": "^4.17.25",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/multer": "^2.1.0",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/nodemailer": "^8.0.1",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/semver": "^7.7.1",
|
||||
"@types/multer": "^2.2.0",
|
||||
"@types/node": "^25.9.8",
|
||||
"@types/nodemailer": "^8.0.2",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/semver": "^7.8.0",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"@types/unzipper": "^0.10.11",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@vitest/coverage-istanbul": "^4.1.11",
|
||||
"@vitest/coverage-v8": "^4.1.11",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint-config-flat-gitignore": "^2.3.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"nodemon": "^3.1.0",
|
||||
"prettier": "^3.8.3",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-flat-gitignore": "^2.4.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"prettier": "^3.9.8",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"supertest": "^7.2.2",
|
||||
"typescript-eslint": "^8.58.2",
|
||||
"unplugin-swc": "^1.5.9",
|
||||
"typescript-eslint": "^8.70.0",
|
||||
"unplugin-swc": "^1.6.0",
|
||||
"vitest": "^4.1.11"
|
||||
}
|
||||
}
|
||||
|
||||
+19
-3
@@ -50,15 +50,31 @@ const db = new Database(dbPath);
|
||||
// journal mode below waits for a busy server instead of failing on the spot.
|
||||
// Five seconds, same as src/db/database.ts.
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
// Temp files in memory, like every connection src/db/connection.ts opens: a
|
||||
// container with a read-only root and no tmpfs on /tmp has nowhere to put them
|
||||
// (#2518).
|
||||
db.exec('PRAGMA temp_store = MEMORY');
|
||||
db.exec(`PRAGMA journal_mode = ${journalMode}`);
|
||||
db.exec(`PRAGMA synchronous = ${synchronous}`);
|
||||
|
||||
const hash = bcrypt.hashSync(password, BCRYPT_COST);
|
||||
const existing = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
|
||||
// Case-insensitive like login, so Admin@example.com is found as admin@example.com.
|
||||
const existing = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?)').get(email);
|
||||
|
||||
if (existing) {
|
||||
db.prepare('UPDATE users SET password_hash = ?, role = ?, must_change_password = 1 WHERE email = ?')
|
||||
.run(hash, 'admin', email);
|
||||
// password_version moves on, as on every password change in the app: it is
|
||||
// what ends the sessions still signed in to an account that needed resetting.
|
||||
db.prepare('UPDATE users SET password_hash = ?, role = ?, must_change_password = 1, password_version = COALESCE(password_version, 0) + 1 WHERE id = ?')
|
||||
.run(hash, 'admin', existing.id);
|
||||
// Its sessions end too, so the account's session list shows none of them
|
||||
// as live. The table is missing on a database that no server tracking
|
||||
// sessions has booted yet; the password_version bump above already refuses
|
||||
// every token there.
|
||||
const sessionsTable = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'user_sessions'").get();
|
||||
if (sessionsTable) {
|
||||
db.prepare('UPDATE user_sessions SET revoked_at = CURRENT_TIMESTAMP WHERE user_id = ? AND revoked_at IS NULL')
|
||||
.run(existing.id);
|
||||
}
|
||||
console.log(`\n✓ Admin password reset: ${email}`);
|
||||
} else {
|
||||
// 'admin' is usually taken by the first-run seed — pick the first free username
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Fixture for `db-call-graph.mjs --sync --tx --root scripts/__fixtures__`: one class that
|
||||
* still touches the database synchronously and opens a raw transaction, so the two gates
|
||||
* CI runs (`--sync`, `--tx`) each have a known-bad case to report. `unawaited-sample.ts`
|
||||
* beside it is clean under both flags.
|
||||
*/
|
||||
|
||||
interface RawDb {
|
||||
get(sql: string, ...args: unknown[]): unknown;
|
||||
transaction<T>(fn: () => T): T;
|
||||
}
|
||||
|
||||
export class SyncSample {
|
||||
private db: RawDb = { get: () => undefined, transaction: (fn) => fn() };
|
||||
|
||||
readSync(id: number): unknown {
|
||||
return this.db.get('SELECT 1 WHERE id = ?', id); // sync DB-touching method
|
||||
}
|
||||
|
||||
writeInTx(): void {
|
||||
this.db.transaction(() => undefined); // raw transaction site
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Fixture for `db-call-graph.mjs --unawaited --root scripts/__fixtures__`. Not part of the
|
||||
* server build or its typecheck — it exists only so the detector has something small and
|
||||
* known-good/known-bad to run against. Three GOOD call shapes should produce no findings;
|
||||
* five BAD ones should each produce exactly one, with a distinct reason tag.
|
||||
*/
|
||||
|
||||
class Dep {
|
||||
async fetchValue(): Promise<number> {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
export class Sample {
|
||||
private dep: Dep = new Dep();
|
||||
|
||||
async loadOne(): Promise<number> {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- GOOD (3): correctly consumed, nothing to report ----
|
||||
|
||||
async good1() {
|
||||
return await this.loadOne(); // awaited
|
||||
}
|
||||
|
||||
async good2() {
|
||||
return this.loadOne(); // returned directly — propagates the promise to the caller
|
||||
}
|
||||
|
||||
async good3() {
|
||||
await Promise.all([this.loadOne(), this.dep.fetchValue()]); // Promise.all combinator
|
||||
}
|
||||
|
||||
// ---- BAD (5): used without await, one per reason tag ----
|
||||
|
||||
async bad1() {
|
||||
const x = this.loadOne(); // stored-then-used
|
||||
return { x };
|
||||
}
|
||||
|
||||
async bad2() {
|
||||
console.log(this.dep.fetchValue()); // argument
|
||||
}
|
||||
|
||||
async bad3() {
|
||||
return { value: this.loadOne() }; // property
|
||||
}
|
||||
|
||||
async bad4() {
|
||||
if (this.loadOne()) {
|
||||
return 1;
|
||||
}
|
||||
return 0; // condition
|
||||
}
|
||||
|
||||
async bad5() {
|
||||
this.loadOne(); // statement — result discarded
|
||||
}
|
||||
}
|
||||
+402
-137
@@ -13,21 +13,20 @@
|
||||
// FeatureCollections that the server serves at runtime (no network at boot).
|
||||
//
|
||||
// geoBoundaries: CC BY 4.0 — https://www.geoboundaries.org/ (attribution required).
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import zlib from 'node:zlib';
|
||||
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import zlib from 'node:zlib'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const OUT_DIR = path.join(__dirname, '..', 'assets', 'atlas')
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const OUT_DIR = path.join(__dirname, '..', 'assets', 'atlas');
|
||||
|
||||
// Pinned geoBoundaries revision (override with GB_REF=<sha|branch|tag>). The LFS media
|
||||
// endpoint resolves a commit SHA, branch, or tag in the <ref> path segment.
|
||||
const GB_REF = process.env.GB_REF || '5c25134028196d43ce97b5071934fd0cfc92f09f'
|
||||
const GB_REF = process.env.GB_REF || '5c25134028196d43ce97b5071934fd0cfc92f09f';
|
||||
const MEDIA = (a3, level) =>
|
||||
`https://media.githubusercontent.com/media/wmgeolab/geoBoundaries/${GB_REF}` +
|
||||
`/releaseData/gbOpen/${a3}/${level}/geoBoundaries-${a3}-${level}_simplified.geojson`
|
||||
`/releaseData/gbOpen/${a3}/${level}/geoBoundaries-${a3}-${level}_simplified.geojson`;
|
||||
|
||||
// Country borders come from CGAZ (the Comprehensive Global Administrative Zones composite)
|
||||
// rather than per-country gbOpen ADM0: CGAZ is gap-filled, so it includes territories
|
||||
@@ -36,10 +35,10 @@ const MEDIA = (a3, level) =>
|
||||
// irrelevant. (gbOpen ADM0 maxes Norway at 71°N and has no Svalbard at all.)
|
||||
const CGAZ_ADM0 =
|
||||
`https://media.githubusercontent.com/media/wmgeolab/geoBoundaries/${GB_REF}` +
|
||||
`/releaseData/CGAZ/geoBoundariesCGAZ_ADM0.geojson`
|
||||
`/releaseData/CGAZ/geoBoundariesCGAZ_ADM0.geojson`;
|
||||
|
||||
const CONCURRENCY = 8
|
||||
const RETRIES = 3
|
||||
const CONCURRENCY = 8;
|
||||
const RETRIES = 3;
|
||||
|
||||
// Complete ISO-3166-1 alpha-3 → alpha-2 map (source: lukes/ISO-3166-Countries-with-
|
||||
// Regional-Codes, plus user-assigned XKX/XK for Kosovo, which geoBoundaries ships but
|
||||
@@ -47,7 +46,258 @@ const RETRIES = 3
|
||||
// code; missing ones 404 and are skipped) and stamps `iso_a2`/`ISO_A2` (geoBoundaries
|
||||
// keys by alpha-3 `shapeGroup`). A complete map — not the client's curated ~180 — is
|
||||
// what restores the dropped territories (Greenland, Falklands, French Guiana, …).
|
||||
const A3_TO_A2 = {"ABW":"AW", "AFG":"AF", "AGO":"AO", "AIA":"AI", "ALA":"AX", "ALB":"AL", "AND":"AD", "ARE":"AE", "ARG":"AR", "ARM":"AM", "ASM":"AS", "ATA":"AQ", "ATF":"TF", "ATG":"AG", "AUS":"AU", "AUT":"AT", "AZE":"AZ", "BDI":"BI", "BEL":"BE", "BEN":"BJ", "BES":"BQ", "BFA":"BF", "BGD":"BD", "BGR":"BG", "BHR":"BH", "BHS":"BS", "BIH":"BA", "BLM":"BL", "BLR":"BY", "BLZ":"BZ", "BMU":"BM", "BOL":"BO", "BRA":"BR", "BRB":"BB", "BRN":"BN", "BTN":"BT", "BVT":"BV", "BWA":"BW", "CAF":"CF", "CAN":"CA", "CCK":"CC", "CHE":"CH", "CHL":"CL", "CHN":"CN", "CIV":"CI", "CMR":"CM", "COD":"CD", "COG":"CG", "COK":"CK", "COL":"CO", "COM":"KM", "CPV":"CV", "CRI":"CR", "CUB":"CU", "CUW":"CW", "CXR":"CX", "CYM":"KY", "CYP":"CY", "CZE":"CZ", "DEU":"DE", "DJI":"DJ", "DMA":"DM", "DNK":"DK", "DOM":"DO", "DZA":"DZ", "ECU":"EC", "EGY":"EG", "ERI":"ER", "ESH":"EH", "ESP":"ES", "EST":"EE", "ETH":"ET", "FIN":"FI", "FJI":"FJ", "FLK":"FK", "FRA":"FR", "FRO":"FO", "FSM":"FM", "GAB":"GA", "GBR":"GB", "GEO":"GE", "GGY":"GG", "GHA":"GH", "GIB":"GI", "GIN":"GN", "GLP":"GP", "GMB":"GM", "GNB":"GW", "GNQ":"GQ", "GRC":"GR", "GRD":"GD", "GRL":"GL", "GTM":"GT", "GUF":"GF", "GUM":"GU", "GUY":"GY", "HKG":"HK", "HMD":"HM", "HND":"HN", "HRV":"HR", "HTI":"HT", "HUN":"HU", "IDN":"ID", "IMN":"IM", "IND":"IN", "IOT":"IO", "IRL":"IE", "IRN":"IR", "IRQ":"IQ", "ISL":"IS", "ISR":"IL", "ITA":"IT", "JAM":"JM", "JEY":"JE", "JOR":"JO", "JPN":"JP", "KAZ":"KZ", "KEN":"KE", "KGZ":"KG", "KHM":"KH", "KIR":"KI", "KNA":"KN", "KOR":"KR", "KWT":"KW", "LAO":"LA", "LBN":"LB", "LBR":"LR", "LBY":"LY", "LCA":"LC", "LIE":"LI", "LKA":"LK", "LSO":"LS", "LTU":"LT", "LUX":"LU", "LVA":"LV", "MAC":"MO", "MAF":"MF", "MAR":"MA", "MCO":"MC", "MDA":"MD", "MDG":"MG", "MDV":"MV", "MEX":"MX", "MHL":"MH", "MKD":"MK", "MLI":"ML", "MLT":"MT", "MMR":"MM", "MNE":"ME", "MNG":"MN", "MNP":"MP", "MOZ":"MZ", "MRT":"MR", "MSR":"MS", "MTQ":"MQ", "MUS":"MU", "MWI":"MW", "MYS":"MY", "MYT":"YT", "NAM":"NA", "NCL":"NC", "NER":"NE", "NFK":"NF", "NGA":"NG", "NIC":"NI", "NIU":"NU", "NLD":"NL", "NOR":"NO", "NPL":"NP", "NRU":"NR", "NZL":"NZ", "OMN":"OM", "PAK":"PK", "PAN":"PA", "PCN":"PN", "PER":"PE", "PHL":"PH", "PLW":"PW", "PNG":"PG", "POL":"PL", "PRI":"PR", "PRK":"KP", "PRT":"PT", "PRY":"PY", "PSE":"PS", "PYF":"PF", "QAT":"QA", "REU":"RE", "ROU":"RO", "RUS":"RU", "RWA":"RW", "SAU":"SA", "SDN":"SD", "SEN":"SN", "SGP":"SG", "SGS":"GS", "SHN":"SH", "SJM":"SJ", "SLB":"SB", "SLE":"SL", "SLV":"SV", "SMR":"SM", "SOM":"SO", "SPM":"PM", "SRB":"RS", "SSD":"SS", "STP":"ST", "SUR":"SR", "SVK":"SK", "SVN":"SI", "SWE":"SE", "SWZ":"SZ", "SXM":"SX", "SYC":"SC", "SYR":"SY", "TCA":"TC", "TCD":"TD", "TGO":"TG", "THA":"TH", "TJK":"TJ", "TKL":"TK", "TKM":"TM", "TLS":"TL", "TON":"TO", "TTO":"TT", "TUN":"TN", "TUR":"TR", "TUV":"TV", "TWN":"TW", "TZA":"TZ", "UGA":"UG", "UKR":"UA", "UMI":"UM", "URY":"UY", "USA":"US", "UZB":"UZ", "VAT":"VA", "VCT":"VC", "VEN":"VE", "VGB":"VG", "VIR":"VI", "VNM":"VN", "VUT":"VU", "WLF":"WF", "WSM":"WS", "XKX":"XK", "YEM":"YE", "ZAF":"ZA", "ZMB":"ZM", "ZWE":"ZW"}
|
||||
const A3_TO_A2 = {
|
||||
ABW: 'AW',
|
||||
AFG: 'AF',
|
||||
AGO: 'AO',
|
||||
AIA: 'AI',
|
||||
ALA: 'AX',
|
||||
ALB: 'AL',
|
||||
AND: 'AD',
|
||||
ARE: 'AE',
|
||||
ARG: 'AR',
|
||||
ARM: 'AM',
|
||||
ASM: 'AS',
|
||||
ATA: 'AQ',
|
||||
ATF: 'TF',
|
||||
ATG: 'AG',
|
||||
AUS: 'AU',
|
||||
AUT: 'AT',
|
||||
AZE: 'AZ',
|
||||
BDI: 'BI',
|
||||
BEL: 'BE',
|
||||
BEN: 'BJ',
|
||||
BES: 'BQ',
|
||||
BFA: 'BF',
|
||||
BGD: 'BD',
|
||||
BGR: 'BG',
|
||||
BHR: 'BH',
|
||||
BHS: 'BS',
|
||||
BIH: 'BA',
|
||||
BLM: 'BL',
|
||||
BLR: 'BY',
|
||||
BLZ: 'BZ',
|
||||
BMU: 'BM',
|
||||
BOL: 'BO',
|
||||
BRA: 'BR',
|
||||
BRB: 'BB',
|
||||
BRN: 'BN',
|
||||
BTN: 'BT',
|
||||
BVT: 'BV',
|
||||
BWA: 'BW',
|
||||
CAF: 'CF',
|
||||
CAN: 'CA',
|
||||
CCK: 'CC',
|
||||
CHE: 'CH',
|
||||
CHL: 'CL',
|
||||
CHN: 'CN',
|
||||
CIV: 'CI',
|
||||
CMR: 'CM',
|
||||
COD: 'CD',
|
||||
COG: 'CG',
|
||||
COK: 'CK',
|
||||
COL: 'CO',
|
||||
COM: 'KM',
|
||||
CPV: 'CV',
|
||||
CRI: 'CR',
|
||||
CUB: 'CU',
|
||||
CUW: 'CW',
|
||||
CXR: 'CX',
|
||||
CYM: 'KY',
|
||||
CYP: 'CY',
|
||||
CZE: 'CZ',
|
||||
DEU: 'DE',
|
||||
DJI: 'DJ',
|
||||
DMA: 'DM',
|
||||
DNK: 'DK',
|
||||
DOM: 'DO',
|
||||
DZA: 'DZ',
|
||||
ECU: 'EC',
|
||||
EGY: 'EG',
|
||||
ERI: 'ER',
|
||||
ESH: 'EH',
|
||||
ESP: 'ES',
|
||||
EST: 'EE',
|
||||
ETH: 'ET',
|
||||
FIN: 'FI',
|
||||
FJI: 'FJ',
|
||||
FLK: 'FK',
|
||||
FRA: 'FR',
|
||||
FRO: 'FO',
|
||||
FSM: 'FM',
|
||||
GAB: 'GA',
|
||||
GBR: 'GB',
|
||||
GEO: 'GE',
|
||||
GGY: 'GG',
|
||||
GHA: 'GH',
|
||||
GIB: 'GI',
|
||||
GIN: 'GN',
|
||||
GLP: 'GP',
|
||||
GMB: 'GM',
|
||||
GNB: 'GW',
|
||||
GNQ: 'GQ',
|
||||
GRC: 'GR',
|
||||
GRD: 'GD',
|
||||
GRL: 'GL',
|
||||
GTM: 'GT',
|
||||
GUF: 'GF',
|
||||
GUM: 'GU',
|
||||
GUY: 'GY',
|
||||
HKG: 'HK',
|
||||
HMD: 'HM',
|
||||
HND: 'HN',
|
||||
HRV: 'HR',
|
||||
HTI: 'HT',
|
||||
HUN: 'HU',
|
||||
IDN: 'ID',
|
||||
IMN: 'IM',
|
||||
IND: 'IN',
|
||||
IOT: 'IO',
|
||||
IRL: 'IE',
|
||||
IRN: 'IR',
|
||||
IRQ: 'IQ',
|
||||
ISL: 'IS',
|
||||
ISR: 'IL',
|
||||
ITA: 'IT',
|
||||
JAM: 'JM',
|
||||
JEY: 'JE',
|
||||
JOR: 'JO',
|
||||
JPN: 'JP',
|
||||
KAZ: 'KZ',
|
||||
KEN: 'KE',
|
||||
KGZ: 'KG',
|
||||
KHM: 'KH',
|
||||
KIR: 'KI',
|
||||
KNA: 'KN',
|
||||
KOR: 'KR',
|
||||
KWT: 'KW',
|
||||
LAO: 'LA',
|
||||
LBN: 'LB',
|
||||
LBR: 'LR',
|
||||
LBY: 'LY',
|
||||
LCA: 'LC',
|
||||
LIE: 'LI',
|
||||
LKA: 'LK',
|
||||
LSO: 'LS',
|
||||
LTU: 'LT',
|
||||
LUX: 'LU',
|
||||
LVA: 'LV',
|
||||
MAC: 'MO',
|
||||
MAF: 'MF',
|
||||
MAR: 'MA',
|
||||
MCO: 'MC',
|
||||
MDA: 'MD',
|
||||
MDG: 'MG',
|
||||
MDV: 'MV',
|
||||
MEX: 'MX',
|
||||
MHL: 'MH',
|
||||
MKD: 'MK',
|
||||
MLI: 'ML',
|
||||
MLT: 'MT',
|
||||
MMR: 'MM',
|
||||
MNE: 'ME',
|
||||
MNG: 'MN',
|
||||
MNP: 'MP',
|
||||
MOZ: 'MZ',
|
||||
MRT: 'MR',
|
||||
MSR: 'MS',
|
||||
MTQ: 'MQ',
|
||||
MUS: 'MU',
|
||||
MWI: 'MW',
|
||||
MYS: 'MY',
|
||||
MYT: 'YT',
|
||||
NAM: 'NA',
|
||||
NCL: 'NC',
|
||||
NER: 'NE',
|
||||
NFK: 'NF',
|
||||
NGA: 'NG',
|
||||
NIC: 'NI',
|
||||
NIU: 'NU',
|
||||
NLD: 'NL',
|
||||
NOR: 'NO',
|
||||
NPL: 'NP',
|
||||
NRU: 'NR',
|
||||
NZL: 'NZ',
|
||||
OMN: 'OM',
|
||||
PAK: 'PK',
|
||||
PAN: 'PA',
|
||||
PCN: 'PN',
|
||||
PER: 'PE',
|
||||
PHL: 'PH',
|
||||
PLW: 'PW',
|
||||
PNG: 'PG',
|
||||
POL: 'PL',
|
||||
PRI: 'PR',
|
||||
PRK: 'KP',
|
||||
PRT: 'PT',
|
||||
PRY: 'PY',
|
||||
PSE: 'PS',
|
||||
PYF: 'PF',
|
||||
QAT: 'QA',
|
||||
REU: 'RE',
|
||||
ROU: 'RO',
|
||||
RUS: 'RU',
|
||||
RWA: 'RW',
|
||||
SAU: 'SA',
|
||||
SDN: 'SD',
|
||||
SEN: 'SN',
|
||||
SGP: 'SG',
|
||||
SGS: 'GS',
|
||||
SHN: 'SH',
|
||||
SJM: 'SJ',
|
||||
SLB: 'SB',
|
||||
SLE: 'SL',
|
||||
SLV: 'SV',
|
||||
SMR: 'SM',
|
||||
SOM: 'SO',
|
||||
SPM: 'PM',
|
||||
SRB: 'RS',
|
||||
SSD: 'SS',
|
||||
STP: 'ST',
|
||||
SUR: 'SR',
|
||||
SVK: 'SK',
|
||||
SVN: 'SI',
|
||||
SWE: 'SE',
|
||||
SWZ: 'SZ',
|
||||
SXM: 'SX',
|
||||
SYC: 'SC',
|
||||
SYR: 'SY',
|
||||
TCA: 'TC',
|
||||
TCD: 'TD',
|
||||
TGO: 'TG',
|
||||
THA: 'TH',
|
||||
TJK: 'TJ',
|
||||
TKL: 'TK',
|
||||
TKM: 'TM',
|
||||
TLS: 'TL',
|
||||
TON: 'TO',
|
||||
TTO: 'TT',
|
||||
TUN: 'TN',
|
||||
TUR: 'TR',
|
||||
TUV: 'TV',
|
||||
TWN: 'TW',
|
||||
TZA: 'TZ',
|
||||
UGA: 'UG',
|
||||
UKR: 'UA',
|
||||
UMI: 'UM',
|
||||
URY: 'UY',
|
||||
USA: 'US',
|
||||
UZB: 'UZ',
|
||||
VAT: 'VA',
|
||||
VCT: 'VC',
|
||||
VEN: 'VE',
|
||||
VGB: 'VG',
|
||||
VIR: 'VI',
|
||||
VNM: 'VN',
|
||||
VUT: 'VU',
|
||||
WLF: 'WF',
|
||||
WSM: 'WS',
|
||||
XKX: 'XK',
|
||||
YEM: 'YE',
|
||||
ZAF: 'ZA',
|
||||
ZMB: 'ZM',
|
||||
ZWE: 'ZW',
|
||||
};
|
||||
|
||||
/**
|
||||
* Countries whose sub-national level is not the one everybody else's ADM1 is.
|
||||
@@ -63,52 +313,55 @@ const A3_TO_A2 = {"ABW":"AW", "AFG":"AF", "AGO":"AO", "AIA":"AI", "ALA":"AX", "A
|
||||
* bundle several times over for no gain: for most countries ADM1 already is the
|
||||
* level people think in.
|
||||
*/
|
||||
const ADM_LEVEL = { GBR: 'ADM2' }
|
||||
const ADM_LEVEL = { GBR: 'ADM2' };
|
||||
|
||||
const COUNTRIES = Object.keys(A3_TO_A2) // every ISO alpha-3 code (ADM1 fetch list)
|
||||
const COUNTRIES = Object.keys(A3_TO_A2); // every ISO alpha-3 code (ADM1 fetch list)
|
||||
|
||||
// Cache raw downloads so re-runs (e.g. to tune simplification) don't re-fetch ~360 files.
|
||||
const CACHE_DIR = path.join(__dirname, '..', '.atlas-geo-cache', GB_REF)
|
||||
const CACHE_DIR = path.join(__dirname, '..', '.atlas-geo-cache', GB_REF);
|
||||
|
||||
async function fetchGeo(url) {
|
||||
const cacheFile = path.join(CACHE_DIR, url.split('/').slice(-1)[0])
|
||||
const cacheFile = path.join(CACHE_DIR, url.split('/').slice(-1)[0]);
|
||||
if (fs.existsSync(cacheFile)) {
|
||||
const cached = fs.readFileSync(cacheFile, 'utf8')
|
||||
return cached === '' ? null : JSON.parse(cached)
|
||||
const cached = fs.readFileSync(cacheFile, 'utf8');
|
||||
return cached === '' ? null : JSON.parse(cached);
|
||||
}
|
||||
for (let attempt = 1; attempt <= RETRIES; attempt++) {
|
||||
try {
|
||||
const res = await fetch(url, { headers: { 'User-Agent': 'TREK atlas builder' } })
|
||||
if (res.status === 404) { fs.writeFileSync(cacheFile, ''); return null } // no file — skip
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
const text = await res.text()
|
||||
if (text.startsWith('version https://git-lfs')) throw new Error('got LFS pointer, not content')
|
||||
const parsed = JSON.parse(text)
|
||||
fs.writeFileSync(cacheFile, text)
|
||||
return parsed
|
||||
const res = await fetch(url, { headers: { 'User-Agent': 'TREK atlas builder' } });
|
||||
if (res.status === 404) {
|
||||
fs.writeFileSync(cacheFile, '');
|
||||
return null;
|
||||
} // no file — skip
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const text = await res.text();
|
||||
if (text.startsWith('version https://git-lfs')) throw new Error('got LFS pointer, not content');
|
||||
const parsed = JSON.parse(text);
|
||||
fs.writeFileSync(cacheFile, text);
|
||||
return parsed;
|
||||
} catch (err) {
|
||||
if (attempt === RETRIES) {
|
||||
console.warn(` ! ${url.split('/').slice(-1)[0]}: ${err.message}`)
|
||||
return null
|
||||
console.warn(` ! ${url.split('/').slice(-1)[0]}: ${err.message}`);
|
||||
return null;
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 500 * attempt))
|
||||
await new Promise((r) => setTimeout(r, 500 * attempt));
|
||||
}
|
||||
}
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
// Run async tasks with a fixed concurrency cap.
|
||||
async function pool(items, worker) {
|
||||
const results = []
|
||||
let i = 0
|
||||
const results = [];
|
||||
let i = 0;
|
||||
const runners = Array.from({ length: CONCURRENCY }, async () => {
|
||||
while (i < items.length) {
|
||||
const idx = i++
|
||||
results[idx] = await worker(items[idx], idx)
|
||||
const idx = i++;
|
||||
results[idx] = await worker(items[idx], idx);
|
||||
}
|
||||
})
|
||||
await Promise.all(runners)
|
||||
return results
|
||||
});
|
||||
await Promise.all(runners);
|
||||
return results;
|
||||
}
|
||||
|
||||
// Geometry size control. geoBoundaries' "_simplified" files still carry ~12-decimal
|
||||
@@ -117,149 +370,161 @@ async function pool(items, worker) {
|
||||
// the now-redundant consecutive duplicate points shrinks the bundles ~5-8x with no
|
||||
// visible effect at the atlas' zoom range (3-10). ADM0 fills are viewed zoomed out, so
|
||||
// they tolerate a coarser grid than ADM1 region borders.
|
||||
const ADM0_DECIMALS = 2 // ~1.1 km
|
||||
const ADM1_DECIMALS = 3 // ~110 m
|
||||
const ADM0_DECIMALS = 2; // ~1.1 km
|
||||
const ADM1_DECIMALS = 3; // ~110 m
|
||||
|
||||
function quantizeRing(ring, decimals) {
|
||||
const m = 10 ** decimals
|
||||
const out = []
|
||||
let prevX, prevY
|
||||
const m = 10 ** decimals;
|
||||
const out = [];
|
||||
let prevX, prevY;
|
||||
for (const pt of ring) {
|
||||
const x = Math.round(pt[0] * m) / m
|
||||
const y = Math.round(pt[1] * m) / m
|
||||
if (x === prevX && y === prevY) continue
|
||||
out.push([x, y])
|
||||
prevX = x; prevY = y
|
||||
const x = Math.round(pt[0] * m) / m;
|
||||
const y = Math.round(pt[1] * m) / m;
|
||||
if (x === prevX && y === prevY) continue;
|
||||
out.push([x, y]);
|
||||
prevX = x;
|
||||
prevY = y;
|
||||
}
|
||||
return out
|
||||
return out;
|
||||
}
|
||||
|
||||
// Quantize a (Multi)Polygon, dropping rings that collapse below a valid ring (<4 pts).
|
||||
function quantizeGeometry(geom, decimals) {
|
||||
if (!geom) return null
|
||||
if (!geom) return null;
|
||||
if (geom.type === 'Polygon') {
|
||||
const rings = geom.coordinates.map(r => quantizeRing(r, decimals)).filter(r => r.length >= 4)
|
||||
return rings.length ? { type: 'Polygon', coordinates: rings } : null
|
||||
const rings = geom.coordinates.map((r) => quantizeRing(r, decimals)).filter((r) => r.length >= 4);
|
||||
return rings.length ? { type: 'Polygon', coordinates: rings } : null;
|
||||
}
|
||||
if (geom.type === 'MultiPolygon') {
|
||||
const polys = geom.coordinates
|
||||
.map(poly => poly.map(r => quantizeRing(r, decimals)).filter(r => r.length >= 4))
|
||||
.filter(poly => poly.length)
|
||||
return polys.length ? { type: 'MultiPolygon', coordinates: polys } : null
|
||||
.map((poly) => poly.map((r) => quantizeRing(r, decimals)).filter((r) => r.length >= 4))
|
||||
.filter((poly) => poly.length);
|
||||
return polys.length ? { type: 'MultiPolygon', coordinates: polys } : null;
|
||||
}
|
||||
return geom
|
||||
return geom;
|
||||
}
|
||||
|
||||
// Normalize one CGAZ ADM0 feature (keyed by alpha-3 `shapeGroup`) to the property names
|
||||
// the client country layer reads (ISO_A2/ADM0_A3/NAME/ADMIN). Returns null for the CRS
|
||||
// pseudo-entry or anything without a group/geometry.
|
||||
function normalizeAdm0Feature(f) {
|
||||
const a3 = f.properties?.shapeGroup
|
||||
if (!a3) return null
|
||||
const name = f.properties?.shapeName || a3
|
||||
const geometry = quantizeGeometry(f.geometry, ADM0_DECIMALS)
|
||||
if (!geometry) return null
|
||||
const a3 = f.properties?.shapeGroup;
|
||||
if (!a3) return null;
|
||||
const name = f.properties?.shapeName || a3;
|
||||
const geometry = quantizeGeometry(f.geometry, ADM0_DECIMALS);
|
||||
if (!geometry) return null;
|
||||
return {
|
||||
type: 'Feature',
|
||||
properties: { ISO_A2: A3_TO_A2[a3] || null, ADM0_A3: a3, NAME: name, ADMIN: name },
|
||||
geometry,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeAdm1(geo, a3, countryName) {
|
||||
if (!geo?.features) return []
|
||||
const a2 = A3_TO_A2[a3] || null
|
||||
if (!geo?.features) return [];
|
||||
const a2 = A3_TO_A2[a3] || null;
|
||||
// Ensure every region in a country ends up with a distinct iso_3166_2 — the Atlas
|
||||
// marks/unmarks regions by this code, so duplicates make one mark light up the whole
|
||||
// country.
|
||||
const used = new Set()
|
||||
const used = new Set();
|
||||
const uniq = (base) => {
|
||||
let code = base, n = 2
|
||||
while (used.has(code)) code = `${base}-${n++}`
|
||||
used.add(code)
|
||||
return code
|
||||
}
|
||||
return geo.features.map(f => {
|
||||
let name = f.properties?.shapeName || ''
|
||||
// geoBoundaries erroneously names Guangdong Province as "Guangzhou Province" (Guangzhou is the capital city).
|
||||
if (a3 === 'CHN' && name === 'Guangzhou Province') {
|
||||
name = 'Guangdong Province'
|
||||
}
|
||||
const geometry = quantizeGeometry(f.geometry, ADM1_DECIMALS)
|
||||
if (!geometry) return null
|
||||
// shapeISO is a real ISO 3166-2 code for most features, but geoBoundaries sometimes
|
||||
// fills it with the bare country code instead of a subdivision code — e.g. every
|
||||
// Spanish region gets "ESP", every Chinese "CHN" (also CL/OM). Keep it only when it
|
||||
// is a real `XX-…` subdivision code and not already taken; otherwise synthesize a
|
||||
// stable, unique-per-country id from the region name so each region is independently
|
||||
// markable.
|
||||
const raw = f.properties?.shapeISO || ''
|
||||
let code
|
||||
if (/^[A-Za-z]{2}-[A-Za-z0-9]+$/.test(raw) && !used.has(raw)) {
|
||||
code = raw
|
||||
used.add(code)
|
||||
} else if (a2) {
|
||||
code = uniq(`${a2}-${name.replace(/[^A-Za-z0-9]/g, '').toUpperCase() || 'RGN'}`)
|
||||
} else {
|
||||
code = raw
|
||||
}
|
||||
return {
|
||||
type: 'Feature',
|
||||
// Property names the Atlas region layer + server getRegionGeo already read.
|
||||
properties: {
|
||||
iso_a2: a2,
|
||||
iso_3166_2: code,
|
||||
name,
|
||||
name_en: name,
|
||||
admin: countryName,
|
||||
},
|
||||
geometry,
|
||||
}
|
||||
}).filter(Boolean)
|
||||
let code = base,
|
||||
n = 2;
|
||||
while (used.has(code)) code = `${base}-${n++}`;
|
||||
used.add(code);
|
||||
return code;
|
||||
};
|
||||
return geo.features
|
||||
.map((f) => {
|
||||
let name = f.properties?.shapeName || '';
|
||||
// geoBoundaries erroneously names Guangdong Province as "Guangzhou Province" (Guangzhou is the capital city).
|
||||
if (a3 === 'CHN' && name === 'Guangzhou Province') {
|
||||
name = 'Guangdong Province';
|
||||
}
|
||||
const geometry = quantizeGeometry(f.geometry, ADM1_DECIMALS);
|
||||
if (!geometry) return null;
|
||||
// shapeISO is a real ISO 3166-2 code for most features, but geoBoundaries sometimes
|
||||
// fills it with the bare country code instead of a subdivision code — e.g. every
|
||||
// Spanish region gets "ESP", every Chinese "CHN" (also CL/OM). Keep it only when it
|
||||
// is a real `XX-…` subdivision code and not already taken; otherwise synthesize a
|
||||
// stable, unique-per-country id from the region name so each region is independently
|
||||
// markable.
|
||||
const raw = f.properties?.shapeISO || '';
|
||||
let code;
|
||||
if (/^[A-Za-z]{2}-[A-Za-z0-9]+$/.test(raw) && !used.has(raw)) {
|
||||
code = raw;
|
||||
used.add(code);
|
||||
} else if (a2) {
|
||||
code = uniq(`${a2}-${name.replace(/[^A-Za-z0-9]/g, '').toUpperCase() || 'RGN'}`);
|
||||
} else {
|
||||
code = raw;
|
||||
}
|
||||
return {
|
||||
type: 'Feature',
|
||||
// Property names the Atlas region layer + server getRegionGeo already read.
|
||||
properties: {
|
||||
iso_a2: a2,
|
||||
iso_3166_2: code,
|
||||
name,
|
||||
name_en: name,
|
||||
admin: countryName,
|
||||
},
|
||||
geometry,
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log(`[atlas-geo] geoBoundaries ref ${GB_REF}; ${COUNTRIES.length} countries`)
|
||||
fs.mkdirSync(OUT_DIR, { recursive: true })
|
||||
fs.mkdirSync(CACHE_DIR, { recursive: true })
|
||||
console.log(`[atlas-geo] geoBoundaries ref ${GB_REF}; ${COUNTRIES.length} countries`);
|
||||
fs.mkdirSync(OUT_DIR, { recursive: true });
|
||||
fs.mkdirSync(CACHE_DIR, { recursive: true });
|
||||
|
||||
// ADM0 (countries) — one comprehensive CGAZ file (large; cached). Also yields the
|
||||
// English country name (shapeGroup → shapeName) used for the ADM1 `admin` field.
|
||||
console.log('[atlas-geo] downloading CGAZ ADM0 (countries)…')
|
||||
const cgaz = await fetchGeo(CGAZ_ADM0)
|
||||
const adm0Features = []
|
||||
const a3ToName = {}
|
||||
console.log('[atlas-geo] downloading CGAZ ADM0 (countries)…');
|
||||
const cgaz = await fetchGeo(CGAZ_ADM0);
|
||||
const adm0Features = [];
|
||||
const a3ToName = {};
|
||||
for (const f of cgaz?.features || []) {
|
||||
const nf = normalizeAdm0Feature(f)
|
||||
if (nf) { a3ToName[nf.properties.ADM0_A3] = nf.properties.NAME; adm0Features.push(nf) }
|
||||
const nf = normalizeAdm0Feature(f);
|
||||
if (nf) {
|
||||
a3ToName[nf.properties.ADM0_A3] = nf.properties.NAME;
|
||||
adm0Features.push(nf);
|
||||
}
|
||||
}
|
||||
|
||||
// ADM1 (sub-national regions) — per-country gbOpen (carries ISO 3166-2 `shapeISO`).
|
||||
console.log('[atlas-geo] downloading ADM1 (regions)…')
|
||||
const adm1Raw = await pool(COUNTRIES, a3 => fetchGeo(MEDIA(a3, ADM_LEVEL[a3] || 'ADM1')))
|
||||
const adm1Features = []
|
||||
let withCodes = 0
|
||||
console.log('[atlas-geo] downloading ADM1 (regions)…');
|
||||
const adm1Raw = await pool(COUNTRIES, (a3) => fetchGeo(MEDIA(a3, ADM_LEVEL[a3] || 'ADM1')));
|
||||
const adm1Features = [];
|
||||
let withCodes = 0;
|
||||
COUNTRIES.forEach((a3, idx) => {
|
||||
const feats = normalizeAdm1(adm1Raw[idx], a3, a3ToName[a3] || a3)
|
||||
for (const f of feats) if (f.properties.iso_3166_2) withCodes++
|
||||
adm1Features.push(...feats)
|
||||
})
|
||||
const feats = normalizeAdm1(adm1Raw[idx], a3, a3ToName[a3] || a3);
|
||||
for (const f of feats) if (f.properties.iso_3166_2) withCodes++;
|
||||
adm1Features.push(...feats);
|
||||
});
|
||||
|
||||
const write = (name, features) => {
|
||||
const fc = { type: 'FeatureCollection', features }
|
||||
const gz = zlib.gzipSync(Buffer.from(JSON.stringify(fc)), { level: 9 })
|
||||
const file = path.join(OUT_DIR, `${name}.geojson.gz`)
|
||||
fs.writeFileSync(file, gz)
|
||||
console.log(`[atlas-geo] wrote ${path.relative(path.join(__dirname, '..'), file)} — ${features.length} features, ${(gz.length / 1e6).toFixed(1)} MB gz`)
|
||||
}
|
||||
const fc = { type: 'FeatureCollection', features };
|
||||
const gz = zlib.gzipSync(Buffer.from(JSON.stringify(fc)), { level: 9 });
|
||||
const file = path.join(OUT_DIR, `${name}.geojson.gz`);
|
||||
fs.writeFileSync(file, gz);
|
||||
console.log(
|
||||
`[atlas-geo] wrote ${path.relative(path.join(__dirname, '..'), file)} — ${features.length} features, ${(gz.length / 1e6).toFixed(1)} MB gz`,
|
||||
);
|
||||
};
|
||||
|
||||
write('admin0', adm0Features)
|
||||
write('admin1', adm1Features)
|
||||
write('admin0', adm0Features);
|
||||
write('admin1', adm1Features);
|
||||
|
||||
const missing1 = COUNTRIES.filter((a3, i) => !normalizeAdm1(adm1Raw[i], a3, '').length)
|
||||
console.log(`[atlas-geo] ADM0 country features: ${adm0Features.length}`)
|
||||
console.log(`[atlas-geo] ADM1 countries without regions (skipped/404): ${missing1.length}`)
|
||||
console.log(`[atlas-geo] ADM1 features with ISO 3166-2 code: ${withCodes}/${adm1Features.length}`)
|
||||
const missing1 = COUNTRIES.filter((a3, i) => !normalizeAdm1(adm1Raw[i], a3, '').length);
|
||||
console.log(`[atlas-geo] ADM0 country features: ${adm0Features.length}`);
|
||||
console.log(`[atlas-geo] ADM1 countries without regions (skipped/404): ${missing1.length}`);
|
||||
console.log(`[atlas-geo] ADM1 features with ISO 3166-2 code: ${withCodes}/${adm1Features.length}`);
|
||||
}
|
||||
|
||||
main().catch(err => { console.error(err); process.exit(1) })
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
#!/usr/bin/env node
|
||||
// Rebuilds tests/fixtures/legacy/legacy-v244.sql: a database as the v4.3.3 release left it.
|
||||
//
|
||||
// 1. `git archive v4.3.3` the server sources into a temp dir outside the repo and
|
||||
// point its node_modules at this checkout's (the runner only needs better-sqlite3,
|
||||
// bcryptjs and @trek/shared, none of which changed shape for it).
|
||||
// 2. Boot that release's own database layer once against an empty file, so the
|
||||
// schema is exactly what its createTables() and positional runner produced.
|
||||
// 3. Insert synthetic rows across the main tables, pin every timestamp, VACUUM.
|
||||
// 4. Write the result as a sqlite3 `.dump`-style script, then delete the temp dir.
|
||||
//
|
||||
// Run from server/: node scripts/build-legacy-fixture-v244.mjs
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const Database = require('better-sqlite3');
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const SERVER = path.join(__dirname, '..');
|
||||
const REPO = path.join(SERVER, '..');
|
||||
const OUT = path.join(SERVER, 'tests', 'fixtures', 'legacy', 'legacy-v244.sql');
|
||||
const TAG = 'v4.3.3';
|
||||
const T = '2026-09-26 10:00:00';
|
||||
|
||||
const HEADER = `-- Legacy-runner install at schema_version 244: the ${TAG} release (the last one shipped
|
||||
-- with the positional runner), booted once on an empty data dir with no DEMO_MODE, then
|
||||
-- synthetic rows across the main tables (users, trips, members, days, places, assignments,
|
||||
-- a booked stay, reservations with endpoints, budget with splits, packing, todos, notes,
|
||||
-- file metadata, tags, a journey with an entry, a notification). Every timestamp is pinned.
|
||||
-- No credential: every password_hash is a placeholder.
|
||||
-- Built by scripts/build-legacy-fixture-v244.mjs. Loaded by tests/helpers/legacy-fixture.ts.`;
|
||||
|
||||
function bootRelease(tmp) {
|
||||
const archive = path.join(tmp, 'src.tar');
|
||||
execFileSync('git', [
|
||||
'-C',
|
||||
REPO,
|
||||
'archive',
|
||||
'-o',
|
||||
archive,
|
||||
TAG,
|
||||
'server/src',
|
||||
'server/package.json',
|
||||
'server/tsconfig.json',
|
||||
]);
|
||||
// Relative names: GNU tar reads a drive letter as a remote host.
|
||||
execFileSync('tar', ['-xf', 'src.tar'], { cwd: tmp });
|
||||
fs.rmSync(archive);
|
||||
fs.symlinkSync(path.join(REPO, 'node_modules'), path.join(tmp, 'node_modules'), 'junction');
|
||||
fs.symlinkSync(path.join(SERVER, 'node_modules'), path.join(tmp, 'server', 'node_modules'), 'junction');
|
||||
|
||||
const dbFile = path.join(tmp, 'data', 'travel.db');
|
||||
const boot = path.join(tmp, 'server', 'boot.cjs');
|
||||
fs.writeFileSync(boot, "require('./src/db/database.ts').closeDb();\n");
|
||||
const env = {
|
||||
PATH: process.env.PATH,
|
||||
SystemRoot: process.env.SystemRoot,
|
||||
NODE_ENV: 'production',
|
||||
TREK_DB_FILE: dbFile,
|
||||
ENCRYPTION_KEY: '0'.repeat(64),
|
||||
ADMIN_EMAIL: 'admin@example.test',
|
||||
ADMIN_PASSWORD: 'fixture-only-unused',
|
||||
};
|
||||
execFileSync(process.execPath, ['--import', 'tsx', boot], { cwd: path.join(tmp, 'server'), env, stdio: 'ignore' });
|
||||
return dbFile;
|
||||
}
|
||||
|
||||
function seed(db) {
|
||||
const ins = (table, row) => {
|
||||
const cols = Object.keys(row);
|
||||
db.prepare(`INSERT INTO ${table} (${cols.join(', ')}) VALUES (${cols.map(() => '?').join(', ')})`).run(
|
||||
...cols.map((c) => row[c]),
|
||||
);
|
||||
};
|
||||
|
||||
db.prepare(`UPDATE users SET password_hash = 'fixture-login-disabled' WHERE id = 1`).run();
|
||||
// Mixed case on purpose: the case-insensitive email index must accept it.
|
||||
ins('users', {
|
||||
id: 2,
|
||||
username: 'alice',
|
||||
email: 'Alice.Traveller@Example.test',
|
||||
password_hash: 'fixture-login-disabled',
|
||||
display_name: 'Alice',
|
||||
});
|
||||
ins('users', { id: 3, username: 'bob', email: 'bob@example.test', password_hash: 'fixture-login-disabled' });
|
||||
ins('settings', { user_id: 2, key: 'temperature_unit', value: 'celsius' });
|
||||
ins('settings', { user_id: 3, key: 'language', value: 'de' });
|
||||
|
||||
// Trip 1 is upcoming and shared; trip 2 lies in the past with a reminder long due.
|
||||
ins('trips', {
|
||||
id: 1,
|
||||
user_id: 2,
|
||||
title: 'Lisbon long weekend',
|
||||
description: 'Synthetic upgrade fixture trip',
|
||||
start_date: '2027-05-10',
|
||||
end_date: '2027-05-12',
|
||||
currency: 'EUR',
|
||||
reminder_days: 3,
|
||||
});
|
||||
ins('trips', {
|
||||
id: 2,
|
||||
user_id: 3,
|
||||
title: 'Alps hiking',
|
||||
start_date: '2026-03-01',
|
||||
end_date: '2026-03-02',
|
||||
currency: 'CHF',
|
||||
reminder_days: 1,
|
||||
is_archived: 1,
|
||||
});
|
||||
ins('trip_members', { trip_id: 1, user_id: 3, invited_by: 2 });
|
||||
|
||||
for (const [id, trip_id, day_number, date, title] of [
|
||||
[1, 1, 1, '2027-05-10', 'Arrival'],
|
||||
[2, 1, 2, '2027-05-11', null],
|
||||
[3, 1, 3, '2027-05-12', 'Departure'],
|
||||
[4, 2, 1, '2026-03-01', null],
|
||||
[5, 2, 2, '2026-03-02', null],
|
||||
]) {
|
||||
ins('days', { id, trip_id, day_number, date, title });
|
||||
}
|
||||
|
||||
ins('places', {
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
name: 'Hotel Alfama',
|
||||
lat: 38.7115,
|
||||
lng: -9.13,
|
||||
address: 'Rua dos Remedios 1, Lisboa',
|
||||
category_id: 1,
|
||||
});
|
||||
ins('places', {
|
||||
id: 2,
|
||||
trip_id: 1,
|
||||
name: 'Torre de Belem',
|
||||
lat: 38.6916,
|
||||
lng: -9.216,
|
||||
address: 'Av. Brasilia, Lisboa',
|
||||
category_id: 3,
|
||||
price: 12.5,
|
||||
currency: 'EUR',
|
||||
notes: 'Book online',
|
||||
});
|
||||
ins('places', {
|
||||
id: 3,
|
||||
trip_id: 1,
|
||||
name: 'Time Out Market',
|
||||
lat: 38.7069,
|
||||
lng: -9.1459,
|
||||
category_id: 2,
|
||||
place_time: '19:30',
|
||||
});
|
||||
ins('places', { id: 4, trip_id: 2, name: 'Gornergrat', lat: 45.9833, lng: 7.7847, category_id: 3 });
|
||||
ins('places', { id: 5, trip_id: 1, name: 'Fado bar', lat: 38.711, lng: -9.129, category_id: 2 });
|
||||
|
||||
// The canaries tests/helpers/legacy-upgrade-suite.ts asserts on, as in legacy-v242:
|
||||
// user-set times on assignments 1 to 3 of day 2, and the booked night after them.
|
||||
ins('day_accommodations', {
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
place_id: 1,
|
||||
start_day_id: 1,
|
||||
end_day_id: 3,
|
||||
check_in: '15:00',
|
||||
check_out: '11:00',
|
||||
confirmation: 'HTL-4242',
|
||||
});
|
||||
ins('day_assignments', {
|
||||
id: 1,
|
||||
day_id: 2,
|
||||
place_id: 2,
|
||||
order_index: 0,
|
||||
assignment_time: '09:00',
|
||||
assignment_end_time: '12:00',
|
||||
});
|
||||
ins('day_assignments', { id: 2, day_id: 2, place_id: 3, order_index: 1, assignment_time: '18:00' });
|
||||
ins('day_assignments', { id: 3, day_id: 2, place_id: 5, order_index: 2, assignment_time: '20:00' });
|
||||
ins('day_assignments', { id: 4, day_id: 2, place_id: 1, order_index: 3, accommodation_id: 1 });
|
||||
ins('day_assignments', { id: 5, day_id: 1, place_id: 1, order_index: 0, accommodation_id: 1 });
|
||||
ins('day_assignments', { id: 6, day_id: 4, place_id: 4, order_index: 0 });
|
||||
ins('day_notes', { day_id: 2, trip_id: 1, text: 'Tram 15 to Belem', time: '09:30', sort_order: 0 });
|
||||
|
||||
ins('reservations', {
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
day_id: 1,
|
||||
title: 'TP 1351 Frankfurt to Lisbon',
|
||||
reservation_time: '2027-05-10T08:15',
|
||||
reservation_end_time: '2027-05-10T10:05',
|
||||
confirmation_number: 'ABC123',
|
||||
status: 'confirmed',
|
||||
type: 'flight',
|
||||
});
|
||||
ins('reservation_endpoints', {
|
||||
reservation_id: 1,
|
||||
role: 'from',
|
||||
sequence: 0,
|
||||
name: 'Frankfurt',
|
||||
code: 'FRA',
|
||||
lat: 50.0379,
|
||||
lng: 8.5622,
|
||||
timezone: 'Europe/Berlin',
|
||||
local_time: '08:15',
|
||||
local_date: '2027-05-10',
|
||||
});
|
||||
ins('reservation_endpoints', {
|
||||
reservation_id: 1,
|
||||
role: 'to',
|
||||
sequence: 1,
|
||||
name: 'Lisbon',
|
||||
code: 'LIS',
|
||||
lat: 38.7742,
|
||||
lng: -9.1342,
|
||||
timezone: 'Europe/Lisbon',
|
||||
local_time: '10:05',
|
||||
local_date: '2027-05-10',
|
||||
});
|
||||
ins('reservations', {
|
||||
id: 2,
|
||||
trip_id: 1,
|
||||
day_id: 1,
|
||||
end_day_id: 3,
|
||||
place_id: 1,
|
||||
accommodation_id: 1,
|
||||
title: 'Hotel Alfama',
|
||||
confirmation_number: 'HTL-4242',
|
||||
status: 'confirmed',
|
||||
type: 'hotel',
|
||||
});
|
||||
|
||||
ins('budget_items', {
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
category: 'Accommodation',
|
||||
name: 'Hotel Alfama, two nights',
|
||||
total_price: 312.4,
|
||||
persons: 2,
|
||||
days: 2,
|
||||
paid_by_user_id: 2,
|
||||
expense_date: '2027-05-10',
|
||||
reservation_id: 2,
|
||||
currency: 'EUR',
|
||||
});
|
||||
ins('budget_item_members', { budget_item_id: 1, user_id: 2, paid: 1, amount: 156.2 });
|
||||
ins('budget_item_members', { budget_item_id: 1, user_id: 3, paid: 0, amount: 156.2 });
|
||||
ins('budget_items', {
|
||||
id: 2,
|
||||
trip_id: 1,
|
||||
category: 'Food',
|
||||
name: 'Dinner at the market',
|
||||
total_price: 64,
|
||||
persons: 2,
|
||||
paid_by_user_id: 3,
|
||||
currency: 'EUR',
|
||||
});
|
||||
|
||||
ins('packing_bags', {
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
name: 'Carry-on',
|
||||
color: '#3b82f6',
|
||||
weight_limit_grams: 8000,
|
||||
sort_order: 0,
|
||||
user_id: 2,
|
||||
});
|
||||
ins('packing_items', {
|
||||
trip_id: 1,
|
||||
name: 'Passport',
|
||||
checked: 1,
|
||||
category: 'Documents',
|
||||
sort_order: 0,
|
||||
bag_id: 1,
|
||||
quantity: 1,
|
||||
});
|
||||
ins('packing_items', {
|
||||
trip_id: 1,
|
||||
name: 'Sunscreen',
|
||||
checked: 0,
|
||||
category: 'Toiletries',
|
||||
sort_order: 1,
|
||||
weight_grams: 150,
|
||||
quantity: 1,
|
||||
});
|
||||
ins('packing_items', {
|
||||
trip_id: 1,
|
||||
name: 'Private charger',
|
||||
checked: 0,
|
||||
category: 'Tech',
|
||||
sort_order: 2,
|
||||
is_private: 1,
|
||||
owner_id: 3,
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
ins('todo_items', {
|
||||
trip_id: 1,
|
||||
name: 'Buy Lisboa Card',
|
||||
checked: 0,
|
||||
category: 'Tickets',
|
||||
sort_order: 0,
|
||||
due_date: '2027-05-01',
|
||||
assigned_user_id: 3,
|
||||
priority: 1,
|
||||
});
|
||||
ins('collab_notes', {
|
||||
trip_id: 1,
|
||||
user_id: 2,
|
||||
category: 'Ideas',
|
||||
title: 'Fado evening',
|
||||
content: 'Ask the hotel for a tip',
|
||||
});
|
||||
|
||||
ins('trip_files', {
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
reservation_id: 1,
|
||||
filename: 'fixture-boarding-pass.pdf',
|
||||
original_name: 'Boarding pass.pdf',
|
||||
file_size: 48213,
|
||||
mime_type: 'application/pdf',
|
||||
uploaded_by: 2,
|
||||
});
|
||||
ins('trip_files', {
|
||||
id: 2,
|
||||
trip_id: 1,
|
||||
place_id: 2,
|
||||
filename: 'fixture-tickets.pdf',
|
||||
original_name: 'Tickets.pdf',
|
||||
file_size: 1024,
|
||||
mime_type: 'application/pdf',
|
||||
uploaded_by: 3,
|
||||
starred: 1,
|
||||
});
|
||||
|
||||
ins('tags', { id: 1, user_id: 2, name: 'Must see', color: '#ef4444' });
|
||||
ins('place_tags', { place_id: 2, tag_id: 1 });
|
||||
|
||||
ins('journeys', {
|
||||
id: 1,
|
||||
user_id: 2,
|
||||
title: 'Portugal 2027',
|
||||
subtitle: 'Three days by the river',
|
||||
status: 'draft',
|
||||
created_at: T,
|
||||
updated_at: T,
|
||||
});
|
||||
ins('journey_trips', { journey_id: 1, trip_id: 1, added_at: T });
|
||||
ins('journey_contributors', { journey_id: 1, user_id: 3, role: 'editor', added_at: T });
|
||||
ins('journey_entries', {
|
||||
id: 1,
|
||||
journey_id: 1,
|
||||
source_trip_id: 1,
|
||||
source_place_id: 2,
|
||||
author_id: 2,
|
||||
type: 'entry',
|
||||
title: 'Belem in the sun',
|
||||
story: 'Pasteis first, tower second.',
|
||||
entry_date: '2027-05-11',
|
||||
entry_time: '11:00',
|
||||
location_name: 'Belem',
|
||||
location_lat: 38.6916,
|
||||
location_lng: -9.216,
|
||||
mood: 'amazing',
|
||||
visibility: 'shared',
|
||||
sort_order: 0,
|
||||
created_at: T,
|
||||
updated_at: T,
|
||||
});
|
||||
|
||||
ins('notifications', {
|
||||
type: 'simple',
|
||||
scope: 'trip',
|
||||
target: 1,
|
||||
sender_id: 2,
|
||||
recipient_id: 3,
|
||||
title_key: 'notif.test.title',
|
||||
text_key: 'notif.test.text',
|
||||
is_read: 0,
|
||||
});
|
||||
}
|
||||
|
||||
/** Every timestamp the runner or a column default wrote is "now"; pin them so a rebuild is byte-stable. */
|
||||
function pinTimestamps(db) {
|
||||
const tables = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`).all();
|
||||
for (const { name } of tables) {
|
||||
for (const { name: col } of db.prepare('SELECT name FROM pragma_table_info(?)').all(name)) {
|
||||
if (['created_at', 'updated_at', 'added_at', 'last_login'].includes(col)) {
|
||||
db.prepare(`UPDATE "${name}" SET "${col}" = ? WHERE "${col}" IS NOT NULL`).run(T);
|
||||
}
|
||||
}
|
||||
}
|
||||
db.prepare(`UPDATE migrations SET timestamp = 0`).run();
|
||||
}
|
||||
|
||||
function literal(v) {
|
||||
if (v === null || v === undefined) return 'NULL';
|
||||
if (typeof v === 'number' || typeof v === 'bigint') return String(v);
|
||||
if (Buffer.isBuffer(v)) return `X'${v.toString('hex')}'`;
|
||||
return `'${String(v).replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
/** The layout `sqlite3 .dump` writes, which is what the other legacy fixtures are. */
|
||||
function dump(db) {
|
||||
const out = [HEADER, 'PRAGMA foreign_keys=OFF;', 'BEGIN TRANSACTION;'];
|
||||
const master = db.prepare(`SELECT type, name, sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY rowid`).all();
|
||||
for (const { type, name, sql } of master) {
|
||||
if (type !== 'table' || name === 'sqlite_sequence') continue;
|
||||
out.push(`${sql};`);
|
||||
for (const row of db.prepare(`SELECT * FROM "${name}" ORDER BY rowid`).raw().all()) {
|
||||
out.push(`INSERT INTO ${name} VALUES(${row.map(literal).join(',')});`);
|
||||
}
|
||||
}
|
||||
out.push('PRAGMA writable_schema=ON;', 'DELETE FROM sqlite_sequence;');
|
||||
for (const row of db.prepare('SELECT name, seq FROM sqlite_sequence ORDER BY rowid').raw().all()) {
|
||||
out.push(`INSERT INTO sqlite_sequence VALUES(${row.map(literal).join(',')});`);
|
||||
}
|
||||
for (const { type, sql } of master) if (type !== 'table') out.push(`${sql};`);
|
||||
out.push('PRAGMA writable_schema=OFF;', 'COMMIT;', '');
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-fixture-v244-'));
|
||||
try {
|
||||
const db = new Database(bootRelease(tmp));
|
||||
db.pragma('foreign_keys = ON');
|
||||
const version = db.prepare('SELECT version FROM schema_version').get().version;
|
||||
if (version !== 244) throw new Error(`${TAG} left schema_version ${version}, expected 244`);
|
||||
db.transaction(() => {
|
||||
seed(db);
|
||||
pinTimestamps(db);
|
||||
})();
|
||||
db.pragma('wal_checkpoint(TRUNCATE)');
|
||||
db.exec('VACUUM');
|
||||
fs.writeFileSync(OUT, dump(db));
|
||||
db.close();
|
||||
console.log(`Wrote ${path.relative(SERVER, OUT)}`);
|
||||
} finally {
|
||||
// The node_modules junctions go first, so the recursive delete can never walk into this checkout's.
|
||||
for (const link of [path.join(tmp, 'node_modules'), path.join(tmp, 'server', 'node_modules')]) {
|
||||
if (fs.existsSync(link)) fs.unlinkSync(link);
|
||||
}
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
@@ -1,8 +1,39 @@
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, rmSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// Resolved from this file rather than cwd, so the directory that gets removed is
|
||||
// always this package's own dist no matter where the script is invoked from.
|
||||
const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
const distDir = join(packageRoot, 'dist');
|
||||
|
||||
// tsc only ever adds to dist, so a module deleted or renamed in src leaves its
|
||||
// compiled twin behind. For most code that is merely stale, but the migrator
|
||||
// globs dist/db/migrations at boot: an orphan there is a live migration with no
|
||||
// source, and it runs. Same for dist/db/seeders. Nothing else writes into dist —
|
||||
// the client bundle goes to server/public and the runtime assets the Dockerfile
|
||||
// needs are copied in separately — so it is safe to drop wholesale.
|
||||
rmSync(distDir, { recursive: true, force: true });
|
||||
|
||||
let tscExitedNonZero = false;
|
||||
try {
|
||||
execSync('tsc -p tsconfig.build.json', { stdio: 'inherit' });
|
||||
execSync('tsc -p tsconfig.build.json', { stdio: 'inherit', cwd: packageRoot });
|
||||
} catch {
|
||||
tscExitedNonZero = true;
|
||||
}
|
||||
|
||||
// `noEmitOnError` is off, so tsc exits non-zero on type errors and still writes
|
||||
// dist — that case is deliberate, and gated by `npm run typecheck`. A tsc that
|
||||
// never ran at all (not on PATH, crashed) is indistinguishable from here, and
|
||||
// now that dist is emptied first it would leave nothing behind while still
|
||||
// reporting success. Checking for the entry point tells the two apart.
|
||||
if (!existsSync(join(distDir, 'index.js'))) {
|
||||
console.error('[build] tsc emitted nothing — dist is empty. Run via `npm run build` so tsc is on PATH.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (tscExitedNonZero) {
|
||||
console.warn('[build] tsc reported type errors — emitting anyway (gated by `npm run typecheck`).');
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,10 @@ const summary = JSON.parse(fs.readFileSync(summaryPath, 'utf8'));
|
||||
const domains = new Map();
|
||||
for (const [file, entry] of Object.entries(summary)) {
|
||||
if (file === 'total') continue;
|
||||
const match = file.split('\\').join('/').match(/\/src\/nest\/([a-z0-9-]+)\//);
|
||||
const match = file
|
||||
.split('\\')
|
||||
.join('/')
|
||||
.match(/\/src\/nest\/([a-z0-9-]+)\//);
|
||||
if (!match) continue;
|
||||
const totals = domains.get(match[1]) ?? new Map(METRICS.map(([k]) => [k, { covered: 0, total: 0 }]));
|
||||
for (const [key, metric] of METRICS) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,14 @@ console.log('[dev] initial build...');
|
||||
execSync('node scripts/build.mjs', { stdio: 'inherit' });
|
||||
|
||||
const children = [];
|
||||
const stop = () => { children.forEach((c) => { try { c.kill(); } catch {} }); process.exit(0); };
|
||||
const stop = () => {
|
||||
children.forEach((c) => {
|
||||
try {
|
||||
c.kill();
|
||||
} catch {}
|
||||
});
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGINT', stop);
|
||||
process.on('SIGTERM', stop);
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"src/db/entities/IdempotencyKeys.entity.ts": {
|
||||
"strftime": 1
|
||||
},
|
||||
"src/db/entities/PlaceShadowPicks.entity.ts": {
|
||||
"datetime": 1
|
||||
},
|
||||
"src/db/entities/PluginCapabilityAudit.entity.ts": {
|
||||
"datetime": 1
|
||||
},
|
||||
"src/db/entities/PluginEgressHosts.entity.ts": {
|
||||
"datetime": 1
|
||||
},
|
||||
"src/db/entities/PluginEntityMetadata.entity.ts": {
|
||||
"datetime": 1
|
||||
},
|
||||
"src/db/entities/PluginOauthTokens.entity.ts": {
|
||||
"datetime": 1
|
||||
},
|
||||
"src/db/entities/PluginScheduledTasks.entity.ts": {
|
||||
"datetime": 1
|
||||
},
|
||||
"src/db/entities/PluginUserConfig.entity.ts": {
|
||||
"datetime": 1
|
||||
},
|
||||
"src/db/entities/PluginUserErasureQueue.entity.ts": {
|
||||
"datetime": 1
|
||||
},
|
||||
"src/db/repositories/MaintenanceRepository.ts": {
|
||||
"pragma": 1
|
||||
},
|
||||
"src/nest/backup/backup-archive.ts": {
|
||||
"pragma": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:dialect: SQLite-only SQL may only shrink.
|
||||
*
|
||||
* The server runs on SQLite today and is meant to run on Postgres next. What
|
||||
* stands in the way is SQL that only SQLite understands, spelled out inline:
|
||||
* INSERT OR IGNORE, datetime('now'), strftime, json_extract, GLOB,
|
||||
* last_insert_rowid, PRAGMA, AUTOINCREMENT and `||` string concatenation.
|
||||
* Each of them has a dialect-neutral form: the query builder's onConflict(),
|
||||
* returning('id'), or a helper in src/db/dialect/ (sql-functions.ts and its
|
||||
* Kysely twin kysely-functions.ts), which dispatches on the live platform
|
||||
* and is the one place allowed to spell an engine's own forms.
|
||||
*
|
||||
* The check reads every string and template literal under src/ (comments
|
||||
* never count) and every `.insertId` read, counts the hits per file and rule,
|
||||
* and holds them to scripts/dialect-baseline.json. A new hit fails, and so
|
||||
* does a baseline entry above what its file holds now, so the change that
|
||||
* removes one lowers the baseline with --update in the same commit.
|
||||
*
|
||||
* Not scanned: src/db/dialect/ (the dialect layer itself) and
|
||||
* the migrations that have shipped (append-only, never edited again; the last
|
||||
* one is FROZEN_MIGRATIONS_THROUGH). A newer migration is scanned for the
|
||||
* DML rules; its DDL may still be engine specific. PRAGMA is allowed in the
|
||||
* src/db/ lifecycle files (src/db/*.ts and the migrations), nowhere else.
|
||||
*
|
||||
* npm run lint:dialect check against the baseline (CI)
|
||||
* npm run lint:dialect -- --update lower the baseline to what the files hold now;
|
||||
* it never raises or adds an entry
|
||||
*
|
||||
* --dir=<path> points the check at another server root (the unit tests use it).
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const ts = require('typescript');
|
||||
|
||||
/** The last migration that shipped before this check existed. Later ones are scanned. */
|
||||
export const FROZEN_MIGRATIONS_THROUGH = 'Migration20200101042400';
|
||||
|
||||
/** The dialect layer: the one place that may spell an engine's own SQL. */
|
||||
const DIALECT_LAYER = 'src/db/dialect/';
|
||||
|
||||
const SQL_KEYWORDS = /\b(SELECT|UPDATE|INSERT|DELETE|WHERE|SET|CASE|WHEN|COALESCE|CAST|VALUES|FROM)\b/i;
|
||||
|
||||
/**
|
||||
* Each rule: a name, a test over one literal's text, the advice the failure
|
||||
* prints, and whether it applies to a migration newer than the frozen ones.
|
||||
*/
|
||||
export const RULES = [
|
||||
{
|
||||
name: 'insert-or',
|
||||
test: (text) => /\bINSERT\s+OR\s+(IGNORE|REPLACE)\b|\bREPLACE\s+INTO\b/i.test(text),
|
||||
advice: "use the query builder's onConflict((oc) => oc.columns([...]).doNothing() / .doUpdateSet(...))",
|
||||
migrations: true,
|
||||
},
|
||||
{
|
||||
name: 'datetime',
|
||||
// The call in SQL text, or the bare name the query builder takes in eb.fn('datetime', [...]).
|
||||
test: (text) =>
|
||||
/\b(datetime|julianday|unixepoch)\s*\(/i.test(text) || /^(datetime|julianday|unixepoch)$/i.test(text.trim()),
|
||||
advice: 'use currentTimestamp/nowMinusDays/nowPlusSeconds and friends from sql-functions.ts',
|
||||
migrations: true,
|
||||
},
|
||||
{
|
||||
name: 'strftime',
|
||||
test: (text) => /\bstrftime\b/i.test(text),
|
||||
advice: 'use unixEpochToIsoKysely or another sql-functions.ts helper',
|
||||
migrations: true,
|
||||
},
|
||||
{
|
||||
name: 'json',
|
||||
test: (text) => /\bjson_(extract|each|set|patch|insert|replace|remove|group_array|group_object)\b/i.test(text),
|
||||
advice: 'read the JSON column and parse it in the service, or add a helper to sql-functions.ts',
|
||||
migrations: true,
|
||||
},
|
||||
{
|
||||
name: 'glob',
|
||||
test: (text) => /\bGLOB\b/.test(text) || text.trim().toLowerCase() === 'glob',
|
||||
advice: 'use LIKE, or startsWithIsoDate and its siblings in sql-functions.ts',
|
||||
migrations: true,
|
||||
},
|
||||
{
|
||||
name: 'last-insert-rowid',
|
||||
test: (text) => /\blast_insert_rowid\b/i.test(text),
|
||||
advice: "read the new id with .returning('id')",
|
||||
migrations: true,
|
||||
},
|
||||
{
|
||||
name: 'autoincrement',
|
||||
test: (text) => /\bAUTOINCREMENT\b/i.test(text),
|
||||
advice: 'tables are created by migrations, not by query-builder code',
|
||||
migrations: false,
|
||||
},
|
||||
{
|
||||
name: 'pragma',
|
||||
// The statement, `PRAGMA name`: the bare word is also an HTTP header.
|
||||
test: (text) => /\bPRAGMA\s+[a-z_]/i.test(text),
|
||||
advice: 'PRAGMA belongs in the src/db/ lifecycle files (connection, durability, migrations)',
|
||||
migrations: false,
|
||||
},
|
||||
{
|
||||
name: 'concat',
|
||||
test: (text, inSqlTag) => text.includes('||') && (inSqlTag || SQL_KEYWORDS.test(text)),
|
||||
advice: 'use concat/concatKysely from sql-functions.ts',
|
||||
migrations: true,
|
||||
},
|
||||
];
|
||||
|
||||
/** `.insertId` reads, the JS face of last_insert_rowid. */
|
||||
const INSERT_ID_RULE = 'insert-id';
|
||||
|
||||
const SOURCE = /\.ts$/;
|
||||
const TEST = /\.(?:test|spec)\./;
|
||||
|
||||
/** 'skip', 'migration' (a newer one, DML rules only) or 'source'. */
|
||||
export function classify(file) {
|
||||
if (file.startsWith(DIALECT_LAYER)) return 'skip';
|
||||
const migration = /^src\/db\/migrations\/(Migration\d+)_/.exec(file);
|
||||
if (migration) return migration[1] <= FROZEN_MIGRATIONS_THROUGH ? 'skip' : 'migration';
|
||||
if (file.startsWith('src/db/migrations/')) return 'skip';
|
||||
return 'source';
|
||||
}
|
||||
|
||||
/** PRAGMA is fine in src/db/*.ts (connection, durability, baseline, snapshot) and the migrations. */
|
||||
export function pragmaAllowed(file) {
|
||||
return /^src\/db\/[^/]+\.ts$/.test(file) || file.startsWith('src/db/migrations/');
|
||||
}
|
||||
|
||||
function isSqlTag(node) {
|
||||
let tag = node.tag;
|
||||
if (ts.isPropertyAccessExpression(tag)) tag = tag.expression;
|
||||
return ts.isIdentifier(tag) && tag.text === 'sql';
|
||||
}
|
||||
|
||||
/** Hits per rule in one file's source. */
|
||||
export function scanSource(file, text) {
|
||||
const kind = classify(file);
|
||||
const counts = {};
|
||||
if (kind === 'skip') return counts;
|
||||
const add = (rule) => {
|
||||
counts[rule] = (counts[rule] ?? 0) + 1;
|
||||
};
|
||||
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
||||
|
||||
const checkText = (literal, inSqlTag) => {
|
||||
for (const rule of RULES) {
|
||||
if (kind === 'migration' && !rule.migrations) continue;
|
||||
if (rule.name === 'pragma' && pragmaAllowed(file)) continue;
|
||||
if (rule.test(literal, inSqlTag)) add(rule.name);
|
||||
}
|
||||
};
|
||||
|
||||
const visit = (node, inSqlTag) => {
|
||||
if (ts.isTaggedTemplateExpression(node) && isSqlTag(node)) {
|
||||
ts.forEachChild(node, (child) => visit(child, true));
|
||||
return;
|
||||
}
|
||||
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
|
||||
checkText(node.text, inSqlTag);
|
||||
} else if (ts.isTemplateExpression(node)) {
|
||||
// The literal parts only: an interpolated value is code, scanned on its own.
|
||||
checkText([node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join(' '), inSqlTag);
|
||||
} else if (ts.isPropertyAccessExpression(node) && node.name.text === 'insertId') {
|
||||
add(INSERT_ID_RULE);
|
||||
} else if (
|
||||
ts.isBindingElement(node) &&
|
||||
((node.propertyName && ts.isIdentifier(node.propertyName) && node.propertyName.text === 'insertId') ||
|
||||
(!node.propertyName && ts.isIdentifier(node.name) && node.name.text === 'insertId'))
|
||||
) {
|
||||
add(INSERT_ID_RULE);
|
||||
}
|
||||
ts.forEachChild(node, (child) => visit(child, inSqlTag));
|
||||
};
|
||||
visit(sf, false);
|
||||
return counts;
|
||||
}
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === 'node_modules') continue;
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path, files);
|
||||
else if (SOURCE.test(name) && !TEST.test(name) && !name.endsWith('.d.ts')) files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** `{ file: { rule: n } }` for every file under src/ with at least one hit. */
|
||||
export function scan(serverDir) {
|
||||
const src = join(serverDir, 'src');
|
||||
if (!existsSync(src) || !statSync(src).isDirectory()) {
|
||||
throw new Error(`src/ does not exist under ${serverDir}: the check would pass without looking at anything`);
|
||||
}
|
||||
const result = {};
|
||||
for (const path of walk(src)) {
|
||||
const file = relative(serverDir, path).split('\\').join('/');
|
||||
const counts = scanSource(file, readFileSync(path, 'utf8'));
|
||||
if (Object.keys(counts).length > 0) result[file] = sortKeys(counts);
|
||||
}
|
||||
return sortKeys(result);
|
||||
}
|
||||
|
||||
function sortKeys(obj) {
|
||||
return Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
|
||||
}
|
||||
|
||||
const RULE_NAMES = new Set([...RULES.map((r) => r.name), INSERT_ID_RULE]);
|
||||
|
||||
/** The committed baseline. Missing or malformed stops the run rather than reading as empty. */
|
||||
export function readBaseline(path) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||||
} catch (err) {
|
||||
throw new Error(`scripts/dialect-baseline.json cannot be read: ${err.message}`);
|
||||
}
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error('scripts/dialect-baseline.json must be an object of file paths to { rule: count }');
|
||||
}
|
||||
for (const [file, rules] of Object.entries(parsed)) {
|
||||
if (rules === null || typeof rules !== 'object' || Array.isArray(rules)) {
|
||||
throw new Error(`scripts/dialect-baseline.json: ${file} must map rule names to counts`);
|
||||
}
|
||||
for (const [rule, n] of Object.entries(rules)) {
|
||||
if (!RULE_NAMES.has(rule))
|
||||
throw new Error(`scripts/dialect-baseline.json: ${file} names an unknown rule "${rule}"`);
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(
|
||||
`scripts/dialect-baseline.json: ${file} ${rule} holds ${JSON.stringify(n)}, expected a positive integer`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** The baseline lowered to what the files hold now. Never raises an entry, never adds one. */
|
||||
export function lowerBaseline(baseline, counts) {
|
||||
const lowered = {};
|
||||
for (const [file, rules] of Object.entries(baseline)) {
|
||||
const kept = {};
|
||||
for (const [rule, allowed] of Object.entries(rules)) {
|
||||
const now = counts[file]?.[rule] ?? 0;
|
||||
if (now > 0) kept[rule] = Math.min(allowed, now);
|
||||
}
|
||||
if (Object.keys(kept).length > 0) lowered[file] = sortKeys(kept);
|
||||
}
|
||||
return sortKeys(lowered);
|
||||
}
|
||||
|
||||
/** New hits over the baseline, and baseline entries above what their file holds now. */
|
||||
export function compare(baseline, counts) {
|
||||
const grown = [];
|
||||
for (const [file, rules] of Object.entries(counts)) {
|
||||
for (const [rule, n] of Object.entries(rules)) {
|
||||
const allowed = baseline[file]?.[rule] ?? 0;
|
||||
if (n > allowed) grown.push({ file, rule, n, allowed });
|
||||
}
|
||||
}
|
||||
const lowered = lowerBaseline(baseline, counts);
|
||||
const stale = [];
|
||||
for (const [file, rules] of Object.entries(baseline)) {
|
||||
for (const [rule, allowed] of Object.entries(rules)) {
|
||||
const now = lowered[file]?.[rule] ?? 0;
|
||||
if (now !== allowed) stale.push({ file, rule, allowed, now: counts[file]?.[rule] ?? 0 });
|
||||
}
|
||||
}
|
||||
return { grown, stale };
|
||||
}
|
||||
|
||||
function adviceFor(rule) {
|
||||
if (rule === INSERT_ID_RULE) return "read the new id with .returning('id'); insertId is undefined on Postgres";
|
||||
return RULES.find((r) => r.name === rule).advice;
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
const dirArg = argv.find((a) => a.startsWith('--dir='));
|
||||
const serverDir = dirArg ? resolve(dirArg.slice('--dir='.length)) : fileURLToPath(new URL('..', import.meta.url));
|
||||
const baselinePath = join(serverDir, 'scripts', 'dialect-baseline.json');
|
||||
const update = argv.includes('--update');
|
||||
|
||||
const counts = scan(serverDir);
|
||||
let baseline = readBaseline(baselinePath);
|
||||
if (update) {
|
||||
baseline = lowerBaseline(baseline, counts);
|
||||
writeFileSync(baselinePath, JSON.stringify(baseline, null, 2) + '\n');
|
||||
}
|
||||
|
||||
const { grown, stale } = compare(baseline, counts);
|
||||
for (const { file, rule, n, allowed } of grown) {
|
||||
console.error(`FAIL ${file}: ${n} SQLite-only ${rule} hit(s), ${allowed} allowed. ${adviceFor(rule)}.`);
|
||||
}
|
||||
for (const { file, rule, allowed, now } of stale) {
|
||||
console.error(
|
||||
`FAIL ${file} is held at ${allowed} ${rule} hit(s) in scripts/dialect-baseline.json, but has ${now} now.`,
|
||||
);
|
||||
}
|
||||
if (stale.length) {
|
||||
console.error('Run npm run lint:dialect -- --update to lower the baseline with the change that removed them.');
|
||||
}
|
||||
const total = Object.values(baseline).reduce(
|
||||
(sum, rules) => sum + Object.values(rules).reduce((a, b) => a + b, 0),
|
||||
0,
|
||||
);
|
||||
console.log(
|
||||
`dialect: ${Object.keys(baseline).length} file(s) hold ${total} SQLite-only spelling(s) at their baseline`,
|
||||
);
|
||||
return grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
|
||||
const isCli =
|
||||
Boolean(process.argv[1]) &&
|
||||
existsSync(process.argv[1]) &&
|
||||
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
try {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
} catch (err) {
|
||||
console.error(`FAIL ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"AccommodationUpdateDto": 1,
|
||||
"AddTripPhotosDto": 3,
|
||||
"AdminAddonUpdateDto": 1,
|
||||
"AdminDefaultUserSettingsDto": 1,
|
||||
"AdminPermissionsDto": 1,
|
||||
"AdminTestNotificationDto": 2,
|
||||
"AppSettingsUpdateDto": 1,
|
||||
"AutoBackupSettingsDto": 1,
|
||||
"BookingImportConfirmDto": 1,
|
||||
"CollabPollCreateDto": 1,
|
||||
"CollectionImportDto": 1,
|
||||
"CollectionImportIntoDto": 1,
|
||||
"CreateAlbumLinkDto": 5,
|
||||
"ImmichSearchDto": 1,
|
||||
"ImmichSettingsDto": 2,
|
||||
"ImmichTestDto": 1,
|
||||
"JourneyAddTripDto": 2,
|
||||
"JourneyContributorAddDto": 3,
|
||||
"JourneyContributorUpdateDto": 2,
|
||||
"JourneyCreateDto": 4,
|
||||
"JourneyEntryCreateDto": 2,
|
||||
"JourneyEntryPhotoUploadDto": 2,
|
||||
"JourneyEntryUpdateDto": 1,
|
||||
"JourneyGalleryVideoDto": 2,
|
||||
"JourneyLinkPhotoDto": 3,
|
||||
"JourneyPhotoUpdateDto": 1,
|
||||
"JourneyPreferencesDto": 1,
|
||||
"JourneyProviderPhotosDto": 8,
|
||||
"JourneyReorderEntriesDto": 2,
|
||||
"JourneyShareLinkDto": 5,
|
||||
"JourneyUpdateDto": 1,
|
||||
"LlmLocalPullDto": 1,
|
||||
"OauthClientCreateDto": 1,
|
||||
"PackingImportDto": 1,
|
||||
"PasskeyLoginVerifyDto": 1,
|
||||
"PasskeyRegisterVerifyDto": 2,
|
||||
"PasskeyRenameDto": 1,
|
||||
"PlaceCreateDto": 1,
|
||||
"PlaceEnrichmentDto": 1,
|
||||
"PlaceUpdateDto": 1,
|
||||
"PluginActivateDto": 1,
|
||||
"PluginConfigDto": 1,
|
||||
"PluginEgressHostsDto": 2,
|
||||
"PluginInstallDto": 1,
|
||||
"PluginLinkDto": 1,
|
||||
"PluginRetrustDto": 1,
|
||||
"PluginRouteDto": 1,
|
||||
"PluginUninstallDto": 1,
|
||||
"PluginUpdateDto": 1,
|
||||
"PluginUserSettingsUpdateDto": 2,
|
||||
"RemoveTripPhotoDto": 1,
|
||||
"ReservationCreateDto": 1,
|
||||
"ReservationUpdateDto": 1,
|
||||
"SettingsBulkDto": 1,
|
||||
"SettingUpsertDto": 1,
|
||||
"SetTripPhotoSharingDto": 2,
|
||||
"SynologySearchDto": 1,
|
||||
"SynologySettingsDto": 1,
|
||||
"SynologyTestDto": 1,
|
||||
"TagCreateDto": 3,
|
||||
"TagUpdateDto": 3
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* contracts:dto-open: runs tests/unit/contracts/dto-open-shapes.test.ts, the
|
||||
* ratchet over the open shapes in every createZodDto class under src/.
|
||||
*
|
||||
* The check has to import the TypeScript DTO files, so it lives in that test
|
||||
* and runs with the unit tests in CI; this wrapper only gives it a command and
|
||||
* the lowering mode:
|
||||
*
|
||||
* npm run contracts:dto-open check against scripts/dto-open-shapes-baseline.json
|
||||
* npm run contracts:dto-open -- --update lower the baseline to today's counts; it never
|
||||
* raises or adds an entry
|
||||
*
|
||||
* The shared package must be built first (the DTOs import @trek/shared).
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { existsSync, realpathSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const SERVER_ROOT = fileURLToPath(new URL('..', import.meta.url));
|
||||
const TEST = 'tests/unit/contracts/dto-open-shapes.test.ts';
|
||||
|
||||
function main(argv) {
|
||||
const unknown = argv.filter((arg) => arg !== '--update');
|
||||
if (unknown.length) throw new Error(`unknown argument(s): ${unknown.join(' ')}`);
|
||||
if (!existsSync(join(SERVER_ROOT, TEST))) throw new Error(`${TEST} is missing`);
|
||||
const vitest = join(dirname(createRequire(import.meta.url).resolve('vitest/package.json')), 'vitest.mjs');
|
||||
const env = { ...process.env, DTO_OPEN_SHAPES_UPDATE: argv.includes('--update') ? '1' : '0' };
|
||||
const result = spawnSync(process.execPath, [vitest, 'run', TEST], { cwd: SERVER_ROOT, env, stdio: 'inherit' });
|
||||
if (result.error) throw result.error;
|
||||
return result.status ?? 1;
|
||||
}
|
||||
|
||||
// Compared by real path, so the check still runs when the script is started through a symlink.
|
||||
const isCli =
|
||||
Boolean(process.argv[1]) &&
|
||||
existsSync(process.argv[1]) &&
|
||||
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
try {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
} catch (err) {
|
||||
console.error(`FAIL ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"src": {
|
||||
"@typescript-eslint/no-explicit-any": 86,
|
||||
"@typescript-eslint/no-non-null-assertion": 263,
|
||||
"@typescript-eslint/no-require-imports": 18,
|
||||
"@typescript-eslint/no-unsafe-function-type": 1,
|
||||
"@typescript-eslint/no-unused-vars": 36,
|
||||
"no-await-in-loop": 563,
|
||||
"no-console": 235,
|
||||
"no-empty": 6
|
||||
},
|
||||
"suppressed": {
|
||||
"@typescript-eslint/no-explicit-any": 124,
|
||||
"@typescript-eslint/no-require-imports": 20,
|
||||
"no-control-regex": 7,
|
||||
"no-misleading-character-class": 1
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 1562,
|
||||
"@typescript-eslint/no-non-null-assertion": 1755,
|
||||
"@typescript-eslint/no-require-imports": 25,
|
||||
"@typescript-eslint/no-unsafe-function-type": 7,
|
||||
"@typescript-eslint/no-unused-vars": 96,
|
||||
"no-await-in-loop": 452,
|
||||
"no-console": 18,
|
||||
"no-empty": 2,
|
||||
"no-useless-escape": 1,
|
||||
"prefer-const": 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:warnings: ESLint errors fail, warnings may only go down.
|
||||
*
|
||||
* Several rules in eslint.config.mjs are warnings (no-explicit-any,
|
||||
* no-unused-vars, no-require-imports, no-await-in-loop, no-non-null-assertion,
|
||||
* no-console and a few js.recommended ones), set that way because the code
|
||||
* had hits when they came in, and a warning never fails a build. So this runs
|
||||
* ESLint over the server with its own config, as `eslint .` does, and counts
|
||||
* the warnings per rule, separately for src/ and tests/, plus the messages an
|
||||
* eslint-disable comment silenced as a third group. Each count may not pass
|
||||
* its entry in scripts/eslint-baseline.json, and an entry above its count
|
||||
* fails as well until --update lowers it, so a fixed warning cannot come back
|
||||
* unseen. Any error fails, so the check stands in for `npm run lint:check`,
|
||||
* and so does a block comment that configures a rule inline: it leaves no
|
||||
* message to count, so it would otherwise be the free way past the ratchet.
|
||||
*
|
||||
* npm run lint:warnings check against the baseline (CI)
|
||||
* npm run lint:warnings -- --update lower the baseline to today's counts;
|
||||
* it never raises an entry
|
||||
*
|
||||
* The tally lives in scripts/lib/eslint-warnings.mjs at the repository root;
|
||||
* ESLint comes from this workspace, so the server lints with the major its
|
||||
* config was written for.
|
||||
*/
|
||||
import { check, lintTextWith, lintWith } from '../../scripts/lib/eslint-warnings.mjs';
|
||||
import { runCli } from '../../scripts/lib/ratchet.mjs';
|
||||
|
||||
import { ESLint } from 'eslint';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:warnings', (args) =>
|
||||
check({ root, update: args.includes('--update'), lint: lintWith(ESLint), lintText: lintTextWith(ESLint) }),
|
||||
);
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Turn pages drawn in the Studio into decorated templates.
|
||||
*
|
||||
* Reads the book of a journey and writes the pages named into a data file of
|
||||
* the decorated templates (shared/src/book/templates/data/), in the format
|
||||
* shared/src/book/templates/template-format.ts describes: every measure a
|
||||
* fraction of the page it was drawn on, the pictures and the words taken out,
|
||||
* the roles and the theme links kept. The reading is shared's
|
||||
* `bookTemplateFromSpread`, so what this writes is what its spec holds.
|
||||
*
|
||||
* How a drawn page says what is what:
|
||||
*
|
||||
* - Name a layer after its role in the layers panel (title, subtitle, date,
|
||||
* body, caption, photo:1, photo:2 and on, map). A text bound to the journal
|
||||
* takes the role of its source without a name, a date mark takes date, a
|
||||
* map takes map, and the photo frames left take the next photo roles in
|
||||
* paint order.
|
||||
* - Group the elements of a lockup (a title with its date line, a badge with
|
||||
* its words, a stamp with its postmark): the group comes along and is laid
|
||||
* as one group of the page.
|
||||
* - Link colours and faces to the book's theme in the inspector. With the
|
||||
* book themed, a colour the document links nowhere (a border, an outline,
|
||||
* a pattern, a sticker's slots) that is exactly one of the theme's is kept
|
||||
* as a tint, so the template follows the theme of any book it is laid in.
|
||||
*
|
||||
* Usage, from server/:
|
||||
*
|
||||
* node scripts/extract-decorated-templates.cjs <journeyId> <archetype> <id>[,<id>...] [out]
|
||||
*
|
||||
* One id per page to take, in book order (the cover first when it is
|
||||
* named), each the template's id; `-` skips a page. The tags start as the
|
||||
* archetype and the description as a line to replace: write both, and the
|
||||
* names in every locale (studio.templates.name.<id in camel case>), before
|
||||
* the file is committed. Run Prettier on it, then build shared and read the
|
||||
* templates' spec.
|
||||
*/
|
||||
const Database = require('better-sqlite3');
|
||||
const fs = require('fs');
|
||||
|
||||
const [journeyArg, archetype, idList, out] = process.argv.slice(2);
|
||||
if (!journeyArg || !archetype || !idList) {
|
||||
console.error('usage: node scripts/extract-decorated-templates.cjs <journeyId> <archetype> <id>[,<id>...] [out]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const {
|
||||
BOOK_COVER_ARCHETYPES,
|
||||
bookDecoratedTemplateSchema,
|
||||
bookTemplateFromSpread,
|
||||
normalizeBookDocument,
|
||||
} = require('@trek/shared');
|
||||
|
||||
if (!BOOK_COVER_ARCHETYPES.includes(archetype)) {
|
||||
console.error(`archetype must be one of ${BOOK_COVER_ARCHETYPES.join(', ')}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const db = new Database('data/travel.db', { readonly: true });
|
||||
const row = db.prepare('SELECT document FROM journey_books WHERE journey_id = ?').get(Number(journeyArg));
|
||||
db.close();
|
||||
if (!row) throw new Error(`no book on journey ${journeyArg}`);
|
||||
|
||||
// Through the contract on the way in, so every element carries every field the document has today.
|
||||
const doc = normalizeBookDocument(JSON.parse(row.document));
|
||||
const ids = idList.split(',');
|
||||
|
||||
const templates = doc.spreads.flatMap((spread, i) => {
|
||||
const id = ids[i];
|
||||
if (!id || id === '-') return [];
|
||||
const tpl = bookTemplateFromSpread(spread, doc.page, {
|
||||
id,
|
||||
archetype,
|
||||
tags: [archetype],
|
||||
descr: 'Describe in one sentence what the page shows.',
|
||||
theme: doc.theme ?? null,
|
||||
});
|
||||
const checked = bookDecoratedTemplateSchema.safeParse(tpl);
|
||||
if (!checked.success) throw new Error(`${id}: ${checked.error.message}`);
|
||||
return [tpl];
|
||||
});
|
||||
|
||||
const name = `EXTRACTED_${archetype.replace(/-/g, '_').toUpperCase()}`;
|
||||
const file = `import type { BookDecoratedTemplate } from '../template-format';
|
||||
|
||||
/**
|
||||
* Decorated templates drawn in the Studio (journey ${journeyArg}) and read out
|
||||
* by server/scripts/extract-decorated-templates.cjs: fractions of the page
|
||||
* they were drawn on, in the format of template-format.ts.
|
||||
*/
|
||||
export const ${name}: readonly BookDecoratedTemplate[] = ${JSON.stringify(templates, null, 2)};
|
||||
`;
|
||||
|
||||
const target = out || `../shared/src/book/templates/data/extracted-${archetype}.data.ts`;
|
||||
fs.writeFileSync(target, file);
|
||||
console.log(`wrote ${templates.length} templates to ${target}`);
|
||||
@@ -4,18 +4,19 @@
|
||||
* Reads the book from a journey and writes the spreads out as data: every
|
||||
* measurement divided by the page it was drawn on, so the same template lays
|
||||
* out on an A4 landscape book as it does on the 210mm square it was designed
|
||||
* for. Run from server/, output goes to the client.
|
||||
* for. Run from server/; the output is the shared auto layout's data file
|
||||
* (shared/src/book/auto/auto-templates.data.ts). Run Prettier on it before committing.
|
||||
*/
|
||||
const Database = require('better-sqlite3')
|
||||
const fs = require('fs')
|
||||
const Database = require('better-sqlite3');
|
||||
const fs = require('fs');
|
||||
|
||||
const JOURNEY = Number(process.argv[2] || 7)
|
||||
const OUT = process.argv[3] || '../client/src/components/Studio/bookTemplates.data.ts'
|
||||
const JOURNEY = Number(process.argv[2] || 7);
|
||||
const OUT = process.argv[3] || '../shared/src/book/auto/auto-templates.data.ts';
|
||||
|
||||
const db = new Database('data/travel.db', { readonly: true })
|
||||
const row = db.prepare('SELECT document FROM journey_books WHERE journey_id = ?').get(JOURNEY)
|
||||
db.close()
|
||||
if (!row) throw new Error(`no book on journey ${JOURNEY}`)
|
||||
const db = new Database('data/travel.db', { readonly: true });
|
||||
const row = db.prepare('SELECT document FROM journey_books WHERE journey_id = ?').get(JOURNEY);
|
||||
db.close();
|
||||
if (!row) throw new Error(`no book on journey ${JOURNEY}`);
|
||||
|
||||
/*
|
||||
* Through the contract on the way in, so a template carries every field the
|
||||
@@ -23,42 +24,46 @@ if (!row) throw new Error(`no book on journey ${JOURNEY}`)
|
||||
* Without it a template written today is missing tomorrow's defaults and does
|
||||
* not typecheck as a BookElement.
|
||||
*/
|
||||
const { normalizeBookDocument } = require('@trek/shared')
|
||||
const doc = normalizeBookDocument(JSON.parse(row.document))
|
||||
const PW = doc.page.pageWidth
|
||||
const PH = doc.page.pageHeight
|
||||
const { normalizeBookDocument } = require('@trek/shared');
|
||||
const doc = normalizeBookDocument(JSON.parse(row.document));
|
||||
const PW = doc.page.pageWidth;
|
||||
const PH = doc.page.pageHeight;
|
||||
|
||||
const r4 = n => Math.round(n * 10000) / 10000
|
||||
const r4 = (n) => Math.round(n * 10000) / 10000;
|
||||
|
||||
/** A frame as fractions of one page's width and of the page height. */
|
||||
function relFrame(f) {
|
||||
return { x: r4(f.x / PW), y: r4(f.y / PH), w: r4(f.w / PW), h: r4(f.h / PH) }
|
||||
return { x: r4(f.x / PW), y: r4(f.y / PH), w: r4(f.w / PW), h: r4(f.h / PH) };
|
||||
}
|
||||
|
||||
/** Type size as a fraction of the page height, so it scales with the sheet. */
|
||||
const relSize = n => r4(n / PH)
|
||||
const relSize = (n) => r4(n / PH);
|
||||
|
||||
function element(e) {
|
||||
// The id travels with the template and is replaced when it is applied —
|
||||
// dropping it here would leave the element off the BookElement union.
|
||||
const out = { ...e, frame: relFrame(e.frame) }
|
||||
if (typeof out.size === 'number') out.size = relSize(out.size)
|
||||
if (typeof out.radius === 'number') out.radius = r4(out.radius / PW)
|
||||
if (typeof out.strokeWidth === 'number') out.strokeWidth = r4(out.strokeWidth / PW)
|
||||
return out
|
||||
const out = { ...e, frame: relFrame(e.frame) };
|
||||
if (typeof out.size === 'number') out.size = relSize(out.size);
|
||||
if (typeof out.radius === 'number') out.radius = r4(out.radius / PW);
|
||||
if (typeof out.strokeWidth === 'number') out.strokeWidth = r4(out.strokeWidth / PW);
|
||||
return out;
|
||||
}
|
||||
|
||||
const spreads = doc.spreads
|
||||
.map((s, i) => ({ index: i, role: s.role, background: s.background, elements: s.elements.map(element) }))
|
||||
.filter(s => s.role === 'inner')
|
||||
.filter((s) => s.role === 'inner');
|
||||
|
||||
const body = spreads.map((s, i) => ` {
|
||||
const body = spreads
|
||||
.map(
|
||||
(s, i) => ` {
|
||||
id: 'ref-${i + 1}',
|
||||
background: ${JSON.stringify(s.background)},
|
||||
elements: ${JSON.stringify(s.elements, null, 6).replace(/\n/g, '\n ')},
|
||||
},`).join('\n')
|
||||
},`,
|
||||
)
|
||||
.join('\n');
|
||||
|
||||
const file = `import type { BookElement } from '@trek/shared'
|
||||
const file = `import type { BookElement } from '../book.schema';
|
||||
|
||||
/**
|
||||
* The spread templates, as data.
|
||||
@@ -93,17 +98,17 @@ const file = `import type { BookElement } from '@trek/shared'
|
||||
* was drawn.
|
||||
*/
|
||||
|
||||
export interface SpreadTemplate {
|
||||
id: string
|
||||
background: string | null
|
||||
/** Frames and sizes are fractions — see the note above. */
|
||||
elements: BookElement[]
|
||||
export interface AutoTemplate {
|
||||
id: string;
|
||||
background: string | null;
|
||||
/** Frames and sizes are fractions; see the note above. */
|
||||
elements: BookElement[];
|
||||
}
|
||||
|
||||
export const SPREAD_TEMPLATES: SpreadTemplate[] = [
|
||||
export const AUTO_TEMPLATES: readonly AutoTemplate[] = [
|
||||
${body}
|
||||
]
|
||||
`
|
||||
];
|
||||
`;
|
||||
|
||||
fs.writeFileSync(OUT, file)
|
||||
console.log(`wrote ${spreads.length} templates to ${OUT}`)
|
||||
fs.writeFileSync(OUT, file);
|
||||
console.log(`wrote ${spreads.length} templates to ${OUT}`);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
[
|
||||
"src/db/repositories/DayAssignments.repository.ts",
|
||||
"src/db/repositories/Places.repository.ts",
|
||||
"src/db/repositories/Reservations.repository.ts",
|
||||
"src/db/repositories/Trips.repository.ts",
|
||||
"src/db/repositories/Users.repository.ts",
|
||||
"src/nest/atlas/atlas-geo.ts",
|
||||
"src/nest/atlas/atlas.service.ts",
|
||||
"src/nest/auth/auth.service.ts",
|
||||
"src/nest/budget/budget.service.ts",
|
||||
"src/nest/collections/collections.service.ts",
|
||||
"src/nest/doc-sync/doc-sync.service.ts",
|
||||
"src/nest/doc-sync/providers/synology-drive.client.ts",
|
||||
"src/nest/journey/journey-domain.service.ts",
|
||||
"src/nest/journey/journey.controller.ts",
|
||||
"src/nest/packing/packing.service.ts",
|
||||
"src/nest/places/places.mcp.ts",
|
||||
"src/nest/places/places.service.ts",
|
||||
"src/nest/plugins/plugin-runtime.service.ts",
|
||||
"src/nest/plugins/runtime/plugin-sdk.ts",
|
||||
"src/nest/reservations/reservations.mcp.ts",
|
||||
"src/nest/reservations/reservations.service.ts",
|
||||
"src/nest/trips/trips.service.ts",
|
||||
"src/nest/vacay/vacay.service.ts",
|
||||
"tests/unit/db/repositories/Places.repository.test.ts",
|
||||
"tests/unit/nest/atlas.service.test.ts",
|
||||
"tests/unit/nest/budget.service.db.test.ts",
|
||||
"tests/unit/nest/calendar.service.test.ts",
|
||||
"tests/unit/nest/collections.service.test.ts",
|
||||
"tests/unit/nest/doc-sync/doc-sync.service.test.ts",
|
||||
"tests/unit/nest/journey-domain.service.test.ts",
|
||||
"tests/unit/nest/maps.service.test.ts",
|
||||
"tests/unit/nest/places.service.test.ts",
|
||||
"tests/unit/nest/reservations.service.test.ts",
|
||||
"tests/unit/nest/trips.service.test.ts",
|
||||
"tests/unit/nest/vacay.service.test.ts"
|
||||
]
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:format: new server code is formatted with Prettier.
|
||||
*
|
||||
* `npm run format:check` was never part of CI, and most files differ from what
|
||||
* .prettierrc asks for. Formatting all of them belongs in one mechanical
|
||||
* commit of its own; until it lands, the files that were unformatted when
|
||||
* this check came in are listed in scripts/format-baseline.json and the list
|
||||
* only shrinks: every file outside it, a new one in particular, must be
|
||||
* formatted, and a listed file leaves the list once it has been. After the
|
||||
* mass reformat, --update empties the list and the check is a plain
|
||||
* prettier --check over src/ and tests/.
|
||||
*
|
||||
* npm run lint:format check against the baseline (CI)
|
||||
* npm run lint:format -- --list print every unformatted file
|
||||
* npm run lint:format -- --update take formatted and deleted files off the list;
|
||||
* it never adds one
|
||||
*
|
||||
* src/db/entities/ is generated and checked by check:entities instead.
|
||||
*
|
||||
* To format a file: npx prettier --write <file>. The comparison lives in
|
||||
* scripts/lib/format.mjs at the repository root; Prettier and its config come
|
||||
* from this workspace.
|
||||
*/
|
||||
import { check } from '../../scripts/lib/format.mjs';
|
||||
import { runCli } from '../../scripts/lib/ratchet.mjs';
|
||||
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import * as prettier from 'prettier';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
// The entity files are written by scripts/generate-entities.ts and held byte for
|
||||
// byte to its output by check:entities, so their layout is the generator's, not
|
||||
// Prettier's. .prettierignore keeps `npm run format` off them for the same reason.
|
||||
const GENERATED = 'src/db/entities/';
|
||||
await runCli('lint:format', (args) =>
|
||||
check({
|
||||
prettier,
|
||||
root,
|
||||
dirs: ['src', 'tests'],
|
||||
accepts: (key) => key.endsWith('.ts') && !key.startsWith(GENERATED),
|
||||
update: args.includes('--update'),
|
||||
list: args.includes('--list'),
|
||||
}),
|
||||
);
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Regenerates every derived copy of the plugin permission facts from the single source,
|
||||
* server/src/nest/plugins/protocol/envelope.ts.
|
||||
* server/src/nest/plugins/protocol/envelope.ts, plus the output contract
|
||||
* (protocol/output-contract.ts) and the addon ids (src/addons.ts) the SDK publishes.
|
||||
*
|
||||
* node --import tsx server/scripts/gen-plugin-facts.ts # write
|
||||
* node --import tsx server/scripts/gen-plugin-facts.ts --check # exit 1 on drift
|
||||
@@ -14,27 +15,78 @@
|
||||
* plugin-sdk/ checkout with no server present, so a build-time artefact would ship an SDK
|
||||
* with an empty permission list.
|
||||
*/
|
||||
// A relative import of the shared SOURCE, not @trek/shared: the plugin-facts CI job
|
||||
// installs only the server, so shared's dist does not exist there. The file has no
|
||||
// imports of its own for exactly this reason.
|
||||
import {
|
||||
PLUGIN_POI_ICONS,
|
||||
PLUGIN_POI_LABEL_MAX,
|
||||
PLUGIN_POI_MAX_CATEGORIES,
|
||||
} from '../../shared/src/plugins/plugin-poi-facts';
|
||||
import { ADDON_IDS } from '../src/addons';
|
||||
import {
|
||||
HOOK_PERMISSION,
|
||||
KNOWN_METHODS,
|
||||
KNOWN_PERMISSIONS,
|
||||
METHOD_PERMISSION,
|
||||
EVENTS_PERMISSION,
|
||||
JOBS_PERMISSION,
|
||||
USER_DATA_PERMISSION,
|
||||
HTTP_OUTBOUND_PREFIX,
|
||||
PLUGIN_API_VERSION,
|
||||
} from '../src/nest/plugins/protocol/envelope';
|
||||
import {
|
||||
ACTIONS_MAX,
|
||||
ADDON_ID_RE,
|
||||
CAPABILITY_NAME_RE,
|
||||
EGRESS_HOST_RE,
|
||||
MCP_TOOLS_MAX,
|
||||
PLUGIN_CHANNEL_EVENTS,
|
||||
PLUGIN_ID_RE,
|
||||
PLUGIN_SEMVER_RE,
|
||||
PLUGIN_TYPES,
|
||||
REPLACEABLE_TABS,
|
||||
RESERVED_PLUGIN_IDS,
|
||||
RESERVED_SETTING_KEYS,
|
||||
ROUTE_PROFILE_ID_RE,
|
||||
ROUTE_PROFILES_MAX,
|
||||
SETTING_FIELD_KEYS,
|
||||
SETTING_KEY_RE,
|
||||
TOOL_NAME_RE,
|
||||
TRIP_PAGE_POSITION_MAX,
|
||||
WIDGET_SLOTS,
|
||||
} from '../src/nest/plugins/protocol/manifest-rules';
|
||||
import {
|
||||
PLUGIN_ENTITY_CONTRACT,
|
||||
PLUGIN_ENTITY_NESTED,
|
||||
PLUGIN_METHOD_OUTPUT,
|
||||
pluginEntityFields,
|
||||
type PluginEntityName,
|
||||
type PluginMethodOutput,
|
||||
} from '../src/nest/plugins/protocol/output-contract';
|
||||
import { SNAPSHOT_GRANT, ENTITY_ID_KEYS } from '../src/plugin-event-sink';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
HOOK_PERMISSION, KNOWN_METHODS, KNOWN_PERMISSIONS, METHOD_PERMISSION,
|
||||
EVENTS_PERMISSION, JOBS_PERMISSION, USER_DATA_PERMISSION, HTTP_OUTBOUND_PREFIX,
|
||||
} from '../src/nest/plugins/protocol/envelope';
|
||||
import { SNAPSHOT_GRANT, ENTITY_ID_KEYS } from '../src/plugin-event-sink';
|
||||
|
||||
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
|
||||
const HEADER = [
|
||||
'// GENERATED — do not edit by hand.',
|
||||
'// Source: server/src/nest/plugins/protocol/envelope.ts + server/src/plugin-event-sink.ts',
|
||||
'// + server/src/nest/plugins/protocol/manifest-rules.ts',
|
||||
'// + server/src/nest/plugins/protocol/output-contract.ts + server/src/addons.ts',
|
||||
'// + shared/src/plugins/plugin-poi-facts.ts',
|
||||
'// Regenerate: node --import tsx server/scripts/gen-plugin-facts.ts',
|
||||
'',
|
||||
].join('\n');
|
||||
|
||||
const list = (xs: readonly string[]) => xs.map((x) => ` '${x}',`).join('\n');
|
||||
const pairs = (o: Readonly<Record<string, string>>) =>
|
||||
Object.entries(o).map(([k, v]) => ` ${/^[A-Za-z_$][\w$]*$/.test(k) ? k : `'${k}'`}: '${v}',`).join('\n');
|
||||
Object.entries(o)
|
||||
.map(([k, v]) => ` ${/^[A-Za-z_$][\w$]*$/.test(k) ? k : `'${k}'`}: '${v}',`)
|
||||
.join('\n');
|
||||
|
||||
/**
|
||||
* Types here are deliberately WIDE — Readonly<Record<string, string>> and string[] —
|
||||
@@ -46,6 +98,26 @@ const pairs = (o: Readonly<Record<string, string>>) =>
|
||||
*/
|
||||
const EVENT_FAMILIES = [...new Set([...Object.keys(ENTITY_ID_KEYS), ...Object.keys(SNAPSHOT_GRANT)])].sort();
|
||||
|
||||
/** `'trip'`, `'trip[]'`, `'host'` or `'readModel'`: what a method's result is. */
|
||||
const describeOutput = (output: PluginMethodOutput): string =>
|
||||
output.kind === 'entity' ? `${output.entity}${output.many ? '[]' : ''}` : output.kind;
|
||||
|
||||
const fieldList = (fields: readonly string[]) => fields.map((f) => ` '${f}',`).join('\n');
|
||||
const ENTITY_FIELDS = (Object.keys(PLUGIN_ENTITY_CONTRACT) as PluginEntityName[])
|
||||
.map((entity) => ` ${entity}: [\n${fieldList(pluginEntityFields(entity))}\n ],`)
|
||||
.join('\n');
|
||||
|
||||
const ENTITY_NESTED = (Object.keys(PLUGIN_ENTITY_NESTED) as PluginEntityName[])
|
||||
.map((entity) => {
|
||||
const children = Object.entries(PLUGIN_ENTITY_NESTED[entity] ?? {}).map(([key, child]) => `${key}: '${child}'`);
|
||||
return ` ${entity}: { ${children.join(', ')} },`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
const METHOD_RESULT = Object.fromEntries(
|
||||
Object.entries(PLUGIN_METHOD_OUTPUT).map(([method, output]) => [method, describeOutput(output)]),
|
||||
);
|
||||
|
||||
const SDK_FACTS = `${HEADER}
|
||||
export const HOOK_PERMISSION: Readonly<Record<string, string>> = {
|
||||
${pairs(HOOK_PERMISSION)}
|
||||
@@ -82,6 +154,104 @@ ${list(EVENT_FAMILIES)}
|
||||
export const EVENT_SNAPSHOT_GRANT: Readonly<Record<string, string>> = {
|
||||
${pairs(SNAPSHOT_GRANT)}
|
||||
};
|
||||
|
||||
/**
|
||||
* \`capabilities.poiCategories\` (#1781): the lucide icons a category may use, how many
|
||||
* categories one plugin may declare, and the longest label.
|
||||
*/
|
||||
export const POI_CATEGORY_ICONS: string[] = [
|
||||
${list(PLUGIN_POI_ICONS)}
|
||||
];
|
||||
|
||||
export const POI_CATEGORY_MAX = ${PLUGIN_POI_MAX_CATEGORIES};
|
||||
export const POI_CATEGORY_LABEL_MAX = ${PLUGIN_POI_LABEL_MAX};
|
||||
|
||||
/**
|
||||
* The addon ids a manifest's \`requiredAddons\` may name: TREK's ADDON_IDS.
|
||||
*/
|
||||
export const KNOWN_ADDONS: string[] = [
|
||||
${list(Object.values(ADDON_IDS))}
|
||||
];
|
||||
|
||||
/**
|
||||
* The fields each entity result carries, and nothing else: the row's published
|
||||
* columns, then the keys the host adds (joined names, counts, hydrated children).
|
||||
* A column TREK adds later is not delivered until it is listed here. A literal,
|
||||
* unlike the wide tables above, because it is new (nothing published depends on a
|
||||
* wider type) and the SDK's entity interfaces are type-checked against it.
|
||||
*/
|
||||
export const PLUGIN_ENTITY_FIELDS = {
|
||||
${ENTITY_FIELDS}
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* The fields of an entity that hold rows of another entity (one row or a list),
|
||||
* and which one. Those rows carry that entity's PLUGIN_ENTITY_FIELDS and no others,
|
||||
* however deep they sit, so a column TREK adds to a child table is held back the
|
||||
* same way. A field not listed here holds a value TREK builds field by field.
|
||||
*/
|
||||
export const PLUGIN_ENTITY_NESTED: Readonly<Record<string, Readonly<Record<string, string>>>> = {
|
||||
${ENTITY_NESTED}
|
||||
};
|
||||
|
||||
/**
|
||||
* What each ctx method returns: an entity from PLUGIN_ENTITY_FIELDS (\`trip\`, or
|
||||
* \`trip[]\` for a list), \`host\` for a value the host builds itself or data the
|
||||
* plugin owns, or \`readModel\` for a domain read model passed on as the app's own
|
||||
* REST route returns it.
|
||||
*/
|
||||
export const PLUGIN_METHOD_RESULT: Readonly<Record<string, string>> = {
|
||||
${pairs(METHOD_RESULT)}
|
||||
};
|
||||
|
||||
/**
|
||||
* The plugin-API version this TREK implements. A manifest's \`apiVersion\` must be a
|
||||
* positive integer no greater than this, or the install refuses it.
|
||||
*/
|
||||
export const PLUGIN_API_VERSION = ${PLUGIN_API_VERSION} as const;
|
||||
|
||||
/**
|
||||
* The manifest format rules TREK's install loader enforces
|
||||
* (server/src/nest/plugins/protocol/manifest-rules.ts), so \`trek-plugin validate\`
|
||||
* refuses exactly what an install refuses.
|
||||
*/
|
||||
export const MANIFEST_ID_RE = ${PLUGIN_ID_RE};
|
||||
export const MANIFEST_RESERVED_IDS: readonly string[] = [
|
||||
${list(RESERVED_PLUGIN_IDS)}
|
||||
];
|
||||
export const MANIFEST_SEMVER_RE = ${PLUGIN_SEMVER_RE};
|
||||
export const MANIFEST_TYPES: readonly string[] = [
|
||||
${list(PLUGIN_TYPES)}
|
||||
];
|
||||
export const MANIFEST_ADDON_ID_RE = ${ADDON_ID_RE};
|
||||
export const MANIFEST_HOST_RE = ${EGRESS_HOST_RE};
|
||||
export const MANIFEST_WIDGET_SLOTS: readonly string[] = [
|
||||
${list(WIDGET_SLOTS)}
|
||||
];
|
||||
export const MANIFEST_REPLACEABLE_TABS: readonly string[] = [
|
||||
${list(REPLACEABLE_TABS)}
|
||||
];
|
||||
export const MANIFEST_TRIP_PAGE_POSITION_MAX = ${TRIP_PAGE_POSITION_MAX};
|
||||
export const MANIFEST_ROUTE_PROFILES_MAX = ${ROUTE_PROFILES_MAX};
|
||||
export const MANIFEST_ROUTE_PROFILE_ID_RE = ${ROUTE_PROFILE_ID_RE};
|
||||
export const MANIFEST_CAPABILITY_NAME_RE = ${CAPABILITY_NAME_RE};
|
||||
export const MANIFEST_MCP_TOOLS_MAX = ${MCP_TOOLS_MAX};
|
||||
export const MANIFEST_TOOL_NAME_RE = ${TOOL_NAME_RE};
|
||||
export const MANIFEST_SETTING_KEY_RE = ${SETTING_KEY_RE};
|
||||
export const MANIFEST_RESERVED_SETTING_KEYS: readonly string[] = [
|
||||
${list(RESERVED_SETTING_KEYS)}
|
||||
];
|
||||
export const MANIFEST_ACTIONS_MAX = ${ACTIONS_MAX};
|
||||
|
||||
/** Every attribute a settings-field object may carry; the host silently drops anything else. */
|
||||
export const SETTING_FIELD_KEYS = [
|
||||
${list(SETTING_FIELD_KEYS)}
|
||||
] as const;
|
||||
|
||||
/** Events a plugin notification channel may carry. Admin-scoped and in-app-only events are excluded. */
|
||||
export const CHANNEL_EVENTS: string[] = [
|
||||
${list(PLUGIN_CHANNEL_EVENTS)}
|
||||
];
|
||||
`;
|
||||
|
||||
const SHARED_FACTS = `${HEADER}
|
||||
@@ -123,9 +293,7 @@ function coverageProblems(): string[] {
|
||||
const ui = fs.readFileSync(path.join(REPO, 'plugin-sdk/src/cli/ui.ts'), 'utf8');
|
||||
const missingHint = KNOWN_PERMISSIONS.filter((p) => !ui.includes(`'${p}'`));
|
||||
if (missingHint.length) {
|
||||
problems.push(
|
||||
`plugin-sdk/src/cli/ui.ts PERMISSION_FAMILIES does not cover: ${missingHint.join(', ')}`,
|
||||
);
|
||||
problems.push(`plugin-sdk/src/cli/ui.ts PERMISSION_FAMILIES does not cover: ${missingHint.join(', ')}`);
|
||||
}
|
||||
|
||||
return problems;
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* Generates the Kysely database type from the migrated schema.
|
||||
*
|
||||
* Repositories that need a statement the MikroORM QueryBuilder cannot express
|
||||
* go through `this.kysely<...>()`, and Kysely types every table and column it
|
||||
* touches from the type parameter. Those parameters used to be interfaces
|
||||
* written by hand in each repository, so a migration that renamed a column or
|
||||
* made it nullable left them stale while `tsc` stayed green. This script
|
||||
* derives them instead, the same way `generate-entities.ts` derives the
|
||||
* entities: it migrates a throwaway SQLite file with the real migrations,
|
||||
* reads every table's columns back and writes
|
||||
*
|
||||
* src/db/kysely/<Table>.table.ts one interface per table
|
||||
* src/db/kysely/db.ts `DB`, the map from table name to interface
|
||||
*
|
||||
* A repository narrows it with `Pick<DB, 'trips' | 'days'>`.
|
||||
*
|
||||
* The column types describe what the driver hands back, which is the storage
|
||||
* model, not the domain one: an INTEGER flag is `number`, a timestamp is the
|
||||
* `string` it is stored as. A column an insert may leave out (an integer
|
||||
* primary key, anything with a DEFAULT, anything nullable) is
|
||||
* `InsertOptional<T>`, declared in the generated `columns.ts`.
|
||||
*
|
||||
* Usage:
|
||||
* node --import tsx scripts/generate-db-types.ts # rewrite src/db/kysely/
|
||||
* node --import tsx scripts/generate-db-types.ts --check # exit 1 when src/db/kysely/ drifted (CI)
|
||||
*/
|
||||
import { migrateTempDb, tempDbPath } from './generate-entities';
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const SERVER_ROOT = path.join(__dirname, '..');
|
||||
export const KYSELY_DIR = path.join(SERVER_ROOT, 'src/db/kysely');
|
||||
|
||||
/** Tables the application never queries: the migrator's own bookkeeping. */
|
||||
const SKIPPED_TABLES: ReadonlySet<string> = new Set(['mikro_orm_migrations']);
|
||||
|
||||
const HEADER =
|
||||
'// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:\n' +
|
||||
'// change the migration, then run `npm run gen:db-types`.\n';
|
||||
|
||||
export interface ColumnInfo {
|
||||
name: string;
|
||||
/** The declared type as `PRAGMA table_xinfo` reports it (may be empty). */
|
||||
type: string;
|
||||
notnull: boolean;
|
||||
hasDefault: boolean;
|
||||
/** Position in the primary key, 0 when the column is not part of it. */
|
||||
pk: number;
|
||||
/** 0 for an ordinary column, 2 or 3 for a generated (computed) one. */
|
||||
hidden: number;
|
||||
}
|
||||
|
||||
export interface TableInfo {
|
||||
name: string;
|
||||
columns: ColumnInfo[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The TypeScript type a value of this declared type comes back as from
|
||||
* better-sqlite3, following SQLite's affinity rules (sqlite.org/datatype3.html
|
||||
* section 3.1). Date-like declarations have NUMERIC affinity on paper, but
|
||||
* every one of them in this schema holds ISO text, so they read as strings.
|
||||
*/
|
||||
export function tsTypeFor(declared: string): string {
|
||||
const t = declared.toUpperCase();
|
||||
if (t.includes('INT')) return 'number';
|
||||
if (t.includes('CHAR') || t.includes('CLOB') || t.includes('TEXT')) return 'string';
|
||||
if (t.includes('BLOB')) return 'Buffer';
|
||||
if (t.includes('REAL') || t.includes('FLOA') || t.includes('DOUB')) return 'number';
|
||||
if (t.includes('DATE') || t.includes('TIME')) return 'string';
|
||||
if (t.includes('BOOL') || t.includes('NUMERIC') || t.includes('DECIMAL')) return 'number';
|
||||
if (t === '') return 'unknown';
|
||||
throw new Error(`generate-db-types: no TypeScript mapping for the declared column type "${declared}"`);
|
||||
}
|
||||
|
||||
/** `budget_items` -> `BudgetItems`. */
|
||||
export function pascalCase(table: string): string {
|
||||
return table
|
||||
.split('_')
|
||||
.filter((part) => part !== '')
|
||||
.map((part) => part[0].toUpperCase() + part.slice(1))
|
||||
.join('');
|
||||
}
|
||||
|
||||
/** The interface name for a table: `BudgetItemsTable`. */
|
||||
export function interfaceName(table: string): string {
|
||||
return `${pascalCase(table)}Table`;
|
||||
}
|
||||
|
||||
function columnType(table: TableInfo, column: ColumnInfo): string {
|
||||
// A lone INTEGER primary key aliases the rowid: it is never null and the
|
||||
// database assigns it when the insert leaves it out.
|
||||
const pkColumns = table.columns.filter((c) => c.pk > 0);
|
||||
const isRowid = column.pk > 0 && pkColumns.length === 1 && column.type.toUpperCase() === 'INTEGER';
|
||||
const base = tsTypeFor(column.type);
|
||||
const nullable = !column.notnull && column.pk === 0;
|
||||
const value = nullable ? `${base} | null` : base;
|
||||
if (column.hidden === 2 || column.hidden === 3) return `GeneratedAlways<${value}>`;
|
||||
if (isRowid || column.hasDefault || nullable) return `InsertOptional<${value}>`;
|
||||
return value;
|
||||
}
|
||||
|
||||
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
||||
|
||||
function propertyKey(name: string): string {
|
||||
return IDENTIFIER.test(name) ? name : `'${name.replace(/'/g, "\\'")}'`;
|
||||
}
|
||||
|
||||
/** The source of `<Table>.table.ts`. */
|
||||
export function renderTable(table: TableInfo): string {
|
||||
const types = table.columns.map((c) => columnType(table, c));
|
||||
const has = (marker: string) => types.some((t) => t.startsWith(`${marker}<`));
|
||||
// Laid out the way the server's Prettier import sorting leaves them, so the
|
||||
// output passes lint:format as written: the relative import first, one blank
|
||||
// line between the groups, and the header comment on the first import with
|
||||
// no blank line after it. A file without imports keeps its blank line.
|
||||
const groups = [
|
||||
has('InsertOptional') ? "import type { InsertOptional } from './columns';\n" : '',
|
||||
has('GeneratedAlways') ? "import type { GeneratedAlways } from 'kysely';\n" : '',
|
||||
].filter((group) => group !== '');
|
||||
const importBlock = groups.length === 0 ? '\n' : `${groups.join('\n')}\n`;
|
||||
const body = table.columns.map((c, i) => ` ${propertyKey(c.name)}: ${types[i]};`).join('\n');
|
||||
return `${HEADER}${importBlock}export interface ${interfaceName(table.name)} {\n${body}\n}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The source of `columns.ts`. Kysely makes a column optional on insert when its
|
||||
* insert type can be null or undefined, which it tests with `NonNullable`. The
|
||||
* server compiles without `strictNullChecks`, where `T | undefined` and
|
||||
* `T | null` collapse to `T`, so Kysely's own `Generated<T>` would still demand
|
||||
* the column. `void` survives that collapse and still refuses any other value,
|
||||
* so the insert stays typed.
|
||||
*/
|
||||
export function renderColumns(): string {
|
||||
return (
|
||||
`${HEADER}import type { ColumnType } from 'kysely';\n\n` +
|
||||
'/** A column an insert may leave out: the database assigns it (rowid, DEFAULT) or stores NULL. */\n' +
|
||||
'export type InsertOptional<T> = ColumnType<T, T | void, T>;\n'
|
||||
);
|
||||
}
|
||||
|
||||
/** The source of `db.ts`. */
|
||||
export function renderDb(tables: readonly TableInfo[]): string {
|
||||
const imports = tables
|
||||
.map((t) => `import type { ${interfaceName(t.name)} } from './${pascalCase(t.name)}.table';`)
|
||||
.join('\n');
|
||||
const body = tables.map((t) => ` ${propertyKey(t.name)}: ${interfaceName(t.name)};`).join('\n');
|
||||
return (
|
||||
`${HEADER}${imports}\n\n` +
|
||||
"/** Every table of the migrated schema. A repository narrows it: `this.kysely<Pick<DB, 'trips'>>()`. */\n" +
|
||||
`export interface DB {\n${body}\n}\n`
|
||||
);
|
||||
}
|
||||
|
||||
/** Reads every application table of a migrated database, sorted by name, columns in declaration order. */
|
||||
export function readSchema(dbPath: string): TableInfo[] {
|
||||
const conn = new Database(dbPath, { readonly: true });
|
||||
try {
|
||||
const names = conn
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
|
||||
.all() as { name: string }[];
|
||||
return names
|
||||
.filter(({ name }) => !SKIPPED_TABLES.has(name))
|
||||
.map(({ name }) => {
|
||||
const rows = conn.prepare(`PRAGMA table_xinfo("${name.replace(/"/g, '""')}")`).all() as {
|
||||
name: string;
|
||||
type: string;
|
||||
notnull: number;
|
||||
dflt_value: string | null;
|
||||
pk: number;
|
||||
hidden: number;
|
||||
}[];
|
||||
return {
|
||||
name,
|
||||
columns: rows
|
||||
.filter((r) => r.hidden !== 1)
|
||||
.map((r) => ({
|
||||
name: r.name,
|
||||
type: r.type,
|
||||
notnull: r.notnull === 1,
|
||||
hasDefault: r.dflt_value !== null,
|
||||
pk: r.pk,
|
||||
hidden: r.hidden,
|
||||
})),
|
||||
};
|
||||
});
|
||||
} finally {
|
||||
conn.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** File name -> content for everything under src/db/kysely/. */
|
||||
export function renderAll(tables: readonly TableInfo[]): Map<string, string> {
|
||||
if (tables.length === 0) {
|
||||
throw new Error('generate-db-types: the migrated schema has no tables; check the migrations path');
|
||||
}
|
||||
const files = new Map<string, string>();
|
||||
for (const table of tables) files.set(`${pascalCase(table.name)}.table.ts`, renderTable(table));
|
||||
files.set('columns.ts', renderColumns());
|
||||
files.set('db.ts', renderDb(tables));
|
||||
return files;
|
||||
}
|
||||
|
||||
export async function generateDbTypes(): Promise<Map<string, string>> {
|
||||
const dbPath = tempDbPath();
|
||||
try {
|
||||
await migrateTempDb(dbPath);
|
||||
return renderAll(readSchema(dbPath));
|
||||
} finally {
|
||||
fs.rmSync(dbPath, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Every file that differs from, is missing from or is extra in `dir`. Read-only. */
|
||||
export function checkDbTypes(dir: string, files: ReadonlyMap<string, string>): string[] {
|
||||
const drift: string[] = [];
|
||||
for (const [fileName, content] of files) {
|
||||
const onDisk = path.join(dir, fileName);
|
||||
const current = fs.existsSync(onDisk) ? fs.readFileSync(onDisk, 'utf8').replace(/\r\n/g, '\n') : undefined;
|
||||
if (current !== content) drift.push(fileName);
|
||||
}
|
||||
const onDiskFiles = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.endsWith('.ts')) : [];
|
||||
for (const fileName of onDiskFiles) {
|
||||
if (!files.has(fileName)) drift.push(`${fileName} (not produced by the generator)`);
|
||||
}
|
||||
return drift.sort();
|
||||
}
|
||||
|
||||
/** Replaces the contents of `dir` with `files`, removing any .ts file the generator no longer produces. */
|
||||
export function writeDbTypes(dir: string, files: ReadonlyMap<string, string>): void {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
for (const fileName of fs.readdirSync(dir)) {
|
||||
if (fileName.endsWith('.ts') && !files.has(fileName)) fs.rmSync(path.join(dir, fileName));
|
||||
}
|
||||
for (const [fileName, content] of files) fs.writeFileSync(path.join(dir, fileName), content);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const check = process.argv.slice(2).includes('--check');
|
||||
const files = await generateDbTypes();
|
||||
if (check) {
|
||||
const drift = checkDbTypes(KYSELY_DIR, files);
|
||||
for (const fileName of drift) console.error(`[generate-db-types] DRIFT: src/db/kysely/${fileName}`);
|
||||
if (drift.length > 0) {
|
||||
console.error('[generate-db-types] --check failed. Run: npm run gen:db-types');
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`[generate-db-types] --check: ${files.size} files match the migrated schema`);
|
||||
return;
|
||||
}
|
||||
writeDbTypes(KYSELY_DIR, files);
|
||||
console.log(`[generate-db-types] wrote ${files.size} files to src/db/kysely/`);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((err: unknown) => {
|
||||
console.error('[generate-db-types] failed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,421 @@
|
||||
{
|
||||
"fileCycles": [],
|
||||
"domainCycles": [
|
||||
"accommodations -> assignments",
|
||||
"accommodations -> nest-rpc",
|
||||
"accommodations -> places",
|
||||
"assignments -> days",
|
||||
"assignments -> journey",
|
||||
"assignments -> nest-rpc",
|
||||
"atlas -> nest-rpc",
|
||||
"auth -> budget",
|
||||
"auth -> files",
|
||||
"auth -> plugins",
|
||||
"budget -> nest-rpc",
|
||||
"calendar -> days",
|
||||
"calendar -> reservations",
|
||||
"categories -> nest-rpc",
|
||||
"collab -> files",
|
||||
"collab -> nest-rpc",
|
||||
"collections -> nest-rpc",
|
||||
"collections -> places",
|
||||
"day-notes -> nest-rpc",
|
||||
"days -> accommodations",
|
||||
"days -> assignments",
|
||||
"days -> nest-rpc",
|
||||
"days -> places",
|
||||
"files -> nest-rpc",
|
||||
"geo -> maps",
|
||||
"integrations -> assignments",
|
||||
"integrations -> atlas",
|
||||
"integrations -> journey",
|
||||
"integrations -> places",
|
||||
"integrations -> reservations",
|
||||
"journey -> atlas",
|
||||
"journey -> files",
|
||||
"journey -> nest-rpc",
|
||||
"maps -> geo",
|
||||
"memories -> photos",
|
||||
"nest-rpc -> plugins",
|
||||
"packing -> nest-rpc",
|
||||
"photos -> memories",
|
||||
"places -> accommodations",
|
||||
"places -> assignments",
|
||||
"places -> atlas",
|
||||
"places -> journey",
|
||||
"places -> nest-rpc",
|
||||
"plugins -> accommodations",
|
||||
"plugins -> assignments",
|
||||
"plugins -> atlas",
|
||||
"plugins -> budget",
|
||||
"plugins -> categories",
|
||||
"plugins -> collab",
|
||||
"plugins -> collections",
|
||||
"plugins -> day-notes",
|
||||
"plugins -> days",
|
||||
"plugins -> files",
|
||||
"plugins -> journey",
|
||||
"plugins -> nest-rpc",
|
||||
"plugins -> packing",
|
||||
"plugins -> places",
|
||||
"plugins -> reservations",
|
||||
"plugins -> tags",
|
||||
"plugins -> todo",
|
||||
"plugins -> trips",
|
||||
"plugins -> vacay",
|
||||
"plugins -> weather",
|
||||
"reservations -> accommodations",
|
||||
"reservations -> assignments",
|
||||
"reservations -> budget",
|
||||
"reservations -> days",
|
||||
"reservations -> integrations",
|
||||
"reservations -> nest-rpc",
|
||||
"tags -> nest-rpc",
|
||||
"todo -> nest-rpc",
|
||||
"trip-members -> auth",
|
||||
"trip-members -> budget",
|
||||
"trip-members -> trips",
|
||||
"trip-read-model -> accommodations",
|
||||
"trip-read-model -> budget",
|
||||
"trip-read-model -> collab",
|
||||
"trip-read-model -> days",
|
||||
"trip-read-model -> files",
|
||||
"trip-read-model -> packing",
|
||||
"trip-read-model -> places",
|
||||
"trip-read-model -> reservations",
|
||||
"trip-read-model -> todo",
|
||||
"trip-read-model -> trip-members",
|
||||
"trip-read-model -> trips",
|
||||
"trips -> accommodations",
|
||||
"trips -> budget",
|
||||
"trips -> calendar",
|
||||
"trips -> collab",
|
||||
"trips -> days",
|
||||
"trips -> files",
|
||||
"trips -> nest-rpc",
|
||||
"trips -> packing",
|
||||
"trips -> places",
|
||||
"trips -> reservations",
|
||||
"trips -> todo",
|
||||
"trips -> trip-members",
|
||||
"trips -> trip-read-model",
|
||||
"trips -> vacay",
|
||||
"vacay -> nest-rpc",
|
||||
"weather -> nest-rpc"
|
||||
],
|
||||
"sharedImportsDomain": [
|
||||
"nest/common/idempotency-cleanup.job.ts -> nest/audit/audit-log.logger.ts",
|
||||
"nest/common/idempotency-cleanup.job.ts -> nest/scheduling/cron-registrar.service.ts",
|
||||
"nest/common/rowShape.ts -> nest/query-helpers/query-helpers.service.ts",
|
||||
"nest/common/validate-route-guards.ts -> nest/public-api/api-token.guard.ts"
|
||||
],
|
||||
"domainInternals": [
|
||||
"addons -> settings/instance-api-keys.ts",
|
||||
"admin -> llm-parse/llm-config.ts",
|
||||
"atlas -> geo/nominatim.client.ts",
|
||||
"atlas -> public-api/public-api-request.ts",
|
||||
"auth -> maps/providers/places-provider.ts",
|
||||
"auth -> plugins/paths.ts",
|
||||
"auth -> plugins/user-erasure-enqueue.ts",
|
||||
"auth -> settings/instance-api-keys.ts",
|
||||
"auth -> storage/storage-upload.factory.ts",
|
||||
"backup -> permissions/permissions-cache.ts",
|
||||
"backup -> plugins/paths.ts",
|
||||
"backup -> plugins/plugin-backup.ts",
|
||||
"booking-import -> airports/airports.data.ts",
|
||||
"booking-import -> llm-parse/image-input.ts",
|
||||
"collab -> storage/storage-upload.factory.ts",
|
||||
"collections -> places/place-image.ts",
|
||||
"collections -> places/places.dto.ts",
|
||||
"collections -> places/places.helpers.ts",
|
||||
"collections -> storage/storage-upload.factory.ts",
|
||||
"days -> accommodations/night-seat.ts",
|
||||
"doc-sync -> storage/content-type.ts",
|
||||
"files -> storage/content-type.ts",
|
||||
"files -> storage/storage-upload.factory.ts",
|
||||
"geo -> maps/maps.helpers.ts",
|
||||
"integrations -> atlas/atlas-geo.ts",
|
||||
"journey -> atlas/atlas-geo.ts",
|
||||
"journey -> memories/photo-provider.registry.ts",
|
||||
"journey -> storage/storage-upload.factory.ts",
|
||||
"maps -> geo/nominatim.client.ts",
|
||||
"maps -> settings/instance-api-keys.ts",
|
||||
"nest-rpc -> plugins/protocol/envelope.ts",
|
||||
"place-enrichment -> maps/maps.helpers.ts",
|
||||
"place-enrichment -> maps/trek-places.client.ts",
|
||||
"places -> atlas/atlas-geo.ts",
|
||||
"places -> storage/storage-upload.factory.ts",
|
||||
"plugins -> llm-parse/clients/openai-compatible.client.ts",
|
||||
"plugins -> llm-parse/llm-client.factory.ts",
|
||||
"plugins -> llm-parse/llm-config.resolver.ts",
|
||||
"plugins -> llm-parse/llm-config.ts",
|
||||
"plugins -> maps/maps.helpers.ts",
|
||||
"plugins -> notifications/channel-registry.ts",
|
||||
"plugins -> notifications/notification-events.ts",
|
||||
"receipt-scan -> llm-parse/image-input.ts",
|
||||
"reservation-import -> integrations/airtrail.dto.ts",
|
||||
"reservation-import -> llm-parse/image-input.ts",
|
||||
"reservations -> airports/airports.data.ts",
|
||||
"roadtrip -> plugins/contributions/plugin-route-normalize.ts",
|
||||
"roadtrip -> plugins/contributions/plugin-search.helpers.ts",
|
||||
"roadtrip -> plugins/kill-switch.ts",
|
||||
"transit -> maps/maps.helpers.ts",
|
||||
"transit -> settings/instance-api-keys.ts",
|
||||
"trip-members -> trips/trips.dto.ts",
|
||||
"trips -> mcp-shared/prompt-args.ts",
|
||||
"trips -> places/places.helpers.ts",
|
||||
"trips -> storage/storage-upload.factory.ts",
|
||||
"unsplash -> settings/instance-api-keys.ts"
|
||||
],
|
||||
"dbImportsNest": [
|
||||
"db/migrations/Migration20200101010100_encrypt_any_plaintext_oidc_client_secret_left.ts -> nest/common/crypto/apiKeyCrypto.ts",
|
||||
"db/migrations/Migration20200101010200_encrypt_any_plaintext_smtp_pass_left_in.ts -> nest/common/crypto/apiKeyCrypto.ts",
|
||||
"db/migrations/Migration20200101010300_encrypt_any_plaintext_immich_api_key_values.ts -> nest/common/crypto/apiKeyCrypto.ts",
|
||||
"db/orm.ts -> nest/database/request-context.ts",
|
||||
"db/reseat-booked-nights.ts -> nest/accommodations/night-seat.ts"
|
||||
],
|
||||
"foreignRepositories": [
|
||||
"accommodations -> BudgetItems (owned by budget)",
|
||||
"accommodations -> DayAssignments (owned by assignments)",
|
||||
"accommodations -> Days (owned by days)",
|
||||
"accommodations -> Places (owned by places)",
|
||||
"accommodations -> Reservations (owned by reservations)",
|
||||
"accommodations -> RoadtripVias (owned by roadtrip)",
|
||||
"addons -> AppSettings (owned by settings)",
|
||||
"addons -> Users (owned by auth)",
|
||||
"admin -> Addons (owned by addons)",
|
||||
"admin -> AppSettings (owned by settings)",
|
||||
"admin -> AuditLog (owned by audit)",
|
||||
"admin -> DocumentProviders (owned by doc-sync)",
|
||||
"admin -> McpTokens (owned by tokens)",
|
||||
"admin -> OauthTokens (owned by oauth)",
|
||||
"admin -> PhotoProviderFields (owned by addons)",
|
||||
"admin -> PhotoProviders (owned by addons)",
|
||||
"admin -> Places (owned by places)",
|
||||
"admin -> PushSubscriptions (owned by notifications)",
|
||||
"admin -> TripFiles (owned by files)",
|
||||
"admin -> Trips (owned by trips)",
|
||||
"admin -> Users (owned by auth)",
|
||||
"airports -> ReservationEndpoints (owned by reservations)",
|
||||
"airports -> Reservations (owned by reservations)",
|
||||
"assignments -> Days (owned by days)",
|
||||
"assignments -> Places (owned by places)",
|
||||
"assignments -> RoadtripVias (owned by roadtrip)",
|
||||
"assignments -> Tours (owned by tours)",
|
||||
"assignments -> TripMembers (owned by trip-membership)",
|
||||
"atlas -> AppSettings (owned by settings)",
|
||||
"atlas -> Places (owned by places)",
|
||||
"atlas -> ReservationEndpoints (owned by reservations)",
|
||||
"atlas -> Trips (owned by trips)",
|
||||
"audit -> Users (owned by auth)",
|
||||
"auth -> AppSettings (owned by settings)",
|
||||
"auth -> BudgetItems (owned by budget)",
|
||||
"auth -> BudgetSettlements (owned by budget)",
|
||||
"auth -> JourneyContributors (owned by journey)",
|
||||
"auth -> JourneyEntries (owned by journey)",
|
||||
"auth -> JourneyShareTokens (owned by journey)",
|
||||
"auth -> Journeys (owned by journey)",
|
||||
"auth -> McpTokens (owned by tokens)",
|
||||
"auth -> OauthTokens (owned by oauth)",
|
||||
"auth -> PluginUserErasureQueue (owned by plugins)",
|
||||
"auth -> Plugins (owned by plugins)",
|
||||
"auth -> PushSubscriptions (owned by notifications)",
|
||||
"auth -> ShareTokens (owned by share)",
|
||||
"auth -> TripMembers (owned by trip-membership)",
|
||||
"auth -> Trips (owned by trips)",
|
||||
"auth-core -> AppSettings (owned by settings)",
|
||||
"auth-core -> UserSessions (owned by sessions)",
|
||||
"auth-core -> Users (owned by auth)",
|
||||
"auth-core -> WebauthnCredentials (owned by auth)",
|
||||
"backup -> UserSessions (owned by sessions)",
|
||||
"booking-import -> Days (owned by days)",
|
||||
"booking-import -> Reservations (owned by reservations)",
|
||||
"budget -> Places (owned by places)",
|
||||
"budget -> Reservations (owned by reservations)",
|
||||
"budget -> TripMembers (owned by trip-membership)",
|
||||
"budget -> Trips (owned by trips)",
|
||||
"calendar -> DayNotes (owned by day-notes)",
|
||||
"calendar -> Days (owned by days)",
|
||||
"calendar -> Reservations (owned by reservations)",
|
||||
"calendar -> Trips (owned by trips)",
|
||||
"collab -> Trips (owned by trips)",
|
||||
"collections -> Categories (owned by categories)",
|
||||
"collections -> PlaceRatings (owned by places)",
|
||||
"collections -> Places (owned by places)",
|
||||
"collections -> Tags (owned by tags)",
|
||||
"collections -> TripMembers (owned by trip-membership)",
|
||||
"collections -> Trips (owned by trips)",
|
||||
"collections -> Users (owned by auth)",
|
||||
"common -> Users (owned by auth)",
|
||||
"day-notes -> Days (owned by days)",
|
||||
"days -> DayAccommodations (owned by accommodations)",
|
||||
"days -> DayAssignments (owned by assignments)",
|
||||
"days -> DayNotes (owned by day-notes)",
|
||||
"days -> ReservationEndpoints (owned by reservations)",
|
||||
"days -> Reservations (owned by reservations)",
|
||||
"days -> RoadtripDayBoundaries (owned by roadtrip)",
|
||||
"days -> RoadtripVias (owned by roadtrip)",
|
||||
"days -> Trips (owned by trips)",
|
||||
"doc-sync -> AppSettings (owned by settings)",
|
||||
"doc-sync -> FileLinks (owned by files)",
|
||||
"doc-sync -> TripFiles (owned by files)",
|
||||
"doc-sync -> Trips (owned by trips)",
|
||||
"feeds -> Trips (owned by trips)",
|
||||
"feeds -> Users (owned by auth)",
|
||||
"files -> AppSettings (owned by settings)",
|
||||
"files -> BudgetItems (owned by budget)",
|
||||
"files -> DayAssignments (owned by assignments)",
|
||||
"files -> Places (owned by places)",
|
||||
"files -> Reservations (owned by reservations)",
|
||||
"files -> UserSessions (owned by sessions)",
|
||||
"files -> Users (owned by auth)",
|
||||
"google-quota -> AppSettings (owned by settings)",
|
||||
"integrations -> AppSettings (owned by settings)",
|
||||
"integrations -> BucketList (owned by atlas)",
|
||||
"integrations -> Days (owned by days)",
|
||||
"integrations -> Places (owned by places)",
|
||||
"integrations -> ReservationEndpoints (owned by reservations)",
|
||||
"integrations -> Reservations (owned by reservations)",
|
||||
"integrations -> Trips (owned by trips)",
|
||||
"integrations -> Users (owned by auth)",
|
||||
"journey -> Places (owned by places)",
|
||||
"journey -> Trips (owned by trips)",
|
||||
"llm-parse -> Addons (owned by addons)",
|
||||
"maps -> AppSettings (owned by settings)",
|
||||
"maps -> Places (owned by places)",
|
||||
"maps -> Users (owned by auth)",
|
||||
"mcp-shared -> Trips (owned by trips)",
|
||||
"mcp-shared -> Users (owned by auth)",
|
||||
"memories -> JourneyContributors (owned by journey)",
|
||||
"memories -> JourneyPhotos (owned by journey)",
|
||||
"memories -> Journeys (owned by journey)",
|
||||
"memories -> PhotoProviders (owned by addons)",
|
||||
"memories -> TrekPhotos (owned by photos)",
|
||||
"memories -> TripPhotos (owned by photos)",
|
||||
"memories -> Trips (owned by trips)",
|
||||
"memories -> Users (owned by auth)",
|
||||
"nest-rpc -> Trips (owned by trips)",
|
||||
"nest-rpc -> Users (owned by auth)",
|
||||
"notifications -> AppSettings (owned by settings)",
|
||||
"notifications -> Settings (owned by settings)",
|
||||
"notifications -> TodoItems (owned by todo)",
|
||||
"notifications -> Trips (owned by trips)",
|
||||
"notifications -> Users (owned by auth)",
|
||||
"oidc -> AppSettings (owned by settings)",
|
||||
"oidc -> InviteTokens (owned by auth)",
|
||||
"oidc -> Users (owned by auth)",
|
||||
"packing -> TripMembers (owned by trip-membership)",
|
||||
"packing -> Trips (owned by trips)",
|
||||
"permissions -> AppSettings (owned by settings)",
|
||||
"permissions -> Trips (owned by trips)",
|
||||
"photos -> JourneyPhotos (owned by journey)",
|
||||
"place-enrichment -> AppSettings (owned by settings)",
|
||||
"place-enrichment -> PlaceDetailsCache (owned by maps)",
|
||||
"place-photos -> CollectionPlaces (owned by collections)",
|
||||
"place-photos -> Places (owned by places)",
|
||||
"place-shadow -> AppSettings (owned by settings)",
|
||||
"places -> BudgetItems (owned by budget)",
|
||||
"places -> Categories (owned by categories)",
|
||||
"places -> CollectionPlaces (owned by collections)",
|
||||
"places -> DayAssignments (owned by assignments)",
|
||||
"places -> Tags (owned by tags)",
|
||||
"places -> TripMembers (owned by trip-membership)",
|
||||
"places -> Trips (owned by trips)",
|
||||
"platform -> Photos (owned by photos)",
|
||||
"platform -> ShareTokens (owned by share)",
|
||||
"platform -> UserSessions (owned by sessions)",
|
||||
"platform -> Users (owned by auth)",
|
||||
"plugins -> DayAccommodations (owned by accommodations)",
|
||||
"plugins -> Days (owned by days)",
|
||||
"plugins -> JourneyEntries (owned by journey)",
|
||||
"plugins -> NotificationChannelPreferences (owned by notifications)",
|
||||
"plugins -> Places (owned by places)",
|
||||
"plugins -> Reservations (owned by reservations)",
|
||||
"plugins -> Settings (owned by settings)",
|
||||
"plugins -> Trips (owned by trips)",
|
||||
"plugins -> UserSessions (owned by sessions)",
|
||||
"plugins -> Users (owned by auth)",
|
||||
"public-api -> BucketList (owned by atlas)",
|
||||
"public-api -> DayNotes (owned by day-notes)",
|
||||
"public-api -> Days (owned by days)",
|
||||
"public-api -> Places (owned by places)",
|
||||
"public-api -> Reservations (owned by reservations)",
|
||||
"public-api -> Trips (owned by trips)",
|
||||
"query-helpers -> AssignmentParticipants (owned by assignments)",
|
||||
"query-helpers -> PlaceRatings (owned by places)",
|
||||
"query-helpers -> Tags (owned by tags)",
|
||||
"realtime -> AppSettings (owned by settings)",
|
||||
"realtime -> Users (owned by auth)",
|
||||
"reservations -> BudgetItems (owned by budget)",
|
||||
"reservations -> DayAccommodations (owned by accommodations)",
|
||||
"reservations -> DayAssignments (owned by assignments)",
|
||||
"reservations -> Days (owned by days)",
|
||||
"reservations -> Places (owned by places)",
|
||||
"reservations -> TripMembers (owned by trip-membership)",
|
||||
"reservations -> Trips (owned by trips)",
|
||||
"reservations -> Users (owned by auth)",
|
||||
"roadtrip -> DayAccommodations (owned by accommodations)",
|
||||
"roadtrip -> DayAssignments (owned by assignments)",
|
||||
"roadtrip -> Days (owned by days)",
|
||||
"roadtrip -> Places (owned by places)",
|
||||
"roadtrip -> Plugins (owned by plugins)",
|
||||
"roadtrip -> ReservationDayPositions (owned by reservations)",
|
||||
"roadtrip -> ReservationEndpoints (owned by reservations)",
|
||||
"roadtrip -> Reservations (owned by reservations)",
|
||||
"roadtrip -> Users (owned by auth)",
|
||||
"route-usage -> AppSettings (owned by settings)",
|
||||
"school-holidays -> VacayHolidayCalendars (owned by vacay)",
|
||||
"share -> BudgetItems (owned by budget)",
|
||||
"share -> Categories (owned by categories)",
|
||||
"share -> CollabMessages (owned by collab)",
|
||||
"share -> DayAssignments (owned by assignments)",
|
||||
"share -> DayNotes (owned by day-notes)",
|
||||
"share -> Days (owned by days)",
|
||||
"share -> PackingItems (owned by packing)",
|
||||
"share -> Places (owned by places)",
|
||||
"share -> Reservations (owned by reservations)",
|
||||
"share -> Trips (owned by trips)",
|
||||
"storage -> AppSettings (owned by settings)",
|
||||
"system-notices -> AppSettings (owned by settings)",
|
||||
"system-notices -> Trips (owned by trips)",
|
||||
"system-notices -> Users (owned by auth)",
|
||||
"todo -> TripMembers (owned by trip-membership)",
|
||||
"tokens -> Users (owned by auth)",
|
||||
"tours -> Places (owned by places)",
|
||||
"transit -> AppSettings (owned by settings)",
|
||||
"transit -> Users (owned by auth)",
|
||||
"trip-members -> TripMembers (owned by trip-membership)",
|
||||
"trip-members -> Trips (owned by trips)",
|
||||
"trip-members -> Users (owned by auth)",
|
||||
"trip-membership -> Trips (owned by trips)",
|
||||
"trip-read-model -> Trips (owned by trips)",
|
||||
"trips -> AssignmentParticipants (owned by assignments)",
|
||||
"trips -> BudgetCategoryOrder (owned by budget)",
|
||||
"trips -> BudgetItemMembers (owned by budget)",
|
||||
"trips -> BudgetItemPayers (owned by budget)",
|
||||
"trips -> BudgetItems (owned by budget)",
|
||||
"trips -> DayAccommodations (owned by accommodations)",
|
||||
"trips -> DayAssignments (owned by assignments)",
|
||||
"trips -> DayNotes (owned by day-notes)",
|
||||
"trips -> Days (owned by days)",
|
||||
"trips -> JourneyEntries (owned by journey)",
|
||||
"trips -> PackingBags (owned by packing)",
|
||||
"trips -> PackingItems (owned by packing)",
|
||||
"trips -> Places (owned by places)",
|
||||
"trips -> Reservations (owned by reservations)",
|
||||
"trips -> RoadtripDayBoundaries (owned by roadtrip)",
|
||||
"trips -> RoadtripDayTracks (owned by roadtrip)",
|
||||
"trips -> RoadtripPreferences (owned by roadtrip)",
|
||||
"trips -> RoadtripVias (owned by roadtrip)",
|
||||
"trips -> Tags (owned by tags)",
|
||||
"trips -> TodoItems (owned by todo)",
|
||||
"trips -> TourWaypoints (owned by tours)",
|
||||
"trips -> Tours (owned by tours)",
|
||||
"trips -> TripMembers (owned by trip-membership)",
|
||||
"trips -> Users (owned by auth)",
|
||||
"unsplash -> AppSettings (owned by settings)",
|
||||
"unsplash -> Users (owned by auth)",
|
||||
"vacay -> SchoolHolidayRegions (owned by school-holidays)"
|
||||
],
|
||||
"providersImportOrchestrator": []
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:boundaries: the server's import graph may only get cleaner.
|
||||
*
|
||||
* Nest resolves a module's `imports` array while the file is still loading, so
|
||||
* an import cycle shows up at runtime as "imports[1] is undefined" (see
|
||||
* src/nest/storage/storage.module.ts), and every new reach into another
|
||||
* domain's internals is one more place a split has to untangle later. Both
|
||||
* were held only by review. This walks every .ts file under src/ with the
|
||||
* TypeScript parser and checks five rules against scripts/import-boundaries-baseline.json:
|
||||
*
|
||||
* fileCycles a runtime import edge between two files that sit on the
|
||||
* same cycle. Type-only imports and lazy ones (import(),
|
||||
* a require() inside a function) are erased or deferred, so
|
||||
* they cannot take part in a load-time cycle and are skipped.
|
||||
* So are the imports of src/db/entities/: MikroORM relations
|
||||
* point both ways by design and are read through `() => X`
|
||||
* thunks after every file has loaded.
|
||||
* domainCycles the same, between src/nest/<domain> folders (and the
|
||||
* layers in LAYERS, src/nest-rpc, src/nest-mcp and src/mcp,
|
||||
* each counted as one domain): domain A
|
||||
* imports from B while B (directly or through others)
|
||||
* imports from A. Keyed by the domain pair, so a further
|
||||
* import along a dependency that already exists is not new;
|
||||
* a new dependency between two domains of the same cycle is.
|
||||
* The shared kernel folders are left out here and held by
|
||||
* the next rule instead.
|
||||
* sharedImportsDomain
|
||||
* a file of the shared kernel (src/nest/common, database,
|
||||
* app-config, auth-core), which every domain imports,
|
||||
* importing from a domain. That ties the domain into every other one.
|
||||
* domainInternals a file in src/nest/<A>/ importing (value or type) a
|
||||
* file of src/nest/<B>/ that is not B's public surface.
|
||||
* Public is what the codebase already treats that way: the
|
||||
* *.module, *.service, *.guard, *.decorator, *.types,
|
||||
* *.interface, *.contract, *.constants and *.logger files,
|
||||
* the shared kernel folders (common, database, app-config)
|
||||
* and the few entry points in PUBLIC_FILES. Keyed by the
|
||||
* importing domain, so moving a file inside A changes nothing.
|
||||
* dbImportsNest a file under src/db/ importing from src/nest/. The data
|
||||
* layer sits below the domains, never the other way round.
|
||||
* foreignRepositories
|
||||
* a class in src/nest/<A>/ (or one of LAYERS) reaching the
|
||||
* repository of an entity another domain owns, through
|
||||
* @InjectRepository(X) or a getRepository(X) call on an
|
||||
* EntityManager. Ownership is
|
||||
* the map in scripts/repository-owners.json (entity class ->
|
||||
* owning domain folder); an injected entity missing from it
|
||||
* stops the run. Keyed by domain and entity, so a second
|
||||
* injection of an entity the domain already reads is not new.
|
||||
* Asking the owner instead (a service such as
|
||||
* trip-membership's TripAccessService) is what shrinks it.
|
||||
* providersImportOrchestrator
|
||||
* a file under a providers/ folder of src/nest/<A>/
|
||||
* importing (value or type) A's own orchestrator,
|
||||
* nest/<A>/<A>.service.ts, or MapsService from any domain.
|
||||
* A provider knows how to ask one source; which source
|
||||
* answers is the orchestrator's decision, so the dependency
|
||||
* only ever points from the orchestrator to its providers.
|
||||
*
|
||||
* Each rule's baseline lists today's violations. A violation not in it fails
|
||||
* the check, and so does an entry that no longer occurs, until --update drops
|
||||
* it: a stale entry would let the same violation back in unseen.
|
||||
*
|
||||
* npm run lint:boundaries check against the baseline (CI)
|
||||
* npm run lint:boundaries -- --update drop the entries that no longer occur;
|
||||
* it never adds one
|
||||
*
|
||||
* --dir=<path> points the check at another server root (the unit tests use it).
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname, join, relative, resolve, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const ts = require('typescript');
|
||||
|
||||
export const RULES = [
|
||||
'fileCycles',
|
||||
'domainCycles',
|
||||
'sharedImportsDomain',
|
||||
'domainInternals',
|
||||
'dbImportsNest',
|
||||
'foreignRepositories',
|
||||
'providersImportOrchestrator',
|
||||
];
|
||||
|
||||
/**
|
||||
* Folders under src/nest whose every file is shared infrastructure, open to all domains.
|
||||
* auth-core holds the request-auth primitives (the guards, the decorators, JWT
|
||||
* verification, ephemeral tokens) every controller needs; it imports no domain.
|
||||
*/
|
||||
export const SHARED_DOMAINS = new Set(['common', 'database', 'app-config', 'auth-core']);
|
||||
|
||||
/** File name suffixes that make up a domain's public surface. */
|
||||
export const PUBLIC_SUFFIXES = [
|
||||
'.module.ts',
|
||||
'.service.ts',
|
||||
'.guard.ts',
|
||||
'.decorator.ts',
|
||||
'.types.ts',
|
||||
'.interface.ts',
|
||||
'.contract.ts',
|
||||
'.constants.ts',
|
||||
'.logger.ts',
|
||||
];
|
||||
|
||||
/**
|
||||
* Entry points that are public although their name does not say so: the
|
||||
* gates and helpers every controller shares. (The plugin RPC kit every
|
||||
* domain's *.rpc.ts is written against sits outside src/nest, in
|
||||
* src/nest-rpc, next to src/nest-mcp.) Adding to this list is a design
|
||||
* decision for review, not a way past the check.
|
||||
*/
|
||||
export const PUBLIC_FILES = [
|
||||
'audit/client-ip.ts',
|
||||
'addons/addon-gate.ts',
|
||||
'addons/mcp-addon-gate.ts',
|
||||
// The maps domain's outbound clients. MapsModule exports them so enrichment
|
||||
// asks Google and Wikimedia directly instead of through a MapsService facade.
|
||||
'maps/providers/google-places.provider.ts',
|
||||
'maps/providers/osm.client.ts',
|
||||
'maps/providers/wikimedia.client.ts',
|
||||
];
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path, files);
|
||||
else if (/\.ts$/.test(name) && !/\.d\.ts$/.test(name)) files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function resolveSpecifier(fromFile, spec) {
|
||||
if (!spec.startsWith('.')) return null;
|
||||
const base = resolve(dirname(fromFile), spec.replace(/\.js$/, ''));
|
||||
for (const candidate of [`${base}.ts`, join(base, 'index.ts'), base]) {
|
||||
if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** True when every name an import declaration brings in is type-only. */
|
||||
function isTypeOnlyImport(node) {
|
||||
const clause = node.importClause;
|
||||
if (!clause) return false; // `import './x'` runs the file.
|
||||
if (clause.isTypeOnly) return true;
|
||||
if (clause.name) return false;
|
||||
const bindings = clause.namedBindings;
|
||||
if (!bindings || !ts.isNamedImports(bindings)) return false;
|
||||
return bindings.elements.length > 0 && bindings.elements.every((el) => el.isTypeOnly);
|
||||
}
|
||||
|
||||
function isTypeOnlyExport(node) {
|
||||
if (node.isTypeOnly) return true;
|
||||
const clause = node.exportClause;
|
||||
return Boolean(
|
||||
clause && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((el) => el.isTypeOnly),
|
||||
);
|
||||
}
|
||||
|
||||
/** Every relative import of a file: { spec, runtime } where runtime means eager and not erased. */
|
||||
export function importsOf(text, fileName = 'file.ts') {
|
||||
const sf = ts.createSourceFile(fileName, text, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS);
|
||||
const found = [];
|
||||
const add = (spec, runtime) => found.push({ spec, runtime });
|
||||
for (const stmt of sf.statements) {
|
||||
if (ts.isImportDeclaration(stmt) && ts.isStringLiteral(stmt.moduleSpecifier)) {
|
||||
add(stmt.moduleSpecifier.text, !isTypeOnlyImport(stmt));
|
||||
} else if (ts.isExportDeclaration(stmt) && stmt.moduleSpecifier && ts.isStringLiteral(stmt.moduleSpecifier)) {
|
||||
add(stmt.moduleSpecifier.text, !isTypeOnlyExport(stmt));
|
||||
} else if (
|
||||
ts.isImportEqualsDeclaration(stmt) &&
|
||||
ts.isExternalModuleReference(stmt.moduleReference) &&
|
||||
ts.isStringLiteral(stmt.moduleReference.expression)
|
||||
) {
|
||||
add(stmt.moduleReference.expression.text, !stmt.isTypeOnly);
|
||||
}
|
||||
}
|
||||
// require() and import() anywhere: eager only when the require sits in top-level code.
|
||||
const visit = (node, depth) => {
|
||||
if (ts.isCallExpression(node) && node.arguments.length === 1 && ts.isStringLiteral(node.arguments[0])) {
|
||||
const isRequire = ts.isIdentifier(node.expression) && node.expression.text === 'require';
|
||||
const isDynamic = node.expression.kind === ts.SyntaxKind.ImportKeyword;
|
||||
if (isRequire || isDynamic) add(node.arguments[0].text, isRequire && depth === 0);
|
||||
}
|
||||
const inner = ts.isFunctionLike(node) ? depth + 1 : depth;
|
||||
ts.forEachChild(node, (child) => visit(child, inner));
|
||||
};
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isImportDeclaration(stmt) && !ts.isExportDeclaration(stmt) && !ts.isImportEqualsDeclaration(stmt))
|
||||
visit(stmt, 0);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** All resolved relative import edges under src/, as src-relative POSIX paths. */
|
||||
export function collectEdges(serverDir) {
|
||||
const src = join(serverDir, 'src');
|
||||
if (!existsSync(src) || !statSync(src).isDirectory()) {
|
||||
throw new Error(`src/ does not exist under ${serverDir}: the check would pass without looking at anything`);
|
||||
}
|
||||
const rel = (p) => relative(src, p).split(sep).join('/');
|
||||
const edges = [];
|
||||
const unresolved = [];
|
||||
for (const file of walk(src)) {
|
||||
for (const { spec, runtime } of importsOf(readFileSync(file, 'utf8'), file)) {
|
||||
if (!spec.startsWith('.')) continue;
|
||||
const target = resolveSpecifier(file, spec);
|
||||
if (!target) {
|
||||
unresolved.push(`${rel(file)} -> ${spec}`);
|
||||
continue;
|
||||
}
|
||||
if (target.startsWith(src + sep)) edges.push({ from: rel(file), to: rel(target), runtime });
|
||||
}
|
||||
}
|
||||
return { edges, unresolved };
|
||||
}
|
||||
|
||||
/** Tarjan's strongly connected components; returns a node -> component id map for components of size > 1. */
|
||||
function cyclicComponents(graph) {
|
||||
let index = 0;
|
||||
const idx = new Map();
|
||||
const low = new Map();
|
||||
const onStack = new Set();
|
||||
const stack = [];
|
||||
const component = new Map();
|
||||
let next = 0;
|
||||
const strong = (v) => {
|
||||
// Iterative, so a deep import chain cannot overflow the call stack.
|
||||
const work = [[v, 0]];
|
||||
idx.set(v, index);
|
||||
low.set(v, index);
|
||||
index++;
|
||||
stack.push(v);
|
||||
onStack.add(v);
|
||||
while (work.length) {
|
||||
const frame = work[work.length - 1];
|
||||
const [node, i] = frame;
|
||||
const targets = [...(graph.get(node) ?? [])];
|
||||
if (i < targets.length) {
|
||||
frame[1]++;
|
||||
const w = targets[i];
|
||||
if (!idx.has(w)) {
|
||||
idx.set(w, index);
|
||||
low.set(w, index);
|
||||
index++;
|
||||
stack.push(w);
|
||||
onStack.add(w);
|
||||
work.push([w, 0]);
|
||||
} else if (onStack.has(w)) {
|
||||
low.set(node, Math.min(low.get(node), idx.get(w)));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
work.pop();
|
||||
if (work.length) {
|
||||
const parent = work[work.length - 1][0];
|
||||
low.set(parent, Math.min(low.get(parent), low.get(node)));
|
||||
}
|
||||
if (low.get(node) === idx.get(node)) {
|
||||
const members = [];
|
||||
let w;
|
||||
do {
|
||||
w = stack.pop();
|
||||
onStack.delete(w);
|
||||
members.push(w);
|
||||
} while (w !== node);
|
||||
if (members.length > 1) {
|
||||
for (const m of members) component.set(m, next);
|
||||
next++;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const v of graph.keys()) if (!idx.has(v)) strong(v);
|
||||
return component;
|
||||
}
|
||||
|
||||
function cycleEdges(pairs) {
|
||||
const graph = new Map();
|
||||
for (const [a, b] of pairs) {
|
||||
if (a === b) continue;
|
||||
if (!graph.has(a)) graph.set(a, new Set());
|
||||
if (!graph.has(b)) graph.set(b, new Set());
|
||||
graph.get(a).add(b);
|
||||
}
|
||||
const component = cyclicComponents(graph);
|
||||
const out = new Set();
|
||||
for (const [a, targets] of graph) {
|
||||
for (const b of targets) {
|
||||
if (component.has(a) && component.get(a) === component.get(b)) out.add(`${a} -> ${b}`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Layers outside src/nest that work like a domain of their own: the plugin RPC
|
||||
* kit, the MCP decorator layer and the process-wide MCP state. They import
|
||||
* domains and domains import them, so they take part in domainCycles and
|
||||
* foreignRepositories under their folder name; moving a file out of src/nest
|
||||
* does not take its edges out of the count.
|
||||
*/
|
||||
export const LAYERS = ['nest-rpc', 'nest-mcp', 'mcp'];
|
||||
|
||||
/** The domain a src/-relative path belongs to: nest/<domain>/..., one of LAYERS, or null. */
|
||||
export const domainOf = (file) => {
|
||||
const nest = file.match(/^nest\/([^/]+)\//)?.[1];
|
||||
if (nest) return nest;
|
||||
const top = file.split('/')[0];
|
||||
return file.includes('/') && LAYERS.includes(top) ? top : null;
|
||||
};
|
||||
|
||||
/** The orchestrators no provider may import: its own domain's main service, and MapsService everywhere. */
|
||||
function isOrchestratorOf(providerFile, target) {
|
||||
const domain = domainOf(providerFile);
|
||||
return target === `nest/${domain}/${domain}.service.ts` || target === 'nest/maps/maps.service.ts';
|
||||
}
|
||||
|
||||
const isProviderFile = (file) => /^nest\/[^/]+\/(?:.+\/)?providers\//.test(file);
|
||||
|
||||
export function isPublic(target) {
|
||||
// A layer outside src/nest is a toolkit every domain is written against.
|
||||
if (!target.startsWith('nest/')) return true;
|
||||
const inner = target.slice('nest/'.length);
|
||||
const domain = inner.split('/')[0];
|
||||
if (SHARED_DOMAINS.has(domain)) return true;
|
||||
if (PUBLIC_FILES.some((p) => (p.endsWith('/') ? inner.startsWith(p) : inner === p))) return true;
|
||||
return PUBLIC_SUFFIXES.some((s) => target.endsWith(s));
|
||||
}
|
||||
|
||||
/**
|
||||
* The entity classes a file reaches a repository of: `@InjectRepository(X)`
|
||||
* and `<anything>.getRepository(X)`, read from the syntax tree so a comment or
|
||||
* a string naming them does not count.
|
||||
*/
|
||||
export function repositoryEntitiesOf(text, fileName = 'file.ts') {
|
||||
const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
|
||||
const found = [];
|
||||
const visit = (node) => {
|
||||
if (ts.isCallExpression(node) && node.arguments.length > 0 && ts.isIdentifier(node.arguments[0])) {
|
||||
const callee = node.expression;
|
||||
const name = ts.isIdentifier(callee)
|
||||
? callee.text
|
||||
: ts.isPropertyAccessExpression(callee)
|
||||
? callee.name.text
|
||||
: null;
|
||||
if (name === 'InjectRepository' || name === 'getRepository') found.push(node.arguments[0].text);
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(source);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Every repository a class under src/nest or one of LAYERS reaches: { domain, entity, file }. */
|
||||
export function collectRepositoryInjections(serverDir) {
|
||||
const src = join(serverDir, 'src');
|
||||
const found = [];
|
||||
for (const top of ['nest', ...LAYERS]) {
|
||||
const dir = join(src, top);
|
||||
if (!existsSync(dir)) continue;
|
||||
for (const file of walk(dir)) {
|
||||
const rel = relative(src, file).split(sep).join('/');
|
||||
const domain = domainOf(rel);
|
||||
if (!domain) continue;
|
||||
for (const entity of repositoryEntitiesOf(readFileSync(file, 'utf8'), file)) {
|
||||
found.push({ domain, entity, file: rel });
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** scripts/repository-owners.json: entity class -> owning domain. Missing is an empty map. */
|
||||
export function readOwners(path) {
|
||||
if (!existsSync(path)) return {};
|
||||
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error('scripts/repository-owners.json must map each entity class to its owning domain');
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** foreignRepositories keys, plus the injected entities the owner map does not know. */
|
||||
export function analyseRepositories(injections, owners) {
|
||||
const foreign = new Set();
|
||||
const unowned = new Set();
|
||||
for (const { domain, entity, file } of injections) {
|
||||
const owner = owners[entity];
|
||||
if (typeof owner !== 'string') {
|
||||
unowned.add(`${entity} (${file})`);
|
||||
continue;
|
||||
}
|
||||
if (owner !== domain) foreign.add(`${domain} -> ${entity} (owned by ${owner})`);
|
||||
}
|
||||
return { foreignRepositories: [...foreign].sort(), unowned: [...unowned].sort() };
|
||||
}
|
||||
|
||||
/** The violations of every rule, each a sorted list of stable string keys. */
|
||||
export function analyse(edges) {
|
||||
const runtime = edges.filter((e) => e.runtime);
|
||||
const fileCycles = cycleEdges(runtime.filter((e) => !e.from.startsWith('db/entities/')).map((e) => [e.from, e.to]));
|
||||
|
||||
const domainPairs = [];
|
||||
for (const e of runtime) {
|
||||
const a = domainOf(e.from);
|
||||
const b = domainOf(e.to);
|
||||
if (a && b && a !== b && !SHARED_DOMAINS.has(a) && !SHARED_DOMAINS.has(b)) domainPairs.push([a, b]);
|
||||
}
|
||||
const domainCycles = cycleEdges(domainPairs);
|
||||
|
||||
const sharedImportsDomain = new Set();
|
||||
const domainInternals = new Set();
|
||||
const dbImportsNest = new Set();
|
||||
const providersImportOrchestrator = new Set();
|
||||
for (const e of edges) {
|
||||
const a = domainOf(e.from);
|
||||
const b = domainOf(e.to);
|
||||
if (a && b && SHARED_DOMAINS.has(a) && !SHARED_DOMAINS.has(b)) sharedImportsDomain.add(`${e.from} -> ${e.to}`);
|
||||
if (a && b && a !== b && !isPublic(e.to)) domainInternals.add(`${a} -> ${e.to.slice('nest/'.length)}`);
|
||||
if (e.from.startsWith('db/') && e.to.startsWith('nest/')) dbImportsNest.add(`${e.from} -> ${e.to}`);
|
||||
if (isProviderFile(e.from) && isOrchestratorOf(e.from, e.to))
|
||||
providersImportOrchestrator.add(`${e.from} -> ${e.to}`);
|
||||
}
|
||||
const sorted = (set) => [...set].sort();
|
||||
return {
|
||||
fileCycles: sorted(fileCycles),
|
||||
domainCycles: sorted(domainCycles),
|
||||
sharedImportsDomain: sorted(sharedImportsDomain),
|
||||
domainInternals: sorted(domainInternals),
|
||||
dbImportsNest: sorted(dbImportsNest),
|
||||
foreignRepositories: [],
|
||||
providersImportOrchestrator: sorted(providersImportOrchestrator),
|
||||
};
|
||||
}
|
||||
|
||||
/** The baseline as committed. Missing, unreadable or malformed stops the run. */
|
||||
export function readBaseline(path) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||||
} catch (err) {
|
||||
throw new Error(`scripts/import-boundaries-baseline.json cannot be read: ${err.message}`);
|
||||
}
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error('scripts/import-boundaries-baseline.json must be an object with one list per rule');
|
||||
}
|
||||
for (const rule of RULES) {
|
||||
if (!Array.isArray(parsed[rule]) || !parsed[rule].every((entry) => typeof entry === 'string')) {
|
||||
throw new Error(`scripts/import-boundaries-baseline.json: "${rule}" must be a list of strings`);
|
||||
}
|
||||
}
|
||||
const unknown = Object.keys(parsed).filter((key) => !RULES.includes(key));
|
||||
if (unknown.length) throw new Error(`scripts/import-boundaries-baseline.json: unknown rule(s) ${unknown.join(', ')}`);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function compare(baseline, found) {
|
||||
const added = {};
|
||||
const gone = {};
|
||||
for (const rule of RULES) {
|
||||
const allowed = new Set(baseline[rule]);
|
||||
const now = new Set(found[rule]);
|
||||
added[rule] = found[rule].filter((key) => !allowed.has(key));
|
||||
gone[rule] = baseline[rule].filter((key) => !now.has(key));
|
||||
}
|
||||
return { added, gone };
|
||||
}
|
||||
|
||||
const HINTS = {
|
||||
fileCycles:
|
||||
'This import closes a load-time cycle. Move the shared piece into a file both can import, or make the import type-only.',
|
||||
domainCycles:
|
||||
'This makes two domains depend on each other. Invert the dependency (an event, a port the other side implements) or move the shared piece into a domain both can import.',
|
||||
domainInternals:
|
||||
"This reaches into another domain's internals. Go through its service or module, or move the piece into a *.types.ts/*.contract.ts file it publishes.",
|
||||
sharedImportsDomain:
|
||||
'The shared kernel is imported by every domain, so it may not import one. Move the piece into the kernel, or inject it from the domain.',
|
||||
dbImportsNest: 'src/db sits below src/nest. Move what the data layer needs into src/db (or src/utils) instead.',
|
||||
foreignRepositories:
|
||||
"This injects the repository of a table another domain owns. Ask the owner's service instead (e.g. TripAccessService for trip visibility), or move the code to the owning domain.",
|
||||
providersImportOrchestrator:
|
||||
'A provider sits below the orchestrator that chooses between providers. Hand it what it needs as an argument, or move the shared piece into a helpers file both import.',
|
||||
};
|
||||
|
||||
function main(argv) {
|
||||
const dirArg = argv.find((a) => a.startsWith('--dir='));
|
||||
const serverDir = dirArg ? resolve(dirArg.slice('--dir='.length)) : fileURLToPath(new URL('..', import.meta.url));
|
||||
const baselinePath = join(serverDir, 'scripts', 'import-boundaries-baseline.json');
|
||||
const update = argv.includes('--update');
|
||||
|
||||
const { edges, unresolved } = collectEdges(serverDir);
|
||||
if (unresolved.length) {
|
||||
// An import the walker cannot follow is an edge it cannot judge: stop rather than pass on a partial graph.
|
||||
for (const u of unresolved) console.error(`FAIL unresolved import ${u}`);
|
||||
return 1;
|
||||
}
|
||||
const found = analyse(edges);
|
||||
const { foreignRepositories, unowned } = analyseRepositories(
|
||||
collectRepositoryInjections(serverDir),
|
||||
readOwners(join(serverDir, 'scripts', 'repository-owners.json')),
|
||||
);
|
||||
if (unowned.length) {
|
||||
// An entity without an owner is an injection the rule cannot judge.
|
||||
for (const u of unowned)
|
||||
console.error(`FAIL no owner for injected entity ${u}: add it to scripts/repository-owners.json`);
|
||||
return 1;
|
||||
}
|
||||
found.foreignRepositories = foreignRepositories;
|
||||
let baseline = readBaseline(baselinePath);
|
||||
if (update) {
|
||||
const now = Object.fromEntries(RULES.map((rule) => [rule, new Set(found[rule])]));
|
||||
baseline = Object.fromEntries(
|
||||
RULES.map((rule) => [rule, baseline[rule].filter((key) => now[rule].has(key)).sort()]),
|
||||
);
|
||||
writeFileSync(baselinePath, JSON.stringify(baseline, null, 2) + '\n');
|
||||
}
|
||||
|
||||
const { added, gone } = compare(baseline, found);
|
||||
let failed = 0;
|
||||
for (const rule of RULES) {
|
||||
for (const key of added[rule]) {
|
||||
console.error(`FAIL ${rule}: ${key}. ${HINTS[rule]}`);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
for (const rule of RULES) {
|
||||
for (const key of gone[rule]) {
|
||||
console.error(`FAIL ${rule}: ${key} is in scripts/import-boundaries-baseline.json but no longer occurs.`);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
if (RULES.some((rule) => gone[rule].length)) {
|
||||
console.error(
|
||||
'Run npm run lint:boundaries -- --update to drop it with the change that fixed it: ' +
|
||||
'a stale entry would let the same violation back in unseen.',
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`boundaries: ${edges.length} import(s); held at baseline: ` +
|
||||
RULES.map((rule) => `${rule} ${baseline[rule].length}`).join(', '),
|
||||
);
|
||||
return failed ? 1 : 0;
|
||||
}
|
||||
|
||||
// Compared by real path, so the check still runs when the script is started through a symlink.
|
||||
const isCli =
|
||||
Boolean(process.argv[1]) &&
|
||||
existsSync(process.argv[1]) &&
|
||||
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
try {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
} catch (err) {
|
||||
console.error(`FAIL ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* The per-file count ratchet shared by lint:mcp-zod, lint:service-http,
|
||||
* lint:test-mocks and lint:test-new-service.
|
||||
*
|
||||
* A check names the tree it walks, which files in it count and how to count one
|
||||
* file's text. Every file is held to its entry in the check's baseline JSON
|
||||
* ({ "counts": { "<server-relative path>": n } }); a file without an entry may
|
||||
* hold none. An entry above what its file holds now, or for a file that is
|
||||
* gone, fails as well until --update lowers it, so a fixed hit cannot come back
|
||||
* unseen. --update never raises an entry and never adds one.
|
||||
*
|
||||
* --dir=<path> points a check at another server root (the unit tests use it).
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path, files);
|
||||
else files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* The text with every // and /* comment blanked out (newlines kept, so line
|
||||
* numbers hold), strings and template literals left as they are. A count
|
||||
* that reads code, not prose, runs over this: a call quoted in a doc comment
|
||||
* is not a call.
|
||||
*/
|
||||
export function stripComments(text) {
|
||||
let out = '';
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
const c = text[i];
|
||||
const next = text[i + 1];
|
||||
if (c === '/' && next === '/') {
|
||||
const end = text.indexOf('\n', i);
|
||||
i = end < 0 ? text.length : end;
|
||||
continue;
|
||||
}
|
||||
if (c === '/' && next === '*') {
|
||||
const end = text.indexOf('*/', i + 2);
|
||||
const stop = end < 0 ? text.length : end + 2;
|
||||
out += text.slice(i, stop).replace(/[^\n]/g, ' ');
|
||||
i = stop;
|
||||
continue;
|
||||
}
|
||||
if (c === '"' || c === "'" || c === '`') {
|
||||
let j = i + 1;
|
||||
while (j < text.length && text[j] !== c) j += text[j] === '\\' ? 2 : 1;
|
||||
out += text.slice(i, j + 1);
|
||||
i = j + 1;
|
||||
continue;
|
||||
}
|
||||
out += c;
|
||||
i++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Counts keyed by the server-relative POSIX path, files without any left out. */
|
||||
export function scan(serverDir, check) {
|
||||
const dir = join(serverDir, check.root);
|
||||
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
|
||||
throw new Error(
|
||||
`${check.root}/ does not exist under ${serverDir}: the check would pass without looking at anything`,
|
||||
);
|
||||
}
|
||||
// A check that needs to read the tree first (a list of class names, say)
|
||||
// builds that context once here; count() gets it with every file.
|
||||
const context = check.prepare ? check.prepare(serverDir) : undefined;
|
||||
const counts = {};
|
||||
for (const path of walk(dir)) {
|
||||
const file = relative(serverDir, path).split('\\').join('/');
|
||||
if (!check.include(file)) continue;
|
||||
const n = check.count(readFileSync(path, 'utf8'), file, context);
|
||||
if (n > 0) counts[file] = n;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** The baseline as committed; missing or malformed stops the run instead of reading as empty. */
|
||||
export function readBaseline(path, name) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||||
} catch (err) {
|
||||
throw new Error(`${name} cannot be read: ${err.message}`);
|
||||
}
|
||||
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
||||
if (!isObject(parsed) || !isObject(parsed.counts))
|
||||
throw new Error(`${name} must be an object with a "counts" object`);
|
||||
for (const [file, n] of Object.entries(parsed.counts)) {
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(`${name}: ${file} holds ${JSON.stringify(n)}, expected a whole number above 0`);
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** The counts lowered to what the files hold now. Never raises an entry, never adds one. */
|
||||
export function lowerCounts(baseline, counts) {
|
||||
const lowered = {};
|
||||
for (const [file, allowed] of Object.entries(baseline.counts)) {
|
||||
const now = counts[file] ?? 0;
|
||||
if (now > 0) lowered[file] = Math.min(allowed, now);
|
||||
}
|
||||
return Object.fromEntries(Object.entries(lowered).sort(([a], [b]) => a.localeCompare(b)));
|
||||
}
|
||||
|
||||
/** Files over their allowance, and entries above what their file holds now. */
|
||||
export function compare(baseline, counts) {
|
||||
const grown = Object.entries(counts).filter(([file, n]) => n > (baseline.counts[file] ?? 0));
|
||||
const lowered = lowerCounts(baseline, counts);
|
||||
const stale = Object.entries(baseline.counts).filter(([file, n]) => lowered[file] !== n);
|
||||
return { grown, stale };
|
||||
}
|
||||
|
||||
/** Runs a check as its CLI does; answers the exit code. */
|
||||
export function runCheck(check, argv, serverDirDefault) {
|
||||
const dirArg = argv.find((a) => a.startsWith('--dir='));
|
||||
const serverDir = dirArg ? resolve(dirArg.slice('--dir='.length)) : serverDirDefault;
|
||||
const baselinePath = join(serverDir, check.baseline);
|
||||
|
||||
const counts = scan(serverDir, check);
|
||||
const baseline = readBaseline(baselinePath, check.baseline);
|
||||
if (argv.includes('--update')) {
|
||||
baseline.counts = lowerCounts(baseline, counts);
|
||||
writeFileSync(baselinePath, JSON.stringify(baseline, null, 2) + '\n');
|
||||
}
|
||||
|
||||
const { grown, stale } = compare(baseline, counts);
|
||||
for (const [file, n] of grown) {
|
||||
const entry = baseline.counts[file];
|
||||
console.error(
|
||||
`FAIL ${file}: ${n} ${check.unit}, ` +
|
||||
(entry ? `its baseline is ${entry}. ` : 'a file without a baseline entry may hold none. ') +
|
||||
check.advice,
|
||||
);
|
||||
}
|
||||
for (const [file, entry] of stale) {
|
||||
console.error(
|
||||
`FAIL ${file} is held at ${entry} in ${check.baseline}, ` +
|
||||
(file in counts ? `but it has ${counts[file]} now.` : 'but it has none left (or the file is gone).'),
|
||||
);
|
||||
}
|
||||
if (stale.length) {
|
||||
console.error(
|
||||
`Run npm run ${check.script} -- --update to lower the baseline with the change that made it smaller.`,
|
||||
);
|
||||
}
|
||||
const total = Object.values(counts).reduce((sum, n) => sum + n, 0);
|
||||
console.log(`${check.name}: ${total} ${check.unit} in ${Object.keys(counts).length} file(s) held at their baseline`);
|
||||
return grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
|
||||
/** Starts `check` when `moduleUrl` is the script node was started with (compared by real path). */
|
||||
export function cliMain(check, moduleUrl) {
|
||||
const isCli =
|
||||
Boolean(process.argv[1]) &&
|
||||
existsSync(process.argv[1]) &&
|
||||
realpathSync(process.argv[1]) === fileURLToPath(moduleUrl);
|
||||
if (!isCli) return;
|
||||
try {
|
||||
process.exitCode = runCheck(check, process.argv.slice(2), fileURLToPath(new URL('..', moduleUrl)));
|
||||
} catch (err) {
|
||||
console.error(`FAIL ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Reading tsc's --pretty false output for lint:strict (scripts/strict-lint.mjs).
|
||||
* Kept free of imports so the unit tests can load it on their own.
|
||||
*/
|
||||
|
||||
/** `src/a.ts(3,7): error TS2322: ...` as tsc --pretty false prints it. */
|
||||
const FILE_ERROR = /^(.+?)\((\d+),(\d+)\): error (TS\d+): /;
|
||||
/** An error tied to no file, such as a config problem. */
|
||||
const GLOBAL_ERROR = /^error (TS\d+): /;
|
||||
|
||||
/**
|
||||
* The errors per file in tsc's output, keyed by the path from the server root
|
||||
* with forward slashes, and the lines of every error that names no file.
|
||||
* Continuation lines (indented) belong to the error above and do not count.
|
||||
*/
|
||||
export function countErrors(output) {
|
||||
const counts = {};
|
||||
const global = [];
|
||||
for (const line of output.replace(/\r\n?/g, '\n').split('\n')) {
|
||||
const match = FILE_ERROR.exec(line);
|
||||
if (match) {
|
||||
const key = match[1].split('\\').join('/').replace(/^\.\//, '');
|
||||
counts[key] = (counts[key] ?? 0) + 1;
|
||||
} else if (GLOBAL_ERROR.test(line)) {
|
||||
global.push(line);
|
||||
}
|
||||
}
|
||||
return { counts, global };
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"counts": {
|
||||
"src/nest/accommodations/accommodations.mcp.ts": 28,
|
||||
"src/nest/airports/airports.mcp.ts": 3,
|
||||
"src/nest/assignments/assignments.mcp.ts": 10,
|
||||
"src/nest/atlas/atlas.mcp.ts": 23,
|
||||
"src/nest/budget/budget.mcp.ts": 36,
|
||||
"src/nest/collab/collab.mcp.ts": 20,
|
||||
"src/nest/collections/collections.mcp.ts": 14,
|
||||
"src/nest/day-notes/day-notes.mcp.ts": 10,
|
||||
"src/nest/days/days.mcp.ts": 2,
|
||||
"src/nest/doc-sync/doc-sync.mcp.ts": 1,
|
||||
"src/nest/files/files.mcp.ts": 4,
|
||||
"src/nest/help/help.mcp.ts": 4,
|
||||
"src/nest/integrations/airtrail.mcp.ts": 2,
|
||||
"src/nest/integrations/dawarich.mcp.ts": 13,
|
||||
"src/nest/journey/journey.mcp.ts": 30,
|
||||
"src/nest/maps/maps.mcp.ts": 18,
|
||||
"src/nest/memories/memories.mcp.ts": 8,
|
||||
"src/nest/notifications/notifications.mcp.ts": 2,
|
||||
"src/nest/packing/packing.mcp.ts": 15,
|
||||
"src/nest/places/places.mcp.ts": 68,
|
||||
"src/nest/plugins/contributions/plugin-pois.mcp.ts": 4,
|
||||
"src/nest/plugins/contributions/plugin-search.mcp.ts": 5,
|
||||
"src/nest/reservations/reservations.mcp.ts": 64,
|
||||
"src/nest/roadtrip/day-boundaries.mcp.ts": 1,
|
||||
"src/nest/roadtrip/google-route.mcp.ts": 2,
|
||||
"src/nest/roadtrip/roadtrip.mcp.ts": 16,
|
||||
"src/nest/school-holidays/school-holidays.mcp.ts": 2,
|
||||
"src/nest/settings/settings.mcp.ts": 21,
|
||||
"src/nest/share/share.mcp.ts": 7,
|
||||
"src/nest/tags/tags.mcp.ts": 4,
|
||||
"src/nest/todo/todo.mcp.ts": 14,
|
||||
"src/nest/transit/transit.mcp.ts": 16,
|
||||
"src/nest/trips/trips.mcp.ts": 24,
|
||||
"src/nest/vacay/vacay.mcp.ts": 25,
|
||||
"src/nest/weather/weather.mcp.ts": 8
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:mcp-zod: inline zod in the MCP tool files may only shrink.
|
||||
*
|
||||
* An MCP tool's input is meant to derive from the request contract in
|
||||
* @trek/shared (`xRequestSchema.shape.field`, `.pick()`, `.extend()`,
|
||||
* `.describe()`), or from a shared primitive such as idSchema, so a bound that
|
||||
* changes on the REST side changes on the tool too. Every `z.` written in a
|
||||
* `*.mcp.ts` under src/nest is a field spelled by hand instead. Where REST is
|
||||
* deliberately looser (an open body, a field without a length) the tool keeps
|
||||
* its own bound, and its count says so.
|
||||
*
|
||||
* Each file is held to its entry in scripts/mcp-inline-zod-baseline.json, and a
|
||||
* new tool file holds none (scripts/lib/count-ratchet.mjs has the rules).
|
||||
*
|
||||
* npm run lint:mcp-zod check against the baseline (CI)
|
||||
* npm run lint:mcp-zod -- --update lower the counts; never raises or adds an entry
|
||||
*/
|
||||
import { cliMain } from './lib/count-ratchet.mjs';
|
||||
|
||||
// Whitespace before the dot counts too: Prettier breaks a long chain into `z`
|
||||
// on one line and `.object(` on the next.
|
||||
const ZOD_CALL = /\bz\s*\./g;
|
||||
|
||||
/** The inline zod calls in one file's text, comments included. */
|
||||
export function countInlineZod(text) {
|
||||
return text.match(ZOD_CALL)?.length ?? 0;
|
||||
}
|
||||
|
||||
export const check = {
|
||||
name: 'mcp-zod',
|
||||
script: 'lint:mcp-zod',
|
||||
root: 'src/nest',
|
||||
baseline: 'scripts/mcp-inline-zod-baseline.json',
|
||||
unit: 'inline z. call(s)',
|
||||
advice: 'Derive the field from the request schema in @trek/shared or a shared primitive (idSchema) instead.',
|
||||
include: (file) => file.endsWith('.mcp.ts'),
|
||||
count: (text) => countInlineZod(text),
|
||||
};
|
||||
|
||||
cliMain(check, import.meta.url);
|
||||
@@ -14,12 +14,11 @@
|
||||
* The script will prompt for the old and new keys interactively so they never
|
||||
* appear in shell history, process arguments, or log output.
|
||||
*/
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import readline from 'readline';
|
||||
import Database from 'better-sqlite3';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Crypto helpers — mirrors apiKeyCrypto.ts and mfaCrypto.ts but with
|
||||
@@ -143,9 +142,7 @@ async function main() {
|
||||
console.log('A backup of the database will be created before any changes are made.\n');
|
||||
|
||||
// Resolve DB path
|
||||
const dbPath = path.resolve(
|
||||
process.env.DB_PATH ?? path.join(__dirname, '../data/travel.db')
|
||||
);
|
||||
const dbPath = path.resolve(process.env.DB_PATH ?? path.join(__dirname, '../data/travel.db'));
|
||||
|
||||
if (!fs.existsSync(dbPath)) {
|
||||
console.error(`Database not found at: ${dbPath}`);
|
||||
@@ -184,6 +181,10 @@ async function main() {
|
||||
|
||||
const db = new Database(dbPath);
|
||||
db.pragma('busy_timeout = 5000');
|
||||
// Temp files in memory, like every connection src/db/connection.ts opens: a
|
||||
// container with a read-only root and no tmpfs on /tmp has nowhere to put
|
||||
// them, and the rotation below runs as one long transaction (#2518).
|
||||
db.pragma('temp_store = MEMORY');
|
||||
|
||||
// The rollback copy has to be a consistent snapshot, not a plain file copy:
|
||||
// this script is documented as running against a live server, so in WAL mode
|
||||
@@ -209,14 +210,18 @@ async function main() {
|
||||
const wantedJournal = (process.env.TREK_DB_JOURNAL_MODE ?? '').trim().toUpperCase();
|
||||
const journalMode = journalModes.includes(wantedJournal) ? wantedJournal : 'WAL';
|
||||
if (wantedJournal && journalMode !== wantedJournal) {
|
||||
console.warn(`TREK_DB_JOURNAL_MODE="${process.env.TREK_DB_JOURNAL_MODE}" is not a SQLite journal mode — using ${journalMode}.`);
|
||||
console.warn(
|
||||
`TREK_DB_JOURNAL_MODE="${process.env.TREK_DB_JOURNAL_MODE}" is not a SQLite journal mode — using ${journalMode}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const wantedSync = (process.env.TREK_DB_SYNCHRONOUS ?? '').trim().toUpperCase();
|
||||
const defaultSync = journalMode === 'WAL' ? 'NORMAL' : 'FULL';
|
||||
const synchronous = syncLevels.includes(wantedSync) ? wantedSync : defaultSync;
|
||||
if (wantedSync && synchronous !== wantedSync) {
|
||||
console.warn(`TREK_DB_SYNCHRONOUS="${process.env.TREK_DB_SYNCHRONOUS}" is not a SQLite synchronous level — using ${synchronous}.`);
|
||||
console.warn(
|
||||
`TREK_DB_SYNCHRONOUS="${process.env.TREK_DB_SYNCHRONOUS}" is not a SQLite synchronous level — using ${synchronous}.`,
|
||||
);
|
||||
}
|
||||
|
||||
db.pragma(`journal_mode = ${journalMode}`);
|
||||
@@ -253,7 +258,10 @@ async function main() {
|
||||
|
||||
// Helper: migrate a single MFA value (no prefix, raw base64)
|
||||
function migrateMfaValue(raw: string, label: string): string | null {
|
||||
if (!raw) { result.skipped++; return null; }
|
||||
if (!raw) {
|
||||
result.skipped++;
|
||||
return null;
|
||||
}
|
||||
|
||||
const plain = decryptMfa(raw, oldKey);
|
||||
if (plain !== null) {
|
||||
@@ -283,6 +291,10 @@ async function main() {
|
||||
// rotation leaves it encrypted under the old key, which reads back as "no
|
||||
// key" and silently drops the install to OpenStreetMap, so the copy is
|
||||
// pinned by tests/unit/db/migrate-encryption-parity.test.ts.
|
||||
//
|
||||
// web_push_vapid_private_key is the Web Push signing key VapidKeysService
|
||||
// generates. Missed here it would no longer decrypt under the new key, and
|
||||
// push would stay off on every device until the old key came back.
|
||||
for (const key of [
|
||||
'oidc_client_secret',
|
||||
'smtp_pass',
|
||||
@@ -291,6 +303,7 @@ async function main() {
|
||||
'maps_api_key',
|
||||
'unsplash_api_key',
|
||||
'amap_api_key',
|
||||
'web_push_vapid_private_key',
|
||||
]) {
|
||||
const row = db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined;
|
||||
if (!row?.value) continue;
|
||||
@@ -326,7 +339,10 @@ async function main() {
|
||||
const users = db.prepare('SELECT id FROM users').all() as { id: number }[];
|
||||
|
||||
for (const user of users) {
|
||||
const row = db.prepare(`SELECT ${apiKeyColumns.join(', ')} FROM users WHERE id = ?`).get(user.id) as Record<string, string>;
|
||||
const row = db.prepare(`SELECT ${apiKeyColumns.join(', ')} FROM users WHERE id = ?`).get(user.id) as Record<
|
||||
string,
|
||||
string
|
||||
>;
|
||||
|
||||
for (const col of apiKeyColumns) {
|
||||
if (!row[col]) continue;
|
||||
@@ -337,7 +353,8 @@ async function main() {
|
||||
}
|
||||
|
||||
// mfa_secret (mfa crypto)
|
||||
const mfaRow = db.prepare('SELECT mfa_secret FROM users WHERE id = ? AND mfa_secret IS NOT NULL').get(user.id) as { mfa_secret: string } | undefined;
|
||||
const mfaRow = db.prepare('SELECT mfa_secret FROM users WHERE id = ? AND mfa_secret IS NOT NULL').get(user.id) as
|
||||
{ mfa_secret: string } | undefined;
|
||||
if (mfaRow?.mfa_secret) {
|
||||
const newVal = migrateMfaValue(mfaRow.mfa_secret, `users[${user.id}].mfa_secret`);
|
||||
if (newVal !== null) {
|
||||
@@ -364,8 +381,7 @@ async function main() {
|
||||
};
|
||||
{
|
||||
const row = db.prepare("SELECT value FROM app_settings WHERE key = 'storage.backends'").get() as
|
||||
| { value: string }
|
||||
| undefined;
|
||||
{ value: string } | undefined;
|
||||
if (row?.value) {
|
||||
let backends: unknown;
|
||||
try {
|
||||
@@ -409,9 +425,11 @@ async function main() {
|
||||
|
||||
// --- settings: per-user encrypted keys ---
|
||||
const encryptedSettingKeys = ['webhook_url', 'ntfy_token', 'mapbox_access_token', 'carto_api_key', 'llm_api_key'];
|
||||
const settingRows = db.prepare(
|
||||
`SELECT user_id, key, value FROM settings WHERE key IN (${encryptedSettingKeys.map(() => '?').join(', ')})`
|
||||
).all(...encryptedSettingKeys) as { user_id: number; key: string; value: string }[];
|
||||
const settingRows = db
|
||||
.prepare(
|
||||
`SELECT user_id, key, value FROM settings WHERE key IN (${encryptedSettingKeys.map(() => '?').join(', ')})`,
|
||||
)
|
||||
.all(...encryptedSettingKeys) as { user_id: number; key: string; value: string }[];
|
||||
|
||||
for (const row of settingRows) {
|
||||
if (!row.value) continue;
|
||||
@@ -456,7 +474,7 @@ async function main() {
|
||||
// Which keys are secret is per plugin and per scope, and it lives in the DB
|
||||
// rather than in this script, so nothing has to be pinned by hand here.
|
||||
const secretFields = db
|
||||
.prepare("SELECT plugin_id, field_key, scope FROM plugin_settings_fields WHERE secret = 1")
|
||||
.prepare('SELECT plugin_id, field_key, scope FROM plugin_settings_fields WHERE secret = 1')
|
||||
.all() as { plugin_id: string; field_key: string; scope: string | null }[];
|
||||
const secretKeysFor = (pluginId: string, scope: string): string[] =>
|
||||
secretFields
|
||||
@@ -491,7 +509,10 @@ async function main() {
|
||||
};
|
||||
|
||||
if (tableExists('plugins')) {
|
||||
const pluginRows = db.prepare('SELECT id, config FROM plugins').all() as { id: string; config: string | null }[];
|
||||
const pluginRows = db.prepare('SELECT id, config FROM plugins').all() as {
|
||||
id: string;
|
||||
config: string | null;
|
||||
}[];
|
||||
for (const row of pluginRows) {
|
||||
const next = migrateConfigJson(row.config, secretKeysFor(row.id, 'instance'), `plugins[${row.id}].config`);
|
||||
if (next !== null) {
|
||||
@@ -501,9 +522,11 @@ async function main() {
|
||||
}
|
||||
|
||||
if (tableExists('plugin_user_config')) {
|
||||
const userConfigRows = db
|
||||
.prepare('SELECT plugin_id, user_id, config FROM plugin_user_config')
|
||||
.all() as { plugin_id: string; user_id: number; config: string | null }[];
|
||||
const userConfigRows = db.prepare('SELECT plugin_id, user_id, config FROM plugin_user_config').all() as {
|
||||
plugin_id: string;
|
||||
user_id: number;
|
||||
config: string | null;
|
||||
}[];
|
||||
for (const row of userConfigRows) {
|
||||
const next = migrateConfigJson(
|
||||
row.config,
|
||||
@@ -521,8 +544,40 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
// --- addons: the AI Parsing addon's instance-wide API key ---
|
||||
// Stored encrypted as `apiKey` inside the addon's JSON config
|
||||
// (llm-parse/llm-config.ts). Left out, LLM parsing quietly runs without a
|
||||
// key after the rotation, since a failed decrypt reads as "no key".
|
||||
if (tableExists('addons')) {
|
||||
const addonRows = db.prepare('SELECT id, config FROM addons WHERE config IS NOT NULL').all() as {
|
||||
id: string;
|
||||
config: string;
|
||||
}[];
|
||||
for (const row of addonRows) {
|
||||
let config: unknown;
|
||||
try {
|
||||
config = JSON.parse(row.config);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (!config || typeof config !== 'object' || Array.isArray(config)) continue;
|
||||
const apiKey = (config as Record<string, unknown>).apiKey;
|
||||
if (typeof apiKey !== 'string' || !apiKey) continue;
|
||||
const newVal = migrateApiKeyValue(apiKey, `addons[${row.id}].config.apiKey`);
|
||||
if (newVal !== null) {
|
||||
db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(
|
||||
JSON.stringify({ ...(config as Record<string, unknown>), apiKey: newVal }),
|
||||
row.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- trip_album_links: passphrase ---
|
||||
const albumLinks = db.prepare('SELECT id, passphrase FROM trip_album_links WHERE passphrase IS NOT NULL').all() as { id: number; passphrase: string }[];
|
||||
const albumLinks = db.prepare('SELECT id, passphrase FROM trip_album_links WHERE passphrase IS NOT NULL').all() as {
|
||||
id: number;
|
||||
passphrase: string;
|
||||
}[];
|
||||
for (const row of albumLinks) {
|
||||
const newVal = migrateApiKeyValue(row.passphrase, `trip_album_links[${row.id}].passphrase`);
|
||||
if (newVal !== null) {
|
||||
@@ -547,7 +602,10 @@ async function main() {
|
||||
}
|
||||
|
||||
// --- trek_photos: passphrase ---
|
||||
const photos = db.prepare('SELECT id, passphrase FROM trek_photos WHERE passphrase IS NOT NULL').all() as { id: number; passphrase: string }[];
|
||||
const photos = db.prepare('SELECT id, passphrase FROM trek_photos WHERE passphrase IS NOT NULL').all() as {
|
||||
id: number;
|
||||
passphrase: string;
|
||||
}[];
|
||||
for (const row of photos) {
|
||||
const newVal = migrateApiKeyValue(row.passphrase, `trek_photos[${row.id}].passphrase`);
|
||||
if (newVal !== null) {
|
||||
@@ -576,6 +634,26 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
// --- ai_connections: secrets ---
|
||||
// The AI assistant's connections keep their credential in ONE encrypted
|
||||
// JSON blob (src/nest/ai-connections/ai-secrets.ts): an API key, or a
|
||||
// ChatGPT sign-in's tokens. Left out of a rotation, the instance's
|
||||
// connection asks the admin for its key again and every ChatGPT user has
|
||||
// to sign in anew. The table arrived with a later migration, hence the
|
||||
// existence check.
|
||||
if (tableExists('ai_connections')) {
|
||||
const aiConnections = db.prepare('SELECT id, secrets FROM ai_connections WHERE secrets IS NOT NULL').all() as {
|
||||
id: number;
|
||||
secrets: string;
|
||||
}[];
|
||||
for (const row of aiConnections) {
|
||||
const newVal = migrateApiKeyValue(row.secrets, `ai_connections[${row.id}].secrets`);
|
||||
if (newVal !== null) {
|
||||
db.prepare('UPDATE ai_connections SET secrets = ? WHERE id = ?').run(newVal, row.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- trip_document_links: webhook_secret ---
|
||||
// The secret a provider signs its webhook calls with, stored through the
|
||||
// same blob helper. It is written once when the link is created and never
|
||||
@@ -603,12 +681,24 @@ async function main() {
|
||||
console.log(` Skipped (empty): ${result.skipped}`);
|
||||
if (result.errors.length > 0) {
|
||||
console.warn(` Errors: ${result.errors.length}`);
|
||||
result.errors.forEach(e => console.warn(` - ${e}`));
|
||||
result.errors.forEach((e) => console.warn(` - ${e}`));
|
||||
console.warn('\nSome secrets could not be migrated. Check the errors above.');
|
||||
console.warn(`Your original database is backed up at: ${backupPath}`);
|
||||
process.exit(1);
|
||||
} else {
|
||||
console.log('\nAll secrets successfully re-encrypted.');
|
||||
// The server refuses to start when ENCRYPTION_KEY and the key file disagree
|
||||
// (src/config.ts), so the file follows the rotation. Only an existing file
|
||||
// next to the database is touched; anything else is left to the operator.
|
||||
const keyFile = path.join(path.dirname(dbPath), '.encryption_key');
|
||||
if (fs.existsSync(keyFile)) {
|
||||
fs.writeFileSync(keyFile, newKey, { mode: 0o600 });
|
||||
console.log(`Key file updated: ${keyFile}`);
|
||||
} else {
|
||||
console.log(
|
||||
'No key file next to the database. Store the new key wherever TREK reads it from (ENCRYPTION_KEY or data/.encryption_key).',
|
||||
);
|
||||
}
|
||||
console.log(`Backup retained at: ${backupPath}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"failing": {
|
||||
"DayAccommodationsRepository.listForTripWithPlaceAndBooking": 1,
|
||||
"DayAccommodationsRepository.listRoadtripStays": 1,
|
||||
"GoogleApiUsageRepository.recordCall": 1,
|
||||
"MaintenanceRepository.vacuumInto": 1,
|
||||
"MaintenanceRepository.walCheckpoint": 1,
|
||||
"ReservationDayPositionsRepository.upsertScoped": 1,
|
||||
"ReservationsRepository.findWithJoins": 1,
|
||||
"ReservationsRepository.listForCalendar": 1,
|
||||
"ReservationsRepository.listForTrip": 1,
|
||||
"ReservationsRepository.listPublicStaysForCalendar": 1,
|
||||
"RouteUsageDailyRepository.record": 1
|
||||
},
|
||||
"uncovered": [
|
||||
"BucketListRepository.update",
|
||||
"BudgetItemsRepository.update",
|
||||
"PackingBagsRepository.update",
|
||||
"TodoItemsRepository.update"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
/**
|
||||
* The Postgres probe: what of the server's SQL runs on Postgres today.
|
||||
*
|
||||
* TREK runs on SQLite, and the dialect layer (src/db/dialect/) is written so
|
||||
* a second engine is a branch there rather than a sweep through the
|
||||
* repositories. Nothing tested that claim until this probe. Given an empty
|
||||
* Postgres database it
|
||||
*
|
||||
* 1. derives a Postgres schema from the entities (pg-probe/schema.ts);
|
||||
* 2. runs every dialect helper on SQLite and on Postgres and checks both
|
||||
* return what the helper promises (pg-probe/helper-cases.ts); every
|
||||
* case must pass;
|
||||
* 3. calls every public repository method once with sample arguments the
|
||||
* TypeScript checker builds from its parameter types
|
||||
* (pg-probe/arg-samples.ts), through a MikroORM Postgres driver that
|
||||
* runs each statement in its own rolled-back transaction and records
|
||||
* whether Postgres accepted it (pg-probe/recorder.ts);
|
||||
* 4. holds the statements Postgres refuses as SQL (SQLSTATE class 42 or
|
||||
* 0A), per method, to scripts/pg-probe-baseline.json, which may only
|
||||
* shrink (pg-probe/baseline.ts); a refusal over a sample value
|
||||
* (class 22) or the empty tables is reported, not held;
|
||||
* 5. holds the methods whose SQL it did not see (it could not call them,
|
||||
* they sent no SQL, or they timed out) to the same file's `uncovered`
|
||||
* list, which may only shrink too, so a new method the probe cannot
|
||||
* reach fails the run instead of landing unmeasured.
|
||||
*
|
||||
* What it measures is the statements each method reaches with sample
|
||||
* arguments against empty tables, not every statement the code can send: a
|
||||
* branch that only runs on data the empty tables do not hold stays unseen.
|
||||
*
|
||||
* It needs a Postgres server, so CI runs it in the `postgres-probe` job
|
||||
* against a service container. Locally:
|
||||
*
|
||||
* docker run --rm -d -p 5432:5432 -e POSTGRES_PASSWORD=probe postgres:17
|
||||
* TREK_PG_PROBE_URL=postgres://postgres:probe@127.0.0.1:5432/postgres npm run probe:pg
|
||||
*
|
||||
* Options:
|
||||
* --url=<postgres url> instead of TREK_PG_PROBE_URL
|
||||
* --update lower scripts/pg-probe-baseline.json to this run (never raises or adds an entry;
|
||||
* an unmeasured baseline gets its first measurement)
|
||||
*
|
||||
* A baseline whose `failing` or `uncovered` is `null` has never been measured and fails the
|
||||
* run (outside `--update`); the baseline the run writes with
|
||||
* `--next-baseline` (the CI artifact) is the first measurement to commit. A
|
||||
* run that called no repository method fails as well.
|
||||
* --next-baseline=<path> write the baseline this run would leave (the CI artifact)
|
||||
* --report=<path> write everything the run saw as JSON
|
||||
* --summary=<path> append the Markdown summary (defaults to $GITHUB_STEP_SUMMARY)
|
||||
*
|
||||
* Exit codes: 0 passed, 1 a helper case or the ratchet failed, 2 the probe
|
||||
* could not run (no database, a database that is not empty, a crash).
|
||||
*/
|
||||
import { planRepositories, readCompilerOptions, type MethodPlan } from './pg-probe/arg-samples';
|
||||
import { compareWithBaseline, formatBaseline, lowerBaseline, readBaseline } from './pg-probe/baseline';
|
||||
import {
|
||||
connectProbeOrm,
|
||||
connectSetupOrm,
|
||||
postgresHelperEngine,
|
||||
prepareDatabase,
|
||||
probeRepositories,
|
||||
sqliteHelperEngine,
|
||||
} from './pg-probe/engines';
|
||||
import { runHelperCases, type HelperResult } from './pg-probe/helper-cases';
|
||||
import { StatementRecorder } from './pg-probe/recorder';
|
||||
import {
|
||||
formatConsole,
|
||||
formatMarkdown,
|
||||
passed,
|
||||
probedNothing,
|
||||
summarize,
|
||||
type MethodResult,
|
||||
type ReportInput,
|
||||
} from './pg-probe/report';
|
||||
|
||||
import { appendFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const SERVER_ROOT = path.join(__dirname, '..');
|
||||
export const BASELINE_PATH = path.join(SERVER_ROOT, 'scripts', 'pg-probe-baseline.json');
|
||||
const REPOSITORIES_DIR = path.join(SERVER_ROOT, 'src', 'db', 'repositories');
|
||||
|
||||
/** A statement that runs longer than this on empty tables is stuck. */
|
||||
const STATEMENT_TIMEOUT_MS = 5_000;
|
||||
/** A method still running after this has hung (a pool wait, a loop over a result it never gets). */
|
||||
const METHOD_TIMEOUT_MS = 20_000;
|
||||
|
||||
export interface ProbeArgs {
|
||||
url: string;
|
||||
update: boolean;
|
||||
nextBaseline: string | null;
|
||||
report: string | null;
|
||||
summary: string | null;
|
||||
}
|
||||
|
||||
export function parseArgs(argv: readonly string[], env: Readonly<Record<string, string | undefined>>): ProbeArgs {
|
||||
const args: ProbeArgs = {
|
||||
url: env.TREK_PG_PROBE_URL ?? '',
|
||||
update: false,
|
||||
nextBaseline: null,
|
||||
report: null,
|
||||
summary: env.GITHUB_STEP_SUMMARY || null,
|
||||
};
|
||||
for (const arg of argv) {
|
||||
const [flag, value] = arg.includes('=')
|
||||
? [arg.slice(0, arg.indexOf('=')), arg.slice(arg.indexOf('=') + 1)]
|
||||
: [arg, ''];
|
||||
if (flag === '--update' && value === '') args.update = true;
|
||||
else if (flag === '--url' && value) args.url = value;
|
||||
else if (flag === '--next-baseline' && value) args.nextBaseline = value;
|
||||
else if (flag === '--report' && value) args.report = value;
|
||||
else if (flag === '--summary' && value) args.summary = value;
|
||||
else throw new Error(`pg-probe: unknown argument ${arg}`);
|
||||
}
|
||||
if (!/^postgres(ql)?:\/\//.test(args.url)) {
|
||||
throw new Error(
|
||||
'pg-probe: no Postgres URL. Set TREK_PG_PROBE_URL or pass --url=postgres://user:password@host:port/database.',
|
||||
);
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
/** The repository files the probe calls into: every `src/db/repositories/*.ts`, the `_shared/` helpers excepted. */
|
||||
export function repositoryFiles(dir: string): string[] {
|
||||
return readdirSync(dir)
|
||||
.filter((name) => name.endsWith('.ts') && !name.endsWith('.d.ts'))
|
||||
.sort()
|
||||
.map((name) => path.join(dir, name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 0 when every helper case passed, the probe called at least one repository
|
||||
* method, the baseline is measured, no method fails more statements than
|
||||
* its entry allows and every method the probe did not measure is listed as
|
||||
* uncovered. An entry above what the run saw (a count above what its method
|
||||
* fails, an uncovered method that is measured now) fails the run too, and so
|
||||
* does an unmeasured baseline, unless this run is the `--update` that lowers
|
||||
* or seeds it.
|
||||
*/
|
||||
export function exitCode(input: Pick<ReportInput, 'verdict' | 'helpers' | 'summary'>, update: boolean): number {
|
||||
if (passed(input)) return 0;
|
||||
const helpersOk = input.helpers.every((result) => result.failure === null);
|
||||
const held = input.verdict.grown.length === 0 && input.verdict.newlyUncovered.length === 0;
|
||||
return helpersOk && !probedNothing(input.summary) && held && update ? 0 : 1;
|
||||
}
|
||||
|
||||
/** GitHub annotations when running in Actions, plain lines otherwise. */
|
||||
function annotate(level: 'error' | 'warning' | 'notice', message: string): void {
|
||||
console.log(process.env.GITHUB_ACTIONS === 'true' ? `::${level}::${message}` : `${level.toUpperCase()}: ${message}`);
|
||||
}
|
||||
|
||||
function timed<T>(label: string, fn: () => Promise<T>): Promise<T> {
|
||||
const start = Date.now();
|
||||
console.log(`-- ${label}`);
|
||||
return fn().finally(() => console.log(` ${label}: ${((Date.now() - start) / 1000).toFixed(1)}s`));
|
||||
}
|
||||
|
||||
async function main(): Promise<number> {
|
||||
const args = parseArgs(process.argv.slice(2), process.env);
|
||||
const baseline = readBaseline(BASELINE_PATH);
|
||||
|
||||
const setup = await timed('connect', () => connectSetupOrm(args.url));
|
||||
let helpers: HelperResult[] = [];
|
||||
let schemaFailures: { statement: string; message: string }[] = [];
|
||||
let results: MethodResult[] = [];
|
||||
try {
|
||||
const schema = await timed('derive the schema from the entities', () => prepareDatabase(setup));
|
||||
schemaFailures = schema.failures;
|
||||
console.log(
|
||||
` ${schema.statements} DDL statements, ${schema.adjusted} columns adjusted, ${schema.failures.length} refused`,
|
||||
);
|
||||
|
||||
helpers = await timed('dialect helpers on SQLite and Postgres', async () => {
|
||||
const sqlite = sqliteHelperEngine();
|
||||
try {
|
||||
return [...(await runHelperCases(sqlite)), ...(await runHelperCases(postgresHelperEngine(setup)))];
|
||||
} finally {
|
||||
sqlite.close();
|
||||
}
|
||||
});
|
||||
|
||||
const plans: MethodPlan[] = await timed('plan the repository calls', async () =>
|
||||
planRepositories(
|
||||
repositoryFiles(REPOSITORIES_DIR),
|
||||
readCompilerOptions(path.join(SERVER_ROOT, 'tsconfig.json')),
|
||||
SERVER_ROOT,
|
||||
),
|
||||
);
|
||||
console.log(` ${plans.length} public repository methods`);
|
||||
|
||||
const recorder = new StatementRecorder();
|
||||
const probe = await connectProbeOrm(args.url, recorder, STATEMENT_TIMEOUT_MS);
|
||||
try {
|
||||
results = await timed('call every repository method', () =>
|
||||
probeRepositories(probe, recorder, plans, SERVER_ROOT, METHOD_TIMEOUT_MS),
|
||||
);
|
||||
} finally {
|
||||
await probe.close(true);
|
||||
}
|
||||
} finally {
|
||||
await setup.close(true);
|
||||
}
|
||||
|
||||
const summary = summarize(results);
|
||||
const uncoveredNow = new Set(summary.uncovered.keys());
|
||||
const verdict = compareWithBaseline(baseline, summary.failingByMethod, uncoveredNow);
|
||||
const input: ReportInput = { summary, verdict, helpers, schemaFailures, results };
|
||||
console.log(formatConsole(input));
|
||||
|
||||
const next = lowerBaseline(baseline, summary.failingByMethod, uncoveredNow);
|
||||
if (args.nextBaseline) writeFileSync(args.nextBaseline, formatBaseline(next));
|
||||
if (args.update) {
|
||||
writeFileSync(BASELINE_PATH, formatBaseline(next));
|
||||
console.log(`Wrote ${path.relative(SERVER_ROOT, BASELINE_PATH)}.`);
|
||||
}
|
||||
if (args.report) {
|
||||
const counts = {
|
||||
failingByMethod: Object.fromEntries(summary.failingByMethod),
|
||||
uncovered: Object.fromEntries(summary.uncovered),
|
||||
failuresByCode: Object.fromEntries(summary.failuresByCode),
|
||||
};
|
||||
const report = { summary: { ...summary, ...counts }, verdict, helpers, schemaFailures, results };
|
||||
writeFileSync(args.report, `${JSON.stringify(report, null, 2)}\n`);
|
||||
}
|
||||
if (args.summary) appendFileSync(args.summary, formatMarkdown(input));
|
||||
|
||||
for (const failure of helpers.filter((result) => result.failure !== null)) {
|
||||
annotate('error', `pg-probe helper case [${failure.engine}] ${failure.name}: ${failure.failure}`);
|
||||
}
|
||||
for (const entry of verdict.grown) {
|
||||
annotate(
|
||||
'error',
|
||||
`pg-probe: ${entry.method} sends ${entry.now} statement(s) Postgres refuses, ${entry.allowed} allowed.`,
|
||||
);
|
||||
}
|
||||
for (const entry of verdict.stale) {
|
||||
annotate(
|
||||
'error',
|
||||
`pg-probe: ${entry.method} fails ${entry.now} statement(s), the baseline allows ${entry.allowed}. ` +
|
||||
'Lower it (--update, or the pg-probe-baseline artifact).',
|
||||
);
|
||||
}
|
||||
for (const method of verdict.newlyUncovered) {
|
||||
annotate(
|
||||
'error',
|
||||
`pg-probe: ${method} ${summary.uncovered.get(method) ?? 'went unmeasured'}, so its SQL was not checked. ` +
|
||||
'Give it arguments the probe can sample, or make it reach its SQL with them.',
|
||||
);
|
||||
}
|
||||
for (const method of verdict.nowCovered) {
|
||||
annotate(
|
||||
'error',
|
||||
`pg-probe: ${method} is listed as uncovered but is measured now (or gone). Drop it (--update, or the pg-probe-baseline artifact).`,
|
||||
);
|
||||
}
|
||||
if (probedNothing(summary))
|
||||
annotate('error', `pg-probe: no repository method was called (${summary.methods} planned).`);
|
||||
if (verdict.unseeded) {
|
||||
annotate(
|
||||
'error',
|
||||
'pg-probe: the baseline has not been measured yet. Commit pg-probe-baseline.json from the pg-probe-baseline artifact ' +
|
||||
'as server/scripts/pg-probe-baseline.json.',
|
||||
);
|
||||
}
|
||||
for (const failure of schemaFailures) annotate('warning', `pg-probe schema: ${failure.message}`);
|
||||
return exitCode(input, args.update);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
// A method abandoned after its timeout may still reject later; that is
|
||||
// already counted as a timeout and must not take the whole run down.
|
||||
process.on('unhandledRejection', (reason: unknown) => {
|
||||
annotate(
|
||||
'warning',
|
||||
`pg-probe: a rejection nobody awaited: ${reason instanceof Error ? reason.message.split('\n')[0] : String(reason)}`,
|
||||
);
|
||||
});
|
||||
main().then(
|
||||
(code) => process.exit(code),
|
||||
(error: unknown) => {
|
||||
console.error(
|
||||
`pg-probe could not run: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
|
||||
);
|
||||
process.exit(2);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* Which repository methods the Postgres probe calls, and with what.
|
||||
*
|
||||
* The probe has no fixtures: it reads every repository class with the
|
||||
* TypeScript checker and builds one sample argument list per public method
|
||||
* from the declared parameter types (a number is 1, a string is "probe" or a
|
||||
* date-shaped string when the name says so, an object gets every property
|
||||
* it can sample, an array one element). The values only have to get the
|
||||
* method to send its SQL; what the probe measures is whether Postgres
|
||||
* accepts that SQL against an empty schema. A sample the column cannot take
|
||||
* (a name-shaped string in a date column) is a data error, which the
|
||||
* ratchet does not hold (pg-probe/baseline.ts). A parameter the sampler
|
||||
* cannot build (a callback, an EntityManager, an entity instance) makes the
|
||||
* method unprobeable: the report lists it instead of guessing, and the
|
||||
* baseline's `uncovered` list must name it, so a new one fails the run.
|
||||
*/
|
||||
import path from 'node:path';
|
||||
import ts from 'typescript';
|
||||
|
||||
export type Sample = { ok: true; value: unknown } | { ok: false; reason: string };
|
||||
|
||||
export type MethodPlan =
|
||||
| { className: string; file: string; method: string; args: unknown[] }
|
||||
| { className: string; file: string; method: string; unprobeable: string };
|
||||
|
||||
const MAX_DEPTH = 4;
|
||||
const SAMPLE_DATE = '2026-01-01';
|
||||
const SAMPLE_TIMESTAMP = '2026-01-01 00:00:00';
|
||||
|
||||
/** A string sample shaped by the parameter or property name it is for. */
|
||||
export function sampleString(name: string): string {
|
||||
const lower = name.toLowerCase();
|
||||
if (/(^|_)(date|day)$|date$/.test(lower) || /^(start|end|from|to)$/.test(lower)) return SAMPLE_DATE;
|
||||
if (/(_at|time|timestamp)$/.test(lower) || /At$/.test(name)) return SAMPLE_TIMESTAMP;
|
||||
if (lower.includes('email')) return 'probe@example.com';
|
||||
if (/(url|uri|href)$/.test(lower)) return 'https://example.com/probe';
|
||||
if (/colou?r$/.test(lower)) return '#000000';
|
||||
if (/(^|_)ids?$|Ids?$/.test(name)) return '1';
|
||||
return 'probe';
|
||||
}
|
||||
|
||||
const OK = (value: unknown): Sample => ({ ok: true, value });
|
||||
const NO = (reason: string): Sample => ({ ok: false, reason });
|
||||
|
||||
/** Why a sample failed (the server's non-strict config does not narrow `ok: false`). */
|
||||
function reasonOf(sample: Sample): string {
|
||||
return 'reason' in sample ? sample.reason : '';
|
||||
}
|
||||
|
||||
function isNullish(type: ts.Type): boolean {
|
||||
return (type.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void)) !== 0;
|
||||
}
|
||||
|
||||
function declaredInNodeModules(symbol: ts.Symbol | undefined): boolean {
|
||||
const declarations = symbol?.getDeclarations() ?? [];
|
||||
return declarations.length > 0 && declarations.every((d) => d.getSourceFile().fileName.includes('/node_modules/'));
|
||||
}
|
||||
|
||||
/** Builds a sample value for `type`; `name` is the parameter or property it is for. */
|
||||
export function sampleFor(checker: ts.TypeChecker, type: ts.Type, name: string, depth = 0): Sample {
|
||||
if (depth > MAX_DEPTH) return NO(`${name}: nested deeper than ${MAX_DEPTH}`);
|
||||
const flags = type.flags;
|
||||
if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) return OK(sampleString(name));
|
||||
if (flags & ts.TypeFlags.TypeParameter) {
|
||||
const constraint = checker.getBaseConstraintOfType(type);
|
||||
return constraint && constraint !== type ? sampleFor(checker, constraint, name, depth + 1) : OK(sampleString(name));
|
||||
}
|
||||
if (type.isUnion()) {
|
||||
const members = type.types.filter((member) => !isNullish(member));
|
||||
if (members.length === 0) return OK(null);
|
||||
if (members.every((member) => member.flags & ts.TypeFlags.BooleanLiteral)) return OK(false);
|
||||
const numeric = members.find((member) => member.flags & ts.TypeFlags.NumberLike);
|
||||
return sampleFor(checker, numeric ?? members[0]!, name, depth + 1);
|
||||
}
|
||||
if (type.isStringLiteral()) return OK(type.value);
|
||||
if (type.isNumberLiteral()) return OK(type.value);
|
||||
if (flags & ts.TypeFlags.BooleanLiteral) return OK(checker.typeToString(type) === 'true');
|
||||
if (flags & ts.TypeFlags.BooleanLike) return OK(false);
|
||||
if (flags & ts.TypeFlags.BigIntLike) return OK(BigInt(1));
|
||||
if (flags & ts.TypeFlags.NumberLike) return OK(1);
|
||||
if (flags & (ts.TypeFlags.StringLike | ts.TypeFlags.TemplateLiteral)) return OK(sampleString(name));
|
||||
if (isNullish(type)) return OK(null);
|
||||
if (type.isIntersection()) return sampleObject(checker, type, name, depth);
|
||||
if (flags & ts.TypeFlags.Object) return sampleObjectType(checker, type as ts.ObjectType, name, depth);
|
||||
return NO(`${name}: no sample for ${checker.typeToString(type)}`);
|
||||
}
|
||||
|
||||
function sampleObjectType(checker: ts.TypeChecker, type: ts.ObjectType, name: string, depth: number): Sample {
|
||||
if (checker.isTupleType(type)) {
|
||||
const values: unknown[] = [];
|
||||
for (const [i, element] of checker.getTypeArguments(type as ts.TypeReference).entries()) {
|
||||
const sample = sampleFor(checker, element, `${name}[${i}]`, depth + 1);
|
||||
if (!sample.ok) return sample;
|
||||
values.push(sample.value);
|
||||
}
|
||||
return OK(values);
|
||||
}
|
||||
if (checker.isArrayType(type)) {
|
||||
const element = checker.getTypeArguments(type as ts.TypeReference)[0];
|
||||
if (!element) return OK([]);
|
||||
const sample = sampleFor(checker, element, singular(name), depth + 1);
|
||||
return sample.ok ? OK([sample.value]) : sample;
|
||||
}
|
||||
const symbolName = type.getSymbol()?.getName();
|
||||
if (symbolName === 'Date') return OK(new Date(`${SAMPLE_DATE}T00:00:00Z`));
|
||||
if (symbolName === 'Buffer' || symbolName === 'Uint8Array') return OK(Buffer.from('probe'));
|
||||
if (symbolName === 'Set' || symbolName === 'ReadonlySet' || symbolName === 'Map' || symbolName === 'ReadonlyMap') {
|
||||
return sampleCollection(checker, type, symbolName, name, depth);
|
||||
}
|
||||
if (type.getCallSignatures().length > 0) return NO(`${name}: a function parameter`);
|
||||
if (symbolName === 'Promise') return NO(`${name}: a promise parameter`);
|
||||
const symbol = type.getSymbol();
|
||||
if (symbol && symbol.flags & (ts.SymbolFlags.Class | ts.SymbolFlags.Interface) && declaredInNodeModules(symbol)) {
|
||||
return NO(`${name}: a ${symbolName} parameter`);
|
||||
}
|
||||
return sampleObject(checker, type, name, depth);
|
||||
}
|
||||
|
||||
function sampleCollection(
|
||||
checker: ts.TypeChecker,
|
||||
type: ts.ObjectType,
|
||||
kind: string,
|
||||
name: string,
|
||||
depth: number,
|
||||
): Sample {
|
||||
const args = checker.getTypeArguments(type as ts.TypeReference);
|
||||
const samples = args.map((arg, i) => sampleFor(checker, arg, i === 0 ? singular(name) : name, depth + 1));
|
||||
const failed = samples.find((sample) => !sample.ok);
|
||||
if (failed) return failed;
|
||||
const values = samples.map((sample) => (sample.ok ? sample.value : undefined));
|
||||
if (kind.endsWith('Set')) return OK(new Set([values[0]]));
|
||||
return OK(new Map([[values[0], values[1]]]));
|
||||
}
|
||||
|
||||
function sampleObject(checker: ts.TypeChecker, type: ts.Type, name: string, depth: number): Sample {
|
||||
const value: Record<string, unknown> = {};
|
||||
for (const property of checker.getPropertiesOfType(type)) {
|
||||
const propertyType = checker.getTypeOfSymbol(property);
|
||||
if (propertyType.getCallSignatures().length > 0) continue;
|
||||
const optional = (property.flags & ts.SymbolFlags.Optional) !== 0;
|
||||
const sample = sampleFor(checker, propertyType, property.getName(), depth + 1);
|
||||
if (sample.ok) value[property.getName()] = sample.value;
|
||||
else if (!optional) return NO(`${name}.${reasonOf(sample)}`);
|
||||
}
|
||||
return OK(value);
|
||||
}
|
||||
|
||||
function singular(name: string): string {
|
||||
return name.endsWith('s') ? name.slice(0, -1) : name;
|
||||
}
|
||||
|
||||
function isPublicMethod(member: ts.ClassElement): member is ts.MethodDeclaration {
|
||||
if (!ts.isMethodDeclaration(member) || !member.body || !ts.isIdentifier(member.name)) return false;
|
||||
const modifiers = ts.getCombinedModifierFlags(member);
|
||||
return (modifiers & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected | ts.ModifierFlags.Static)) === 0;
|
||||
}
|
||||
|
||||
/** The sample argument list for one method, or why there is none. */
|
||||
export function planMethod(
|
||||
checker: ts.TypeChecker,
|
||||
method: ts.MethodDeclaration,
|
||||
): { args: unknown[] } | { unprobeable: string } {
|
||||
const args: unknown[] = [];
|
||||
for (const parameter of method.parameters) {
|
||||
const name = ts.isIdentifier(parameter.name) ? parameter.name.text : 'options';
|
||||
const optional = parameter.questionToken !== undefined || parameter.initializer !== undefined;
|
||||
const sample = sampleFor(checker, checker.getTypeAtLocation(parameter), name);
|
||||
if (!sample.ok) {
|
||||
if (optional || parameter.dotDotDotToken) break;
|
||||
return { unprobeable: reasonOf(sample) };
|
||||
}
|
||||
if (parameter.dotDotDotToken && Array.isArray(sample.value)) args.push(...(sample.value as unknown[]));
|
||||
else args.push(sample.value);
|
||||
}
|
||||
return { args };
|
||||
}
|
||||
|
||||
/** Every public method of every exported class declared in `files`, with its sample arguments. */
|
||||
export function planRepositories(
|
||||
files: readonly string[],
|
||||
compilerOptions: ts.CompilerOptions,
|
||||
root: string,
|
||||
): MethodPlan[] {
|
||||
const program = ts.createProgram({ rootNames: [...files], options: { ...compilerOptions, noEmit: true } });
|
||||
const checker = program.getTypeChecker();
|
||||
const wanted = new Set(files.map((file) => path.resolve(file)));
|
||||
const plans: MethodPlan[] = [];
|
||||
for (const sourceFile of program.getSourceFiles()) {
|
||||
if (!wanted.has(path.resolve(sourceFile.fileName))) continue;
|
||||
const file = path.relative(root, sourceFile.fileName).split(path.sep).join('/');
|
||||
for (const statement of sourceFile.statements) {
|
||||
if (!ts.isClassDeclaration(statement) || !statement.name) continue;
|
||||
if (!(ts.getCombinedModifierFlags(statement) & ts.ModifierFlags.Export)) continue;
|
||||
if (ts.getCombinedModifierFlags(statement) & ts.ModifierFlags.Abstract) continue;
|
||||
const className = statement.name.text;
|
||||
for (const member of statement.members) {
|
||||
if (!isPublicMethod(member)) continue;
|
||||
const method = (member.name as ts.Identifier).text;
|
||||
const plan = planMethod(checker, member);
|
||||
plans.push(
|
||||
'args' in plan
|
||||
? { className, file, method, args: plan.args }
|
||||
: { className, file, method, unprobeable: plan.unprobeable },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return plans.sort((a, b) => `${a.className}.${a.method}`.localeCompare(`${b.className}.${b.method}`));
|
||||
}
|
||||
|
||||
/** The compiler options of a tsconfig file, as `tsc -p` would read them. */
|
||||
export function readCompilerOptions(tsconfigPath: string): ts.CompilerOptions {
|
||||
const read = ts.readConfigFile(tsconfigPath, (file) => ts.sys.readFile(file));
|
||||
if (read.error) throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, '\n'));
|
||||
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, path.dirname(tsconfigPath));
|
||||
return parsed.options;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* The Postgres probe's ratchet: how many statements of each repository method
|
||||
* Postgres may still refuse, and which methods the probe may still leave
|
||||
* unmeasured.
|
||||
*
|
||||
* `scripts/pg-probe-baseline.json` maps `Class.method` to the number of
|
||||
* distinct statements of that method that failed on Postgres when the entry
|
||||
* was written. A method may fail no more statements than its entry (none
|
||||
* without one), and an entry above what its method fails now fails the check
|
||||
* too, so the change that fixes a statement lowers the baseline with it.
|
||||
* `--update` lowers entries and drops the ones that reach zero or whose
|
||||
* method is gone; it never raises or adds one.
|
||||
*
|
||||
* Only statements Postgres refuses as SQL count here (SQLSTATE classes 42
|
||||
* and 0A, see `countsTowardRatchet`). A value the sample arguments got wrong
|
||||
* (class 22, a sample string in a date column) says nothing about the
|
||||
* dialect and is reported without being held.
|
||||
*
|
||||
* `uncovered` lists the methods whose SQL the probe did not see: the ones it
|
||||
* could not call, the ones that sent no SQL (they threw first, or never
|
||||
* reach the database) and the ones that timed out. A method outside that
|
||||
* list that ends up uncovered (a new method the sampler cannot build
|
||||
* arguments for, or an old one that starts throwing before its first
|
||||
* statement) fails the run, and so does an entry whose method is measured
|
||||
* now or gone, so the list only shrinks and the part of the code the probe
|
||||
* reaches cannot quietly shrink with it.
|
||||
*
|
||||
* The only exception is the first run: a baseline whose `failing` or
|
||||
* `uncovered` is `null` has never been measured, so there is nothing to
|
||||
* compare and the run fails (scripts/pg-probe.ts) until the first
|
||||
* measurement, written by `--update` or taken from the CI artifact, is
|
||||
* committed.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
export interface ProbeBaseline {
|
||||
/** `Class.method` → failing statements allowed; `null` until the first measurement is written. */
|
||||
failing: Record<string, number> | null;
|
||||
/** `Class.method` names the probe may leave unmeasured; `null` until the first measurement is written. */
|
||||
uncovered: string[] | null;
|
||||
}
|
||||
|
||||
export interface BaselineVerdict {
|
||||
/** The baseline has never been measured: nothing to compare, and the run fails until it is seeded. */
|
||||
unseeded: boolean;
|
||||
/** Methods failing more statements than their entry allows. */
|
||||
grown: { method: string; allowed: number; now: number }[];
|
||||
/** Entries above what their method fails now (the method may be gone). */
|
||||
stale: { method: string; allowed: number; now: number }[];
|
||||
/** Methods the probe did not measure that the baseline does not list. */
|
||||
newlyUncovered: string[];
|
||||
/** Entries in `uncovered` whose method is measured now, or gone. */
|
||||
nowCovered: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a refused statement counts toward the ratchet: SQLSTATE class 42
|
||||
* (syntax error, unknown function, operator or column, datatype mismatch)
|
||||
* and class 0A (feature not supported) are what a SQLite-only spelling gets.
|
||||
* Anything else (a data exception such as 22P02 or 22007, a constraint, a
|
||||
* timeout) comes from the sample values or the empty tables, not the SQL.
|
||||
*/
|
||||
export function countsTowardRatchet(code: string): boolean {
|
||||
return /^(42|0A)/.test(code);
|
||||
}
|
||||
|
||||
const METHOD_KEY = /^[A-Za-z_$][\w$]*\.[A-Za-z_$][\w$]*$/;
|
||||
|
||||
export function parseBaseline(text: string, source: string): ProbeBaseline {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(text);
|
||||
} catch (error) {
|
||||
throw new Error(`${source} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
if (data === null || typeof data !== 'object' || Array.isArray(data) || !('failing' in data)) {
|
||||
throw new Error(`${source} must be an object with a "failing" key`);
|
||||
}
|
||||
return {
|
||||
failing: parseFailing((data as { failing: unknown }).failing, source),
|
||||
uncovered: parseUncovered((data as { uncovered?: unknown }).uncovered, source),
|
||||
};
|
||||
}
|
||||
|
||||
function parseFailing(failing: unknown, source: string): Record<string, number> | null {
|
||||
if (failing === null) return null;
|
||||
if (typeof failing !== 'object' || Array.isArray(failing)) {
|
||||
throw new Error(`${source}: "failing" must be null or an object of Class.method to counts`);
|
||||
}
|
||||
const entries: Record<string, number> = {};
|
||||
for (const [method, count] of Object.entries(failing as Record<string, unknown>)) {
|
||||
if (!METHOD_KEY.test(method)) {
|
||||
throw new Error(`${source}: "${method}" is not a Class.method key`);
|
||||
}
|
||||
if (typeof count !== 'number' || !Number.isInteger(count) || count < 1) {
|
||||
throw new Error(`${source}: ${method} holds ${JSON.stringify(count)}, expected a positive integer`);
|
||||
}
|
||||
entries[method] = count;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** A missing `uncovered` key reads as unmeasured, so a baseline written before the list existed gets it seeded. */
|
||||
function parseUncovered(uncovered: unknown, source: string): string[] | null {
|
||||
if (uncovered === undefined || uncovered === null) return null;
|
||||
if (!Array.isArray(uncovered))
|
||||
throw new Error(`${source}: "uncovered" must be null or an array of Class.method names`);
|
||||
const seen = new Set<string>();
|
||||
for (const method of uncovered as unknown[]) {
|
||||
if (typeof method !== 'string' || !METHOD_KEY.test(method)) {
|
||||
throw new Error(`${source}: "uncovered" holds ${JSON.stringify(method)}, expected a Class.method name`);
|
||||
}
|
||||
if (seen.has(method)) throw new Error(`${source}: "uncovered" lists ${method} twice`);
|
||||
seen.add(method);
|
||||
}
|
||||
return [...seen];
|
||||
}
|
||||
|
||||
export function readBaseline(path: string): ProbeBaseline {
|
||||
return parseBaseline(readFileSync(path, 'utf8'), path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares what failed now (`Class.method` → failing statements, zero counts
|
||||
* allowed) and which methods went unmeasured now with the baseline.
|
||||
*/
|
||||
export function compareWithBaseline(
|
||||
baseline: ProbeBaseline,
|
||||
failingNow: ReadonlyMap<string, number>,
|
||||
uncoveredNow: ReadonlySet<string>,
|
||||
): BaselineVerdict {
|
||||
if (baseline.failing === null || baseline.uncovered === null) {
|
||||
return { unseeded: true, grown: [], stale: [], newlyUncovered: [], nowCovered: [] };
|
||||
}
|
||||
const allowedFor = baseline.failing;
|
||||
const grown: BaselineVerdict['grown'] = [];
|
||||
const stale: BaselineVerdict['stale'] = [];
|
||||
for (const [method, now] of [...failingNow.entries()].sort(([a], [b]) => a.localeCompare(b))) {
|
||||
const allowed = allowedFor[method] ?? 0;
|
||||
if (now > allowed) grown.push({ method, allowed, now });
|
||||
}
|
||||
for (const method of Object.keys(allowedFor).sort()) {
|
||||
const allowed = allowedFor[method]!;
|
||||
const now = failingNow.get(method) ?? 0;
|
||||
if (now < allowed) stale.push({ method, allowed, now });
|
||||
}
|
||||
const listed = new Set(baseline.uncovered);
|
||||
const newlyUncovered = [...uncoveredNow].filter((method) => !listed.has(method)).sort((a, b) => a.localeCompare(b));
|
||||
const nowCovered = [...listed].filter((method) => !uncoveredNow.has(method)).sort((a, b) => a.localeCompare(b));
|
||||
return { unseeded: false, grown, stale, newlyUncovered, nowCovered };
|
||||
}
|
||||
|
||||
/**
|
||||
* The baseline `--update` writes: every entry lowered to what its method
|
||||
* fails now, zeros dropped, `uncovered` cut to the methods still unmeasured,
|
||||
* nothing added. An unseeded part is seeded with what the run saw.
|
||||
*/
|
||||
export function lowerBaseline(
|
||||
baseline: ProbeBaseline,
|
||||
failingNow: ReadonlyMap<string, number>,
|
||||
uncoveredNow: ReadonlySet<string>,
|
||||
): ProbeBaseline {
|
||||
const next: Record<string, number> = {};
|
||||
if (baseline.failing === null) {
|
||||
for (const [method, now] of failingNow) if (now > 0) next[method] = now;
|
||||
} else {
|
||||
for (const [method, allowed] of Object.entries(baseline.failing)) {
|
||||
const now = Math.min(allowed, failingNow.get(method) ?? 0);
|
||||
if (now > 0) next[method] = now;
|
||||
}
|
||||
}
|
||||
const uncovered =
|
||||
baseline.uncovered === null ? [...uncoveredNow] : baseline.uncovered.filter((method) => uncoveredNow.has(method));
|
||||
return {
|
||||
failing: Object.fromEntries(Object.entries(next).sort(([a], [b]) => a.localeCompare(b))),
|
||||
uncovered: [...new Set(uncovered)].sort((a, b) => a.localeCompare(b)),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatBaseline(baseline: ProbeBaseline): string {
|
||||
return `${JSON.stringify(baseline, null, 2)}\n`;
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
/**
|
||||
* The parts of the Postgres probe that talk to a database: the two MikroORM
|
||||
* instances (a stock one that builds the schema and runs the helper cases,
|
||||
* and one whose driver records every repository statement), the scratch
|
||||
* SQLite database the helper cases are compared on, and the loop that calls
|
||||
* every repository method.
|
||||
*/
|
||||
import { ALL_ENTITIES } from '../../src/db/entities';
|
||||
import type { MethodPlan } from './arg-samples';
|
||||
import {
|
||||
VALUES_TABLE,
|
||||
VALUES_TABLE_DDL,
|
||||
type HelperEngine,
|
||||
type KyselySelect,
|
||||
type RawSelect,
|
||||
type ValuesDB,
|
||||
type ValuesRow,
|
||||
} from './helper-cases';
|
||||
import { ProbePostgresDialect, type StatementRecorder } from './recorder';
|
||||
import type { MethodResult } from './report';
|
||||
import { adjustColumns, NOCASE_COLLATION_SQL, splitStatements, type ColumnMeta } from './schema';
|
||||
import { RequestContext, type Configuration, type EntityManager, type EntityProperty } from '@mikro-orm/core';
|
||||
import { MikroORM, PostgreSqlConnection, PostgreSqlDriver, type Options } from '@mikro-orm/postgresql';
|
||||
import { SqlitePlatform } from '@mikro-orm/sql';
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import {
|
||||
DummyDriver,
|
||||
Kysely,
|
||||
SqliteAdapter,
|
||||
SqliteIntrospector,
|
||||
SqliteQueryCompiler,
|
||||
type PostgresDialect,
|
||||
} from 'kysely';
|
||||
import path from 'node:path';
|
||||
|
||||
/** Marks a database the probe built, so a rerun may drop what it finds there and nothing else. */
|
||||
const MARKER_TABLE = 'trek_pg_probe_marker';
|
||||
|
||||
function baseOptions(url: string): Options {
|
||||
return {
|
||||
clientUrl: url,
|
||||
entities: [...ALL_ENTITIES],
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
debug: false,
|
||||
allowGlobalContext: true,
|
||||
pool: { min: 0, max: 4 },
|
||||
schemaGenerator: { createForeignKeyConstraints: false },
|
||||
};
|
||||
}
|
||||
|
||||
/** The stock ORM: builds the schema and runs the helper cases. */
|
||||
export function connectSetupOrm(url: string): Promise<MikroORM> {
|
||||
return MikroORM.init(baseOptions(url));
|
||||
}
|
||||
|
||||
/** A Postgres driver whose Kysely dialect records every statement (see recorder.ts). */
|
||||
export function createProbeDriverClass(
|
||||
recorder: StatementRecorder,
|
||||
statementTimeoutMs: number,
|
||||
): typeof PostgreSqlDriver {
|
||||
class ProbeConnection extends PostgreSqlConnection {
|
||||
override createKyselyDialect(
|
||||
overrides: Parameters<PostgreSqlConnection['createKyselyDialect']>[0],
|
||||
): PostgresDialect {
|
||||
return new ProbePostgresDialect(super.createKyselyDialect(overrides), recorder, statementTimeoutMs);
|
||||
}
|
||||
}
|
||||
return class ProbePostgreSqlDriver extends PostgreSqlDriver {
|
||||
constructor(config: Configuration) {
|
||||
super(config);
|
||||
// Same seam as src/db/orm-driver.ts: the base constructor hardcodes the
|
||||
// connection class, so the instance is swapped before anything connects.
|
||||
(this as unknown as { connection: PostgreSqlConnection }).connection = new ProbeConnection(config);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function connectProbeOrm(
|
||||
url: string,
|
||||
recorder: StatementRecorder,
|
||||
statementTimeoutMs: number,
|
||||
): Promise<MikroORM> {
|
||||
return MikroORM.init({ ...baseOptions(url), driver: createProbeDriverClass(recorder, statementTimeoutMs) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a database that holds tables the probe did not create, then drops
|
||||
* and recreates the `public` schema. The probe needs a throwaway database
|
||||
* (CI's service container); pointing it at anything else must not cost data.
|
||||
*/
|
||||
async function resetDatabase(orm: MikroORM): Promise<void> {
|
||||
const connection = orm.em.getConnection();
|
||||
const tables = await connection.execute<{ table_name: string }[]>(
|
||||
"select table_name from information_schema.tables where table_schema = 'public'",
|
||||
);
|
||||
const names = tables.map((row) => row.table_name);
|
||||
if (names.length > 0 && !names.includes(MARKER_TABLE)) {
|
||||
throw new Error(
|
||||
`refusing to run: the database holds ${names.length} table(s) the probe did not create. Point it at an empty database.`,
|
||||
);
|
||||
}
|
||||
if (names.length > 0) {
|
||||
await connection.execute('drop schema public cascade');
|
||||
await connection.execute('create schema public');
|
||||
}
|
||||
await connection.execute(`create table ${MARKER_TABLE} (created_at text)`);
|
||||
}
|
||||
|
||||
export interface SchemaFailure {
|
||||
statement: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** Resets the database and builds the probe schema; returns the DDL statements Postgres refused. */
|
||||
export async function prepareDatabase(
|
||||
orm: MikroORM,
|
||||
): Promise<{ failures: SchemaFailure[]; adjusted: number; statements: number }> {
|
||||
await resetDatabase(orm);
|
||||
const connection = orm.em.getConnection();
|
||||
const failures: SchemaFailure[] = [];
|
||||
const run = async (statement: string): Promise<void> => {
|
||||
try {
|
||||
await connection.execute(statement);
|
||||
} catch (error) {
|
||||
failures.push({ statement, message: error instanceof Error ? error.message.split('\n')[0]! : String(error) });
|
||||
}
|
||||
};
|
||||
await run(NOCASE_COLLATION_SQL);
|
||||
let adjusted = 0;
|
||||
for (const meta of orm.getMetadata().getAll().values()) {
|
||||
adjusted += adjustColumns(meta.props as EntityProperty[] as ColumnMeta[]).length;
|
||||
}
|
||||
const statements = splitStatements(await orm.schema.getCreateSchemaSQL({ wrap: false }));
|
||||
for (const statement of statements) await run(statement);
|
||||
await run(VALUES_TABLE_DDL.postgres);
|
||||
return { failures, adjusted, statements: statements.length };
|
||||
}
|
||||
|
||||
export function postgresHelperEngine(orm: MikroORM): HelperEngine {
|
||||
const connection = orm.em.getConnection();
|
||||
const kysely = orm.em.getKysely<ValuesDB>();
|
||||
return {
|
||||
engine: 'postgres',
|
||||
platform: orm.em.getPlatform(),
|
||||
async writeRow(row: ValuesRow) {
|
||||
await connection.execute(`delete from ${VALUES_TABLE}`);
|
||||
await kysely.insertInto(VALUES_TABLE).values(row).execute();
|
||||
},
|
||||
async selectRaw(select: RawSelect) {
|
||||
const sql = `select ${select.sql}${select.column ? '' : ' as v'} from ${VALUES_TABLE}`;
|
||||
const rows = await connection.execute<Record<string, unknown>[]>(sql, select.params);
|
||||
return rows[0]?.[select.column ?? 'v'];
|
||||
},
|
||||
async selectKysely(select: KyselySelect) {
|
||||
const platform = orm.em.getPlatform();
|
||||
const row = await kysely
|
||||
.selectFrom(VALUES_TABLE)
|
||||
.select((eb) => select(platform, eb).as('v'))
|
||||
.executeTakeFirst();
|
||||
return row?.v;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The same cases on an in-memory SQLite database, through the SQLite branch of every helper. */
|
||||
export function sqliteHelperEngine(): HelperEngine & { close(): void } {
|
||||
const db = new Database(':memory:');
|
||||
db.exec(VALUES_TABLE_DDL.sqlite);
|
||||
const platform = new SqlitePlatform();
|
||||
const compiler = new Kysely<ValuesDB>({
|
||||
dialect: {
|
||||
createAdapter: () => new SqliteAdapter(),
|
||||
createDriver: () => new DummyDriver(),
|
||||
createIntrospector: (kysely) => new SqliteIntrospector(kysely),
|
||||
createQueryCompiler: () => new SqliteQueryCompiler(),
|
||||
},
|
||||
});
|
||||
const bind = (value: unknown): unknown => (typeof value === 'boolean' ? Number(value) : value);
|
||||
return {
|
||||
engine: 'sqlite',
|
||||
platform,
|
||||
async writeRow(row: ValuesRow) {
|
||||
db.prepare(`delete from ${VALUES_TABLE}`).run();
|
||||
db.prepare(`insert into ${VALUES_TABLE} (id, a, b, n, x) values (?, ?, ?, ?, ?)`).run(
|
||||
row.id,
|
||||
row.a,
|
||||
row.b,
|
||||
row.n,
|
||||
row.x,
|
||||
);
|
||||
},
|
||||
async selectRaw(select: RawSelect) {
|
||||
const sql = `select ${select.sql}${select.column ? '' : ' as v'} from ${VALUES_TABLE}`;
|
||||
const row = db.prepare(sql).get(...select.params.map(bind)) as Record<string, unknown> | undefined;
|
||||
return row?.[select.column ?? 'v'];
|
||||
},
|
||||
async selectKysely(select: KyselySelect) {
|
||||
const compiled = compiler
|
||||
.selectFrom(VALUES_TABLE)
|
||||
.select((eb) => select(platform, eb).as('v'))
|
||||
.compile();
|
||||
const row = db.prepare(compiled.sql).get(...compiled.parameters.map(bind)) as Record<string, unknown> | undefined;
|
||||
return row?.v;
|
||||
},
|
||||
close: () => db.close(),
|
||||
};
|
||||
}
|
||||
|
||||
type RepositoryFactory = (em: EntityManager) => object;
|
||||
|
||||
/** How to reach each repository class: through its entity, or `new X(em)` for the two that have none. */
|
||||
function repositoryFactories(
|
||||
orm: MikroORM,
|
||||
plans: readonly MethodPlan[],
|
||||
serverRoot: string,
|
||||
): Map<string, RepositoryFactory | string> {
|
||||
const byEntity = new Map<string, RepositoryFactory>();
|
||||
for (const meta of orm.getMetadata().getAll().values()) {
|
||||
const repository = meta.repository?.();
|
||||
if (repository) byEntity.set(repository.name, (em) => em.getRepository(meta.class));
|
||||
}
|
||||
const factories = new Map<string, RepositoryFactory | string>();
|
||||
for (const plan of plans) {
|
||||
if (factories.has(plan.className)) continue;
|
||||
const viaEntity = byEntity.get(plan.className);
|
||||
if (viaEntity) {
|
||||
factories.set(plan.className, viaEntity);
|
||||
continue;
|
||||
}
|
||||
const exported = (require(path.join(serverRoot, plan.file)) as Record<string, unknown>)[plan.className];
|
||||
if (typeof exported === 'function' && exported.length === 1) {
|
||||
const RepositoryClass = exported as new (em: EntityManager) => object;
|
||||
factories.set(plan.className, (em) => new RepositoryClass(em));
|
||||
} else {
|
||||
factories.set(plan.className, 'no entity maps it and it does not take an EntityManager');
|
||||
}
|
||||
}
|
||||
return factories;
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, ms: number): Promise<{ value: T } | 'timeout'> {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<'timeout'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('timeout'), ms);
|
||||
});
|
||||
return Promise.race([promise.then((value) => ({ value })), timeout]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/** Calls every planned method once, inside a request context, and collects what each one sent. */
|
||||
export async function probeRepositories(
|
||||
orm: MikroORM,
|
||||
recorder: StatementRecorder,
|
||||
plans: readonly MethodPlan[],
|
||||
serverRoot: string,
|
||||
methodTimeoutMs: number,
|
||||
): Promise<MethodResult[]> {
|
||||
const factories = repositoryFactories(orm, plans, serverRoot);
|
||||
const results: MethodResult[] = [];
|
||||
for (const plan of plans) {
|
||||
const key = `${plan.className}.${plan.method}`;
|
||||
const factory = factories.get(plan.className);
|
||||
if ('unprobeable' in plan) {
|
||||
results.push({ key, statements: [], unprobeable: plan.unprobeable });
|
||||
continue;
|
||||
}
|
||||
if (typeof factory !== 'function') {
|
||||
results.push({ key, statements: [], unprobeable: factory ?? 'unknown class' });
|
||||
continue;
|
||||
}
|
||||
const result: MethodResult = { key, statements: [] };
|
||||
try {
|
||||
const outcome = await recorder.run(key, () =>
|
||||
withTimeout(
|
||||
RequestContext.create(orm.em, async () => {
|
||||
const repository = factory(RequestContext.getEntityManager() ?? orm.em.fork()) as Record<string, unknown>;
|
||||
const method = repository[plan.method];
|
||||
if (typeof method !== 'function') throw new Error(`${key} is not a function at runtime`);
|
||||
return (await (method as (...args: unknown[]) => unknown).apply(repository, plan.args)) as unknown;
|
||||
}),
|
||||
methodTimeoutMs,
|
||||
),
|
||||
);
|
||||
if (outcome === 'timeout') result.timedOut = true;
|
||||
} catch (error) {
|
||||
result.threw = error instanceof Error ? error.message.split('\n')[0]! : String(error);
|
||||
}
|
||||
result.statements = [...recorder.statementsOf(key)];
|
||||
results.push(result);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
/**
|
||||
* The dialect helpers, run on both engines.
|
||||
*
|
||||
* Each case puts one row into a scratch table, selects one helper's
|
||||
* expression over it and checks the value. The same case runs on SQLite
|
||||
* (an in-memory better-sqlite3 database) and on Postgres, so a Postgres
|
||||
* branch is held to what its SQLite twin returns, not to a value written
|
||||
* down once. The cases stay inside what both engines agree on: Postgres
|
||||
* folds every letter in LOWER and NOCASE while SQLite folds only ASCII (the
|
||||
* helpers' docstrings say so), and what Postgres does with a non-ASCII
|
||||
* letter also depends on the database's locale, so the inputs are ASCII. An
|
||||
* expectation may still name a value per engine where they are meant to
|
||||
* differ.
|
||||
*
|
||||
* Unlike the repository statements, nothing here is baselined: every case
|
||||
* must pass on both engines.
|
||||
*/
|
||||
import {
|
||||
castIntegerKysely,
|
||||
concatKysely,
|
||||
currentTimestampKysely,
|
||||
nowPlusSecondsKysely,
|
||||
startsWithIsoDateKysely,
|
||||
substringKysely,
|
||||
unixEpochToIsoKysely,
|
||||
} from '../../src/db/dialect/kysely-functions';
|
||||
import {
|
||||
absDifference,
|
||||
caseWhenEquals,
|
||||
caseWhenNotNull,
|
||||
castInteger,
|
||||
coalesce,
|
||||
coalesceOverride,
|
||||
coalesceOverrideWhileSame,
|
||||
coalesceParam,
|
||||
collateNoCase,
|
||||
columnIncrementedBy,
|
||||
columnRef,
|
||||
concat,
|
||||
countAll,
|
||||
countAllRef,
|
||||
currentTimestamp,
|
||||
dateAdd,
|
||||
dateOf,
|
||||
dayDistance,
|
||||
foundAgainState,
|
||||
lower,
|
||||
lowerParam,
|
||||
lowerTrim,
|
||||
lowerTrimParam,
|
||||
maxOf,
|
||||
minOf,
|
||||
nowDateOffset,
|
||||
nowMinusDays,
|
||||
nowMinusHours,
|
||||
nowPlusSeconds,
|
||||
startsWithIsoDate,
|
||||
substring,
|
||||
trim,
|
||||
} from '../../src/db/dialect/sql-functions';
|
||||
import type { Platform } from '@mikro-orm/core';
|
||||
|
||||
import type { AliasableExpression, ExpressionBuilder } from 'kysely';
|
||||
|
||||
export type Engine = 'sqlite' | 'postgres';
|
||||
|
||||
export const VALUES_TABLE = 'trek_pg_probe_values';
|
||||
|
||||
export interface ValuesRow {
|
||||
id: number;
|
||||
a: string | null;
|
||||
b: string | null;
|
||||
n: number | null;
|
||||
x: number | null;
|
||||
}
|
||||
|
||||
export interface ValuesDB {
|
||||
trek_pg_probe_values: ValuesRow;
|
||||
}
|
||||
|
||||
export const VALUES_TABLE_DDL: Record<Engine, string> = {
|
||||
sqlite: `CREATE TABLE ${VALUES_TABLE} (id INTEGER PRIMARY KEY, a TEXT, b TEXT, n INTEGER, x REAL)`,
|
||||
postgres: `CREATE TABLE ${VALUES_TABLE} (id integer PRIMARY KEY, a text, b text, n bigint, x double precision)`,
|
||||
};
|
||||
|
||||
/** A fragment rendered into `select <sql> [as v] from trek_pg_probe_values`. */
|
||||
export interface RawSelect {
|
||||
sql: string;
|
||||
params: unknown[];
|
||||
/** The fragment already names its column (`COUNT(*) as c`); read that one instead of `v`. */
|
||||
column?: string;
|
||||
}
|
||||
|
||||
export type KyselySelect = (
|
||||
platform: Platform,
|
||||
eb: ExpressionBuilder<ValuesDB, 'trek_pg_probe_values'>,
|
||||
) => AliasableExpression<unknown>;
|
||||
|
||||
export type Expectation =
|
||||
| { equals: string | number | boolean | null }
|
||||
| { timestamp: number }
|
||||
| { date: number }
|
||||
| { perEngine: Record<Engine, Expectation> };
|
||||
|
||||
export interface HelperCase {
|
||||
name: string;
|
||||
row: Partial<Omit<ValuesRow, 'id'>>;
|
||||
raw?: (platform: Platform) => RawSelect;
|
||||
kysely?: KyselySelect;
|
||||
expect: Expectation;
|
||||
}
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const CLOCK_TOLERANCE_MS = 120_000;
|
||||
|
||||
const rawOf = (fragment: { sql: string; params: readonly unknown[] }, column?: string): RawSelect => ({
|
||||
sql: fragment.sql,
|
||||
params: [...fragment.params],
|
||||
column,
|
||||
});
|
||||
|
||||
/** `(<key> = <value>)` for the helpers used as a filter key. */
|
||||
const comparison = (
|
||||
key: { sql: string; params: readonly unknown[] },
|
||||
value: { sql: string; params: readonly unknown[] },
|
||||
): RawSelect => ({
|
||||
sql: `(${key.sql} = ${value.sql})`,
|
||||
params: [...key.params, ...value.params],
|
||||
});
|
||||
|
||||
const bound = (value: unknown): { sql: string; params: unknown[] } => ({ sql: '?', params: [value] });
|
||||
|
||||
/** Epoch milliseconds as the ISO text `unixEpochToIsoKysely` renders (whole seconds, `Z`). */
|
||||
export function isoSeconds(ms: number): string {
|
||||
return new Date(Math.floor(ms / 1000) * 1000).toISOString().replace('.000Z', 'Z');
|
||||
}
|
||||
|
||||
const EPOCH_MS = 1_758_459_909_123;
|
||||
|
||||
export const HELPER_CASES: readonly HelperCase[] = [
|
||||
{
|
||||
name: 'dateOf',
|
||||
row: { a: '2026-09-21 13:05:09' },
|
||||
raw: (p) => rawOf(dateOf(p, 'a')),
|
||||
expect: { equals: '2026-09-21' },
|
||||
},
|
||||
{
|
||||
name: 'dateAdd forward',
|
||||
row: { a: '2026-09-21 13:05:09' },
|
||||
raw: (p) => rawOf(dateAdd(p, 'a', 10)),
|
||||
expect: { equals: '2026-10-01' },
|
||||
},
|
||||
{
|
||||
name: 'dateAdd back',
|
||||
row: { a: '2026-09-21 13:05:09' },
|
||||
raw: (p) => rawOf(dateAdd(p, 'a', -10)),
|
||||
expect: { equals: '2026-09-11' },
|
||||
},
|
||||
{ name: 'currentTimestamp', row: {}, raw: (p) => rawOf(currentTimestamp(p)), expect: { timestamp: 0 } },
|
||||
{ name: 'nowMinusDays', row: {}, raw: (p) => rawOf(nowMinusDays(p, 30)), expect: { timestamp: -30 * DAY_MS } },
|
||||
{ name: 'nowMinusHours', row: {}, raw: (p) => rawOf(nowMinusHours(p, 20)), expect: { timestamp: -20 * 3_600_000 } },
|
||||
{ name: 'nowPlusSeconds', row: {}, raw: (p) => rawOf(nowPlusSeconds(p, 90)), expect: { timestamp: 90_000 } },
|
||||
{ name: 'nowDateOffset back', row: {}, raw: (p) => rawOf(nowDateOffset(p, -400)), expect: { date: -400 } },
|
||||
{ name: 'nowDateOffset forward', row: {}, raw: (p) => rawOf(nowDateOffset(p, 1)), expect: { date: 1 } },
|
||||
{ name: 'columnRef', row: { n: 7 }, raw: (p) => rawOf(columnRef(p, 'n')), expect: { equals: 7 } },
|
||||
{
|
||||
name: 'columnIncrementedBy',
|
||||
row: { n: 7 },
|
||||
raw: (p) => rawOf(columnIncrementedBy(p, 'n', -2)),
|
||||
expect: { equals: 5 },
|
||||
},
|
||||
{ name: 'lower', row: { a: 'Probe@X.com' }, raw: (p) => rawOf(lower(p, 'a')), expect: { equals: 'probe@x.com' } },
|
||||
{
|
||||
name: 'lower = lowerParam',
|
||||
row: { a: 'Probe@X.com' },
|
||||
raw: (p) => comparison(lower(p, 'a'), lowerParam(p, 'PROBE@x.COM')),
|
||||
expect: { equals: true },
|
||||
},
|
||||
{ name: 'trim', row: { a: ' probe ' }, raw: (p) => rawOf(trim(p, 'a')), expect: { equals: 'probe' } },
|
||||
{ name: 'lowerTrim', row: { a: ' AbC ' }, raw: (p) => rawOf(lowerTrim(p, 'a')), expect: { equals: 'abc' } },
|
||||
{
|
||||
name: 'lowerTrim = lowerTrimParam',
|
||||
row: { a: ' AbC ' },
|
||||
raw: (p) => comparison(lowerTrim(p, 'a'), lowerTrimParam(p, ' aBc')),
|
||||
expect: { equals: true },
|
||||
},
|
||||
{
|
||||
name: 'coalesce',
|
||||
row: { a: null, b: 'fallback' },
|
||||
raw: (p) => rawOf(coalesce(p, 'a', 'b')),
|
||||
expect: { equals: 'fallback' },
|
||||
},
|
||||
{
|
||||
name: 'coalesceParam keeps the column',
|
||||
row: { a: 'stored' },
|
||||
raw: (p) => rawOf(coalesceParam(p, 'a', 'new')),
|
||||
expect: { equals: 'stored' },
|
||||
},
|
||||
{
|
||||
name: 'coalesceParam fills a null',
|
||||
row: { a: null },
|
||||
raw: (p) => rawOf(coalesceParam(p, 'a', 'new')),
|
||||
expect: { equals: 'new' },
|
||||
},
|
||||
{
|
||||
name: 'coalesceOverride prefers the value',
|
||||
row: { a: 'stored' },
|
||||
raw: (p) => rawOf(coalesceOverride(p, 'new', 'a')),
|
||||
expect: { equals: 'new' },
|
||||
},
|
||||
{
|
||||
name: 'coalesceOverride keeps on null',
|
||||
row: { a: 'stored' },
|
||||
raw: (p) => rawOf(coalesceOverride(p, null, 'a')),
|
||||
expect: { equals: 'stored' },
|
||||
},
|
||||
{ name: 'absDifference', row: { x: 4 }, raw: (p) => rawOf(absDifference(p, 'x', 6.5)), expect: { equals: 2.5 } },
|
||||
{ name: 'countAll', row: {}, raw: (p) => rawOf(countAll(p, 'c'), 'c'), expect: { equals: 1 } },
|
||||
{ name: 'countAllRef', row: {}, raw: (p) => rawOf(countAllRef(p)), expect: { equals: 1 } },
|
||||
{ name: 'minOf', row: { n: 3 }, raw: (p) => rawOf(minOf(p, 'n', 'lo'), 'lo'), expect: { equals: 3 } },
|
||||
{ name: 'maxOf', row: { n: 3 }, raw: (p) => rawOf(maxOf(p, 'n', 'hi'), 'hi'), expect: { equals: 3 } },
|
||||
{
|
||||
name: 'caseWhenEquals',
|
||||
row: { n: 7 },
|
||||
raw: (p) => rawOf(caseWhenEquals(p, 'n', 7, 'owner', 'member')),
|
||||
expect: { equals: 'owner' },
|
||||
},
|
||||
{
|
||||
name: 'caseWhenEquals else',
|
||||
row: { n: 8 },
|
||||
raw: (p) => rawOf(caseWhenEquals(p, 'n', 7, 'owner', 'member')),
|
||||
expect: { equals: 'member' },
|
||||
},
|
||||
{
|
||||
name: 'startsWithIsoDate yes',
|
||||
row: { a: '2026-09-21T10:00' },
|
||||
raw: (p) => rawOf(startsWithIsoDate(p, 'a')),
|
||||
expect: { equals: true },
|
||||
},
|
||||
{
|
||||
name: 'startsWithIsoDate no',
|
||||
row: { a: 'abcd-ef-gh' },
|
||||
raw: (p) => rawOf(startsWithIsoDate(p, 'a')),
|
||||
expect: { equals: false },
|
||||
},
|
||||
{
|
||||
name: 'substring with length',
|
||||
row: { a: '2026-09-21T10:00' },
|
||||
raw: (p) => rawOf(substring(p, 'a', 1, 10)),
|
||||
expect: { equals: '2026-09-21' },
|
||||
},
|
||||
{
|
||||
name: 'substring to the end',
|
||||
row: { a: '2026-09-21T10:00' },
|
||||
raw: (p) => rawOf(substring(p, 'a', 12)),
|
||||
expect: { equals: '10:00' },
|
||||
},
|
||||
{
|
||||
name: 'concat',
|
||||
row: { a: '2026-09-21', b: '10:00' },
|
||||
raw: (p) => rawOf(concat(p, { column: 'a' }, { value: 'T' }, { column: 'b' })),
|
||||
expect: { equals: '2026-09-21T10:00' },
|
||||
},
|
||||
{ name: 'castInteger of 14.0', row: { a: '14.0' }, raw: (p) => rawOf(castInteger(p, 'a')), expect: { equals: 14 } },
|
||||
{ name: 'castInteger of 14', row: { a: '14' }, raw: (p) => rawOf(castInteger(p, 'a')), expect: { equals: 14 } },
|
||||
{
|
||||
name: 'dayDistance',
|
||||
row: { a: '2026-09-21' },
|
||||
raw: (p) => rawOf(dayDistance(p, 'a', '2026-09-24')),
|
||||
expect: { equals: 3 },
|
||||
},
|
||||
{
|
||||
name: 'collateNoCase',
|
||||
row: { a: 'Probe' },
|
||||
raw: (p) => comparison(collateNoCase(p, 'a'), bound('pROBE')),
|
||||
expect: { equals: true },
|
||||
},
|
||||
{
|
||||
name: 'foundAgainState recovers',
|
||||
row: { a: 'remote_missing', b: 'file-1' },
|
||||
raw: (p) => rawOf(foundAgainState(p, 'a', 'b')),
|
||||
expect: { equals: 'synced' },
|
||||
},
|
||||
{
|
||||
name: 'foundAgainState passes through',
|
||||
row: { a: 'error', b: 'file-1' },
|
||||
raw: (p) => rawOf(foundAgainState(p, 'a', 'b')),
|
||||
expect: { equals: 'error' },
|
||||
},
|
||||
{
|
||||
name: 'coalesceOverrideWhileSame keeps for the same key',
|
||||
row: { a: 'https://a', n: 1 },
|
||||
raw: (p) => rawOf(coalesceOverrideWhileSame(p, null, 'n', 'a', 'https://a')),
|
||||
expect: { equals: 1 },
|
||||
},
|
||||
{
|
||||
name: 'coalesceOverrideWhileSame resets for a new key',
|
||||
row: { a: 'https://a', n: 1 },
|
||||
raw: (p) => rawOf(coalesceOverrideWhileSame(p, null, 'n', 'a', 'https://b')),
|
||||
expect: { equals: 0 },
|
||||
},
|
||||
{
|
||||
name: 'caseWhenNotNull',
|
||||
row: { a: 'x', b: 'route' },
|
||||
raw: (p) => rawOf(caseWhenNotNull(p, 'a', 'b')),
|
||||
expect: { equals: 'route' },
|
||||
},
|
||||
{
|
||||
name: 'caseWhenNotNull null',
|
||||
row: { a: null, b: 'route' },
|
||||
raw: (p) => rawOf(caseWhenNotNull(p, 'a', 'b')),
|
||||
expect: { equals: null },
|
||||
},
|
||||
{
|
||||
name: 'startsWithIsoDateKysely',
|
||||
row: { a: '2026-09-21 10:00:00' },
|
||||
kysely: (p, eb) =>
|
||||
eb
|
||||
.case()
|
||||
.when(startsWithIsoDateKysely(p, eb, 'a'))
|
||||
.then('yes')
|
||||
.else('no')
|
||||
.end(),
|
||||
expect: { equals: 'yes' },
|
||||
},
|
||||
{
|
||||
name: 'substringKysely',
|
||||
row: { a: '2026-09-21T10:00' },
|
||||
kysely: (p, eb) => substringKysely(p, eb, 'a', 1, 10),
|
||||
expect: { equals: '2026-09-21' },
|
||||
},
|
||||
{
|
||||
name: 'concatKysely',
|
||||
row: { a: '2026-09-21', b: 'xx10:00' },
|
||||
kysely: (p, eb) =>
|
||||
concatKysely(p, eb, { column: 'a' }, { value: 'T' }, { expression: substringKysely(p, eb, 'b', 3) }),
|
||||
expect: { equals: '2026-09-21T10:00' },
|
||||
},
|
||||
{
|
||||
name: 'castIntegerKysely',
|
||||
row: { a: '14.0' },
|
||||
kysely: (p, eb) => castIntegerKysely(p, eb, 'a'),
|
||||
expect: { equals: 14 },
|
||||
},
|
||||
{
|
||||
name: 'unixEpochToIsoKysely',
|
||||
row: { n: EPOCH_MS },
|
||||
kysely: (p, eb) => unixEpochToIsoKysely(p, eb, 'n'),
|
||||
expect: { equals: isoSeconds(EPOCH_MS) },
|
||||
},
|
||||
{
|
||||
name: 'nowPlusSecondsKysely',
|
||||
row: {},
|
||||
kysely: (p, eb) => nowPlusSecondsKysely(p, eb, 45),
|
||||
expect: { timestamp: 45_000 },
|
||||
},
|
||||
{ name: 'currentTimestampKysely', row: {}, kysely: (p) => currentTimestampKysely(p), expect: { timestamp: 0 } },
|
||||
];
|
||||
|
||||
const TIMESTAMP_TEXT = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
|
||||
const DATE_TEXT = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
/** Why `value` does not meet `expectation` on `engine`, or null when it does. `now` is epoch ms around the query. */
|
||||
export function checkValue(expectation: Expectation, value: unknown, engine: Engine, now: number): string | null {
|
||||
if ('perEngine' in expectation) return checkValue(expectation.perEngine[engine], value, engine, now);
|
||||
if ('timestamp' in expectation) {
|
||||
if (typeof value !== 'string' || !TIMESTAMP_TEXT.test(value))
|
||||
return `expected timestamp text, got ${JSON.stringify(value)}`;
|
||||
const off = Date.parse(`${value.replace(' ', 'T')}Z`) - (now + expectation.timestamp);
|
||||
return Math.abs(off) <= CLOCK_TOLERANCE_MS ? null : `${value} is ${Math.round(off / 1000)}s off`;
|
||||
}
|
||||
if ('date' in expectation) {
|
||||
if (typeof value !== 'string' || !DATE_TEXT.test(value)) return `expected date text, got ${JSON.stringify(value)}`;
|
||||
const wanted = Date.parse(new Date(now + expectation.date * DAY_MS).toISOString().slice(0, 10));
|
||||
return Math.abs(Date.parse(value) - wanted) <= DAY_MS
|
||||
? null
|
||||
: `${value} is not ${expectation.date} day(s) from today`;
|
||||
}
|
||||
const expected = expectation.equals;
|
||||
if (expected === null) return value === null ? null : `expected null, got ${JSON.stringify(value)}`;
|
||||
if (typeof expected === 'boolean') {
|
||||
const truthy = value === true || value === 1 || value === 't' || value === '1';
|
||||
const falsy = value === false || value === 0 || value === 'f' || value === '0';
|
||||
return (expected ? truthy : falsy) ? null : `expected ${expected}, got ${JSON.stringify(value)}`;
|
||||
}
|
||||
if (typeof expected === 'number') {
|
||||
const n =
|
||||
typeof value === 'bigint'
|
||||
? Number(value)
|
||||
: typeof value === 'string' || typeof value === 'number'
|
||||
? Number(value)
|
||||
: Number.NaN;
|
||||
return Math.abs(n - expected) < 1e-9
|
||||
? null
|
||||
: `expected ${expected}, got ${JSON.stringify(typeof value === 'bigint' ? String(value) : value)}`;
|
||||
}
|
||||
return value === expected ? null : `expected ${JSON.stringify(expected)}, got ${JSON.stringify(value)}`;
|
||||
}
|
||||
|
||||
/** How one engine runs a case: write the row, select the expression, hand back the value. */
|
||||
export interface HelperEngine {
|
||||
engine: Engine;
|
||||
platform: Platform;
|
||||
writeRow(row: ValuesRow): Promise<void>;
|
||||
selectRaw(select: RawSelect): Promise<unknown>;
|
||||
selectKysely(select: KyselySelect): Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface HelperResult {
|
||||
engine: Engine;
|
||||
name: string;
|
||||
failure: string | null;
|
||||
}
|
||||
|
||||
export async function runHelperCases(
|
||||
engine: HelperEngine,
|
||||
cases: readonly HelperCase[] = HELPER_CASES,
|
||||
): Promise<HelperResult[]> {
|
||||
const results: HelperResult[] = [];
|
||||
for (const helperCase of cases) {
|
||||
let failure: string | null;
|
||||
try {
|
||||
await engine.writeRow({ id: 1, a: null, b: null, n: null, x: null, ...helperCase.row });
|
||||
const before = Date.now();
|
||||
let value: unknown;
|
||||
if (helperCase.raw) value = await engine.selectRaw(helperCase.raw(engine.platform));
|
||||
else if (helperCase.kysely) value = await engine.selectKysely(helperCase.kysely);
|
||||
else throw new Error('a case needs raw or kysely');
|
||||
failure = checkValue(helperCase.expect, value, engine.engine, Math.round((before + Date.now()) / 2));
|
||||
} catch (error) {
|
||||
failure = `threw: ${error instanceof Error ? error.message.split('\n')[0] : String(error)}`;
|
||||
}
|
||||
results.push({ engine: engine.engine, name: helperCase.name, failure });
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* The statement recorder under the Postgres probe.
|
||||
*
|
||||
* The probe runs every repository method against an empty Postgres schema and
|
||||
* wants two things from each SQL statement the method sends: whether
|
||||
* Postgres accepts it, and that nothing it does survives. This module wraps a
|
||||
* Kysely dialect so both hold for every statement, whichever API built it
|
||||
* (the MikroORM QueryBuilder, `em.insert`, `this.kysely()`), because they all
|
||||
* end in the same Kysely driver:
|
||||
*
|
||||
* - every statement runs alone inside `begin; set local statement_timeout;
|
||||
* <statement>; rollback`, so it always meets empty tables and can never
|
||||
* hang the run;
|
||||
* - a statement Postgres refuses is recorded with its SQLSTATE and answered
|
||||
* with an empty result, the way an empty table would answer, so the method
|
||||
* goes on and its later statements are probed too;
|
||||
* - the transaction calls MikroORM and Kysely make (begin, commit,
|
||||
* savepoints) become no-ops, since each statement already rolls back.
|
||||
*
|
||||
* Statements are attributed to the method that sent them through
|
||||
* AsyncLocalStorage, so a straggler from a timed-out method can never be
|
||||
* counted against the next one.
|
||||
*/
|
||||
import {
|
||||
CompiledQuery,
|
||||
type DatabaseConnection,
|
||||
type DatabaseIntrospector,
|
||||
type DialectAdapter,
|
||||
type Driver,
|
||||
type Kysely,
|
||||
PostgresDialect,
|
||||
type QueryCompiler,
|
||||
type QueryResult,
|
||||
} from 'kysely';
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
|
||||
export type StatementOutcome = { ok: true } | { ok: false; code: string; message: string };
|
||||
|
||||
export interface StatementRecord {
|
||||
sql: string;
|
||||
outcome: StatementOutcome;
|
||||
}
|
||||
|
||||
/** Transaction control a probed method sends; each statement already runs in its own rolled-back transaction. */
|
||||
const TRANSACTION_CONTROL =
|
||||
/^\s*(begin|commit|rollback|end|abort|start\s+transaction|savepoint|release(\s+savepoint)?)\b/i;
|
||||
|
||||
export function isTransactionControl(sql: string): boolean {
|
||||
return TRANSACTION_CONTROL.test(sql);
|
||||
}
|
||||
|
||||
/** The SQLSTATE of a driver error (`pg` puts it on `code`), or a marker when there is none. */
|
||||
export function sqlState(error: unknown): string {
|
||||
if (error !== null && typeof error === 'object' && 'code' in error) {
|
||||
const code = (error as { code: unknown }).code;
|
||||
if (typeof code === 'string' && /^[0-9A-Z]{5}$/.test(code)) return code;
|
||||
}
|
||||
return 'NOSQLSTATE';
|
||||
}
|
||||
|
||||
/** The first line of an error message, without the stack. */
|
||||
export function errorLine(error: unknown): string {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return message.split('\n')[0]!.trim();
|
||||
}
|
||||
|
||||
export class StatementRecorder {
|
||||
private readonly scope = new AsyncLocalStorage<string>();
|
||||
private readonly records = new Map<string, StatementRecord[]>();
|
||||
|
||||
/** Runs `fn` with every statement it sends attributed to `key`. */
|
||||
async run<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
||||
if (!this.records.has(key)) this.records.set(key, []);
|
||||
return this.scope.run(key, fn);
|
||||
}
|
||||
|
||||
/** The method the current async context belongs to, or null outside one. */
|
||||
current(): string | null {
|
||||
return this.scope.getStore() ?? null;
|
||||
}
|
||||
|
||||
record(key: string, record: StatementRecord): void {
|
||||
const list = this.records.get(key);
|
||||
if (list) list.push(record);
|
||||
else this.records.set(key, [record]);
|
||||
}
|
||||
|
||||
statementsOf(key: string): readonly StatementRecord[] {
|
||||
return this.records.get(key) ?? [];
|
||||
}
|
||||
|
||||
entries(): [string, readonly StatementRecord[]][] {
|
||||
return [...this.records.entries()];
|
||||
}
|
||||
}
|
||||
|
||||
export class ProbeConnection implements DatabaseConnection {
|
||||
constructor(
|
||||
readonly inner: DatabaseConnection,
|
||||
private readonly recorder: StatementRecorder,
|
||||
private readonly statementTimeoutMs: number,
|
||||
) {}
|
||||
|
||||
async executeQuery<R>(compiled: CompiledQuery): Promise<QueryResult<R>> {
|
||||
const key = this.recorder.current();
|
||||
if (key === null) return this.inner.executeQuery<R>(compiled);
|
||||
if (isTransactionControl(compiled.sql)) return { rows: [] };
|
||||
|
||||
await this.inner.executeQuery(CompiledQuery.raw('begin'));
|
||||
try {
|
||||
await this.inner.executeQuery(CompiledQuery.raw(`set local statement_timeout = ${this.statementTimeoutMs}`));
|
||||
const result = await this.inner.executeQuery<R>(compiled);
|
||||
this.recorder.record(key, { sql: compiled.sql, outcome: { ok: true } });
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.recorder.record(key, {
|
||||
sql: compiled.sql,
|
||||
outcome: { ok: false, code: sqlState(error), message: errorLine(error) },
|
||||
});
|
||||
return { rows: [] };
|
||||
} finally {
|
||||
await this.inner.executeQuery(CompiledQuery.raw('rollback'));
|
||||
}
|
||||
}
|
||||
|
||||
streamQuery<R>(compiled: CompiledQuery, chunkSize?: number): AsyncIterableIterator<QueryResult<R>> {
|
||||
return this.inner.streamQuery<R>(compiled, chunkSize);
|
||||
}
|
||||
}
|
||||
|
||||
export class ProbeDriver implements Driver {
|
||||
private readonly wrapped = new WeakMap<DatabaseConnection, ProbeConnection>();
|
||||
|
||||
constructor(
|
||||
private readonly inner: Driver,
|
||||
private readonly recorder: StatementRecorder,
|
||||
private readonly statementTimeoutMs: number,
|
||||
) {}
|
||||
|
||||
init(): Promise<void> {
|
||||
return this.inner.init();
|
||||
}
|
||||
|
||||
async acquireConnection(): Promise<DatabaseConnection> {
|
||||
const connection = await this.inner.acquireConnection();
|
||||
let probe = this.wrapped.get(connection);
|
||||
if (!probe) {
|
||||
probe = new ProbeConnection(connection, this.recorder, this.statementTimeoutMs);
|
||||
this.wrapped.set(connection, probe);
|
||||
}
|
||||
return probe;
|
||||
}
|
||||
|
||||
async beginTransaction(): Promise<void> {
|
||||
// Every statement runs in a transaction of its own (ProbeConnection).
|
||||
}
|
||||
|
||||
async commitTransaction(): Promise<void> {
|
||||
// See beginTransaction.
|
||||
}
|
||||
|
||||
async rollbackTransaction(): Promise<void> {
|
||||
// See beginTransaction.
|
||||
}
|
||||
|
||||
async savepoint(): Promise<void> {
|
||||
// See beginTransaction.
|
||||
}
|
||||
|
||||
async rollbackToSavepoint(): Promise<void> {
|
||||
// See beginTransaction.
|
||||
}
|
||||
|
||||
async releaseSavepoint(): Promise<void> {
|
||||
// See beginTransaction.
|
||||
}
|
||||
|
||||
releaseConnection(connection: DatabaseConnection): Promise<void> {
|
||||
return this.inner.releaseConnection(connection instanceof ProbeConnection ? connection.inner : connection);
|
||||
}
|
||||
|
||||
destroy(): Promise<void> {
|
||||
return this.inner.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A Postgres dialect whose driver is `base`'s wrapped in a {@link ProbeDriver};
|
||||
* compiler, adapter and introspector stay `base`'s own. A subclass rather
|
||||
* than a plain `Dialect` object because MikroORM's `PostgreSqlConnection`
|
||||
* declares `createKyselyDialect()` to return a `PostgresDialect`. The config
|
||||
* handed to `super` is never read: every method that would read it is
|
||||
* overridden to delegate to `base`.
|
||||
*/
|
||||
export class ProbePostgresDialect extends PostgresDialect {
|
||||
constructor(
|
||||
private readonly base: PostgresDialect,
|
||||
private readonly recorder: StatementRecorder,
|
||||
private readonly statementTimeoutMs: number,
|
||||
) {
|
||||
super({ pool: () => Promise.reject(new Error('ProbePostgresDialect: the base dialect owns the pool')) });
|
||||
}
|
||||
|
||||
override createDriver(): Driver {
|
||||
return new ProbeDriver(this.base.createDriver(), this.recorder, this.statementTimeoutMs);
|
||||
}
|
||||
|
||||
override createQueryCompiler(): QueryCompiler {
|
||||
return this.base.createQueryCompiler();
|
||||
}
|
||||
|
||||
override createAdapter(): DialectAdapter {
|
||||
return this.base.createAdapter();
|
||||
}
|
||||
|
||||
override createIntrospector(db: Kysely<unknown>): DatabaseIntrospector {
|
||||
return this.base.createIntrospector(db);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* Turns what the Postgres probe saw into counts, a console log and the
|
||||
* Markdown the CI job writes to its step summary.
|
||||
*/
|
||||
import { countsTowardRatchet, type BaselineVerdict } from './baseline';
|
||||
import type { HelperResult } from './helper-cases';
|
||||
import type { StatementRecord } from './recorder';
|
||||
|
||||
export interface MethodResult {
|
||||
/** `Class.method`. */
|
||||
key: string;
|
||||
statements: readonly StatementRecord[];
|
||||
/** Why the method was not called at all. */
|
||||
unprobeable?: string;
|
||||
/** The method threw (in JS, after or before its SQL); the statements it sent still count. */
|
||||
threw?: string;
|
||||
timedOut?: boolean;
|
||||
}
|
||||
|
||||
export interface FailedStatement {
|
||||
method: string;
|
||||
code: string;
|
||||
message: string;
|
||||
sql: string;
|
||||
/** A dialect refusal (SQLSTATE class 42 or 0A) the ratchet holds; anything else is reported only. */
|
||||
counted: boolean;
|
||||
}
|
||||
|
||||
export interface ProbeSummary {
|
||||
methods: number;
|
||||
called: number;
|
||||
unprobeable: number;
|
||||
/** Called, but sent no SQL (a pure helper, or it threw before reaching the database). */
|
||||
withoutSql: number;
|
||||
timedOut: number;
|
||||
/** Distinct statements per method, summed. */
|
||||
statements: number;
|
||||
/** Every distinct statement Postgres refused, counted toward the ratchet or not. */
|
||||
failedStatements: FailedStatement[];
|
||||
/**
|
||||
* `Class.method` → distinct statements Postgres refused as SQL (SQLSTATE
|
||||
* class 42 or 0A); every called method appears, zeros included.
|
||||
*/
|
||||
failingByMethod: Map<string, number>;
|
||||
/**
|
||||
* `Class.method` → why the probe saw none or not all of its SQL: it could
|
||||
* not call it, it sent no SQL (it threw first, or never reaches the
|
||||
* database), or it timed out. Held to the baseline's `uncovered` list.
|
||||
*/
|
||||
uncovered: Map<string, string>;
|
||||
/** SQLSTATE → distinct failing statements. */
|
||||
failuresByCode: Map<string, number>;
|
||||
}
|
||||
|
||||
export function summarize(results: readonly MethodResult[]): ProbeSummary {
|
||||
const summary: ProbeSummary = {
|
||||
methods: results.length,
|
||||
called: 0,
|
||||
unprobeable: 0,
|
||||
withoutSql: 0,
|
||||
timedOut: 0,
|
||||
statements: 0,
|
||||
failedStatements: [],
|
||||
failingByMethod: new Map(),
|
||||
uncovered: new Map(),
|
||||
failuresByCode: new Map(),
|
||||
};
|
||||
for (const result of results) {
|
||||
if (result.unprobeable !== undefined) {
|
||||
summary.unprobeable += 1;
|
||||
summary.uncovered.set(result.key, `could not be called: ${result.unprobeable}`);
|
||||
continue;
|
||||
}
|
||||
summary.called += 1;
|
||||
if (result.timedOut) {
|
||||
summary.timedOut += 1;
|
||||
summary.uncovered.set(result.key, 'timed out');
|
||||
} else if (result.statements.length === 0) {
|
||||
summary.uncovered.set(
|
||||
result.key,
|
||||
result.threw === undefined ? 'sent no SQL' : `threw before any statement: ${result.threw}`,
|
||||
);
|
||||
}
|
||||
if (result.statements.length === 0) summary.withoutSql += 1;
|
||||
const seen = new Set<string>();
|
||||
const failed = new Map<string, StatementRecord>();
|
||||
for (const statement of result.statements) {
|
||||
seen.add(statement.sql);
|
||||
if (!statement.outcome.ok && !failed.has(statement.sql)) failed.set(statement.sql, statement);
|
||||
}
|
||||
summary.statements += seen.size;
|
||||
let counted = 0;
|
||||
for (const statement of failed.values()) {
|
||||
const outcome = statement.outcome;
|
||||
if (!('code' in outcome)) continue;
|
||||
const dialect = countsTowardRatchet(outcome.code);
|
||||
if (dialect) counted += 1;
|
||||
summary.failedStatements.push({
|
||||
method: result.key,
|
||||
code: outcome.code,
|
||||
message: outcome.message,
|
||||
sql: statement.sql,
|
||||
counted: dialect,
|
||||
});
|
||||
summary.failuresByCode.set(outcome.code, (summary.failuresByCode.get(outcome.code) ?? 0) + 1);
|
||||
}
|
||||
summary.failingByMethod.set(result.key, counted);
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
/** Refused statements the ratchet holds (dialect errors) and the ones it only reports. */
|
||||
export function splitRefusals(summary: Pick<ProbeSummary, 'failedStatements'>): {
|
||||
counted: FailedStatement[];
|
||||
reported: FailedStatement[];
|
||||
} {
|
||||
return {
|
||||
counted: summary.failedStatements.filter((failed) => failed.counted),
|
||||
reported: summary.failedStatements.filter((failed) => !failed.counted),
|
||||
};
|
||||
}
|
||||
|
||||
/** SQL on one line, cut to `max` characters, for a log or a table cell. */
|
||||
export function oneLine(sql: string, max = 160): string {
|
||||
const flat = sql.replace(/\s+/g, ' ').trim();
|
||||
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
|
||||
}
|
||||
|
||||
function cell(text: string): string {
|
||||
return text.replace(/\|/g, '\\|').replace(/`/g, "'");
|
||||
}
|
||||
|
||||
export interface ReportInput {
|
||||
summary: ProbeSummary;
|
||||
verdict: BaselineVerdict;
|
||||
helpers: readonly HelperResult[];
|
||||
schemaFailures: readonly { statement: string; message: string }[];
|
||||
results: readonly MethodResult[];
|
||||
}
|
||||
|
||||
export function helperFailures(helpers: readonly HelperResult[]): HelperResult[] {
|
||||
return helpers.filter((result) => result.failure !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the probe called no repository method at all. A broken plan (an
|
||||
* unreadable tsconfig, a moved repositories directory) would otherwise pass
|
||||
* with nothing failing, and its empty measurement could seed the baseline.
|
||||
*/
|
||||
export function probedNothing(summary: Pick<ProbeSummary, 'called'>): boolean {
|
||||
return summary.called === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the run passes: every helper case on both engines, at least one
|
||||
* repository method called, a measured baseline, and the ratchet held (no
|
||||
* method failing more statements than allowed, no new unmeasured method, no
|
||||
* entry left above what the run saw). An unmeasured baseline fails, so the
|
||||
* gate cannot merge before it holds anything.
|
||||
*/
|
||||
export function passed(input: Pick<ReportInput, 'verdict' | 'helpers' | 'summary'>): boolean {
|
||||
return (
|
||||
helperFailures(input.helpers).length === 0 &&
|
||||
!probedNothing(input.summary) &&
|
||||
!input.verdict.unseeded &&
|
||||
input.verdict.grown.length === 0 &&
|
||||
input.verdict.stale.length === 0 &&
|
||||
input.verdict.newlyUncovered.length === 0 &&
|
||||
input.verdict.nowCovered.length === 0
|
||||
);
|
||||
}
|
||||
|
||||
export function formatConsole(input: ReportInput): string {
|
||||
const { summary, verdict } = input;
|
||||
const lines: string[] = [];
|
||||
const failures = helperFailures(input.helpers);
|
||||
lines.push(
|
||||
`Dialect helpers: ${input.helpers.length - failures.length}/${input.helpers.length} cases pass on SQLite and Postgres.`,
|
||||
);
|
||||
for (const failure of failures) lines.push(` FAIL [${failure.engine}] ${failure.name}: ${failure.failure}`);
|
||||
if (input.schemaFailures.length > 0) {
|
||||
lines.push(
|
||||
`Schema: ${input.schemaFailures.length} DDL statement(s) Postgres refused (their tables are missing below):`,
|
||||
);
|
||||
for (const failure of input.schemaFailures)
|
||||
lines.push(` ${failure.message} <- ${oneLine(failure.statement, 120)}`);
|
||||
}
|
||||
lines.push(
|
||||
`Repositories: ${summary.methods} methods, ${summary.called} called, ${summary.unprobeable} unprobeable, ` +
|
||||
`${summary.withoutSql} sent no SQL, ${summary.timedOut} timed out.`,
|
||||
);
|
||||
const refusals = splitRefusals(summary);
|
||||
lines.push(
|
||||
`Statements: ${summary.statements} distinct, ${summary.failedStatements.length} refused by Postgres ` +
|
||||
`(${refusals.counted.length} as SQL, held to the baseline; ${refusals.reported.length} over a sample value or the empty tables, reported only).`,
|
||||
);
|
||||
for (const [code, count] of [...summary.failuresByCode.entries()].sort((a, b) => b[1] - a[1])) {
|
||||
lines.push(` ${code}: ${count}${countsTowardRatchet(code) ? '' : ' (not held)'}`);
|
||||
}
|
||||
for (const failed of summary.failedStatements) {
|
||||
lines.push(` ${failed.method} ${failed.code} ${failed.message}${failed.counted ? '' : ' (not held)'}`);
|
||||
lines.push(` ${oneLine(failed.sql)}`);
|
||||
}
|
||||
if (summary.uncovered.size > 0) {
|
||||
lines.push(`Unmeasured: ${summary.uncovered.size} method(s) whose SQL the probe did not see:`);
|
||||
for (const [method, why] of [...summary.uncovered.entries()].sort(([a], [b]) => a.localeCompare(b)))
|
||||
lines.push(` ${method}: ${why}`);
|
||||
}
|
||||
if (probedNothing(summary)) {
|
||||
lines.push(
|
||||
`FAIL No repository method was called (${summary.methods} planned); there is nothing to hold to the baseline.`,
|
||||
);
|
||||
}
|
||||
if (verdict.unseeded) {
|
||||
lines.push(
|
||||
'FAIL Baseline: not measured yet (failing is null). Commit the next baseline this run wrote ' +
|
||||
'(the pg-probe-baseline artifact in CI) as scripts/pg-probe-baseline.json.',
|
||||
);
|
||||
}
|
||||
for (const entry of verdict.grown) {
|
||||
lines.push(`FAIL ${entry.method} sends ${entry.now} statement(s) Postgres refuses, ${entry.allowed} allowed.`);
|
||||
}
|
||||
for (const entry of verdict.stale) {
|
||||
lines.push(
|
||||
`FAIL ${entry.method} is held at ${entry.allowed} failing statement(s) but fails ${entry.now} now; lower the baseline.`,
|
||||
);
|
||||
}
|
||||
for (const method of verdict.newlyUncovered) {
|
||||
lines.push(
|
||||
`FAIL ${method} ${summary.uncovered.get(method) ?? 'went unmeasured'}, and the baseline does not list it as uncovered. ` +
|
||||
'Give it arguments the probe can sample, or make it reach its SQL with them.',
|
||||
);
|
||||
}
|
||||
for (const method of verdict.nowCovered) {
|
||||
lines.push(`FAIL ${method} is listed as uncovered but is measured now (or gone); drop it from the baseline.`);
|
||||
}
|
||||
lines.push(passed(input) ? 'Postgres probe passed.' : 'Postgres probe failed.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export function formatMarkdown(input: ReportInput): string {
|
||||
const { summary, verdict } = input;
|
||||
const failures = helperFailures(input.helpers);
|
||||
const out: string[] = ['## Postgres probe', ''];
|
||||
out.push(passed(input) ? 'Result: **passed**' : 'Result: **failed**', '');
|
||||
out.push('| | |', '|---|---|');
|
||||
out.push(
|
||||
`| Dialect helper cases (SQLite and Postgres) | ${input.helpers.length - failures.length} of ${input.helpers.length} pass |`,
|
||||
);
|
||||
out.push(`| Schema statements refused | ${input.schemaFailures.length} |`);
|
||||
const refusals = splitRefusals(summary);
|
||||
out.push(
|
||||
`| Repository methods | ${summary.methods} (${summary.called} called, ${summary.unprobeable} unprobeable) |`,
|
||||
);
|
||||
out.push(`| Methods whose SQL the probe did not see | ${summary.uncovered.size} |`);
|
||||
out.push(`| Distinct statements | ${summary.statements} |`);
|
||||
out.push(`| Refused by Postgres as SQL (held) | ${refusals.counted.length} |`);
|
||||
out.push(`| Refused over a sample value or the empty tables (reported only) | ${refusals.reported.length} |`);
|
||||
out.push('');
|
||||
if (probedNothing(summary))
|
||||
out.push('No repository method was called, so there is nothing to hold to the baseline.', '');
|
||||
if (verdict.unseeded) {
|
||||
out.push(
|
||||
'The baseline has not been measured yet, which fails the run. Commit `pg-probe-baseline.json` from the `pg-probe-baseline` artifact as `server/scripts/pg-probe-baseline.json`.',
|
||||
'',
|
||||
);
|
||||
}
|
||||
if (verdict.grown.length > 0 || verdict.stale.length > 0) {
|
||||
out.push('### Ratchet', '', '| Method | Allowed | Now |', '|---|---|---|');
|
||||
for (const entry of [...verdict.grown, ...verdict.stale])
|
||||
out.push(`| ${cell(entry.method)} | ${entry.allowed} | ${entry.now} |`);
|
||||
out.push('');
|
||||
}
|
||||
if (verdict.newlyUncovered.length > 0 || verdict.nowCovered.length > 0) {
|
||||
out.push('### Coverage ratchet', '', '| Method | Baseline | Now |', '|---|---|---|');
|
||||
for (const method of verdict.newlyUncovered)
|
||||
out.push(`| ${cell(method)} | measured | ${cell(summary.uncovered.get(method) ?? 'unmeasured')} |`);
|
||||
for (const method of verdict.nowCovered) out.push(`| ${cell(method)} | uncovered | measured or gone |`);
|
||||
out.push('');
|
||||
}
|
||||
if (failures.length > 0) {
|
||||
out.push('### Helper cases that failed', '', '| Engine | Case | Why |', '|---|---|---|');
|
||||
for (const failure of failures)
|
||||
out.push(`| ${failure.engine} | ${cell(failure.name)} | ${cell(failure.failure ?? '')} |`);
|
||||
out.push('');
|
||||
}
|
||||
if (summary.failuresByCode.size > 0) {
|
||||
out.push('### Refused statements by SQLSTATE', '', '| SQLSTATE | Statements |', '|---|---|');
|
||||
for (const [code, count] of [...summary.failuresByCode.entries()].sort((a, b) => b[1] - a[1]))
|
||||
out.push(`| ${code} | ${count} |`);
|
||||
out.push('');
|
||||
out.push(
|
||||
'<details><summary>Every refused statement</summary>',
|
||||
'',
|
||||
'| Method | SQLSTATE | Held | Message |',
|
||||
'|---|---|---|---|',
|
||||
);
|
||||
for (const failed of summary.failedStatements) {
|
||||
out.push(
|
||||
`| ${cell(failed.method)} | ${failed.code} | ${failed.counted ? 'yes' : 'no'} | ${cell(failed.message)} |`,
|
||||
);
|
||||
}
|
||||
out.push('', '</details>', '');
|
||||
}
|
||||
if (summary.uncovered.size > 0) {
|
||||
out.push(
|
||||
'<details><summary>Methods whose SQL the probe did not see</summary>',
|
||||
'',
|
||||
'| Method | Why |',
|
||||
'|---|---|',
|
||||
);
|
||||
for (const [method, why] of [...summary.uncovered.entries()].sort(([a], [b]) => a.localeCompare(b)))
|
||||
out.push(`| ${cell(method)} | ${cell(why)} |`);
|
||||
out.push('', '</details>', '');
|
||||
}
|
||||
return `${out.join('\n')}\n`;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* The Postgres schema the probe runs against, derived from the entities.
|
||||
*
|
||||
* The entities are generated from the migrated SQLite schema and a parity
|
||||
* test pins them to it (`npm run check:entities`), so they are the one
|
||||
* description of the tables both engines can read. MikroORM's schema
|
||||
* generator turns them into Postgres DDL after three adjustments that keep
|
||||
* the probe about the SQL the repositories send, not about the storage
|
||||
* decisions a real Postgres port still has to make:
|
||||
*
|
||||
* - timestamps stay TEXT, the storage model the services and the dialect
|
||||
* helpers are written for (server/CLAUDE.md, "Storage model");
|
||||
* - a SQLite-only default (`datetime('now')`, `strftime('%s','now')`) gets
|
||||
* its Postgres equivalent, and a column declared `COLLATE NOCASE` uses
|
||||
* the `nocase` collation `collateNoCase()` names on Postgres;
|
||||
* - no foreign keys, so a statement is never refused only because the
|
||||
* sample row it writes points at nothing (every statement meets empty
|
||||
* tables).
|
||||
*
|
||||
* Unique and partial unique indexes stay, because `ON CONFLICT` needs them.
|
||||
*/
|
||||
import { pgTimestampText, PG_UTC_NOW } from '../../src/db/dialect/platform';
|
||||
|
||||
/** SQLite's timestamp text on Postgres, for a column default. */
|
||||
export const PG_NOW_TEXT_DEFAULT = pgTimestampText(PG_UTC_NOW);
|
||||
|
||||
/** The case-insensitive collation `collateNoCase()` names on Postgres. */
|
||||
export const NOCASE_COLLATION_SQL =
|
||||
"CREATE COLLATION IF NOT EXISTS nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false)";
|
||||
|
||||
/** The Postgres spelling of a column default the entities carry in SQLite's. */
|
||||
export function portableDefault(raw: string): string {
|
||||
const text = raw
|
||||
.trim()
|
||||
.replace(/^\((.*)\)$/s, '$1')
|
||||
.trim();
|
||||
if (/^current_timestamp$/i.test(text) || /^datetime\(\s*'now'\s*\)$/i.test(text)) return PG_NOW_TEXT_DEFAULT;
|
||||
if (/^strftime\(\s*'%s'\s*,\s*'now'\s*\)$/i.test(text))
|
||||
return 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)';
|
||||
return raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits generated DDL into single statements on `;` outside quotes, so one
|
||||
* statement Postgres refuses does not take the rest of the schema with it.
|
||||
*/
|
||||
export function splitStatements(sql: string): string[] {
|
||||
const statements: string[] = [];
|
||||
let current = '';
|
||||
let quote: '"' | "'" | null = null;
|
||||
for (const char of sql) {
|
||||
if (quote) {
|
||||
if (char === quote) quote = null;
|
||||
current += char;
|
||||
} else if (char === "'" || char === '"') {
|
||||
quote = char;
|
||||
current += char;
|
||||
} else if (char === ';') {
|
||||
if (current.trim()) statements.push(current.trim());
|
||||
current = '';
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
if (current.trim()) statements.push(current.trim());
|
||||
return statements.filter((statement) => !/^set\s/i.test(statement));
|
||||
}
|
||||
|
||||
/** The subset of MikroORM's property metadata the schema adjustments touch. */
|
||||
export interface ColumnMeta {
|
||||
name: string;
|
||||
defaultRaw?: string;
|
||||
collation?: string;
|
||||
columnTypes?: string[];
|
||||
customType?: { constructor: { name: string } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the adjustments above to one entity's properties in place:
|
||||
* timestamp columns become `text`, SQLite-only defaults and the NOCASE
|
||||
* collation their Postgres spelling. Returns the names of the properties
|
||||
* it changed, for the log.
|
||||
*/
|
||||
export function adjustColumns(properties: readonly ColumnMeta[]): string[] {
|
||||
const changed: string[] = [];
|
||||
for (const property of properties) {
|
||||
let touched = false;
|
||||
if (property.customType?.constructor.name === 'DbTimestampType' && property.columnTypes) {
|
||||
property.columnTypes = property.columnTypes.map(() => 'text');
|
||||
touched = true;
|
||||
}
|
||||
if (typeof property.defaultRaw === 'string') {
|
||||
const next = portableDefault(property.defaultRaw);
|
||||
if (next !== property.defaultRaw) {
|
||||
property.defaultRaw = next;
|
||||
touched = true;
|
||||
}
|
||||
}
|
||||
if (property.collation?.toUpperCase() === 'NOCASE') {
|
||||
property.collation = 'nocase';
|
||||
touched = true;
|
||||
}
|
||||
if (touched) changed.push(property.name);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"counts": {
|
||||
"src/db/repositories/_shared/packing-visibility.ts": 1,
|
||||
"src/db/repositories/_shared/reservation-travelers-owns.ts": 1,
|
||||
"src/db/repositories/AssignmentParticipants.repository.ts": 3,
|
||||
"src/db/repositories/BudgetItems.repository.ts": 1,
|
||||
"src/db/repositories/Categories.repository.ts": 1,
|
||||
"src/db/repositories/CollabMessageReactions.repository.ts": 2,
|
||||
"src/db/repositories/CollabPollVotes.repository.ts": 1,
|
||||
"src/db/repositories/DawarichConnections.repository.ts": 4,
|
||||
"src/db/repositories/DawarichVisitSuggestions.repository.ts": 4,
|
||||
"src/db/repositories/DayAccommodations.repository.ts": 12,
|
||||
"src/db/repositories/DayAssignments.repository.ts": 20,
|
||||
"src/db/repositories/DayNotes.repository.ts": 6,
|
||||
"src/db/repositories/Days.repository.ts": 7,
|
||||
"src/db/repositories/InviteTokens.repository.ts": 3,
|
||||
"src/db/repositories/JourneyBooks.repository.ts": 3,
|
||||
"src/db/repositories/JourneyEntries.repository.ts": 9,
|
||||
"src/db/repositories/JourneyPhotos.repository.ts": 6,
|
||||
"src/db/repositories/Journeys.repository.ts": 4,
|
||||
"src/db/repositories/JourneyShareTokens.repository.ts": 4,
|
||||
"src/db/repositories/JourneyTrips.repository.ts": 1,
|
||||
"src/db/repositories/McpTokens.repository.ts": 5,
|
||||
"src/db/repositories/OauthTokens.repository.ts": 3,
|
||||
"src/db/repositories/PlaceRatings.repository.ts": 1,
|
||||
"src/db/repositories/Places.repository.ts": 28,
|
||||
"src/db/repositories/PlaceShadowPicks.repository.ts": 3,
|
||||
"src/db/repositories/PushSubscriptions.repository.ts": 1,
|
||||
"src/db/repositories/ReservationDayPositions.repository.ts": 1,
|
||||
"src/db/repositories/ReservationEndpoints.repository.ts": 5,
|
||||
"src/db/repositories/Reservations.repository.ts": 14,
|
||||
"src/db/repositories/ReservationTravelers.repository.ts": 2,
|
||||
"src/db/repositories/RoadtripDayBoundaries.repository.ts": 3,
|
||||
"src/db/repositories/RoadtripDayTracks.repository.ts": 1,
|
||||
"src/db/repositories/RoadtripPreferences.repository.ts": 1,
|
||||
"src/db/repositories/RoadtripVias.repository.ts": 6,
|
||||
"src/db/repositories/Tags.repository.ts": 3,
|
||||
"src/db/repositories/TodoItems.repository.ts": 2,
|
||||
"src/db/repositories/TripDocumentLinks.repository.ts": 5,
|
||||
"src/db/repositories/TripInviteTokens.repository.ts": 4,
|
||||
"src/db/repositories/TripMembers.repository.ts": 8,
|
||||
"src/db/repositories/TripPhotos.repository.ts": 1,
|
||||
"src/db/repositories/Trips.repository.ts": 14,
|
||||
"src/db/repositories/Users.repository.ts": 1,
|
||||
"src/db/repositories/VacayPlanMembers.repository.ts": 3,
|
||||
"src/db/repositories/VacayShares.repository.ts": 2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:query-api: MikroORM QueryBuilder calls in the repositories may only shrink.
|
||||
*
|
||||
* A repository has three ways to build a statement: the entity methods
|
||||
* (findOne/find/insert/nativeUpdate/nativeDelete/upsert/count), Kysely on the
|
||||
* generated table types (`this.kysely<Pick<DB, ...>>()`), and MikroORM's
|
||||
* QueryBuilder (`this.qb(...)`, `createQueryBuilder(...)`). server/CLAUDE.md
|
||||
* ("Which query API") settles which one new code uses: Kysely for a read that
|
||||
* joins, aggregates or projects, the entity methods for single-table CRUD,
|
||||
* and no QueryBuilder. The ones already written stay until their method is
|
||||
* touched; this check makes sure they only recede.
|
||||
*
|
||||
* Every `.qb(` and `createQueryBuilder(` under src/db/repositories/ is
|
||||
* counted per file (the TrekRepository base that defines `qb` is left out).
|
||||
* A file may hold at most its entry in scripts/query-api-baseline.json, and a
|
||||
* file without an entry none. An entry above what its file holds now, or for
|
||||
* a file that is gone, fails too until --update lowers it.
|
||||
*
|
||||
* npm run lint:query-api check against the baseline (CI)
|
||||
* npm run lint:query-api -- --update lower the counts to what the files hold now;
|
||||
* it never raises an entry and never adds one
|
||||
*
|
||||
* --dir=<path> points the check at another server root (the unit tests use it).
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/** The tree the check walks, relative to the server root. */
|
||||
export const ROOT = 'src/db/repositories';
|
||||
|
||||
/** The baseline, relative to the server root. */
|
||||
export const BASELINE = 'scripts/query-api-baseline.json';
|
||||
|
||||
/** Files that define the QueryBuilder entry point rather than use it. */
|
||||
export const IGNORED = new Set(['src/db/repositories/_shared/trek-repository.ts']);
|
||||
|
||||
const SOURCE = /\.ts$/;
|
||||
const QB_CALL = /\.qb\(|\bcreateQueryBuilder\(/g;
|
||||
|
||||
/** The QueryBuilder calls in one file's text, comments included. */
|
||||
export function countQueryBuilderCalls(text) {
|
||||
return text.match(QB_CALL)?.length ?? 0;
|
||||
}
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path, files);
|
||||
else if (SOURCE.test(name)) files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** QueryBuilder counts keyed by the server-relative POSIX path, files without any left out. */
|
||||
export function scan(serverDir) {
|
||||
const dir = join(serverDir, ROOT);
|
||||
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
|
||||
throw new Error(`${ROOT}/ does not exist under ${serverDir}: the check would pass without looking at anything`);
|
||||
}
|
||||
const counts = {};
|
||||
for (const path of walk(dir)) {
|
||||
const file = relative(serverDir, path).split('\\').join('/');
|
||||
if (IGNORED.has(file)) continue;
|
||||
const n = countQueryBuilderCalls(readFileSync(path, 'utf8'));
|
||||
if (n > 0) counts[file] = n;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** The baseline as committed; missing or malformed stops the run instead of reading as empty. */
|
||||
export function readBaseline(path) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||||
} catch (err) {
|
||||
throw new Error(`${BASELINE} cannot be read: ${err.message}`);
|
||||
}
|
||||
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
||||
if (!isObject(parsed) || !isObject(parsed.counts)) {
|
||||
throw new Error(`${BASELINE} must be an object with a "counts" object`);
|
||||
}
|
||||
for (const [file, n] of Object.entries(parsed.counts)) {
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(`${BASELINE}: ${file} holds ${JSON.stringify(n)}, expected a whole number above 0`);
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** The counts lowered to what the files hold now. Never raises an entry, never adds one. */
|
||||
export function lowerCounts(baseline, counts) {
|
||||
const lowered = {};
|
||||
for (const [file, allowed] of Object.entries(baseline.counts)) {
|
||||
const now = counts[file] ?? 0;
|
||||
if (now > 0) lowered[file] = Math.min(allowed, now);
|
||||
}
|
||||
return Object.fromEntries(Object.entries(lowered).sort(([a], [b]) => a.localeCompare(b)));
|
||||
}
|
||||
|
||||
/** Files over their allowance, and entries above what their file holds now. */
|
||||
export function compare(baseline, counts) {
|
||||
const grown = Object.entries(counts).filter(([file, n]) => n > (baseline.counts[file] ?? 0));
|
||||
const lowered = lowerCounts(baseline, counts);
|
||||
const stale = Object.entries(baseline.counts).filter(([file, n]) => lowered[file] !== n);
|
||||
return { grown, stale };
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
const dirArg = argv.find((a) => a.startsWith('--dir='));
|
||||
const serverDir = dirArg ? resolve(dirArg.slice('--dir='.length)) : fileURLToPath(new URL('..', import.meta.url));
|
||||
const baselinePath = join(serverDir, BASELINE);
|
||||
|
||||
const counts = scan(serverDir);
|
||||
const baseline = readBaseline(baselinePath);
|
||||
if (argv.includes('--update')) {
|
||||
baseline.counts = lowerCounts(baseline, counts);
|
||||
writeFileSync(baselinePath, JSON.stringify(baseline, null, 2) + '\n');
|
||||
}
|
||||
|
||||
const { grown, stale } = compare(baseline, counts);
|
||||
for (const [file, n] of grown) {
|
||||
const entry = baseline.counts[file];
|
||||
console.error(
|
||||
`FAIL ${file}: ${n} QueryBuilder call(s), ` +
|
||||
(entry ? `its baseline is ${entry}. ` : 'a file without a baseline entry may hold none. ') +
|
||||
'Use Kysely for a join or aggregate read and the entity methods for single-table CRUD (server/CLAUDE.md).',
|
||||
);
|
||||
}
|
||||
for (const [file, entry] of stale) {
|
||||
console.error(
|
||||
`FAIL ${file} is held at ${entry} in ${BASELINE}, ` +
|
||||
(file in counts ? `but it has ${counts[file]} now.` : 'but it has none left (or the file is gone).'),
|
||||
);
|
||||
}
|
||||
if (stale.length) {
|
||||
console.error('Run npm run lint:query-api -- --update to lower the baseline with the change that made it smaller.');
|
||||
}
|
||||
const total = Object.values(counts).reduce((sum, n) => sum + n, 0);
|
||||
console.log(
|
||||
`query-api: ${total} QueryBuilder call(s) in ${Object.keys(counts).length} file(s) held at their baseline`,
|
||||
);
|
||||
return grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
|
||||
// Compared by real path, so the check still runs when the script is started through a symlink.
|
||||
const isCli =
|
||||
Boolean(process.argv[1]) &&
|
||||
existsSync(process.argv[1]) &&
|
||||
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
try {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
} catch (err) {
|
||||
console.error(`FAIL ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
{
|
||||
"Addons": "addons",
|
||||
"AiConnections": "ai-connections",
|
||||
"AppSettings": "settings",
|
||||
"AssignmentParticipants": "assignments",
|
||||
"AssistantAttachments": "assistant",
|
||||
"AssistantMessages": "assistant",
|
||||
"AssistantThreads": "assistant",
|
||||
"AssistantToolCalls": "assistant",
|
||||
"AssistantUsage": "ai-connections",
|
||||
"AuditLog": "audit",
|
||||
"BucketList": "atlas",
|
||||
"BudgetCategoryOrder": "budget",
|
||||
"BudgetItemMembers": "budget",
|
||||
"BudgetItemPayers": "budget",
|
||||
"BudgetItems": "budget",
|
||||
"BudgetSettlements": "budget",
|
||||
"Categories": "categories",
|
||||
"CollabLinks": "collab",
|
||||
"CollabMessageReactions": "collab",
|
||||
"CollabMessages": "collab",
|
||||
"CollabNotes": "collab",
|
||||
"CollabPollVotes": "collab",
|
||||
"CollabPolls": "collab",
|
||||
"CollectionLabels": "collections",
|
||||
"CollectionMembers": "collections",
|
||||
"CollectionPlaceRatings": "collections",
|
||||
"CollectionPlaces": "collections",
|
||||
"CollectionTours": "tours",
|
||||
"Collections": "collections",
|
||||
"DawarichConnections": "integrations",
|
||||
"DawarichVisitSuggestions": "integrations",
|
||||
"DayAccommodations": "accommodations",
|
||||
"DayAssignments": "assignments",
|
||||
"DayNotes": "day-notes",
|
||||
"Days": "days",
|
||||
"DocumentConnections": "doc-sync",
|
||||
"DocumentProviderFields": "doc-sync",
|
||||
"DocumentProviders": "doc-sync",
|
||||
"DocumentSyncItems": "doc-sync",
|
||||
"FerrataTiles": "ferratas",
|
||||
"FileLinks": "files",
|
||||
"GoogleApiUsage": "google-quota",
|
||||
"GooglePlacePhotoMeta": "place-photos",
|
||||
"HiddenCountries": "atlas",
|
||||
"HiddenRegions": "atlas",
|
||||
"IdempotencyKeys": "common",
|
||||
"InviteTokens": "auth",
|
||||
"JourneyBookRevisions": "journey",
|
||||
"JourneyBooks": "journey",
|
||||
"JourneyContributors": "journey",
|
||||
"JourneyEntries": "journey",
|
||||
"JourneyEntryPhotos": "journey",
|
||||
"JourneyEntryStays": "journey",
|
||||
"JourneyPhotos": "journey",
|
||||
"JourneyRecordedDays": "journey",
|
||||
"JourneyRecordingPrep": "journey",
|
||||
"JourneyShareTokens": "journey",
|
||||
"JourneyTrips": "journey",
|
||||
"Journeys": "journey",
|
||||
"McpTokens": "tokens",
|
||||
"NotificationChannelPreferences": "notifications",
|
||||
"Notifications": "notifications",
|
||||
"OauthClients": "oauth",
|
||||
"OauthConsents": "oauth",
|
||||
"OauthTokens": "oauth",
|
||||
"PackingBags": "packing",
|
||||
"PackingCategoryAssignees": "packing",
|
||||
"PackingItemContributors": "packing",
|
||||
"PackingItems": "packing",
|
||||
"PackingTemplateCategories": "packing",
|
||||
"PackingTemplateItems": "packing",
|
||||
"PackingTemplates": "packing",
|
||||
"PaddleFeatures": "paddle-obstacles",
|
||||
"PaddleRegionRequests": "paddle-obstacles",
|
||||
"PaddleRegions": "paddle-obstacles",
|
||||
"PaddleWaterGraphs": "paddle-routing",
|
||||
"PasswordResetTokens": "auth",
|
||||
"PhotoProviderFields": "addons",
|
||||
"PhotoProviders": "addons",
|
||||
"Photos": "photos",
|
||||
"PlaceDetailsCache": "maps",
|
||||
"PlaceRatings": "places",
|
||||
"PlaceRegions": "atlas",
|
||||
"PlaceShadowPicks": "place-shadow",
|
||||
"Places": "places",
|
||||
"PluginActions": "plugins",
|
||||
"PluginCapabilityAudit": "plugins",
|
||||
"PluginEgressHosts": "plugins",
|
||||
"PluginEntityMetadata": "plugins",
|
||||
"PluginErrorLog": "plugins",
|
||||
"PluginMetaMigrations": "plugins",
|
||||
"PluginOauthState": "plugins",
|
||||
"PluginOauthTokens": "plugins",
|
||||
"PluginScheduledTasks": "plugins",
|
||||
"PluginSettingsFields": "plugins",
|
||||
"PluginUserConfig": "plugins",
|
||||
"PluginUserErasureQueue": "plugins",
|
||||
"Plugins": "plugins",
|
||||
"PushSubscriptions": "notifications",
|
||||
"ReservationDayPositions": "reservations",
|
||||
"ReservationEndpoints": "reservations",
|
||||
"ReservationEndpointsEntity": "reservations",
|
||||
"ReservationTravelers": "reservations",
|
||||
"ReservationTravelersEntity": "reservations",
|
||||
"Reservations": "reservations",
|
||||
"RoadtripDayBoundaries": "roadtrip",
|
||||
"RoadtripDayTracks": "roadtrip",
|
||||
"RoadtripPreferences": "roadtrip",
|
||||
"RoadtripPreferencesEntity": "roadtrip",
|
||||
"RoadtripVias": "roadtrip",
|
||||
"RouteUsageDaily": "route-usage",
|
||||
"SchedulerLeases": "scheduling",
|
||||
"SchoolHolidayCountries": "school-holidays",
|
||||
"SchoolHolidayPeriods": "school-holidays",
|
||||
"SchoolHolidayRegions": "school-holidays",
|
||||
"Settings": "settings",
|
||||
"ShareTokens": "share",
|
||||
"Tags": "tags",
|
||||
"TodoCategoryAssignees": "todo",
|
||||
"TodoItems": "todo",
|
||||
"TourActivities": "tours",
|
||||
"TourActivityExclusions": "tours",
|
||||
"TourChangeSteps": "tours",
|
||||
"TourDrafts": "tours",
|
||||
"TourObstacleReviews": "tours",
|
||||
"TourStationVisits": "tours",
|
||||
"TourPackingLinks": "tours",
|
||||
"TourSourceHints": "tours",
|
||||
"TourSources": "tours",
|
||||
"TourTypes": "tours",
|
||||
"TourWaypoints": "tours",
|
||||
"Tours": "tours",
|
||||
"TrekPhotoCacheMeta": "memories",
|
||||
"TrekPhotoSignals": "photos",
|
||||
"TrekPhotos": "photos",
|
||||
"TripAlbumLinks": "memories",
|
||||
"TripDocumentLinks": "doc-sync",
|
||||
"TripFiles": "files",
|
||||
"TripInviteTokens": "trip-invite",
|
||||
"TripJournalLinkMembers": "journey",
|
||||
"TripJournalLinks": "journey",
|
||||
"TripMemberRemovals": "trip-membership",
|
||||
"TripMembers": "trip-membership",
|
||||
"TripPhotos": "photos",
|
||||
"Trips": "trips",
|
||||
"UserNoticeDismissals": "system-notices",
|
||||
"UserSessions": "sessions",
|
||||
"Users": "auth",
|
||||
"VacayCompanyHolidays": "vacay",
|
||||
"VacayEntries": "vacay",
|
||||
"VacayHolidayCalendars": "vacay",
|
||||
"VacayPlanMembers": "vacay",
|
||||
"VacayPlans": "vacay",
|
||||
"VacayShares": "vacay",
|
||||
"VacayUserColors": "vacay",
|
||||
"VacayUserSettingsEntity": "vacay",
|
||||
"VacayUserYears": "vacay",
|
||||
"VacayYears": "vacay",
|
||||
"VisitedCountries": "atlas",
|
||||
"VisitedRegions": "atlas",
|
||||
"WandererConnections": "wanderer",
|
||||
"WebauthnChallenges": "auth",
|
||||
"WebauthnCredentials": "auth"
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
{
|
||||
"counts": {
|
||||
"src/nest/accommodations/accommodations.controller.ts": 4,
|
||||
"src/nest/addons/addons.controller.ts": 1,
|
||||
"src/nest/admin/admin.controller.ts": 44,
|
||||
"src/nest/airports/airports.controller.ts": 2,
|
||||
"src/nest/assignments/assignments.controller.ts": 13,
|
||||
"src/nest/atlas/atlas.controller.ts": 14,
|
||||
"src/nest/atlas/public-stats.controller.ts": 1,
|
||||
"src/nest/atlas/travel-stats.controller.ts": 1,
|
||||
"src/nest/auth/auth-public.controller.ts": 9,
|
||||
"src/nest/auth/auth.controller.ts": 24,
|
||||
"src/nest/auth/passkey.controller.ts": 7,
|
||||
"src/nest/auth/sessions.controller.ts": 3,
|
||||
"src/nest/backup/backup.controller.ts": 8,
|
||||
"src/nest/budget/budget.controller.ts": 16,
|
||||
"src/nest/categories/categories.controller.ts": 4,
|
||||
"src/nest/collections/collections.controller.ts": 40,
|
||||
"src/nest/config/config.controller.ts": 1,
|
||||
"src/nest/day-notes/day-notes.controller.ts": 4,
|
||||
"src/nest/days/days.controller.ts": 6,
|
||||
"src/nest/doc-sync/doc-sync-webhook.controller.ts": 1,
|
||||
"src/nest/doc-sync/doc-sync.controller.ts": 15,
|
||||
"src/nest/feeds/feeds.controller.ts": 10,
|
||||
"src/nest/google-quota/google-quota.controller.ts": 2,
|
||||
"src/nest/health/features.controller.ts": 3,
|
||||
"src/nest/help/help.controller.ts": 4,
|
||||
"src/nest/integrations/airtrail.controller.ts": 6,
|
||||
"src/nest/integrations/dawarich.controller.ts": 15,
|
||||
"src/nest/journey/journey-public.controller.ts": 3,
|
||||
"src/nest/journey/journey.controller.ts": 20,
|
||||
"src/nest/llm-parse/llm-capabilities.controller.ts": 1,
|
||||
"src/nest/llm-parse/llm-local.controller.ts": 2,
|
||||
"src/nest/maps/maps.controller.ts": 11,
|
||||
"src/nest/mcp-transport/mcp-transport.controller.ts": 3,
|
||||
"src/nest/memories/immich.controller.ts": 12,
|
||||
"src/nest/memories/synology.controller.ts": 10,
|
||||
"src/nest/memories/unified.controller.ts": 7,
|
||||
"src/nest/notifications/notifications.controller.ts": 18,
|
||||
"src/nest/notifications/push/push.controller.ts": 3,
|
||||
"src/nest/oauth/oauth-api.controller.ts": 8,
|
||||
"src/nest/oauth/oauth-public.controller.ts": 3,
|
||||
"src/nest/oidc/oidc.controller.ts": 5,
|
||||
"src/nest/packing/admin-packing-templates.controller.ts": 11,
|
||||
"src/nest/packing/packing.controller.ts": 20,
|
||||
"src/nest/photos/photos.controller.ts": 3,
|
||||
"src/nest/place-enrichment/place-enrichment.controller.ts": 2,
|
||||
"src/nest/place-shadow/place-shadow.controller.ts": 4,
|
||||
"src/nest/places/places.controller.ts": 17,
|
||||
"src/nest/platform/discovery.controller.ts": 9,
|
||||
"src/nest/plugins/contributions/atlas-layers.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/day-schedule.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/day-tints.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/journal-entry-rows.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/map-layers.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/map-markers.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/pdf-sections.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/place-details.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/plugin-calendar.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/plugin-photos.controller.ts": 3,
|
||||
"src/nest/plugins/contributions/plugin-pois.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/plugin-routes.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/plugin-search.controller.ts": 2,
|
||||
"src/nest/plugins/contributions/trip-card-contributions.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/trip-warnings.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/view-contributions.controller.ts": 1,
|
||||
"src/nest/plugins/oauth/plugin-oauth.controller.ts": 4,
|
||||
"src/nest/plugins/plugin-activity.controller.ts": 1,
|
||||
"src/nest/plugins/plugin-frame.controller.ts": 1,
|
||||
"src/nest/plugins/plugin-user-settings.controller.ts": 3,
|
||||
"src/nest/plugins/plugins-feed.controller.ts": 1,
|
||||
"src/nest/plugins/plugins-proxy.controller.ts": 1,
|
||||
"src/nest/plugins/plugins.controller.ts": 24,
|
||||
"src/nest/public-api/public-api.controller.ts": 3,
|
||||
"src/nest/receipt-scan/receipt-scan.controller.ts": 1,
|
||||
"src/nest/reservation-import/reservation-import.controller.ts": 5,
|
||||
"src/nest/reservations/reservations.controller.ts": 6,
|
||||
"src/nest/reservations/upcoming-reservations.controller.ts": 1,
|
||||
"src/nest/roadtrip/charging-lookup.controller.ts": 1,
|
||||
"src/nest/roadtrip/charging.controller.ts": 1,
|
||||
"src/nest/roadtrip/day-boundaries.controller.ts": 3,
|
||||
"src/nest/roadtrip/google-route.controller.ts": 2,
|
||||
"src/nest/roadtrip/roadtrip-hazards.controller.ts": 1,
|
||||
"src/nest/roadtrip/roadtrip-preferences.controller.ts": 2,
|
||||
"src/nest/roadtrip/roadtrip-search.controller.ts": 1,
|
||||
"src/nest/roadtrip/roadtrip.controller.ts": 7,
|
||||
"src/nest/route-usage/route-usage.controller.ts": 3,
|
||||
"src/nest/school-holidays/school-holidays.controller.ts": 8,
|
||||
"src/nest/share/share.controller.ts": 5,
|
||||
"src/nest/storage/storage-admin.controller.ts": 8,
|
||||
"src/nest/system-notices/system-notices.controller.ts": 2,
|
||||
"src/nest/tags/tags.controller.ts": 4,
|
||||
"src/nest/tours/tours.controller.ts": 4,
|
||||
"src/nest/transit/transit.controller.ts": 2,
|
||||
"src/nest/trip-invite/trip-invite.controller.ts": 5,
|
||||
"src/nest/trip-members/trip-members.controller.ts": 7,
|
||||
"src/nest/trips/trips.controller.ts": 12,
|
||||
"src/nest/vacay/vacay.controller.ts": 5,
|
||||
"src/nest/weather/weather.controller.ts": 2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:response-contracts: route handlers without a @ResponseContract may only shrink.
|
||||
*
|
||||
* `@ResponseContract(schema)` (src/nest/common/response-contract.ts) names the
|
||||
* @trek/shared schema a handler answers with, and under NODE_ENV=test every
|
||||
* response is parsed against it, so the e2e suites catch a response that
|
||||
* drifted from its contract. This holds the handlers still without one to
|
||||
* what they are today.
|
||||
*
|
||||
* Every method under src/nest/ carrying a route decorator (@Get, @Post, @Put,
|
||||
* @Patch, @Delete, @All, @Head, @Options) counts as a handler. One counts as
|
||||
* covered when it also carries @ResponseContract(...), or when it writes
|
||||
* through @Res() (or hands off with @Next()) and a comment above it reads
|
||||
* `response-contract-exempt: <reason>`: a redirect or a stream has no return
|
||||
* value to check. The marker on a handler that returns its body excuses
|
||||
* nothing, so a comment cannot stand in for a schema. The
|
||||
* uncovered handlers are counted per file against
|
||||
* scripts/response-contract-baseline.json: a file may hold at most its entry,
|
||||
* a file without one none. An entry above what its file holds now, or for a
|
||||
* file that is gone, fails too until --update lowers it.
|
||||
*
|
||||
* npm run lint:response-contracts check against the baseline (CI)
|
||||
* npm run lint:response-contracts -- --update lower the counts to what the files hold now;
|
||||
* it never raises an entry and never adds one
|
||||
*
|
||||
* --dir=<path> points the check at another server root (the unit tests use it).
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const ts = require('typescript');
|
||||
|
||||
/** The tree the check walks, relative to the server root. */
|
||||
export const ROOT = 'src/nest';
|
||||
|
||||
/** The baseline, relative to the server root. */
|
||||
export const BASELINE = 'scripts/response-contract-baseline.json';
|
||||
|
||||
/** The decorators that make a method a route handler. */
|
||||
export const ROUTE_DECORATORS = new Set(['Get', 'Post', 'Put', 'Patch', 'Delete', 'All', 'Head', 'Options']);
|
||||
|
||||
/** The comment that excuses a handler with no return value to check. */
|
||||
export const EXEMPT_MARKER = 'response-contract-exempt:';
|
||||
|
||||
const SOURCE = /\.ts$/;
|
||||
|
||||
function decoratorName(decorator) {
|
||||
const expr = decorator.expression;
|
||||
const callee = ts.isCallExpression(expr) ? expr.expression : expr;
|
||||
if (ts.isIdentifier(callee)) return callee.text;
|
||||
if (ts.isPropertyAccessExpression(callee)) return callee.name.text;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether a comment directly above the method (between its decorators or before them) exempts it. */
|
||||
function isExempt(text, method) {
|
||||
const head = text.slice(method.getFullStart(), method.name.getStart());
|
||||
return head.split('\n').some((line) => /^\s*(\/\/|\/?\*)/.test(line) && line.includes(EXEMPT_MARKER));
|
||||
}
|
||||
|
||||
/** Whether the handler takes the response (or next) object, so it answers through it rather than by returning. */
|
||||
function writesThroughResponse(method) {
|
||||
return method.parameters.some((param) =>
|
||||
(ts.getDecorators(param) ?? []).some((d) => {
|
||||
const name = decoratorName(d);
|
||||
return name === 'Res' || name === 'Next' || name === 'Response';
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The route handlers of one file's text: `{ name, covered }` in source order. */
|
||||
export function handlersOf(text, fileName = 'file.ts') {
|
||||
const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
||||
const handlers = [];
|
||||
const visit = (node) => {
|
||||
if (ts.isMethodDeclaration(node)) {
|
||||
const names = (ts.getDecorators(node) ?? []).map(decoratorName);
|
||||
if (names.some((n) => n && ROUTE_DECORATORS.has(n))) {
|
||||
const name = node.name && ts.isIdentifier(node.name) ? node.name.text : (node.name?.getText(source) ?? '?');
|
||||
const exempt = isExempt(text, node) && writesThroughResponse(node);
|
||||
handlers.push({ name, covered: names.includes('ResponseContract') || exempt });
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(source);
|
||||
return handlers;
|
||||
}
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path, files);
|
||||
else if (SOURCE.test(name)) files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handler totals and the uncovered counts keyed by the server-relative POSIX path
|
||||
* (files with none left out of `uncovered`).
|
||||
*/
|
||||
export function scan(serverDir) {
|
||||
const dir = join(serverDir, ROOT);
|
||||
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
|
||||
throw new Error(`${ROOT}/ does not exist under ${serverDir}: the check would pass without looking at anything`);
|
||||
}
|
||||
const uncovered = {};
|
||||
let total = 0;
|
||||
for (const path of walk(dir)) {
|
||||
const file = relative(serverDir, path).split('\\').join('/');
|
||||
const handlers = handlersOf(readFileSync(path, 'utf8'), file);
|
||||
total += handlers.length;
|
||||
const n = handlers.filter((h) => !h.covered).length;
|
||||
if (n > 0) uncovered[file] = n;
|
||||
}
|
||||
if (total === 0)
|
||||
throw new Error(`no route handler found under ${ROOT}/: the check would pass without looking at anything`);
|
||||
return { total, uncovered };
|
||||
}
|
||||
|
||||
/** The baseline as committed; missing or malformed stops the run instead of reading as empty. */
|
||||
export function readBaseline(path) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||||
} catch (err) {
|
||||
throw new Error(`${BASELINE} cannot be read: ${err.message}`);
|
||||
}
|
||||
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
||||
if (!isObject(parsed) || !isObject(parsed.counts)) {
|
||||
throw new Error(`${BASELINE} must be an object with a "counts" object`);
|
||||
}
|
||||
for (const [file, n] of Object.entries(parsed.counts)) {
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(`${BASELINE}: ${file} holds ${JSON.stringify(n)}, expected a whole number above 0`);
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** The counts lowered to what the files hold now. Never raises an entry, never adds one. */
|
||||
export function lowerCounts(baseline, counts) {
|
||||
const lowered = {};
|
||||
for (const [file, allowed] of Object.entries(baseline.counts)) {
|
||||
const now = counts[file] ?? 0;
|
||||
if (now > 0) lowered[file] = Math.min(allowed, now);
|
||||
}
|
||||
return Object.fromEntries(Object.entries(lowered).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
||||
}
|
||||
|
||||
/** Files over their allowance, and entries above what their file holds now. */
|
||||
export function compare(baseline, counts) {
|
||||
const grown = Object.entries(counts).filter(([file, n]) => n > (baseline.counts[file] ?? 0));
|
||||
const lowered = lowerCounts(baseline, counts);
|
||||
const stale = Object.entries(baseline.counts).filter(([file, n]) => lowered[file] !== n);
|
||||
return { grown, stale };
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
const dirArg = argv.find((a) => a.startsWith('--dir='));
|
||||
const serverDir = dirArg ? resolve(dirArg.slice('--dir='.length)) : fileURLToPath(new URL('..', import.meta.url));
|
||||
const baselinePath = join(serverDir, BASELINE);
|
||||
|
||||
const { total, uncovered } = scan(serverDir);
|
||||
const baseline = readBaseline(baselinePath);
|
||||
if (argv.includes('--update')) {
|
||||
baseline.counts = lowerCounts(baseline, uncovered);
|
||||
writeFileSync(baselinePath, JSON.stringify(baseline, null, 2) + '\n');
|
||||
}
|
||||
|
||||
const { grown, stale } = compare(baseline, uncovered);
|
||||
for (const [file, n] of grown) {
|
||||
const entry = baseline.counts[file];
|
||||
console.error(
|
||||
`FAIL ${file}: ${n} route handler(s) without @ResponseContract, ` +
|
||||
(entry ? `its baseline is ${entry}. ` : 'a file without a baseline entry may hold none. ') +
|
||||
'Declare the @trek/shared response schema the handler answers with (src/nest/common/response-contract.ts), ' +
|
||||
`or mark a handler that writes through @Res() with a "${EXEMPT_MARKER} <reason>" comment.`,
|
||||
);
|
||||
}
|
||||
for (const [file, entry] of stale) {
|
||||
console.error(
|
||||
`FAIL ${file} is held at ${entry} in ${BASELINE}, ` +
|
||||
(file in uncovered ? `but it has ${uncovered[file]} now.` : 'but it has none left (or the file is gone).'),
|
||||
);
|
||||
}
|
||||
if (stale.length) {
|
||||
console.error(
|
||||
'Run npm run lint:response-contracts -- --update to lower the baseline with the change that made it smaller.',
|
||||
);
|
||||
}
|
||||
const open = Object.values(uncovered).reduce((sum, n) => sum + n, 0);
|
||||
const share = ((100 * (total - open)) / total).toFixed(1);
|
||||
console.log(
|
||||
`response-contracts: ${total - open} of ${total} route handler(s) covered (${share} %), the rest held at their baseline`,
|
||||
);
|
||||
return grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
|
||||
// Compared by real path, so the check still runs when the script is started through a symlink.
|
||||
const isCli =
|
||||
Boolean(process.argv[1]) &&
|
||||
existsSync(process.argv[1]) &&
|
||||
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
try {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
} catch (err) {
|
||||
console.error(`FAIL ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"counts": {
|
||||
"src/nest/auth/auth-public.controller.ts": 1,
|
||||
"src/nest/auth/auth.service.ts": 5,
|
||||
"src/nest/auth/passkey.controller.ts": 1,
|
||||
"src/nest/auth/passkey.service.ts": 2,
|
||||
"src/nest/backup/backup-archive.ts": 8,
|
||||
"src/nest/backup/backup.impl.ts": 1,
|
||||
"src/nest/collab/collab.controller.ts": 7,
|
||||
"src/nest/collab/collab.mcp.ts": 3,
|
||||
"src/nest/collab/collab.rpc.ts": 2,
|
||||
"src/nest/doc-sync/doc-sync-config.service.ts": 2,
|
||||
"src/nest/llm-parse/llm-local.service.ts": 3,
|
||||
"src/nest/maps/maps-url.resolver.ts": 2,
|
||||
"src/nest/maps/providers/osm.client.ts": 4,
|
||||
"src/nest/memories/immich.controller.ts": 6,
|
||||
"src/nest/memories/immich.service.ts": 15,
|
||||
"src/nest/memories/memories.mcp.ts": 6,
|
||||
"src/nest/memories/synology.controller.ts": 1,
|
||||
"src/nest/memories/synology.service.ts": 5,
|
||||
"src/nest/memories/unified.controller.ts": 7,
|
||||
"src/nest/notifications/push/push.controller.ts": 1,
|
||||
"src/nest/oauth/oauth-api.controller.ts": 4,
|
||||
"src/nest/oauth/oauth-public.controller.ts": 3,
|
||||
"src/nest/oauth/oauth.service.ts": 22,
|
||||
"src/nest/oidc/oidc.controller.ts": 4,
|
||||
"src/nest/oidc/oidc.service.ts": 1,
|
||||
"src/nest/photos/photos.controller.ts": 1,
|
||||
"src/nest/place-import/place-import.service.ts": 1,
|
||||
"src/nest/place-import/providers/google-directions.provider.ts": 5,
|
||||
"src/nest/place-import/providers/google-list.provider.ts": 12,
|
||||
"src/nest/place-import/providers/naver-list.provider.ts": 10,
|
||||
"src/nest/plugins/contributions/plugin-pois.controller.ts": 1,
|
||||
"src/nest/plugins/contributions/plugin-pois.mcp.ts": 1,
|
||||
"src/nest/plugins/contributions/plugin-pois.service.ts": 4,
|
||||
"src/nest/public-api/public-api-request.ts": 3,
|
||||
"src/nest/reservations/reservations.mcp.ts": 4,
|
||||
"src/nest/tokens/token.service.ts": 2,
|
||||
"src/nest/vacay/vacay.controller.ts": 1,
|
||||
"src/nest/vacay/vacay.mcp.ts": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:service-http: the result-envelope idioms may only shrink.
|
||||
*
|
||||
* A service refuses by throwing a DomainError (src/nest/common/domain-error.ts)
|
||||
* with the status and the exact text the client sees. The global filter turns it
|
||||
* into REST's `{ error }` and the MCP registry into the tool's errorResult, so no
|
||||
* caller translates it. What this counts is the older way, where every caller did:
|
||||
*
|
||||
* - in any file under src/nest outside the HTTP and adapter layers (services,
|
||||
* helpers, impl files, providers): a `status: 4xx` or `status: 5xx` literal
|
||||
* (the `return { error, status }` result) and `new HttpException(` (HTTP in
|
||||
* the domain layer). Controllers, guards, pipes, filters, interceptors and
|
||||
* DTOs speak HTTP by design, and src/nest/common/domain-error.ts defines the
|
||||
* status a refusal carries, so those are left out by name;
|
||||
* - in a *.controller.ts, *.mcp.ts or *.rpc.ts: a branch on a returned error,
|
||||
* `if (result.error)`, `if (!r.error)`, `'error' in result`,
|
||||
* `result.error === 'not_found'`, `r?.error && ...`, `x.error ? a : b`.
|
||||
*
|
||||
* Each file is held to its entry in scripts/service-http-baseline.json, and a
|
||||
* file without an entry holds none (scripts/lib/count-ratchet.mjs has the rules).
|
||||
*
|
||||
* npm run lint:service-http check against the baseline (CI)
|
||||
* npm run lint:service-http -- --update lower the counts; never raises or adds an entry
|
||||
*/
|
||||
import { cliMain } from './lib/count-ratchet.mjs';
|
||||
|
||||
const STATUS_LITERAL = /\bstatus:\s*[45]\d\d\b/g;
|
||||
const HTTP_EXCEPTION = /\bnew HttpException\(/g;
|
||||
// A property path such as result, res.body or this.state?.last.
|
||||
const PATH = String.raw`[\w$]+(?:\??\.[\w$]+)*`;
|
||||
const RESULT_ERROR_BRANCH = new RegExp(
|
||||
[
|
||||
String.raw`['"]error['"]\s+in\s+[\w$.]+`,
|
||||
String.raw`\bif\s*\(\s*!?\s*${PATH}\??\.error\s*\)`,
|
||||
String.raw`${PATH}\??\.error\b\s*(?:===|!==|==|!=|&&|\|\||\?(?![.?]))`,
|
||||
].join('|'),
|
||||
'g',
|
||||
);
|
||||
|
||||
/** Files that speak HTTP by design: the status literals in them are not an envelope. */
|
||||
const HTTP_LAYER = /\.(?:controller|guard|pipe|filter|interceptor|dto)\.ts$/;
|
||||
const DEFINES_THE_STATUS = new Set(['src/nest/common/domain-error.ts']);
|
||||
/** The adapters over a service, where a branch on its returned error is the caller translating it. */
|
||||
const ADAPTER = /\.(?:controller|mcp|rpc)\.ts$/;
|
||||
|
||||
const hits = (text, pattern) => text.match(pattern)?.length ?? 0;
|
||||
|
||||
/** The envelope idioms in one domain-layer file. */
|
||||
export function countServiceIdioms(text) {
|
||||
return hits(text, STATUS_LITERAL) + hits(text, HTTP_EXCEPTION);
|
||||
}
|
||||
|
||||
/** The branches on a returned error in one controller, MCP or RPC file. */
|
||||
export function countResultBranches(text) {
|
||||
return hits(text, RESULT_ERROR_BRANCH);
|
||||
}
|
||||
|
||||
/** What one file under src/nest holds, by the layer its name puts it in. */
|
||||
export function countFile(text, file) {
|
||||
let n = ADAPTER.test(file) ? countResultBranches(text) : 0;
|
||||
if (!HTTP_LAYER.test(file) && !DEFINES_THE_STATUS.has(file)) n += countServiceIdioms(text);
|
||||
return n;
|
||||
}
|
||||
|
||||
export const check = {
|
||||
name: 'service-http',
|
||||
script: 'lint:service-http',
|
||||
root: 'src/nest',
|
||||
baseline: 'scripts/service-http-baseline.json',
|
||||
unit: 'error-envelope idiom(s)',
|
||||
advice: 'Throw a DomainError from the service (src/nest/common/domain-error.ts) and let REST and MCP answer it.',
|
||||
include: (file) => file.endsWith('.ts') && !file.endsWith('.d.ts'),
|
||||
count: countFile,
|
||||
};
|
||||
|
||||
cliMain(check, import.meta.url);
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"scripts/db-call-graph.mjs": 1036,
|
||||
"scripts/generate-entities.ts": 2259,
|
||||
"src/db/repositories/Places.repository.ts": 1439,
|
||||
"src/db/repositories/Reservations.repository.ts": 1604,
|
||||
"src/db/repositories/Trips.repository.ts": 1121,
|
||||
"src/db/repositories/Users.repository.ts": 1445,
|
||||
"src/nest/atlas/atlas.service.ts": 1182,
|
||||
"src/nest/auth/auth.service.ts": 1143,
|
||||
"src/nest/budget/budget.service.ts": 1617,
|
||||
"src/nest/collections/collections.service.ts": 1478,
|
||||
"src/nest/doc-sync/doc-sync.service.ts": 1060,
|
||||
"src/nest/doc-sync/providers/synology-drive.client.ts": 1160,
|
||||
"src/nest/journey/journey-domain.service.ts": 1659,
|
||||
"src/nest/places/places.service.ts": 1592,
|
||||
"src/nest/plugins/plugin-runtime.service.ts": 1463,
|
||||
"src/nest/plugins/runtime/plugin-sdk.ts": 1093,
|
||||
"src/nest/reservations/reservations.service.ts": 1237,
|
||||
"src/nest/trips/trips.service.ts": 1006,
|
||||
"src/nest/vacay/vacay.service.ts": 1409
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:size: keeps server source files from growing into the next god service.
|
||||
*
|
||||
* The same ratchet as client/scripts/size-lint.mjs. A file past a thousand
|
||||
* lines holds several concerns that no longer fit in one reading (maps,
|
||||
* places and journey are the cautionary tales), and every change to one of
|
||||
* them risks the others. Each source file under src/ and scripts/ may hold
|
||||
* LIMIT lines; the files that were already longer are listed in
|
||||
* scripts/size-baseline.json with the length they had, and the check fails
|
||||
* when one of them grows past its entry. A file that needs to grow is split
|
||||
* by concern instead (trips into trips/trip-members/trip-membership/
|
||||
* trip-invite/trip-read-model/calendar is the precedent). An entry above what
|
||||
* its file holds now, or for a file that is gone, fails as well until
|
||||
* --update lowers it: otherwise the file could grow back unseen, and a new
|
||||
* file at a deleted path would inherit its allowance.
|
||||
*
|
||||
* Tests are held the same way under their own, wider limit: a file under
|
||||
* tests/ (helpers and fixtures included) may hold TEST_LIMIT lines, the longer
|
||||
* ones are listed in scripts/test-size-baseline.json, and a suite that needs
|
||||
* to grow is split by the behaviour it covers.
|
||||
*
|
||||
* Lines are counted the way they read, not the way they are stored: a line
|
||||
* longer than LINE_WIDTH (prettier's printWidth) counts once per LINE_WIDTH
|
||||
* columns it spans, so joining lines does not buy room under the limit.
|
||||
*
|
||||
* npm run lint:size check against the baseline (CI)
|
||||
* npm run lint:size -- --update lower the baseline to what the files hold now;
|
||||
* it never raises an entry, and drops a file
|
||||
* that is back under the limit
|
||||
*
|
||||
* --dir=<path> points the check at another server root (the unit tests use it).
|
||||
* Walking the tree and handling the baseline live in scripts/lib/ratchet.mjs
|
||||
* at the repository root.
|
||||
*/
|
||||
import {
|
||||
listFiles,
|
||||
lowerCounts,
|
||||
RatchetError,
|
||||
readBaseline,
|
||||
readText,
|
||||
runCli,
|
||||
staleCounts,
|
||||
toKey,
|
||||
writeBaseline,
|
||||
} from '../../scripts/lib/ratchet.mjs';
|
||||
|
||||
import { join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/** The most lines a source file without a baseline entry may hold. */
|
||||
const LIMIT = 1000;
|
||||
|
||||
/** The most lines a test file without a baseline entry may hold. */
|
||||
const TEST_LIMIT = 2000;
|
||||
|
||||
/** prettier's printWidth for the server: a line past it counts once per width it spans. */
|
||||
const LINE_WIDTH = 120;
|
||||
|
||||
const SOURCE = /\.(?:[cm]?[jt]s)$/;
|
||||
const TEST = /\.(?:test|spec)\./;
|
||||
|
||||
const nameOf = (key) => key.slice(key.lastIndexOf('/') + 1);
|
||||
|
||||
/**
|
||||
* What the check holds. Each scope walks its trees (relative to the server
|
||||
* root; each one must exist) against its own limit and baseline file.
|
||||
*/
|
||||
const SCOPES = [
|
||||
{
|
||||
label: 'size',
|
||||
roots: ['src', 'scripts'],
|
||||
limit: LIMIT,
|
||||
baseline: 'size-baseline.json',
|
||||
accepts: (key) => SOURCE.test(nameOf(key)) && !TEST.test(nameOf(key)),
|
||||
advice: 'Split a concern into a service, helper or module of its own instead of growing the file.',
|
||||
},
|
||||
{
|
||||
label: 'size (tests)',
|
||||
roots: ['tests'],
|
||||
limit: TEST_LIMIT,
|
||||
baseline: 'test-size-baseline.json',
|
||||
accepts: (key) => SOURCE.test(nameOf(key)),
|
||||
advice: 'Split the suite by the behaviour it covers instead of growing the file.',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Lines as an editor numbers them (a final newline does not start another),
|
||||
* with every line longer than LINE_WIDTH weighted by the widths it spans.
|
||||
*/
|
||||
function lineCount(text) {
|
||||
if (text === '') return 0;
|
||||
const lines = text.split('\n');
|
||||
if (lines[lines.length - 1] === '') lines.pop();
|
||||
let total = 0;
|
||||
for (const line of lines) total += Math.max(1, Math.ceil(line.length / LINE_WIDTH));
|
||||
return total;
|
||||
}
|
||||
|
||||
/** Weighted line counts keyed by the server-relative POSIX path. A missing root is an error. */
|
||||
function scan(serverDir, scope) {
|
||||
const counts = {};
|
||||
for (const path of listFiles(serverDir, scope.roots, scope.accepts)) {
|
||||
counts[toKey(serverDir, path)] = lineCount(readText(path));
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** Every entry must be a whole number above the limit: anything else is a hand edit gone wrong. */
|
||||
const sizeEntries = (limit) => (value) => {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return 'it must be an object of file paths to line counts';
|
||||
}
|
||||
for (const [file, n] of Object.entries(value)) {
|
||||
if (!Number.isInteger(n) || n <= limit)
|
||||
return `${file} holds ${JSON.stringify(n)}, expected an integer above ${limit}`;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/** One scope against its baseline; answers whether it failed. */
|
||||
function checkScope(serverDir, scope, update) {
|
||||
const { limit } = scope;
|
||||
const baselinePath = join(serverDir, 'scripts', scope.baseline);
|
||||
|
||||
const counts = scan(serverDir, scope);
|
||||
let baseline = readBaseline(baselinePath, sizeEntries(limit));
|
||||
if (update) {
|
||||
baseline = lowerCounts(baseline, counts, limit);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
const grown = Object.entries(counts).filter(([file, n]) => n > Math.max(baseline[file] ?? 0, limit));
|
||||
const stale = staleCounts(baseline, counts, limit);
|
||||
for (const [file, n] of grown) {
|
||||
const entry = baseline[file];
|
||||
console.error(
|
||||
`FAIL ${file}: ${n} lines, ` + (entry ? `its baseline is ${entry}. ` : `the limit is ${limit}. `) + scope.advice,
|
||||
);
|
||||
}
|
||||
for (const { key, entry } of stale) {
|
||||
console.error(
|
||||
`FAIL ${key} is held at ${entry} in scripts/${scope.baseline}, ` +
|
||||
(key in counts ? `but it has ${counts[key]} lines now.` : 'but the file is gone.'),
|
||||
);
|
||||
}
|
||||
if (stale.length) {
|
||||
console.error(
|
||||
'Run npm run lint:size -- --update to lower the baseline with the change that made it smaller: ' +
|
||||
'an entry above the file lets it grow back unseen.',
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`${scope.label}: ${Object.keys(counts).length} file(s), ` +
|
||||
`${Object.keys(baseline).length} over ${limit} lines held at their baseline`,
|
||||
);
|
||||
return grown.length > 0 || stale.length > 0;
|
||||
}
|
||||
|
||||
function check(argv) {
|
||||
const dirArg = argv.find((a) => a.startsWith('--dir='));
|
||||
const serverDir = dirArg ? resolve(dirArg.slice('--dir='.length)) : fileURLToPath(new URL('..', import.meta.url));
|
||||
const update = argv.includes('--update');
|
||||
let failed = false;
|
||||
for (const scope of SCOPES) failed = checkScope(serverDir, scope, update) || failed;
|
||||
return failed ? 1 : 0;
|
||||
}
|
||||
|
||||
await runCli('lint:size', (argv) => {
|
||||
try {
|
||||
return check(argv);
|
||||
} catch (err) {
|
||||
// A scan or baseline problem the lib reports as a plain Error is still a failure of the check itself.
|
||||
if (err instanceof RatchetError) throw err;
|
||||
throw new RatchetError(err.message);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"src/db/repositories/BudgetItems.repository.ts": 1,
|
||||
"src/db/repositories/CollabLinks.repository.ts": 1,
|
||||
"src/db/repositories/CollabMessageReactions.repository.ts": 1,
|
||||
"src/db/repositories/CollabMessages.repository.ts": 1,
|
||||
"src/db/repositories/CollabNotes.repository.ts": 1,
|
||||
"src/db/repositories/CollabPollVotes.repository.ts": 1,
|
||||
"src/db/repositories/CollabPolls.repository.ts": 1,
|
||||
"src/db/repositories/CollectionMembers.repository.ts": 1,
|
||||
"src/db/repositories/CollectionPlaces.repository.ts": 1,
|
||||
"src/db/repositories/Collections.repository.ts": 1,
|
||||
"src/db/repositories/DawarichVisitSuggestions.repository.ts": 1,
|
||||
"src/db/repositories/DayAccommodations.repository.ts": 2,
|
||||
"src/db/repositories/DayAssignments.repository.ts": 2,
|
||||
"src/db/repositories/DayNotes.repository.ts": 2,
|
||||
"src/db/repositories/Days.repository.ts": 3,
|
||||
"src/db/repositories/DocumentConnections.repository.ts": 1,
|
||||
"src/db/repositories/InviteTokens.repository.ts": 1,
|
||||
"src/db/repositories/JourneyBooks.repository.ts": 1,
|
||||
"src/db/repositories/JourneyContributors.repository.ts": 1,
|
||||
"src/db/repositories/JourneyEntries.repository.ts": 2,
|
||||
"src/db/repositories/JourneyShareTokens.repository.ts": 1,
|
||||
"src/db/repositories/Journeys.repository.ts": 1,
|
||||
"src/db/repositories/McpTokens.repository.ts": 1,
|
||||
"src/db/repositories/Notifications.repository.ts": 1,
|
||||
"src/db/repositories/OauthTokens.repository.ts": 4,
|
||||
"src/db/repositories/PackingBags.repository.ts": 1,
|
||||
"src/db/repositories/PackingItems.repository.ts": 3,
|
||||
"src/db/repositories/PackingTemplates.repository.ts": 2,
|
||||
"src/db/repositories/PasswordResetTokens.repository.ts": 1,
|
||||
"src/db/repositories/PhotoProviderFields.repository.ts": 1,
|
||||
"src/db/repositories/Places.repository.ts": 3,
|
||||
"src/db/repositories/ReservationEndpoints.repository.ts": 1,
|
||||
"src/db/repositories/Reservations.repository.ts": 3,
|
||||
"src/db/repositories/RoadtripVias.repository.ts": 1,
|
||||
"src/db/repositories/SchoolHolidayPeriods.repository.ts": 1,
|
||||
"src/db/repositories/SchoolHolidayRegions.repository.ts": 1,
|
||||
"src/db/repositories/ShareTokens.repository.ts": 1,
|
||||
"src/db/repositories/Tags.repository.ts": 1,
|
||||
"src/db/repositories/TourWaypoints.repository.ts": 1,
|
||||
"src/db/repositories/Tours.repository.ts": 1,
|
||||
"src/db/repositories/TripDocumentLinks.repository.ts": 1,
|
||||
"src/db/repositories/TripFiles.repository.ts": 1,
|
||||
"src/db/repositories/TripInviteTokens.repository.ts": 1,
|
||||
"src/db/repositories/TripMembers.repository.ts": 1,
|
||||
"src/db/repositories/Trips.repository.ts": 2,
|
||||
"src/db/repositories/UserSessions.repository.ts": 1,
|
||||
"src/db/repositories/VacayCompanyHolidays.repository.ts": 1,
|
||||
"src/db/repositories/VacayEntries.repository.ts": 1,
|
||||
"src/db/repositories/VacayHolidayCalendars.repository.ts": 1,
|
||||
"src/db/repositories/VacayPlanMembers.repository.ts": 1,
|
||||
"src/db/repositories/VacayPlans.repository.ts": 1,
|
||||
"src/db/repositories/VacayShares.repository.ts": 1,
|
||||
"src/db/repositories/VacayYears.repository.ts": 1,
|
||||
"src/db/repositories/WebauthnCredentials.repository.ts": 1,
|
||||
"src/db/repositories/_shared/trek-repository.ts": 8,
|
||||
"src/mcp/sessionManager.ts": 2,
|
||||
"src/mcp/tools.ts": 1,
|
||||
"src/nest-mcp/registry.ts": 2,
|
||||
"src/nest/accommodations/accommodations.service.ts": 2,
|
||||
"src/nest/atlas/atlas-geo.ts": 2,
|
||||
"src/nest/auth/auth.service.ts": 1,
|
||||
"src/nest/budget/budget.service.ts": 2,
|
||||
"src/nest/calendar/calendar.service.ts": 5,
|
||||
"src/nest/collections/collections.service.ts": 1,
|
||||
"src/nest/day-notes/day-notes.mcp.ts": 1,
|
||||
"src/nest/day-notes/day-notes.service.ts": 1,
|
||||
"src/nest/doc-sync/doc-sync.helpers.ts": 6,
|
||||
"src/nest/files/files.controller.ts": 1,
|
||||
"src/nest/integrations/airtrail.mapper.ts": 4,
|
||||
"src/nest/integrations/airtrail.service.ts": 1,
|
||||
"src/nest/integrations/dawarich-suggestions.service.ts": 1,
|
||||
"src/nest/journey/journey-domain.service.ts": 1,
|
||||
"src/nest/journey/journey.controller.ts": 5,
|
||||
"src/nest/journey/journey.dto.ts": 2,
|
||||
"src/nest/journey/journey.mcp.ts": 1,
|
||||
"src/nest/llm-parse/mime-email.ts": 1,
|
||||
"src/nest/maps/providers/amap.provider.ts": 1,
|
||||
"src/nest/mcp-transport/mcp-transport.service.ts": 4,
|
||||
"src/nest/memories/immich.controller.ts": 1,
|
||||
"src/nest/memories/immich.service.ts": 1,
|
||||
"src/nest/memories/synology.service.ts": 5,
|
||||
"src/nest/notifications/notification-preferences.service.ts": 1,
|
||||
"src/nest/oauth/oauth-api.controller.ts": 1,
|
||||
"src/nest/oauth/oauth-sdk.provider.ts": 6,
|
||||
"src/nest/oauth/oauth.module.ts": 2,
|
||||
"src/nest/packing/admin-packing-templates.controller.ts": 3,
|
||||
"src/nest/packing/packing.controller.ts": 1,
|
||||
"src/nest/packing/packing.dto.ts": 1,
|
||||
"src/nest/places/places.controller.ts": 1,
|
||||
"src/nest/places/places.mcp.ts": 5,
|
||||
"src/nest/platform/discovery-metadata.service.ts": 3,
|
||||
"src/nest/plugins/host/plugin-jobs.ts": 1,
|
||||
"src/nest/plugins/host/rpc/host-surface.rpc.ts": 8,
|
||||
"src/nest/plugins/registry/registry.service.ts": 1,
|
||||
"src/nest/plugins/runtime/plugin-host-entry.ts": 3,
|
||||
"src/nest/public-api/public-api.service.ts": 1,
|
||||
"src/nest/query-helpers/query-helpers.service.ts": 1,
|
||||
"src/nest/reservations/reservations-read.service.ts": 1,
|
||||
"src/nest/reservations/reservations.service.ts": 4,
|
||||
"src/nest/roadtrip/roadtrip-router.service.ts": 12,
|
||||
"src/nest/settings/settings.service.ts": 1,
|
||||
"src/nest/storage/drivers/s3.driver.ts": 1,
|
||||
"src/nest/trips/trips.service.ts": 1
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:strict: the strict type errors per file may only go down.
|
||||
*
|
||||
* The server compiles with strict: false, so a value that can be null or
|
||||
* undefined reads as always present, and an untyped parameter is a silent
|
||||
* `any` that no lint rule counts. Switching strict on at once is not a change
|
||||
* anyone can review, so this runs tsc over tsconfig.strict.json (the build
|
||||
* config plus strictNullChecks and noImplicitAny) and counts its errors per
|
||||
* file. A file may hold at most its entry in scripts/strict-baseline.json and
|
||||
* a file without an entry, a new one in particular, none. An entry above what
|
||||
* its file holds now, or for a file that is gone, fails as well until
|
||||
* --update lowers it, so a fixed error cannot come back unseen. An error tsc
|
||||
* reports outside any file (a broken config) fails the run, and so does a
|
||||
* tsc that exits non-zero without one error it can name: the check never
|
||||
* passes on output it could not read.
|
||||
*
|
||||
* npm run lint:strict check against the baseline (CI)
|
||||
* npm run lint:strict -- --update lower the baseline to today's counts;
|
||||
* it never raises or adds an entry
|
||||
*
|
||||
* --dir=<path> points it at another server root and --tsc-output=<file> reads
|
||||
* a saved `tsc --pretty false` output instead of running tsc (the unit tests
|
||||
* use both). The counting lives in scripts/lib/tsc-errors.mjs, the baseline
|
||||
* handling in scripts/lib/ratchet.mjs at the repository root.
|
||||
*/
|
||||
import {
|
||||
countMap,
|
||||
lowerCounts,
|
||||
RatchetError,
|
||||
readBaseline,
|
||||
reportStale,
|
||||
staleCounts,
|
||||
writeBaseline,
|
||||
} from '../../scripts/lib/ratchet.mjs';
|
||||
import { countErrors } from './lib/tsc-errors.mjs';
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/** tsc over tsconfig.strict.json, as its output and exit status. */
|
||||
function runTsc(serverDir) {
|
||||
const tsc = createRequire(join(serverDir, 'package.json')).resolve('typescript/bin/tsc');
|
||||
try {
|
||||
const output = execFileSync(
|
||||
process.execPath,
|
||||
[tsc, '-p', 'tsconfig.strict.json', '--noEmit', '--pretty', 'false'],
|
||||
{
|
||||
cwd: serverDir,
|
||||
encoding: 'utf8',
|
||||
maxBuffer: 256 * 1024 * 1024,
|
||||
},
|
||||
);
|
||||
return { output, status: 0 };
|
||||
} catch (err) {
|
||||
if (typeof err.status !== 'number') throw err;
|
||||
return { output: `${err.stdout ?? ''}${err.stderr ?? ''}`, status: err.status };
|
||||
}
|
||||
}
|
||||
|
||||
const sum = (map) => Object.values(map).reduce((a, b) => a + b, 0);
|
||||
|
||||
function check(argv) {
|
||||
const dirArg = argv.find((a) => a.startsWith('--dir='));
|
||||
const outputArg = argv.find((a) => a.startsWith('--tsc-output='));
|
||||
const serverDir = dirArg ? resolve(dirArg.slice('--dir='.length)) : fileURLToPath(new URL('..', import.meta.url));
|
||||
const baselinePath = join(serverDir, 'scripts', 'strict-baseline.json');
|
||||
|
||||
let baseline = readBaseline(baselinePath, countMap);
|
||||
const { output, status } = outputArg
|
||||
? { output: readFileSync(resolve(outputArg.slice('--tsc-output='.length)), 'utf8'), status: null }
|
||||
: runTsc(serverDir);
|
||||
const { counts, global } = countErrors(output);
|
||||
if (global.length) {
|
||||
throw new RatchetError(`tsc reported errors outside any file:\n ${global.join('\n ')}`);
|
||||
}
|
||||
if (status !== null && status !== 0 && !Object.keys(counts).length) {
|
||||
throw new RatchetError(`tsc exited with ${status} without an error it could name:\n${output.slice(0, 2000)}`);
|
||||
}
|
||||
|
||||
if (argv.includes('--update')) {
|
||||
baseline = lowerCounts(baseline, counts);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
const grown = Object.entries(counts).filter(([file, n]) => n > (baseline[file] ?? 0));
|
||||
for (const [file, n] of grown) {
|
||||
const entry = baseline[file];
|
||||
console.error(
|
||||
`FAIL ${file}: ${n} strict error(s), ` +
|
||||
(entry ? `its baseline is ${entry}. ` : 'a file without a baseline entry may have none. ') +
|
||||
'Run npx tsc -p tsconfig.strict.json --noEmit to see them; narrow the null case or type the parameter.',
|
||||
);
|
||||
// The first few in the log too, so a red CI job names them without a local run.
|
||||
const shown = output.split('\n').filter((line) => line.startsWith(`${file}(`));
|
||||
for (const line of shown.slice(0, 5)) console.error(` ${line.trim()}`);
|
||||
}
|
||||
const stale = staleCounts(baseline, counts);
|
||||
reportStale(stale, { file: 'strict-baseline.json', command: 'lint:strict', root: serverDir, error: console.error });
|
||||
console.log(
|
||||
`strict: ${sum(counts)} error(s) in ${Object.keys(counts).length} file(s), baseline ${sum(baseline)} in ${Object.keys(baseline).length}`,
|
||||
);
|
||||
return grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
|
||||
const isCli = Boolean(process.argv[1]) && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
try {
|
||||
process.exitCode = check(process.argv.slice(2));
|
||||
} catch (err) {
|
||||
if (!(err instanceof RatchetError)) throw err;
|
||||
console.error(`FAIL lint:strict: ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// The MCP SDK's client and in-memory transport resolve, through the `paths`
|
||||
// redirect in tsconfig.json, to its CommonJS build, which ships no type
|
||||
// definitions next to it, so the build reads them as untyped modules. Only
|
||||
// the strict ratchet (tsconfig.strict.json) loads this file: it declares the
|
||||
// two modules untyped there too, so an import of them is not counted as an
|
||||
// error the build does not have. The build and the tests never see it.
|
||||
|
||||
declare module '@modelcontextprotocol/sdk/client/index';
|
||||
declare module '@modelcontextprotocol/sdk/inMemory';
|
||||
@@ -0,0 +1,280 @@
|
||||
{
|
||||
"counts": {
|
||||
"tests/e2e/addons.e2e.test.ts": 1,
|
||||
"tests/e2e/admin.e2e.test.ts": 1,
|
||||
"tests/e2e/airports.e2e.test.ts": 1,
|
||||
"tests/e2e/assignments.e2e.test.ts": 1,
|
||||
"tests/e2e/atlas.e2e.test.ts": 1,
|
||||
"tests/e2e/auth.e2e.test.ts": 1,
|
||||
"tests/e2e/backup.e2e.test.ts": 1,
|
||||
"tests/e2e/booking-import.e2e.test.ts": 1,
|
||||
"tests/e2e/budget.e2e.test.ts": 1,
|
||||
"tests/e2e/calendar-feed-visibility.e2e.test.ts": 1,
|
||||
"tests/e2e/categories.e2e.test.ts": 1,
|
||||
"tests/e2e/collab.e2e.test.ts": 1,
|
||||
"tests/e2e/collections.e2e.test.ts": 1,
|
||||
"tests/e2e/dawarich.e2e.test.ts": 1,
|
||||
"tests/e2e/days.e2e.test.ts": 1,
|
||||
"tests/e2e/doc-sync.e2e.test.ts": 1,
|
||||
"tests/e2e/feeds.e2e.test.ts": 1,
|
||||
"tests/e2e/files.e2e.test.ts": 1,
|
||||
"tests/e2e/google-quota.e2e.test.ts": 1,
|
||||
"tests/e2e/journey.e2e.test.ts": 1,
|
||||
"tests/e2e/mailer.e2e.test.ts": 1,
|
||||
"tests/e2e/maps.e2e.test.ts": 1,
|
||||
"tests/e2e/memories.e2e.test.ts": 1,
|
||||
"tests/e2e/notifications.e2e.test.ts": 1,
|
||||
"tests/e2e/oauth.e2e.test.ts": 1,
|
||||
"tests/e2e/oidc.e2e.test.ts": 1,
|
||||
"tests/e2e/packing.e2e.test.ts": 1,
|
||||
"tests/e2e/place-enrichment.e2e.test.ts": 1,
|
||||
"tests/e2e/place-shadow.e2e.test.ts": 1,
|
||||
"tests/e2e/places.e2e.test.ts": 1,
|
||||
"tests/e2e/plugin-pois.e2e.test.ts": 1,
|
||||
"tests/e2e/plugin-search.e2e.test.ts": 1,
|
||||
"tests/e2e/public-api.e2e.test.ts": 1,
|
||||
"tests/e2e/push.e2e.test.ts": 1,
|
||||
"tests/e2e/receipt-scan.e2e.test.ts": 1,
|
||||
"tests/e2e/reservations.e2e.test.ts": 1,
|
||||
"tests/e2e/roadtrip.e2e.test.ts": 1,
|
||||
"tests/e2e/school-holidays.e2e.test.ts": 1,
|
||||
"tests/e2e/session-revocation.e2e.test.ts": 1,
|
||||
"tests/e2e/sessions.e2e.test.ts": 1,
|
||||
"tests/e2e/settings.e2e.test.ts": 1,
|
||||
"tests/e2e/share.e2e.test.ts": 1,
|
||||
"tests/e2e/storage-admin.e2e.test.ts": 1,
|
||||
"tests/e2e/system-notices.e2e.test.ts": 1,
|
||||
"tests/e2e/tags.e2e.test.ts": 1,
|
||||
"tests/e2e/todo.e2e.test.ts": 1,
|
||||
"tests/e2e/tours.e2e.test.ts": 1,
|
||||
"tests/e2e/transit-provider.e2e.test.ts": 1,
|
||||
"tests/e2e/transit.e2e.test.ts": 1,
|
||||
"tests/e2e/trip-invite.e2e.test.ts": 1,
|
||||
"tests/e2e/trips.e2e.test.ts": 1,
|
||||
"tests/e2e/vacay.e2e.test.ts": 1,
|
||||
"tests/e2e/weather.e2e.test.ts": 1,
|
||||
"tests/integration/admin.test.ts": 1,
|
||||
"tests/integration/airtrail-sync-request-context.test.ts": 1,
|
||||
"tests/integration/api-docs.test.ts": 1,
|
||||
"tests/integration/app-config.test.ts": 1,
|
||||
"tests/integration/assignments.test.ts": 1,
|
||||
"tests/integration/async-closure-truthiness-guards.test.ts": 1,
|
||||
"tests/integration/atlas-geocode-request-context.test.ts": 1,
|
||||
"tests/integration/atlas.test.ts": 1,
|
||||
"tests/integration/auth.test.ts": 1,
|
||||
"tests/integration/backup.test.ts": 1,
|
||||
"tests/integration/boot-sweeps-request-context.test.ts": 1,
|
||||
"tests/integration/bootstrap.test.ts": 1,
|
||||
"tests/integration/budget.test.ts": 1,
|
||||
"tests/integration/categories.test.ts": 1,
|
||||
"tests/integration/collab.test.ts": 1,
|
||||
"tests/integration/collections.test.ts": 1,
|
||||
"tests/integration/dayNotes.test.ts": 1,
|
||||
"tests/integration/dayReorder.test.ts": 1,
|
||||
"tests/integration/days.test.ts": 1,
|
||||
"tests/integration/demo-seed-request-context.test.ts": 1,
|
||||
"tests/integration/doc-sync-webhook-request-context.test.ts": 1,
|
||||
"tests/integration/feeds-request-context.test.ts": 1,
|
||||
"tests/integration/files.test.ts": 1,
|
||||
"tests/integration/help.test.ts": 1,
|
||||
"tests/integration/immich.test.ts": 1,
|
||||
"tests/integration/journey-place-order.test.ts": 1,
|
||||
"tests/integration/journey.test.ts": 1,
|
||||
"tests/integration/leg-mode-incoming.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v066.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v082.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v205.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v242.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v244.test.ts": 1,
|
||||
"tests/integration/maps.test.ts": 1,
|
||||
"tests/integration/mcp.test.ts": 1,
|
||||
"tests/integration/memories-immich.test.ts": 1,
|
||||
"tests/integration/memories-synology.test.ts": 1,
|
||||
"tests/integration/memories-unified.test.ts": 1,
|
||||
"tests/integration/misc.test.ts": 1,
|
||||
"tests/integration/notifications.test.ts": 1,
|
||||
"tests/integration/oauth-authorize.test.ts": 1,
|
||||
"tests/integration/oauth.test.ts": 1,
|
||||
"tests/integration/oidc-local-provider.test.ts": 1,
|
||||
"tests/integration/oidc.test.ts": 1,
|
||||
"tests/integration/orm-request-context-seams.test.ts": 1,
|
||||
"tests/integration/packing.test.ts": 1,
|
||||
"tests/integration/passkey.test.ts": 1,
|
||||
"tests/integration/places.test.ts": 1,
|
||||
"tests/integration/plugins/boot-registry-order.test.ts": 1,
|
||||
"tests/integration/plugins/plugin-runtime.test.ts": 1,
|
||||
"tests/integration/profile.test.ts": 1,
|
||||
"tests/integration/reservations.test.ts": 1,
|
||||
"tests/integration/scheduler-gate.test.ts": 1,
|
||||
"tests/integration/security.test.ts": 1,
|
||||
"tests/integration/settings.test.ts": 1,
|
||||
"tests/integration/share.test.ts": 1,
|
||||
"tests/integration/storage-health-notifier-request-context.test.ts": 1,
|
||||
"tests/integration/systemNotices.test.ts": 1,
|
||||
"tests/integration/tags.test.ts": 1,
|
||||
"tests/integration/todo.test.ts": 1,
|
||||
"tests/integration/trip-access-primitives.test.ts": 1,
|
||||
"tests/integration/trips.test.ts": 1,
|
||||
"tests/integration/uploads-photo-request-context.test.ts": 1,
|
||||
"tests/integration/uploads-static.test.ts": 1,
|
||||
"tests/integration/vacay.test.ts": 1,
|
||||
"tests/setup.ts": 1,
|
||||
"tests/unit/auto-backup.test.ts": 1,
|
||||
"tests/unit/db/database-lazy-open.test.ts": 1,
|
||||
"tests/unit/mcp/demo-tool-gate.test.ts": 1,
|
||||
"tests/unit/mcp/tools-addon-gating.test.ts": 1,
|
||||
"tests/unit/mcp/tools-airtrail.test.ts": 1,
|
||||
"tests/unit/mcp/tools-assignments-reservations-extra.test.ts": 1,
|
||||
"tests/unit/mcp/tools-assignments.test.ts": 1,
|
||||
"tests/unit/mcp/tools-atlas-expanded.test.ts": 1,
|
||||
"tests/unit/mcp/tools-atlas.test.ts": 1,
|
||||
"tests/unit/mcp/tools-budget-advanced.test.ts": 1,
|
||||
"tests/unit/mcp/tools-budget.test.ts": 1,
|
||||
"tests/unit/mcp/tools-categories.test.ts": 1,
|
||||
"tests/unit/mcp/tools-collab-polls-chat.test.ts": 1,
|
||||
"tests/unit/mcp/tools-collections.test.ts": 1,
|
||||
"tests/unit/mcp/tools-days-accommodations.test.ts": 1,
|
||||
"tests/unit/mcp/tools-days.test.ts": 1,
|
||||
"tests/unit/mcp/tools-feeds-invite.test.ts": 1,
|
||||
"tests/unit/mcp/tools-files.test.ts": 1,
|
||||
"tests/unit/mcp/tools-help-addons.test.ts": 1,
|
||||
"tests/unit/mcp/tools-journey.test.ts": 1,
|
||||
"tests/unit/mcp/tools-leg-transport-mode.test.ts": 1,
|
||||
"tests/unit/mcp/tools-memories.test.ts": 1,
|
||||
"tests/unit/mcp/tools-notes.test.ts": 1,
|
||||
"tests/unit/mcp/tools-notifications.test.ts": 1,
|
||||
"tests/unit/mcp/tools-packing-advanced.test.ts": 1,
|
||||
"tests/unit/mcp/tools-packing.test.ts": 1,
|
||||
"tests/unit/mcp/tools-places.test.ts": 1,
|
||||
"tests/unit/mcp/tools-plugin-pois.test.ts": 1,
|
||||
"tests/unit/mcp/tools-plugin-search.test.ts": 1,
|
||||
"tests/unit/mcp/tools-prompts.test.ts": 1,
|
||||
"tests/unit/mcp/tools-reservations.test.ts": 1,
|
||||
"tests/unit/mcp/tools-roadtrip.test.ts": 1,
|
||||
"tests/unit/mcp/tools-settings.test.ts": 1,
|
||||
"tests/unit/mcp/tools-share.test.ts": 1,
|
||||
"tests/unit/mcp/tools-tags-maps-weather.test.ts": 1,
|
||||
"tests/unit/mcp/tools-todos.test.ts": 1,
|
||||
"tests/unit/mcp/tools-transit.test.ts": 1,
|
||||
"tests/unit/mcp/tools-transports.test.ts": 1,
|
||||
"tests/unit/mcp/tools-trip-members.test.ts": 1,
|
||||
"tests/unit/mcp/tools-trip-warnings.test.ts": 1,
|
||||
"tests/unit/mcp/tools-trips.test.ts": 1,
|
||||
"tests/unit/mcp/tools-vacay.test.ts": 1,
|
||||
"tests/unit/nest/accommodations.service.test.ts": 1,
|
||||
"tests/unit/nest/admin.service.test.ts": 1,
|
||||
"tests/unit/nest/admin.version-notification.test.ts": 1,
|
||||
"tests/unit/nest/assignments.service.test.ts": 1,
|
||||
"tests/unit/nest/atlas.service.test.ts": 1,
|
||||
"tests/unit/nest/auth.service.test.ts": 1,
|
||||
"tests/unit/nest/backup.impl.test.ts": 1,
|
||||
"tests/unit/nest/booking-import/booking-import.service.test.ts": 1,
|
||||
"tests/unit/nest/budget.service.calc.test.ts": 1,
|
||||
"tests/unit/nest/budget.service.db.test.ts": 1,
|
||||
"tests/unit/nest/budget.service.test.ts": 1,
|
||||
"tests/unit/nest/calendar.service.test.ts": 1,
|
||||
"tests/unit/nest/channel-override.test.ts": 1,
|
||||
"tests/unit/nest/collab.service.test.ts": 1,
|
||||
"tests/unit/nest/collections.service.test.ts": 1,
|
||||
"tests/unit/nest/common/conflictUpdate.test.ts": 1,
|
||||
"tests/unit/nest/database/database-lifecycle.service.test.ts": 2,
|
||||
"tests/unit/nest/dawarich-sync.service.test.ts": 1,
|
||||
"tests/unit/nest/day-notes.service.test.ts": 1,
|
||||
"tests/unit/nest/day-removal.service.test.ts": 1,
|
||||
"tests/unit/nest/days.service.test.ts": 1,
|
||||
"tests/unit/nest/doc-sync/doc-sync-config.service.test.ts": 1,
|
||||
"tests/unit/nest/doc-sync/doc-sync-webhook.controller.test.ts": 1,
|
||||
"tests/unit/nest/doc-sync/doc-sync.controller.test.ts": 1,
|
||||
"tests/unit/nest/doc-sync/doc-sync.service.test.ts": 1,
|
||||
"tests/unit/nest/files.service.test.ts": 1,
|
||||
"tests/unit/nest/google-quota.service.test.ts": 1,
|
||||
"tests/unit/nest/immich.service.test.ts": 1,
|
||||
"tests/unit/nest/journey-book.service.test.ts": 1,
|
||||
"tests/unit/nest/journey-domain.service.test.ts": 1,
|
||||
"tests/unit/nest/journey-share.service.test.ts": 1,
|
||||
"tests/unit/nest/journey-stats.service.test.ts": 1,
|
||||
"tests/unit/nest/mailer.service.test.ts": 1,
|
||||
"tests/unit/nest/maps.amap.test.ts": 1,
|
||||
"tests/unit/nest/maps.curated-images.test.ts": 1,
|
||||
"tests/unit/nest/maps.google-quota.test.ts": 1,
|
||||
"tests/unit/nest/maps.identity.test.ts": 1,
|
||||
"tests/unit/nest/maps.service.test.ts": 1,
|
||||
"tests/unit/nest/mcp-shared.service.test.ts": 1,
|
||||
"tests/unit/nest/mcp-transport.service.test.ts": 1,
|
||||
"tests/unit/nest/memories-access.service.test.ts": 1,
|
||||
"tests/unit/nest/notification-preferences.service.test.ts": 1,
|
||||
"tests/unit/nest/notification-transports.test.ts": 1,
|
||||
"tests/unit/nest/notifications.inapp-prefs.test.ts": 1,
|
||||
"tests/unit/nest/notifications.service.test.ts": 1,
|
||||
"tests/unit/nest/notifications/push-subscriptions.service.test.ts": 1,
|
||||
"tests/unit/nest/notifications/vapid-keys.service.test.ts": 1,
|
||||
"tests/unit/nest/notifications/web-push-dispatch.test.ts": 1,
|
||||
"tests/unit/nest/notifications/web-push.service.test.ts": 1,
|
||||
"tests/unit/nest/oauth.service.test.ts": 1,
|
||||
"tests/unit/nest/oidc.service.test.ts": 1,
|
||||
"tests/unit/nest/packing.service.test.ts": 1,
|
||||
"tests/unit/nest/passkey.service.test.ts": 1,
|
||||
"tests/unit/nest/permissions.service.test.ts": 1,
|
||||
"tests/unit/nest/photo-resolver.service.test.ts": 1,
|
||||
"tests/unit/nest/photos/trekPhotoMedia.test.ts": 1,
|
||||
"tests/unit/nest/place-photos/place-photo-cache.service.test.ts": 1,
|
||||
"tests/unit/nest/place-regions-repair.test.ts": 1,
|
||||
"tests/unit/nest/places.controller.test.ts": 1,
|
||||
"tests/unit/nest/places.directions.test.ts": 1,
|
||||
"tests/unit/nest/places.helpers.test.ts": 1,
|
||||
"tests/unit/nest/places.service.test.ts": 1,
|
||||
"tests/unit/nest/platform.controller.test.ts": 1,
|
||||
"tests/unit/nest/public-api-scopes.test.ts": 1,
|
||||
"tests/unit/nest/registration-invites.service.test.ts": 1,
|
||||
"tests/unit/nest/reminder-jobs.service.test.ts": 1,
|
||||
"tests/unit/nest/reservations.service.test.ts": 1,
|
||||
"tests/unit/nest/route-inventory.test.ts": 1,
|
||||
"tests/unit/nest/settings.service.test.ts": 1,
|
||||
"tests/unit/nest/share.service.test.ts": 1,
|
||||
"tests/unit/nest/storage/storage-admin.service.test.ts": 1,
|
||||
"tests/unit/nest/storage/storage-jobs.service.test.ts": 1,
|
||||
"tests/unit/nest/storage/storage-registry.service.test.ts": 1,
|
||||
"tests/unit/nest/storage/storage-stats.service.test.ts": 1,
|
||||
"tests/unit/nest/synology.service.test.ts": 1,
|
||||
"tests/unit/nest/todo.service.test.ts": 1,
|
||||
"tests/unit/nest/token.service.test.ts": 1,
|
||||
"tests/unit/nest/tours.controller.test.ts": 1,
|
||||
"tests/unit/nest/tours.gpx.atomic.test.ts": 1,
|
||||
"tests/unit/nest/tours.permissions.boundaries.mock-only.test.ts": 1,
|
||||
"tests/unit/nest/tours.permissions.test.ts": 1,
|
||||
"tests/unit/nest/tours.service.permissions.test.ts": 1,
|
||||
"tests/unit/nest/tours.service.test.ts": 1,
|
||||
"tests/unit/nest/transit-itinerary.helpers.test.ts": 1,
|
||||
"tests/unit/nest/travel-stats.service.test.ts": 1,
|
||||
"tests/unit/nest/trip-invite.service.test.ts": 1,
|
||||
"tests/unit/nest/trip-members.service.test.ts": 1,
|
||||
"tests/unit/nest/trip-read-model.service.test.ts": 1,
|
||||
"tests/unit/nest/trips.service.test.ts": 1,
|
||||
"tests/unit/nest/unified-memories.service.test.ts": 1,
|
||||
"tests/unit/nest/user-cleanup.service.test.ts": 1,
|
||||
"tests/unit/nest/user-profile.service.test.ts": 1,
|
||||
"tests/unit/nest/vacay.service.test.ts": 1,
|
||||
"tests/unit/plugins/atlas-layers.controller.test.ts": 1,
|
||||
"tests/unit/plugins/day-schedule.controller.test.ts": 1,
|
||||
"tests/unit/plugins/day-tints.controller.test.ts": 1,
|
||||
"tests/unit/plugins/host-rpc.test.ts": 1,
|
||||
"tests/unit/plugins/map-layers.controller.test.ts": 1,
|
||||
"tests/unit/plugins/map-markers.controller.test.ts": 1,
|
||||
"tests/unit/plugins/operator-egress.test.ts": 1,
|
||||
"tests/unit/plugins/pdf-sections.controller.test.ts": 1,
|
||||
"tests/unit/plugins/place-details.controller.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-instance-settings.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-oauth.service.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-pois.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-retrust.controller.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-routes.controller.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-user-settings.test.ts": 1,
|
||||
"tests/unit/plugins/plugins-service.test.ts": 1,
|
||||
"tests/unit/plugins/settings-isolation.test.ts": 1,
|
||||
"tests/unit/plugins/trip-card-contributions.controller.test.ts": 1,
|
||||
"tests/unit/plugins/trip-warnings.controller.test.ts": 1,
|
||||
"tests/unit/plugins/view-contributions.controller.test.ts": 1,
|
||||
"tests/websocket/connection.test.ts": 1,
|
||||
"tests/websocket/wire-envelope.test.ts": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:test-mocks: module mocks of the config, the realtime transport and the
|
||||
* database modules in tests/ may only shrink.
|
||||
*
|
||||
* A `vi.mock` of one of those paths replaces a module every domain imports,
|
||||
* so a suite stays green for reasons its cases do not show (a factory that
|
||||
* happens to export the names the import order reaches first) and every
|
||||
* constructor or import change ripples through hundreds of factories. The
|
||||
* test infrastructure covers each of them instead:
|
||||
*
|
||||
* src/config the setup file fixes its values once
|
||||
* (tests/helpers/test-config.ts, overrideTestConfig)
|
||||
* src/nest/realtime/** a FakeRealtimeService through DI, or spyOnRealtime(app)
|
||||
* src/db/** a snapshot test db (tests/helpers/db-mock.ts) handed
|
||||
* to the code under test; the remaining `src/db/database`
|
||||
* mocks are the legacy this counts down
|
||||
*
|
||||
* Every `vi.mock(` / `vi.doMock(` outside a comment whose path (a string, or
|
||||
* `import('...')`) ends in one of those modules counts, per file, against scripts/test-mocks-baseline.json; a file without
|
||||
* an entry may hold none (scripts/lib/count-ratchet.mjs has the rules).
|
||||
*
|
||||
* npm run lint:test-mocks check against the baseline (CI)
|
||||
* npm run lint:test-mocks -- --update lower the counts; never raises or adds an entry
|
||||
*/
|
||||
import { cliMain, stripComments } from './lib/count-ratchet.mjs';
|
||||
|
||||
// The path as a string, or wrapped in import(), the typed form vi.mock also takes.
|
||||
const MOCK_CALL = /\bvi\.(?:mock|doMock)\(\s*(?:import\(\s*)?(['"`])([^'"`]+)\1/g;
|
||||
|
||||
/** A mocked path that names one of the held modules, with or without an extension. */
|
||||
const HELD_TARGET = /(?:^|\/)src\/(?:config|websocket|db(?:\/[^'"`]*)?|nest\/realtime(?:\/[^'"`]*)?)$/;
|
||||
|
||||
/** The module mocks of held targets in one file's text; a mock quoted in a comment does not count. */
|
||||
export function countHeldMocks(text) {
|
||||
let n = 0;
|
||||
for (const match of stripComments(text).matchAll(MOCK_CALL)) {
|
||||
const target = match[2].replace(/\.(?:[cm]?[jt]s)$/, '');
|
||||
if (HELD_TARGET.test(target)) n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
export const check = {
|
||||
name: 'test-mocks',
|
||||
script: 'lint:test-mocks',
|
||||
root: 'tests',
|
||||
baseline: 'scripts/test-mocks-baseline.json',
|
||||
unit: 'module mock(s) of config, realtime or db',
|
||||
advice:
|
||||
'Use the test config (overrideTestConfig), a FakeRealtimeService or spyOnRealtime(app), ' +
|
||||
'and a snapshot test db handed to the code under test instead of mocking the module.',
|
||||
include: (file) => /\.[cm]?[jt]s$/.test(file),
|
||||
count: (text) => countHeldMocks(text),
|
||||
};
|
||||
|
||||
cliMain(check, import.meta.url);
|
||||
@@ -0,0 +1,204 @@
|
||||
{
|
||||
"counts": {
|
||||
"tests/helpers/accommodations-service.ts": 8,
|
||||
"tests/helpers/maps-service.ts": 1,
|
||||
"tests/helpers/notifications.ts": 10,
|
||||
"tests/helpers/place-import.ts": 1,
|
||||
"tests/helpers/plugin-host.ts": 45,
|
||||
"tests/helpers/sessions.ts": 1,
|
||||
"tests/helpers/storage-fixture.ts": 1,
|
||||
"tests/helpers/test-addons.ts": 1,
|
||||
"tests/helpers/test-uow.ts": 3,
|
||||
"tests/integration/dayReorder.test.ts": 3,
|
||||
"tests/integration/mcp.test.ts": 2,
|
||||
"tests/integration/oauth-authorize.test.ts": 2,
|
||||
"tests/integration/oauth.test.ts": 2,
|
||||
"tests/integration/plugins/boot-registry-order.test.ts": 7,
|
||||
"tests/integration/plugins/plugin-runtime.task2-conversion.test.ts": 17,
|
||||
"tests/integration/plugins/plugin-scheduler-sweep.test.ts": 5,
|
||||
"tests/integration/plugins/registry.test.ts": 2,
|
||||
"tests/integration/share.test.ts": 2,
|
||||
"tests/integration/storage-restore-reload.test.ts": 2,
|
||||
"tests/integration/storage-stream-abort.test.ts": 3,
|
||||
"tests/unit/budget/costs.rpc.test.ts": 1,
|
||||
"tests/unit/db/connection.test.ts": 1,
|
||||
"tests/unit/db/repositories/DemoRepository.test.ts": 1,
|
||||
"tests/unit/db/repositories/MaintenanceRepository.test.ts": 2,
|
||||
"tests/unit/db/repositories/UserConnections.repository.test.ts": 3,
|
||||
"tests/unit/demo/demo-reset-sessions.test.ts": 3,
|
||||
"tests/unit/mcp/tools-airtrail.test.ts": 1,
|
||||
"tests/unit/mcp/tools-budget-advanced.test.ts": 2,
|
||||
"tests/unit/mcp/tools-categories.test.ts": 4,
|
||||
"tests/unit/mcp/tools-prompts.test.ts": 7,
|
||||
"tests/unit/mcp/tools-roadtrip.test.ts": 1,
|
||||
"tests/unit/mcp/tools-transit.test.ts": 1,
|
||||
"tests/unit/nest-rpc/plugin-guards.test.ts": 1,
|
||||
"tests/unit/nest-rpc/rpc-kit/registry.service.test.ts": 3,
|
||||
"tests/unit/nest/accommodations.service.test.ts": 1,
|
||||
"tests/unit/nest/addons.service.test.ts": 2,
|
||||
"tests/unit/nest/admin.service.test.ts": 11,
|
||||
"tests/unit/nest/admin.version-notification.test.ts": 11,
|
||||
"tests/unit/nest/airports/airports.service.test.ts": 7,
|
||||
"tests/unit/nest/airtrail.service.test.ts": 3,
|
||||
"tests/unit/nest/assignments.service.test.ts": 6,
|
||||
"tests/unit/nest/atlas.service.test.ts": 2,
|
||||
"tests/unit/nest/audit.service.test.ts": 1,
|
||||
"tests/unit/nest/auth-core/auth-guard.test.ts": 3,
|
||||
"tests/unit/nest/auth.controller.test.ts": 1,
|
||||
"tests/unit/nest/auth.service.test.ts": 9,
|
||||
"tests/unit/nest/backup.controller.test.ts": 1,
|
||||
"tests/unit/nest/booking-import/booking-import.service.test.ts": 3,
|
||||
"tests/unit/nest/booking-import/import-jobs.service.test.ts": 1,
|
||||
"tests/unit/nest/booking-import/kitinerary-extractor.service.test.ts": 1,
|
||||
"tests/unit/nest/budget.service.calc.test.ts": 1,
|
||||
"tests/unit/nest/budget.service.db.test.ts": 6,
|
||||
"tests/unit/nest/budget.service.test.ts": 1,
|
||||
"tests/unit/nest/calendar.service.test.ts": 6,
|
||||
"tests/unit/nest/categories.service.test.ts": 1,
|
||||
"tests/unit/nest/channel-override.test.ts": 2,
|
||||
"tests/unit/nest/charging.test.ts": 6,
|
||||
"tests/unit/nest/collab.service.test.ts": 6,
|
||||
"tests/unit/nest/collections.service.test.ts": 3,
|
||||
"tests/unit/nest/common/conflictUpdate.test.ts": 9,
|
||||
"tests/unit/nest/cron-registrar.service.test.ts": 18,
|
||||
"tests/unit/nest/dawarich-suggestions.service.test.ts": 1,
|
||||
"tests/unit/nest/dawarich-sync.service.test.ts": 1,
|
||||
"tests/unit/nest/dawarich-tracks.service.test.ts": 1,
|
||||
"tests/unit/nest/dawarich.service.test.ts": 1,
|
||||
"tests/unit/nest/day-boundaries.test.ts": 1,
|
||||
"tests/unit/nest/demo.service.test.ts": 1,
|
||||
"tests/unit/nest/doc-sync/doc-sync-config.service.test.ts": 1,
|
||||
"tests/unit/nest/doc-sync/doc-sync.controller.test.ts": 1,
|
||||
"tests/unit/nest/doc-sync/doc-sync.job.test.ts": 3,
|
||||
"tests/unit/nest/doc-sync/doc-sync.service.test.ts": 3,
|
||||
"tests/unit/nest/features.controller.test.ts": 2,
|
||||
"tests/unit/nest/feeds.service.test.ts": 1,
|
||||
"tests/unit/nest/files.service.test.ts": 7,
|
||||
"tests/unit/nest/google-quota.service.test.ts": 1,
|
||||
"tests/unit/nest/google-route.test.ts": 1,
|
||||
"tests/unit/nest/google-transit.provider.test.ts": 7,
|
||||
"tests/unit/nest/immich.service.test.ts": 1,
|
||||
"tests/unit/nest/integrations/airtrailImport.test.ts": 5,
|
||||
"tests/unit/nest/integrations/airtrailTestConnection.test.ts": 3,
|
||||
"tests/unit/nest/integrations/airtrailWriteback.test.ts": 3,
|
||||
"tests/unit/nest/integrations/airtrailWriteGate.test.ts": 2,
|
||||
"tests/unit/nest/journey-book.service.test.ts": 3,
|
||||
"tests/unit/nest/journey-domain.service.test.ts": 2,
|
||||
"tests/unit/nest/journey-photo-capture.service.test.ts": 3,
|
||||
"tests/unit/nest/journey-share.service.test.ts": 4,
|
||||
"tests/unit/nest/journey-stats.service.test.ts": 2,
|
||||
"tests/unit/nest/llm-parse/llm-parse.service.test.ts": 1,
|
||||
"tests/unit/nest/mailer.service.test.ts": 1,
|
||||
"tests/unit/nest/mcp-shared.service.test.ts": 2,
|
||||
"tests/unit/nest/mcp-transport.service.test.ts": 1,
|
||||
"tests/unit/nest/memories-access.service.test.ts": 1,
|
||||
"tests/unit/nest/memories.service.test.ts": 1,
|
||||
"tests/unit/nest/memories/journey-thumbs.job.test.ts": 2,
|
||||
"tests/unit/nest/memories/trek-photo-cache.job.test.ts": 1,
|
||||
"tests/unit/nest/notification-preferences.service.test.ts": 4,
|
||||
"tests/unit/nest/notification-transports.test.ts": 3,
|
||||
"tests/unit/nest/notifications/storage-health-notifier.service.test.ts": 2,
|
||||
"tests/unit/nest/notifications/vapid-keys.service.test.ts": 2,
|
||||
"tests/unit/nest/notifications/web-push.service.test.ts": 1,
|
||||
"tests/unit/nest/oauth.controller.test.ts": 1,
|
||||
"tests/unit/nest/oauth.service.test.ts": 4,
|
||||
"tests/unit/nest/oidc.service.test.ts": 13,
|
||||
"tests/unit/nest/packing-writes.service.test.ts": 2,
|
||||
"tests/unit/nest/packing.controller.test.ts": 1,
|
||||
"tests/unit/nest/packing.service.test.ts": 1,
|
||||
"tests/unit/nest/passkey.service.test.ts": 10,
|
||||
"tests/unit/nest/permissions.service.test.ts": 2,
|
||||
"tests/unit/nest/photo-capture-backfill.exif.test.ts": 1,
|
||||
"tests/unit/nest/photo-capture-backfill.service.test.ts": 5,
|
||||
"tests/unit/nest/photo-resolver.service.test.ts": 2,
|
||||
"tests/unit/nest/photos/trekPhotoMedia.test.ts": 1,
|
||||
"tests/unit/nest/place-enrichment.brand.test.ts": 1,
|
||||
"tests/unit/nest/place-enrichment.controller.test.ts": 2,
|
||||
"tests/unit/nest/place-enrichment.description.test.ts": 1,
|
||||
"tests/unit/nest/place-enrichment.service.test.ts": 1,
|
||||
"tests/unit/nest/place-photos/place-photo-cache.job.test.ts": 2,
|
||||
"tests/unit/nest/place-photos/place-photo-cache.service.test.ts": 1,
|
||||
"tests/unit/nest/place-regions-repair.test.ts": 1,
|
||||
"tests/unit/nest/place-shadow.service.test.ts": 1,
|
||||
"tests/unit/nest/places.directions.test.ts": 6,
|
||||
"tests/unit/nest/places.service.test.ts": 6,
|
||||
"tests/unit/nest/process-state-ports.test.ts": 9,
|
||||
"tests/unit/nest/public-api-scopes.test.ts": 4,
|
||||
"tests/unit/nest/public-api.service.test.ts": 1,
|
||||
"tests/unit/nest/public-stats.controller.test.ts": 2,
|
||||
"tests/unit/nest/query-helpers.service.test.ts": 1,
|
||||
"tests/unit/nest/rate-limit.service.test.ts": 6,
|
||||
"tests/unit/nest/realtime.gateway.test.ts": 16,
|
||||
"tests/unit/nest/receipt-scan.controller.test.ts": 1,
|
||||
"tests/unit/nest/registration-invites.service.test.ts": 1,
|
||||
"tests/unit/nest/reminder-jobs.service.test.ts": 2,
|
||||
"tests/unit/nest/reservations.service.test.ts": 2,
|
||||
"tests/unit/nest/roadtrip-plan.service.test.ts": 5,
|
||||
"tests/unit/nest/roadtrip-planning.test.ts": 2,
|
||||
"tests/unit/nest/roadtrip-router.test.ts": 1,
|
||||
"tests/unit/nest/roadtrip-search.test.ts": 3,
|
||||
"tests/unit/nest/roadtrip.service.test.ts": 1,
|
||||
"tests/unit/nest/route-usage.service.test.ts": 1,
|
||||
"tests/unit/nest/school-holidays.service.test.ts": 1,
|
||||
"tests/unit/nest/sessions/sessions.service.test.ts": 1,
|
||||
"tests/unit/nest/settings.service.test.ts": 1,
|
||||
"tests/unit/nest/share.service.test.ts": 3,
|
||||
"tests/unit/nest/sqlite-database-backup.test.ts": 2,
|
||||
"tests/unit/nest/storage/storage-admin.service.test.ts": 5,
|
||||
"tests/unit/nest/storage/storage-jobs.service.test.ts": 15,
|
||||
"tests/unit/nest/storage/storage-registry.service.test.ts": 3,
|
||||
"tests/unit/nest/storage/storage-stats.service.test.ts": 3,
|
||||
"tests/unit/nest/storage/storage.service.test.ts": 5,
|
||||
"tests/unit/nest/synology.service.test.ts": 1,
|
||||
"tests/unit/nest/system-notices.branch-coverage.test.ts": 1,
|
||||
"tests/unit/nest/system-notices.service.test.ts": 1,
|
||||
"tests/unit/nest/tags.service.test.ts": 1,
|
||||
"tests/unit/nest/thumbnail.service.test.ts": 1,
|
||||
"tests/unit/nest/todo.service.test.ts": 5,
|
||||
"tests/unit/nest/token.service.test.ts": 1,
|
||||
"tests/unit/nest/tours.gpx.atomic.test.ts": 7,
|
||||
"tests/unit/nest/tours.permissions.boundaries.mock-only.test.ts": 1,
|
||||
"tests/unit/nest/tours.service.permissions.test.ts": 1,
|
||||
"tests/unit/nest/tours.service.test.ts": 1,
|
||||
"tests/unit/nest/transit.service.test.ts": 2,
|
||||
"tests/unit/nest/travel-stats.service.test.ts": 1,
|
||||
"tests/unit/nest/trek-photo-cache.service.test.ts": 2,
|
||||
"tests/unit/nest/trek-photo-registration.service.test.ts": 1,
|
||||
"tests/unit/nest/trip-invite.service.test.ts": 4,
|
||||
"tests/unit/nest/trip-members.service.test.ts": 6,
|
||||
"tests/unit/nest/trip-membership/trip-membership.service.test.ts": 1,
|
||||
"tests/unit/nest/trip-read-model.service.test.ts": 31,
|
||||
"tests/unit/nest/trips.service.test.ts": 38,
|
||||
"tests/unit/nest/unified-memories.service.test.ts": 3,
|
||||
"tests/unit/nest/unsplash/unsplash.service.test.ts": 1,
|
||||
"tests/unit/nest/user-cleanup.service.test.ts": 8,
|
||||
"tests/unit/nest/user-profile.service.test.ts": 1,
|
||||
"tests/unit/nest/vacay.service.test.ts": 2,
|
||||
"tests/unit/nest/weather/weather-cache-lifecycle.test.ts": 1,
|
||||
"tests/unit/nest/webauthn-config.service.test.ts": 1,
|
||||
"tests/unit/packing/packing.rpc.test.ts": 1,
|
||||
"tests/unit/plugins/addon-gates.rpc.test.ts": 1,
|
||||
"tests/unit/plugins/day-schedule.controller.test.ts": 1,
|
||||
"tests/unit/plugins/day-tints.controller.test.ts": 1,
|
||||
"tests/unit/plugins/map-layers.controller.test.ts": 1,
|
||||
"tests/unit/plugins/map-markers.controller.test.ts": 1,
|
||||
"tests/unit/plugins/operator-egress.test.ts": 1,
|
||||
"tests/unit/plugins/pdf-sections.controller.test.ts": 1,
|
||||
"tests/unit/plugins/place-details.controller.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-instance-settings.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-mcp-tools.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-oauth.service.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-pois.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-routes.controller.test.ts": 1,
|
||||
"tests/unit/plugins/plugin-runtime.boot-no-orm.test.ts": 3,
|
||||
"tests/unit/plugins/plugin-user-settings.test.ts": 2,
|
||||
"tests/unit/plugins/plugins-service.test.ts": 1,
|
||||
"tests/unit/plugins/request-context.test.ts": 1,
|
||||
"tests/unit/plugins/rpc-coverage.test.ts": 1,
|
||||
"tests/unit/plugins/settings-isolation.test.ts": 3,
|
||||
"tests/unit/plugins/trip-card-contributions.controller.test.ts": 1,
|
||||
"tests/unit/plugins/trip-warnings.controller.test.ts": 1,
|
||||
"tests/unit/plugins/view-contributions.controller.test.ts": 1,
|
||||
"tests/websocket/connection.test.ts": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:test-new-service: hand-built services and repositories in tests/ may
|
||||
* only shrink.
|
||||
*
|
||||
* `new XService(a, b, c, ...)` in a test pins the constructor's parameter
|
||||
* order: every dependency a service gains is a change to every suite that
|
||||
* builds it (and to every suite that builds one of its consumers), which is
|
||||
* why the harness files are among the most churned in the repository. A suite
|
||||
* takes its subject from a Nest testing module instead (tests/helpers/
|
||||
* test-module.ts: createTestModule with overrides), and a booted app hands
|
||||
* the rest out through `app.get(...)`.
|
||||
*
|
||||
* Every `new <Name>Service(` and `new <Name>Repository(` under tests/ outside a
|
||||
* comment counts (an import alias or `new (Name)(` counts as the class it
|
||||
* names), per file, against scripts/test-new-service-baseline.json; a file without an
|
||||
* entry may hold none (scripts/lib/count-ratchet.mjs has the rules). The
|
||||
* allowlist is derived, not kept by hand: a class whose constructor takes no
|
||||
* parameters (no constructor of its own, or an empty one, down its chain of
|
||||
* `extends` inside src/ and tests/helpers/) has no wiring to pin, so building
|
||||
* it with `new` does not count. RealtimeService and FakeRealtimeService are
|
||||
* the common case.
|
||||
*
|
||||
* npm run lint:test-new-service check against the baseline (CI)
|
||||
* npm run lint:test-new-service -- --update lower the counts; never raises or adds an entry
|
||||
*/
|
||||
import { cliMain, stripComments } from './lib/count-ratchet.mjs';
|
||||
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const CLASS_DECL = /\bclass\s+([A-Za-z_$][\w$]*)(?:\s*<[^{]*?>)?(?:\s+extends\s+([A-Za-z_$][\w$.]*))?[^{]*\{/g;
|
||||
|
||||
/** The trees whose classes the allowlist is derived from, relative to the server root. */
|
||||
const CLASS_ROOTS = ['src', 'tests/helpers'];
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === 'node_modules') continue;
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path, files);
|
||||
else if (/\.[cm]?ts$/.test(name)) files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** The index just past the bracket that closes the one at `open`, skipping strings and comments. */
|
||||
function closeOf(text, open) {
|
||||
const pairs = { '(': ')', '{': '}', '[': ']' };
|
||||
const stack = [];
|
||||
for (let i = open; i < text.length; i++) {
|
||||
const c = text[i];
|
||||
if (c === '/' && text[i + 1] === '/') {
|
||||
i = text.indexOf('\n', i);
|
||||
if (i < 0) return text.length;
|
||||
continue;
|
||||
}
|
||||
if (c === '/' && text[i + 1] === '*') {
|
||||
i = text.indexOf('*/', i + 2) + 1;
|
||||
if (i <= 0) return text.length;
|
||||
continue;
|
||||
}
|
||||
if (c === '"' || c === "'" || c === '`') {
|
||||
for (i++; i < text.length && text[i] !== c; i++) if (text[i] === '\\') i++;
|
||||
continue;
|
||||
}
|
||||
if (pairs[c]) stack.push(pairs[c]);
|
||||
else if (c === stack[stack.length - 1]) {
|
||||
stack.pop();
|
||||
if (!stack.length) return i + 1;
|
||||
}
|
||||
}
|
||||
return text.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every class declared in `text`: its parent, and whether its own constructor
|
||||
* takes parameters (`null` when it declares none).
|
||||
*/
|
||||
export function parseClasses(text) {
|
||||
const classes = [];
|
||||
for (const match of text.matchAll(CLASS_DECL)) {
|
||||
const bodyOpen = match.index + match[0].length - 1;
|
||||
const body = text.slice(bodyOpen, closeOf(text, bodyOpen));
|
||||
const ctor = /\bconstructor\s*\(/.exec(body);
|
||||
let ctorHasParams = null;
|
||||
if (ctor) {
|
||||
const open = ctor.index + ctor[0].length - 1;
|
||||
const params = body
|
||||
.slice(open + 1, closeOf(body, open) - 1)
|
||||
.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
.replace(/\/\/.*$/gm, '')
|
||||
.trim();
|
||||
ctorHasParams = params.length > 0;
|
||||
}
|
||||
classes.push({ name: match[1], parent: match[2] ?? null, ctorHasParams });
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The names whose constructor takes no parameters, resolved down the extends
|
||||
* chain. A parent declared outside the scanned trees (a library class) is
|
||||
* taken to need arguments, so a subclass without a constructor of its own counts.
|
||||
*/
|
||||
export function zeroArgClasses(classes) {
|
||||
const byName = new Map();
|
||||
for (const c of classes) if (!byName.has(c.name)) byName.set(c.name, c);
|
||||
const memo = new Map();
|
||||
const resolve = (name, seen = new Set()) => {
|
||||
if (memo.has(name)) return memo.get(name);
|
||||
const c = byName.get(name);
|
||||
let zero;
|
||||
if (!c || seen.has(name)) zero = false;
|
||||
else if (c.ctorHasParams !== null) zero = !c.ctorHasParams;
|
||||
else zero = c.parent === null ? true : resolve(c.parent, new Set([...seen, name]));
|
||||
memo.set(name, zero);
|
||||
return zero;
|
||||
};
|
||||
return new Set([...byName.keys()].filter((name) => resolve(name)));
|
||||
}
|
||||
|
||||
// `new X(`, `new X<T>(` and `new (X)(`: the name is checked after aliases resolve.
|
||||
const ANY_NEW = /\bnew(?:\s+|\s*\(\s*)([A-Za-z_$][\w$]*)\s*\)?\s*[(<]/g;
|
||||
// `import { DaysService as Days }` (and `type`-less re-imports of the same shape).
|
||||
const IMPORT_BLOCK = /\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\b/g;
|
||||
const ALIAS = /\b([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)/g;
|
||||
const SERVICE_NAME = /^[A-Z][A-Za-z0-9_]*(?:Service|Repository)$/;
|
||||
|
||||
/** Local name -> imported name, for every renamed import in the text. */
|
||||
function importAliases(text) {
|
||||
const aliases = new Map();
|
||||
for (const block of text.matchAll(IMPORT_BLOCK)) {
|
||||
for (const m of block[1].matchAll(ALIAS)) aliases.set(m[2], m[1]);
|
||||
}
|
||||
return aliases;
|
||||
}
|
||||
|
||||
/**
|
||||
* The hand-built services and repositories in one file's text, `allowed` left
|
||||
* out. Comments do not count; an import alias (`DaysService as Days`) and a
|
||||
* parenthesised class (`new (DaysService)(`) count as the class they name.
|
||||
*/
|
||||
export function countNewServices(text, allowed = new Set()) {
|
||||
const code = stripComments(text);
|
||||
const aliases = importAliases(code);
|
||||
let n = 0;
|
||||
for (const match of code.matchAll(ANY_NEW)) {
|
||||
const name = aliases.get(match[1]) ?? match[1];
|
||||
if (SERVICE_NAME.test(name) && !allowed.has(name)) n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
export const check = {
|
||||
name: 'test-new-service',
|
||||
script: 'lint:test-new-service',
|
||||
root: 'tests',
|
||||
baseline: 'scripts/test-new-service-baseline.json',
|
||||
unit: 'hand-built service(s) or repository(ies)',
|
||||
advice:
|
||||
'Take the subject from createTestModule (tests/helpers/test-module.ts) with overrides for its ' +
|
||||
'collaborators, or from a booted app with app.get(), instead of calling its constructor.',
|
||||
prepare: (serverDir) => {
|
||||
const classes = [];
|
||||
for (const root of CLASS_ROOTS) {
|
||||
const dir = join(serverDir, root);
|
||||
if (!existsSync(dir)) continue;
|
||||
for (const path of walk(dir)) classes.push(...parseClasses(readFileSync(path, 'utf8')));
|
||||
}
|
||||
return zeroArgClasses(classes);
|
||||
},
|
||||
include: (file) => /\.[cm]?[jt]s$/.test(file),
|
||||
count: (text, _file, allowed) => countNewServices(text, allowed),
|
||||
};
|
||||
|
||||
cliMain(check, import.meta.url);
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"tests/unit/nest/atlas.service.test.ts": 2193,
|
||||
"tests/unit/nest/budget.service.db.test.ts": 2220,
|
||||
"tests/unit/nest/doc-sync/doc-sync.service.test.ts": 2511,
|
||||
"tests/unit/nest/journey-domain.service.test.ts": 3876,
|
||||
"tests/unit/nest/maps.service.test.ts": 3681,
|
||||
"tests/unit/nest/places.service.test.ts": 2561,
|
||||
"tests/unit/nest/trips.service.test.ts": 2404
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"exempt": {
|
||||
"tests/helpers/legacy-fixture.ts": "Loads and fingerprints the legacy SQL fixtures, databases the retired positional runner built before any ORM schema existed.",
|
||||
"tests/helpers/legacy-upgrade-suite.ts": "Reads legacy databases before and after the legacy baseline adopts them; the bookkeeping tables it checks (schema_version, mikro_orm_migrations) are the subject.",
|
||||
"tests/integration/legacy-upgrade-v244.test.ts": "Compares a v4.3.3 database column by column before and after the upgrade, through pragma_table_info, on a copy no ORM is bound to.",
|
||||
"tests/unit/db/booked-night-reseat.test.ts": "Tests migration step 242, which reseats booked nights over the raw connection; the rows it seeds are the ones the step transforms before any repository runs.",
|
||||
"tests/unit/db/dialect/sql-functions.test.ts": "Pins the SQL text and the engine result of every dialect function in src/db/dialect/sql-functions.ts; the raw statement is what is under test.",
|
||||
"tests/unit/db/entity-schema-parity.test.ts": "Compares PRAGMA table_info, foreign_key_list and index_list of the migrated schema against the entity metadata.",
|
||||
"tests/unit/db/foreign-key-indexes.test.ts": "Reads PRAGMA foreign_key_list, index_list and index_info and EXPLAIN QUERY PLAN to prove every foreign key is indexed.",
|
||||
"tests/unit/db/migrate-encryption-parity.test.ts": "Seeds and reads a bare database for scripts/migrate-encryption.ts, which runs on the raw handle without the ORM.",
|
||||
"tests/unit/db/nul-safe-sqlite-platform.test.ts": "Pins how the SQLite driver binds and returns the literals the platform has to escape (NUL, NaN, infinities).",
|
||||
"tests/unit/db/place-regions-follow-place.test.ts": "Pins the place_regions trigger the migrations install, by raw UPDATEs on places and on databases built by the migrations alone.",
|
||||
"tests/unit/db/pre-migrate-snapshot.test.ts": "Inspects the VACUUM INTO copy written before the migrator runs, a file no ORM is bound to.",
|
||||
"tests/unit/db/restore-migrates-forward.test.ts": "Probes a restored database file before any ORM boots on it.",
|
||||
"tests/unit/db/test-orm.test.ts": "Proves the test ORM shares the raw handle it was given; the raw statements are the subject."
|
||||
},
|
||||
"counts": {
|
||||
"tests/helpers/db-mock.ts": 4,
|
||||
"tests/helpers/factories.ts": 62,
|
||||
"tests/helpers/test-db.ts": 5,
|
||||
"tests/helpers/tours-repos.ts": 1,
|
||||
"tests/integration/plugins/plugin-runtime.test.ts": 67,
|
||||
"tests/unit/plugins/host-rpc.test.ts": 38
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:test-sql: raw better-sqlite3 statements in the server tests may only shrink.
|
||||
*
|
||||
* The suite used to seed and read its database through `.prepare()` on the
|
||||
* synchronous better-sqlite3 handle: thousands of hand-written SQLite
|
||||
* statements that no other driver can serve, which welds every test to one
|
||||
* engine and bypasses the repositories the app goes through. The factories
|
||||
* and readers in tests/helpers/factories/ do the same work through MikroORM
|
||||
* (see the README there); this check makes sure the old way only recedes.
|
||||
*
|
||||
* Every `.prepare(` under tests/ is counted per file, mentions in comments
|
||||
* included. A file may hold at most its entry in the `counts` of
|
||||
* scripts/test-sql-baseline.json, and a file without an entry none at all.
|
||||
* An entry above what its file holds now, or for a file that is gone, fails
|
||||
* too until --update lowers it, so a converted file cannot grow back unseen.
|
||||
*
|
||||
* Two ways out, both explicit and reviewed:
|
||||
* - a file whose subject is raw SQL itself (migrations, the legacy
|
||||
* baseline, the dialect functions, PRAGMA introspection) is listed under
|
||||
* `exempt` with the reason; it is not counted, and an exemption for a
|
||||
* file that is gone fails;
|
||||
* - a single statement that has to stay raw carries a comment with
|
||||
* `test-sql-allow:` and a reason, on its own line or the line above
|
||||
* (when Prettier has broken the statement below it up, the marker
|
||||
* covers the first call in that statement). A marker with no reason
|
||||
* does not count.
|
||||
*
|
||||
* npm run lint:test-sql check against the baseline (CI)
|
||||
* npm run lint:test-sql -- --update lower the counts to what the files hold now;
|
||||
* it never raises an entry, never adds one,
|
||||
* and never touches the exemptions
|
||||
*
|
||||
* --dir=<path> points the check at another server root (the unit tests use it).
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/** The tree the check walks, relative to the server root. */
|
||||
export const ROOT = 'tests';
|
||||
|
||||
/** The baseline, relative to the server root. */
|
||||
export const BASELINE = 'scripts/test-sql-baseline.json';
|
||||
|
||||
const SOURCE = /\.(?:[cm]?[jt]s)$/;
|
||||
const PREPARE = /\.prepare\(/g;
|
||||
const ALLOW = /test-sql-allow:\s*\S/;
|
||||
|
||||
const HAS_PREPARE = /\.prepare\(/;
|
||||
|
||||
/** How many lines below its marker a statement Prettier has broken up may reach its call. */
|
||||
const REACH = 8;
|
||||
|
||||
/**
|
||||
* What the allow markers cover. A marker excuses every call on its own line
|
||||
* and on the line right below it. When that line holds no call, because
|
||||
* Prettier broke the statement up (`const rows = (` above `db.prepare(`, `db`
|
||||
* above `.prepare(`, a `for` head above its body), it excuses the first call
|
||||
* further down in that same statement: up to the line that ends it with `;`,
|
||||
* never past a blank line, at most REACH lines below the marker.
|
||||
*/
|
||||
function allowances(lines) {
|
||||
const wholeLines = new Set();
|
||||
const firstCallOnly = new Set();
|
||||
lines.forEach((line, i) => {
|
||||
if (!ALLOW.test(line)) return;
|
||||
wholeLines.add(i);
|
||||
wholeLines.add(i + 1);
|
||||
if (HAS_PREPARE.test(lines[i + 1] ?? '')) return;
|
||||
for (let j = i + 1; j < lines.length && j <= i + REACH; j++) {
|
||||
if (lines[j].trim() === '') return;
|
||||
if (j > i + 1 && HAS_PREPARE.test(lines[j])) {
|
||||
firstCallOnly.add(j);
|
||||
return;
|
||||
}
|
||||
if (lines[j].trimEnd().endsWith(';')) return;
|
||||
}
|
||||
});
|
||||
return { wholeLines, firstCallOnly };
|
||||
}
|
||||
|
||||
/**
|
||||
* The raw statements in one file's text: every `.prepare(` except those an
|
||||
* allow marker with a reason covers (see allowances).
|
||||
*/
|
||||
export function countPrepares(text) {
|
||||
const lines = text.replace(/\r\n?/g, '\n').split('\n');
|
||||
const { wholeLines, firstCallOnly } = allowances(lines);
|
||||
let total = 0;
|
||||
lines.forEach((line, i) => {
|
||||
const hits = line.match(PREPARE)?.length ?? 0;
|
||||
if (hits === 0 || wholeLines.has(i)) return;
|
||||
total += firstCallOnly.has(i) ? hits - 1 : hits;
|
||||
});
|
||||
return total;
|
||||
}
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === 'node_modules') continue;
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path, files);
|
||||
else if (SOURCE.test(name)) files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** Raw statement counts keyed by the server-relative POSIX path, files without any left out. */
|
||||
export function scan(serverDir) {
|
||||
const dir = join(serverDir, ROOT);
|
||||
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
|
||||
throw new Error(`${ROOT}/ does not exist under ${serverDir}: the check would pass without looking at anything`);
|
||||
}
|
||||
const counts = {};
|
||||
for (const path of walk(dir)) {
|
||||
const n = countPrepares(readFileSync(path, 'utf8'));
|
||||
if (n > 0) counts[relative(serverDir, path).split('\\').join('/')] = n;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/**
|
||||
* The baseline as committed. Missing, unreadable or malformed stops the run:
|
||||
* read as empty, every file would fail with no hint at the cause, and
|
||||
* --update would replace it with an empty one.
|
||||
*/
|
||||
export function readBaseline(path) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||||
} catch (err) {
|
||||
throw new Error(`${BASELINE} cannot be read: ${err.message}`);
|
||||
}
|
||||
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
||||
if (!isObject(parsed) || !isObject(parsed.exempt) || !isObject(parsed.counts)) {
|
||||
throw new Error(`${BASELINE} must be an object with an "exempt" and a "counts" object`);
|
||||
}
|
||||
for (const [file, reason] of Object.entries(parsed.exempt)) {
|
||||
if (typeof reason !== 'string' || reason.trim() === '') {
|
||||
throw new Error(`${BASELINE}: the exemption for ${file} needs a reason`);
|
||||
}
|
||||
if (file in parsed.counts) {
|
||||
throw new Error(`${BASELINE}: ${file} is both exempt and counted`);
|
||||
}
|
||||
}
|
||||
for (const [file, n] of Object.entries(parsed.counts)) {
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(`${BASELINE}: ${file} holds ${JSON.stringify(n)}, expected a whole number above 0`);
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** The counts lowered to what the files hold now. Never raises an entry, never adds one. */
|
||||
export function lowerCounts(baseline, counts) {
|
||||
const lowered = {};
|
||||
for (const [file, allowed] of Object.entries(baseline.counts)) {
|
||||
const now = counts[file] ?? 0;
|
||||
if (now > 0) lowered[file] = Math.min(allowed, now);
|
||||
}
|
||||
return Object.fromEntries(Object.entries(lowered).sort(([a], [b]) => a.localeCompare(b)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Files over their allowance; count entries above what their file holds now
|
||||
* (exactly the ones lowerCounts would lower or drop); exemptions for files
|
||||
* that are gone.
|
||||
*/
|
||||
export function compare(baseline, counts, serverDir) {
|
||||
const exempt = baseline.exempt;
|
||||
const grown = Object.entries(counts).filter(([file, n]) => !(file in exempt) && n > (baseline.counts[file] ?? 0));
|
||||
const lowered = lowerCounts(baseline, counts);
|
||||
const stale = Object.entries(baseline.counts).filter(([file, n]) => lowered[file] !== n);
|
||||
const goneExempt = Object.keys(exempt).filter((file) => !existsSync(join(serverDir, file)));
|
||||
return { grown, stale, goneExempt };
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
const dirArg = argv.find((a) => a.startsWith('--dir='));
|
||||
const serverDir = dirArg ? resolve(dirArg.slice('--dir='.length)) : fileURLToPath(new URL('..', import.meta.url));
|
||||
const baselinePath = join(serverDir, BASELINE);
|
||||
const update = argv.includes('--update');
|
||||
|
||||
const counts = scan(serverDir);
|
||||
const baseline = readBaseline(baselinePath);
|
||||
if (update) {
|
||||
baseline.counts = lowerCounts(baseline, counts);
|
||||
writeFileSync(baselinePath, JSON.stringify(baseline, null, 2) + '\n');
|
||||
}
|
||||
|
||||
const { grown, stale, goneExempt } = compare(baseline, counts, serverDir);
|
||||
for (const [file, n] of grown) {
|
||||
const entry = baseline.counts[file];
|
||||
console.error(
|
||||
`FAIL ${file}: ${n} raw statement(s), ` +
|
||||
(entry ? `its baseline is ${entry}. ` : 'a file without a baseline entry may hold none. ') +
|
||||
'Seed and read through tests/helpers/factories/ instead (see the README there).',
|
||||
);
|
||||
}
|
||||
for (const [file, entry] of stale) {
|
||||
console.error(
|
||||
`FAIL ${file} is held at ${entry} in ${BASELINE}, ` +
|
||||
(file in counts ? `but it has ${counts[file]} now.` : 'but it has none left (or the file is gone).'),
|
||||
);
|
||||
}
|
||||
for (const file of goneExempt) {
|
||||
console.error(`FAIL ${file} is exempt in ${BASELINE}, but the file is gone: drop the exemption.`);
|
||||
}
|
||||
if (stale.length) {
|
||||
console.error(
|
||||
'Run npm run lint:test-sql -- --update to lower the baseline with the change that made it smaller: ' +
|
||||
'an entry above the file lets it grow back unseen.',
|
||||
);
|
||||
}
|
||||
const total = Object.entries(counts)
|
||||
.filter(([file]) => !(file in baseline.exempt))
|
||||
.reduce((sum, [, n]) => sum + n, 0);
|
||||
console.log(
|
||||
`test-sql: ${total} raw statement(s) in ${Object.keys(baseline.counts).length} baselined file(s), ` +
|
||||
`${Object.keys(baseline.exempt).length} file(s) exempt`,
|
||||
);
|
||||
return grown.length || stale.length || goneExempt.length ? 1 : 0;
|
||||
}
|
||||
|
||||
// Compared by real path, so the check still runs when the script is started through a symlink.
|
||||
const isCli =
|
||||
Boolean(process.argv[1]) &&
|
||||
existsSync(process.argv[1]) &&
|
||||
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
try {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
} catch (err) {
|
||||
console.error(`FAIL ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"src/db/repositories/DemoRepository.ts#DemoRepository.restoreInstanceApiKeys": 2,
|
||||
"src/nest/admin/admin.controller.ts#AdminController.updateAddon": 2,
|
||||
"src/nest/atlas/atlas.service.ts#AtlasService.cacheRegionsInBackground": 2,
|
||||
"src/nest/atlas/atlas.service.ts#AtlasService.repairStaleRegionCache": 2,
|
||||
"src/nest/atlas/place-regions-repair.job.ts#PlaceRegionsRepairJob.runOnce": 2,
|
||||
"src/nest/auth/passkey.service.ts#PasskeyService.passkeyLoginOptions": 2,
|
||||
"src/nest/auth/passkey.service.ts#PasskeyService.passkeyLoginVerify": 2,
|
||||
"src/nest/auth/passkey.service.ts#PasskeyService.passkeyRegisterOptions": 2,
|
||||
"src/nest/auth/passkey.service.ts#PasskeyService.passkeyRegisterVerify": 2,
|
||||
"src/nest/doc-sync/doc-sync-config.service.ts#DocSyncConfigService.upsertConnection": 3,
|
||||
"src/nest/doc-sync/doc-sync.controller.ts#DocSyncController.createLink": 4,
|
||||
"src/nest/doc-sync/doc-sync.controller.ts#DocSyncController.deleteConnection": 2,
|
||||
"src/nest/doc-sync/doc-sync.controller.ts#DocSyncController.deleteLink": 2,
|
||||
"src/nest/doc-sync/doc-sync.controller.ts#DocSyncController.listConnections": 2,
|
||||
"src/nest/doc-sync/doc-sync.controller.ts#DocSyncController.syncNow": 2,
|
||||
"src/nest/doc-sync/doc-sync.controller.ts#DocSyncController.testConnection": 2,
|
||||
"src/nest/doc-sync/doc-sync.controller.ts#DocSyncController.upsertConnection": 2,
|
||||
"src/nest/doc-sync/doc-sync.job.ts#DocSyncJob.tick": 3,
|
||||
"src/nest/doc-sync/doc-sync.mcp.ts#DocSyncMcp.syncNow": 4,
|
||||
"src/nest/doc-sync/doc-sync.service.ts#DocSyncService.applyAction": 2,
|
||||
"src/nest/doc-sync/doc-sync.service.ts#DocSyncService.pull": 3,
|
||||
"src/nest/doc-sync/doc-sync.service.ts#DocSyncService.push": 2,
|
||||
"src/nest/doc-sync/doc-sync.service.ts#DocSyncService.renameRemoteTo": 2,
|
||||
"src/nest/doc-sync/doc-sync.service.ts#DocSyncService.resolveConflict": 3,
|
||||
"src/nest/doc-sync/doc-sync.service.ts#DocSyncService.runLink": 4,
|
||||
"src/nest/doc-sync/doc-sync.service.ts#DocSyncService.syncLink": 2,
|
||||
"src/nest/integrations/airtrail-link.service.ts#AirtrailLinkService.pushReservationToAirtrail": 2,
|
||||
"src/nest/integrations/airtrail-sync.service.ts#AirtrailSyncService.runAirtrailSync": 2,
|
||||
"src/nest/integrations/airtrail-sync.service.ts#AirtrailSyncService.syncOwner": 8,
|
||||
"src/nest/integrations/airtrail.service.ts#AirtrailService.saveSettings": 2,
|
||||
"src/nest/integrations/dawarich-sync.service.ts#DawarichSyncService.runSync": 2,
|
||||
"src/nest/integrations/dawarich-sync.service.ts#DawarichSyncService.syncTripWindow": 3,
|
||||
"src/nest/integrations/dawarich-sync.service.ts#DawarichSyncService.syncUserOnce": 3,
|
||||
"src/nest/journey/journey.controller.ts#JourneyController.uploadEntryPhotos": 4,
|
||||
"src/nest/memories/photo-resolver.service.ts#PhotoResolverService.streamCachedThumbnail": 3,
|
||||
"src/nest/memories/photo-resolver.service.ts#PhotoResolverService.streamPhoto": 2,
|
||||
"src/nest/memories/synology.service.ts#SynologyService._fetchAllSynologyAlbums": 2,
|
||||
"src/nest/memories/synology.service.ts#SynologyService._getSynologySession": 2,
|
||||
"src/nest/memories/synology.service.ts#SynologyService._requestSynologyApi": 3,
|
||||
"src/nest/memories/synology.service.ts#SynologyService.collectSynologyAlbumSelection": 2,
|
||||
"src/nest/memories/synology.service.ts#SynologyService.getSynologyAlbumPhotos": 2,
|
||||
"src/nest/memories/synology.service.ts#SynologyService.listSynologyAlbums": 3,
|
||||
"src/nest/memories/synology.service.ts#SynologyService.testSynologyConnection": 2,
|
||||
"src/nest/memories/synology.service.ts#SynologyService.updateSynologySettings": 2,
|
||||
"src/nest/memories/trek-photo-cache.job.ts#TrekPhotoCacheJob.onApplicationBootstrap": 2,
|
||||
"src/nest/memories/trek-photo-cache.service.ts#TrekPhotoCacheService.sweepExpired": 2,
|
||||
"src/nest/memories/unified-memories.service.ts#UnifiedMemoriesService.addTripPhotos": 4,
|
||||
"src/nest/memories/unified-memories.service.ts#UnifiedMemoriesService.syncImmichAlbum": 2,
|
||||
"src/nest/memories/unified-memories.service.ts#UnifiedMemoriesService.syncSynologyAlbum": 3,
|
||||
"src/nest/notifications/push/push.controller.ts#PushController.subscribe": 2,
|
||||
"src/nest/notifications/reminder-jobs.service.ts#ReminderJobsService.onApplicationBootstrap": 2,
|
||||
"src/nest/notifications/reminder-jobs.service.ts#ReminderJobsService.todoTick": 4,
|
||||
"src/nest/notifications/reminder-jobs.service.ts#ReminderJobsService.tripTick": 4,
|
||||
"src/nest/notifications/transports/web-push.service.ts#WebPushService.deliver": 3,
|
||||
"src/nest/notifications/transports/web-push.service.ts#WebPushService.deliverTo": 2,
|
||||
"src/nest/notifications/transports/web-push.service.ts#WebPushService.settle": 2,
|
||||
"src/nest/oidc/oidc.controller.ts#OidcController.callback": 2,
|
||||
"src/nest/place-enrichment/place-enrichment.service.ts#PlaceEnrichmentService.collectPhotos": 5,
|
||||
"src/nest/place-enrichment/place-enrichment.service.ts#PlaceEnrichmentService.enrich": 5,
|
||||
"src/nest/place-enrichment/place-enrichment.service.ts#PlaceEnrichmentService.readCache": 2,
|
||||
"src/nest/place-enrichment/place-enrichment.service.ts#PlaceEnrichmentService.storeCandidate": 2,
|
||||
"src/nest/place-photos/place-photo-cache.job.ts#PlacePhotoCacheJob.onApplicationBootstrap": 2,
|
||||
"src/nest/place-photos/place-photo-cache.service.ts#PlacePhotoCacheService.sweepOrphans": 2,
|
||||
"src/nest/places/places.mcp.ts#PlacesMcp.bulkDeletePlaces": 3,
|
||||
"src/nest/places/places.mcp.ts#PlacesMcp.createAndAssignPlace": 2,
|
||||
"src/nest/places/places.mcp.ts#PlacesMcp.deletePlace": 2,
|
||||
"src/nest/places/places.rpc.ts#PlacesRpc.create": 2,
|
||||
"src/nest/places/places.rpc.ts#PlacesRpc.delete": 2,
|
||||
"src/nest/places/places.rpc.ts#PlacesRpc.update": 2,
|
||||
"src/nest/places/places.service.ts#PlacesService.backfillMissingAddresses": 2,
|
||||
"src/nest/places/places.service.ts#PlacesService.enrichImportedList": 2,
|
||||
"src/nest/places/places.service.ts#PlacesService.enrichOne": 3,
|
||||
"src/nest/places/places.service.ts#PlacesService.importGoogleDirections": 2,
|
||||
"src/nest/places/places.service.ts#PlacesService.importGoogleList": 2,
|
||||
"src/nest/places/places.service.ts#PlacesService.importNaverList": 2,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.activate": 2,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.deactivateForDisabledAddon": 2,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.deactivateWithDependents": 2,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.link": 3,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.onApplicationBootstrap": 7,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.reload": 2,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.runDrainOnce": 4,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.setOperatorEgressHosts": 2,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.sideload": 2,
|
||||
"src/nest/plugins/plugin-runtime.service.ts#PluginRuntimeService.update": 3,
|
||||
"src/nest/plugins/plugins.controller.ts#PluginsController.install": 2,
|
||||
"src/nest/plugins/plugins.controller.ts#PluginsController.update": 2,
|
||||
"src/nest/plugins/plugins.controller.ts#PluginsController.updateConfig": 3,
|
||||
"src/nest/vacay/vacay.service.ts#VacayService.updatePlan": 2
|
||||
}
|
||||
@@ -0,0 +1,521 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:tx: a method that writes more than once must do it inside one transaction.
|
||||
*
|
||||
* A crash or a thrown error between two writes leaves half a change behind (a
|
||||
* journey without its owner row, a reservation whose budget line was not
|
||||
* updated). The rule in server/CLAUDE.md is that a multi-statement write runs
|
||||
* in `await this.uow.transactional(...)`; this script finds the methods that
|
||||
* do not, as far as a static read of the source can.
|
||||
*
|
||||
* HOW IT COUNTS
|
||||
* Every class under src/ is read with the TypeScript parser. A repository
|
||||
* method (src/db/repositories/) is a write when it builds an INSERT, UPDATE
|
||||
* or DELETE (insertInto/updateTable/deleteFrom, nativeInsert/nativeUpdate/
|
||||
* nativeDelete, insert/insertMany/upsert/upsertMany, a query builder's
|
||||
* update/delete, flush, or a raw SQL string that starts with a write verb),
|
||||
* directly or through another method of its own class.
|
||||
*
|
||||
* A method's "write units" are then counted over its body:
|
||||
* - a call to a write, on a constructor-injected field (`this.trips.x()`)
|
||||
* or on its own class (`this.x()`), is one unit;
|
||||
* - a `.transactional(...)` call that holds any write is one unit, however
|
||||
* many writes it holds;
|
||||
* - a call to a method of another class that is itself reported counts as
|
||||
* one unit here (the fault is reported once, where it lives);
|
||||
* - a write inside a loop, or inside a callback handed to forEach/map/
|
||||
* reduce and friends, counts twice (it can run any number of times);
|
||||
* - of two branches (if/else, a ternary, the cases of a switch, an `if`
|
||||
* that returns or throws against the rest of its block) only the larger
|
||||
* one counts, since only one of them runs.
|
||||
* A method tagged `@txStandalone` in its JSDoc (an audit row, a notification,
|
||||
* a failure record, an idempotent lazy provision, a non-fatal derived refresh)
|
||||
* adds no unit to its callers; the tag says why in its text. A method tagged
|
||||
* `@txIndependent` (writes that are each complete on their own on purpose,
|
||||
* such as a retention sweep in passes or a sync with network I/O between its
|
||||
* writes) is not reported itself.
|
||||
* A method holding two or more units is reported, unless every call to it
|
||||
* that the script can resolve sits inside a `.transactional(...)` callback or
|
||||
* in a method that is itself only ever called that way (a helper that runs
|
||||
* inside its callers' transaction).
|
||||
*
|
||||
* WHAT IT CANNOT SEE
|
||||
* A local helper (`const f = async () => ...` inside the method) is counted
|
||||
* where it is called, not where it is declared.
|
||||
* Calls through anything but `this.<field>.<method>()`, `this.<method>()` and
|
||||
* such a local helper (a free function, a value passed in as an argument, a
|
||||
* dynamic dispatch) are not followed, and a write after network I/O that cannot share a
|
||||
* transaction with it is still reported: those entries stay in the baseline.
|
||||
*
|
||||
* THE RATCHET
|
||||
* scripts/tx-writes-baseline.json holds today's reported methods with their
|
||||
* unit count. A method not in it fails, and so does one past its count. An
|
||||
* entry above what its method holds now, or for a method that is no longer
|
||||
* reported, fails too until --update lowers or drops it, so a fixed method
|
||||
* cannot quietly regress.
|
||||
*
|
||||
* npm run lint:tx check against the baseline (CI)
|
||||
* npm run lint:tx -- --update lower the baseline to what the code holds now;
|
||||
* it never raises or adds an entry
|
||||
* npm run lint:tx -- --list print every reported method with its count
|
||||
* npm run lint:tx -- --explain the same, with the line of each call that counted
|
||||
*
|
||||
* --dir=<path> points the check at another server root (the unit tests use it).
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const require_ = createRequire(import.meta.url);
|
||||
const ts = require_('typescript');
|
||||
|
||||
const SOURCE = /\.ts$/;
|
||||
const SKIP = /\.(?:test|spec|d)\.ts$/;
|
||||
const REPOSITORY_DIR = 'src/db/repositories/';
|
||||
|
||||
/** Calls that issue a write wherever a repository makes them. */
|
||||
const WRITE_CALLS = new Set([
|
||||
'insertInto',
|
||||
'updateTable',
|
||||
'deleteFrom',
|
||||
'replaceInto',
|
||||
'nativeInsert',
|
||||
'nativeUpdate',
|
||||
'nativeDelete',
|
||||
'insert',
|
||||
'insertMany',
|
||||
'upsert',
|
||||
'upsertMany',
|
||||
'update',
|
||||
'delete',
|
||||
'truncate',
|
||||
'flush',
|
||||
'persistAndFlush',
|
||||
'removeAndFlush',
|
||||
]);
|
||||
|
||||
/** The base-class writes a service may call on a repository field directly. */
|
||||
const BASE_WRITES = new Set([
|
||||
'nativeInsert',
|
||||
'nativeUpdate',
|
||||
'nativeDelete',
|
||||
'insert',
|
||||
'insertMany',
|
||||
'upsert',
|
||||
'upsertMany',
|
||||
]);
|
||||
|
||||
/**
|
||||
* A method whose JSDoc carries this tag writes something that stands on its own,
|
||||
* whatever its caller does around it: an audit row, a notification, a failure
|
||||
* record, an idempotent lazy provision, a non-fatal derived refresh. Its calls
|
||||
* add no unit to the caller. The method's own body is still counted.
|
||||
*/
|
||||
export const STANDALONE_TAG = 'txStandalone';
|
||||
|
||||
/**
|
||||
* A method whose JSDoc carries this tag writes in steps that are each complete
|
||||
* on their own on purpose: a retention sweep that deletes in passes, a sync
|
||||
* whose network round trips sit between its writes, one transaction per item
|
||||
* of a batch. It is not reported; the tag's text says why.
|
||||
*/
|
||||
export const INDEPENDENT_TAG = 'txIndependent';
|
||||
|
||||
const RAW_WRITE = /^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i;
|
||||
|
||||
/** Array methods that run their callback once per element. */
|
||||
const LOOP_CALLBACKS = new Set(['forEach', 'map', 'flatMap', 'filter', 'reduce', 'some', 'every', 'find', 'findIndex']);
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === 'node_modules') continue;
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path, files);
|
||||
else if (SOURCE.test(name) && !SKIP.test(name)) files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function nameOf(node) {
|
||||
return node && node.name && (ts.isIdentifier(node.name) || ts.isPrivateIdentifier(node.name)) ? node.name.text : null;
|
||||
}
|
||||
|
||||
/** The class a type annotation names: `FooRepository`, `Foo | undefined`, `Readonly<Foo>` all give `Foo...`. */
|
||||
function typeName(type) {
|
||||
if (!type) return null;
|
||||
if (ts.isTypeReferenceNode(type)) {
|
||||
const n = type.typeName;
|
||||
return ts.isIdentifier(n) ? n.text : n.right.text;
|
||||
}
|
||||
if (ts.isUnionTypeNode(type)) {
|
||||
for (const t of type.types) {
|
||||
const found = typeName(t);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every class in the tree, with its methods and the classes its constructor injects. */
|
||||
export function collect(serverDir) {
|
||||
const srcDir = join(serverDir, 'src');
|
||||
if (!existsSync(srcDir) || !statSync(srcDir).isDirectory()) {
|
||||
throw new Error(`src/ does not exist under ${serverDir}: the check would pass without looking at anything`);
|
||||
}
|
||||
const classes = new Map();
|
||||
for (const path of walk(srcDir)) {
|
||||
const file = relative(serverDir, path).split('\\').join('/');
|
||||
const sf = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true);
|
||||
const visit = (node) => {
|
||||
if (ts.isClassDeclaration(node) && node.name) {
|
||||
const cls = {
|
||||
name: node.name.text,
|
||||
file,
|
||||
repository: file.startsWith(REPOSITORY_DIR),
|
||||
fields: new Map(),
|
||||
methods: new Map(),
|
||||
standalone: new Set(),
|
||||
independent: new Set(),
|
||||
};
|
||||
for (const member of node.members) {
|
||||
if (ts.isConstructorDeclaration(member)) {
|
||||
for (const p of member.parameters) {
|
||||
const field = ts.isIdentifier(p.name) ? p.name.text : null;
|
||||
const type = typeName(p.type);
|
||||
if (field && type) cls.fields.set(field, type);
|
||||
}
|
||||
} else if (ts.isPropertyDeclaration(member) && member.initializer && ts.isArrowFunction(member.initializer)) {
|
||||
const method = nameOf(member);
|
||||
if (method) cls.methods.set(method, member.initializer);
|
||||
} else if (ts.isPropertyDeclaration(member)) {
|
||||
const field = nameOf(member);
|
||||
const type = typeName(member.type);
|
||||
if (field && type) cls.fields.set(field, type);
|
||||
} else if (ts.isMethodDeclaration(member) && member.body) {
|
||||
const method = nameOf(member);
|
||||
if (method) cls.methods.set(method, member);
|
||||
const tags = method ? ts.getJSDocTags(member).map((tag) => tag.tagName.text) : [];
|
||||
if (tags.includes(STANDALONE_TAG)) cls.standalone.add(method);
|
||||
if (tags.includes(INDEPENDENT_TAG)) cls.independent.add(method);
|
||||
}
|
||||
}
|
||||
// Two classes of one name: keep the first; the second is reached by no field type.
|
||||
if (!classes.has(cls.name)) classes.set(cls.name, cls);
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(sf);
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
|
||||
/** `this.x` → 'x', `this.#x` → '#x', otherwise null. */
|
||||
function thisMember(expr) {
|
||||
if (ts.isPropertyAccessExpression(expr) && expr.expression.kind === ts.SyntaxKind.ThisKeyword) return expr.name.text;
|
||||
return null;
|
||||
}
|
||||
|
||||
function exits(stmt) {
|
||||
if (!stmt) return false;
|
||||
if (ts.isReturnStatement(stmt) || ts.isThrowStatement(stmt)) return true;
|
||||
if (ts.isBlock(stmt)) return stmt.statements.length > 0 && exits(stmt.statements[stmt.statements.length - 1]);
|
||||
if (ts.isIfStatement(stmt)) return exits(stmt.thenStatement) && exits(stmt.elseStatement);
|
||||
return false;
|
||||
}
|
||||
|
||||
export function analyse(classes) {
|
||||
const units = new Map(); // "Class.method" → number
|
||||
const inProgress = new Set();
|
||||
const callSites = new Map(); // "Class.method" → [{ caller, covered }]
|
||||
const reading = []; // the "Class.method" whose body is being read
|
||||
const sites = new Map(); // "Class.method" → the calls that added a unit, for --explain
|
||||
const frames = [];
|
||||
const locals = []; // per method read: local `const f = async () => ...` helpers, counted where they are called
|
||||
const running = new Set();
|
||||
|
||||
/** Records the call that added a unit to the method being read, and returns that unit. */
|
||||
function unit(node, label) {
|
||||
const sf = node.getSourceFile();
|
||||
const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
|
||||
frames[frames.length - 1]?.push(`${line}: ${label}`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** What `callee` is: { cls, method } on a known class, a base write, or null. */
|
||||
function resolve(cls, callee) {
|
||||
if (!ts.isPropertyAccessExpression(callee)) return null;
|
||||
const method = callee.name.text;
|
||||
const own = thisMember(callee);
|
||||
if (own !== null) return cls.methods.has(own) ? { cls, method: own } : null;
|
||||
const field = thisMember(callee.expression);
|
||||
if (field === null) return null;
|
||||
const target = classes.get(cls.fields.get(field));
|
||||
if (!target) return null;
|
||||
if (target.methods.has(method)) return { cls: target, method };
|
||||
if (target.repository && BASE_WRITES.has(method)) return { write: true };
|
||||
return null;
|
||||
}
|
||||
|
||||
function directWrite(cls, call) {
|
||||
if (!cls.repository) return false;
|
||||
const callee = call.expression;
|
||||
if (ts.isPropertyAccessExpression(callee) && WRITE_CALLS.has(callee.name.text)) {
|
||||
// `this.update(...)` on a repository's own method is resolved as a call instead.
|
||||
if (callee.expression.kind === ts.SyntaxKind.ThisKeyword && cls.methods.has(callee.name.text)) return false;
|
||||
return true;
|
||||
}
|
||||
const first = call.arguments[0];
|
||||
return Boolean(
|
||||
first && (ts.isStringLiteral(first) || ts.isNoSubstitutionTemplateLiteral(first)) && RAW_WRITE.test(first.text),
|
||||
);
|
||||
}
|
||||
|
||||
/** Write units of `node`, read inside `cls`. `covered` is true inside a transactional callback. */
|
||||
function count(cls, node, covered) {
|
||||
if (!node) return 0;
|
||||
if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) return 0;
|
||||
if (ts.isBlock(node) || ts.isSourceFile(node) || ts.isModuleBlock(node))
|
||||
return statements(cls, node.statements, 0, covered);
|
||||
if (ts.isIfStatement(node)) {
|
||||
return (
|
||||
count(cls, node.expression, covered) +
|
||||
Math.max(count(cls, node.thenStatement, covered), count(cls, node.elseStatement, covered))
|
||||
);
|
||||
}
|
||||
if (ts.isConditionalExpression(node)) {
|
||||
return (
|
||||
count(cls, node.condition, covered) +
|
||||
Math.max(count(cls, node.whenTrue, covered), count(cls, node.whenFalse, covered))
|
||||
);
|
||||
}
|
||||
if (ts.isSwitchStatement(node)) {
|
||||
let max = 0;
|
||||
for (const clause of node.caseBlock.clauses) max = Math.max(max, statements(cls, clause.statements, 0, covered));
|
||||
return count(cls, node.expression, covered) + max;
|
||||
}
|
||||
if (
|
||||
ts.isForStatement(node) ||
|
||||
ts.isForOfStatement(node) ||
|
||||
ts.isForInStatement(node) ||
|
||||
ts.isWhileStatement(node) ||
|
||||
ts.isDoStatement(node)
|
||||
) {
|
||||
let head = 0;
|
||||
if (ts.isForStatement(node)) head = count(cls, node.initializer, covered);
|
||||
else if (!ts.isDoStatement(node) && !ts.isWhileStatement(node)) head = count(cls, node.expression, covered);
|
||||
return head + 2 * count(cls, node.statement, covered);
|
||||
}
|
||||
if (ts.isCallExpression(node)) return call(cls, node, covered);
|
||||
if (
|
||||
ts.isVariableDeclaration(node) &&
|
||||
ts.isIdentifier(node.name) &&
|
||||
node.initializer &&
|
||||
(ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer))
|
||||
) {
|
||||
locals[locals.length - 1].set(node.name.text, node.initializer.body);
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
ts.forEachChild(node, (child) => {
|
||||
total += count(cls, child, covered);
|
||||
});
|
||||
return total;
|
||||
}
|
||||
|
||||
/** A block read statement by statement: an `if` that always leaves competes with the rest of the block. */
|
||||
function statements(cls, list, from, covered) {
|
||||
let total = 0;
|
||||
for (let i = from; i < list.length; i++) {
|
||||
const stmt = list[i];
|
||||
if (ts.isIfStatement(stmt) && !stmt.elseStatement && exits(stmt.thenStatement)) {
|
||||
const rest = statements(cls, list, i + 1, covered);
|
||||
return total + count(cls, stmt.expression, covered) + Math.max(count(cls, stmt.thenStatement, covered), rest);
|
||||
}
|
||||
total += count(cls, stmt, covered);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function call(cls, node, covered) {
|
||||
const callee = node.expression;
|
||||
const method = ts.isPropertyAccessExpression(callee) ? callee.name.text : null;
|
||||
const receiver = ts.isPropertyAccessExpression(callee)
|
||||
? count(cls, callee.expression, covered)
|
||||
: count(cls, callee, covered);
|
||||
if (method === 'transactional') {
|
||||
let inner = 0;
|
||||
frames.push([]); // what runs inside is one unit, not a list of its own
|
||||
for (const arg of node.arguments) inner += count(cls, arg, true);
|
||||
frames.pop();
|
||||
return receiver + (inner > 0 ? unit(node, 'transactional(...)') : 0);
|
||||
}
|
||||
let args = 0;
|
||||
for (const arg of node.arguments) args += count(cls, arg, covered);
|
||||
if (method && LOOP_CALLBACKS.has(method)) args *= 2;
|
||||
const local = ts.isIdentifier(callee) ? callee.text : null;
|
||||
const helper = local !== null ? locals[locals.length - 1].get(local) : undefined;
|
||||
if (helper && !running.has(helper)) {
|
||||
running.add(helper);
|
||||
const inner = count(cls, helper, covered);
|
||||
running.delete(helper);
|
||||
return receiver + args + inner;
|
||||
}
|
||||
const text = ts.isPropertyAccessExpression(callee) ? callee.getText().replace(/\s+/g, '') : method;
|
||||
if (directWrite(cls, node)) return receiver + args + unit(node, text);
|
||||
const target = resolve(cls, callee);
|
||||
if (!target) return receiver + args;
|
||||
if (target.write) return receiver + args + unit(node, text);
|
||||
if (target.cls.standalone.has(target.method)) return receiver + args;
|
||||
const key = `${target.cls.name}.${target.method}`;
|
||||
const list = callSites.get(key) ?? [];
|
||||
list.push({ caller: reading[reading.length - 1], covered });
|
||||
callSites.set(key, list);
|
||||
return receiver + args + (unitsOf(target.cls, target.method) > 0 ? unit(node, text) : 0);
|
||||
}
|
||||
|
||||
function unitsOf(cls, method) {
|
||||
const key = `${cls.name}.${method}`;
|
||||
if (units.has(key)) return units.get(key);
|
||||
if (inProgress.has(key)) return 0; // recursion: the outer frame counts the body once
|
||||
inProgress.add(key);
|
||||
const fn = cls.methods.get(method);
|
||||
frames.push([]);
|
||||
locals.push(new Map());
|
||||
reading.push(key);
|
||||
const n = count(cls, fn.body, false);
|
||||
reading.pop();
|
||||
locals.pop();
|
||||
sites.set(key, frames.pop());
|
||||
inProgress.delete(key);
|
||||
units.set(key, n);
|
||||
return n;
|
||||
}
|
||||
|
||||
for (const cls of classes.values()) for (const method of cls.methods.keys()) unitsOf(cls, method);
|
||||
|
||||
// Bound to a transaction: called at least once, and every call either sits in a
|
||||
// transactional callback or comes from a method that is bound itself. Grown from
|
||||
// nothing to a fixed point, so a cycle of methods calling each other binds none.
|
||||
const bound = new Set();
|
||||
for (let grew = true; grew;) {
|
||||
grew = false;
|
||||
for (const [key, list] of callSites) {
|
||||
if (bound.has(key) || list.length === 0) continue;
|
||||
if (list.every((site) => site.covered || bound.has(site.caller))) {
|
||||
bound.add(key);
|
||||
grew = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const reported = {};
|
||||
const explained = {};
|
||||
for (const cls of classes.values()) {
|
||||
for (const method of cls.methods.keys()) {
|
||||
const key = `${cls.name}.${method}`;
|
||||
const n = units.get(key);
|
||||
if (n < 2) continue;
|
||||
if (bound.has(key) || cls.independent.has(method)) continue;
|
||||
reported[`${cls.file}#${key}`] = n;
|
||||
explained[`${cls.file}#${key}`] = sites.get(key);
|
||||
}
|
||||
}
|
||||
return {
|
||||
found: Object.fromEntries(Object.entries(reported).sort(([a], [b]) => a.localeCompare(b))),
|
||||
sites: explained,
|
||||
};
|
||||
}
|
||||
|
||||
/** The baseline as committed. Missing or malformed stops the run instead of reading as empty. */
|
||||
export function readBaseline(path) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||||
} catch (err) {
|
||||
throw new Error(`scripts/tx-writes-baseline.json cannot be read: ${err.message}`);
|
||||
}
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error('scripts/tx-writes-baseline.json must be an object of methods to write counts');
|
||||
}
|
||||
for (const [key, n] of Object.entries(parsed)) {
|
||||
if (!Number.isInteger(n) || n < 2) {
|
||||
throw new Error(
|
||||
`scripts/tx-writes-baseline.json: ${key} holds ${JSON.stringify(n)}, expected an integer of at least 2`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** The baseline lowered to what the code holds now. Never raises an entry, never adds one. */
|
||||
export function lowerBaseline(baseline, found) {
|
||||
const lowered = {};
|
||||
for (const [key, allowed] of Object.entries(baseline)) {
|
||||
if (key in found) lowered[key] = Math.min(allowed, found[key]);
|
||||
}
|
||||
return Object.fromEntries(Object.entries(lowered).sort(([a], [b]) => a.localeCompare(b)));
|
||||
}
|
||||
|
||||
export function compare(baseline, found) {
|
||||
const grown = Object.entries(found).filter(([key, n]) => n > (baseline[key] ?? 1));
|
||||
const lowered = lowerBaseline(baseline, found);
|
||||
const stale = Object.entries(baseline).filter(([key, n]) => lowered[key] !== n);
|
||||
return { grown, stale };
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
const dirArg = argv.find((a) => a.startsWith('--dir='));
|
||||
const serverDir = dirArg ? resolve(dirArg.slice('--dir='.length)) : fileURLToPath(new URL('..', import.meta.url));
|
||||
const baselinePath = join(serverDir, 'scripts', 'tx-writes-baseline.json');
|
||||
|
||||
const { found, sites } = analyse(collect(serverDir));
|
||||
if (argv.includes('--list') || argv.includes('--explain')) {
|
||||
for (const [key, n] of Object.entries(found)) {
|
||||
console.log(`${n}\t${key}`);
|
||||
if (argv.includes('--explain')) for (const site of sites[key]) console.log(`\t\t${site}`);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
let baseline = readBaseline(baselinePath);
|
||||
if (argv.includes('--update')) {
|
||||
baseline = lowerBaseline(baseline, found);
|
||||
writeFileSync(baselinePath, JSON.stringify(baseline, null, 2) + '\n');
|
||||
}
|
||||
|
||||
const { grown, stale } = compare(baseline, found);
|
||||
for (const [key, n] of grown) {
|
||||
const entry = baseline[key];
|
||||
console.error(
|
||||
`FAIL ${key}: ${n} writes outside one transaction` +
|
||||
(entry ? `, its baseline is ${entry}. ` : '. ') +
|
||||
'Wrap the sequence in await this.uow.transactional(...) in the service.',
|
||||
);
|
||||
}
|
||||
for (const [key, entry] of stale) {
|
||||
console.error(
|
||||
`FAIL ${key} is held at ${entry} in scripts/tx-writes-baseline.json, ` +
|
||||
(key in found ? `but it has ${found[key]} now.` : 'but it is no longer reported.'),
|
||||
);
|
||||
}
|
||||
if (stale.length) {
|
||||
console.error('Run npm run lint:tx -- --update to lower the baseline with the change that fixed it.');
|
||||
}
|
||||
console.log(
|
||||
`tx: ${Object.keys(found).length} method(s) with writes outside one transaction, ${Object.keys(baseline).length} held at their baseline`,
|
||||
);
|
||||
return grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
|
||||
const isCli =
|
||||
Boolean(process.argv[1]) &&
|
||||
existsSync(process.argv[1]) &&
|
||||
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
try {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
} catch (err) {
|
||||
console.error(`FAIL ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,11 @@ export const ADDON_IDS = {
|
||||
LLM_PARSING: 'llm_parsing',
|
||||
COLLECTIONS: 'collections',
|
||||
ROADTRIP: 'roadtrip',
|
||||
TOURS: 'tours',
|
||||
AI_ASSISTANT: 'ai_assistant',
|
||||
} as const;
|
||||
|
||||
export type AddonId = typeof ADDON_IDS[keyof typeof ADDON_IDS];
|
||||
export type AddonId = (typeof ADDON_IDS)[keyof typeof ADDON_IDS];
|
||||
|
||||
/**
|
||||
* The addons that gate an MCP surface, which is what decides whether switching
|
||||
@@ -46,5 +48,6 @@ export const MCP_GATED_ADDON_IDS: readonly AddonId[] = [
|
||||
ADDON_IDS.JOURNEY,
|
||||
ADDON_IDS.PACKING,
|
||||
ADDON_IDS.ROADTRIP,
|
||||
ADDON_IDS.TOURS,
|
||||
ADDON_IDS.VACAY,
|
||||
];
|
||||
|
||||
@@ -8,9 +8,10 @@ the pre-init Express middleware.
|
||||
```
|
||||
env.schema.ts Zod catalog of the whole env surface; fail-fast at boot
|
||||
derive.ts pure (raw env) → typed namespace functions, exact per-site coercions
|
||||
env.ts readEnv() live accessor + validateEnvAtBoot()
|
||||
env.ts readEnv() live accessor + normalizeEnvAtBoot() + validateEnvAtBoot()
|
||||
app-url.ts getAppUrl()/getMcpSafeUrl() instance base-URL resolution
|
||||
boot-validate.ts side-effect import used by index.ts (validates before other modules load)
|
||||
data-paths.ts resolveDataPaths(): data/, uploads/, backups, tmp, logs, key files, DB file
|
||||
boot-validate.ts side-effect import used by index.ts (trims, then validates before other modules load)
|
||||
parsers.ts shared coercion helpers (boolTrueLoose, numberOr, csvList, …)
|
||||
```
|
||||
|
||||
@@ -31,6 +32,10 @@ tokens, `RuntimeEnvService`) and consumes the SAME derive functions.
|
||||
together wrong. It is empty without the switch, so a self-hoster never meets
|
||||
it. Put a rule there only if booting anyway would be a security or data
|
||||
problem — not to enforce a preference.
|
||||
The report prints each malformed value, because that is what makes a typo
|
||||
findable, except for the credentials in `SECRET_ENV_KEYS` (`env.ts`), which
|
||||
print as `***`. A new password, token, key or secret variable goes into that
|
||||
set; `validate.test.ts` fails on a credential-sounding name missing from it.
|
||||
3. **Parity is law — with one deliberate exception.** Every derived field pins
|
||||
the exact coercion of the call site(s) it replaced (`Number(x) || d`
|
||||
treating `"0"` as unset, per-site defaults for the same variable, …). Do not
|
||||
@@ -49,6 +54,34 @@ tokens, `RuntimeEnvService`) and consumes the SAME derive functions.
|
||||
rate limits, …) keep freeze-at-import timing, merely sourcing the value from
|
||||
`readEnv()` at module top. Request-time reads stay request-time.
|
||||
|
||||
## data-paths.ts: the one data layout
|
||||
|
||||
`resolveDataPaths()` is the only place the server anchors `data/` and
|
||||
`uploads/` (on `SERVER_ROOT`, the package directory, never on `process.cwd()`)
|
||||
and names what lives in them: backups, the scratch dir, the logs, the JWT
|
||||
secret and encryption key files, and the database file (TREK_DB_FILE when set,
|
||||
else `data/travel.db`). Never derive one of these paths from `__dirname` in a
|
||||
new file: a moved file would quietly move the data.
|
||||
|
||||
Two ways in, by where the code runs:
|
||||
|
||||
- **Nest providers inject `DataPathsService`** (`src/nest/app-config/`), which
|
||||
resolves the same layout once per built app: `AdminService` (the JWT secret
|
||||
file), `StorageRegistryService` (the built-in uploads and backups roots and
|
||||
the scratch dir) and, through `StorageRegistryService.tempDir()`,
|
||||
`StorageJobsService`. A new provider that needs a data path takes it the
|
||||
same way.
|
||||
- **Plain modules call `resolveDataPaths()`** because they run without a
|
||||
container or are shared with code that does: `config.ts` key resolution,
|
||||
`db/db-path.ts`, `index.ts`, the file logger, `demo/demo-reset.ts`, the
|
||||
backup restore and archive functions (`nest/backup/backup.impl.ts`,
|
||||
`auto-backup.settings.ts`, file I/O with no container state), the plugin
|
||||
trees (`nest/plugins/paths.ts`, also read by the out-of-process supervisor),
|
||||
and `nest/storage/storage-paths.ts`, which keeps the seed-config test seam
|
||||
that `StorageAdminService` and the registry share. `files.constants.ts`
|
||||
still exports `filesDir` for the tests that pin the layout; no production
|
||||
code reads it.
|
||||
|
||||
## app-url.ts — instance base-URL resolution (moved 2026-07-28)
|
||||
|
||||
`getAppUrl()` (APP_URL → first ALLOWED_ORIGINS entry → `http://localhost:PORT`,
|
||||
@@ -60,14 +93,62 @@ invariant 1: `readEnv()` per call, live, never cached. The invalid-URL silent
|
||||
fallthrough and the strip-ALL-slashes quirk (see `parsers.ts`
|
||||
`stripTrailingSlashes`) are parity-pinned — do not "fix" them here.
|
||||
|
||||
## Ownership: one door per variable
|
||||
|
||||
Every variable has exactly one owner, and the owner decides how it is read:
|
||||
|
||||
- **A registerAs token** (`src/nest/app-config/tokens.ts`, derived by
|
||||
`boot-derive.ts`): boot-stable values that only Nest classes need. The token
|
||||
is snapshotted per built app and injected (`@Inject(storageConfig.KEY)`, or
|
||||
`app.get(httpConfig.KEY)` for the pre-init Express layer). Today:
|
||||
`httpConfig` (TRUST_PROXY, HSTS_INCLUDE_SUBDOMAINS, HTTP_KEEP_ALIVE_TIMEOUT_MS),
|
||||
`storageConfig` (TREK_PLACE_PHOTO_DIR), `transitConfig` (TRANSIT_API_URL,
|
||||
for TransitService) and `kitineraryConfig` (KITINERARY_EXTRACTOR_PATH and
|
||||
PATH, for KitineraryExtractorService's binary probe). A module whose provider
|
||||
injects one imports `AppConfigModule`, so it also builds on its own in a test.
|
||||
- **`readEnv()` / `RuntimeEnvService`** (`derive.ts`): everything else, both
|
||||
the runtime-toggled values and the boot-stable ones that code outside a Nest
|
||||
provider reads, which freezes them in module-top consts. Each of those has a
|
||||
reader the container cannot inject into:
|
||||
- PORT, HOST: `index.ts`, before the app exists.
|
||||
- SESSION_DURATION(_REMEMBER), DEFAULT_LANGUAGE, ENCRYPTION_KEY: `src/config.ts`,
|
||||
a plain module evaluated at process start.
|
||||
- MCP_*: `src/mcp/`, the process-wide session state.
|
||||
- TREK_PLUGIN_RPC_*/LOG_*/MAX_RSS_MB: the plugin host and supervisor, which
|
||||
are deliberately not Nest (the sandbox boundary).
|
||||
- TREK_PLUGIN_REGISTRY_URL: `PluginRegistryService` is a provider, but several
|
||||
plugin suites build it by hand with a trailing `@Optional()` UnitOfWork, so
|
||||
a required token parameter cannot go in without reordering that signature.
|
||||
- TREK_WIKI_DIR: `nest/help/wiki.ts`, a plain module the help MCP tools call.
|
||||
- BACKUP_*: `nest/backup/backup-archive.ts`, which the first-start restore
|
||||
(`boot-restore.ts`, called from `index.ts`) runs before the database opens.
|
||||
- LOG_LEVEL: the logger, imported everywhere.
|
||||
- ALLOW_INTERNAL_NETWORK, ALLOW_LINK_LOCAL_IPS: the SSRF guard in `utils/`.
|
||||
- TREK_DB_FILE, TREK_DB_JOURNAL_MODE, TREK_DB_SYNCHRONOUS: the database,
|
||||
opened before the container.
|
||||
|
||||
`deriveAll()` never reads a variable a token owns, and a token is dropped once
|
||||
nothing injects it. `tests/unit/app-config/config-ownership.test.ts` records
|
||||
the keys each side reads through a Proxy and fails on an overlap, on a token
|
||||
without a consumer and on a variable the schema does not validate. Moving a
|
||||
variable to a token means moving its field from `derive.ts` to
|
||||
`boot-derive.ts` and converting every reader in the same change.
|
||||
|
||||
`server/.env.example` names every variable the schema validates except the
|
||||
few in `env-reference.test.ts`'s `NOT_OPERATOR_SETTINGS`; that test fails on
|
||||
drift in either direction. The managed-hosting switches (TREK_MANAGED and the
|
||||
keys only a managed install sets: MAPBOX_ACCESS_TOKEN, CARTO_API_KEY,
|
||||
PLACES_API_BASE) are on that list on purpose and stay out of every public
|
||||
reference.
|
||||
|
||||
## Classification: boot-stable vs runtime-toggled
|
||||
|
||||
**Boot-stable** (frozen at app/module creation; snapshot `registerAs`/`ConfigType`
|
||||
DI in Nest, module-top `readEnv()` consts elsewhere):
|
||||
PORT, HOST, TRUST_PROXY, SESSION_DURATION(_REMEMBER), MCP_SESSION_TTL,
|
||||
**Boot-stable** (frozen at app/module creation; a `registerAs` token where the
|
||||
variable is token-owned, module-top `readEnv()` consts elsewhere):
|
||||
PORT, HOST, TRUST_PROXY, HSTS_INCLUDE_SUBDOMAINS, HTTP_KEEP_ALIVE_TIMEOUT_MS, SESSION_DURATION(_REMEMBER), MCP_SESSION_TTL,
|
||||
MCP_MAX_SESSION_PER_USER, MCP_SSE_KEEPALIVE, TREK_PLUGIN_RPC_*/LOG_*/MAX_RSS_MB,
|
||||
TREK_PLUGIN_REGISTRY_URL, TREK_WIKI_DIR*, TREK_PLACE_PHOTO_DIR, BACKUP_*,
|
||||
TRANSIT_API_URL, LOG_LEVEL*, ALLOW_INTERNAL_NETWORK*, ALLOW_LINK_LOCAL_IPS*, DEFAULT_LANGUAGE,
|
||||
TRANSIT_API_URL, KITINERARY_EXTRACTOR_PATH, LOG_LEVEL*, ALLOW_INTERNAL_NETWORK*, ALLOW_LINK_LOCAL_IPS*, DEFAULT_LANGUAGE,
|
||||
TREK_DB_FILE, TREK_DB_JOURNAL_MODE, TREK_DB_SYNCHRONOUS, ENCRYPTION_KEY**.
|
||||
(* frozen today because the consuming module captures it at import; tests that
|
||||
override these set them at file top, before the SUT import.)
|
||||
@@ -79,10 +160,13 @@ below.)
|
||||
`RuntimeEnvService`; tests mutate these mid-lifetime):
|
||||
TREK_MANAGED, PLACES_API_BASE, PLACES_API_KEY, AMAP_API_BASE, AMAP_API_KEY, AMAP_API_SECRET, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED,
|
||||
TREK_PLUGINS_ENABLED / _DEV_LINK / _IGNORE_TREK_RANGE / _DIR / _DATA_DIR / TREK_PLUGIN_PERMISSIONS,
|
||||
OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE, HSTS_INCLUDE_SUBDOMAINS,
|
||||
OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE,
|
||||
ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL,
|
||||
TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP) (read when a migration run starts; the
|
||||
legacy-upgrade suites set it per file),
|
||||
ADMIN_PASSWORD, IDEMPOTENCY_TTL_SECONDS, MCP_RATE_LIMIT (request-path check),
|
||||
LLM_TIMEOUT_MS, NOMINATIM_URL.
|
||||
LLM_TIMEOUT_MS, LLM_MAX_OUTPUT_TOKENS, NOMINATIM_URL, VAPID_* (resolved per use by the Web Push key
|
||||
service, which the notification suites build without the container).
|
||||
|
||||
## Exemptions — raw `process.env` stays
|
||||
|
||||
@@ -116,3 +200,5 @@ The exemption list is enforced by the `no-restricted-syntax` ban on
|
||||
- NODE_ENV comparisons are case-sensitive at some sites (HSTS activation,
|
||||
platform statics, spa-fallback, authService dev_mode, oidcService
|
||||
frontendUrl) and case-insensitive at others.
|
||||
Surrounding whitespace is stripped once at boot (`normalizeEnvAtBoot`,
|
||||
together with LOG_LEVEL and DEFAULT_LANGUAGE), the casing is not.
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Derive functions for the BOOT-STABLE values that Nest injects through a
|
||||
* registerAs token (src/nest/app-config/tokens.ts) and nothing else reads.
|
||||
*
|
||||
* Every environment variable has exactly one owner. A variable derived here is
|
||||
* owned by its token: `deriveAll()` (and so `readEnv()`) never reads it, which
|
||||
* tests/unit/app-config/config-ownership.test.ts checks by recording the keys
|
||||
* each side touches. A value that pre-container code needs, or that tests
|
||||
* mutate mid-lifetime, belongs in derive.ts instead.
|
||||
*/
|
||||
import type { RawEnv } from './derive';
|
||||
import { parseBool, positiveIntOr, stripTrailingSlashes } from './parsers';
|
||||
|
||||
/**
|
||||
* Longer than the upstream idle timeout of the common reverse proxies and load
|
||||
* balancers (60 s for nginx and most load balancers, 90 s for Traefik), so the
|
||||
* proxy closes an idle upstream connection before Node does. The other way
|
||||
* round the proxy reuses a socket Node just closed and answers that request
|
||||
* with a 502. The headers timeout follows one second above, still well under
|
||||
* Node's 300 s request timeout.
|
||||
*/
|
||||
export const DEFAULT_KEEP_ALIVE_TIMEOUT_MS = 95_000;
|
||||
|
||||
/** What the pre-init Express layer and the HTTP server freeze when buildApp() runs. */
|
||||
export function deriveHttpBoot(raw: RawEnv) {
|
||||
// env.schema.ts accepts 0 as a valid hop count, so `|| 1` would quietly turn
|
||||
// "trust nothing" into "trust one hop" and let a forged X-Forwarded-For through.
|
||||
const trustProxyHops = Number.parseInt(raw.TRUST_PROXY ?? '', 10);
|
||||
return {
|
||||
trustProxyRaw: raw.TRUST_PROXY,
|
||||
trustProxy: Number.isFinite(trustProxyHops) ? trustProxyHops : 1,
|
||||
hstsIncludeSubdomains: parseBool(raw.HSTS_INCLUDE_SUBDOMAINS) === true,
|
||||
/** How long the HTTP server keeps an idle keep-alive connection open. */
|
||||
keepAliveTimeoutMs: positiveIntOr(raw.HTTP_KEEP_ALIVE_TIMEOUT_MS, DEFAULT_KEEP_ALIVE_TIMEOUT_MS),
|
||||
};
|
||||
}
|
||||
|
||||
/** Where the storage registry puts its conditional place-photo backend. */
|
||||
export function deriveStorage(raw: RawEnv) {
|
||||
return {
|
||||
placePhotoDir: raw.TREK_PLACE_PHOTO_DIR,
|
||||
};
|
||||
}
|
||||
|
||||
/** The Transitous/MOTIS instance TransitService proxies to. */
|
||||
export function deriveTransit(raw: RawEnv) {
|
||||
return {
|
||||
apiBase: stripTrailingSlashes(raw.TRANSIT_API_URL || 'https://api.transitous.org'),
|
||||
};
|
||||
}
|
||||
|
||||
/** Where KitineraryExtractorService looks for its binary when the module starts. */
|
||||
export function deriveKitinerary(raw: RawEnv) {
|
||||
return {
|
||||
extractorPath: raw.KITINERARY_EXTRACTOR_PATH,
|
||||
// Windows spells it Path; every other platform PATH. Split here so the
|
||||
// probe gets a list and never re-implements the delimiter.
|
||||
searchPath: (raw.PATH || raw.Path || '')
|
||||
.split(process.platform === 'win32' ? ';' : ':')
|
||||
.map((p) => p.trim())
|
||||
.filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
/** One entry per token: the namespace it registers under and the function it derives with. */
|
||||
export const BOOT_DERIVERS = {
|
||||
http: deriveHttpBoot,
|
||||
storage: deriveStorage,
|
||||
transit: deriveTransit,
|
||||
kitinerary: deriveKitinerary,
|
||||
} as const;
|
||||
|
||||
export type BootNamespace = keyof typeof BOOT_DERIVERS;
|
||||
@@ -1,12 +1,16 @@
|
||||
/**
|
||||
* Side-effect module: validates the environment the moment it is imported.
|
||||
* Side-effect module: normalizes and validates the environment the moment it
|
||||
* is imported.
|
||||
*
|
||||
* index.ts imports this immediately after `import 'dotenv/config'` — as a
|
||||
* side-effect import (not a function call) so validation runs BEFORE the rest
|
||||
* of the import graph executes its module-load side effects (config.ts key
|
||||
* resolution, db/database.ts initDb, ...). A plain call in index.ts's body
|
||||
* would run after all of those, because imports hoist.
|
||||
* resolution, ...). A plain call in index.ts's body
|
||||
* would run after all of those, because imports hoist. The trim runs first,
|
||||
* so everything after it, Express and the plugin children included, reads the
|
||||
* cleaned value.
|
||||
*/
|
||||
import { validateEnvAtBoot } from './env';
|
||||
import { normalizeEnvAtBoot, validateEnvAtBoot } from './env';
|
||||
|
||||
normalizeEnvAtBoot();
|
||||
validateEnvAtBoot();
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { readEnv, type AppEnv } from './env';
|
||||
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* `<server>/`, the directory holding package.json. `src/app-config` and
|
||||
* `dist/app-config` both sit two levels below it, so the anchor is the same
|
||||
* under vitest, `npm run dev` and the built image.
|
||||
*/
|
||||
export const SERVER_ROOT = path.resolve(__dirname, '..', '..');
|
||||
|
||||
/**
|
||||
* Where TREK keeps what it writes. In the image `data/` and `uploads/` are
|
||||
* symlinks into `/app`, which is why every consumer used to anchor on its own
|
||||
* `__dirname` and why none of them may use `process.cwd()` instead.
|
||||
*/
|
||||
export interface DataPaths {
|
||||
/** `<server>/data`: the database, the key files, backups, logs and plugin trees. */
|
||||
readonly dataDir: string;
|
||||
/** `<server>/uploads`: the local upload categories (files, covers, photos, ...). */
|
||||
readonly uploadsDir: string;
|
||||
/** `data/backups`: archives written by the manual and the automatic backup. */
|
||||
readonly backupsDir: string;
|
||||
/** `data/tmp`: driver-agnostic scratch space (restore spool, mirror staging). */
|
||||
readonly tmpDir: string;
|
||||
/** `data/logs`: the rotating `trek.log`. */
|
||||
readonly logsDir: string;
|
||||
/** `data/.jwt_secret`: written on first start and by the admin's JWT rotation. */
|
||||
readonly jwtSecretFile: string;
|
||||
/** `data/.encryption_key`: the at-rest key when ENCRYPTION_KEY does not provide it. */
|
||||
readonly encryptionKeyFile: string;
|
||||
/**
|
||||
* The SQLite file a non-test process opens: TREK_DB_FILE when set, else
|
||||
* `data/travel.db`. Under NODE_ENV=test the connection is `:memory:` instead
|
||||
* (db/db-path.ts), which is a property of the connection, not of the layout.
|
||||
*/
|
||||
readonly dbFile: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The data layout, derived from the server root and the live environment.
|
||||
*
|
||||
* The only variable involved is TREK_DB_FILE, read through `readEnv()` like
|
||||
* every other live value, so a test that points it somewhere else is seen on
|
||||
* the next call. Nothing here touches the disk: creating a directory is the
|
||||
* caller's decision.
|
||||
*/
|
||||
export function resolveDataPaths(
|
||||
env: { db: Pick<AppEnv['db'], 'trekDbFile'> } = readEnv(),
|
||||
root: string = SERVER_ROOT,
|
||||
): DataPaths {
|
||||
const dataDir = path.join(root, 'data');
|
||||
return {
|
||||
dataDir,
|
||||
uploadsDir: path.join(root, 'uploads'),
|
||||
backupsDir: path.join(dataDir, 'backups'),
|
||||
tmpDir: path.join(dataDir, 'tmp'),
|
||||
logsDir: path.join(dataDir, 'logs'),
|
||||
jwtSecretFile: path.join(dataDir, '.jwt_secret'),
|
||||
encryptionKeyFile: path.join(dataDir, '.encryption_key'),
|
||||
dbFile: env.db.trekDbFile || path.join(dataDir, 'travel.db'),
|
||||
};
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* call, which is what keeps the runtime env-mutation semantics the test suite
|
||||
* depends on. Zod validation runs once at boot (env.schema.ts), never here.
|
||||
*/
|
||||
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared';
|
||||
import { imageVersion } from './image-version';
|
||||
import {
|
||||
csvList,
|
||||
csvListFiltered,
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
resolveSessionTtlMs,
|
||||
stripTrailingSlashes,
|
||||
} from './parsers';
|
||||
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared';
|
||||
|
||||
export type RawEnv = Record<string, string | undefined>;
|
||||
|
||||
@@ -43,8 +44,13 @@ export function deriveApp(raw: RawEnv) {
|
||||
isTest: nodeEnv === 'test',
|
||||
port: numberOr(raw.PORT, 3001),
|
||||
host: raw.HOST,
|
||||
/** Raw APP_VERSION — fallbacks differ per site ('0.0.0' vs package.json vs semver-validated); each keeps its own. */
|
||||
appVersion: raw.APP_VERSION,
|
||||
/**
|
||||
* The image's own VERSION file, else raw APP_VERSION. Fallbacks differ per
|
||||
* site ('0.0.0' vs package.json vs semver-validated); each keeps its own.
|
||||
* The file wins because a container keeps its env across image updates
|
||||
* (image-version.ts).
|
||||
*/
|
||||
appVersion: imageVersion() ?? raw.APP_VERSION,
|
||||
/** Raw APP_URL — trailing-slash stripping differs per site (feeds strips one, notifications strips all). */
|
||||
appUrl: raw.APP_URL,
|
||||
tz: raw.TZ,
|
||||
@@ -63,20 +69,19 @@ function resolveDefaultLanguage(raw: string | undefined): string {
|
||||
return canonical ?? 'en';
|
||||
}
|
||||
|
||||
/**
|
||||
* The live half of the HTTP settings. TRUST_PROXY and HSTS_INCLUDE_SUBDOMAINS
|
||||
* are not here: they are boot-stable and owned by the `httpConfig` token
|
||||
* (boot-derive.ts), so they cannot be read through two doors.
|
||||
*/
|
||||
export function deriveHttp(raw: RawEnv) {
|
||||
// env.schema.ts accepts 0 as a valid hop count, so `|| 1` would quietly turn
|
||||
// "trust nothing" into "trust one hop" and let a forged X-Forwarded-For through.
|
||||
const trustProxyHops = Number.parseInt(raw.TRUST_PROXY ?? '', 10);
|
||||
return {
|
||||
allowedOriginsRaw: raw.ALLOWED_ORIGINS,
|
||||
/** globalMiddleware CORS variant: trim + drop empty entries. */
|
||||
corsOrigins: csvListFiltered(raw.ALLOWED_ORIGINS),
|
||||
/** websocket variant: trim only — an empty entry stays (and can never match an Origin header). */
|
||||
wsOrigins: csvList(raw.ALLOWED_ORIGINS),
|
||||
trustProxyRaw: raw.TRUST_PROXY,
|
||||
trustProxy: Number.isFinite(trustProxyHops) ? trustProxyHops : 1,
|
||||
forceHttps: parseBool(raw.FORCE_HTTPS) === true,
|
||||
hstsIncludeSubdomains: parseBool(raw.HSTS_INCLUDE_SUBDOMAINS) === true,
|
||||
/** COOKIE_SECURE is tri-state: an explicit falsy value disables secure cookies; anything else means auto-detect. */
|
||||
cookieSecureDisabled: parseBool(raw.COOKIE_SECURE) === false,
|
||||
apiDocsEnabled: parseBool(raw.TREK_API_DOCS_ENABLED) === true,
|
||||
@@ -135,6 +140,7 @@ export function deriveManaged(raw: RawEnv) {
|
||||
export function deriveMaps(raw: RawEnv) {
|
||||
return {
|
||||
placesApiBase: raw.PLACES_API_BASE || undefined,
|
||||
googleListDataBase: raw.GOOGLE_LIST_DATA_BASE?.trim() || undefined,
|
||||
/**
|
||||
* Base URL of the TREK Places API. Unset means the public instance; an
|
||||
* operator who runs their own copy of the index points at it here, and one
|
||||
@@ -206,6 +212,9 @@ export function deriveOidc(raw: RawEnv) {
|
||||
only: parseBool(raw.OIDC_ONLY) === true,
|
||||
adminClaim: raw.OIDC_ADMIN_CLAIM || 'groups',
|
||||
adminValue: raw.OIDC_ADMIN_VALUE,
|
||||
// Unset keeps the old order (name, then preferred_username), so an instance
|
||||
// that never sets it names new accounts exactly as before (#1677).
|
||||
usernameClaim: raw.OIDC_USERNAME_CLAIM?.trim() || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -271,7 +280,6 @@ export function deriveWebauthn(raw: RawEnv) {
|
||||
export function deriveIntegrations(raw: RawEnv) {
|
||||
return {
|
||||
unsplashAccessKey: raw.UNSPLASH_ACCESS_KEY?.trim(),
|
||||
transitApiBase: stripTrailingSlashes(raw.TRANSIT_API_URL || 'https://api.transitous.org'),
|
||||
// Trimmed before the default fires: the schema validates the trimmed value and
|
||||
// treats a blank one as unset, so a padded or whitespace-only value would
|
||||
// otherwise pass startup and then be the string that cannot be fetched.
|
||||
@@ -280,7 +288,6 @@ export function deriveIntegrations(raw: RawEnv) {
|
||||
// Longer than the `[timeout:20]` the query itself carries, or we abort an answer the
|
||||
// mirror was still allowed to be working on. See OVERPASS_QUERY_TIMEOUT_S.
|
||||
overpassTimeoutMs: positiveNumberOr(raw.OVERPASS_TIMEOUT_MS, 25000),
|
||||
kitineraryExtractorPath: raw.KITINERARY_EXTRACTOR_PATH,
|
||||
/**
|
||||
* One ceiling for a model call, replacing the three per-client constants
|
||||
* that used to disagree. The default is deliberately generous: heavier
|
||||
@@ -289,12 +296,23 @@ export function deriveIntegrations(raw: RawEnv) {
|
||||
* rejects a fractional value.
|
||||
*/
|
||||
llmTimeoutMs: Math.floor(positiveNumberOr(raw.LLM_TIMEOUT_MS, 900_000)),
|
||||
// Windows spells it Path; every other platform PATH. Split here so callers
|
||||
// get a list and never re-implement the delimiter.
|
||||
searchPath: (raw.PATH || raw.Path || '')
|
||||
.split(process.platform === 'win32' ? ';' : ':')
|
||||
.map(p => p.trim())
|
||||
.filter(Boolean),
|
||||
/**
|
||||
* How long one AI-parsing answer may get. Unset leaves each client the cap it
|
||||
* has always sent (4096 to OpenAI-compatible servers, 8192 to Anthropic): a
|
||||
* bigger default would make the server of a small local model refuse every
|
||||
* request whose prompt plus cap overruns its context (#2677).
|
||||
*/
|
||||
llmMaxOutputTokens: positiveIntOr(raw.LLM_MAX_OUTPUT_TOKENS, 0) || undefined,
|
||||
// TRANSIT_API_URL, KITINERARY_EXTRACTOR_PATH and PATH are boot-stable and
|
||||
// read only by Nest providers, so the transitConfig and kitineraryConfig
|
||||
// tokens own them (boot-derive.ts).
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveFiles(raw: RawEnv) {
|
||||
return {
|
||||
/** Largest document a user may upload to a trip, a booking or a note (#1364). Videos keep their own cap. */
|
||||
uploadLimitMb: positiveNumberOr(raw.FILE_UPLOAD_LIMIT_MB, 50),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -304,6 +322,8 @@ export function deriveBackup(raw: RawEnv) {
|
||||
maxDecompressedMb: positiveNumberOr(raw.BACKUP_MAX_DECOMPRESSED_MB, 5 * 1024),
|
||||
/** backupService only bundles data/.encryption_key into archives when the key does NOT come from env. */
|
||||
encryptionKeyFromEnv: !!raw.ENCRYPTION_KEY,
|
||||
/** Archive restored on the first start, while no database exists yet (#1089). Null when unset or blank. */
|
||||
restoreFromBackup: raw.RESTORE_FROM_BACKUP?.trim() || null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -317,13 +337,21 @@ export function deriveDb(raw: RawEnv) {
|
||||
synchronous: durability.synchronous,
|
||||
/** Complaints about unusable values; derivation stays side-effect free, so db/durability.ts logs them when it opens the file. */
|
||||
durabilityWarnings: durability.warnings,
|
||||
/**
|
||||
* Snapshot the database before a boot migrates it. Undefined when unset: the
|
||||
* caller then decides (on, except under NODE_ENV=test). false is the escape
|
||||
* hatch for a data dir that cannot hold a second copy.
|
||||
*/
|
||||
preMigrateSnapshot: parseBool(raw.TREK_DB_PRE_MIGRATE_SNAPSHOT),
|
||||
/** How many pre-migration snapshots stay in the data dir, newest first. */
|
||||
preMigrateSnapshotKeep: Math.min(positiveIntOr(raw.TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP, 3), 100),
|
||||
};
|
||||
}
|
||||
|
||||
/** TREK_PLACE_PHOTO_DIR is boot-stable and owned by the `storageConfig` token (boot-derive.ts). */
|
||||
export function derivePaths(raw: RawEnv) {
|
||||
return {
|
||||
wikiDir: raw.TREK_WIKI_DIR,
|
||||
placePhotoDir: raw.TREK_PLACE_PHOTO_DIR,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -331,6 +359,26 @@ export function deriveNet(raw: RawEnv) {
|
||||
return {
|
||||
allowInternalNetwork: parseBool(raw.ALLOW_INTERNAL_NETWORK) === true,
|
||||
allowLinkLocalIps: parseLinkLocalAllowList(raw.ALLOW_LINK_LOCAL_IPS).ips,
|
||||
// The variables Node's own env proxy reads, both spellings, so the guarded
|
||||
// requests below follow the same proxy as everything else (#1754).
|
||||
proxy: {
|
||||
http: (raw.HTTP_PROXY ?? raw.http_proxy)?.trim() || undefined,
|
||||
https: (raw.HTTPS_PROXY ?? raw.https_proxy)?.trim() || undefined,
|
||||
noProxy: ((raw.NO_PROXY ?? raw.no_proxy) || '')
|
||||
.split(',')
|
||||
.map((entry) => entry.trim().toLowerCase())
|
||||
.filter(Boolean),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function derivePush(raw: RawEnv) {
|
||||
return {
|
||||
// Trimmed, and blank counts as unset: the schema validated the trimmed value,
|
||||
// so a padded key must not reach the crypto as a different string.
|
||||
vapidPublicKey: raw.VAPID_PUBLIC_KEY?.trim() || undefined,
|
||||
vapidPrivateKey: raw.VAPID_PRIVATE_KEY?.trim() || undefined,
|
||||
vapidSubject: raw.VAPID_SUBJECT?.trim() || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -350,9 +398,11 @@ export function deriveAll(raw: RawEnv) {
|
||||
webauthn: deriveWebauthn(raw),
|
||||
integrations: deriveIntegrations(raw),
|
||||
backup: deriveBackup(raw),
|
||||
files: deriveFiles(raw),
|
||||
db: deriveDb(raw),
|
||||
paths: derivePaths(raw),
|
||||
net: deriveNet(raw),
|
||||
push: derivePush(raw),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,16 @@
|
||||
* listed here pass through untouched (Zod strips unknown keys, it does not
|
||||
* reject them).
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
isP256PrivateKey,
|
||||
isUncompressedP256Key,
|
||||
isVapidSubject,
|
||||
parseDurationMs,
|
||||
parseLinkLocalAllowList,
|
||||
} from './parsers';
|
||||
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared';
|
||||
import { parseDurationMs, parseLinkLocalAllowList } from './parsers';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/** Present-but-malformed fails; unset/blank always passes (defaults apply). */
|
||||
function optionalWith(test: (v: string) => boolean, message: string) {
|
||||
@@ -43,10 +50,7 @@ const url = optionalWith((v) => {
|
||||
return false;
|
||||
}
|
||||
}, 'must be a valid URL (with protocol)');
|
||||
const duration = optionalWith(
|
||||
(v) => parseDurationMs(v) != null,
|
||||
'must be a duration like "1h", "7d" or "30d"',
|
||||
);
|
||||
const duration = optionalWith((v) => parseDurationMs(v) != null, 'must be a duration like "1h", "7d" or "30d"');
|
||||
const oneOf = (values: string[]) =>
|
||||
optionalWith((v) => values.includes(v.toLowerCase()), `must be one of: ${values.join(', ')}`);
|
||||
|
||||
@@ -56,6 +60,7 @@ export const envSchema = z.object({
|
||||
HOST: anyString,
|
||||
// NODE_ENV and TZ are deliberately unvalidated: non-standard values (e.g.
|
||||
// NODE_ENV=staging) behave as "not production" today and must keep booting.
|
||||
// Surrounding whitespace on NODE_ENV is trimmed before this runs (env.ts).
|
||||
NODE_ENV: anyString,
|
||||
TZ: anyString,
|
||||
LOG_LEVEL: oneOf(['error', 'warn', 'info', 'debug']),
|
||||
@@ -73,6 +78,9 @@ export const envSchema = z.object({
|
||||
FORCE_HTTPS: boolStr,
|
||||
HSTS_INCLUDE_SUBDOMAINS: boolStr,
|
||||
TRUST_PROXY: integer(0, 2 ** 31, 'must be an integer (number of trusted proxy hops)'),
|
||||
// Capped below Node's 300 s request timeout, which the headers timeout (one
|
||||
// second above this) has to stay under.
|
||||
HTTP_KEEP_ALIVE_TIMEOUT_MS: integer(1_000, 290_000, 'must be a whole number of milliseconds between 1000 and 290000'),
|
||||
ALLOW_INTERNAL_NETWORK: boolStr,
|
||||
ALLOW_LINK_LOCAL_IPS: optionalWith(
|
||||
(v) => parseLinkLocalAllowList(v).invalid.length === 0,
|
||||
@@ -91,6 +99,7 @@ export const envSchema = z.object({
|
||||
OIDC_ONLY: boolStr,
|
||||
OIDC_ADMIN_CLAIM: anyString,
|
||||
OIDC_ADMIN_VALUE: anyString,
|
||||
OIDC_USERNAME_CLAIM: anyString,
|
||||
|
||||
// SMTP
|
||||
SMTP_HOST: anyString,
|
||||
@@ -104,6 +113,18 @@ export const envSchema = z.object({
|
||||
WEBAUTHN_RP_ID: anyString,
|
||||
WEBAUTHN_ORIGINS: anyString,
|
||||
|
||||
// Web Push (VAPID). All optional: without them the server keeps a pair of its
|
||||
// own in the database. Only the shape is checked here; whether the two keys
|
||||
// belong together is checked where they are used, which turns push off while
|
||||
// they do not (never signing with a stored pair in their place) and says so
|
||||
// in the log instead of refusing to boot.
|
||||
VAPID_PUBLIC_KEY: optionalWith(
|
||||
isUncompressedP256Key,
|
||||
'must be a base64url-encoded P-256 public key (65 bytes, uncompressed, starting with 0x04)',
|
||||
),
|
||||
VAPID_PRIVATE_KEY: optionalWith(isP256PrivateKey, 'must be a base64url-encoded P-256 private key (32 bytes)'),
|
||||
VAPID_SUBJECT: optionalWith(isVapidSubject, 'must be a mailto: address or an https:// URL'),
|
||||
|
||||
// MCP
|
||||
MCP_SESSION_TTL: positiveNumber,
|
||||
MCP_MAX_SESSION_PER_USER: positiveNumber,
|
||||
@@ -123,6 +144,8 @@ export const envSchema = z.object({
|
||||
// 2^31-1 makes Node clamp the delay to 1 ms and do the same. Both refuse at
|
||||
// boot rather than degrading into a timeout of zero.
|
||||
LLM_TIMEOUT_MS: integer(1, 2_147_483_647, 'must be a whole number of milliseconds between 1 and 2147483647'),
|
||||
// Below 256 not even one reservation fits, so a value that small is a typo, not a choice.
|
||||
LLM_MAX_OUTPUT_TOKENS: integer(256, 1_000_000, 'must be a whole number of tokens between 256 and 1000000'),
|
||||
KITINERARY_EXTRACTOR_PATH: anyString,
|
||||
// The OS search path. Not configuration anybody sets for TREK — it is here so
|
||||
// the kitinerary probe can resolve its binary to an absolute path itself
|
||||
@@ -139,16 +162,26 @@ export const envSchema = z.object({
|
||||
// this schema at all. Resolution lives in parsers.resolveDurability().
|
||||
TREK_DB_JOURNAL_MODE: anyString,
|
||||
TREK_DB_SYNCHRONOUS: anyString,
|
||||
// The copy of the database taken before a boot applies pending migrations.
|
||||
// Unlike the two pragmas a typo here refuses the boot: the switch exists to
|
||||
// turn a safety net off, and a misspelt "off" must not leave it on silently
|
||||
// or a misspelt "on" turn it off.
|
||||
TREK_DB_PRE_MIGRATE_SNAPSHOT: boolStr,
|
||||
TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP: integer(1, 100),
|
||||
TREK_WIKI_DIR: anyString,
|
||||
TREK_PLACE_PHOTO_DIR: anyString,
|
||||
BACKUP_UPLOAD_LIMIT_MB: positiveNumber,
|
||||
FILE_UPLOAD_LIMIT_MB: positiveNumber,
|
||||
BACKUP_MAX_DECOMPRESSED_MB: positiveNumber,
|
||||
// A backup archive to restore on the very first start, before any setup (#1089).
|
||||
RESTORE_FROM_BACKUP: anyString,
|
||||
|
||||
// Admin / demo
|
||||
ADMIN_EMAIL: anyString,
|
||||
ADMIN_PASSWORD: anyString,
|
||||
TREK_MANAGED: boolStr,
|
||||
PLACES_API_BASE: url,
|
||||
GOOGLE_LIST_DATA_BASE: url,
|
||||
TREK_PLACES_URL: url,
|
||||
TREK_PLACES_ENABLED: boolStr,
|
||||
PLACES_API_KEY: anyString,
|
||||
|
||||
@@ -14,6 +14,70 @@ export function readEnv(): AppEnv {
|
||||
return deriveAll(process.env as RawEnv);
|
||||
}
|
||||
|
||||
/**
|
||||
* Variables whose value never goes into the boot report, even when it is the
|
||||
* malformed one: the report lands in container logs, and a key that is merely
|
||||
* mistyped is still a real key. The name and the problem are enough to fix it.
|
||||
*/
|
||||
export const SECRET_ENV_KEYS: ReadonlySet<string> = new Set([
|
||||
'ENCRYPTION_KEY',
|
||||
'OIDC_CLIENT_SECRET',
|
||||
'SMTP_PASS',
|
||||
'VAPID_PRIVATE_KEY',
|
||||
'UNSPLASH_ACCESS_KEY',
|
||||
'ADMIN_PASSWORD',
|
||||
'PLACES_API_KEY',
|
||||
'AMAP_API_KEY',
|
||||
'AMAP_API_SECRET',
|
||||
'MAPBOX_ACCESS_TOKEN',
|
||||
'CARTO_API_KEY',
|
||||
'DEMO_ADMIN_PASS',
|
||||
]);
|
||||
|
||||
/** How a variable's value appears in the boot report. */
|
||||
function reportedValue(key: string, value: string | undefined): string {
|
||||
return SECRET_ENV_KEYS.has(key) ? '***' : JSON.stringify(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Variables whose surrounding whitespace is stripped once at boot. The schema
|
||||
* already validates them trimmed, but every reader compares the raw string:
|
||||
* NODE_ENV="production " served no web UI at all (#2565), LOG_LEVEL="debug "
|
||||
* fell back to info, DEFAULT_LANGUAGE="de " to English. Deliberately a short
|
||||
* list, not every variable: a secret may carry its spaces on purpose.
|
||||
*/
|
||||
const TRIMMED_AT_BOOT = ['NODE_ENV', 'LOG_LEVEL', 'DEFAULT_LANGUAGE'] as const;
|
||||
|
||||
/**
|
||||
* Strips the whitespace a .env line or a compose file left around the values in
|
||||
* TRIMMED_AT_BOOT and writes the result back, so Express (`app.get('env')`),
|
||||
* the plugin child processes and any library reading NODE_ENV itself see the
|
||||
* same value as readEnv(). Casing is left alone. Each change is reported, since
|
||||
* the banner cannot show a trailing space.
|
||||
*
|
||||
* NODE_ENV="test " is the one exception: trimmed it would switch a running
|
||||
* instance onto an in-memory database without crons, so it is only reported.
|
||||
*/
|
||||
export function normalizeEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
|
||||
for (const key of TRIMMED_AT_BOOT) {
|
||||
const value = raw[key];
|
||||
if (value === undefined) continue;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed === value) continue;
|
||||
if (key === 'NODE_ENV' && trimmed === 'test') {
|
||||
bootWarning(`${key}=${JSON.stringify(value)} has surrounding whitespace and is not treated as "test".`);
|
||||
continue;
|
||||
}
|
||||
raw[key] = trimmed;
|
||||
bootWarning(`${key}=${JSON.stringify(value)} has surrounding whitespace, using ${JSON.stringify(trimmed)}.`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs before the file logger exists, so it goes to stderr as a process warning. */
|
||||
function bootWarning(message: string): void {
|
||||
process.emitWarning(message, { code: 'TREK_ENV_WHITESPACE' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail-fast startup validation: a variable that is PRESENT but malformed aborts
|
||||
* boot with an aggregated report; unset/blank variables always pass (their
|
||||
@@ -28,7 +92,7 @@ export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
|
||||
? []
|
||||
: result.error.issues.map((issue) => {
|
||||
const key = String(issue.path[0]);
|
||||
return ` - ${key}=${JSON.stringify(raw[key])}: ${issue.message}`;
|
||||
return ` - ${key}=${reportedValue(key, raw[key])}: ${issue.message}`;
|
||||
});
|
||||
lines.push(...managedPreconditions(raw));
|
||||
if (lines.length === 0) return;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
/**
|
||||
* The version the Docker image was built as, from the `VERSION` file the
|
||||
* Dockerfile writes next to `server/package.json`.
|
||||
*
|
||||
* It wins over the APP_VERSION env var because an env var belongs to the
|
||||
* container, not to the image. Portainer's "recreate" and `docker run` with a
|
||||
* copied config carry the previous image's APP_VERSION into a container built
|
||||
* from the new one, so the server kept announcing the old release and no client
|
||||
* ever handed over to the new bundle. A file inside the image cannot outlive it.
|
||||
*
|
||||
* Read once: the file is part of the image and does not change while the
|
||||
* process runs. `null` outside an image (source checkout, tests), where the env
|
||||
* var and package.json keep deciding as before.
|
||||
*/
|
||||
let cached: string | null | undefined;
|
||||
|
||||
export function imageVersion(file = resolve(__dirname, '../../VERSION')): string | null {
|
||||
if (cached !== undefined) return cached;
|
||||
try {
|
||||
cached = readFileSync(file, 'utf8').trim() || null;
|
||||
} catch {
|
||||
cached = null;
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
/** Test seam: forget the cached read. */
|
||||
export function resetImageVersion(): void {
|
||||
cached = undefined;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export { readEnv, validateEnvAtBoot } from './env';
|
||||
export { getAppUrl, getMcpSafeUrl } from './app-url';
|
||||
export { runningVersion } from './running-version';
|
||||
export type { AppEnv, RawEnv } from './env';
|
||||
export {
|
||||
deriveAll,
|
||||
@@ -17,9 +18,12 @@ export {
|
||||
deriveWebauthn,
|
||||
deriveIntegrations,
|
||||
deriveBackup,
|
||||
deriveFiles,
|
||||
deriveDb,
|
||||
derivePaths,
|
||||
deriveNet,
|
||||
derivePush,
|
||||
} from './derive';
|
||||
export * from './parsers';
|
||||
export { envSchema } from './env.schema';
|
||||
export { resolveDataPaths, SERVER_ROOT, type DataPaths } from './data-paths';
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { LogLevel } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* LOG_LEVEL → the Nest logger levels `NestFactory.create` should keep.
|
||||
*
|
||||
* Nest's built-in logger ignores LOG_LEVEL and prints everything, so every
|
||||
* boot wrote its full route map (`RouterExplorer`/`RoutesResolver`/
|
||||
* `InstanceLoader`, ~700 lines) no matter what the operator asked for — and
|
||||
* every e2e boot in the test suite did the same, which is most of what a
|
||||
* green CI log was made of. The file logger (`nest/audit/audit-log.logger.ts`)
|
||||
* already ranks error < warn < info < debug; this is the same ladder expressed
|
||||
* in Nest's vocabulary. Unset or unknown falls back to `info`, as index.ts does.
|
||||
*/
|
||||
export function nestLogLevels(logLevel: string | undefined): LogLevel[] {
|
||||
switch ((logLevel ?? 'info').toLowerCase()) {
|
||||
case 'error':
|
||||
return ['fatal', 'error'];
|
||||
case 'warn':
|
||||
return ['fatal', 'error', 'warn'];
|
||||
case 'debug':
|
||||
return ['fatal', 'error', 'warn', 'log', 'debug', 'verbose'];
|
||||
default:
|
||||
return ['fatal', 'error', 'warn', 'log'];
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
/**
|
||||
* Pure env-string coercion helpers shared by the whole config layer (derive.ts,
|
||||
* env.schema.ts) and — until their call sites migrate — by legacy readers like
|
||||
* src/mcp/config.ts. Kept free of imports so units can test them in isolation.
|
||||
* env.schema.ts). Kept free of imports so units can test them in isolation.
|
||||
*
|
||||
* Each helper reproduces a coercion family that already exists in the codebase.
|
||||
* Parity is law: do NOT "fix" a family's quirks here (e.g. `numberOr` treating
|
||||
@@ -102,7 +101,6 @@ export function parseDurationMs(value: string): number | null {
|
||||
/**
|
||||
* Session idle TTL in SECONDS via MCP_SESSION_TTL, default 1 hour, clamped to
|
||||
* 24h so a milliseconds-value typo can't produce a 1000-hour session.
|
||||
* (Same contract as src/mcp/config.ts, which commit 7 retires in favor of this.)
|
||||
*/
|
||||
export function resolveSessionTtlMs(raw: string | undefined): number {
|
||||
const parsed = Number.parseInt(raw ?? '');
|
||||
@@ -201,7 +199,10 @@ export function synchronousName(level: unknown): string {
|
||||
export function parseLinkLocalAllowList(raw: string | undefined): { ips: string[]; invalid: string[] } {
|
||||
const ips: string[] = [];
|
||||
const invalid: string[] = [];
|
||||
for (const entry of (raw ?? '').split(',').map((e) => e.trim()).filter(Boolean)) {
|
||||
for (const entry of (raw ?? '')
|
||||
.split(',')
|
||||
.map((e) => e.trim())
|
||||
.filter(Boolean)) {
|
||||
const m = /^169\.254\.(\d{1,3})\.(\d{1,3})$/.exec(entry);
|
||||
const canonical = m !== null && [m[1], m[2]].every((o) => String(Number(o)) === o && Number(o) <= 255);
|
||||
if (canonical && m[1] !== '169' && m[1] !== '170') ips.push(entry);
|
||||
@@ -209,3 +210,46 @@ export function parseLinkLocalAllowList(raw: string | undefined): { ips: string[
|
||||
}
|
||||
return { ips, invalid };
|
||||
}
|
||||
|
||||
// ── Web Push key material ──────────────────────────────────────────────────
|
||||
|
||||
const BASE64URL = /^[A-Za-z0-9_-]+={0,2}$/;
|
||||
|
||||
/**
|
||||
* Strict base64url decode, null for anything that is not base64url. Web Push
|
||||
* keys arrive in this alphabet from the browser and from the VAPID_* variables.
|
||||
* Buffer.from(value, 'base64url') alone skips characters it does not know, so a
|
||||
* mangled key would decode to fewer bytes instead of being refused, and the size
|
||||
* checks below would then report the wrong problem.
|
||||
*/
|
||||
export function decodeBase64Url(value: string): Buffer | null {
|
||||
const trimmed = value.trim();
|
||||
if (!BASE64URL.test(trimmed)) return null;
|
||||
return Buffer.from(trimmed, 'base64url');
|
||||
}
|
||||
|
||||
/** An uncompressed P-256 point: 65 bytes, the first one 0x04 (VAPID public key, subscription p256dh). */
|
||||
export function isUncompressedP256Key(value: string): boolean {
|
||||
const bytes = decodeBase64Url(value);
|
||||
return bytes?.length === 65 && bytes[0] === 0x04;
|
||||
}
|
||||
|
||||
/** A P-256 private scalar as the Web Push tools print it: 32 bytes. */
|
||||
export function isP256PrivateKey(value: string): boolean {
|
||||
return decodeBase64Url(value)?.length === 32;
|
||||
}
|
||||
|
||||
/**
|
||||
* The VAPID `sub` claim (RFC 8292 section 2.1): a mailto: address or an https:
|
||||
* URL. Apple refuses anything else, and so does this check, so a subject that
|
||||
* boots is one every push service accepts.
|
||||
*/
|
||||
export function isVapidSubject(value: string): boolean {
|
||||
const trimmed = value.trim();
|
||||
if (/^mailto:[^\s@]+@[^\s@]+$/i.test(trimmed)) return true;
|
||||
try {
|
||||
return new URL(trimmed).protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { readEnv } from './env';
|
||||
|
||||
/**
|
||||
* The running TREK version: the image's VERSION file or APP_VERSION (both behind
|
||||
* `readEnv().app.appVersion`), else server/package.json. The websocket welcome
|
||||
* frame and the plugin host-compatibility checks both announce it, so it lives
|
||||
* here rather than inside either domain.
|
||||
*/
|
||||
export function runningVersion(): string {
|
||||
return readEnv().app.appVersion || (require('../../package.json') as { version: string }).version;
|
||||
}
|
||||
+93
-29
@@ -1,24 +1,30 @@
|
||||
import nodeHttp from 'node:http';
|
||||
import express from 'express';
|
||||
import type { Request, Response, NextFunction, RequestHandler } from 'express';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ExpressAdapter } from '@nestjs/platform-express';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import { AppModule } from './nest/app.module';
|
||||
import { httpConfig } from './nest/app-config';
|
||||
import { readEnv } from './app-config';
|
||||
import { nestLogLevels } from './app-config/nest-log-levels';
|
||||
import { applyGlobalMiddleware, routingCspOrigins } from './middleware/globalMiddleware';
|
||||
import { SettingsService } from './nest/settings/settings.service';
|
||||
import { applyPlatformUploads, applyPlatformStatic } from './nest/platform/platform.routes';
|
||||
import { httpConfig } from './nest/app-config';
|
||||
import { AppModule } from './nest/app.module';
|
||||
import { apiDocsEnabled } from './nest/common/api-docs.kill-switch';
|
||||
import { validateBodyContracts } from './nest/common/validate-body-contracts';
|
||||
import { validateManagedRoutes } from './nest/common/validate-managed-routes';
|
||||
import { validateRouteGuards } from './nest/common/validate-route-guards';
|
||||
import { DatabaseLifecycle } from './nest/database/database-lifecycle.service';
|
||||
import { withRequestContext } from './nest/database/request-context';
|
||||
import { setupApiDocs } from './nest/platform/api-docs';
|
||||
import { MCP_METADATA_MIDDLEWARE } from './nest/platform/mcp-metadata.middleware';
|
||||
import { validateBodyContracts } from './nest/common/validate-body-contracts';
|
||||
import { validateRouteGuards } from './nest/common/validate-route-guards';
|
||||
import { validateManagedRoutes } from './nest/common/validate-managed-routes';
|
||||
import { applyPlatformUploads, applyPlatformStatic } from './nest/platform/platform.routes';
|
||||
import { TrekWsAdapter } from './nest/realtime/trek-ws.adapter';
|
||||
import { SettingsService } from './nest/settings/settings.service';
|
||||
import { StorageService } from './nest/storage/storage.service';
|
||||
import { MAX_COLLECTION_FILE_BYTES } from '@trek/shared';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ExpressAdapter } from '@nestjs/platform-express';
|
||||
import { MAX_COLLECTION_FILE_BYTES, TOUR_WRITE_MAX_BYTES } from '@trek/shared';
|
||||
|
||||
import express from 'express';
|
||||
import type { Request, Response, NextFunction, RequestHandler } from 'express';
|
||||
import nodeHttp from 'node:http';
|
||||
|
||||
/**
|
||||
* Builds the unified TREK NestJS application that serves the ENTIRE surface — the
|
||||
@@ -54,6 +60,13 @@ import { MAX_COLLECTION_FILE_BYTES } from '@trek/shared';
|
||||
*/
|
||||
let boundHttpServer: nodeHttp.Server | null = null;
|
||||
|
||||
/**
|
||||
* The provider that owns the database connection, for index.ts to close it on
|
||||
* shutdown. Re-exported so index.ts reaches it through the one module it loads
|
||||
* after a first-boot restore.
|
||||
*/
|
||||
export { DatabaseLifecycle };
|
||||
|
||||
/**
|
||||
* The http server buildApp created and bound the ws gateway to.
|
||||
*
|
||||
@@ -66,11 +79,37 @@ export function getHttpServer(): nodeHttp.Server {
|
||||
return boundHttpServer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep-alive behind a reverse proxy. Node's default is to drop an idle
|
||||
* keep-alive connection after 5 s, while proxies keep their upstream
|
||||
* connections for about a minute: a proxy that reuses a socket Node has just
|
||||
* closed answers that request with a 502, intermittently and with nothing in
|
||||
* TREK's log. The headers timeout stays above the keep-alive one, so a
|
||||
* connection waiting for its next request is never cut by the wrong timer.
|
||||
*/
|
||||
export function applyProxyTimeouts(server: nodeHttp.Server, keepAliveTimeoutMs: number): void {
|
||||
server.keepAliveTimeout = keepAliveTimeoutMs;
|
||||
server.headersTimeout = keepAliveTimeoutMs + 1_000;
|
||||
}
|
||||
|
||||
export async function buildApp(): Promise<INestApplication> {
|
||||
// rawBody keeps the unparsed request bytes on req.rawBody so a plugin webhook
|
||||
// route can verify a provider's HMAC signature over the exact payload (the
|
||||
// parsed JSON alone can't be re-serialised byte-for-byte).
|
||||
const app = await NestFactory.create(AppModule, new ExpressAdapter(), { rawBody: true });
|
||||
// `logger` is the only place Nest's own logger learns about LOG_LEVEL; without
|
||||
// it every boot prints its full route map whatever the operator asked for.
|
||||
const app = await NestFactory.create(AppModule, new ExpressAdapter(), {
|
||||
rawBody: true,
|
||||
logger: nestLogLevels(readEnv().app.logLevel),
|
||||
});
|
||||
// Schema first, before ANY consumer reads it. The connection lifecycle is the
|
||||
// DatabaseLifecycle provider's: it opens the connection (the ORM's first
|
||||
// connect usually already has), binds the ORM to later swaps, and runs the
|
||||
// legacy baseline, the migrations and the seeders. That is async, so this is
|
||||
// the earliest point it can happen. It has to stay above the SettingsService
|
||||
// resolution below, which is the boot's first DB read.
|
||||
const orm = app.get(MikroORM);
|
||||
await app.get(DatabaseLifecycle).open();
|
||||
const instance = app.getHttpAdapter().getInstance();
|
||||
// The http server is created HERE, not by the caller after buildApp returns,
|
||||
// and that ordering is the whole point: Nest binds gateways during app.init(),
|
||||
@@ -80,30 +119,31 @@ export async function buildApp(): Promise<INestApplication> {
|
||||
// boot succeeds, the gateway logs as registered, every test passes, and no
|
||||
// browser can connect. Callers take the server from getHttpServer() below.
|
||||
boundHttpServer = nodeHttp.createServer(instance);
|
||||
app.useWebSocketAdapter(new TrekWsAdapter(boundHttpServer));
|
||||
// ConfigModule.forRoot's load factories already ran inside NestFactory.create,
|
||||
// so the boot-stable snapshot is resolvable here, BEFORE app.init() — this is
|
||||
// so the boot-stable snapshot is resolvable here, BEFORE app.init(); this is
|
||||
// the one bridge that lets the pre-init Express layer consume the validated
|
||||
// config instead of reading process.env itself.
|
||||
const http = app.get<ConfigType<typeof httpConfig>>(httpConfig.KEY);
|
||||
applyProxyTimeouts(boundHttpServer, http.keepAliveTimeoutMs);
|
||||
app.useWebSocketAdapter(new TrekWsAdapter(boundHttpServer, orm));
|
||||
// Same pre-init bridge: a self-hosted routing engine has to be named in connect-src, or
|
||||
// the browser blocks every request to it without an error the app could report. Both
|
||||
// engines go through the same door — the second one answers the avoidance questions
|
||||
// the first cannot, and is blocked just as silently when the policy leaves it out.
|
||||
const settings = app.get(SettingsService, { strict: false });
|
||||
const defaults = settings?.getAdminUserDefaults();
|
||||
// Boot runs outside any HTTP request, so there is no per-request EntityManager
|
||||
// yet and `allowGlobalContext` is off in production: every repository-backed
|
||||
// read at boot goes through D6's explicit context (see request-context.ts).
|
||||
const defaults = await withRequestContext(orm, () => settings?.getAdminUserDefaults());
|
||||
const asUrl = (value: unknown) => (typeof value === 'string' ? value : null);
|
||||
applyGlobalMiddleware(instance, {
|
||||
http,
|
||||
extraConnectSrc: routingCspOrigins([
|
||||
asUrl(defaults?.routing_base_url),
|
||||
asUrl(defaults?.valhalla_base_url),
|
||||
]),
|
||||
extraConnectSrc: routingCspOrigins([asUrl(defaults?.routing_base_url), asUrl(defaults?.valhalla_base_url)]),
|
||||
});
|
||||
// Same pre-init consumption bridge as httpConfig above: the StorageService
|
||||
// instance is resolvable before init, and the handlers only *register* here —
|
||||
// per-request resolution runs after app.init() completed the registry load.
|
||||
applyPlatformUploads(instance, app.get(StorageService));
|
||||
applyPlatformUploads(instance, app.get(StorageService), orm);
|
||||
// The SDK discovery router (+ its addon gate). Container-built so its deps
|
||||
// are injected (same pre-init consumption bridge as httpConfig above), but
|
||||
// applied here as a PATHLESS app.use: the SDK router matches absolute
|
||||
@@ -131,7 +171,7 @@ export async function buildApp(): Promise<INestApplication> {
|
||||
if (Buffer.isBuffer(buffer)) (req as Request & { rawBody?: Buffer }).rawBody = buffer;
|
||||
};
|
||||
/*
|
||||
* ── Why one route gets a larger body than the rest ───────────────────
|
||||
* ── Why a few routes get a larger body than the rest ─────────────────
|
||||
*
|
||||
* A hundred kilobytes is the right ceiling for an API of forms and ids, and
|
||||
* it is the wrong one for a photo book. A Studio document is sent WHOLE on
|
||||
@@ -151,28 +191,52 @@ export async function buildApp(): Promise<INestApplication> {
|
||||
* GPX of anybody who uses OsmAnd (#2301). The three routes that carry one,
|
||||
* the import into a new list, the GPX reader and the import into a list that
|
||||
* already exists, are measured against that megabyte, doubled for the JSON
|
||||
* escaping of a document full of quotes. Everything else keeps the tighter
|
||||
* limit.
|
||||
* escaping of a document full of quotes.
|
||||
*
|
||||
* A tour is the third. Creating or editing one sends it whole: the full line
|
||||
* with its heights, and every fixed leg's own line besides, about fifty bytes
|
||||
* a point. A ride along a signposted horse route (HOR-01) is a few thousand
|
||||
* points from OpenStreetMap, and one section of it alone can pass a hundred
|
||||
* kilobytes, so those two routes are measured against TOUR_WRITE_MAX_BYTES.
|
||||
* The planner's unsaved draft carries the same points and fixed legs (its
|
||||
* contract caps it at TOUR_DRAFT_MAX_CHARS), so its write takes that ceiling
|
||||
* too. Everything else keeps the tighter limit.
|
||||
*/
|
||||
const bookBody = express.json({ limit: '8mb', verify: rawBodyKeeper });
|
||||
const listFileBody = express.json({ limit: MAX_COLLECTION_FILE_BYTES * 2, verify: rawBodyKeeper });
|
||||
const tourBody = express.json({ limit: TOUR_WRITE_MAX_BYTES, verify: rawBodyKeeper });
|
||||
const json = express.json({ limit: '100kb', verify: rawBodyKeeper });
|
||||
const urlencoded = express.urlencoded({ limit: '100kb', extended: true, verify: rawBodyKeeper });
|
||||
const isMcp = (req: Request) => req.path === '/mcp' || req.path === '/mcp/';
|
||||
const isBookWrite = (req: Request) =>
|
||||
req.method === 'PUT' && /^\/api\/journeys\/\d+\/book$/.test(req.path);
|
||||
const isBookWrite = (req: Request) => req.method === 'PUT' && /^\/api\/journeys\/\d+\/book$/.test(req.path);
|
||||
const isListFile = (req: Request) =>
|
||||
req.method === 'POST' && /^\/api\/addons\/collections\/(import|gpx\/read|\d+\/import)$/.test(req.path);
|
||||
const isTourWrite = (req: Request) =>
|
||||
(req.method === 'POST' && /^\/api\/trips\/\d+\/tours$/.test(req.path)) ||
|
||||
(req.method === 'PUT' && /^\/api\/trips\/\d+\/tours\/\d+$/.test(req.path)) ||
|
||||
(req.method === 'PUT' && /^\/api\/trips\/\d+\/tour-draft$/.test(req.path));
|
||||
|
||||
instance.use(function jsonParser(req: Request, res: Response, next: NextFunction) {
|
||||
if (isBookWrite(req)) return bookBody(req, res, next);
|
||||
if (isListFile(req)) return listFileBody(req, res, next);
|
||||
if (isTourWrite(req)) return tourBody(req, res, next);
|
||||
return isMcp(req) ? next() : json(req, res, next);
|
||||
});
|
||||
instance.use(function urlencodedParser(req: Request, res: Response, next: NextFunction) {
|
||||
return isMcp(req) ? next() : urlencoded(req, res, next);
|
||||
});
|
||||
if (apiDocsEnabled()) setupApiDocs(app);
|
||||
// The per-request EntityManager fork every Nest route runs inside (D6). This
|
||||
// used to be @mikro-orm/nestjs's own middleware, which Nest 11 mounts as an
|
||||
// app.all('/{*all}') route: Express decodes the wildcard param before the
|
||||
// handler runs, so a malformed %-escape anywhere (GET /uploads/avatars/%ZZ)
|
||||
// died as a 400 "Failed to decode param" instead of falling through to the
|
||||
// 404 envelope (UPLOADS-P16). A pathless app.use has no param to decode.
|
||||
// Registered last before init, where the module middleware used to sit.
|
||||
// AppModule turns the module's own registration off (registerRequestContext).
|
||||
instance.use(function mikroOrmRequestContext(_req: Request, _res: Response, next: NextFunction) {
|
||||
withRequestContext(orm, next);
|
||||
});
|
||||
await app.init();
|
||||
// Fail closed on unvalidated mutation bodies: every POST/PUT/PATCH @Body()
|
||||
// must carry a createZodDto class (validated by the global ZodValidationPipe)
|
||||
|
||||
+45
-10
@@ -1,10 +1,10 @@
|
||||
import { readEnv } from './app-config';
|
||||
import { resolveDataPaths } from './app-config/data-paths';
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { readEnv } from './app-config';
|
||||
|
||||
const dataDir = path.resolve(__dirname, '../data');
|
||||
const jwtSecretFile = path.join(dataDir, '.jwt_secret');
|
||||
const { dataDir, jwtSecretFile, encryptionKeyFile: encKeyFile } = resolveDataPaths();
|
||||
|
||||
// ENCRYPTION_KEY is used to derive at-rest encryption keys for stored secrets
|
||||
// (API keys, MFA TOTP secrets, SMTP password, OIDC client secret, etc.).
|
||||
@@ -20,18 +20,51 @@ const jwtSecretFile = path.join(dataDir, '.jwt_secret');
|
||||
// data/.encryption_key so JWT rotation can never break decryption later.
|
||||
// 4. Auto-generated — fresh install with none of the above; persisted to
|
||||
// data/.encryption_key.
|
||||
const encKeyFile = path.join(dataDir, '.encryption_key');
|
||||
let _encryptionKey: string = process.env.ENCRYPTION_KEY || '';
|
||||
|
||||
if (_encryptionKey) {
|
||||
// Env var is set explicitly — persist it to file so the value survives
|
||||
// container restarts even if the env var is later removed.
|
||||
// Under test the suite sets its own fixed ENCRYPTION_KEY. Comparing it with, or
|
||||
// writing it over, the developer's own data/.encryption_key would either stop
|
||||
// every test run or quietly replace the key a local dev server encrypts with.
|
||||
const keyFileFollowsEnv = process.env.NODE_ENV !== 'test';
|
||||
|
||||
/**
|
||||
* Persist an explicit ENCRYPTION_KEY to the key file, so the value survives
|
||||
* container restarts even if the env var is later removed.
|
||||
*
|
||||
* A key file that disagrees with the env var means every stored secret was
|
||||
* encrypted with the file's key. Booting would make them unreadable and the
|
||||
* write would destroy the only copy of that key, which is exactly what a
|
||||
* regenerated Helm secret or a typo in the variable used to do in silence. The
|
||||
* rotation script updates the file, so a real rotation never lands here.
|
||||
*/
|
||||
function persistEnvKey(envKey: string): void {
|
||||
let storedKey = '';
|
||||
try {
|
||||
storedKey = fs.readFileSync(encKeyFile, 'utf8').trim();
|
||||
} catch {
|
||||
// No readable file yet: nothing to protect, the env value becomes the file.
|
||||
}
|
||||
if (storedKey && storedKey !== envKey.trim()) {
|
||||
console.error(`FATAL: ENCRYPTION_KEY does not match ${encKeyFile}.`);
|
||||
console.error(
|
||||
'The stored secrets are encrypted with the key in that file, so TREK will not start with a different one.',
|
||||
);
|
||||
console.error(
|
||||
'To change the key, run scripts/migrate-encryption.ts first; it re-encrypts the secrets and updates the file.',
|
||||
);
|
||||
console.error('Otherwise set ENCRYPTION_KEY back to the value in the file, or remove the variable.');
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
|
||||
fs.writeFileSync(encKeyFile, _encryptionKey, { mode: 0o600 });
|
||||
fs.writeFileSync(encKeyFile, envKey, { mode: 0o600 });
|
||||
} catch {
|
||||
// Non-fatal: env var is the source of truth when set.
|
||||
}
|
||||
}
|
||||
|
||||
if (_encryptionKey) {
|
||||
if (keyFileFollowsEnv) persistEnvKey(_encryptionKey);
|
||||
} else {
|
||||
// Try the dedicated key file first (covers all installs after first start).
|
||||
try {
|
||||
@@ -51,7 +84,9 @@ if (_encryptionKey) {
|
||||
if (code === 'EISDIR') {
|
||||
// Compose creating a missing bind-mount source as a directory is by far
|
||||
// the most common way this file stops being a file.
|
||||
console.error('EISDIR: the path is a directory. A bind mount pointed at data/.encryption_key created it as one — remove it and mount the data directory instead.');
|
||||
console.error(
|
||||
'EISDIR: the path is a directory. A bind mount pointed at data/.encryption_key created it as one — remove it and mount the data directory instead.',
|
||||
);
|
||||
}
|
||||
console.error('Fix the file permissions or set ENCRYPTION_KEY explicitly.');
|
||||
process.exit(1);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import Database from 'better-sqlite3';
|
||||
|
||||
/**
|
||||
* Opens a SQLite connection. Every handle the server opens comes from here (the
|
||||
* main database, each plugin's own database, a backup being checked before a
|
||||
* restore), so what has to hold for all of them is set in one place. A Buffer
|
||||
* opens a serialized database in memory (the test schema snapshot).
|
||||
*
|
||||
* Temporary storage stays in memory. Statement journals, sort runs and transient
|
||||
* indices move to a temp file once they outgrow a small in-memory buffer, and
|
||||
* SQLite looks for a directory to hold that file in SQLITE_TMPDIR, TMPDIR,
|
||||
* /var/tmp, /usr/tmp, /tmp and the working directory. A container with a
|
||||
* read-only root filesystem and no tmpfs on /tmp has none of them writable, so
|
||||
* the first statement that needs a temp file fails with SQLITE_IOERR_GETTEMPPATH.
|
||||
* Deleting a trip is where that showed: the cascade keeps a statement journal
|
||||
* larger than the 64 KiB SQLite holds before it spills to disk (#2518).
|
||||
*
|
||||
* The data directory is the only place TREK can count on being able to write,
|
||||
* and SQLite has no supported per-connection way to put temp files there, so
|
||||
* they stay in RAM. The shipped compose file already had them there, its /tmp
|
||||
* being a tmpfs. VACUUM INTO, the only VACUUM TREK runs, writes straight into
|
||||
* its target file and builds no temporary database.
|
||||
*/
|
||||
export function openDatabase(filename: string | Buffer, options?: Database.Options): Database.Database {
|
||||
const db = new Database(filename, options);
|
||||
db.pragma('temp_store = MEMORY');
|
||||
return db;
|
||||
}
|
||||
+140
-129
@@ -1,172 +1,183 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { readEnv } from '../app-config';
|
||||
import { openDatabase } from './connection';
|
||||
import { resolveDbPath } from './db-path';
|
||||
import { applyDurabilityPragmas } from './durability';
|
||||
import { createTables } from './schema';
|
||||
import { runMigrations } from './migrations';
|
||||
import { runSeeds } from './seeds';
|
||||
import { Place, Tag } from '../types';
|
||||
import { readSchemaSnapshot } from './schema-snapshot';
|
||||
|
||||
// In test mode each vitest worker gets an isolated in-memory DB so that
|
||||
// parallel forks can't race on the same file or share migration state.
|
||||
const isTest = readEnv().app.isTest;
|
||||
|
||||
let dbPath: string;
|
||||
if (isTest) {
|
||||
dbPath = ':memory:';
|
||||
} else if (readEnv().db.trekDbFile) {
|
||||
// Explicit DB file (used by the Playwright E2E harness to run against an
|
||||
// isolated, throwaway database instead of the real data/travel.db). Purely
|
||||
// additive — when unset the default path below is used exactly as before.
|
||||
dbPath = readEnv().db.trekDbFile!;
|
||||
const dir = path.dirname(dbPath);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
} else {
|
||||
const dataDir = path.join(__dirname, '../../data');
|
||||
if (!fs.existsSync(dataDir)) {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
dbPath = path.join(dataDir, 'travel.db');
|
||||
}
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
let _db: Database.Database | null = null;
|
||||
/**
|
||||
* Set by `closeDb()`, cleared by `openDb()`. A handle that was never opened is
|
||||
* opened on first use; one that was closed on purpose (a restore swapping the
|
||||
* file, the shutdown) stays closed until somebody reopens it, so nothing can
|
||||
* quietly reconnect to a file that is being replaced.
|
||||
*/
|
||||
let closedOnPurpose = false;
|
||||
|
||||
function initDb(): void {
|
||||
if (_db) {
|
||||
try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
|
||||
try { _db.close(); } catch (e) {}
|
||||
_db = null;
|
||||
}
|
||||
|
||||
_db = new Database(dbPath);
|
||||
/**
|
||||
* Opens the connection and applies the pragmas. It deliberately does NOT build
|
||||
* the schema: migrations and seeding are MikroORM's job and run from
|
||||
* `db/orm.ts` when `DatabaseLifecycle.open()` (`nest/database/`) is called by
|
||||
* `buildApp()`, because the migrator is async.
|
||||
*
|
||||
* Nothing calls this at import any more. The first reader opens it: in
|
||||
* production that is the ORM's first connect inside `NestFactory.create()`,
|
||||
* which is still after `index.ts` ran a first-boot restore. Opening an open
|
||||
* connection is a no-op.
|
||||
*
|
||||
* In test mode there is no `buildApp()` for the handful of suites that use this
|
||||
* singleton directly, so those open a copy of a schema snapshot the vitest
|
||||
* global setup migrated once for the whole run.
|
||||
*/
|
||||
function openDb(): void {
|
||||
if (_db) return;
|
||||
// Resolved here rather than at import, so loading the module touches neither
|
||||
// the environment nor the data directory.
|
||||
const dbPath = resolveDbPath();
|
||||
const snapshot = readEnv().app.isTest ? readSchemaSnapshot() : null;
|
||||
const handle = openDatabase(snapshot ?? dbPath);
|
||||
// Ahead of the journal switch now: changing journal_mode needs an exclusive
|
||||
// lock, which a sibling process (reset-admin, the rotation script) may hold.
|
||||
_db.exec('PRAGMA busy_timeout = 5000');
|
||||
const durability = applyDurabilityPragmas(_db);
|
||||
_db.exec('PRAGMA foreign_keys = ON');
|
||||
// Reported so an operator can see whether their setting took — the test DB is
|
||||
handle.exec('PRAGMA busy_timeout = 5000');
|
||||
const durability = applyDurabilityPragmas(handle);
|
||||
handle.exec('PRAGMA foreign_keys = ON');
|
||||
_db = handle;
|
||||
closedOnPurpose = false;
|
||||
// Reported so an operator can see whether their setting took. The test DB is
|
||||
// :memory: and has no journal file, so there is nothing to report there.
|
||||
if (dbPath !== ':memory:') {
|
||||
console.log(`[DB] journal_mode=${durability.journalMode}, synchronous=${durability.synchronous}`);
|
||||
}
|
||||
|
||||
createTables(_db);
|
||||
runMigrations(_db);
|
||||
|
||||
runSeeds(_db);
|
||||
}
|
||||
|
||||
initDb();
|
||||
/** The open handle, opening it on first use. Throws while it is closed on purpose. */
|
||||
function current(): Database.Database {
|
||||
if (!_db && !closedOnPurpose) openDb();
|
||||
if (!_db) throw new Error('Database connection is not available (restore in progress?)');
|
||||
return _db;
|
||||
}
|
||||
|
||||
/**
|
||||
* The live better-sqlite3 handle, for the MikroORM dialect in `orm-driver.ts`.
|
||||
*
|
||||
* Deliberately not the `db` Proxy below: Kysely holds whatever it is given for
|
||||
* the life of its client, and a Proxy would hide the swap a restore performs.
|
||||
* The driver calls this on every connect so it always binds the current handle.
|
||||
*/
|
||||
function getRawConnection(): Database.Database {
|
||||
return current();
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan 4 Task 4 deleted `DatabaseService`/`DatabaseModule` and every `src/`
|
||||
* importer of this Proxy is gone — but the export itself stays, deliberately:
|
||||
* ~190 test files' `vi.mock('…/db/database', …)` factories return a
|
||||
* `{ db: <mock handle>, … }` shape (`buildDbMock`/the ad-hoc equivalents),
|
||||
* and their own `import { db as testDb } from '…/db/database'` line is typed
|
||||
* against THIS file's real exports, not the runtime mock — Vitest's
|
||||
* `vi.mock` swaps the module at runtime, but `tsc` resolves the import
|
||||
* statically regardless. Deleting this export makes every one of those
|
||||
* files fail `typecheck:tests` even though none of them use the exported
|
||||
* Proxy in production. That test-harness idiom is Track B's own territory
|
||||
* (5a/5b/5c's "e2e pattern"), not enumerated in this task's file set —
|
||||
* left for a follow-up that swaps the idiom, not deleted out from under it.
|
||||
* `src/` never imports it, so ESLint's `no-restricted-imports` shrink still
|
||||
* holds this file to its permanent allow-list entry (rule 4) regardless.
|
||||
*/
|
||||
const db = new Proxy({} as Database.Database, {
|
||||
get(_, prop: string | symbol) {
|
||||
if (!_db) throw new Error('Database connection is not available (restore in progress?)');
|
||||
const val = (_db as unknown as Record<string | symbol, unknown>)[prop];
|
||||
return typeof val === 'function' ? val.bind(_db) : val;
|
||||
const handle = current();
|
||||
const val = (handle as unknown as Record<string | symbol, unknown>)[prop];
|
||||
return typeof val === 'function' ? val.bind(handle) : val;
|
||||
},
|
||||
set(_, prop: string | symbol, val: unknown) {
|
||||
(_db as unknown as Record<string | symbol, unknown>)[prop] = val;
|
||||
(current() as unknown as Record<string | symbol, unknown>)[prop] = val;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
if (readEnv().demo.enabled) {
|
||||
/**
|
||||
* Demo seeding, which used to run here at module load.
|
||||
*
|
||||
* It has to follow the schema now: `demo-seed.ts` inserts places against
|
||||
* hard-coded category ids 1-9, and with `foreign_keys = ON` those rows only
|
||||
* resolve once the category seeder has run. Called from the schema bootstrap in
|
||||
* `db/orm.ts`, immediately after the seeders.
|
||||
*/
|
||||
// Plan 3i Task 3: `seedDemoData` converted onto `DemoRepository` (an
|
||||
// EntityManager-backed repository), so it is `async` now and no longer takes
|
||||
// the raw `db` handle — it resolves its EntityManager itself via
|
||||
// `RequestContext.getEntityManager()`, which `runSchemaBootstrap`'s existing
|
||||
// `withRequestContext(orm, () => runDemoSeed())` wrap (`db/orm.ts:59`)
|
||||
// already populates by the time this runs. `runDemoSeed` awaits it now too:
|
||||
// previously both were fully synchronous, so the try/catch below already
|
||||
// caught everything before this function returned; without the `await` a
|
||||
// rejected promise from `seedDemoData` would become an unhandled rejection
|
||||
// instead of the `[Demo] Seed error:` log line this catch has always produced.
|
||||
async function runDemoSeed(): Promise<void> {
|
||||
if (!readEnv().demo.enabled) return;
|
||||
try {
|
||||
const { seedDemoData } = require('../demo/demo-seed');
|
||||
seedDemoData(_db);
|
||||
await seedDemoData();
|
||||
} catch (err: unknown) {
|
||||
console.error('[Demo] Seed error:', err instanceof Error ? err.message : err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets `DatabaseLifecycle` (`nest/database/`) rebuild the ORM's connection when
|
||||
* this module swaps handles, without this module importing the ORM (which
|
||||
* imports this module back).
|
||||
*/
|
||||
let onReinitialize: (() => Promise<void>) | null = null;
|
||||
function registerReinitializeHook(hook: () => Promise<void>): void {
|
||||
onReinitialize = hook;
|
||||
}
|
||||
|
||||
function closeDb(): void {
|
||||
if (_db) {
|
||||
try { _db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
|
||||
try { _db.close(); } catch (e) {}
|
||||
try {
|
||||
_db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
|
||||
} catch (e) {}
|
||||
try {
|
||||
_db.close();
|
||||
} catch (e) {}
|
||||
_db = null;
|
||||
closedOnPurpose = true;
|
||||
console.log('[DB] Database connection closed');
|
||||
}
|
||||
}
|
||||
|
||||
function reinitialize(): void {
|
||||
/**
|
||||
* Reopens the connection after a restore has swapped the file underneath us.
|
||||
*
|
||||
* Async now, because bringing a restored backup up to date means running the
|
||||
* migrations, and the hook also has to rebuild the ORM's Kysely client: it
|
||||
* cached the handle this function is about to replace.
|
||||
*
|
||||
* Production code reaches this through `DatabaseLifecycle.reopen()`; the export
|
||||
* stays for the suites that drive the swap directly and for the mock factories
|
||||
* that stub it.
|
||||
*/
|
||||
async function reinitialize(): Promise<void> {
|
||||
console.log('[DB] Reinitializing database connection after restore...');
|
||||
if (_db) closeDb();
|
||||
initDb();
|
||||
openDb();
|
||||
if (onReinitialize) await onReinitialize();
|
||||
console.log('[DB] Database reinitialized successfully');
|
||||
}
|
||||
|
||||
interface PlaceWithCategory extends Place {
|
||||
category_name: string | null;
|
||||
category_color: string | null;
|
||||
category_icon: string | null;
|
||||
}
|
||||
// getPlaceWithTags/canAccessTrip/isOwner and the TripAccess/PlaceWithTags
|
||||
// interfaces lived here through Plan 3c Task 0a's async sweep. Task 0b moved
|
||||
// their bodies onto TripsRepository.findAccessible/isOwner and
|
||||
// PlacesRepository.findWithTagsAndRatings — db/repositories/Trips.repository.ts's
|
||||
// TripAccess is now the single source. Plan 4 Task 4 deleted `DatabaseService`
|
||||
// (its last `src/` consumer) once every caller moved onto a repository, the
|
||||
// `UnitOfWork`, or (for the two whole-database-file statements no
|
||||
// entity/repository call can express) `MaintenanceRepository`/
|
||||
// `DemoRepository`'s own `connection.execute()`. The `db` Proxy itself stays
|
||||
// exported — see its own docstring above for why (~190 test files' static
|
||||
// typecheck, not a production `src/` need).
|
||||
|
||||
interface PlaceWithTags extends Place {
|
||||
category: { id: number; name: string; color: string; icon: string } | null;
|
||||
tags: Tag[];
|
||||
ratings: { user_id: number; username: string; avatar: string | null; rating: number }[];
|
||||
rating_avg: number | null;
|
||||
rating_count: number;
|
||||
}
|
||||
|
||||
function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
|
||||
const place = db.prepare(`
|
||||
SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
|
||||
FROM places p
|
||||
LEFT JOIN categories c ON p.category_id = c.id
|
||||
WHERE p.id = ?
|
||||
`).get(placeId) as PlaceWithCategory | undefined;
|
||||
|
||||
if (!place) return null;
|
||||
|
||||
const tags = db.prepare(`
|
||||
SELECT t.* FROM tags t
|
||||
JOIN place_tags pt ON t.id = pt.tag_id
|
||||
WHERE pt.place_id = ?
|
||||
`).all(placeId) as Tag[];
|
||||
|
||||
// Collaborative ratings (#1435): every voter with username/avatar for the
|
||||
// who-voted tooltip; the displayed value is the average.
|
||||
const ratings = db.prepare(`
|
||||
SELECT pr.user_id, u.username, u.avatar, pr.rating FROM place_ratings pr
|
||||
JOIN users u ON pr.user_id = u.id
|
||||
WHERE pr.place_id = ? ORDER BY pr.created_at
|
||||
`).all(placeId) as { user_id: number; username: string; avatar: string | null; rating: number }[];
|
||||
|
||||
return {
|
||||
...place,
|
||||
category: place.category_id ? {
|
||||
id: place.category_id,
|
||||
name: place.category_name!,
|
||||
color: place.category_color!,
|
||||
icon: place.category_icon!,
|
||||
} : null,
|
||||
tags,
|
||||
ratings,
|
||||
rating_avg: ratings.length > 0 ? ratings.reduce((s, r) => s + r.rating, 0) / ratings.length : null,
|
||||
rating_count: ratings.length,
|
||||
};
|
||||
}
|
||||
|
||||
interface TripAccess {
|
||||
id: number;
|
||||
user_id: number;
|
||||
currency: string | null;
|
||||
}
|
||||
|
||||
function canAccessTrip(tripId: number | string, userId: number): TripAccess | undefined {
|
||||
return db.prepare(`
|
||||
SELECT t.id, t.user_id, t.currency FROM trips t
|
||||
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
|
||||
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
|
||||
`).get(userId, tripId, userId) as TripAccess | undefined;
|
||||
}
|
||||
|
||||
function isOwner(tripId: number | string, userId: number): boolean {
|
||||
return !!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId);
|
||||
}
|
||||
|
||||
|
||||
export { db, closeDb, reinitialize, getPlaceWithTags, canAccessTrip, isOwner };
|
||||
export type { TripAccess, PlaceWithTags };
|
||||
export { db, openDb, closeDb, reinitialize, getRawConnection, registerReinitializeHook, runDemoSeed };
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { readEnv } from '../app-config';
|
||||
import { resolveDataPaths } from '../app-config/data-paths';
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* The SQLite file this process talks to.
|
||||
*
|
||||
* Shared by `database.ts` (which opens the connection) and `mikro-orm.config.ts`
|
||||
* (which needs the same target for the CLI and for the Nest-owned ORM). Kept in
|
||||
* one place because a config that names a different file than the connection is
|
||||
* the kind of mistake that only shows up as an empty database.
|
||||
*
|
||||
* Creates the containing directory as a side effect, exactly as the original
|
||||
* inline block in `database.ts` did.
|
||||
*/
|
||||
export function resolveDbPath(): string {
|
||||
// In test mode each vitest worker gets an isolated in-memory DB so that
|
||||
// parallel forks can't race on the same file or share migration state.
|
||||
if (readEnv().app.isTest) return ':memory:';
|
||||
|
||||
// TREK_DB_FILE (the Playwright E2E harness runs against a throwaway file this
|
||||
// way) or data/travel.db, both resolved by the one data layout.
|
||||
const file = resolveDataPaths().dbFile;
|
||||
const dir = path.dirname(file);
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
return file;
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import {
|
||||
isKnownPlatform,
|
||||
isPostgres,
|
||||
isSqlite,
|
||||
PG_ISO_DATE_PREFIX,
|
||||
PG_TIMESTAMP_FORMAT,
|
||||
PG_UTC_NOW,
|
||||
pgTimestampText,
|
||||
unsupported,
|
||||
} from './platform';
|
||||
import type { Platform } from '@mikro-orm/core';
|
||||
|
||||
import {
|
||||
sql,
|
||||
type Expression,
|
||||
type ExpressionBuilder,
|
||||
type ExpressionWrapper,
|
||||
type RawBuilder,
|
||||
type ReferenceExpression,
|
||||
type SqlBool,
|
||||
type StringReference,
|
||||
} from 'kysely';
|
||||
|
||||
/**
|
||||
* The Kysely-expression half of the dialect layer: the twins of the MikroORM
|
||||
* `raw()` helpers in `sql-functions.ts`, for statements built with
|
||||
* `this.kysely<...>()`. Same contract as that file: every helper takes the
|
||||
* live MikroORM `Platform`, dispatches on it at runtime and fails closed on a
|
||||
* platform it does not know. Values are bound or validated, never spliced in.
|
||||
*/
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3d Task 0 review (H1/L1) — the helpers in `sql-functions.ts` return a
|
||||
// MikroORM `RawQueryFragment`. Handed into a Kysely statement, a `RawQueryFragment`
|
||||
// stringifies through its own `[Symbol.toPrimitive]('string')` coercion into
|
||||
// the literal text `?` (its parameter-placeholder marker, meant for the
|
||||
// MikroORM QueryBuilder's OWN parameter interpolation, not Kysely's) — Kysely
|
||||
// binds it as an actual `?` value parameter and the statement fails at
|
||||
// execution (verified directly, not assumed: `db.selectFrom(...).where(...,
|
||||
// startsWithIsoDate(platform, 'col'))` throws `SqliteError: near "?": syntax
|
||||
// error` the first time it runs). Task 2 absorbed this finding (its report,
|
||||
// H1/L1) — these are genuinely separate functions, not a wrapper over the
|
||||
// ones above, because a Kysely `Expression` and a MikroORM `RawQueryFragment`
|
||||
// are different types with no conversion between them. Each takes the
|
||||
// caller's own `ExpressionBuilder<DB, TB>` (the same "no consumer-facing
|
||||
// generic DB" shape `_shared/reservation-visibility.ts`'s `publicStayExists`
|
||||
// documents is the only one that survives `tsc` for a shared Kysely helper —
|
||||
// unlike that one, these ARE fully generic over `<DB, TB>`, because they only
|
||||
// ever call `eb.fn`/`eb.cast`/`eb(...)`, none of which hit the QueryBuilder
|
||||
// method-chaining inference limit that forced `publicStayExists` to fix its
|
||||
// shape). Platform-dispatched and fail-closed like every helper in
|
||||
// `sql-functions.ts`; each has an SQLF-0xx test pinning its compiled
|
||||
// `{sql, parameters}` AND a raw-statement equivalence on seeded rows
|
||||
// (`tests/unit/db/dialect/sql-functions.test.ts`), and its Postgres branch is
|
||||
// pinned in `sql-functions.postgres.test.ts` and run by the CI Postgres probe.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The Kysely-expression twin of {@link startsWithIsoDate}: `<ref> GLOB
|
||||
* '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'`, spelled through SQLite's
|
||||
* function form (`glob(X, Y)` is exactly `Y GLOB X` — the inventory's own
|
||||
* §19 finding, since Kysely's `ComparisonOperator` union has no `GLOB`
|
||||
* entry). Returns a boolean `Expression<SqlBool>`, usable in a `.where()`
|
||||
* or inside a `CASE WHEN` condition. Same digit-class pattern as the
|
||||
* MikroORM version — NOT the wider `'????-??-??*'` shorthand (a `?` in
|
||||
* SQLite GLOB matches any character, letters included). On Postgres it is
|
||||
* the anchored regular expression `CAST(<ref> AS text) ~ '^[0-9]{4}-…'`.
|
||||
*/
|
||||
export function startsWithIsoDateKysely<DB, TB extends keyof DB>(
|
||||
platform: Platform,
|
||||
eb: ExpressionBuilder<DB, TB>,
|
||||
ref: ReferenceExpression<DB, TB>,
|
||||
): ExpressionWrapper<DB, TB, SqlBool> {
|
||||
if (isSqlite(platform)) {
|
||||
return eb.fn<SqlBool>('glob', [eb.val('[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'), ref]);
|
||||
}
|
||||
if (isPostgres(platform)) return eb(eb.cast<string>(ref, 'text'), '~', eb.val(PG_ISO_DATE_PREFIX));
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Kysely-expression twin of {@link substring}: `substr(<ref>,
|
||||
* <start>[, <length>])`, 1-based on both ends. `start`/`length` are
|
||||
* validated integers, the same guard `substring()` above applies, and bound
|
||||
* as genuine parameters here (`eb.val`) rather than spelled into the SQL
|
||||
* text — Kysely's `fn()` takes `ReferenceExpression`s, not a raw text
|
||||
* fragment, so there is no equivalent "spell a constant into the SQL"
|
||||
* shape to match; a bound integer literal renders identically. Postgres has
|
||||
* the same `substr` with the same 1-based arguments.
|
||||
*/
|
||||
export function substringKysely<DB, TB extends keyof DB>(
|
||||
platform: Platform,
|
||||
eb: ExpressionBuilder<DB, TB>,
|
||||
ref: ReferenceExpression<DB, TB>,
|
||||
start: number,
|
||||
length?: number,
|
||||
): ExpressionWrapper<DB, TB, string> {
|
||||
if (!Number.isInteger(start) || start < 1) {
|
||||
throw new Error(`sql-functions: substringKysely needs a 1-based integer start, got ${start}`);
|
||||
}
|
||||
if (length !== undefined && (!Number.isInteger(length) || length < 0)) {
|
||||
throw new Error(`sql-functions: substringKysely needs a non-negative integer length, got ${length}`);
|
||||
}
|
||||
if (isKnownPlatform(platform)) {
|
||||
const args: ReferenceExpression<DB, TB>[] =
|
||||
length === undefined ? [ref, eb.val(start)] : [ref, eb.val(start), eb.val(length)];
|
||||
return eb.fn<string>('substr', args);
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** A part of a `concatKysely()` expression — a column reference, a bound value, or a nested Kysely `Expression<string>` (composes freely, unlike `concat()`'s MikroORM `RawQueryFragment` form). */
|
||||
export type KyselyConcatPart<DB, TB extends keyof DB> =
|
||||
{ column: StringReference<DB, TB> } | { value: string } | { expression: Expression<string> };
|
||||
|
||||
/**
|
||||
* The Kysely-expression twin of {@link concat}: `<part> || <part> || …`,
|
||||
* SQLite's/Postgres's string concatenation operator, built through the
|
||||
* expression builder's own binary-operator call (`eb(lhs, '||', rhs)`) so
|
||||
* it composes with {@link substringKysely}/{@link castIntegerKysely} —
|
||||
* exactly the composition `concat()`'s MikroORM form cannot do (its
|
||||
* docstring explains why). On Postgres a bound value part is cast to `text`:
|
||||
* `pg` sends parameters untyped, and `$1 || $2` alone gives the planner no
|
||||
* type to resolve the operator with.
|
||||
*/
|
||||
export function concatKysely<DB, TB extends keyof DB>(
|
||||
platform: Platform,
|
||||
eb: ExpressionBuilder<DB, TB>,
|
||||
...parts: readonly KyselyConcatPart<DB, TB>[]
|
||||
): ExpressionWrapper<DB, TB, string> {
|
||||
if (parts.length < 2) {
|
||||
throw new Error(`sql-functions: concatKysely needs at least two parts, got ${parts.length}`);
|
||||
}
|
||||
if (!isKnownPlatform(platform)) return unsupported(platform);
|
||||
const value = (text: string): Expression<string> =>
|
||||
isPostgres(platform) ? eb.cast<string>(eb.val(text), 'text') : eb.val(text);
|
||||
const operand = (part: KyselyConcatPart<DB, TB>): Expression<string> =>
|
||||
'column' in part ? eb.ref(part.column).$castTo<string>() : 'value' in part ? value(part.value) : part.expression;
|
||||
let acc: Expression<string> = operand(parts[0]!);
|
||||
for (const part of parts.slice(1)) {
|
||||
acc = eb(acc, '||', operand(part));
|
||||
}
|
||||
// The loop above always runs at least once (the `parts.length < 2` guard
|
||||
// above throws otherwise), so `acc` is always the result of the `eb(...)`
|
||||
// binary-operator call — a real `ExpressionWrapper`, not the bare
|
||||
// `Expression` interface `operand()`'s own return type declares.
|
||||
return acc as ExpressionWrapper<DB, TB, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Kysely-expression twin of {@link castInteger}: `CAST(<ref> AS
|
||||
* INTEGER)`, for `reservations.accommodation_id` (TEXT) compared against an
|
||||
* INTEGER column inside a Kysely statement (RS20/RV2's join shape — a
|
||||
* correlated `EXISTS`/scalar-subquery context the MikroORM QueryBuilder
|
||||
* cannot express, per the inventory's own T6 ruling). Postgres refuses to
|
||||
* cast the text `'14.0'` to an integer, so its branch goes through `numeric`
|
||||
* and truncates, as SQLite's cast does: `CAST(trunc(CAST(<ref> AS numeric))
|
||||
* AS integer)`.
|
||||
*/
|
||||
export function castIntegerKysely<DB, TB extends keyof DB>(
|
||||
platform: Platform,
|
||||
eb: ExpressionBuilder<DB, TB>,
|
||||
ref: ReferenceExpression<DB, TB>,
|
||||
): ExpressionWrapper<DB, TB, number> {
|
||||
if (isSqlite(platform)) return eb.cast<number>(ref, 'integer');
|
||||
if (isPostgres(platform)) return eb.cast<number>(eb.fn('trunc', [eb.cast(ref, 'numeric')]), 'integer');
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3g Task 0 (R1) — no consumer yet: Task 1 (`getJourneyFull`'s gallery
|
||||
// read) and Task 3 (`getPublicJourney`'s gallery read) each fold this into
|
||||
// their own rebuild of the legacy `GALLERY_CHRONOLOGICAL_ORDER` (tests/helpers/)
|
||||
// text (a `COALESCE(NULLIF(tp.taken_at, ''), <correlated MIN+concat subquery>,
|
||||
// <this>)` ORDER BY, worked out in full in Task 0's report for both to paste
|
||||
// in verbatim, neither re-deriving it). Added here, Kysely-only (no MikroORM
|
||||
// `raw()` sibling): the shape it exists for is genuinely Kysely-only (a
|
||||
// correlated scalar subquery cannot be expressed through the MikroORM
|
||||
// QueryBuilder — the same "T6 ruling" `castIntegerKysely`'s own docstring
|
||||
// cites for RS20/RV2), and nothing else in this plan's inventory needs a
|
||||
// MikroORM-form epoch-to-ISO conversion (§6: "no other strftime/julianday
|
||||
// sites found elsewhere in this cluster"). A raw twin can be added later,
|
||||
// same as every other helper here, the moment a real consumer needs one.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `strftime('%Y-%m-%dT%H:%M:%SZ', <ref> / 1000, 'unixepoch')` — the last of
|
||||
* `GALLERY_CHRONOLOGICAL_ORDER`'s three fallback tiers (R1): when a gallery
|
||||
* photo has neither a capture time (`tp.taken_at`) nor a linked entry to
|
||||
* borrow a date from, the moment it was added is what is left to order by.
|
||||
* `<ref>` is an epoch-MILLISECONDS column (`journey_photos.created_at`, like
|
||||
* every other `*_at` epoch column in this codebase) — SQLite's `unixepoch`
|
||||
* modifier expects whole SECONDS, so the division is load-bearing, not
|
||||
* decorative, and matches the legacy text's own `gp.created_at / 1000`
|
||||
* exactly. SQLite's `/` on two integers truncates instead of rounding; that
|
||||
* sub-second loss is the legacy statement's own behaviour, preserved here
|
||||
* rather than "fixed" into a float divide that would render a different ISO
|
||||
* string for any timestamp not an exact multiple of 1000ms.
|
||||
*
|
||||
* On Postgres: `to_char(timezone('UTC', to_timestamp(<ref> / 1000)),
|
||||
* 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`. An integer column divided by an integer
|
||||
* truncates there too, so both engines drop the same sub-second part.
|
||||
*
|
||||
* Named for what it computes, not the SQL function it spells — matching
|
||||
* every other `*Kysely` twin in this file (`castIntegerKysely`, not
|
||||
* `castKysely`; `startsWithIsoDateKysely`, not `globKysely`).
|
||||
*/
|
||||
export function unixEpochToIsoKysely<DB, TB extends keyof DB>(
|
||||
platform: Platform,
|
||||
eb: ExpressionBuilder<DB, TB>,
|
||||
ref: ReferenceExpression<DB, TB>,
|
||||
): ExpressionWrapper<DB, TB, string> {
|
||||
if (!isKnownPlatform(platform)) return unsupported(platform);
|
||||
const seconds = eb(ref, '/', eb.val(1000));
|
||||
if (isSqlite(platform)) {
|
||||
return eb.fn<string>('strftime', [eb.val('%Y-%m-%dT%H:%M:%SZ'), seconds, eb.val('unixepoch')]);
|
||||
}
|
||||
const utc = eb.fn('timezone', [eb.cast(eb.val('UTC'), 'text'), eb.fn('to_timestamp', [seconds])]);
|
||||
return eb.fn<string>('to_char', [utc, eb.cast(eb.val('YYYY-MM-DD"T"HH24:MI:SS"Z"'), 'text')]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Kysely-expression twin of {@link nowPlusSeconds}: DS23/DS24's
|
||||
* `ON CONFLICT ... DO UPDATE` / `INSERT ... VALUES` (R3) is a hand-typed
|
||||
* Kysely statement — MikroORM's `em.upsert` cannot express a
|
||||
* partial-unique-index conflict target (R3's own ruling) — so the
|
||||
* `next_attempt_at` computation inside its `CASE WHEN` needs a Kysely
|
||||
* `Expression`, not a MikroORM `RawQueryFragment` (SQLF-048: a
|
||||
* `RawQueryFragment` throws when handed into a Kysely statement). Same
|
||||
* validation, same always-non-negative-integer trust boundary as the
|
||||
* MikroORM form in `sql-functions.ts`. On Postgres the validated count is
|
||||
* inlined as a literal into `make_interval(secs => n)` and the sum rendered
|
||||
* as SQLite's timestamp text.
|
||||
*/
|
||||
export function nowPlusSecondsKysely<DB, TB extends keyof DB>(
|
||||
platform: Platform,
|
||||
eb: ExpressionBuilder<DB, TB>,
|
||||
seconds: number,
|
||||
): ExpressionWrapper<DB, TB, string> {
|
||||
if (!Number.isInteger(seconds) || seconds < 0) {
|
||||
throw new Error(`sql-functions: nowPlusSecondsKysely needs a non-negative integer second count, got ${seconds}`);
|
||||
}
|
||||
if (isSqlite(platform)) {
|
||||
return eb.fn<string>('datetime', [eb.val('now'), eb.val(`+${seconds} seconds`)]);
|
||||
}
|
||||
if (isPostgres(platform)) {
|
||||
const later = sql`${sql.raw(PG_UTC_NOW)} + make_interval(secs => ${sql.lit(seconds)})`;
|
||||
return eb.fn<string>('to_char', [later, eb.cast(eb.val(PG_TIMESTAMP_FORMAT), 'text')]);
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Kysely-expression twin of {@link currentTimestamp}: the bare
|
||||
* `CURRENT_TIMESTAMP` keyword, for a value position inside a hand-typed
|
||||
* Kysely statement (DS24's `ON CONFLICT ... DO UPDATE SET last_seen_at =
|
||||
* CURRENT_TIMESTAMP` — R3's partial-index upsert). Verified directly against
|
||||
* `better-sqlite3` that SQLite accepts the bare keyword (`SELECT
|
||||
* CURRENT_TIMESTAMP`) but rejects it called as a function
|
||||
* (`SELECT CURRENT_TIMESTAMP()` → `near "(": syntax error`), so
|
||||
* `eb.fn('current_timestamp', [])` — every other helper in this file's
|
||||
* usual Kysely shape — is not an option here; the whole point of a keyword
|
||||
* literal is that it takes no parentheses. This is this file's one
|
||||
* Kysely-side use of the `sql` template tag — confined here, the sanctioned
|
||||
* escape hatch this file already is for every raw-SQL spelling in the
|
||||
* codebase (the MikroORM helpers in `sql-functions.ts` use `raw()` for the
|
||||
* identical reason), never inline in a repository (the TRAP list's "Kysely
|
||||
* `sql` banned under repositories" is about repository FILES, not this one).
|
||||
* On Postgres it renders the UTC clock as SQLite's timestamp text.
|
||||
*/
|
||||
export function currentTimestampKysely(platform: Platform): RawBuilder<string> {
|
||||
if (isSqlite(platform)) return sql<string>`CURRENT_TIMESTAMP`;
|
||||
if (isPostgres(platform)) return sql.raw<string>(pgTimestampText(PG_UTC_NOW));
|
||||
return unsupported(platform);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { Platform } from '@mikro-orm/core';
|
||||
import { BasePostgreSqlPlatform, SqlitePlatform } from '@mikro-orm/sql';
|
||||
|
||||
/**
|
||||
* Which engine a dialect helper is spelling for.
|
||||
*
|
||||
* Every helper in `sql-functions.ts` and `kysely-functions.ts` dispatches
|
||||
* on the live MikroORM platform (`em.getPlatform()`): SQLite is the engine
|
||||
* TREK runs on, Postgres is the second one the helpers are written for and
|
||||
* the CI Postgres probe (`scripts/pg-probe.ts`) runs them against. Anything
|
||||
* else fails closed through {@link unsupported} rather than guessing.
|
||||
*
|
||||
* `BasePostgreSqlPlatform` is the class every MikroORM Postgres platform
|
||||
* extends (the `@mikro-orm/postgresql` driver's own `PostgreSqlPlatform`
|
||||
* among them), so the check does not need the driver package at runtime.
|
||||
*/
|
||||
export function isSqlite(platform: Platform): boolean {
|
||||
return platform instanceof SqlitePlatform;
|
||||
}
|
||||
|
||||
export function isPostgres(platform: Platform): boolean {
|
||||
return platform instanceof BasePostgreSqlPlatform;
|
||||
}
|
||||
|
||||
/** True when one spelling serves every engine the dialect layer knows. */
|
||||
export function isKnownPlatform(platform: Platform): boolean {
|
||||
return isSqlite(platform) || isPostgres(platform);
|
||||
}
|
||||
|
||||
export function unsupported(platform: Platform): never {
|
||||
throw new Error(`sql-functions: no implementation for platform ${platform.constructor.name}`);
|
||||
}
|
||||
|
||||
// Postgres spellings shared by both helper files. The storage model stays the
|
||||
// one SQLite has (server/CLAUDE.md, "Storage model"): a timestamp is the TEXT
|
||||
// `YYYY-MM-DD HH:MM:SS` in UTC and a date is `YYYY-MM-DD`, so every Postgres
|
||||
// branch that reads the clock renders that same text instead of handing back
|
||||
// a `timestamptz`, and a text column compares against it exactly as on SQLite.
|
||||
|
||||
/** The database clock as UTC wall time, what SQLite's `CURRENT_TIMESTAMP` reads. */
|
||||
export const PG_UTC_NOW = "(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')";
|
||||
|
||||
/** `to_char` pattern for SQLite's timestamp text. */
|
||||
export const PG_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS';
|
||||
|
||||
/** `to_char` pattern for SQLite's date text. */
|
||||
export const PG_DATE_FORMAT = 'YYYY-MM-DD';
|
||||
|
||||
/** A timestamp expression rendered as SQLite's timestamp text. */
|
||||
export function pgTimestampText(expression: string): string {
|
||||
return `to_char(${expression}, '${PG_TIMESTAMP_FORMAT}')`;
|
||||
}
|
||||
|
||||
/** A timestamp expression rendered as SQLite's date text. */
|
||||
export function pgDateText(expression: string): string {
|
||||
return `to_char(${expression}, '${PG_DATE_FORMAT}')`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The POSIX regular expression for "starts with an ISO calendar date", the
|
||||
* same digit classes SQLite's `GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'`
|
||||
* spells, anchored at the start because GLOB always matches the whole value.
|
||||
*/
|
||||
export const PG_ISO_DATE_PREFIX = '^[0-9]{4}-[0-9]{2}-[0-9]{2}';
|
||||
@@ -0,0 +1,843 @@
|
||||
import {
|
||||
isKnownPlatform,
|
||||
isPostgres,
|
||||
isSqlite,
|
||||
PG_ISO_DATE_PREFIX,
|
||||
PG_UTC_NOW,
|
||||
pgDateText,
|
||||
pgTimestampText,
|
||||
unsupported,
|
||||
} from './platform';
|
||||
import { raw, type Platform, type RawQueryFragment } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* The only place a repository may spell a database function.
|
||||
*
|
||||
* Every helper takes the MikroORM `Platform` the caller's EntityManager is
|
||||
* running on (`em.getPlatform()`) plus an already-qualified column reference
|
||||
* (`'t.created_at'`), and dispatches on that platform at runtime. TREK ships
|
||||
* one binary and the database is chosen by configuration, so the dialect is a
|
||||
* runtime property of the live connection, not a build-time swap. Every
|
||||
* helper has a SQLite branch (the engine TREK runs on) and a Postgres branch
|
||||
* (the second engine; `scripts/pg-probe.ts` runs each one against a real
|
||||
* Postgres in CI), and a spelling both engines read the same way serves both
|
||||
* through `isKnownPlatform`. An unknown platform fails closed rather than
|
||||
* guessing a spelling. The Kysely-expression twins live in
|
||||
* `kysely-functions.ts`, the platform checks in `platform.ts`.
|
||||
*
|
||||
* Values are never interpolated — the day count in `dateAdd` is checked to be
|
||||
* an integer before it is spelled.
|
||||
*/
|
||||
|
||||
function column(ref: string): string {
|
||||
if (!/^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/i.test(ref)) {
|
||||
throw new Error(`sql-functions: not a column reference: ${ref}`);
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
|
||||
/** The calendar date (`YYYY-MM-DD`) of a timestamp column. */
|
||||
export function dateOf(platform: Platform, ref: string): RawQueryFragment {
|
||||
if (isSqlite(platform)) return raw(`date(${column(ref)})`);
|
||||
if (isPostgres(platform)) return raw(pgDateText(`CAST(${column(ref)} AS timestamp)`));
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** The timestamp column shifted by whole days, as a calendar date. */
|
||||
export function dateAdd(platform: Platform, ref: string, days: number): RawQueryFragment {
|
||||
if (!Number.isInteger(days)) throw new Error(`sql-functions: dateAdd needs an integer day count, got ${days}`);
|
||||
if (isSqlite(platform)) {
|
||||
const sign = days < 0 ? '-' : '+';
|
||||
return raw(`date(${column(ref)}, '${sign}${Math.abs(days)} days')`);
|
||||
}
|
||||
if (isPostgres(platform)) return raw(pgDateText(`CAST(${column(ref)} AS timestamp) + INTERVAL '${days} days'`));
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** The database clock, in the same text the column defaults produce (UTC `YYYY-MM-DD HH:MM:SS`). */
|
||||
export function currentTimestamp(platform: Platform): RawQueryFragment {
|
||||
if (isSqlite(platform)) return raw('CURRENT_TIMESTAMP');
|
||||
if (isPostgres(platform)) return raw(pgTimestampText(PG_UTC_NOW));
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* A bare reference to another column of the same row, for a filter or update
|
||||
* value that must compare against or combine with a sibling column instead
|
||||
* of a bound parameter (e.g. `used_count < max_uses` — `InviteTokensRepository
|
||||
* .incrementUsedCount`'s capacity guard). Portable across dialects on its own,
|
||||
* but still routed through this file (not spelled with `raw()` in a
|
||||
* repository) so every escape hatch stays in one place ESLint's
|
||||
* `no-restricted-syntax` rule for `src/db/repositories/**` can enforce.
|
||||
*/
|
||||
export function columnRef(platform: Platform, ref: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) return raw(column(ref));
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** A column shifted by a signed integer amount: `<col> + n` / `<col> - n`. */
|
||||
export function columnIncrementedBy(platform: Platform, ref: string, amount: number): RawQueryFragment {
|
||||
if (!Number.isInteger(amount)) {
|
||||
throw new Error(`sql-functions: columnIncrementedBy needs an integer amount, got ${amount}`);
|
||||
}
|
||||
if (isKnownPlatform(platform)) {
|
||||
const sign = amount < 0 ? '-' : '+';
|
||||
return raw(`${column(ref)} ${sign} ${Math.abs(amount)}`);
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* A case-insensitive column reference, for use as a filter's object key:
|
||||
* `{ [lower(platform, 'email')]: <value-side> }` produces
|
||||
* `WHERE LOWER(email) = <value-side>`.
|
||||
*
|
||||
* **SQLite's `LOWER()` is ASCII-only; JavaScript's `String.prototype
|
||||
* .toLowerCase()` is full-Unicode.** They do NOT agree on every input this
|
||||
* codebase stores — a locally-registered e-mail can carry any non-whitespace
|
||||
* character (`EMAIL_REGEX`), including non-ASCII letters (program rule 18;
|
||||
* Plan 3b Task 7 review, H1: `JOSÉ@x.com` proved a live login lockout). Two
|
||||
* value-side shapes are legitimate, and they are NOT interchangeable:
|
||||
*
|
||||
* - `LOWER(col) = LOWER(?)` — pair with `lowerParam()` below, binding the
|
||||
* RAW value. Both sides are folded by the SAME engine (SQLite's), so they
|
||||
* agree on every input. This is the shape for every legacy
|
||||
* `LOWER(col) = LOWER(?)` statement (AU9, AU12, UP5, UP6, O12).
|
||||
* - `LOWER(col) = ?` — pair with a value the CALLER has already lowered in
|
||||
* JS (`value.toLowerCase()`) as a plain string, matching a legacy
|
||||
* `LOWER(col) = ?` statement exactly (only O4 today —
|
||||
* `OidcService.findOrCreateUser` JS-lowers the email once upfront and the
|
||||
* legacy statement it replaced never re-lowered it in SQL). Do not use
|
||||
* this shape for a value the caller has not already lowered.
|
||||
*
|
||||
* Typed `RawQueryFragment & symbol` (not the bare `RawQueryFragment` the
|
||||
* other helpers in this file return): TypeScript only accepts a
|
||||
* `string | number | symbol` as a computed property name, and a raw
|
||||
* fragment is only usable as an object key because `raw()`'s default
|
||||
* generic already brands it with a `[Symbol.toPrimitive]`. The other
|
||||
* helpers here are only ever used as VALUES, where that brand isn't needed.
|
||||
*
|
||||
* Postgres spells it the same, but its `LOWER()` folds every letter, not
|
||||
* only ASCII. Pair it with `lowerParam()` there too and both sides still
|
||||
* fold through one engine, so a lookup agrees with itself on either engine.
|
||||
*/
|
||||
export function lower(platform: Platform, ref: string): RawQueryFragment & symbol {
|
||||
if (isKnownPlatform(platform)) return raw(`LOWER(${column(ref)})`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* The value-side twin of `lower()`: `LOWER(?)` bound with the RAW,
|
||||
* untransformed value, for the right-hand side of a `lower(platform, col)`
|
||||
* filter key. Together they render `LOWER(<column>) = LOWER(?)`,
|
||||
* byte-for-byte a legacy `LOWER(col) = LOWER(?)` statement, because SQLite
|
||||
* folds BOTH sides with the same (ASCII-only) engine — proven directly
|
||||
* against `better-sqlite3`: `SELECT LOWER(?)` on `'JOSÉ@x.com'` yields
|
||||
* `'josÉ@x.com'` (only the ASCII letters fold; the `É` is untouched), the
|
||||
* same transform SQLite would apply to a stored column. Do NOT pre-lower
|
||||
* the value in JS before calling this (program rule 18) — that reintroduces
|
||||
* the mixed-engine bug this helper exists to close.
|
||||
*/
|
||||
export function lowerParam(platform: Platform, value: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) return raw('LOWER(?)', [value]);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3c Task 0b (R6) — no consumer yet: Tasks 1–8 wire these in as each
|
||||
// converts the statement that needs them (`place-shadow.service.ts:192`,
|
||||
// `places.service.ts:642,651-652`, the ~16 `COALESCE` sites across
|
||||
// `days`/`assignments`/`trip-members`/`places`). Added here, with their own
|
||||
// SQLF-0xx tests pinning the SQLite text against a raw statement, so a later
|
||||
// task imports a tested helper instead of writing one inline.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `datetime('now', '-N days')` — the SQLite clock shifted backwards by whole
|
||||
* days, as TEXT (not a stored column's value — `dateAdd` above is the wrong
|
||||
* shape for this: it shifts a *column*, not "now"). `days` is validated to be
|
||||
* a non-negative integer and spelled directly into the fragment rather than
|
||||
* bound: the legacy statement (`place-shadow.service.ts:192`) binds the
|
||||
* WHOLE modifier string (`'-30 days'`) as one parameter, and MikroORM's raw
|
||||
* fragments do not accept a placeholder inside the modifier argument of a
|
||||
* SQLite date/time function — `datetime('now', ?)` with `'-30 days'` bound
|
||||
* does work in raw SQLite, but composing that shape through a `raw()`
|
||||
* fragment used as a QueryBuilder value needs the modifier already in the
|
||||
* SQL text, the same way `dateAdd` above spells its own day count.
|
||||
*/
|
||||
export function nowMinusDays(platform: Platform, days: number): RawQueryFragment {
|
||||
if (!Number.isInteger(days) || days < 0) {
|
||||
throw new Error(`sql-functions: nowMinusDays needs a non-negative integer day count, got ${days}`);
|
||||
}
|
||||
if (isSqlite(platform)) return raw(`datetime('now', '-${days} days')`);
|
||||
if (isPostgres(platform)) return raw(pgTimestampText(`${PG_UTC_NOW} - INTERVAL '${days} days'`));
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `TRIM(<col>)`, standalone. **Does NOT compose with `lower()`** to build
|
||||
* `LOWER(TRIM(name))` (Task 0b review M3): `lower()`'s `ref` argument goes
|
||||
* through `column()`, whose regex rejects anything but a bare
|
||||
* `alias.column` reference — `TRIM(name)` fails it — and even if it didn't,
|
||||
* `coalesce()`'s own docstring in this file documents that a
|
||||
* `RawQueryFragment` cannot be nested inside another one (`raw()`'s
|
||||
* `[Symbol.toPrimitive]` only implements the `'string'` coercion hint, which
|
||||
* is the object-key position, not template-literal interpolation). Use
|
||||
* `lowerTrim()` below for the composed shape.
|
||||
*/
|
||||
export function trim(platform: Platform, ref: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) return raw(`TRIM(${column(ref)})`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `LOWER(TRIM(<col>))` as one fragment — the shape `places.service.ts:642`
|
||||
* (`lower(trim(name))`, PL26) actually needs; `lower()`/`trim()` above
|
||||
* cannot be composed to build it (see `trim()`'s docstring, Task 0b review
|
||||
* M3). Typed `RawQueryFragment & symbol`, the same brand `lower()` carries,
|
||||
* for use as a filter KEY: `{ [lowerTrim(platform, 'name')]: lowerParam(...) }`.
|
||||
* SQLite's `LOWER()` is ASCII-only (program rule 18) — unchanged by the
|
||||
* `TRIM()`.
|
||||
*/
|
||||
export function lowerTrim(platform: Platform, ref: string): RawQueryFragment & symbol {
|
||||
if (isKnownPlatform(platform)) return raw(`LOWER(TRIM(${column(ref)}))`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `COALESCE(<col>, <fallbackCol>)` — both sides column references, for the
|
||||
* `COALESCE(a, b)` SELECT-projection shape (`days.service.ts:93-94`,
|
||||
* `assignments.service.ts:103-104`, `trip-members.service.ts:116-143`, …).
|
||||
*
|
||||
* Not composed by nesting a `RawQueryFragment` inside this one: MikroORM's
|
||||
* `RawQueryFragment[Symbol.toPrimitive]` only returns a usable value for the
|
||||
* `'string'` coercion hint (object-key position) — a template-literal
|
||||
* `${fragment}` embed uses the `'default'` hint and throws
|
||||
* (`node_modules/@mikro-orm/core/utils/RawQueryFragment.js`, verified
|
||||
* directly, not assumed). So `coalesce`'s second argument is a second
|
||||
* `column()`-validated identifier, spelled into the same fragment as the
|
||||
* first — two columns, one statement, matching `lower`/`lowerParam`'s
|
||||
* two-function split for the same reason (a filter KEY vs a bound VALUE
|
||||
* are different shapes).
|
||||
*/
|
||||
export function coalesce(platform: Platform, ref: string, fallbackRef: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) return raw(`COALESCE(${column(ref)}, ${column(fallbackRef)})`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `COALESCE(<col>, ?)` — the value-side twin of `coalesce()` above, for the
|
||||
* `COALESCE(col, ?)` UPDATE-SET shape (`places.service.ts:344,351,363,…`).
|
||||
* `value` is bound as a genuine parameter, never interpolated.
|
||||
*
|
||||
* Typed `RawQueryFragment & symbol` (widened from a bare `RawQueryFragment`
|
||||
* in Plan 3d Task 0, R3 — `_shared/reservation-visibility.ts`'s
|
||||
* `publicReservationCondition` needs `COALESCE(alias.ingest_state, 'live')`
|
||||
* as a `.where({...})` filter KEY, `{ [coalesceParam(...)]: { $ne: 'staged'
|
||||
* } }`, the same brand `lower()`/`lowerTrim()`/`castInteger()` carry for
|
||||
* that use): every existing UPDATE-SET caller (`Places.repository.ts`'s six
|
||||
* `coalesceParam(...)` assignments into a loosely-typed `data` object) keeps
|
||||
* typechecking unchanged — `RawQueryFragment & symbol` is assignable
|
||||
* anywhere a plain `RawQueryFragment` is expected, a strict widening with no
|
||||
* behaviour change (the function body is untouched).
|
||||
*/
|
||||
export function coalesceParam(
|
||||
platform: Platform,
|
||||
ref: string,
|
||||
value: string | number | null,
|
||||
): RawQueryFragment & symbol {
|
||||
if (isKnownPlatform(platform)) return raw(`COALESCE(${column(ref)}, ?)`, [value]);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `COALESCE(?, <col>)` — the MIRROR-IMAGE value-side shape of
|
||||
* {@link coalesceParam} above: the bound value goes FIRST, the column is
|
||||
* the fallback. NOT interchangeable with `coalesceParam` — that one keeps
|
||||
* the EXISTING column unless it is NULL (`places.service.ts`'s own legacy
|
||||
* shape); this one prefers the NEW value unless IT is null, keeping the
|
||||
* existing column only then. `doc-sync.service.ts`'s DS23/DS24
|
||||
* (`upsertItem`'s `file_id=COALESCE(?,file_id)`,
|
||||
* `remote_id=COALESCE(?,remote_id)`, … eight columns, both the plain
|
||||
* `nativeUpdate` and the Kysely `ON CONFLICT` forms) is the shape this
|
||||
* exists for — confirmed genuinely the opposite direction from
|
||||
* `coalesceParam`'s own doc'd precedent by reading the legacy SQL text
|
||||
* literally, not assumed from the function name alone (a same-named
|
||||
* "coalesce" helper reused in the wrong direction silently drops every
|
||||
* incoming update — verified directly against a live row: a `recordAttempt`
|
||||
* call passing a genuinely new `remote_version`/`content_sha256` left both
|
||||
* columns exactly as they were before, since `coalesceParam`'s `COALESCE(col,
|
||||
* ?)` always preferred the non-null existing value).
|
||||
*/
|
||||
export function coalesceOverride(
|
||||
platform: Platform,
|
||||
value: string | number | null,
|
||||
ref: string,
|
||||
): RawQueryFragment & symbol {
|
||||
if (isKnownPlatform(platform)) return raw(`COALESCE(?, ${column(ref)})`, [value]);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `ABS(<col> - ?)`, for use as a filter KEY (the `'string'`-hint coercion
|
||||
* `lower()` above relies on) so it composes with `$lte`/`$gte`:
|
||||
* `{ [absDifference(platform, 'lat', targetLat)]: { $lte: tolerance } }`
|
||||
* renders `WHERE ABS(lat - ?) <= ?`, matching `places.service.ts:651-652`'s
|
||||
* `abs(lat - ?) <= ?` (and the sibling `lng` comparison at `:652`) exactly.
|
||||
* Typed `RawQueryFragment & symbol`, same reason `lower()` is: only a
|
||||
* `string | number | symbol` is a valid computed property name, and the
|
||||
* brand only lives on that typing for values meant to be used as a key.
|
||||
*/
|
||||
export function absDifference(platform: Platform, ref: string, value: number): RawQueryFragment & symbol {
|
||||
if (isKnownPlatform(platform)) return raw(`ABS(${column(ref)} - ?)`, [value]);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3c Task 1 — aggregate SELECT projections (`PlaceShadowPicksRepository
|
||||
// .totals`/`countBySource`/`countByLiveRank`, `place-shadow.service.ts:144,
|
||||
// 149, 157`). `alias` is a hand-written literal at every call site today
|
||||
// (never user input), validated the same way `column()` validates a column
|
||||
// reference, so a future caller cannot smuggle SQL through it either.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function alias(name: string): string {
|
||||
if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {
|
||||
throw new Error(`sql-functions: not an alias: ${name}`);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/** `COUNT(*) as <alias>`, for a single-row totals read or a `GROUP BY` count column. */
|
||||
export function countAll(platform: Platform, aliasName: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) return raw(`COUNT(*) as ${alias(aliasName)}`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** `MIN(<col>) as <alias>`. */
|
||||
export function minOf(platform: Platform, ref: string, aliasName: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) return raw(`MIN(${column(ref)}) as ${alias(aliasName)}`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** `MAX(<col>) as <alias>`. */
|
||||
export function maxOf(platform: Platform, ref: string, aliasName: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) return raw(`MAX(${column(ref)}) as ${alias(aliasName)}`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3c Task 6 — `TripMembersRepository.listWithUserAndInviter`
|
||||
// (`trip-members.service.ts:117`, TM2): the `role` column, a `CASE WHEN`
|
||||
// comparing the joined user's id against the trip's owner id.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `CASE WHEN <col> = ? THEN ? ELSE ? END`, for use as a `.select()` value
|
||||
* (chain `.as(aliasName)` at the call site, the same way `coalesce()`'s
|
||||
* callers do — this file does not bake the alias into the SQL text itself
|
||||
* for this one, unlike `countAll`/`minOf`/`maxOf`, because `.as()` already
|
||||
* covers it and a `value`-bearing fragment cannot reuse `alias()`'s bare
|
||||
* identifier validation the same way an aggregate's literal alias does).
|
||||
* `value`/`whenTrue`/`whenFalse` are all passed through `raw()`'s own
|
||||
* parameter escaping, never spliced into the SQL text by this function —
|
||||
* even though today's only caller (TM2's owner/member role label) passes
|
||||
* fixed literal strings, parity is by VALUE, not by whether the string
|
||||
* happens to be a source-code literal at the call site. (Task 6 review's
|
||||
* I1: downstream, MikroORM still formats the FINAL query with every
|
||||
* parameter inlined as an escaped literal in the SQL text it hands
|
||||
* better-sqlite3 — not as a separate bound-params array — so a non-finite
|
||||
* `value` renders as the bare token `NaN`/`Infinity` and fails at PREPARE
|
||||
* time regardless of this function's own escaping; callers must guard a
|
||||
* non-finite `value` before calling.)
|
||||
*/
|
||||
export function caseWhenEquals(
|
||||
platform: Platform,
|
||||
ref: string,
|
||||
value: number,
|
||||
whenTrue: string,
|
||||
whenFalse: string,
|
||||
): RawQueryFragment {
|
||||
if (isKnownPlatform(platform))
|
||||
return raw(`CASE WHEN ${column(ref)} = ? THEN ? ELSE ? END`, [value, whenTrue, whenFalse]);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3c Task 1 fix round (review M1) — `PlaceShadowPicksRepository
|
||||
// .countBySource` (PS5): `.orderBy()` on `countAll()`'s aliased column throws
|
||||
// ("Trying to query by not existing property" — `raw()`'s alias carries no
|
||||
// literal type for `ExtractRawAliases` to register), and sorting the fetched
|
||||
// rows in JS is NOT equivalent to the legacy `ORDER BY count DESC`: SQLite's
|
||||
// own sorter is not stable, so on a tie it orders descending by GROUP BY key,
|
||||
// while `Array.prototype.sort` (stable) leaves ties in the rows' incoming
|
||||
// (ascending) order — verified directly (five sources, two tied pairs).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `COUNT(*)` as an ORDER BY EXPRESSION (not an alias — `.orderBy()` cannot
|
||||
* order by `countAll()`'s aliased column; ordering by the expression itself
|
||||
* works and reproduces the legacy `ORDER BY count DESC` tie order exactly).
|
||||
* Typed `RawQueryFragment & symbol`, the same brand `lower()`/`lowerTrim()`
|
||||
* carry, so it is usable as an `.orderBy()` object key:
|
||||
* `.orderBy({ [countAllRef(platform)]: 'desc' })`.
|
||||
*/
|
||||
export function countAllRef(platform: Platform): RawQueryFragment & symbol {
|
||||
if (isKnownPlatform(platform)) return raw('COUNT(*)');
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3d Task 0 (R6) — no consumer yet: Tasks 2/4 wire these in as each
|
||||
// converts the statement that needs them (`reservations.service.ts` RS11 and
|
||||
// RS20 `listUpcoming`, `reservation-visibility.ts` RV2, DY23 in
|
||||
// `days.service.ts`). Added here, with their own SQLF-0xx tests pinning the
|
||||
// SQLite text against a raw statement on seeded rows, so Tasks 1-6 import a
|
||||
// tested helper instead of writing one inline.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `<col> GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'` — "does this
|
||||
* column's TEXT value start with an ISO calendar date (`YYYY-MM-DD`)?", the
|
||||
* legacy `DATED` constant (`reservations.service.ts:120`:
|
||||
* `` `r.reservation_time GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'` ``,
|
||||
* used at `:453-454` inside RS20's two `CASE WHEN` arms). Spelled with
|
||||
* SQLite's `[0-9]` character-class glob syntax, NOT the plan's shorthand
|
||||
* `'????-??-??*'` — verified directly against the legacy source, not
|
||||
* assumed: a `?` in SQLite GLOB matches any single character (letters
|
||||
* included), so `????-??-??*` is a strictly WIDER, non-equivalent pattern
|
||||
* (it would also match `abcd-ef-gh...`); only the digit-class form matches
|
||||
* the legacy's actual behaviour byte-for-byte.
|
||||
*
|
||||
* A full boolean expression, not a bare value — pair with a `CASE WHEN`
|
||||
* builder or a QB/Kysely raw condition, never nest inside another raw
|
||||
* fragment (see `coalesce()`'s docstring on why nesting doesn't work).
|
||||
* Kysely has no `GLOB` comparison operator (`operator-node.d.ts`'s
|
||||
* `ComparisonOperator` union omits it — verified against the installed
|
||||
* 0.29.6 typings, per the inventory's §19 MikroORM/Kysely capability table),
|
||||
* so this helper is the only portable spelling for this shape.
|
||||
* Postgres reads it as the anchored regular expression
|
||||
* `CAST(<col> AS text) ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}'`.
|
||||
*/
|
||||
export function startsWithIsoDate(platform: Platform, ref: string): RawQueryFragment {
|
||||
if (isSqlite(platform)) {
|
||||
return raw(`${column(ref)} GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'`);
|
||||
}
|
||||
if (isPostgres(platform)) return raw(`CAST(${column(ref)} AS text) ~ '${PG_ISO_DATE_PREFIX}'`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `substr(<col>, <start>[, <length>])`, 1-based on both ends — the legacy
|
||||
* shape at `reservations.service.ts:453` (`substr(r.reservation_time, 1,
|
||||
* 10)`, three-arg), `:454` (`substr(r.reservation_time, 12)`, two-arg — "from
|
||||
* position 12 to the end of the string") and `days.service.ts` DY23
|
||||
* (`SUBSTR(reservation_time, 11)`, same two-arg shape, spelled uppercase in
|
||||
* that statement — SQL function names are case-insensitive, so this helper's
|
||||
* lowercase spelling is behaviourally identical). `length` is optional,
|
||||
* matching SQLite's own two-arg `substr(X, Y)` form (everything from `Y` to
|
||||
* the end) — passing it renders the three-arg form instead. `start` and
|
||||
* `length` are validated integers and spelled directly (not bound): they are
|
||||
* always source-code constants at every known call site (`1`, `10`, `11`,
|
||||
* `12`), never user input, the same trust boundary `dateAdd`'s day count and
|
||||
* `columnIncrementedBy`'s amount already rely on in this file.
|
||||
*/
|
||||
export function substring(platform: Platform, ref: string, start: number, length?: number): RawQueryFragment {
|
||||
if (!Number.isInteger(start) || start < 1) {
|
||||
throw new Error(`sql-functions: substring needs a 1-based integer start, got ${start}`);
|
||||
}
|
||||
if (length !== undefined && (!Number.isInteger(length) || length < 0)) {
|
||||
throw new Error(`sql-functions: substring needs a non-negative integer length, got ${length}`);
|
||||
}
|
||||
if (isKnownPlatform(platform)) {
|
||||
if (length === undefined) return raw(`substr(${column(ref)}, ${start})`);
|
||||
return raw(`substr(${column(ref)}, ${start}, ${length})`);
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* A part of a `concat()` expression: either a column reference (rendered
|
||||
* through `column()`, the same identifier validation every other helper in
|
||||
* this file applies) or a plain value bound as a genuine parameter (`?`) —
|
||||
* never interpolated, even for what today's only legacy caller spells as a
|
||||
* literal (`'T'` in `d.date || 'T' || a.check_in`,
|
||||
* `reservations.service.ts:475, :493`): a bound constant and an interpolated
|
||||
* one produce byte-identical SQLite behaviour for a plain string, and
|
||||
* binding is the shape every other value-side helper in this file already
|
||||
* prefers (`coalesceParam`, `lowerParam`, `absDifference`).
|
||||
*/
|
||||
export type ConcatPart = { column: string } | { value: string };
|
||||
|
||||
/**
|
||||
* `<part> || <part> || …` — SQLite (and Postgres) string concatenation, the
|
||||
* legacy shape at `reservations.service.ts:475, :493`
|
||||
* (`d.date || 'T' || a.check_in`, RS20's two check-in/check-out arms) and
|
||||
* `days.service.ts` DY23 (`:date || SUBSTR(reservation_time, 11)`, inside an
|
||||
* `UPDATE … SET`). Needs at least two parts — a one-part "concatenation" is
|
||||
* a caller bug, not a legitimate call. Each part is a `ConcatPart` (see its
|
||||
* own docstring) rather than a bare string, so a column reference and a
|
||||
* bound literal can never be confused with each other the way an untyped
|
||||
* `...parts: string[]` would invite (a plain string could mean either).
|
||||
*
|
||||
* Deliberately does NOT accept a nested `RawQueryFragment` as a part (e.g.
|
||||
* the output of `substring()` above) — the same limitation `coalesce()`'s
|
||||
* docstring documents: `RawQueryFragment`'s `[Symbol.toPrimitive]` only
|
||||
* implements the `'string'` coercion hint (the object-key position), not the
|
||||
* `'default'` hint a template-literal embed or an array-join would need, so
|
||||
* composing `concat(platform, substring(...), ...)` throws at the `raw()`
|
||||
* boundary rather than rendering silently wrong SQL. A caller that needs
|
||||
* `SUBSTR(...)` as one side of a `||` builds that one statement directly
|
||||
* (Kysely's `'||'` binary operator, per the inventory's §17a/§19), the same
|
||||
* way RS20's own CASE/CTE shape is built outside this file's helpers.
|
||||
*/
|
||||
export function concat(platform: Platform, ...parts: readonly ConcatPart[]): RawQueryFragment {
|
||||
if (parts.length < 2) {
|
||||
throw new Error(`sql-functions: concat needs at least two parts, got ${parts.length}`);
|
||||
}
|
||||
if (isKnownPlatform(platform)) {
|
||||
const bindings: string[] = [];
|
||||
const sql = parts
|
||||
.map((part) => {
|
||||
if ('column' in part) return column(part.column);
|
||||
bindings.push(part.value);
|
||||
return '?';
|
||||
})
|
||||
.join(' || ');
|
||||
return raw(sql, bindings);
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `CAST(<col> AS INTEGER)` — the legacy shape at `reservations.service.ts:471,
|
||||
* :489` (inside RS20's correlated `stay_first_reservation_id`/title
|
||||
* subqueries: `CAST(res.accommodation_id AS INTEGER) = a.id`) and
|
||||
* `reservation-visibility.ts:106-107` (RV2's `publicStaySql`:
|
||||
* `CAST(vr.accommodation_id AS INTEGER) = ${alias}.id`). Exists specifically
|
||||
* for `reservations.accommodation_id`, a TEXT column holding integer ids
|
||||
* with no FK (§18.1 of the inventory — some rows read back as `"14.0"`):
|
||||
* casting it to INTEGER before comparing against a genuine INTEGER column
|
||||
* (`day_accommodations.id`) applies numeric affinity to BOTH sides, matching
|
||||
* `"14"` and `"14.0"` alike, the same way the legacy statement does. Postgres
|
||||
* refuses `CAST('14.0' AS integer)`, so its branch casts through `numeric`
|
||||
* and truncates: `CAST(trunc(CAST(<col> AS numeric)) AS integer)`.
|
||||
*
|
||||
* Typed `RawQueryFragment & symbol`, the same brand `lower()`/`lowerTrim()`
|
||||
* carry: both known legacy call sites compare the cast against ANOTHER
|
||||
* COLUMN, not a bound value (`= a.id`, `= ${alias}.id`) — the shape is
|
||||
* `{ [castInteger(platform, 'vr.accommodation_id')]: columnRef(platform,
|
||||
* 'a.id') }`, pairing this helper's filter-KEY brand with `columnRef()`'s
|
||||
* existing VALUE-side column reference. The brand also lets it appear in a
|
||||
* `.select()` projection via `.as(alias)` (the `lowerTrim`/SQLF-027 dual-use
|
||||
* precedent) for a caller that only needs the cast INTEGER value itself.
|
||||
*/
|
||||
export function castInteger(platform: Platform, ref: string): RawQueryFragment & symbol {
|
||||
if (isSqlite(platform)) return raw(`CAST(${column(ref)} AS INTEGER)`);
|
||||
if (isPostgres(platform)) return raw(`CAST(trunc(CAST(${column(ref)} AS numeric)) AS integer)`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `ABS(JULIANDAY(<col>) - JULIANDAY(?))` — the legacy shape at
|
||||
* `reservations.service.ts:307` (RS11, `resolveDayIdFromTime`'s
|
||||
* nearest-day fallback: `ORDER BY ABS(JULIANDAY(date) - JULIANDAY(?)) ASC,
|
||||
* date ASC LIMIT 1`), which clamps an imported booking's date to the
|
||||
* closest day row in the trip when no exact match exists. `isoDate` is
|
||||
* bound as a genuine parameter (never interpolated), matching the legacy
|
||||
* statement's own bind. Distinct from `absDifference()` above:
|
||||
* `absDifference` is `ABS(<col> - ?)` on plain NUMERIC values (for a
|
||||
* lat/lng tolerance filter); this helper compares two `JULIANDAY(...)`
|
||||
* calendar values. Typed `RawQueryFragment & symbol`, the same brand
|
||||
* `countAllRef()` carries, so it is usable as an `.orderBy()` object key —
|
||||
* `.orderBy({ [dayDistance(platform, 'date', isoDate)]: 'asc' })` —
|
||||
* matching the legacy's own `ORDER BY ABS(JULIANDAY(...) - JULIANDAY(?)) ASC`
|
||||
* shape exactly (an aliased column cannot be ordered by, the same
|
||||
* `ExtractRawAliases` limitation `countAllRef`'s own docstring / SQLF-024's
|
||||
* comment documents; ordering by the EXPRESSION itself is what works).
|
||||
* Postgres measures the same distance in days from the epoch difference of
|
||||
* the two values cast to `timestamp`.
|
||||
*/
|
||||
export function dayDistance(platform: Platform, ref: string, isoDate: string): RawQueryFragment & symbol {
|
||||
if (isSqlite(platform)) return raw(`ABS(JULIANDAY(${column(ref)}) - JULIANDAY(?))`, [isoDate]);
|
||||
if (isPostgres(platform)) {
|
||||
return raw(`ABS(EXTRACT(EPOCH FROM (CAST(${column(ref)} AS timestamp) - CAST(? AS timestamp))) / 86400)`, [
|
||||
isoDate,
|
||||
]);
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3f Task 0 (R9) — no consumer yet: Task 2 (`collateNoCase`, SH9's
|
||||
// `school-holidays.service.ts#checkName` duplicate-name guard) and Task 4
|
||||
// (`nowMinusHours`, RJ4's `reminder-jobs.service.ts#todoTick`
|
||||
// `datetime('now', '-20 hours')`) wire these in when each converts the
|
||||
// statement that needs them. `lowerTrimParam` (AT31's value side, atlas's
|
||||
// bucket-list dedup) is Task 1's. Added here, with their own SQLF-0xx tests
|
||||
// pinning the SQLite text against a raw statement on seeded rows, so each
|
||||
// task imports a tested helper instead of writing one inline.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A case-insensitive column reference via SQLite's `NOCASE` collating
|
||||
* sequence, for use as a filter's object key — the same `{ [collateNoCase(
|
||||
* platform, 'name')]: value }` shape `lower()` documents, rendering `WHERE
|
||||
* name COLLATE NOCASE = <value-side>`. The legacy statement this replaces
|
||||
* (`school-holidays.service.ts:50`, SH9) spells the COLLATE on the VALUE
|
||||
* side instead (`name = ? COLLATE NOCASE`) — textually different, but SQLite
|
||||
* resolves a binary comparison's collating sequence from the FIRST operand
|
||||
* that carries an explicit `COLLATE`, scanning left to right, so `col
|
||||
* COLLATE NOCASE = ?` and `col = ? COLLATE NOCASE` select the same collation
|
||||
* (NOCASE) for the whole comparison either way — verified directly
|
||||
* (SQLF-060: both forms select the identical row set on a mixed-case
|
||||
* fixture), not assumed from the operator's documented precedence alone.
|
||||
*
|
||||
* **Not the same helper as `lower()`, and not reusable in its place.**
|
||||
* SQLite's built-in `NOCASE` collation is documented to fold ONLY the 26
|
||||
* ASCII letters, exactly like `LOWER()`'s own ASCII-only fold (program rule
|
||||
* 18) — verified directly against `better-sqlite3` (SQLF-061): on every
|
||||
* non-ASCII fixture this file's own `LOWER()` test (SQLF-014) already
|
||||
* carries, `x = y COLLATE NOCASE` and `LOWER(x) = LOWER(y)` agree, letter for
|
||||
* letter — neither engine folds a non-ASCII case pair. So `collateNoCase`
|
||||
* does NOT diverge from `lower()` on any input constructed here; it is a
|
||||
* NEW helper anyway (per R9's own instruction) because the two are
|
||||
* textually different SQL constructs matching two textually different
|
||||
* legacy statements (`COLLATE NOCASE` vs `LOWER(...)`), and because a
|
||||
* `COLLATE`-based comparison lets SQLite use an index on the un-wrapped
|
||||
* column in a way `LOWER(col) = ?` cannot — a real, if not row-visible,
|
||||
* difference between the two shapes.
|
||||
*
|
||||
* Postgres has no built-in `NOCASE`. Its branch names a collation `nocase`
|
||||
* that a Postgres schema creates as a nondeterministic ICU collation
|
||||
* (`CREATE COLLATION nocase (provider = icu, locale = 'und-u-ks-level2',
|
||||
* deterministic = false)`, which `scripts/pg-probe.ts` does). That one folds
|
||||
* case for every letter, not only ASCII, and supports `=` but not `LIKE`.
|
||||
*/
|
||||
export function collateNoCase(platform: Platform, ref: string): RawQueryFragment & symbol {
|
||||
if (isSqlite(platform)) return raw(`${column(ref)} COLLATE NOCASE`);
|
||||
if (isPostgres(platform)) return raw(`${column(ref)} COLLATE "nocase"`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `datetime('now', '-N hours')` — the hour-granularity sibling of
|
||||
* `nowMinusDays()` above, for `reminder-jobs.service.ts#todoTick`'s
|
||||
* `datetime('now', '-20 hours')` (RJ4) — 20 hours is not expressible as
|
||||
* `nowMinusDays` with a fractional day. Same validation shape as
|
||||
* `nowMinusDays` (a non-negative integer, spelled directly into the
|
||||
* fragment rather than bound — MikroORM's raw fragments do not accept a
|
||||
* placeholder inside a SQLite date/time function's modifier argument, the
|
||||
* same reasoning `nowMinusDays`'s own docstring gives).
|
||||
*/
|
||||
export function nowMinusHours(platform: Platform, hours: number): RawQueryFragment {
|
||||
if (!Number.isInteger(hours) || hours < 0) {
|
||||
throw new Error(`sql-functions: nowMinusHours needs a non-negative integer hour count, got ${hours}`);
|
||||
}
|
||||
if (isSqlite(platform)) return raw(`datetime('now', '-${hours} hours')`);
|
||||
if (isPostgres(platform)) return raw(pgTimestampText(`${PG_UTC_NOW} - INTERVAL '${hours} hours'`));
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* The value-side twin of `lowerTrim()`: `LOWER(TRIM(?))` bound with the RAW,
|
||||
* untransformed value — confirmed genuinely missing by reading this file's
|
||||
* full export list before adding it (R9), not assumed from the inventory's
|
||||
* own flag. Pairs with `lowerTrim()` as a filter KEY for the composed
|
||||
* `LOWER(TRIM(<column>)) = LOWER(TRIM(?))` shape
|
||||
* `atlas.service.ts:876-877`'s AT31 needs (`lower(trim(name)) =
|
||||
* lower(trim(?))`), the same "bind the raw value, let SQL apply the SAME
|
||||
* transform to both sides" reasoning `lowerParam()`'s own docstring gives —
|
||||
* do NOT pre-trim/pre-lower the value in JS before calling this (program
|
||||
* rule 18: mixing engines is the bug this pairing exists to avoid).
|
||||
*/
|
||||
export function lowerTrimParam(platform: Platform, value: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) return raw('LOWER(TRIM(?))', [value]);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3h Task 0 — no consumer yet: Task 3 (`dawarich-sync.service.ts`'s
|
||||
// `listTripsToSync`, DSY2 — `date('now','-400 days')` / `date('now','+1
|
||||
// day')`) and Task 4 (`route-usage.service.ts`'s `purgeExpired`, RU4 —
|
||||
// `date('now', ?)` bound with the modifier `-${RETENTION_DAYS} days`, and
|
||||
// RETENTION_DAYS (`route-usage.service.ts:13`) is a compile-time module
|
||||
// constant (`400`), not a runtime value — so RU4's "bound parameter" and
|
||||
// DSY2's "literal" are the SAME shape at the call site once the modifier is
|
||||
// known, confirmed directly against both files' actual source rather than
|
||||
// assumed from the legacy SQL's own binding style) wire `nowDateOffset` in
|
||||
// when each converts its own statement.
|
||||
//
|
||||
// Plan 3f's own four `date('now')` sites (atlas.service.ts AT39/AT42/AT44/
|
||||
// AT45 — 3g's inventory's own open question, inherited from 3f and never
|
||||
// resolved until now) do NOT go through a dialect helper at all: `todayUtc()`
|
||||
// (a `@trek/shared` JS function) resolves the calendar date once in the
|
||||
// CALLING SERVICE (`atlas.service.ts:912`, `const trip = await
|
||||
// this.trips.lastStartedTrip(userId, todayUtc())`) and the repository binds
|
||||
// it as a plain parameter (`Trips.repository.ts#lastStartedTrip`:
|
||||
// `.where((eb) => eb(eb.fn.coalesce('t.start_date', 't.end_date'), '<=',
|
||||
// today))`) — confirmed by reading the actual converted code at HEAD, not
|
||||
// the plan document's description of it. That pattern covers a BARE
|
||||
// `date('now')` (no offset) cleanly, and needs no new helper here. It does
|
||||
// not extend to an OFFSET the way DSY2/RU4 need without every call site
|
||||
// re-deriving day arithmetic in JS by hand, so this file instead grows the
|
||||
// sibling `nowMinusDays`/`nowMinusHours` already establish for exactly this
|
||||
// family (Plan 3c Task 0b/Plan 3f Task 0 R9): a signed day-count offset from
|
||||
// "now", spelled into the fragment after integer validation, the same
|
||||
// reasoning those two helpers give (MikroORM's raw fragments do not accept a
|
||||
// placeholder inside a SQLite date/time function's modifier argument).
|
||||
// `PlaceShadowPicksRepository.expireStale` (Plan 3c Task 1) is this shape's
|
||||
// own closest working precedent — a retention-window purge built on
|
||||
// `nowMinusDays` exactly the way `RouteUsageDailyRepository`'s own purge
|
||||
// (RU4) will be built on `nowDateOffset` below.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `date('now', '<sign>N days')` — the SQLite clock's CALENDAR DATE (`date()`,
|
||||
* not `datetime()` — `nowMinusDays` above is the wrong shape for this: it
|
||||
* targets `datetime()`, and only ever subtracts), shifted by a signed whole
|
||||
* day count. Unlike `nowMinusDays`, `days` may be POSITIVE (forward),
|
||||
* NEGATIVE (backward) or zero — `dawarich-sync.service.ts`'s
|
||||
* `listTripsToSync` (DSY2) needs both directions in the SAME statement
|
||||
* (`date('now','-400 days')` for the trailing edge, `date('now','+1 day')`
|
||||
* for the leading one). `days` is spelled directly into the fragment (not
|
||||
* bound), the same reasoning `nowMinusDays`'s own docstring gives.
|
||||
*
|
||||
* Verified directly (not assumed) that SQLite's modifier keyword tolerates
|
||||
* the singular/plural mismatch between the two legacy texts (`'+1 day'`
|
||||
* singular, `'-400 days'` plural): `date('now','+1 day')` and
|
||||
* `date('now','+1 days')` render the identical result against a live
|
||||
* `better-sqlite3` connection, so this helper's always-plural spelling is
|
||||
* behaviourally identical to both legacy statements, not just the plural one.
|
||||
*/
|
||||
export function nowDateOffset(platform: Platform, days: number): RawQueryFragment {
|
||||
if (!Number.isInteger(days)) {
|
||||
throw new Error(`sql-functions: nowDateOffset needs an integer day count, got ${days}`);
|
||||
}
|
||||
if (isSqlite(platform)) {
|
||||
const sign = days < 0 ? '-' : '+';
|
||||
return raw(`date('now', '${sign}${Math.abs(days)} days')`);
|
||||
}
|
||||
if (isPostgres(platform)) return raw(pgDateText(`${PG_UTC_NOW} + INTERVAL '${days} days'`));
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `datetime('now', '+N seconds')` — the seconds-granularity, ADDING sibling
|
||||
* of `nowMinusDays`/`nowMinusHours` above: the shape `doc-sync.service.ts`'s
|
||||
* `upsertItem` (DS23, inside an `ON CONFLICT DO UPDATE`'s `CASE WHEN`; DS26,
|
||||
* inside the sibling `INSERT ... VALUES`) and `recordLinkFailure` (a third,
|
||||
* structurally identical call site found re-reading the file at HEAD —
|
||||
* `next_attempt_at = datetime('now', '+' || ? || ' seconds')`,
|
||||
* `doc-sync.service.ts:967`, not individually numbered in the plan's own
|
||||
* inventory) all need: a caller-computed backoff window (`backoffSeconds(
|
||||
* ...)`, a genuine RUNTIME value, never a source-code constant the way
|
||||
* `nowMinusDays`'s callers' day counts are) added to the database clock.
|
||||
* `seconds` is validated non-negative-integer and spelled directly into the
|
||||
* fragment — the same reasoning (and the same MikroORM raw-fragment
|
||||
* placeholder limitation) `nowMinusDays`'s own docstring gives; every known
|
||||
* call site's `seconds` argument is already a JS-computed `number`, never
|
||||
* user input, the same trust boundary this file relies on elsewhere
|
||||
* (`dateAdd`'s day count, `substring`'s start/length).
|
||||
*/
|
||||
export function nowPlusSeconds(platform: Platform, seconds: number): RawQueryFragment {
|
||||
if (!Number.isInteger(seconds) || seconds < 0) {
|
||||
throw new Error(`sql-functions: nowPlusSeconds needs a non-negative integer second count, got ${seconds}`);
|
||||
}
|
||||
if (isSqlite(platform)) return raw(`datetime('now', '+${seconds} seconds')`);
|
||||
if (isPostgres(platform)) return raw(pgTimestampText(`${PG_UTC_NOW} + INTERVAL '${seconds} seconds'`));
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3h Task 5 (doc-sync) — `FOUND_AGAIN` (`doc-sync.service.ts:53-54`), the
|
||||
// module-level SQL-text CASE constant reused by four legacy UPDATEs (DS2
|
||||
// `relocate`, DS3 `rename_remote`, DS5 `rename_local`, DS12 `touch`). Unlike
|
||||
// every other CASE in this file's DS2-DS12 neighbourhood — whose WHEN
|
||||
// condition binds a value already known in JS at the call site (a boolean
|
||||
// flag, a state string), so the whole CASE collapses to a plain JS ternary
|
||||
// deciding which field to include in a `nativeUpdate` call — this one
|
||||
// compares the ROW'S OWN CURRENT `state`/`file_id` columns, which are not
|
||||
// knowable until the UPDATE executes. That is genuinely SQL-level, and the
|
||||
// four call sites share one method (`DocumentSyncItemsRepository`'s private
|
||||
// `foundAgain` builder) rather than four independent re-derivations, per the
|
||||
// task's own instruction to keep `FOUND_AGAIN` "a reusable typed CASE
|
||||
// expression ... consumed by all four".
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `CASE WHEN <stateRef> = 'remote_missing' AND <fileIdRef> IS NOT NULL THEN
|
||||
* 'synced' ELSE <stateRef> END` — doc-sync's `FOUND_AGAIN` clause, for the
|
||||
* `state` column of an UPDATE `document_sync_items` SET list. Only a copy
|
||||
* that is BOTH on record as missing AND still paired to a file recovers this
|
||||
* way; every other state (`error`, `conflict`, a row with no file at all)
|
||||
* passes through unchanged. `remote_missing_at` is cleared unconditionally
|
||||
* by the SAME UPDATE's own `remote_missing_at = NULL` (a plain value, not
|
||||
* part of this fragment — the caller sets it alongside).
|
||||
*/
|
||||
export function foundAgainState(platform: Platform, stateRef: string, fileIdRef: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) {
|
||||
return raw(
|
||||
`CASE WHEN ${column(stateRef)} = 'remote_missing' AND ${column(fileIdRef)} IS NOT NULL THEN 'synced' ELSE ${column(stateRef)} END`,
|
||||
);
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// `UsersRepository.setImmichSettings` (IM4, #2475): the self-signed switch is
|
||||
// trusted for ONE server, so whether a null incoming value may keep the stored
|
||||
// choice depends on whether the URL written in the same SET list is the URL
|
||||
// already stored. Like `foundAgainState` above, the WHEN condition reads the
|
||||
// ROW'S OWN CURRENT column, which is not knowable in JS before the UPDATE runs
|
||||
// — a read-then-write would be two statements where the legacy SQL had one.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `CASE WHEN <keyRef> IS ? THEN COALESCE(?, <ref>) ELSE COALESCE(?, 0) END` —
|
||||
* {@link coalesceOverride}'s "new value wins unless it is null" shape, but the
|
||||
* stored column is only a valid fallback WHILE the key column still holds
|
||||
* `keyValue` (the value the same UPDATE writes to it). Once the key changes,
|
||||
* a null `value` falls back to the column's default `0` instead of a choice
|
||||
* made for a different key. SET expressions see the row as it was before the
|
||||
* UPDATE, so `<keyRef> IS ?` compares the STORED key with the new one even
|
||||
* though the same statement overwrites it. `value` is bound twice on purpose:
|
||||
* the fragment has two value slots and `raw()` binds positionally. SQLite's
|
||||
* null-safe `IS` is `IS NOT DISTINCT FROM` on Postgres.
|
||||
*/
|
||||
export function coalesceOverrideWhileSame(
|
||||
platform: Platform,
|
||||
value: number | null,
|
||||
ref: string,
|
||||
keyRef: string,
|
||||
keyValue: string,
|
||||
): RawQueryFragment {
|
||||
if (isSqlite(platform)) {
|
||||
return raw(`CASE WHEN ${column(keyRef)} IS ? THEN COALESCE(?, ${column(ref)}) ELSE COALESCE(?, 0) END`, [
|
||||
keyValue,
|
||||
value,
|
||||
value,
|
||||
]);
|
||||
}
|
||||
if (isPostgres(platform)) {
|
||||
const sql = `CASE WHEN ${column(keyRef)} IS NOT DISTINCT FROM ? THEN COALESCE(?, ${column(ref)}) ELSE COALESCE(?, 0) END`;
|
||||
return raw(sql, [keyValue, value, value]);
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tours (#2586): `DayAssignmentsRepository`'s assignment projection carries a
|
||||
// place's route geometry only when the place is a Tour, so the day list never
|
||||
// hauls an ordinary track's geometry along with every stop.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `CASE WHEN <testRef> IS NOT NULL THEN <thenRef> END`, for use as a
|
||||
* `.select()` value (chain `.as(aliasName)` at the call site). The missing
|
||||
* ELSE is deliberate: a null test column yields SQL NULL.
|
||||
*/
|
||||
export function caseWhenNotNull(platform: Platform, testRef: string, thenRef: string): RawQueryFragment {
|
||||
if (isKnownPlatform(platform)) return raw(`CASE WHEN ${column(testRef)} IS NOT NULL THEN ${column(thenRef)} END`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
/**
|
||||
* The five document providers and the fields their connection form asks for.
|
||||
*
|
||||
* Shared by the migration that introduces the tables and by `seeds.ts`, so a
|
||||
* fresh install and an upgraded one end up with the same rows. Both call sites
|
||||
* use INSERT OR IGNORE, which is what lets an operator rename or re-sort a row
|
||||
* without a later boot undoing it.
|
||||
* Shared by the migration that introduces the tables and by
|
||||
* DocumentProviderSeeder, so a fresh install and an upgraded one end up with
|
||||
* the same rows. Both insert without overwriting an existing row, which is what
|
||||
* lets an operator rename or re-sort a row without a later boot undoing it.
|
||||
*
|
||||
* `label` and `hint` are i18n key suffixes, never display text: the client
|
||||
* resolves them as `docsync.<label>`, the same way the photo provider form
|
||||
@@ -18,7 +16,7 @@ import type Database from 'better-sqlite3';
|
||||
* scanning the addon shelf should find the product they actually run.
|
||||
*/
|
||||
|
||||
interface ProviderRow {
|
||||
export interface ProviderRow {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
@@ -26,7 +24,7 @@ interface ProviderRow {
|
||||
sort_order: number;
|
||||
}
|
||||
|
||||
interface ProviderFieldRow {
|
||||
export interface ProviderFieldRow {
|
||||
provider_id: string;
|
||||
field_key: string;
|
||||
label: string;
|
||||
@@ -38,7 +36,7 @@ interface ProviderFieldRow {
|
||||
sort_order: number;
|
||||
}
|
||||
|
||||
const PROVIDERS: ProviderRow[] = [
|
||||
export const DOCUMENT_PROVIDERS: ProviderRow[] = [
|
||||
{
|
||||
id: 'paperless',
|
||||
name: 'Paperless-ngx',
|
||||
@@ -82,56 +80,258 @@ const PROVIDERS: ProviderRow[] = [
|
||||
* instance with a self-signed certificate is common enough to need the switch
|
||||
* and not common enough to justify shipping it on.
|
||||
*/
|
||||
const FIELDS: ProviderFieldRow[] = [
|
||||
export const DOCUMENT_PROVIDER_FIELDS: ProviderFieldRow[] = [
|
||||
// Paperless-ngx: token auth, tag scope.
|
||||
{ provider_id: 'paperless', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://paperless.example.com', hint: null, required: 1, secret: 0, sort_order: 0 },
|
||||
{ provider_id: 'paperless', field_key: 'api_token', label: 'providerApiToken', input_type: 'password', placeholder: 'API token', hint: 'hintPaperlessToken', required: 1, secret: 1, sort_order: 1 },
|
||||
{ provider_id: 'paperless', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 2 },
|
||||
{
|
||||
provider_id: 'paperless',
|
||||
field_key: 'base_url',
|
||||
label: 'providerUrl',
|
||||
input_type: 'url',
|
||||
placeholder: 'https://paperless.example.com',
|
||||
hint: null,
|
||||
required: 1,
|
||||
secret: 0,
|
||||
sort_order: 0,
|
||||
},
|
||||
{
|
||||
provider_id: 'paperless',
|
||||
field_key: 'api_token',
|
||||
label: 'providerApiToken',
|
||||
input_type: 'password',
|
||||
placeholder: 'API token',
|
||||
hint: 'hintPaperlessToken',
|
||||
required: 1,
|
||||
secret: 1,
|
||||
sort_order: 1,
|
||||
},
|
||||
{
|
||||
provider_id: 'paperless',
|
||||
field_key: 'allow_insecure_tls',
|
||||
label: 'allowInsecureTls',
|
||||
input_type: 'checkbox',
|
||||
placeholder: null,
|
||||
hint: null,
|
||||
required: 0,
|
||||
secret: 0,
|
||||
sort_order: 2,
|
||||
},
|
||||
|
||||
// Papra: bearer key, and an organisation the key must already belong to.
|
||||
{ provider_id: 'papra', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://papra.example.com', hint: null, required: 1, secret: 0, sort_order: 0 },
|
||||
{ provider_id: 'papra', field_key: 'api_key', label: 'providerApiKey', input_type: 'password', placeholder: 'ppapi_…', hint: 'hintPapraKey', required: 1, secret: 1, sort_order: 1 },
|
||||
{ provider_id: 'papra', field_key: 'organization_id', label: 'providerOrganization', input_type: 'text', placeholder: 'org_…', hint: 'hintPapraOrg', required: 1, secret: 0, sort_order: 2 },
|
||||
{ provider_id: 'papra', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 3 },
|
||||
{
|
||||
provider_id: 'papra',
|
||||
field_key: 'base_url',
|
||||
label: 'providerUrl',
|
||||
input_type: 'url',
|
||||
placeholder: 'https://papra.example.com',
|
||||
hint: null,
|
||||
required: 1,
|
||||
secret: 0,
|
||||
sort_order: 0,
|
||||
},
|
||||
{
|
||||
provider_id: 'papra',
|
||||
field_key: 'api_key',
|
||||
label: 'providerApiKey',
|
||||
input_type: 'password',
|
||||
placeholder: 'ppapi_…',
|
||||
hint: 'hintPapraKey',
|
||||
required: 1,
|
||||
secret: 1,
|
||||
sort_order: 1,
|
||||
},
|
||||
{
|
||||
provider_id: 'papra',
|
||||
field_key: 'organization_id',
|
||||
label: 'providerOrganization',
|
||||
input_type: 'text',
|
||||
placeholder: 'org_…',
|
||||
hint: 'hintPapraOrg',
|
||||
required: 1,
|
||||
secret: 0,
|
||||
sort_order: 2,
|
||||
},
|
||||
{
|
||||
provider_id: 'papra',
|
||||
field_key: 'allow_insecure_tls',
|
||||
label: 'allowInsecureTls',
|
||||
input_type: 'checkbox',
|
||||
placeholder: null,
|
||||
hint: null,
|
||||
required: 0,
|
||||
secret: 0,
|
||||
sort_order: 3,
|
||||
},
|
||||
|
||||
// Nextcloud: an app password, never the account password. The latter breaks
|
||||
// the moment the account turns on 2FA or logs in through OIDC.
|
||||
{ provider_id: 'nextcloud', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://cloud.example.com', hint: null, required: 1, secret: 0, sort_order: 0 },
|
||||
{ provider_id: 'nextcloud', field_key: 'login_name', label: 'providerUsername', input_type: 'text', placeholder: 'username', hint: 'hintNextcloudLogin', required: 1, secret: 0, sort_order: 1 },
|
||||
{ provider_id: 'nextcloud', field_key: 'app_password', label: 'providerAppPassword', input_type: 'password', placeholder: 'app password', hint: 'hintNextcloudAppPassword', required: 1, secret: 1, sort_order: 2 },
|
||||
{ provider_id: 'nextcloud', field_key: 'base_path', label: 'providerBasePath', input_type: 'text', placeholder: '/TREK', hint: 'hintBasePath', required: 0, secret: 0, sort_order: 3 },
|
||||
{ provider_id: 'nextcloud', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 4 },
|
||||
{
|
||||
provider_id: 'nextcloud',
|
||||
field_key: 'base_url',
|
||||
label: 'providerUrl',
|
||||
input_type: 'url',
|
||||
placeholder: 'https://cloud.example.com',
|
||||
hint: null,
|
||||
required: 1,
|
||||
secret: 0,
|
||||
sort_order: 0,
|
||||
},
|
||||
{
|
||||
provider_id: 'nextcloud',
|
||||
field_key: 'login_name',
|
||||
label: 'providerUsername',
|
||||
input_type: 'text',
|
||||
placeholder: 'username',
|
||||
hint: 'hintNextcloudLogin',
|
||||
required: 1,
|
||||
secret: 0,
|
||||
sort_order: 1,
|
||||
},
|
||||
{
|
||||
provider_id: 'nextcloud',
|
||||
field_key: 'app_password',
|
||||
label: 'providerAppPassword',
|
||||
input_type: 'password',
|
||||
placeholder: 'app password',
|
||||
hint: 'hintNextcloudAppPassword',
|
||||
required: 1,
|
||||
secret: 1,
|
||||
sort_order: 2,
|
||||
},
|
||||
{
|
||||
provider_id: 'nextcloud',
|
||||
field_key: 'base_path',
|
||||
label: 'providerBasePath',
|
||||
input_type: 'text',
|
||||
placeholder: '/TREK',
|
||||
hint: 'hintBasePath',
|
||||
required: 0,
|
||||
secret: 0,
|
||||
sort_order: 3,
|
||||
},
|
||||
{
|
||||
provider_id: 'nextcloud',
|
||||
field_key: 'allow_insecure_tls',
|
||||
label: 'allowInsecureTls',
|
||||
input_type: 'checkbox',
|
||||
placeholder: null,
|
||||
hint: null,
|
||||
required: 0,
|
||||
secret: 0,
|
||||
sort_order: 4,
|
||||
},
|
||||
|
||||
// OpenCloud: auth-app token, spaces instead of folders.
|
||||
{ provider_id: 'opencloud', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://opencloud.example.com', hint: null, required: 1, secret: 0, sort_order: 0 },
|
||||
{ provider_id: 'opencloud', field_key: 'username', label: 'providerUsername', input_type: 'text', placeholder: 'username', hint: null, required: 1, secret: 0, sort_order: 1 },
|
||||
{ provider_id: 'opencloud', field_key: 'app_token', label: 'providerAppToken', input_type: 'password', placeholder: 'app token', hint: 'hintOpenCloudToken', required: 1, secret: 1, sort_order: 2 },
|
||||
{ provider_id: 'opencloud', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 3 },
|
||||
{
|
||||
provider_id: 'opencloud',
|
||||
field_key: 'base_url',
|
||||
label: 'providerUrl',
|
||||
input_type: 'url',
|
||||
placeholder: 'https://opencloud.example.com',
|
||||
hint: null,
|
||||
required: 1,
|
||||
secret: 0,
|
||||
sort_order: 0,
|
||||
},
|
||||
{
|
||||
provider_id: 'opencloud',
|
||||
field_key: 'username',
|
||||
label: 'providerUsername',
|
||||
input_type: 'text',
|
||||
placeholder: 'username',
|
||||
hint: null,
|
||||
required: 1,
|
||||
secret: 0,
|
||||
sort_order: 1,
|
||||
},
|
||||
{
|
||||
provider_id: 'opencloud',
|
||||
field_key: 'app_token',
|
||||
label: 'providerAppToken',
|
||||
input_type: 'password',
|
||||
placeholder: 'app token',
|
||||
hint: 'hintOpenCloudToken',
|
||||
required: 1,
|
||||
secret: 1,
|
||||
sort_order: 2,
|
||||
},
|
||||
{
|
||||
provider_id: 'opencloud',
|
||||
field_key: 'allow_insecure_tls',
|
||||
label: 'allowInsecureTls',
|
||||
input_type: 'checkbox',
|
||||
placeholder: null,
|
||||
hint: null,
|
||||
required: 0,
|
||||
secret: 0,
|
||||
sort_order: 3,
|
||||
},
|
||||
|
||||
// Synology: DSM has no app tokens at all, so this is a real account. The OTP
|
||||
// is used once to obtain a device token, which is what gets stored.
|
||||
{ provider_id: 'synologydrive', field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://nas.example.com:5001', hint: 'hintSynologyUrl', required: 1, secret: 0, sort_order: 0 },
|
||||
{ provider_id: 'synologydrive', field_key: 'username', label: 'providerUsername', input_type: 'text', placeholder: 'username', hint: 'hintSynologyUser', required: 1, secret: 0, sort_order: 1 },
|
||||
{ provider_id: 'synologydrive', field_key: 'password', label: 'providerPassword', input_type: 'password', placeholder: 'password', hint: null, required: 1, secret: 1, sort_order: 2 },
|
||||
{ provider_id: 'synologydrive', field_key: 'otp_code', label: 'providerOTP', input_type: 'text', placeholder: '123456', hint: 'hintSynologyOtp', required: 0, secret: 1, sort_order: 3 },
|
||||
{ provider_id: 'synologydrive', field_key: 'base_path', label: 'providerBasePath', input_type: 'text', placeholder: '/trek', hint: 'hintBasePath', required: 0, secret: 0, sort_order: 4 },
|
||||
{ provider_id: 'synologydrive', field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: 0, secret: 0, sort_order: 5 },
|
||||
{
|
||||
provider_id: 'synologydrive',
|
||||
field_key: 'base_url',
|
||||
label: 'providerUrl',
|
||||
input_type: 'url',
|
||||
placeholder: 'https://nas.example.com:5001',
|
||||
hint: 'hintSynologyUrl',
|
||||
required: 1,
|
||||
secret: 0,
|
||||
sort_order: 0,
|
||||
},
|
||||
{
|
||||
provider_id: 'synologydrive',
|
||||
field_key: 'username',
|
||||
label: 'providerUsername',
|
||||
input_type: 'text',
|
||||
placeholder: 'username',
|
||||
hint: 'hintSynologyUser',
|
||||
required: 1,
|
||||
secret: 0,
|
||||
sort_order: 1,
|
||||
},
|
||||
{
|
||||
provider_id: 'synologydrive',
|
||||
field_key: 'password',
|
||||
label: 'providerPassword',
|
||||
input_type: 'password',
|
||||
placeholder: 'password',
|
||||
hint: null,
|
||||
required: 1,
|
||||
secret: 1,
|
||||
sort_order: 2,
|
||||
},
|
||||
{
|
||||
provider_id: 'synologydrive',
|
||||
field_key: 'otp_code',
|
||||
label: 'providerOTP',
|
||||
input_type: 'text',
|
||||
placeholder: '123456',
|
||||
hint: 'hintSynologyOtp',
|
||||
required: 0,
|
||||
secret: 1,
|
||||
sort_order: 3,
|
||||
},
|
||||
{
|
||||
provider_id: 'synologydrive',
|
||||
field_key: 'base_path',
|
||||
label: 'providerBasePath',
|
||||
input_type: 'text',
|
||||
placeholder: '/trek',
|
||||
hint: 'hintBasePath',
|
||||
required: 0,
|
||||
secret: 0,
|
||||
sort_order: 4,
|
||||
},
|
||||
{
|
||||
provider_id: 'synologydrive',
|
||||
field_key: 'allow_insecure_tls',
|
||||
label: 'allowInsecureTls',
|
||||
input_type: 'checkbox',
|
||||
placeholder: null,
|
||||
hint: null,
|
||||
required: 0,
|
||||
secret: 0,
|
||||
sort_order: 5,
|
||||
},
|
||||
];
|
||||
|
||||
export function seedDocumentProviders(db: Database.Database): void {
|
||||
const insertProvider = db.prepare(
|
||||
'INSERT OR IGNORE INTO document_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, 0, ?)',
|
||||
);
|
||||
for (const p of PROVIDERS) insertProvider.run(p.id, p.name, p.description, p.icon, p.sort_order);
|
||||
|
||||
const insertField = db.prepare(
|
||||
`INSERT OR IGNORE INTO document_provider_fields
|
||||
(provider_id, field_key, label, input_type, placeholder, hint, required, secret, sort_order)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
);
|
||||
for (const f of FIELDS) {
|
||||
insertField.run(f.provider_id, f.field_key, f.label, f.input_type, f.placeholder, f.hint, f.required, f.secret, f.sort_order);
|
||||
}
|
||||
}
|
||||
|
||||
export const DOCUMENT_PROVIDER_SEED_IDS = PROVIDERS.map((p) => p.id);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { readEnv } from '../app-config';
|
||||
import { synchronousName } from '../app-config/parsers';
|
||||
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
export interface ActiveDurability {
|
||||
journalMode: string;
|
||||
synchronous: string;
|
||||
@@ -24,7 +25,7 @@ export interface ActiveDurability {
|
||||
*/
|
||||
export function applyDurabilityPragmas(db: Database.Database): ActiveDurability {
|
||||
const { journalMode, synchronous, durabilityWarnings } = readEnv().db;
|
||||
durabilityWarnings.forEach(warning => console.warn(`[DB] ${warning}`));
|
||||
durabilityWarnings.forEach((warning) => console.warn(`[DB] ${warning}`));
|
||||
|
||||
db.exec(`PRAGMA journal_mode = ${journalMode}`);
|
||||
db.exec(`PRAGMA synchronous = ${synchronous}`);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Connection } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* The case-insensitive unique index on users.email, when its migration had to
|
||||
* leave it out.
|
||||
*
|
||||
* `Migration20200101042400_one_account_per_email_whatever_its_case` creates
|
||||
* `idx_users_email_lower` unless two accounts already share an address in
|
||||
* different case; then it records `email_case_index_pending` and the install
|
||||
* boots without it. A migration runs once, so this runs on every boot while
|
||||
* that flag is set: once the accounts were told apart it creates the index and
|
||||
* clears the flag, until then it repeats the warning.
|
||||
*/
|
||||
|
||||
const PENDING_KEY = 'email_case_index_pending';
|
||||
|
||||
export async function ensureEmailCaseIndex(connection: Connection): Promise<void> {
|
||||
const pending: unknown[] = await connection.execute(`SELECT value FROM app_settings WHERE key = ?`, [PENDING_KEY]);
|
||||
if (pending.length === 0) return;
|
||||
|
||||
const duplicates: Array<{ ids: string }> = await connection.execute(
|
||||
`SELECT group_concat(id, ', ') AS ids FROM (SELECT id, email FROM users ORDER BY id) GROUP BY lower(email) HAVING COUNT(*) > 1`,
|
||||
);
|
||||
if (duplicates.length > 0) {
|
||||
console.warn(
|
||||
`[DB] ${duplicates.length} email address(es) still belong to more than one account when case is ignored ` +
|
||||
`(user ids ${duplicates.map((row) => row.ids).join('; ')}), so users.email has no case-insensitive unique ` +
|
||||
'index yet. Give each of those accounts its own address under Admin > Users; the next start creates it.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await connection.transactional(async (trx) => {
|
||||
await connection.execute(
|
||||
'CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_lower ON users (lower(email))',
|
||||
[],
|
||||
'run',
|
||||
trx,
|
||||
);
|
||||
await connection.execute('DELETE FROM app_settings WHERE key = ?', [PENDING_KEY], 'run', trx);
|
||||
});
|
||||
console.log(
|
||||
'[DB] Every account has its own email address now; created the case-insensitive unique index on users.email',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { EntityRepositoryType, type Opt, defineEntity, p } from '@mikro-orm/core';
|
||||
import { AddonsRepository } from '../repositories/Addons.repository';
|
||||
|
||||
export interface AddonConfig {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export class Addons {
|
||||
[EntityRepositoryType]?: AddonsRepository;
|
||||
id?: string | null;
|
||||
name!: string;
|
||||
description?: string | null;
|
||||
type: string & Opt = 'global';
|
||||
icon?: string | null = 'Puzzle';
|
||||
enabled?: boolean | null = false;
|
||||
config?: AddonConfig | null;
|
||||
sort_order?: number | null = 0;
|
||||
}
|
||||
|
||||
export const AddonsSchema = defineEntity({
|
||||
class: Addons,
|
||||
repository: () => AddonsRepository,
|
||||
properties: {
|
||||
id: p.text().primary().nullable(),
|
||||
name: p.text(),
|
||||
description: p.text().nullable(),
|
||||
type: p.text().default('global'),
|
||||
icon: p.text().nullable(),
|
||||
enabled: p.boolean().nullable(),
|
||||
config: p.json<AddonConfig>().nullable().default('{}'),
|
||||
sort_order: p.integer().nullable(),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { AiConnectionsRepository } from '../repositories/AiConnections.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { Users } from './Users.entity';
|
||||
|
||||
export class AiConnections {
|
||||
[EntityRepositoryType]?: AiConnectionsRepository;
|
||||
id!: number & Opt;
|
||||
scope!: string;
|
||||
user?: Ref<Users> | null;
|
||||
user_id?: number | null;
|
||||
kind!: string;
|
||||
model!: string;
|
||||
base_url?: string | null;
|
||||
secrets?: string | null;
|
||||
secrets_version: number & Opt = 0;
|
||||
hint?: string | null;
|
||||
account?: string | null;
|
||||
status: string & Opt = 'ok';
|
||||
created_at!: string & Opt;
|
||||
updated_at!: string & Opt;
|
||||
}
|
||||
|
||||
export const AiConnectionsSchema = defineEntity({
|
||||
class: AiConnections,
|
||||
repository: () => AiConnectionsRepository,
|
||||
uniques: [
|
||||
{
|
||||
name: 'idx_ai_connections_instance',
|
||||
where: 'user_id IS NULL',
|
||||
properties: ['scope'],
|
||||
},
|
||||
{
|
||||
name: 'idx_ai_connections_user',
|
||||
where: 'user_id IS NOT NULL',
|
||||
properties: ['user_id'],
|
||||
},
|
||||
],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
scope: p.text(),
|
||||
user: () => p.manyToOne(Users).ref().deleteRule('cascade').nullable().hidden(),
|
||||
user_id: p.integer().nullable().persist(false),
|
||||
kind: p.text(),
|
||||
model: p.text(),
|
||||
base_url: p.text().nullable(),
|
||||
secrets: p.text().nullable(),
|
||||
secrets_version: p.integer().default(0),
|
||||
hint: p.text().nullable(),
|
||||
account: p.text().nullable(),
|
||||
status: p.text().default('ok'),
|
||||
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
updated_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { EntityRepositoryType, PrimaryKeyProp, defineEntity, p } from '@mikro-orm/core';
|
||||
import { AppSettingsRepository } from '../repositories/AppSettings.repository';
|
||||
|
||||
export class AppSettings {
|
||||
[EntityRepositoryType]?: AppSettingsRepository;
|
||||
[PrimaryKeyProp]?: 'key';
|
||||
key?: string | null;
|
||||
value?: string | null;
|
||||
}
|
||||
|
||||
export const AppSettingsSchema = defineEntity({
|
||||
class: AppSettings,
|
||||
repository: () => AppSettingsRepository,
|
||||
properties: {
|
||||
key: p.text().primary().nullable(),
|
||||
value: p.text().nullable(),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { AssignmentParticipantsRepository } from '../repositories/AssignmentParticipants.repository';
|
||||
import { DayAssignments } from './DayAssignments.entity';
|
||||
import { Users } from './Users.entity';
|
||||
|
||||
export class AssignmentParticipants {
|
||||
[EntityRepositoryType]?: AssignmentParticipantsRepository;
|
||||
id!: number & Opt;
|
||||
assignment!: Ref<DayAssignments>;
|
||||
assignment_id!: number;
|
||||
user!: Ref<Users>;
|
||||
user_id!: number;
|
||||
}
|
||||
|
||||
export const AssignmentParticipantsSchema = defineEntity({
|
||||
class: AssignmentParticipants,
|
||||
repository: () => AssignmentParticipantsRepository,
|
||||
uniques: [{ properties: ['assignment', 'user'] }],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
assignment: () => p.manyToOne(DayAssignments).ref().deleteRule('cascade').hidden().index('idx_assignment_participants_assignment'),
|
||||
assignment_id: p.integer().persist(false).index('idx_assignment_participants_assignment'),
|
||||
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_assignment_participants_user_id'),
|
||||
user_id: p.integer().persist(false).index('idx_assignment_participants_user_id'),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { AssistantAttachmentsRepository } from '../repositories/AssistantAttachments.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { AssistantThreads } from './AssistantThreads.entity';
|
||||
import { TripFiles } from './TripFiles.entity';
|
||||
import { Trips } from './Trips.entity';
|
||||
import { Users } from './Users.entity';
|
||||
|
||||
export class AssistantAttachments {
|
||||
[EntityRepositoryType]?: AssistantAttachmentsRepository;
|
||||
id!: string;
|
||||
thread!: Ref<AssistantThreads>;
|
||||
thread_id!: number;
|
||||
user!: Ref<Users>;
|
||||
user_id!: number;
|
||||
trip!: Ref<Trips>;
|
||||
trip_id!: number;
|
||||
name!: string;
|
||||
mime!: string;
|
||||
size!: number;
|
||||
sha256!: string;
|
||||
storage_key!: string;
|
||||
text?: string | null;
|
||||
text_status!: string;
|
||||
shared_at?: string | null;
|
||||
file?: Ref<TripFiles> | null;
|
||||
file_id?: number | null;
|
||||
created_at!: string & Opt;
|
||||
}
|
||||
|
||||
export const AssistantAttachmentsSchema = defineEntity({
|
||||
class: AssistantAttachments,
|
||||
repository: () => AssistantAttachmentsRepository,
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_assistant_attachments_thread',
|
||||
properties: ['thread_id', 'created_at'],
|
||||
},
|
||||
],
|
||||
properties: {
|
||||
id: p.text().primary(),
|
||||
thread: () => p.manyToOne(AssistantThreads).ref().deleteRule('cascade').hidden(),
|
||||
thread_id: p.integer().persist(false),
|
||||
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_assistant_attachments_user'),
|
||||
user_id: p.integer().persist(false).index('idx_assistant_attachments_user'),
|
||||
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_assistant_attachments_trip'),
|
||||
trip_id: p.integer().persist(false).index('idx_assistant_attachments_trip'),
|
||||
name: p.text(),
|
||||
mime: p.text(),
|
||||
size: p.integer(),
|
||||
sha256: p.text(),
|
||||
storage_key: p.text(),
|
||||
text: p.text().nullable(),
|
||||
text_status: p.text(),
|
||||
shared_at: p.type(DbTimestampType).nullable(),
|
||||
file: () => p.manyToOne(TripFiles).ref().nullable().hidden().index('idx_assistant_attachments_file'),
|
||||
file_id: p.integer().nullable().persist(false).index('idx_assistant_attachments_file'),
|
||||
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`).index('idx_assistant_attachments_created'),
|
||||
},
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user