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:
Maurice
2026-10-25 17:04:15 +01:00
11842 changed files with 1361077 additions and 180501 deletions
+4 -1
View File
@@ -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,
];
+94 -8
View File
@@ -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.
+73
View File
@@ -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;
+8 -4
View File
@@ -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();
+63
View File
@@ -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'),
};
}
+68 -18
View File
@@ -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),
};
}
+39 -6
View File
@@ -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,
+65 -1
View File
@@ -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;
+33
View File
@@ -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;
}
+4
View File
@@ -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';
+25
View File
@@ -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'];
}
}
+48 -4
View File
@@ -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;
}
}
+11
View File
@@ -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
View File
@@ -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
View File
@@ -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);
+28
View File
@@ -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
View File
@@ -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 };
+29
View File
@@ -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;
}
+275
View 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);
}
+64
View File
@@ -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}';
+843
View File
@@ -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);
}
+250 -50
View File
@@ -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);
+3 -2
View File
@@ -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}`);
+45
View File
@@ -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',
);
}
+33
View File
@@ -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'),
},
});
@@ -0,0 +1,39 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantMessagesRepository } from '../repositories/AssistantMessages.repository';
import { DbTimestampType } from '../types';
import { AssistantThreads } from './AssistantThreads.entity';
import { AssistantToolCalls } from './AssistantToolCalls.entity';
export class AssistantMessages {
[EntityRepositoryType]?: AssistantMessagesRepository;
id!: number & Opt;
thread!: Ref<AssistantThreads>;
thread_id!: number;
role!: string;
parts!: string;
provider_state?: string | null;
status: string & Opt = 'complete';
model?: string | null;
created_at!: string & Opt;
assistant_tool_calls_collection = new Collection<AssistantToolCalls>(this);
}
export const AssistantMessagesSchema = defineEntity({
class: AssistantMessages,
repository: () => AssistantMessagesRepository,
indexes: [
{ name: 'idx_assistant_messages_thread', properties: ['thread_id', 'id'] },
],
properties: {
id: p.integer().primary(),
thread: () => p.manyToOne(AssistantThreads).ref().deleteRule('cascade').hidden(),
thread_id: p.integer().persist(false),
role: p.text(),
parts: p.text(),
provider_state: p.text().nullable(),
status: p.text().default('complete'),
model: p.text().nullable(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
assistant_tool_calls_collection: () => p.oneToMany(AssistantToolCalls).mappedBy('message').hidden(),
},
});
@@ -0,0 +1,56 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantThreadsRepository } from '../repositories/AssistantThreads.repository';
import { DbTimestampType } from '../types';
import { AssistantAttachments } from './AssistantAttachments.entity';
import { AssistantMessages } from './AssistantMessages.entity';
import { AssistantToolCalls } from './AssistantToolCalls.entity';
import { Journeys } from './Journeys.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class AssistantThreads {
[EntityRepositoryType]?: AssistantThreadsRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
trip?: Ref<Trips> | null;
trip_id?: number | null;
journey?: Ref<Journeys> | null;
journey_id?: number | null;
title!: string;
created_at!: string & Opt;
last_message_at!: string & Opt;
assistant_attachments_collection = new Collection<AssistantAttachments>(this);
assistant_messages_collection = new Collection<AssistantMessages>(this);
assistant_tool_calls_collection = new Collection<AssistantToolCalls>(this);
}
export const AssistantThreadsSchema = defineEntity({
class: AssistantThreads,
repository: () => AssistantThreadsRepository,
indexes: [
{
name: 'idx_assistant_threads_user_trip',
properties: ['user_id', 'trip_id', 'last_message_at'],
},
{
name: 'idx_assistant_threads_user_journey',
properties: ['user_id', 'journey_id', 'last_message_at'],
},
],
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').nullable().hidden().index('idx_assistant_threads_trip'),
trip_id: p.integer().nullable().persist(false).index('idx_assistant_threads_trip'),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').nullable().hidden().index('idx_assistant_threads_journey'),
journey_id: p.integer().nullable().persist(false).index('idx_assistant_threads_journey'),
title: p.text(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
last_message_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
assistant_attachments_collection: () => p.oneToMany(AssistantAttachments).mappedBy('thread').hidden(),
assistant_messages_collection: () => p.oneToMany(AssistantMessages).mappedBy('thread').hidden(),
assistant_tool_calls_collection: () => p.oneToMany(AssistantToolCalls).mappedBy('thread').hidden(),
},
});
@@ -0,0 +1,45 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantToolCallsRepository } from '../repositories/AssistantToolCalls.repository';
import { DbTimestampType } from '../types';
import { AssistantMessages } from './AssistantMessages.entity';
import { AssistantThreads } from './AssistantThreads.entity';
export class AssistantToolCalls {
[EntityRepositoryType]?: AssistantToolCallsRepository;
id!: string;
thread!: Ref<AssistantThreads>;
thread_id!: number;
message!: Ref<AssistantMessages>;
message_id!: number;
provider_call_id!: string;
tool_name!: string;
args!: string;
preview!: string;
state: string & Opt = 'approval_requested';
result?: string | null;
undo_until?: string | null;
created_at!: string & Opt;
decided_at?: string | null;
}
export const AssistantToolCallsSchema = defineEntity({
class: AssistantToolCalls,
repository: () => AssistantToolCallsRepository,
uniques: [{ properties: ['thread', 'provider_call_id'] }],
properties: {
id: p.text().primary(),
thread: () => p.manyToOne(AssistantThreads).ref().deleteRule('cascade').hidden(),
thread_id: p.integer().persist(false),
message: () => p.manyToOne(AssistantMessages).ref().deleteRule('cascade').hidden().index('idx_assistant_tool_calls_message'),
message_id: p.integer().persist(false).index('idx_assistant_tool_calls_message'),
provider_call_id: p.text(),
tool_name: p.text(),
args: p.text(),
preview: p.text(),
state: p.text().default('approval_requested'),
result: p.text().nullable(),
undo_until: p.type(DbTimestampType).nullable(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
decided_at: p.type(DbTimestampType).nullable(),
},
});
@@ -0,0 +1,30 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantUsageRepository } from '../repositories/AssistantUsage.repository';
import { Users } from './Users.entity';
export class AssistantUsage {
[EntityRepositoryType]?: AssistantUsageRepository;
[PrimaryKeyProp]?: ['user', 'day', 'paid_by'];
user!: Ref<Users>;
user_id!: number;
day!: string;
paid_by!: string;
turns: number & Opt = 0;
input_tokens: number & Opt = 0;
output_tokens: number & Opt = 0;
}
export const AssistantUsageSchema = defineEntity({
class: AssistantUsage,
repository: () => AssistantUsageRepository,
uniques: [{ properties: ['user', 'day', 'paid_by'] }],
properties: {
user: () => p.manyToOne(Users).primary().ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
day: p.text().primary(),
paid_by: p.text().primary(),
turns: p.integer().default(0),
input_tokens: p.integer().default(0),
output_tokens: p.integer().default(0),
},
});
+31
View File
@@ -0,0 +1,31 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AuditLogRepository } from '../repositories/AuditLog.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class AuditLog {
[EntityRepositoryType]?: AuditLogRepository;
id!: number & Opt;
created_at?: string | null;
user?: Ref<Users> | null;
user_id?: number | null;
action!: string;
resource?: string | null;
details?: string | null;
ip?: string | null;
}
export const AuditLogSchema = defineEntity({
class: AuditLog,
repository: () => AuditLogRepository,
properties: {
id: p.integer().primary(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`).index('idx_audit_log_created'),
user: () => p.manyToOne(Users).ref().nullable().hidden().index('idx_audit_log_user_id'),
user_id: p.integer().nullable().persist(false).index('idx_audit_log_user_id'),
action: p.text(),
resource: p.text().nullable(),
details: p.text().nullable(),
ip: p.text().nullable(),
},
});
@@ -0,0 +1,46 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { BucketListRepository } from '../repositories/BucketList.repository';
import { DbTimestampType } from '../types';
import { DawarichVisitSuggestions } from './DawarichVisitSuggestions.entity';
import { Users } from './Users.entity';
export class BucketList {
[EntityRepositoryType]?: BucketListRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
name!: string;
lat?: number | null;
lng?: number | null;
country_code?: string | null;
notes?: string | null;
created_at?: string | null;
target_date?: string | null;
visited_at?: string | null;
visited_source?: string | null;
region_code?: string | null;
dawarich_visit_suggestions_collection = new Collection<DawarichVisitSuggestions>(this);
dawarich_visit_suggestions_collection1 = new Collection<DawarichVisitSuggestions>(this);
}
export const BucketListSchema = defineEntity({
class: BucketList,
repository: () => BucketListRepository,
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_bucket_list_user_id'),
user_id: p.integer().persist(false).index('idx_bucket_list_user_id'),
name: p.text(),
lat: p.double().nullable(),
lng: p.double().nullable(),
country_code: p.text().nullable(),
notes: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
target_date: p.text().nullable().defaultRaw(`NULL`),
visited_at: p.text().nullable(),
visited_source: p.text().nullable(),
region_code: p.text().nullable(),
dawarich_visit_suggestions_collection: () => p.oneToMany(DawarichVisitSuggestions).mappedBy('acceptedBucketListItem').hidden(),
dawarich_visit_suggestions_collection1: () => p.oneToMany(DawarichVisitSuggestions).mappedBy('matchedBucketListItem').hidden(),
},
});
@@ -0,0 +1,24 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { BudgetCategoryOrderRepository } from '../repositories/BudgetCategoryOrder.repository';
import { Trips } from './Trips.entity';
export class BudgetCategoryOrder {
[EntityRepositoryType]?: BudgetCategoryOrderRepository;
[PrimaryKeyProp]?: ['trip', 'category'];
trip!: Ref<Trips>;
trip_id!: number;
category!: string;
sort_order: number & Opt = 0;
}
export const BudgetCategoryOrderSchema = defineEntity({
class: BudgetCategoryOrder,
repository: () => BudgetCategoryOrderRepository,
uniques: [{ properties: ['trip', 'category'] }],
properties: {
trip: () => p.manyToOne(Trips).primary().ref().deleteRule('cascade').hidden(),
trip_id: p.integer().persist(false),
category: p.text().primary(),
sort_order: p.integer().default(0),
},
});
@@ -0,0 +1,30 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { BudgetItemMembersRepository } from '../repositories/BudgetItemMembers.repository';
import { BudgetItems } from './BudgetItems.entity';
import { Users } from './Users.entity';
export class BudgetItemMembers {
[EntityRepositoryType]?: BudgetItemMembersRepository;
id!: number & Opt;
budgetItem!: Ref<BudgetItems>;
budget_item_id!: number;
user!: Ref<Users>;
user_id!: number;
paid: number & Opt = 0;
amount?: number | null;
}
export const BudgetItemMembersSchema = defineEntity({
class: BudgetItemMembers,
repository: () => BudgetItemMembersRepository,
uniques: [{ properties: ['budgetItem', 'user'] }],
properties: {
id: p.integer().primary(),
budgetItem: () => p.manyToOne(BudgetItems).ref().deleteRule('cascade').hidden().index('idx_budget_item_members_item'),
budget_item_id: p.integer().persist(false).index('idx_budget_item_members_item'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_budget_item_members_user'),
user_id: p.integer().persist(false).index('idx_budget_item_members_user'),
paid: p.integer().default(0),
amount: p.double().nullable(),
},
});
@@ -0,0 +1,28 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { BudgetItemPayersRepository } from '../repositories/BudgetItemPayers.repository';
import { BudgetItems } from './BudgetItems.entity';
import { Users } from './Users.entity';
export class BudgetItemPayers {
[EntityRepositoryType]?: BudgetItemPayersRepository;
id!: number & Opt;
budgetItem!: Ref<BudgetItems>;
budget_item_id!: number;
user!: Ref<Users>;
user_id!: number;
amount!: number & Opt;
}
export const BudgetItemPayersSchema = defineEntity({
class: BudgetItemPayers,
repository: () => BudgetItemPayersRepository,
uniques: [{ properties: ['budgetItem', 'user'] }],
properties: {
id: p.integer().primary(),
budgetItem: () => p.manyToOne(BudgetItems).ref().deleteRule('cascade').hidden().index('idx_budget_item_payers_item'),
budget_item_id: p.integer().persist(false).index('idx_budget_item_payers_item'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_budget_item_payers_user_id'),
user_id: p.integer().persist(false).index('idx_budget_item_payers_user_id'),
amount: p.double().defaultRaw(`0`),
},
});
@@ -0,0 +1,69 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { BudgetItemsRepository } from '../repositories/BudgetItems.repository';
import { DbTimestampType } from '../types';
import { BudgetItemMembers } from './BudgetItemMembers.entity';
import { BudgetItemPayers } from './BudgetItemPayers.entity';
import { FileLinks } from './FileLinks.entity';
import { Places } from './Places.entity';
import { Reservations } from './Reservations.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class BudgetItems {
[EntityRepositoryType]?: BudgetItemsRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
category: string & Opt = 'Other';
name!: string;
total_price!: number & Opt;
persons?: number | null;
days?: number | null;
note?: string | null;
sort_order?: number | null = 0;
created_at?: string | null;
paidByUser?: Ref<Users> | null;
paid_by_user_id?: number | null;
expense_date?: string | null;
reservation?: Ref<Reservations> | null;
reservation_id?: number | null;
currency?: string | null;
exchange_rate!: number & Opt;
ticket_json?: string | null;
place?: Ref<Places> | null;
place_id?: number | null;
budget_item_members_collection = new Collection<BudgetItemMembers>(this);
budget_item_payers_collection = new Collection<BudgetItemPayers>(this);
file_links_collection = new Collection<FileLinks>(this);
}
export const BudgetItemsSchema = defineEntity({
class: BudgetItems,
repository: () => BudgetItemsRepository,
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_budget_items_trip_id'),
trip_id: p.integer().persist(false).index('idx_budget_items_trip_id'),
category: p.text().default('Other'),
name: p.text(),
total_price: p.double().defaultRaw(`0`),
persons: p.integer().nullable().defaultRaw(`NULL`),
days: p.integer().nullable().defaultRaw(`NULL`),
note: p.text().nullable(),
sort_order: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
paidByUser: () => p.manyToOne(Users).ref().deleteRule('no action').nullable().hidden().index('idx_budget_items_paid_by_user_id'),
paid_by_user_id: p.integer().nullable().persist(false).index('idx_budget_items_paid_by_user_id'),
expense_date: p.text().nullable().defaultRaw(`NULL`),
reservation: () => p.manyToOne(Reservations).ref().nullable().hidden().defaultRaw(`NULL`).index('idx_budget_items_reservation_id'),
reservation_id: p.integer().nullable().persist(false).defaultRaw(`NULL`).index('idx_budget_items_reservation_id'),
currency: p.text().nullable(),
exchange_rate: p.double().defaultRaw(`1`),
ticket_json: p.text().nullable(),
place: () => p.manyToOne(Places).ref().nullable().hidden().defaultRaw(`NULL`).index('idx_budget_items_place_id'),
place_id: p.integer().nullable().persist(false).defaultRaw(`NULL`).index('idx_budget_items_place_id'),
budget_item_members_collection: () => p.oneToMany(BudgetItemMembers).mappedBy('budgetItem').hidden(),
budget_item_payers_collection: () => p.oneToMany(BudgetItemPayers).mappedBy('budgetItem').hidden(),
file_links_collection: () => p.oneToMany(FileLinks).mappedBy('budgetItem').hidden(),
},
});
@@ -0,0 +1,46 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { BudgetSettlementsRepository } from '../repositories/BudgetSettlements.repository';
import { DbTimestampType } from '../types';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class BudgetSettlements {
[EntityRepositoryType]?: BudgetSettlementsRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
fromUser!: Ref<Users>;
from_user_id!: number;
toUser!: Ref<Users>;
to_user_id!: number;
amount!: number & Opt;
created_at?: string | null;
createdByUser?: Ref<Users> | null;
created_by_user_id?: number | null;
currency?: string | null;
exchange_rate!: number & Opt;
settled_at?: string | null;
note?: string | null;
}
export const BudgetSettlementsSchema = defineEntity({
class: BudgetSettlements,
repository: () => BudgetSettlementsRepository,
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_budget_settlements_trip'),
trip_id: p.integer().persist(false).index('idx_budget_settlements_trip'),
fromUser: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_budget_settlements_from_user_id'),
from_user_id: p.integer().persist(false).index('idx_budget_settlements_from_user_id'),
toUser: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_budget_settlements_to_user_id'),
to_user_id: p.integer().persist(false).index('idx_budget_settlements_to_user_id'),
amount: p.double().defaultRaw(`0`),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
createdByUser: () => p.manyToOne(Users).ref().deleteRule('no action').nullable().hidden().index('idx_budget_settlements_created_by_user_id'),
created_by_user_id: p.integer().nullable().persist(false).index('idx_budget_settlements_created_by_user_id'),
currency: p.text().nullable(),
exchange_rate: p.double().defaultRaw(`1`),
settled_at: p.text().nullable(),
note: p.text().nullable(),
},
});
@@ -0,0 +1,35 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CategoriesRepository } from '../repositories/Categories.repository';
import { DbTimestampType } from '../types';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { Places } from './Places.entity';
import { Users } from './Users.entity';
export class Categories {
[EntityRepositoryType]?: CategoriesRepository;
id!: number & Opt;
name!: string;
color?: string | null = '#6366f1';
icon?: string | null = '📍';
user?: Ref<Users> | null;
user_id?: number | null;
created_at?: string | null;
collection_places_collection = new Collection<CollectionPlaces>(this);
places_collection = new Collection<Places>(this);
}
export const CategoriesSchema = defineEntity({
class: Categories,
repository: () => CategoriesRepository,
properties: {
id: p.integer().primary(),
name: p.text(),
color: p.text().nullable(),
icon: p.text().nullable(),
user: () => p.manyToOne(Users).ref().nullable().hidden().index('idx_categories_user_id'),
user_id: p.integer().nullable().persist(false).index('idx_categories_user_id'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
collection_places_collection: () => p.oneToMany(CollectionPlaces).mappedBy('category').hidden(),
places_collection: () => p.oneToMany(Places).mappedBy('category').hidden(),
},
});
@@ -0,0 +1,36 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollabLinksRepository } from '../repositories/CollabLinks.repository';
import { DbTimestampType } from '../types';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class CollabLinks {
[EntityRepositoryType]?: CollabLinksRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
user!: Ref<Users>;
user_id!: number;
title!: string;
url!: string;
pinned?: number | null = 0;
created_at?: string | null;
updated_at?: string | null;
}
export const CollabLinksSchema = defineEntity({
class: CollabLinks,
repository: () => CollabLinksRepository,
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_collab_links_trip'),
trip_id: p.integer().persist(false).index('idx_collab_links_trip'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collab_links_user_id'),
user_id: p.integer().persist(false).index('idx_collab_links_user_id'),
title: p.text(),
url: p.text(),
pinned: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,31 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollabMessageReactionsRepository } from '../repositories/CollabMessageReactions.repository';
import { DbTimestampType } from '../types';
import { CollabMessages } from './CollabMessages.entity';
import { Users } from './Users.entity';
export class CollabMessageReactions {
[EntityRepositoryType]?: CollabMessageReactionsRepository;
id!: number & Opt;
message!: Ref<CollabMessages>;
message_id!: number;
user!: Ref<Users>;
user_id!: number;
emoji!: string;
created_at?: string | null;
}
export const CollabMessageReactionsSchema = defineEntity({
class: CollabMessageReactions,
repository: () => CollabMessageReactionsRepository,
uniques: [{ properties: ['message', 'user', 'emoji'] }],
properties: {
id: p.integer().primary(),
message: () => p.manyToOne(CollabMessages).ref().deleteRule('cascade').hidden().index('idx_collab_reactions_msg'),
message_id: p.integer().persist(false).index('idx_collab_reactions_msg'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collab_message_reactions_user_id'),
user_id: p.integer().persist(false).index('idx_collab_message_reactions_user_id'),
emoji: p.text(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,46 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollabMessagesRepository } from '../repositories/CollabMessages.repository';
import { DbTimestampType } from '../types';
import { CollabMessageReactions } from './CollabMessageReactions.entity';
import { TripFiles } from './TripFiles.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class CollabMessages {
[EntityRepositoryType]?: CollabMessagesRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
user!: Ref<Users>;
user_id!: number;
text!: string;
reply_to?: number | null;
created_at?: string | null;
deleted?: number | null = 0;
origin?: string | null;
replyToRef?: Ref<CollabMessages> | null;
collab_message_reactions_collection = new Collection<CollabMessageReactions>(this);
collab_messages_collection = new Collection<CollabMessages>(this);
trip_files_collection = new Collection<TripFiles>(this);
}
export const CollabMessagesSchema = defineEntity({
class: CollabMessages,
repository: () => CollabMessagesRepository,
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_collab_messages_trip'),
trip_id: p.integer().persist(false).index('idx_collab_messages_trip'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collab_messages_user_id'),
user_id: p.integer().persist(false).index('idx_collab_messages_user_id'),
text: p.text(),
reply_to: p.integer().nullable().persist(false).index('idx_collab_messages_reply_to'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
deleted: p.integer().nullable(),
origin: p.text().nullable(),
replyToRef: () => p.manyToOne(CollabMessages).ref().joinColumn('reply_to').nullable().hidden().index('idx_collab_messages_reply_to'),
collab_message_reactions_collection: () => p.oneToMany(CollabMessageReactions).mappedBy('message').hidden(),
collab_messages_collection: () => p.oneToMany(CollabMessages).mappedBy('replyToRef').hidden(),
trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('message').hidden(),
},
});
@@ -0,0 +1,45 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollabNotesRepository } from '../repositories/CollabNotes.repository';
import { DbTimestampType } from '../types';
import { TripFiles } from './TripFiles.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class CollabNotes {
[EntityRepositoryType]?: CollabNotesRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
user!: Ref<Users>;
user_id!: number;
category?: string | null = 'General';
title!: string;
content?: string | null;
color?: string | null = '#6366f1';
pinned?: number | null = 0;
created_at?: string | null;
updated_at?: string | null;
website?: string | null;
trip_files_collection = new Collection<TripFiles>(this);
}
export const CollabNotesSchema = defineEntity({
class: CollabNotes,
repository: () => CollabNotesRepository,
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_collab_notes_trip'),
trip_id: p.integer().persist(false).index('idx_collab_notes_trip'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collab_notes_user_id'),
user_id: p.integer().persist(false).index('idx_collab_notes_user_id'),
category: p.text().nullable(),
title: p.text(),
content: p.text().nullable(),
color: p.text().nullable(),
pinned: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
website: p.text().nullable(),
trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('note').hidden(),
},
});
@@ -0,0 +1,31 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollabPollVotesRepository } from '../repositories/CollabPollVotes.repository';
import { DbTimestampType } from '../types';
import { CollabPolls } from './CollabPolls.entity';
import { Users } from './Users.entity';
export class CollabPollVotes {
[EntityRepositoryType]?: CollabPollVotesRepository;
id!: number & Opt;
poll!: Ref<CollabPolls>;
poll_id!: number;
user!: Ref<Users>;
user_id!: number;
option_index!: number;
created_at?: string | null;
}
export const CollabPollVotesSchema = defineEntity({
class: CollabPollVotes,
repository: () => CollabPollVotesRepository,
uniques: [{ properties: ['poll', 'user', 'option_index'] }],
properties: {
id: p.integer().primary(),
poll: () => p.manyToOne(CollabPolls).ref().deleteRule('cascade').hidden(),
poll_id: p.integer().persist(false),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collab_poll_votes_user_id'),
user_id: p.integer().persist(false).index('idx_collab_poll_votes_user_id'),
option_index: p.integer(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,41 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollabPollsRepository } from '../repositories/CollabPolls.repository';
import { DbTimestampType } from '../types';
import { CollabPollVotes } from './CollabPollVotes.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class CollabPolls {
[EntityRepositoryType]?: CollabPollsRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
user!: Ref<Users>;
user_id!: number;
question!: string;
options!: string;
multiple?: number | null = 0;
closed?: number | null = 0;
deadline?: string | null;
created_at?: string | null;
collab_poll_votes_collection = new Collection<CollabPollVotes>(this);
}
export const CollabPollsSchema = defineEntity({
class: CollabPolls,
repository: () => CollabPollsRepository,
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_collab_polls_trip'),
trip_id: p.integer().persist(false).index('idx_collab_polls_trip'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collab_polls_user_id'),
user_id: p.integer().persist(false).index('idx_collab_polls_user_id'),
question: p.text(),
options: p.text(),
multiple: p.integer().nullable(),
closed: p.integer().nullable(),
deadline: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
collab_poll_votes_collection: () => p.oneToMany(CollabPollVotes).mappedBy('poll').hidden(),
},
});
@@ -0,0 +1,32 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollectionLabelsRepository } from '../repositories/CollectionLabels.repository';
import { DbTimestampType } from '../types';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { Collections } from './Collections.entity';
export class CollectionLabels {
[EntityRepositoryType]?: CollectionLabelsRepository;
id!: number & Opt;
collection!: Ref<Collections>;
collection_id!: number;
name!: string;
color?: string | null = '#6366f1';
sort_order?: number | null = 0;
created_at?: string | null;
collection_place_labels_inverse = new Collection<CollectionPlaces>(this);
}
export const CollectionLabelsSchema = defineEntity({
class: CollectionLabels,
repository: () => CollectionLabelsRepository,
properties: {
id: p.integer().primary(),
collection: () => p.manyToOne(Collections).ref().deleteRule('cascade').hidden().index('idx_collection_labels_collection'),
collection_id: p.integer().persist(false).index('idx_collection_labels_collection'),
name: p.text(),
color: p.text().nullable(),
sort_order: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
collection_place_labels_inverse: () => p.manyToMany(CollectionPlaces).mappedBy('collection_place_labels').hidden(),
},
});
@@ -0,0 +1,33 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollectionMembersRepository } from '../repositories/CollectionMembers.repository';
import { DbTimestampType } from '../types';
import { Collections } from './Collections.entity';
import { Users } from './Users.entity';
export class CollectionMembers {
[EntityRepositoryType]?: CollectionMembersRepository;
id!: number & Opt;
collection!: Ref<Collections>;
collection_id!: number;
user!: Ref<Users>;
user_id!: number;
status: string & Opt = 'pending';
role: string & Opt = 'editor';
created_at?: string | null;
}
export const CollectionMembersSchema = defineEntity({
class: CollectionMembers,
repository: () => CollectionMembersRepository,
uniques: [{ properties: ['collection', 'user'] }],
properties: {
id: p.integer().primary(),
collection: () => p.manyToOne(Collections).ref().deleteRule('cascade').hidden(),
collection_id: p.integer().persist(false),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collection_members_user'),
user_id: p.integer().persist(false).index('idx_collection_members_user'),
status: p.text().default('pending'),
role: p.text().default('editor'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,31 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollectionPlaceRatingsRepository } from '../repositories/CollectionPlaceRatings.repository';
import { DbTimestampType } from '../types';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { Users } from './Users.entity';
export class CollectionPlaceRatings {
[EntityRepositoryType]?: CollectionPlaceRatingsRepository;
id!: number & Opt;
collectionPlace!: Ref<CollectionPlaces>;
collection_place_id!: number;
user!: Ref<Users>;
user_id!: number;
rating!: number;
created_at?: string | null;
}
export const CollectionPlaceRatingsSchema = defineEntity({
class: CollectionPlaceRatings,
repository: () => CollectionPlaceRatingsRepository,
uniques: [{ properties: ['collectionPlace', 'user'] }],
properties: {
id: p.integer().primary(),
collectionPlace: () => p.manyToOne(CollectionPlaces).ref().deleteRule('cascade').hidden().index('idx_collection_place_ratings_place'),
collection_place_id: p.integer().persist(false).index('idx_collection_place_ratings_place'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collection_place_ratings_user_id'),
user_id: p.integer().persist(false).index('idx_collection_place_ratings_user_id'),
rating: p.integer(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,86 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollectionPlacesRepository } from '../repositories/CollectionPlaces.repository';
import { DbTimestampType } from '../types';
import { Categories } from './Categories.entity';
import { CollectionLabels } from './CollectionLabels.entity';
import { CollectionPlaceRatings } from './CollectionPlaceRatings.entity';
import { Collections } from './Collections.entity';
import { Tags } from './Tags.entity';
import { Users } from './Users.entity';
export class CollectionPlaces {
[EntityRepositoryType]?: CollectionPlacesRepository;
id!: number & Opt;
collection!: Ref<Collections>;
collection_id!: number;
owner!: Ref<Users>;
owner_id!: number;
saved_by?: number | null;
name!: string;
description?: string | null;
lat?: number | null;
lng?: number | null;
address?: string | null;
category?: Ref<Categories> | null;
category_id?: number | null;
price?: number | null;
currency?: string | null;
notes?: string | null;
image_url?: string | null;
google_place_id?: string | null;
google_ftid?: string | null;
osm_id?: string | null;
website?: string | null;
phone?: string | null;
status: string & Opt = 'idea';
source_trip_id?: number | null;
source_place_id?: number | null;
links?: string | null;
sort_order?: number | null = 0;
created_at?: string | null;
updated_at?: string | null;
savedByRef?: Ref<Users> | null;
collection_place_labels = new Collection<CollectionLabels>(this);
collection_place_tags = new Collection<Tags>(this);
collection_place_ratings_collection = new Collection<CollectionPlaceRatings>(this);
}
export const CollectionPlacesSchema = defineEntity({
class: CollectionPlaces,
repository: () => CollectionPlacesRepository,
properties: {
id: p.integer().primary(),
collection: () => p.manyToOne(Collections).ref().deleteRule('cascade').hidden().index('idx_collection_places_collection'),
collection_id: p.integer().persist(false).index('idx_collection_places_collection'),
owner: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collection_places_owner_id'),
owner_id: p.integer().persist(false).index('idx_collection_places_owner_id'),
saved_by: p.integer().nullable().persist(false).index('idx_collection_places_saved_by'),
name: p.text(),
description: p.text().nullable(),
lat: p.double().nullable(),
lng: p.double().nullable(),
address: p.text().nullable(),
category: () => p.manyToOne(Categories).ref().nullable().hidden().index('idx_collection_places_category_id'),
category_id: p.integer().nullable().persist(false).index('idx_collection_places_category_id'),
price: p.double().nullable(),
currency: p.text().nullable(),
notes: p.text().nullable(),
image_url: p.text().nullable(),
google_place_id: p.text().nullable(),
google_ftid: p.text().nullable(),
osm_id: p.text().nullable(),
website: p.text().nullable(),
phone: p.text().nullable(),
status: p.text().default('idea'),
source_trip_id: p.integer().nullable(),
source_place_id: p.integer().nullable(),
links: p.text().nullable(),
sort_order: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
savedByRef: () => p.manyToOne(Users).ref().joinColumn('saved_by').nullable().hidden().index('idx_collection_places_saved_by'),
collection_place_labels: () => p.manyToMany(CollectionLabels).pivotTable('collection_place_labels').joinColumn('collection_place_id').inverseJoinColumn('label_id').hidden(),
collection_place_tags: () => p.manyToMany(Tags).pivotTable('collection_place_tags').joinColumn('collection_place_id').inverseJoinColumn('tag_id').hidden(),
collection_place_ratings_collection: () => p.oneToMany(CollectionPlaceRatings).mappedBy('collectionPlace').hidden(),
},
});
@@ -0,0 +1,101 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollectionToursRepository } from '../repositories/CollectionTours.repository';
import { DbTimestampType } from '../types';
import { Collections } from './Collections.entity';
import { TourTypes } from './TourTypes.entity';
import { Users } from './Users.entity';
export class CollectionTours {
[EntityRepositoryType]?: CollectionToursRepository;
id!: number & Opt;
collection!: Ref<Collections>;
collection_id!: number;
saved_by?: number | null;
name!: string;
description?: string | null;
website?: string | null;
route_geometry?: string | null;
waypoints!: string;
tour_type!: string;
distance?: number | null;
elevation_gain?: number | null;
elevation_loss?: number | null;
duration?: number | null;
planned_duration_minutes?: number | null;
break_additional_minutes?: number | null;
difficulty?: string | null;
wanderer_ref?: string | null;
match_confidence?: number | null;
max_hiking_difficulty?: number | null;
bike_profile?: string | null;
run_profile?: string | null;
run_pace_seconds_per_km?: number | null;
ski_discipline?: string | null;
ski_technique?: string | null;
boat_type?: string | null;
water_context?: string | null;
paddle_speed_kmh?: number | null;
portage_speed_kmh?: number | null;
paddle_lake_style?: string | null;
track_marks?: string | null;
hiking_preferences?: string | null;
origin!: string;
origin_file_name?: string | null;
track_started_at?: string | null;
track_ended_at?: string | null;
source_trip_title!: string;
source_tour_name!: string;
created_at!: string & Opt;
ski_options?: string | null;
tourTypeRef!: Ref<TourTypes>;
savedByRef?: Ref<Users> | null;
}
export const CollectionToursSchema = defineEntity({
class: CollectionTours,
repository: () => CollectionToursRepository,
properties: {
id: p.integer().primary(),
collection: () => p.manyToOne(Collections).ref().deleteRule('cascade').hidden().index('idx_collection_tours_collection'),
collection_id: p.integer().persist(false).index('idx_collection_tours_collection'),
saved_by: p.integer().nullable().persist(false).index('idx_collection_tours_saved_by'),
name: p.text(),
description: p.text().nullable(),
website: p.text().nullable(),
route_geometry: p.text().nullable(),
waypoints: p.text(),
tour_type: p.text().persist(false).index('idx_collection_tours_tour_type'),
distance: p.double().nullable(),
elevation_gain: p.double().nullable(),
elevation_loss: p.double().nullable(),
duration: p.double().nullable(),
planned_duration_minutes: p.integer().nullable(),
break_additional_minutes: p.integer().nullable(),
difficulty: p.text().nullable(),
wanderer_ref: p.text().nullable(),
match_confidence: p.double().nullable(),
max_hiking_difficulty: p.integer().nullable(),
bike_profile: p.text().nullable(),
run_profile: p.text().nullable(),
run_pace_seconds_per_km: p.integer().nullable(),
ski_discipline: p.text().nullable(),
ski_technique: p.text().nullable(),
boat_type: p.text().nullable(),
water_context: p.text().nullable(),
paddle_speed_kmh: p.double().nullable(),
portage_speed_kmh: p.double().nullable(),
paddle_lake_style: p.text().nullable(),
track_marks: p.text().nullable(),
hiking_preferences: p.text().nullable(),
origin: p.text(),
origin_file_name: p.text().nullable(),
track_started_at: p.type(DbTimestampType).nullable(),
track_ended_at: p.type(DbTimestampType).nullable(),
source_trip_title: p.text(),
source_tour_name: p.text(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
ski_options: p.text().nullable(),
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_collection_tours_tour_type'),
savedByRef: () => p.manyToOne(Users).ref().joinColumn('saved_by').nullable().hidden().index('idx_collection_tours_saved_by'),
},
});
@@ -0,0 +1,51 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollectionsRepository } from '../repositories/Collections.repository';
import { DbTimestampType } from '../types';
import { CollectionLabels } from './CollectionLabels.entity';
import { CollectionMembers } from './CollectionMembers.entity';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { CollectionTours } from './CollectionTours.entity';
import { Users } from './Users.entity';
export class Collections {
[EntityRepositoryType]?: CollectionsRepository;
id!: number & Opt;
owner!: Ref<Users>;
owner_id!: number;
name!: string;
description?: string | null;
color?: string | null = '#6366f1';
icon?: string | null = 'Bookmark';
cover_image?: string | null;
links?: string | null;
sort_order?: number | null = 0;
created_at?: string | null;
updated_at?: string | null;
collection_labels_collection = new Collection<CollectionLabels>(this);
collection_members_collection = new Collection<CollectionMembers>(this);
collection_places_collection = new Collection<CollectionPlaces>(this);
collection_tours_collection = new Collection<CollectionTours>(this);
}
export const CollectionsSchema = defineEntity({
class: Collections,
repository: () => CollectionsRepository,
properties: {
id: p.integer().primary(),
owner: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_collections_owner_id'),
owner_id: p.integer().persist(false).index('idx_collections_owner_id'),
name: p.text(),
description: p.text().nullable(),
color: p.text().nullable(),
icon: p.text().nullable(),
cover_image: p.text().nullable(),
links: p.text().nullable(),
sort_order: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
collection_labels_collection: () => p.oneToMany(CollectionLabels).mappedBy('collection').hidden(),
collection_members_collection: () => p.oneToMany(CollectionMembers).mappedBy('collection').hidden(),
collection_places_collection: () => p.oneToMany(CollectionPlaces).mappedBy('collection').hidden(),
collection_tours_collection: () => p.oneToMany(CollectionTours).mappedBy('collection').hidden(),
},
});
@@ -0,0 +1,40 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { DawarichConnectionsRepository } from '../repositories/DawarichConnections.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class DawarichConnections {
[EntityRepositoryType]?: DawarichConnectionsRepository;
[PrimaryKeyProp]?: 'user';
user?: Ref<Users> | null;
user_id?: number | null;
url?: string | null;
api_key?: string | null;
allow_insecure_tls: number & Opt = 0;
sync_enabled: number & Opt = 1;
last_sync_at?: string | null;
last_sync_state: string & Opt = 'never';
last_sync_error?: string | null;
capabilities?: string | null;
created_at?: string | null;
updated_at?: string | null;
}
export const DawarichConnectionsSchema = defineEntity({
class: DawarichConnections,
repository: () => DawarichConnectionsRepository,
properties: {
user: () => p.oneToOne(Users).primary().ref().deleteRule('cascade').nullable().hidden(),
user_id: p.integer().nullable().persist(false),
url: p.text().nullable(),
api_key: p.text().nullable(),
allow_insecure_tls: p.integer().default(0),
sync_enabled: p.integer().default(1),
last_sync_at: p.text().nullable(),
last_sync_state: p.text().default('never'),
last_sync_error: p.text().nullable(),
capabilities: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,86 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { DawarichVisitSuggestionsRepository } from '../repositories/DawarichVisitSuggestions.repository';
import { BucketList } from './BucketList.entity';
import { Places } from './Places.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class DawarichVisitSuggestions {
[EntityRepositoryType]?: DawarichVisitSuggestionsRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
source_visit_id!: string;
trip?: Ref<Trips> | null;
trip_id?: number | null;
name!: string;
lat?: number | null;
lng?: number | null;
started_at!: string;
ended_at!: string;
duration_minutes: number & Opt = 0;
local_date!: string;
source_status: string & Opt = 'suggested';
confidence?: number | null;
confidence_band?: string | null;
country_code?: string | null;
state: string & Opt = 'new';
target?: string | null;
acceptedPlace?: Ref<Places> | null;
accepted_place_id?: number | null;
accepted_journal_entry_id?: number | null;
acceptedBucketListItem?: Ref<BucketList> | null;
accepted_bucket_list_item_id?: number | null;
matchedBucketListItem?: Ref<BucketList> | null;
matched_bucket_list_item_id?: number | null;
source_hash!: string;
accepted_hash?: string | null;
source_missing_at?: string | null;
first_seen_at!: string & Opt;
last_seen_at!: string & Opt;
}
export const DawarichVisitSuggestionsSchema = defineEntity({
class: DawarichVisitSuggestions,
repository: () => DawarichVisitSuggestionsRepository,
indexes: [
{
name: 'idx_dawarich_suggestions_user_state',
properties: ['user_id', 'state'],
},
],
uniques: [{ properties: ['user', 'source_visit_id'] }],
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
source_visit_id: p.text(),
trip: () => p.manyToOne(Trips).ref().nullable().hidden().index('idx_dawarich_suggestions_trip'),
trip_id: p.integer().nullable().persist(false).index('idx_dawarich_suggestions_trip'),
name: p.text(),
lat: p.double().nullable(),
lng: p.double().nullable(),
started_at: p.text(),
ended_at: p.text(),
duration_minutes: p.integer().default(0),
local_date: p.text(),
source_status: p.text().default('suggested'),
confidence: p.double().nullable(),
confidence_band: p.text().nullable(),
country_code: p.text().nullable(),
state: p.text().default('new'),
target: p.text().nullable(),
acceptedPlace: () => p.manyToOne(Places).ref().nullable().hidden().index('idx_dawarich_visit_suggestions_accepted_place_id'),
accepted_place_id: p.integer().nullable().persist(false).index('idx_dawarich_visit_suggestions_accepted_place_id'),
accepted_journal_entry_id: p.integer().nullable(),
acceptedBucketListItem: () => p.manyToOne(BucketList).ref().nullable().hidden().index('idx_dawarich_visit_suggestions_accepted_bucket_list_item_id'),
accepted_bucket_list_item_id: p.integer().nullable().persist(false).index('idx_dawarich_visit_suggestions_accepted_bucket_list_item_id'),
matchedBucketListItem: () => p.manyToOne(BucketList).ref().nullable().hidden().index('idx_dawarich_visit_suggestions_matched_bucket_list_item_id'),
matched_bucket_list_item_id: p.integer().nullable().persist(false).index('idx_dawarich_visit_suggestions_matched_bucket_list_item_id'),
source_hash: p.text(),
accepted_hash: p.text().nullable(),
source_missing_at: p.text().nullable(),
first_seen_at: p.text().defaultRaw(`CURRENT_TIMESTAMP`),
last_seen_at: p.text().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,47 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { DayAccommodationsRepository } from '../repositories/DayAccommodations.repository';
import { DbTimestampType } from '../types';
import { Days } from './Days.entity';
import { Places } from './Places.entity';
import { Trips } from './Trips.entity';
export class DayAccommodations {
[EntityRepositoryType]?: DayAccommodationsRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
place?: Ref<Places> | null;
place_id?: number | null;
startDay!: Ref<Days>;
start_day_id!: number;
endDay!: Ref<Days>;
end_day_id!: number;
check_in?: string | null;
check_in_end?: string | null;
check_out?: string | null;
confirmation?: string | null;
notes?: string | null;
created_at?: string | null;
}
export const DayAccommodationsSchema = defineEntity({
class: DayAccommodations,
repository: () => DayAccommodationsRepository,
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_day_accommodations_trip_id'),
trip_id: p.integer().persist(false).index('idx_day_accommodations_trip_id'),
place: () => p.manyToOne(Places).ref().nullable().hidden().index('idx_day_accommodations_place_id'),
place_id: p.integer().nullable().persist(false).index('idx_day_accommodations_place_id'),
startDay: () => p.manyToOne(Days).ref().deleteRule('cascade').hidden().index('idx_day_accommodations_start_day_id'),
start_day_id: p.integer().persist(false).index('idx_day_accommodations_start_day_id'),
endDay: () => p.manyToOne(Days).ref().deleteRule('cascade').hidden().index('idx_day_accommodations_end_day_id'),
end_day_id: p.integer().persist(false).index('idx_day_accommodations_end_day_id'),
check_in: p.text().nullable(),
check_in_end: p.text().nullable(),
check_out: p.text().nullable(),
confirmation: p.text().nullable(),
notes: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,81 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { DayAssignmentsRepository } from '../repositories/DayAssignments.repository';
import { DbTimestampType } from '../types';
import { AssignmentParticipants } from './AssignmentParticipants.entity';
import { Days } from './Days.entity';
import { FileLinks } from './FileLinks.entity';
import { Places } from './Places.entity';
import { Reservations } from './Reservations.entity';
import { RoadtripDayBoundaries } from './RoadtripDayBoundaries.entity';
import { TourActivities } from './TourActivities.entity';
import { TourStationVisits } from './TourStationVisits.entity';
export class DayAssignments {
[EntityRepositoryType]?: DayAssignmentsRepository;
id!: number & Opt;
day!: Ref<Days>;
day_id!: number;
place!: Ref<Places>;
place_id!: number;
order_index?: number | null = 0;
notes?: string | null;
reservation_status?: string | null = 'none';
reservation_notes?: string | null;
reservation_datetime?: string | null;
created_at?: string | null;
assignment_time?: string | null;
assignment_end_time?: string | null;
leg_transport_mode?: string | null;
incoming_leg_transport_mode?: string | null;
end_day: number & Opt = 0;
accommodation_id?: number | null;
route_excluded: number & Opt = 0;
tour_stage_key?: string | null;
assignment_participants_collection = new Collection<AssignmentParticipants>(this);
file_links_collection = new Collection<FileLinks>(this);
reservations_collection = new Collection<Reservations>(this);
roadtrip_day_boundaries_collection = new Collection<RoadtripDayBoundaries>(this);
roadtrip_day_boundaries_collection1 = new Collection<RoadtripDayBoundaries>(this);
tour_activities_collection = new Collection<TourActivities>(this);
tour_station_visits_collection = new Collection<TourStationVisits>(this);
}
export const DayAssignmentsSchema = defineEntity({
class: DayAssignments,
repository: () => DayAssignmentsRepository,
indexes: [
{
name: 'idx_day_assignments_tour_stage',
where: 'tour_stage_key IS NOT NULL',
properties: ['place_id', 'tour_stage_key'],
},
],
properties: {
id: p.integer().primary(),
day: () => p.manyToOne(Days).ref().deleteRule('cascade').hidden().index('idx_day_assignments_day_id'),
day_id: p.integer().persist(false).index('idx_day_assignments_day_id'),
place: () => p.manyToOne(Places).ref().deleteRule('cascade').hidden().index('idx_day_assignments_place_id'),
place_id: p.integer().persist(false).index('idx_day_assignments_place_id'),
order_index: p.integer().nullable(),
notes: p.text().nullable(),
reservation_status: p.text().nullable(),
reservation_notes: p.text().nullable(),
reservation_datetime: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
assignment_time: p.text().nullable(),
assignment_end_time: p.text().nullable(),
leg_transport_mode: p.text().nullable(),
incoming_leg_transport_mode: p.text().nullable(),
end_day: p.integer().default(0),
accommodation_id: p.integer().nullable().index('idx_day_assignments_accommodation_id'),
route_excluded: p.integer().default(0),
tour_stage_key: p.text().nullable(),
assignment_participants_collection: () => p.oneToMany(AssignmentParticipants).mappedBy('assignment').hidden(),
file_links_collection: () => p.oneToMany(FileLinks).mappedBy('assignment').hidden(),
reservations_collection: () => p.oneToMany(Reservations).mappedBy('assignment').hidden(),
roadtrip_day_boundaries_collection: () => p.oneToMany(RoadtripDayBoundaries).mappedBy('fromAssignment').hidden(),
roadtrip_day_boundaries_collection1: () => p.oneToMany(RoadtripDayBoundaries).mappedBy('toAssignment').hidden(),
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('assignment').hidden(),
tour_station_visits_collection: () => p.oneToMany(TourStationVisits).mappedBy('assignment').hidden(),
},
});
+38
View File
@@ -0,0 +1,38 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { DayNotesRepository } from '../repositories/DayNotes.repository';
import { DbTimestampType } from '../types';
import { Days } from './Days.entity';
import { Trips } from './Trips.entity';
export class DayNotes {
[EntityRepositoryType]?: DayNotesRepository;
id!: number & Opt;
day!: Ref<Days>;
day_id!: number;
trip!: Ref<Trips>;
trip_id!: number;
text!: string;
time?: string | null;
icon?: string | null = '📝';
sort_order?: number | null;
created_at?: string | null;
color?: string | null;
}
export const DayNotesSchema = defineEntity({
class: DayNotes,
repository: () => DayNotesRepository,
properties: {
id: p.integer().primary(),
day: () => p.manyToOne(Days).ref().deleteRule('cascade').hidden().index('idx_day_notes_day_id'),
day_id: p.integer().persist(false).index('idx_day_notes_day_id'),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_day_notes_trip_id'),
trip_id: p.integer().persist(false).index('idx_day_notes_trip_id'),
text: p.text(),
time: p.text().nullable(),
icon: p.text().nullable(),
sort_order: p.double().nullable().defaultRaw(`0`),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
color: p.text().nullable(),
},
});
+59
View File
@@ -0,0 +1,59 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { DaysRepository } from '../repositories/Days.repository';
import { DayAccommodations } from './DayAccommodations.entity';
import { DayAssignments } from './DayAssignments.entity';
import { DayNotes } from './DayNotes.entity';
import { Photos } from './Photos.entity';
import { ReservationDayPositions } from './ReservationDayPositions.entity';
import { Reservations } from './Reservations.entity';
import { RoadtripDayTracks } from './RoadtripDayTracks.entity';
import { RoadtripVias } from './RoadtripVias.entity';
import { Trips } from './Trips.entity';
export class Days {
[EntityRepositoryType]?: DaysRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
day_number!: number;
date?: string | null;
notes?: string | null;
title?: string | null;
default_transport_mode?: string | null;
day_accommodations_collection = new Collection<DayAccommodations>(this);
day_accommodations_collection1 = new Collection<DayAccommodations>(this);
day_assignments_collection = new Collection<DayAssignments>(this);
day_notes_collection = new Collection<DayNotes>(this);
photos_collection = new Collection<Photos>(this);
reservation_day_positions_collection = new Collection<ReservationDayPositions>(this);
reservations_collection = new Collection<Reservations>(this);
reservations_collection1 = new Collection<Reservations>(this);
roadtrip_day_tracks: Ref<RoadtripDayTracks> | null = null;
roadtrip_vias_collection = new Collection<RoadtripVias>(this);
}
export const DaysSchema = defineEntity({
class: Days,
repository: () => DaysRepository,
uniques: [{ properties: ['trip', 'day_number'] }],
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_days_trip_id'),
trip_id: p.integer().persist(false).index('idx_days_trip_id'),
day_number: p.integer(),
date: p.text().nullable(),
notes: p.text().nullable(),
title: p.text().nullable(),
default_transport_mode: p.text().nullable(),
day_accommodations_collection: () => p.oneToMany(DayAccommodations).mappedBy('startDay').hidden(),
day_accommodations_collection1: () => p.oneToMany(DayAccommodations).mappedBy('endDay').hidden(),
day_assignments_collection: () => p.oneToMany(DayAssignments).mappedBy('day').hidden(),
day_notes_collection: () => p.oneToMany(DayNotes).mappedBy('day').hidden(),
photos_collection: () => p.oneToMany(Photos).mappedBy('day').hidden(),
reservation_day_positions_collection: () => p.oneToMany(ReservationDayPositions).mappedBy('day').hidden(),
reservations_collection: () => p.oneToMany(Reservations).mappedBy('day').hidden(),
reservations_collection1: () => p.oneToMany(Reservations).mappedBy('endDay').hidden(),
roadtrip_day_tracks: () => p.oneToOne(RoadtripDayTracks).ref().mappedBy('day').hidden(),
roadtrip_vias_collection: () => p.oneToMany(RoadtripVias).mappedBy('day').hidden(),
},
});
@@ -0,0 +1,55 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { DocumentConnectionsRepository } from '../repositories/DocumentConnections.repository';
import { DbTimestampType } from '../types';
import { DocumentProviders } from './DocumentProviders.entity';
import { TripDocumentLinks } from './TripDocumentLinks.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class DocumentConnections {
[EntityRepositoryType]?: DocumentConnectionsRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
provider!: Ref<DocumentProviders>;
provider_id!: string;
ownerUser!: Ref<Users>;
owner_user_id!: number;
base_url!: string;
secrets?: string | null;
settings: string & Opt = '{}';
allow_insecure_tls: number & Opt = 0;
capabilities?: string | null;
last_probe_at?: string | null;
last_probe_state: string & Opt = 'never';
last_probe_error?: string | null;
created_at?: string | null;
updated_at?: string | null;
trip_document_links_collection = new Collection<TripDocumentLinks>(this);
}
export const DocumentConnectionsSchema = defineEntity({
class: DocumentConnections,
repository: () => DocumentConnectionsRepository,
uniques: [{ properties: ['trip', 'provider'] }],
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_document_connections_trip'),
trip_id: p.integer().persist(false).index('idx_document_connections_trip'),
provider: () => p.manyToOne(DocumentProviders).ref().deleteRule('cascade').hidden().index('idx_document_connections_provider_id'),
provider_id: p.text().persist(false).index('idx_document_connections_provider_id'),
ownerUser: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_document_connections_owner'),
owner_user_id: p.integer().persist(false).index('idx_document_connections_owner'),
base_url: p.text(),
secrets: p.text().nullable(),
settings: p.text().default('{}'),
allow_insecure_tls: p.integer().default(0),
capabilities: p.text().nullable(),
last_probe_at: p.text().nullable(),
last_probe_state: p.text().default('never'),
last_probe_error: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
trip_document_links_collection: () => p.oneToMany(TripDocumentLinks).mappedBy('connection').hidden(),
},
});
@@ -0,0 +1,37 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { DocumentProviderFieldsRepository } from '../repositories/DocumentProviderFields.repository';
import { DocumentProviders } from './DocumentProviders.entity';
export class DocumentProviderFields {
[EntityRepositoryType]?: DocumentProviderFieldsRepository;
id!: number & Opt;
provider!: Ref<DocumentProviders>;
provider_id!: string;
field_key!: string;
label!: string;
input_type: string & Opt = 'text';
placeholder?: string | null;
hint?: string | null;
required?: number | null = 0;
secret?: number | null = 0;
sort_order?: number | null = 0;
}
export const DocumentProviderFieldsSchema = defineEntity({
class: DocumentProviderFields,
repository: () => DocumentProviderFieldsRepository,
uniques: [{ properties: ['provider', 'field_key'] }],
properties: {
id: p.integer().primary(),
provider: () => p.manyToOne(DocumentProviders).ref().deleteRule('cascade').hidden(),
provider_id: p.text().persist(false),
field_key: p.text(),
label: p.text(),
input_type: p.text().default('text'),
placeholder: p.text().nullable(),
hint: p.text().nullable(),
required: p.integer().nullable(),
secret: p.integer().nullable(),
sort_order: p.integer().nullable(),
},
});
@@ -0,0 +1,31 @@
import { Collection, EntityRepositoryType, defineEntity, p } from '@mikro-orm/core';
import { DocumentProvidersRepository } from '../repositories/DocumentProviders.repository';
import { DocumentConnections } from './DocumentConnections.entity';
import { DocumentProviderFields } from './DocumentProviderFields.entity';
export class DocumentProviders {
[EntityRepositoryType]?: DocumentProvidersRepository;
id?: string | null;
name!: string;
description?: string | null;
icon?: string | null = 'FileText';
enabled?: number | null = 0;
sort_order?: number | null = 0;
document_connections_collection = new Collection<DocumentConnections>(this);
document_provider_fields_collection = new Collection<DocumentProviderFields>(this);
}
export const DocumentProvidersSchema = defineEntity({
class: DocumentProviders,
repository: () => DocumentProvidersRepository,
properties: {
id: p.text().primary().nullable(),
name: p.text(),
description: p.text().nullable(),
icon: p.text().nullable(),
enabled: p.integer().nullable(),
sort_order: p.integer().nullable(),
document_connections_collection: () => p.oneToMany(DocumentConnections).mappedBy('provider').hidden(),
document_provider_fields_collection: () => p.oneToMany(DocumentProviderFields).mappedBy('provider').hidden(),
},
});
@@ -0,0 +1,94 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { DocumentSyncItemsRepository } from '../repositories/DocumentSyncItems.repository';
import { TripDocumentLinks } from './TripDocumentLinks.entity';
import { TripFiles } from './TripFiles.entity';
import { Trips } from './Trips.entity';
export class DocumentSyncItems {
[EntityRepositoryType]?: DocumentSyncItemsRepository;
id!: number & Opt;
link!: Ref<TripDocumentLinks>;
link_id!: number;
trip!: Ref<Trips>;
trip_id!: number;
file?: Ref<TripFiles> | null;
file_id?: number | null;
trek_doc_uid!: string;
remote_id?: string | null;
remote_name?: string | null;
remote_version?: string | null;
remote_size?: number | null;
remote_modified_at?: string | null;
content_sha256?: string | null;
pushed_sha256?: string | null;
state: string & Opt = 'pending';
error_code?: string | null;
attempts: number & Opt = 0;
next_attempt_at?: string | null;
remote_missing_at?: string | null;
first_seen_at!: string & Opt;
last_seen_at!: string & Opt;
synced_at?: string | null;
remote_trashed_at?: string | null;
}
export const DocumentSyncItemsSchema = defineEntity({
class: DocumentSyncItems,
repository: () => DocumentSyncItemsRepository,
indexes: [
{
name: 'idx_document_sync_items_due',
properties: ['link_id', 'next_attempt_at'],
},
{
name: 'idx_document_sync_items_hash',
properties: ['link_id', 'content_sha256'],
},
{
name: 'idx_document_sync_items_trip_state',
properties: ['trip_id', 'state'],
},
],
uniques: [
{
name: 'idx_document_sync_items_uid',
properties: ['link_id', 'trek_doc_uid'],
},
{
name: 'idx_document_sync_items_file',
where: 'file_id IS NOT NULL',
properties: ['link_id', 'file_id'],
},
{
name: 'idx_document_sync_items_remote',
where: 'remote_id IS NOT NULL',
properties: ['link_id', 'remote_id'],
},
],
properties: {
id: p.integer().primary(),
link: () => p.manyToOne(TripDocumentLinks).ref().deleteRule('cascade').hidden(),
link_id: p.integer().persist(false),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden(),
trip_id: p.integer().persist(false),
file: () => p.manyToOne(TripFiles).ref().nullable().hidden().index('idx_document_sync_items_file_id'),
file_id: p.integer().nullable().persist(false).index('idx_document_sync_items_file_id'),
trek_doc_uid: p.text(),
remote_id: p.text().nullable(),
remote_name: p.text().nullable(),
remote_version: p.text().nullable(),
remote_size: p.integer().nullable(),
remote_modified_at: p.text().nullable(),
content_sha256: p.text().nullable(),
pushed_sha256: p.text().nullable(),
state: p.text().default('pending'),
error_code: p.text().nullable(),
attempts: p.integer().default(0),
next_attempt_at: p.text().nullable(),
remote_missing_at: p.text().nullable(),
first_seen_at: p.text().defaultRaw(`CURRENT_TIMESTAMP`),
last_seen_at: p.text().defaultRaw(`CURRENT_TIMESTAMP`),
synced_at: p.text().nullable(),
remote_trashed_at: p.text().nullable(),
},
});
@@ -0,0 +1,20 @@
import { EntityRepositoryType, PrimaryKeyProp, defineEntity, p } from '@mikro-orm/core';
import { FerrataTilesRepository } from '../repositories/FerrataTiles.repository';
export class FerrataTiles {
[EntityRepositoryType]?: FerrataTilesRepository;
[PrimaryKeyProp]?: 'tile_key';
tile_key!: string;
payload!: string;
fetched_at!: number;
}
export const FerrataTilesSchema = defineEntity({
class: FerrataTiles,
repository: () => FerrataTilesRepository,
properties: {
tile_key: p.text().primary(),
payload: p.text(),
fetched_at: p.integer(),
},
});
@@ -0,0 +1,52 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { FileLinksRepository } from '../repositories/FileLinks.repository';
import { DbTimestampType } from '../types';
import { BudgetItems } from './BudgetItems.entity';
import { DayAssignments } from './DayAssignments.entity';
import { Places } from './Places.entity';
import { Reservations } from './Reservations.entity';
import { TripFiles } from './TripFiles.entity';
export class FileLinks {
[EntityRepositoryType]?: FileLinksRepository;
id!: number & Opt;
file!: Ref<TripFiles>;
file_id!: number;
reservation?: Ref<Reservations> | null;
reservation_id?: number | null;
assignment?: Ref<DayAssignments> | null;
assignment_id?: number | null;
place?: Ref<Places> | null;
place_id?: number | null;
created_at?: string | null;
budgetItem?: Ref<BudgetItems> | null;
budget_item_id?: number | null;
}
export const FileLinksSchema = defineEntity({
class: FileLinks,
repository: () => FileLinksRepository,
uniques: [
{
name: 'idx_file_links_file_budget',
properties: ['file_id', 'budget_item_id'],
},
{ properties: ['file', 'place'] },
{ properties: ['file', 'assignment'] },
{ properties: ['file', 'reservation'] },
],
properties: {
id: p.integer().primary(),
file: () => p.manyToOne(TripFiles).ref().deleteRule('cascade').hidden(),
file_id: p.integer().persist(false),
reservation: () => p.manyToOne(Reservations).ref().deleteRule('cascade').nullable().hidden().index('idx_file_links_reservation_id'),
reservation_id: p.integer().nullable().persist(false).index('idx_file_links_reservation_id'),
assignment: () => p.manyToOne(DayAssignments).ref().deleteRule('cascade').nullable().hidden().index('idx_file_links_assignment_id'),
assignment_id: p.integer().nullable().persist(false).index('idx_file_links_assignment_id'),
place: () => p.manyToOne(Places).ref().deleteRule('cascade').nullable().hidden().index('idx_file_links_place_id'),
place_id: p.integer().nullable().persist(false).index('idx_file_links_place_id'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
budgetItem: () => p.manyToOne(BudgetItems).ref().nullable().hidden().index('idx_file_links_budget_item_id'),
budget_item_id: p.integer().nullable().persist(false).index('idx_file_links_budget_item_id'),
},
});
@@ -0,0 +1,18 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, defineEntity, p } from '@mikro-orm/core';
import { GoogleApiUsageRepository } from '../repositories/GoogleApiUsage.repository';
export class GoogleApiUsage {
[EntityRepositoryType]?: GoogleApiUsageRepository;
[PrimaryKeyProp]?: 'day';
day?: string | null;
calls: number & Opt = 0;
}
export const GoogleApiUsageSchema = defineEntity({
class: GoogleApiUsage,
repository: () => GoogleApiUsageRepository,
properties: {
day: p.text().primary().nullable(),
calls: p.integer().default(0),
},
});
@@ -0,0 +1,22 @@
import { EntityRepositoryType, PrimaryKeyProp, defineEntity, p } from '@mikro-orm/core';
import { GooglePlacePhotoMetaRepository } from '../repositories/GooglePlacePhotoMeta.repository';
export class GooglePlacePhotoMeta {
[EntityRepositoryType]?: GooglePlacePhotoMetaRepository;
[PrimaryKeyProp]?: 'place_id';
place_id?: string | null;
attribution?: string | null;
fetched_at!: number;
error_at?: number | null;
}
export const GooglePlacePhotoMetaSchema = defineEntity({
class: GooglePlacePhotoMeta,
repository: () => GooglePlacePhotoMetaRepository,
properties: {
place_id: p.text().primary().nullable(),
attribution: p.text().nullable(),
fetched_at: p.integer(),
error_at: p.integer().nullable(),
},
});
@@ -0,0 +1,26 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { HiddenCountriesRepository } from '../repositories/HiddenCountries.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class HiddenCountries {
[EntityRepositoryType]?: HiddenCountriesRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
country_code!: string;
created_at?: string | null;
}
export const HiddenCountriesSchema = defineEntity({
class: HiddenCountries,
repository: () => HiddenCountriesRepository,
uniques: [{ properties: ['user', 'country_code'] }],
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_hidden_countries_user'),
user_id: p.integer().persist(false).index('idx_hidden_countries_user'),
country_code: p.text(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,28 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { HiddenRegionsRepository } from '../repositories/HiddenRegions.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class HiddenRegions {
[EntityRepositoryType]?: HiddenRegionsRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
region_code!: string;
country_code!: string;
created_at?: string | null;
}
export const HiddenRegionsSchema = defineEntity({
class: HiddenRegions,
repository: () => HiddenRegionsRepository,
uniques: [{ properties: ['user', 'region_code'] }],
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_hidden_regions_user'),
user_id: p.integer().persist(false).index('idx_hidden_regions_user'),
region_code: p.text(),
country_code: p.text(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,32 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { IdempotencyKeysRepository } from '../repositories/IdempotencyKeys.repository';
import { Users } from './Users.entity';
export class IdempotencyKeys {
[EntityRepositoryType]?: IdempotencyKeysRepository;
[PrimaryKeyProp]?: ['key', 'user', 'method', 'path'];
key!: string;
user!: Ref<Users>;
user_id!: number;
method!: string;
path!: string;
status_code!: number;
response_body!: string;
created_at!: number & Opt;
}
export const IdempotencyKeysSchema = defineEntity({
class: IdempotencyKeys,
repository: () => IdempotencyKeysRepository,
uniques: [{ properties: ['key', 'user', 'method', 'path'] }],
properties: {
key: p.text().primary(),
user: () => p.manyToOne(Users).primary().ref().deleteRule('cascade').hidden().index('idx_idempotency_keys_user_id'),
user_id: p.integer().persist(false).index('idx_idempotency_keys_user_id'),
method: p.text().primary(),
path: p.text().primary(),
status_code: p.integer(),
response_body: p.text(),
created_at: p.integer().defaultRaw(`(strftime('%s','now'))`).index('idx_idempotency_keys_created'),
},
});
@@ -0,0 +1,37 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { InviteTokensRepository } from '../repositories/InviteTokens.repository';
import { DbTimestampType } from '../types';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class InviteTokens {
[EntityRepositoryType]?: InviteTokensRepository;
id!: number & Opt;
token!: string;
max_uses: number & Opt = 1;
used_count: number & Opt = 0;
expires_at?: string | null;
created_by!: number;
created_at?: string | null;
trip?: Ref<Trips> | null;
trip_id?: number | null;
createdByRef!: Ref<Users>;
}
export const InviteTokensSchema = defineEntity({
class: InviteTokens,
repository: () => InviteTokensRepository,
uniques: [{ properties: ['token'] }],
properties: {
id: p.integer().primary(),
token: p.text(),
max_uses: p.integer().default(1),
used_count: p.integer().default(0),
expires_at: p.text().nullable(),
created_by: p.integer().persist(false).index('idx_invite_tokens_created_by'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
trip: () => p.manyToOne(Trips).ref().nullable().hidden().index('idx_invite_tokens_trip_id'),
trip_id: p.integer().nullable().persist(false).index('idx_invite_tokens_trip_id'),
createdByRef: () => p.manyToOne(Users).ref().joinColumn('created_by').deleteRule('cascade').hidden().index('idx_invite_tokens_created_by'),
},
});
@@ -0,0 +1,27 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyBookRevisionsRepository } from '../repositories/JourneyBookRevisions.repository';
import { DbTimestampType } from '../types';
import { Journeys } from './Journeys.entity';
export class JourneyBookRevisions {
[EntityRepositoryType]?: JourneyBookRevisionsRepository;
id!: number & Opt;
journey!: Ref<Journeys>;
journey_id!: number;
version!: number;
document!: string;
created_at!: string & Opt;
}
export const JourneyBookRevisionsSchema = defineEntity({
class: JourneyBookRevisions,
repository: () => JourneyBookRevisionsRepository,
properties: {
id: p.integer().primary(),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').hidden().index('idx_journey_book_revisions_journey'),
journey_id: p.integer().persist(false).index('idx_journey_book_revisions_journey'),
version: p.integer(),
document: p.text(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,40 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyBooksRepository } from '../repositories/JourneyBooks.repository';
import { DbTimestampType } from '../types';
import { Journeys } from './Journeys.entity';
import { Users } from './Users.entity';
export class JourneyBooks {
[EntityRepositoryType]?: JourneyBooksRepository;
id!: number & Opt;
journey!: Ref<Journeys>;
journey_id!: number;
title: string & Opt = '';
document!: string;
version: number & Opt = 1;
created_by?: number | null;
updated_by?: number | null;
created_at?: string | null;
updated_at?: string | null;
updatedByRef?: Ref<Users> | null;
createdByRef?: Ref<Users> | null;
}
export const JourneyBooksSchema = defineEntity({
class: JourneyBooks,
repository: () => JourneyBooksRepository,
properties: {
id: p.integer().primary(),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').hidden().index('idx_journey_books_journey'),
journey_id: p.integer().persist(false).index('idx_journey_books_journey'),
title: p.text().default(''),
document: p.text(),
version: p.integer().default(1),
created_by: p.integer().nullable().persist(false).index('idx_journey_books_created_by'),
updated_by: p.integer().nullable().persist(false).index('idx_journey_books_updated_by'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updatedByRef: () => p.manyToOne(Users).ref().joinColumn('updated_by').nullable().hidden().index('idx_journey_books_updated_by'),
createdByRef: () => p.manyToOne(Users).ref().joinColumn('created_by').nullable().hidden().index('idx_journey_books_created_by'),
},
});
@@ -0,0 +1,31 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyContributorsRepository } from '../repositories/JourneyContributors.repository';
import { Journeys } from './Journeys.entity';
import { Users } from './Users.entity';
export class JourneyContributors {
[EntityRepositoryType]?: JourneyContributorsRepository;
[PrimaryKeyProp]?: ['journey', 'user'];
journey!: Ref<Journeys>;
journey_id!: number;
user!: Ref<Users>;
user_id!: number;
role!: string;
added_at!: number;
hide_skeletons: number & Opt = 0;
}
export const JourneyContributorsSchema = defineEntity({
class: JourneyContributors,
repository: () => JourneyContributorsRepository,
uniques: [{ properties: ['journey', 'user'] }],
properties: {
journey: () => p.manyToOne(Journeys).primary().ref().hidden(),
journey_id: p.integer().persist(false),
user: () => p.manyToOne(Users).primary().ref().deleteRule('no action').hidden().index('idx_journey_contributors_user'),
user_id: p.integer().persist(false).index('idx_journey_contributors_user'),
role: p.text(),
added_at: p.integer(),
hide_skeletons: p.integer().default(0),
},
});
@@ -0,0 +1,97 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyEntriesRepository } from '../repositories/JourneyEntries.repository';
import { JourneyEntryPhotos } from './JourneyEntryPhotos.entity';
import { JourneyEntryStays } from './JourneyEntryStays.entity';
import { Journeys } from './Journeys.entity';
import { Places } from './Places.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class JourneyEntries {
[EntityRepositoryType]?: JourneyEntriesRepository;
id!: number & Opt;
journey!: Ref<Journeys>;
journey_id!: number;
sourceTrip?: Ref<Trips> | null;
source_trip_id?: number | null;
sourcePlace?: Ref<Places> | null;
source_place_id?: number | null;
author!: Ref<Users>;
author_id!: number;
type!: string;
title?: string | null;
story?: string | null;
entry_date!: string;
entry_time?: string | null;
location_name?: string | null;
location_lat?: number | null;
location_lng?: number | null;
mood?: string | null;
weather?: string | null;
tags?: string | null;
visibility?: string | null = 'private';
sort_order?: number | null = 0;
created_at!: number;
updated_at!: number;
pros_cons?: string | null;
stats_excluded: number & Opt = 0;
dismissed: number & Opt = 0;
country_code?: string | null;
source_assignment_id?: number | null;
is_draft: number & Opt = 0;
journey_entry_photos_collection = new Collection<JourneyEntryPhotos>(this);
journey_entry_stays_collection = new Collection<JourneyEntryStays>(this);
}
export const JourneyEntriesSchema = defineEntity({
class: JourneyEntries,
repository: () => JourneyEntriesRepository,
indexes: [
{
name: 'idx_journey_entries_source_assignment',
properties: ['source_place_id', 'source_assignment_id'],
},
{
name: 'idx_journey_entries_order',
properties: ['journey_id', 'entry_date', 'sort_order'],
},
{
name: 'idx_journey_entries_journey',
properties: ['journey_id', 'entry_date'],
},
],
properties: {
id: p.integer().primary(),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').hidden(),
journey_id: p.integer().persist(false),
sourceTrip: () => p.manyToOne(Trips).ref().nullable().hidden().index('idx_journey_entries_source_trip_id'),
source_trip_id: p.integer().nullable().persist(false).index('idx_journey_entries_source_trip_id'),
sourcePlace: () => p.manyToOne(Places).ref().nullable().hidden().index('idx_journey_entries_source'),
source_place_id: p.integer().nullable().persist(false).index('idx_journey_entries_source'),
author: () => p.manyToOne(Users).ref().hidden().index('idx_journey_entries_author_id'),
author_id: p.integer().persist(false).index('idx_journey_entries_author_id'),
type: p.text(),
title: p.text().nullable(),
story: p.text().nullable(),
entry_date: p.text(),
entry_time: p.text().nullable(),
location_name: p.text().nullable(),
location_lat: p.double().nullable(),
location_lng: p.double().nullable(),
mood: p.text().nullable(),
weather: p.text().nullable(),
tags: p.text().nullable(),
visibility: p.text().nullable(),
sort_order: p.integer().nullable(),
created_at: p.integer(),
updated_at: p.integer(),
pros_cons: p.text().nullable(),
stats_excluded: p.integer().default(0),
dismissed: p.integer().default(0),
country_code: p.text().nullable(),
source_assignment_id: p.integer().nullable(),
is_draft: p.integer().default(0),
journey_entry_photos_collection: () => p.oneToMany(JourneyEntryPhotos).mappedBy('entry').hidden(),
journey_entry_stays_collection: () => p.oneToMany(JourneyEntryStays).mappedBy('entry').hidden(),
},
});
@@ -0,0 +1,29 @@
import { EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyEntryPhotosRepository } from '../repositories/JourneyEntryPhotos.repository';
import { JourneyEntries } from './JourneyEntries.entity';
import { JourneyPhotos } from './JourneyPhotos.entity';
export class JourneyEntryPhotos {
[EntityRepositoryType]?: JourneyEntryPhotosRepository;
[PrimaryKeyProp]?: ['entry', 'journeyPhoto'];
entry!: Ref<JourneyEntries>;
entry_id!: number;
journeyPhoto!: Ref<JourneyPhotos>;
journey_photo_id!: number;
sort_order?: number | null = 0;
created_at!: number;
}
export const JourneyEntryPhotosSchema = defineEntity({
class: JourneyEntryPhotos,
repository: () => JourneyEntryPhotosRepository,
uniques: [{ properties: ['entry', 'journeyPhoto'] }],
properties: {
entry: () => p.manyToOne(JourneyEntries).primary().ref().hidden().index('idx_journey_entry_photos_entry'),
entry_id: p.integer().persist(false).index('idx_journey_entry_photos_entry'),
journeyPhoto: () => p.manyToOne(JourneyPhotos).primary().ref().hidden().index('idx_journey_entry_photos_photo'),
journey_photo_id: p.integer().persist(false).index('idx_journey_entry_photos_photo'),
sort_order: p.integer().nullable(),
created_at: p.integer(),
},
});
@@ -0,0 +1,57 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyEntryStaysRepository } from '../repositories/JourneyEntryStays.repository';
import { DbTimestampType } from '../types';
import { JourneyEntries } from './JourneyEntries.entity';
import { Journeys } from './Journeys.entity';
import { Users } from './Users.entity';
export class JourneyEntryStays {
[EntityRepositoryType]?: JourneyEntryStaysRepository;
id!: number & Opt;
journey!: Ref<Journeys>;
journey_id!: number;
entry!: Ref<JourneyEntries>;
entry_id!: number;
source: string & Opt = 'dawarich';
source_visit_id!: string;
name!: string;
lat?: number | null;
lng?: number | null;
started_at!: string;
ended_at!: string;
duration_minutes: number & Opt = 0;
sort_order: number & Opt = 0;
user?: Ref<Users> | null;
user_id?: number | null;
created_at!: string & Opt;
}
export const JourneyEntryStaysSchema = defineEntity({
class: JourneyEntryStays,
repository: () => JourneyEntryStaysRepository,
uniques: [
{
name: 'idx_journey_entry_stays_stay',
properties: ['journey_id', 'source', 'user_id', 'source_visit_id'],
},
],
properties: {
id: p.integer().primary(),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').hidden(),
journey_id: p.integer().persist(false),
entry: () => p.manyToOne(JourneyEntries).ref().deleteRule('cascade').hidden().index('idx_journey_entry_stays_entry'),
entry_id: p.integer().persist(false).index('idx_journey_entry_stays_entry'),
source: p.text().default('dawarich'),
source_visit_id: p.text(),
name: p.text(),
lat: p.double().nullable(),
lng: p.double().nullable(),
started_at: p.text(),
ended_at: p.text(),
duration_minutes: p.integer().default(0),
sort_order: p.integer().default(0),
user: () => p.manyToOne(Users).ref().nullable().hidden().index('idx_journey_entry_stays_user'),
user_id: p.integer().nullable().persist(false).index('idx_journey_entry_stays_user'),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,43 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyPhotosRepository } from '../repositories/JourneyPhotos.repository';
import { JourneyEntryPhotos } from './JourneyEntryPhotos.entity';
import { Journeys } from './Journeys.entity';
import { TrekPhotos } from './TrekPhotos.entity';
export class JourneyPhotos {
[EntityRepositoryType]?: JourneyPhotosRepository;
id!: number & Opt;
journey!: Ref<Journeys>;
journey_id!: number;
photo!: Ref<TrekPhotos>;
photo_id!: number;
caption?: string | null;
shared?: number | null = 0;
sort_order?: number | null = 0;
provider?: string | null;
asset_id?: string | null;
owner_id?: number | null;
created_at!: number;
journey_entry_photos_collection = new Collection<JourneyEntryPhotos>(this);
}
export const JourneyPhotosSchema = defineEntity({
class: JourneyPhotos,
repository: () => JourneyPhotosRepository,
uniques: [{ properties: ['journey', 'photo'] }],
properties: {
id: p.integer().primary(),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').hidden().index('idx_journey_photos_journey'),
journey_id: p.integer().persist(false).index('idx_journey_photos_journey'),
photo: () => p.manyToOne(TrekPhotos).ref().deleteRule('cascade').hidden().index('idx_journey_photos_photo_id'),
photo_id: p.integer().persist(false).index('idx_journey_photos_photo_id'),
caption: p.text().nullable(),
shared: p.integer().nullable(),
sort_order: p.integer().nullable(),
provider: p.text().nullable(),
asset_id: p.text().nullable(),
owner_id: p.integer().nullable(),
created_at: p.integer(),
journey_entry_photos_collection: () => p.oneToMany(JourneyEntryPhotos).mappedBy('journeyPhoto').hidden(),
},
});
@@ -0,0 +1,60 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyRecordedDaysRepository } from '../repositories/JourneyRecordedDays.repository';
import { DbTimestampType } from '../types';
import { Journeys } from './Journeys.entity';
import { Users } from './Users.entity';
export class JourneyRecordedDays {
[EntityRepositoryType]?: JourneyRecordedDaysRepository;
id!: number & Opt;
journey!: Ref<Journeys>;
journey_id!: number;
local_date!: string;
source: string & Opt = 'dawarich';
source_kind!: string;
utc_offset_minutes!: number;
window_from!: string;
window_to!: string;
segments!: string;
point_count!: number;
distance_m?: number | null;
content_hash!: string;
truncated: number & Opt = 0;
fetched_at!: string;
imported_by?: number | null;
created_at!: string & Opt;
updated_at!: string & Opt;
importedByRef?: Ref<Users> | null;
}
export const JourneyRecordedDaysSchema = defineEntity({
class: JourneyRecordedDays,
repository: () => JourneyRecordedDaysRepository,
uniques: [
{
name: 'idx_journey_recorded_days_day',
properties: ['journey_id', 'local_date', 'source'],
},
],
properties: {
id: p.integer().primary(),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').hidden(),
journey_id: p.integer().persist(false),
local_date: p.text(),
source: p.text().default('dawarich'),
source_kind: p.text(),
utc_offset_minutes: p.integer(),
window_from: p.text(),
window_to: p.text(),
segments: p.text(),
point_count: p.integer(),
distance_m: p.double().nullable(),
content_hash: p.text(),
truncated: p.integer().default(0),
fetched_at: p.text(),
imported_by: p.integer().nullable().persist(false).index('idx_journey_recorded_days_imported_by'),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
importedByRef: () => p.manyToOne(Users).ref().joinColumn('imported_by').nullable().hidden().index('idx_journey_recorded_days_imported_by'),
},
});
@@ -0,0 +1,37 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyRecordingPrepRepository } from '../repositories/JourneyRecordingPrep.repository';
import { Journeys } from './Journeys.entity';
import { Users } from './Users.entity';
export class JourneyRecordingPrep {
[EntityRepositoryType]?: JourneyRecordingPrepRepository;
id!: number & Opt;
journey!: Ref<Journeys>;
journey_id!: number;
user!: Ref<Users>;
user_id!: number;
last_attempt_at?: string | null;
last_success_at?: string | null;
last_error?: string | null;
}
export const JourneyRecordingPrepSchema = defineEntity({
class: JourneyRecordingPrep,
repository: () => JourneyRecordingPrepRepository,
uniques: [
{
name: 'idx_journey_recording_prep_person',
properties: ['journey_id', 'user_id'],
},
],
properties: {
id: p.integer().primary(),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').hidden(),
journey_id: p.integer().persist(false),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_journey_recording_prep_user'),
user_id: p.integer().persist(false).index('idx_journey_recording_prep_user'),
last_attempt_at: p.text().nullable(),
last_success_at: p.text().nullable(),
last_error: p.text().nullable(),
},
});
@@ -0,0 +1,43 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyShareTokensRepository } from '../repositories/JourneyShareTokens.repository';
import { DbTimestampType } from '../types';
import { Journeys } from './Journeys.entity';
import { Users } from './Users.entity';
export class JourneyShareTokens {
[EntityRepositoryType]?: JourneyShareTokensRepository;
id!: number & Opt;
journey!: Ref<Journeys>;
journey_id!: number;
token!: string;
created_by!: number;
share_timeline?: number | null = 1;
share_gallery?: number | null = 1;
share_map?: number | null = 1;
created_at?: string | null;
newest_first: number & Opt = 0;
share_plan: number & Opt = 0;
share_recordings: number & Opt = 0;
createdByRef!: Ref<Users>;
}
export const JourneyShareTokensSchema = defineEntity({
class: JourneyShareTokens,
repository: () => JourneyShareTokensRepository,
uniques: [{ properties: ['token'] }],
properties: {
id: p.integer().primary(),
journey: () => p.oneToOne(Journeys).ref().deleteRule('cascade').hidden().unique('idx_journey_share_journey'),
journey_id: p.integer().persist(false).unique('idx_journey_share_journey'),
token: p.text(),
created_by: p.integer().persist(false).index('idx_journey_share_tokens_created_by'),
share_timeline: p.integer().nullable(),
share_gallery: p.integer().nullable(),
share_map: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
newest_first: p.integer().default(0),
share_plan: p.integer().default(0),
share_recordings: p.integer().default(0),
createdByRef: () => p.manyToOne(Users).ref().joinColumn('created_by').hidden().index('idx_journey_share_tokens_created_by'),
},
});
@@ -0,0 +1,27 @@
import { EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyTripsRepository } from '../repositories/JourneyTrips.repository';
import { Journeys } from './Journeys.entity';
import { Trips } from './Trips.entity';
export class JourneyTrips {
[EntityRepositoryType]?: JourneyTripsRepository;
[PrimaryKeyProp]?: ['journey', 'trip'];
journey!: Ref<Journeys>;
journey_id!: number;
trip!: Ref<Trips>;
trip_id!: number;
added_at!: number;
}
export const JourneyTripsSchema = defineEntity({
class: JourneyTrips,
repository: () => JourneyTripsRepository,
uniques: [{ properties: ['journey', 'trip'] }],
properties: {
journey: () => p.manyToOne(Journeys).primary().ref().hidden().index('idx_journey_trips_journey'),
journey_id: p.integer().persist(false).index('idx_journey_trips_journey'),
trip: () => p.manyToOne(Trips).primary().ref().hidden().index('idx_journey_trips_trip_id'),
trip_id: p.integer().persist(false).index('idx_journey_trips_trip_id'),
added_at: p.integer(),
},
});
+84
View File
@@ -0,0 +1,84 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneysRepository } from '../repositories/Journeys.repository';
import { AssistantThreads } from './AssistantThreads.entity';
import { JourneyBookRevisions } from './JourneyBookRevisions.entity';
import { JourneyBooks } from './JourneyBooks.entity';
import { JourneyContributors } from './JourneyContributors.entity';
import { JourneyEntries } from './JourneyEntries.entity';
import { JourneyEntryStays } from './JourneyEntryStays.entity';
import { JourneyPhotos } from './JourneyPhotos.entity';
import { JourneyRecordedDays } from './JourneyRecordedDays.entity';
import { JourneyRecordingPrep } from './JourneyRecordingPrep.entity';
import { JourneyShareTokens } from './JourneyShareTokens.entity';
import { JourneyTrips } from './JourneyTrips.entity';
import { TripJournalLinks } from './TripJournalLinks.entity';
import { Users } from './Users.entity';
export class Journeys {
[EntityRepositoryType]?: JourneysRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
title!: string;
subtitle?: string | null;
cover_gradient?: string | null;
status?: string | null = 'draft';
created_at!: number;
updated_at!: number;
cover_image?: string | null;
show_trip_tracks: number & Opt = 0;
show_verdict: number & Opt = 1;
show_mood: number & Opt = 1;
show_weather: number & Opt = 1;
status_override?: string | null;
photo_location: number & Opt = 0;
auto_prepare_recordings: number & Opt = 0;
assistant_threads_collection = new Collection<AssistantThreads>(this);
journey_book_revisions_collection = new Collection<JourneyBookRevisions>(this);
journey_books_collection = new Collection<JourneyBooks>(this);
journey_contributors_collection = new Collection<JourneyContributors>(this);
journey_entries_collection = new Collection<JourneyEntries>(this);
journey_entry_stays_collection = new Collection<JourneyEntryStays>(this);
journey_photos_collection = new Collection<JourneyPhotos>(this);
journey_recorded_days_collection = new Collection<JourneyRecordedDays>(this);
journey_recording_prep_collection = new Collection<JourneyRecordingPrep>(this);
journey_share_tokens: Ref<JourneyShareTokens> | null = null;
journey_trips_collection = new Collection<JourneyTrips>(this);
trip_journal_links_collection = new Collection<TripJournalLinks>(this);
}
export const JourneysSchema = defineEntity({
class: Journeys,
repository: () => JourneysRepository,
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().hidden().index('idx_journeys_user'),
user_id: p.integer().persist(false).index('idx_journeys_user'),
title: p.text(),
subtitle: p.text().nullable(),
cover_gradient: p.text().nullable(),
status: p.text().nullable(),
created_at: p.integer(),
updated_at: p.integer(),
cover_image: p.text().nullable(),
show_trip_tracks: p.integer().default(0),
show_verdict: p.integer().default(1),
show_mood: p.integer().default(1),
show_weather: p.integer().default(1),
status_override: p.text().nullable(),
photo_location: p.integer().default(0),
auto_prepare_recordings: p.integer().default(0),
assistant_threads_collection: () => p.oneToMany(AssistantThreads).mappedBy('journey').hidden(),
journey_book_revisions_collection: () => p.oneToMany(JourneyBookRevisions).mappedBy('journey').hidden(),
journey_books_collection: () => p.oneToMany(JourneyBooks).mappedBy('journey').hidden(),
journey_contributors_collection: () => p.oneToMany(JourneyContributors).mappedBy('journey').hidden(),
journey_entries_collection: () => p.oneToMany(JourneyEntries).mappedBy('journey').hidden(),
journey_entry_stays_collection: () => p.oneToMany(JourneyEntryStays).mappedBy('journey').hidden(),
journey_photos_collection: () => p.oneToMany(JourneyPhotos).mappedBy('journey').hidden(),
journey_recorded_days_collection: () => p.oneToMany(JourneyRecordedDays).mappedBy('journey').hidden(),
journey_recording_prep_collection: () => p.oneToMany(JourneyRecordingPrep).mappedBy('journey').hidden(),
journey_share_tokens: () => p.oneToOne(JourneyShareTokens).ref().mappedBy('journey').hidden(),
journey_trips_collection: () => p.oneToMany(JourneyTrips).mappedBy('journey').hidden(),
trip_journal_links_collection: () => p.oneToMany(TripJournalLinks).mappedBy('journey').hidden(),
},
});
@@ -0,0 +1,37 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { McpTokensRepository } from '../repositories/McpTokens.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class McpTokens {
[EntityRepositoryType]?: McpTokensRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
name!: string;
token_hash!: string;
token_prefix!: string;
created_at?: string | null;
last_used_at?: string | null;
kind: string & Opt = 'mcp';
scope_mode: string & Opt = 'all';
api_scopes?: string | null;
}
export const McpTokensSchema = defineEntity({
class: McpTokens,
repository: () => McpTokensRepository,
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_mcp_tokens_user_id'),
user_id: p.integer().persist(false).index('idx_mcp_tokens_user_id'),
name: p.text(),
token_hash: p.text().unique('idx_mcp_tokens_hash'),
token_prefix: p.text(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
last_used_at: p.type(DbTimestampType).nullable(),
kind: p.text().default('mcp'),
scope_mode: p.text().default('all'),
api_scopes: p.text().nullable(),
},
});
@@ -0,0 +1,19 @@
import { EntityRepositoryType, defineEntity, p } from '@mikro-orm/core';
import { MigrationsRepository } from '../repositories/Migrations.repository';
export class Migrations {
[EntityRepositoryType]?: MigrationsRepository;
id!: number;
timestamp!: bigint;
name!: string;
}
export const MigrationsSchema = defineEntity({
class: Migrations,
repository: () => MigrationsRepository,
properties: {
id: p.integer().primary(),
timestamp: p.bigint(),
name: p.string(),
},
});
@@ -0,0 +1,26 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { NotificationChannelPreferencesRepository } from '../repositories/NotificationChannelPreferences.repository';
import { Users } from './Users.entity';
export class NotificationChannelPreferences {
[EntityRepositoryType]?: NotificationChannelPreferencesRepository;
[PrimaryKeyProp]?: ['user', 'event_type', 'channel'];
user!: Ref<Users>;
user_id!: number;
event_type!: string;
channel!: string;
enabled: number & Opt = 1;
}
export const NotificationChannelPreferencesSchema = defineEntity({
class: NotificationChannelPreferences,
repository: () => NotificationChannelPreferencesRepository,
uniques: [{ properties: ['user', 'event_type', 'channel'] }],
properties: {
user: () => p.manyToOne(Users).primary().ref().deleteRule('cascade').hidden().index('idx_ncp_user'),
user_id: p.integer().persist(false).index('idx_ncp_user'),
event_type: p.text().primary(),
channel: p.text().primary(),
enabled: p.integer().default(1),
},
});
@@ -0,0 +1,68 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { NotificationsRepository } from '../repositories/Notifications.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class Notifications {
[EntityRepositoryType]?: NotificationsRepository;
id!: number & Opt;
type!: string;
scope!: string;
target!: number;
sender?: Ref<Users> | null;
sender_id?: number | null;
recipient!: Ref<Users>;
recipient_id!: number;
title_key!: string;
title_params?: string | null = '{}';
text_key!: string;
text_params?: string | null = '{}';
positive_text_key?: string | null;
negative_text_key?: string | null;
positive_callback?: string | null;
negative_callback?: string | null;
response?: string | null;
navigate_text_key?: string | null;
navigate_target?: string | null;
is_read?: number | null = 0;
created_at?: string | null;
}
export const NotificationsSchema = defineEntity({
class: Notifications,
repository: () => NotificationsRepository,
indexes: [
{ name: 'idx_notifications_target_scope', properties: ['target', 'scope'] },
{
name: 'idx_notifications_recipient_created',
properties: ['recipient_id', 'created_at'],
},
{
name: 'idx_notifications_recipient',
properties: ['recipient_id', 'is_read', 'created_at'],
},
],
properties: {
id: p.integer().primary(),
type: p.text(),
scope: p.text(),
target: p.integer(),
sender: () => p.manyToOne(Users).ref().nullable().hidden().index('idx_notifications_sender_id'),
sender_id: p.integer().nullable().persist(false).index('idx_notifications_sender_id'),
recipient: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
recipient_id: p.integer().persist(false),
title_key: p.text(),
title_params: p.text().nullable(),
text_key: p.text(),
text_params: p.text().nullable(),
positive_text_key: p.text().nullable(),
negative_text_key: p.text().nullable(),
positive_callback: p.text().nullable(),
negative_callback: p.text().nullable(),
response: p.text().nullable(),
navigate_text_key: p.text().nullable(),
navigate_target: p.text().nullable(),
is_read: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,46 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { OauthClientsRepository } from '../repositories/OauthClients.repository';
import { DbTimestampType } from '../types';
import { OauthConsents } from './OauthConsents.entity';
import { OauthTokens } from './OauthTokens.entity';
import { Users } from './Users.entity';
export class OauthClients {
[EntityRepositoryType]?: OauthClientsRepository;
id?: string | null;
user?: Ref<Users> | null;
user_id?: number | null;
name!: string;
client_id!: string;
client_secret_hash!: string;
redirect_uris: string & Opt = '[]';
allowed_scopes: string & Opt = '[]';
created_at?: string | null;
is_public: number & Opt = 0;
created_via: string & Opt = 'settings_ui';
allows_client_credentials: number & Opt = 0;
oauth_consents_collection = new Collection<OauthConsents>(this);
oauth_tokens_collection = new Collection<OauthTokens>(this);
}
export const OauthClientsSchema = defineEntity({
class: OauthClients,
repository: () => OauthClientsRepository,
uniques: [{ properties: ['client_id'] }],
properties: {
id: p.text().primary().nullable(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').nullable().hidden().index('idx_oauth_clients_user'),
user_id: p.integer().nullable().persist(false).index('idx_oauth_clients_user'),
name: p.text(),
client_id: p.text().unique('idx_oauth_clients_client_id'),
client_secret_hash: p.text(),
redirect_uris: p.text().default('[]'),
allowed_scopes: p.text().default('[]'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
is_public: p.integer().default(0),
created_via: p.text().default('settings_ui'),
allows_client_credentials: p.integer().default(0),
oauth_consents_collection: () => p.oneToMany(OauthConsents).mappedBy('client').hidden(),
oauth_tokens_collection: () => p.oneToMany(OauthTokens).mappedBy('client').hidden(),
},
});
@@ -0,0 +1,31 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { OauthConsentsRepository } from '../repositories/OauthConsents.repository';
import { DbTimestampType } from '../types';
import { OauthClients } from './OauthClients.entity';
import { Users } from './Users.entity';
export class OauthConsents {
[EntityRepositoryType]?: OauthConsentsRepository;
id!: number & Opt;
client!: Ref<OauthClients>;
client_id!: string;
user!: Ref<Users>;
user_id!: number;
scopes: string & Opt = '[]';
updated_at?: string | null;
}
export const OauthConsentsSchema = defineEntity({
class: OauthConsents,
repository: () => OauthConsentsRepository,
uniques: [{ properties: ['client', 'user'] }],
properties: {
id: p.integer().primary(),
client: () => p.manyToOne(OauthClients).ref().name('client_id').deleteRule('cascade').hidden().referencedColumnNames('client_id'),
client_id: p.text().persist(false),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_oauth_consents_user_id'),
user_id: p.integer().persist(false).index('idx_oauth_consents_user_id'),
scopes: p.text().default('[]'),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,52 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { OauthTokensRepository } from '../repositories/OauthTokens.repository';
import { DbTimestampType } from '../types';
import { OauthClients } from './OauthClients.entity';
import { Users } from './Users.entity';
export class OauthTokens {
[EntityRepositoryType]?: OauthTokensRepository;
id!: number & Opt;
client!: Ref<OauthClients>;
client_id!: string;
user!: Ref<Users>;
user_id!: number;
access_token_hash!: string;
refresh_token_hash!: string;
scopes: string & Opt = '[]';
access_token_expires_at!: string;
refresh_token_expires_at!: string;
revoked_at?: string | null;
created_at?: string | null;
parentToken?: Ref<OauthTokens> | null;
parent_token_id?: number | null;
audience?: string | null;
oauth_tokens_collection = new Collection<OauthTokens>(this);
}
export const OauthTokensSchema = defineEntity({
class: OauthTokens,
repository: () => OauthTokensRepository,
uniques: [
{ properties: ['refresh_token_hash'] },
{ properties: ['access_token_hash'] },
],
properties: {
id: p.integer().primary(),
client: () => p.manyToOne(OauthClients).ref().name('client_id').deleteRule('cascade').hidden().index('idx_oauth_tokens_client_id').referencedColumnNames('client_id'),
client_id: p.text().persist(false).index('idx_oauth_tokens_client_id'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_oauth_tokens_user'),
user_id: p.integer().persist(false).index('idx_oauth_tokens_user'),
access_token_hash: p.text().unique('idx_oauth_tokens_access'),
refresh_token_hash: p.text().unique('idx_oauth_tokens_refresh'),
scopes: p.text().default('[]'),
access_token_expires_at: p.type(DbTimestampType),
refresh_token_expires_at: p.type(DbTimestampType),
revoked_at: p.type(DbTimestampType).nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
parentToken: () => p.manyToOne(OauthTokens).ref().deleteRule('no action').nullable().hidden().index('idx_oauth_tokens_parent'),
parent_token_id: p.integer().nullable().persist(false).index('idx_oauth_tokens_parent'),
audience: p.text().nullable(),
oauth_tokens_collection: () => p.oneToMany(OauthTokens).mappedBy('parentToken').hidden(),
},
});
@@ -0,0 +1,41 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PackingBagsRepository } from '../repositories/PackingBags.repository';
import { DbTimestampType } from '../types';
import { PackingItems } from './PackingItems.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class PackingBags {
[EntityRepositoryType]?: PackingBagsRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
name!: string;
color: string & Opt = '#6366f1';
weight_limit_grams?: number | null;
sort_order?: number | null = 0;
created_at?: string | null;
user?: Ref<Users> | null;
user_id?: number | null;
packing_bag_members = new Collection<Users>(this);
packing_items_collection = new Collection<PackingItems>(this);
}
export const PackingBagsSchema = defineEntity({
class: PackingBags,
repository: () => PackingBagsRepository,
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_packing_bags_trip_id'),
trip_id: p.integer().persist(false).index('idx_packing_bags_trip_id'),
name: p.text(),
color: p.text().default('#6366f1'),
weight_limit_grams: p.integer().nullable(),
sort_order: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
user: () => p.manyToOne(Users).ref().nullable().hidden().defaultRaw(`NULL`).index('idx_packing_bags_user_id'),
user_id: p.integer().nullable().persist(false).defaultRaw(`NULL`).index('idx_packing_bags_user_id'),
packing_bag_members: () => p.manyToMany(Users).pivotTable('packing_bag_members').joinColumn('bag_id').inverseJoinColumn('user_id').hidden(),
packing_items_collection: () => p.oneToMany(PackingItems).mappedBy('bag').hidden(),
},
});
@@ -0,0 +1,28 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PackingCategoryAssigneesRepository } from '../repositories/PackingCategoryAssignees.repository';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class PackingCategoryAssignees {
[EntityRepositoryType]?: PackingCategoryAssigneesRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
category_name!: string;
user!: Ref<Users>;
user_id!: number;
}
export const PackingCategoryAssigneesSchema = defineEntity({
class: PackingCategoryAssignees,
repository: () => PackingCategoryAssigneesRepository,
uniques: [{ properties: ['trip', 'category_name', 'user'] }],
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden(),
trip_id: p.integer().persist(false),
category_name: p.text(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_packing_category_assignees_user_id'),
user_id: p.integer().persist(false).index('idx_packing_category_assignees_user_id'),
},
});
@@ -0,0 +1,30 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PackingItemContributorsRepository } from '../repositories/PackingItemContributors.repository';
import { DbTimestampType } from '../types';
import { PackingItems } from './PackingItems.entity';
import { Users } from './Users.entity';
export class PackingItemContributors {
[EntityRepositoryType]?: PackingItemContributorsRepository;
[PrimaryKeyProp]?: ['item', 'user'];
item!: Ref<PackingItems>;
item_id!: number;
user!: Ref<Users>;
user_id!: number;
status: string & Opt = 'accepted';
created_at?: string | null;
}
export const PackingItemContributorsSchema = defineEntity({
class: PackingItemContributors,
repository: () => PackingItemContributorsRepository,
uniques: [{ properties: ['item', 'user'] }],
properties: {
item: () => p.manyToOne(PackingItems).primary().ref().hidden(),
item_id: p.integer().persist(false),
user: () => p.manyToOne(Users).primary().ref().hidden().index('idx_packing_item_contributors_user_id'),
user_id: p.integer().persist(false).index('idx_packing_item_contributors_user_id'),
status: p.text().default('accepted'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,58 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PackingItemsRepository } from '../repositories/PackingItems.repository';
import { DbTimestampType } from '../types';
import { PackingBags } from './PackingBags.entity';
import { PackingItemContributors } from './PackingItemContributors.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class PackingItems {
[EntityRepositoryType]?: PackingItemsRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
name!: string;
checked?: number | null = 0;
category?: string | null;
sort_order?: number | null = 0;
created_at?: string | null;
weight_grams?: number | null;
bag?: Ref<PackingBags> | null;
bag_id?: number | null;
quantity: number & Opt = 1;
updated_at?: string | null;
is_private: number & Opt = 0;
owner?: Ref<Users> | null;
owner_id?: number | null;
packed_quantity?: number | null;
packing_item_contributors = new Collection<Users>(this);
packing_item_recipients = new Collection<Users>(this);
packing_item_contributors_collection = new Collection<PackingItemContributors>(this);
}
export const PackingItemsSchema = defineEntity({
class: PackingItems,
repository: () => PackingItemsRepository,
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_packing_items_trip_id'),
trip_id: p.integer().persist(false).index('idx_packing_items_trip_id'),
name: p.text(),
checked: p.integer().nullable(),
category: p.text().nullable(),
sort_order: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
weight_grams: p.integer().nullable(),
bag: () => p.manyToOne(PackingBags).ref().nullable().hidden().index('idx_packing_items_bag_id'),
bag_id: p.integer().nullable().persist(false).index('idx_packing_items_bag_id'),
quantity: p.integer().default(1),
updated_at: p.type(DbTimestampType).nullable(),
is_private: p.integer().default(0),
owner: () => p.manyToOne(Users).ref().nullable().hidden().index('idx_packing_items_owner_id'),
owner_id: p.integer().nullable().persist(false).index('idx_packing_items_owner_id'),
packed_quantity: p.integer().nullable(),
packing_item_contributors: () => p.manyToMany(Users).pivotTable('packing_item_contributors').pivotEntity(() => PackingItemContributors).joinColumn('item_id').inverseJoinColumn('user_id').hidden(),
packing_item_recipients: () => p.manyToMany(Users).pivotTable('packing_item_recipients').joinColumn('item_id').inverseJoinColumn('user_id').hidden(),
packing_item_contributors_collection: () => p.oneToMany(PackingItemContributors).mappedBy('item').hidden(),
},
});
@@ -0,0 +1,27 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PackingTemplateCategoriesRepository } from '../repositories/PackingTemplateCategories.repository';
import { PackingTemplateItems } from './PackingTemplateItems.entity';
import { PackingTemplates } from './PackingTemplates.entity';
export class PackingTemplateCategories {
[EntityRepositoryType]?: PackingTemplateCategoriesRepository;
id!: number & Opt;
template!: Ref<PackingTemplates>;
template_id!: number;
name!: string;
sort_order: number & Opt = 0;
packing_template_items_collection = new Collection<PackingTemplateItems>(this);
}
export const PackingTemplateCategoriesSchema = defineEntity({
class: PackingTemplateCategories,
repository: () => PackingTemplateCategoriesRepository,
properties: {
id: p.integer().primary(),
template: () => p.manyToOne(PackingTemplates).ref().deleteRule('cascade').hidden().index('idx_packing_template_categories_template_id'),
template_id: p.integer().persist(false).index('idx_packing_template_categories_template_id'),
name: p.text(),
sort_order: p.integer().default(0),
packing_template_items_collection: () => p.oneToMany(PackingTemplateItems).mappedBy('category').hidden(),
},
});
@@ -0,0 +1,30 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PackingTemplateItemsRepository } from '../repositories/PackingTemplateItems.repository';
import { PackingTemplateCategories } from './PackingTemplateCategories.entity';
export class PackingTemplateItems {
[EntityRepositoryType]?: PackingTemplateItemsRepository;
id!: number & Opt;
category!: Ref<PackingTemplateCategories>;
category_id!: number;
name!: string;
sort_order: number & Opt = 0;
weight_grams?: number | null;
quantity: number & Opt = 1;
bag_name?: string | null;
}
export const PackingTemplateItemsSchema = defineEntity({
class: PackingTemplateItems,
repository: () => PackingTemplateItemsRepository,
properties: {
id: p.integer().primary(),
category: () => p.manyToOne(PackingTemplateCategories).ref().deleteRule('cascade').hidden().index('idx_packing_template_items_category_id'),
category_id: p.integer().persist(false).index('idx_packing_template_items_category_id'),
name: p.text(),
sort_order: p.integer().default(0),
weight_grams: p.integer().nullable(),
quantity: p.integer().default(1),
bag_name: p.text().nullable(),
},
});
@@ -0,0 +1,28 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PackingTemplatesRepository } from '../repositories/PackingTemplates.repository';
import { DbTimestampType } from '../types';
import { PackingTemplateCategories } from './PackingTemplateCategories.entity';
import { Users } from './Users.entity';
export class PackingTemplates {
[EntityRepositoryType]?: PackingTemplatesRepository;
id!: number & Opt;
name!: string;
created_by!: number;
created_at?: string | null;
createdByRef!: Ref<Users>;
packing_template_categories_collection = new Collection<PackingTemplateCategories>(this);
}
export const PackingTemplatesSchema = defineEntity({
class: PackingTemplates,
repository: () => PackingTemplatesRepository,
properties: {
id: p.integer().primary(),
name: p.text(),
created_by: p.integer().persist(false).index('idx_packing_templates_created_by'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
createdByRef: () => p.manyToOne(Users).ref().joinColumn('created_by').deleteRule('cascade').hidden().index('idx_packing_templates_created_by'),
packing_template_categories_collection: () => p.oneToMany(PackingTemplateCategories).mappedBy('template').hidden(),
},
});
@@ -0,0 +1,54 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PaddleFeaturesRepository } from '../repositories/PaddleFeatures.repository';
import { PaddleRegions } from './PaddleRegions.entity';
export class PaddleFeatures {
[EntityRepositoryType]?: PaddleFeaturesRepository;
id!: number & Opt;
region!: Ref<PaddleRegions>;
region_id!: string;
osm_ref!: string;
kind!: string;
group_key?: string | null;
name?: string | null;
geometry!: string;
tags!: string;
tag_hash!: string;
min_lat!: number;
min_lng!: number;
max_lat!: number;
max_lng!: number;
}
export const PaddleFeaturesSchema = defineEntity({
class: PaddleFeatures,
repository: () => PaddleFeaturesRepository,
indexes: [
{
name: 'idx_paddle_features_box',
properties: ['min_lat', 'max_lat', 'min_lng', 'max_lng'],
},
],
uniques: [
{
name: 'idx_paddle_features_region_ref',
properties: ['region_id', 'osm_ref'],
},
],
properties: {
id: p.integer().primary(),
region: () => p.manyToOne(PaddleRegions).ref().deleteRule('cascade').hidden(),
region_id: p.text().persist(false),
osm_ref: p.text(),
kind: p.text(),
group_key: p.text().nullable(),
name: p.text().nullable(),
geometry: p.text(),
tags: p.text(),
tag_hash: p.text(),
min_lat: p.double(),
min_lng: p.double(),
max_lat: p.double(),
max_lng: p.double(),
},
});
@@ -0,0 +1,37 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, defineEntity, p } from '@mikro-orm/core';
import { PaddleRegionRequestsRepository } from '../repositories/PaddleRegionRequests.repository';
import { DbTimestampType } from '../types';
export class PaddleRegionRequests {
[EntityRepositoryType]?: PaddleRegionRequestsRepository;
[PrimaryKeyProp]?: 'region_id';
region_id!: string;
name!: string;
reason!: TPaddleRegionRequestsReason;
bytes?: number | null;
requested_by?: string | null;
requested_at!: string & Opt;
declined_at?: string | null;
}
export const PaddleRegionRequestsReason = {
ASK: 'ask',
TOO_LARGE: 'too_large',
LIMIT: 'limit',
} as const;
export type TPaddleRegionRequestsReason = (typeof PaddleRegionRequestsReason)[keyof typeof PaddleRegionRequestsReason];
export const PaddleRegionRequestsSchema = defineEntity({
class: PaddleRegionRequests,
repository: () => PaddleRegionRequestsRepository,
properties: {
region_id: p.text().primary(),
name: p.text(),
reason: p.enum(() => PaddleRegionRequestsReason),
bytes: p.integer().nullable(),
requested_by: p.text().nullable(),
requested_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
declined_at: p.type(DbTimestampType).nullable(),
},
});
@@ -0,0 +1,64 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PaddleRegionsRepository } from '../repositories/PaddleRegions.repository';
import { DbTimestampType } from '../types';
import { PaddleFeatures } from './PaddleFeatures.entity';
import { PaddleWaterGraphs } from './PaddleWaterGraphs.entity';
export class PaddleRegions {
[EntityRepositoryType]?: PaddleRegionsRepository;
id!: string;
name!: string;
boundary?: string | null;
min_lat?: number | null;
min_lng?: number | null;
max_lat?: number | null;
max_lng?: number | null;
status: TPaddleRegionsStatus & Opt = PaddleRegionsStatus.QUEUED;
source_timestamp?: string | null;
imported_at?: string | null;
feature_count: number & Opt = 0;
error?: string | null;
created_at?: string | null;
origin: TPaddleRegionsOrigin & Opt = PaddleRegionsOrigin.ADMIN;
paddle_features_collection = new Collection<PaddleFeatures>(this);
paddle_water_graphs: Ref<PaddleWaterGraphs> | null = null;
}
export const PaddleRegionsStatus = {
QUEUED: 'queued',
IMPORTING: 'importing',
READY: 'ready',
FAILED: 'failed',
} as const;
export type TPaddleRegionsStatus = (typeof PaddleRegionsStatus)[keyof typeof PaddleRegionsStatus];
export const PaddleRegionsOrigin = {
ADMIN: 'admin',
AUTO: 'auto',
} as const;
export type TPaddleRegionsOrigin = (typeof PaddleRegionsOrigin)[keyof typeof PaddleRegionsOrigin];
export const PaddleRegionsSchema = defineEntity({
class: PaddleRegions,
repository: () => PaddleRegionsRepository,
properties: {
id: p.text().primary(),
name: p.text(),
boundary: p.text().nullable(),
min_lat: p.double().nullable(),
min_lng: p.double().nullable(),
max_lat: p.double().nullable(),
max_lng: p.double().nullable(),
status: p.enum(() => PaddleRegionsStatus).default('queued'),
source_timestamp: p.text().nullable(),
imported_at: p.type(DbTimestampType).nullable(),
feature_count: p.integer().default(0),
error: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
origin: p.enum(() => PaddleRegionsOrigin).default('admin'),
paddle_features_collection: () => p.oneToMany(PaddleFeatures).mappedBy('region').hidden(),
paddle_water_graphs: () => p.oneToOne(PaddleWaterGraphs).ref().mappedBy('region').hidden(),
},
});

Some files were not shown because too many files have changed in this diff Show More