setNewCategoryName(e.target.value)}
onKeyDown={e => {
@@ -309,7 +310,7 @@ export default function MPackingListTab({ planner }: { planner: TripPlanner }) {
setSaveTemplateName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void saveAsTemplate() }}
@@ -529,7 +530,7 @@ function PackingCategoryCard({
{renaming ? (
setRenameDraft(e.target.value)}
onBlur={commitRename}
@@ -589,7 +590,7 @@ function PackingCategoryCard({
setNewItemName(e.target.value)}
onBlur={() => { if (!newItemName.trim()) { setAddingItem(false); setNewItemName('') } }}
diff --git a/client/src/mobile/screens/trip/tabs/MTaskSheet.tsx b/client/src/mobile/screens/trip/tabs/MTaskSheet.tsx
index 1b84fe351..37783856c 100644
--- a/client/src/mobile/screens/trip/tabs/MTaskSheet.tsx
+++ b/client/src/mobile/screens/trip/tabs/MTaskSheet.tsx
@@ -1,3 +1,4 @@
+import { focusRevealedEditor } from '../../../../components/shared/dialogFocus'
import { useEffect, useRef, useState } from 'react'
import { Check, Flag, Plus, User } from 'lucide-react'
import type { TodoCreateItemRequest } from '@trek/shared'
@@ -175,7 +176,7 @@ export default function MTaskSheet({ planner, open, itemId, categories, members,
setCategoryDraft(e.target.value)}
onKeyDown={e => {
diff --git a/client/src/mobile/screens/trip/tabs/tabChrome.tsx b/client/src/mobile/screens/trip/tabs/tabChrome.tsx
index d271815ca..11b148e11 100644
--- a/client/src/mobile/screens/trip/tabs/tabChrome.tsx
+++ b/client/src/mobile/screens/trip/tabs/tabChrome.tsx
@@ -125,7 +125,7 @@ export function TabPanes({ aside, asideLabel, children }: { aside: ReactNode; as
/** Where the list starts in its scroll body's content, under the body's top padding. */
function listStartIn(el: HTMLElement, top: HTMLElement): number {
- const pad = parseFloat(getComputedStyle(el).paddingTop) || 0
+ const pad = Number.parseFloat(getComputedStyle(el).paddingTop) || 0
return top.getBoundingClientRect().top - el.getBoundingClientRect().top - pad + el.scrollTop
}
diff --git a/client/src/native/serverAddress.ts b/client/src/native/serverAddress.ts
index 79eade814..aa7b9a24e 100644
--- a/client/src/native/serverAddress.ts
+++ b/client/src/native/serverAddress.ts
@@ -1,3 +1,4 @@
+import { stripTrailingSlashes } from '@trek/shared';
import { detectAuthGate, type AuthGate } from './authGate';
import { DEMO_SERVER_URL } from './links';
@@ -59,7 +60,7 @@ function normalize(raw: string): string | null {
return null;
}
if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || !parsed.hostname) return null;
- return parsed.origin + parsed.pathname.replace(/\/+$/, '');
+ return parsed.origin + stripTrailingSlashes(parsed.pathname);
}
/**
diff --git a/client/src/pages/ResetPasswordPage.tsx b/client/src/pages/ResetPasswordPage.tsx
index 5d6d80d95..69a0d4f48 100644
--- a/client/src/pages/ResetPasswordPage.tsx
+++ b/client/src/pages/ResetPasswordPage.tsx
@@ -145,7 +145,6 @@ function ResetPasswordPage() {
type="text" inputMode="numeric" value={mfaCode}
onChange={(e: ChangeEvent) => setMfaCode(e.target.value)}
required placeholder="123456 or backup-code" style={{ ...inputBase, paddingInlineEnd: 12 }}
- autoFocus
onFocus={(e) => { e.currentTarget.style.borderColor = '#111827' }}
onBlur={(e) => { e.currentTarget.style.borderColor = '#e5e7eb' }}
/>
diff --git a/client/src/pages/atlas/AtlasGlobeWishAdd.tsx b/client/src/pages/atlas/AtlasGlobeWishAdd.tsx
index f3e5a2132..84902d94f 100644
--- a/client/src/pages/atlas/AtlasGlobeWishAdd.tsx
+++ b/client/src/pages/atlas/AtlasGlobeWishAdd.tsx
@@ -1,5 +1,6 @@
import { ChevronLeft, ChevronRight, Loader2, MapPin, PenLine, Search, Sparkles, Star, X } from 'lucide-react';
import React from 'react';
+import { focusRevealedEditor } from '../../components/shared/dialogFocus';
import { fs } from '../../components/shared/DialogShell';
import { HUB_CARD, HUB_FIELD, HUB_INSET, HubGhost, HubGlow, HubIconButton, HubPrimary } from './atlasHubKit';
import type { AtlasGlobeState } from './useAtlasGlobe';
@@ -85,7 +86,7 @@ export default function AtlasGlobeWishAdd({ s }: { s: AtlasGlobeState }): React.
className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-muted"
/>
setQuery(e.target.value)}
onKeyDown={(e) => {
diff --git a/client/src/pages/atlas/atlasGlobePaint.ts b/client/src/pages/atlas/atlasGlobePaint.ts
index 51bab795d..ab350ff6c 100644
--- a/client/src/pages/atlas/atlasGlobePaint.ts
+++ b/client/src/pages/atlas/atlasGlobePaint.ts
@@ -133,7 +133,7 @@ export function paintGlobe(engine: GlobeEngine, input: GlobePaintInput): void {
const r = engine.renderer;
const byCode = new Map((input.data?.countries ?? []).map((c) => [c.code, c]));
const visitYears = (input.data?.countries ?? [])
- .map((c) => (c.firstVisit ? Number(c.firstVisit.slice(0, 4)) : NaN))
+ .map((c) => (c.firstVisit ? Number(c.firstVisit.slice(0, 4)) : Number.NaN))
.filter((y) => !Number.isNaN(y));
const firstYear = visitYears.length ? Math.min(...visitYears) : new Date().getFullYear();
const lastYear = visitYears.length ? Math.max(...visitYears) : firstYear;
diff --git a/client/src/pages/atlas/useAtlasGlobe.ts b/client/src/pages/atlas/useAtlasGlobe.ts
index 96c390bf2..749e9a23d 100644
--- a/client/src/pages/atlas/useAtlasGlobe.ts
+++ b/client/src/pages/atlas/useAtlasGlobe.ts
@@ -431,7 +431,7 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) {
for (const rows of Object.values(regions))
regionCount += rows.filter((r) => (r.status ?? 'visited') === 'visited').length;
const years = visited
- .map((c) => (c.firstVisit ? Number(c.firstVisit.slice(0, 4)) : NaN))
+ .map((c) => (c.firstVisit ? Number(c.firstVisit.slice(0, 4)) : Number.NaN))
.filter((y) => !Number.isNaN(y));
const perYear = new Map();
for (const y of years) perYear.set(y, (perYear.get(y) ?? 0) + 1);
diff --git a/client/src/repo/mapMatchRepo.ts b/client/src/repo/mapMatchRepo.ts
index a0377ac5d..2cbd7ad5e 100644
--- a/client/src/repo/mapMatchRepo.ts
+++ b/client/src/repo/mapMatchRepo.ts
@@ -44,8 +44,8 @@ export async function findOnMap(queries: string[], lang?: string): Promise typeof v === 'string' && v.trim() !== '');
const address = typeof place.address === 'string' && place.address.trim() ? place.address : undefined;
diff --git a/client/src/utils/colorSpace.ts b/client/src/utils/colorSpace.ts
index 541e422f0..14ca1aba9 100644
--- a/client/src/utils/colorSpace.ts
+++ b/client/src/utils/colorSpace.ts
@@ -23,7 +23,7 @@ export function normalizeHex(raw: string): string | null {
export function hexToHsv(hex: string): Hsv {
const norm = normalizeHex(hex) ?? '#000000';
- const [r, g, b] = [1, 3, 5].map((i) => parseInt(norm.slice(i, i + 2), 16) / 255);
+ const [r, g, b] = [1, 3, 5].map((i) => Number.parseInt(norm.slice(i, i + 2), 16) / 255);
const max = Math.max(r, g, b);
const d = max - Math.min(r, g, b);
let h = 0;
diff --git a/server/src/app-config/parsers.ts b/server/src/app-config/parsers.ts
index b848ae0c8..8624bda00 100644
--- a/server/src/app-config/parsers.ts
+++ b/server/src/app-config/parsers.ts
@@ -1,6 +1,6 @@
/**
* Pure env-string coercion helpers shared by the whole config layer (derive.ts,
- * env.schema.ts). Kept free of imports so units can test them in isolation.
+ * env.schema.ts). Kept free of environment access 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
@@ -67,14 +67,7 @@ export function csvListFiltered(raw: string | undefined): string[] | null {
: null;
}
-/** Strip ALL trailing slashes (`/\/+$/`) — app-url.getAppUrl / TRANSIT_API_URL variant.
- * Scanned rather than replaced: `/\/+$/` re-walks the slash run from every start
- * position, which is quadratic on a slash-heavy value. Same result, same quirk. */
-export function stripTrailingSlashes(value: string): string {
- let end = value.length;
- while (end > 0 && value.charCodeAt(end - 1) === 47 /* '/' */) end--;
- return value.slice(0, end);
-}
+export { stripTrailingSlashes } from '@trek/shared';
const DURATION_UNITS_MS: Record = {
ms: 1,
diff --git a/server/src/db/engine/postgres/pg-tools.ts b/server/src/db/engine/postgres/pg-tools.ts
index 444f8c279..7c7df560a 100644
--- a/server/src/db/engine/postgres/pg-tools.ts
+++ b/server/src/db/engine/postgres/pg-tools.ts
@@ -363,11 +363,14 @@ function migrationNamesFromCopy(script: string): string[] {
return match !== null && !isPluginSchemaName(match[1] ?? '');
});
if (copy < 0) return [];
- const columns =
- /\(([^)]*)\)/
- .exec(lines[copy])?.[1]
- .split(',')
- .map((column) => column.trim()) ?? [];
+ const header = lines[copy];
+ const start = header.indexOf('(') + 1;
+ const end = header.indexOf(')', start);
+ if (end === -1) return [];
+ const columns = header
+ .slice(start, end)
+ .split(',')
+ .map((column) => column.trim());
const nameAt = columns.indexOf('name');
if (nameAt < 0) return [];
const names: string[] = [];
diff --git a/server/src/db/engine/postgres/sqlite-move/plugin-data.ts b/server/src/db/engine/postgres/sqlite-move/plugin-data.ts
index e4bff412a..b874850ee 100644
--- a/server/src/db/engine/postgres/sqlite-move/plugin-data.ts
+++ b/server/src/db/engine/postgres/sqlite-move/plugin-data.ts
@@ -69,7 +69,7 @@ export function pluginColumnKind(declaredType: string, storage: ReadonlySet> {
- const trimmed = raw.trim().replace(/\/+$/, '');
+ const trimmed = stripTrailingSlashes(raw.trim());
if (!trimmed) return { success: false, error: { code: 'unreachable', detail: 'empty url' } };
const verdict = await checkSsrf(trimmed);
if (!verdict.allowed && !verdict.isPrivate) {
diff --git a/server/src/nest/doc-sync/providers/synology-drive.client.ts b/server/src/nest/doc-sync/providers/synology-drive.client.ts
index 5ae50029a..d6350e629 100644
--- a/server/src/nest/doc-sync/providers/synology-drive.client.ts
+++ b/server/src/nest/doc-sync/providers/synology-drive.client.ts
@@ -1,3 +1,4 @@
+import { stripTrailingSlashes } from '@trek/shared';
import { Readable } from 'node:stream';
import { createHash } from 'node:crypto';
import type { DocsyncErrorCode } from '@trek/shared';
@@ -336,8 +337,7 @@ function isRecord(value: unknown): value is Record {
export function normalizeBaseUrl(raw: string): string {
const trimmed = raw.trim();
const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
- return withScheme
- .replace(/\/+$/, '')
+ return stripTrailingSlashes(withScheme)
.replace(/\/webapi\/(entry|auth|query)\.cgi$/i, '')
.replace(/\/webapi$/i, '');
}
diff --git a/server/src/nest/doc-sync/providers/webdav.client.ts b/server/src/nest/doc-sync/providers/webdav.client.ts
index e2894c568..7b0568cc1 100644
--- a/server/src/nest/doc-sync/providers/webdav.client.ts
+++ b/server/src/nest/doc-sync/providers/webdav.client.ts
@@ -2,6 +2,7 @@ import { readCappedJson, readCappedText } from '../../../utils/cappedFetch';
import { PROVIDER_JSON_MAX_BYTES, PROVIDER_TIMEOUT_MS, PROVIDER_TRANSFER_TIMEOUT_MS } from '../doc-sync.constants';
import { DOWNLOAD_MAX_BYTES, guardDownload, providerFetch, statusErrorCode } from './provider-http';
import { Injectable } from '@nestjs/common';
+import { stripTrailingSlashes } from '@trek/shared';
import type { DocsyncErrorCode } from '@trek/shared';
import { XMLParser } from 'fast-xml-parser';
@@ -213,15 +214,13 @@ export function normalizeFileId(raw: string | null, flavor: WebdavFlavor): strin
* rule would also eat an install that lives under `/apps/nextcloud`.
*/
export function normalizeOrigin(baseUrl: string): string {
- return baseUrl
- .trim()
- .replace(/[?#].*$/, '')
- .replace(/\/+$/, '')
+ const [base = ''] = baseUrl.trim().split(/[?#]/, 1);
+ const origin = stripTrailingSlashes(base)
.replace(/\/(?:remote|index)\.php(?:\/.*)?$/i, '')
.replace(/\/apps\/(?:files|dashboard)(?:\/.*)?$/i, '')
.replace(/\/dav\/spaces(?:\/.*)?$/i, '')
- .replace(/\/graph(?:\/.*)?$/i, '')
- .replace(/\/+$/, '');
+ .replace(/\/graph(?:\/.*)?$/i, '');
+ return stripTrailingSlashes(origin);
}
/**
@@ -251,7 +250,7 @@ export function encodePath(path: string): string {
/** `/a/b/` and `a//b` both mean `/a/b`. Every comparison here depends on one spelling. */
export function normalizePath(path: string): string {
- const collapsed = `/${path}`.replace(/\/+/g, '/').replace(/\/+$/, '');
+ const collapsed = stripTrailingSlashes(`/${path}`.replace(/\/+/g, '/'));
return collapsed === '' ? '/' : collapsed;
}
diff --git a/server/src/nest/doc-sync/providers/webdav.provider.ts b/server/src/nest/doc-sync/providers/webdav.provider.ts
index 2f06302ca..f9a633327 100644
--- a/server/src/nest/doc-sync/providers/webdav.provider.ts
+++ b/server/src/nest/doc-sync/providers/webdav.provider.ts
@@ -170,9 +170,10 @@ function sanitizeName(name: string): string {
// eslint-disable-next-line no-control-regex
.replace(/[\\/<>:"|?*\u0000-\u001f]/g, '-')
.replace(/\s+/g, ' ')
- .trim()
- .replace(/[. ]+$/, '');
- return cleaned.slice(0, 200);
+ .trim();
+ let end = cleaned.length;
+ while (end > 0 && (cleaned[end - 1] === '.' || cleaned[end - 1] === ' ')) end--;
+ return cleaned.slice(0, Math.min(end, 200));
}
function parentOf(encodedPath: string): string {
diff --git a/server/src/nest/flight-live/flight-live.derive.ts b/server/src/nest/flight-live/flight-live.derive.ts
index aa89f4f6d..3acd646e2 100644
--- a/server/src/nest/flight-live/flight-live.derive.ts
+++ b/server/src/nest/flight-live/flight-live.derive.ts
@@ -217,6 +217,8 @@ function bearingDeg(lat1: number, lng1: number, lat2: number, lng2: number): num
return (Math.atan2(y, x) * 180) / Math.PI;
}
+const NO_SIBLING_SECTORS = { now: 0, siblings: [] as readonly SiblingSector[] };
+
/**
* The aircraft that flies this leg among those the feed answered for the
* callsign: the one with a position nearest the great circle between the two
@@ -228,10 +230,12 @@ function bearingDeg(lat1: number, lng1: number, lat2: number, lng2: number): num
export function pickAircraft(
aircraft: readonly FeedAircraft[],
route: Route,
- sectors: { now: number; siblings: readonly SiblingSector[]; departed?: boolean; taxied?: boolean } = {
- now: 0,
- siblings: [],
- },
+ sectors: {
+ now: number;
+ siblings: readonly SiblingSector[];
+ departed?: boolean;
+ taxied?: boolean;
+ } = NO_SIBLING_SECTORS,
): FeedAircraft | null {
let best: FeedAircraft | null = null;
let bestScore = Number.POSITIVE_INFINITY;
diff --git a/server/src/nest/help/wiki.ts b/server/src/nest/help/wiki.ts
index 6e561ec0e..00d490c83 100644
--- a/server/src/nest/help/wiki.ts
+++ b/server/src/nest/help/wiki.ts
@@ -1,5 +1,6 @@
import { readEnv } from '../../app-config';
import { exceedsDeclaredLength, readCapped, readCappedText } from '../../utils/cappedFetch';
+import { replaceInlineMarkdownLinks, stripPreviewTags } from '@trek/shared';
import { existsSync, promises as fs } from 'fs';
import path from 'path';
@@ -142,12 +143,28 @@ function parseSidebar(md: string): WikiNavSection[] {
return sections.filter((s) => s.pages.length > 0);
}
+function replaceWikiLinks(input: string, render: (label: string, original: string) => string): string {
+ const parts: string[] = [];
+ let cursor = 0;
+ for (let open = input.indexOf('[['); open !== -1;) {
+ const close = input.indexOf(']', open + 2);
+ if (close === -1) break;
+ if (close > open + 2 && input[close + 1] === ']') {
+ parts.push(input.slice(cursor, open), render(input.slice(open + 2, close), input.slice(open, close + 2)));
+ cursor = close + 2;
+ }
+ open = input.indexOf('[[', Math.max(cursor, close + 1));
+ }
+ parts.push(input.slice(cursor));
+ return parts.join('');
+}
+
/** Rewrite GitHub-wiki `[[..]]` links to /help routes and proxy relative images. */
function processMarkdown(md: string): string {
// Strip HTML comments (e.g. `` placeholders) — the
// markdown renderer would otherwise surface them as raw text.
let out = md.replace(//g, '');
- out = out.replace(/\[\[([^\]]+)\]\]/g, (_m, inner: string) => {
+ out = replaceWikiLinks(out, (inner) => {
const [titleRaw, slugRaw] = inner.includes('|') ? inner.split('|') : [inner, inner];
const slug = slugRaw.trim().replace(/\s+/g, '-');
// `[[Plugin Development#talking-to-plugins|Plugin-Development]]` must not
@@ -173,7 +190,8 @@ function processMarkdown(md: string): string {
// Runs last: `[[..]]` links and images have already become absolute paths by
// this point, so the leading-slash guard skips them.
out = outsideCode(out, (segment) =>
- segment.replace(/(^|[^!])\[([^\]]+)\]\(([^)\s]+)\)/g, (m, prefix: string, text: string, url: string) => {
+ replaceInlineMarkdownLinks(segment, (text, url, m, offset) => {
+ if (!text || !url || segment[offset - 1] === '!' || /\s/.test(url)) return m;
if (/^(https?:|mailto:|tel:|#|\/)/i.test(url)) return m;
const [pageRaw, anchor] = url.includes('#') ? url.split('#') : [url, ''];
const page = pageRaw
@@ -181,7 +199,7 @@ function processMarkdown(md: string): string {
.replace(/\.md$/i, '')
.trim();
if (!page || !SLUG_RE.test(page)) return m;
- return `${prefix}[${text}](/help/${page}${anchor ? `#${anchor}` : ''})`;
+ return `[${text}](/help/${page}${anchor ? `#${anchor}` : ''})`;
}),
);
return out;
@@ -328,13 +346,13 @@ function headingAnchor(text: string): string {
* itself is still rendered from the real markdown.
*/
function toPlainText(md: string): string {
- return md
+ const withoutImages = md
.replace(//g, ' ')
.replace(/```[\s\S]*?```|~~~[\s\S]*?~~~/g, ' ')
- .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
- .replace(/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g, '$1')
- .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
- .replace(/<[^>]+>/g, ' ')
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1');
+ const withoutWikiLinks = replaceWikiLinks(withoutImages, (label, original) => label.split('|', 1)[0] || original);
+ const plain = replaceInlineMarkdownLinks(withoutWikiLinks, (label, _target, original) => label || original, true);
+ return stripPreviewTags(plain, false)
.replace(/[`*_~>|#]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
@@ -353,10 +371,10 @@ function chunkByHeading(md: string): IndexedPage['chunks'] {
let inFence = false;
for (const line of md.split('\n')) {
if (/^(```|~~~)/.test(line)) inFence = !inFence;
- const h = !inFence && line.match(/^#{2,4}\s+(\S.*\S|.)\s*$/);
- if (h) {
+ const h = !inFence && /^#{2,4}\s/.exec(line);
+ if (h && line.length > h[0].length) {
flush();
- heading = h[1].replace(/[*_`]/g, '').trim();
+ heading = line.slice(h[0].length).replace(/[*_`]/g, '').trim();
continue;
}
buf.push(line);
diff --git a/server/src/nest/integrations/dawarich.helpers.ts b/server/src/nest/integrations/dawarich.helpers.ts
index 71a0cf24e..b0cc666ba 100644
--- a/server/src/nest/integrations/dawarich.helpers.ts
+++ b/server/src/nest/integrations/dawarich.helpers.ts
@@ -90,11 +90,11 @@ export function syncWindow(
lookbackDays: number,
lookaheadDays: number,
): { from: Date; to: Date } | null {
- const start = startDate ? Date.parse(`${startDate}T00:00:00Z`) : NaN;
+ const start = startDate ? Date.parse(`${startDate}T00:00:00Z`) : Number.NaN;
if (!Number.isFinite(start)) return null;
const from = new Date(start - lookbackDays * 86_400_000);
- const end = endDate ? Date.parse(`${endDate}T23:59:59Z`) : NaN;
+ const end = endDate ? Date.parse(`${endDate}T23:59:59Z`) : Number.NaN;
const to = Number.isFinite(end) ? new Date(Math.min(end + lookaheadDays * 86_400_000, now.getTime())) : now;
return to.getTime() > from.getTime() ? { from, to } : null;
diff --git a/server/src/nest/journey/book-design-draft.store.ts b/server/src/nest/journey/book-design-draft.store.ts
index 9c95c8928..99413a18b 100644
--- a/server/src/nest/journey/book-design-draft.store.ts
+++ b/server/src/nest/journey/book-design-draft.store.ts
@@ -81,12 +81,11 @@ export class InMemoryBookDesignDraftStore extends BookDesignDraftStore {
put(draft: BookDesignDraft): Promise {
const size = JSON.stringify(draft.doc).length + (draft.base ? JSON.stringify(draft.base).length : 0);
if (size > BOOK_DESIGN_DRAFTS.maxChars) {
- return Promise.reject(
- new DomainError(422, 'This design is too large to keep', {
- code: 'book_design_too_large',
- mcpMessage: 'This design is too large to keep as a draft: design fewer pages (pages.max) or a scope.',
- }),
- );
+ const error: Error = new DomainError(422, 'This design is too large to keep', {
+ code: 'book_design_too_large',
+ mcpMessage: 'This design is too large to keep as a draft: design fewer pages (pages.max) or a scope.',
+ });
+ return Promise.reject(error);
}
this.sweep();
const key = keyOf(draft.userId, draft.journeyId, draft.designId);
diff --git a/server/src/nest/llm-parse/mime-walker.ts b/server/src/nest/llm-parse/mime-walker.ts
index dbdebebb5..8d52bd3d2 100644
--- a/server/src/nest/llm-parse/mime-walker.ts
+++ b/server/src/nest/llm-parse/mime-walker.ts
@@ -362,11 +362,16 @@ const FORWARD_MARKER = new RegExp(String.raw`^\s*[-_]{2,}\s*(?:${FORWARD_MARKER_
const FORWARD_INTRO = new RegExp(String.raw`^\s*(?:${FORWARD_INTRO_WORDS.join('|')})\s*:\s*$`, 'i');
/** Outlook's rule above the header block of a forwarded message. */
const OUTLOOK_RULE = /^\s*_{10,}\s*$/;
-/**
- * "On 1 May, Ana wrote:", the line above a quoted reply, which names the sender.
- * The lookahead checks the closing colon first, which keeps a long line without one linear.
- */
-const ATTRIBUTION = /^(?=.*:\s*$)\s*(?:on\s.+\swrote|am\s.+\sschrieb\s.+|le\s.+\sa\s[ée]crit)\s*:\s*$/i;
+/** A line such as "On 1 May, Ana wrote:" above a quoted reply. */
+function isReplyAttribution(line: string): boolean {
+ const trimmed = line.trim();
+ if (!trimmed.endsWith(':')) return false;
+ const header = trimmed.slice(0, -1);
+ if (/^am\s/i.test(header)) return /\sschrieb\s./i.test(header.slice(4));
+ const words = header.trimEnd();
+ if (/^on\s/i.test(words)) return /\swrote$/i.test(words.slice(4));
+ return /^le\s/i.test(words) && /\sa\s[ée]crit$/i.test(words.slice(4));
+}
const HEADER_LINE = fieldLine([...SENDER_FIELDS, ...OTHER_FIELDS, ...SUBJECT_FIELDS]);
const FROM_LINE = fieldLine(SENDER_FIELDS);
const SUBJECT_LINE = fieldLine(SUBJECT_FIELDS);
@@ -408,7 +413,7 @@ function unwrapLayer(lines: string[]): { lines: string[]; changed: boolean } {
} else if (bareBlockStarts[i]) {
i = skipHeaderBlock(lines, i);
changed = true;
- } else if (line.length <= MAX_ATTRIBUTION_LINE && ATTRIBUTION.test(line)) {
+ } else if (line.length <= MAX_ATTRIBUTION_LINE && isReplyAttribution(line)) {
i++;
changed = true;
} else if (/^\s*>/.test(line)) {
diff --git a/server/src/nest/mail-ingest/mail-ingest-address.service.ts b/server/src/nest/mail-ingest/mail-ingest-address.service.ts
index 44c359ccb..74c435811 100644
--- a/server/src/nest/mail-ingest/mail-ingest-address.service.ts
+++ b/server/src/nest/mail-ingest/mail-ingest-address.service.ts
@@ -193,7 +193,10 @@ export function hashToken(token: string): string {
* Null for an address that holds none.
*/
export function tokenOf(recipient: string, template: string | null): string | null {
- const address = recipient.replace(/^.*, '').replace(/>.*$/, '').trim().toLowerCase();
+ const lines = recipient.replace(/^.*, '').split(/([\r\n\u2028\u2029])/);
+ const last = lines.length - 1;
+ lines[last] = lines[last].split('>', 1)[0];
+ const address = lines.join('').trim().toLowerCase();
const local = address.split('@')[0] ?? '';
if (template) {
const [prefix, suffix] = template.toLowerCase().split('@')[0].split('{token}');
diff --git a/server/src/nest/mail-ingest/mail-ingest-inbound.controller.ts b/server/src/nest/mail-ingest/mail-ingest-inbound.controller.ts
index 6c6998d12..a6f368045 100644
--- a/server/src/nest/mail-ingest/mail-ingest-inbound.controller.ts
+++ b/server/src/nest/mail-ingest/mail-ingest-inbound.controller.ts
@@ -93,7 +93,10 @@ export class MailIngestInboundController {
* arriving at the deadline ends the read the same way.
*/
function readBody(req: Request, maxBytes: number, take: (bytes: number) => boolean): Promise {
- if (Number(req.get('content-length')) > maxBytes) return Promise.reject(new DomainError(413, TOO_LARGE));
+ if (Number(req.get('content-length')) > maxBytes) {
+ const error: Error = new DomainError(413, TOO_LARGE);
+ return Promise.reject(error);
+ }
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let size = 0;
@@ -112,7 +115,7 @@ function readBody(req: Request, maxBytes: number, take: (bytes: number) => boole
};
const onEnd = () => {
clearTimeout(deadline);
- if (size > maxBytes) reject(new DomainError(413, TOO_LARGE));
+ if (size > maxBytes) stop(new DomainError(413, TOO_LARGE));
else resolve(Buffer.concat(chunks));
};
const deadline = setTimeout(() => stop(new DomainError(408, TOO_SLOW)), READ_DEADLINE_MS);
diff --git a/server/src/nest/maps/trek-places.client.ts b/server/src/nest/maps/trek-places.client.ts
index 66773a357..2bbf3abea 100644
--- a/server/src/nest/maps/trek-places.client.ts
+++ b/server/src/nest/maps/trek-places.client.ts
@@ -17,6 +17,7 @@ import { toApiLang } from './maps.helpers';
import { trekCommunityValuesSchema, type TrekCommunityValues } from './trek-community.schema';
import { identifiedFetch } from './trek-places.fetch';
import {
+ stripTrailingSlashes,
normalizePlaceWebsite,
skiRouteBuildSchema,
winterIndexRowSchema,
@@ -190,7 +191,7 @@ export function trekPlacesMiss(err: unknown): TrekPlacesMiss {
export function trekPlacesBaseUrl(): string {
const configured = (readEnv().maps.trekPlacesUrl || '').trim();
- return (configured || DEFAULT_TREK_PLACES_URL).replace(/\/+$/, '');
+ return stripTrailingSlashes(configured || DEFAULT_TREK_PLACES_URL);
}
/**
diff --git a/server/src/nest/maps/trek-places.fetch.ts b/server/src/nest/maps/trek-places.fetch.ts
index ec928fcdf..086f27cea 100644
--- a/server/src/nest/maps/trek-places.fetch.ts
+++ b/server/src/nest/maps/trek-places.fetch.ts
@@ -42,7 +42,7 @@ function instanceToken(): string {
const url = getAppUrl();
let hash = 0;
for (let i = 0; i < url.length; i++) {
- hash = ((hash << 5) - hash + url.charCodeAt(i)) | 0;
+ hash = ((hash << 5) - hash + url.charCodeAt(i)) >>> 0;
}
return `trek-${(hash >>> 0).toString(36)}`;
}
diff --git a/server/src/nest/notifications/transports/ntfy.service.ts b/server/src/nest/notifications/transports/ntfy.service.ts
index 55a6f5d82..3fc1fc168 100644
--- a/server/src/nest/notifications/transports/ntfy.service.ts
+++ b/server/src/nest/notifications/transports/ntfy.service.ts
@@ -9,6 +9,7 @@ import { decrypt_api_key } from '../../common/crypto/apiKeyCrypto';
import type { NotifEventType } from '../notification-events';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
+import { stripTrailingSlashes } from '@trek/shared';
/** NS2's three per-user ntfy keys, read together off `SettingsRepository.getForUser`. */
const NTFY_USER_KEYS = new Set(['ntfy_topic', 'ntfy_server', 'ntfy_token']);
@@ -79,7 +80,7 @@ export function isOperatorNtfyServer(server: string | null | undefined, adminSer
const raw = (value || 'https://ntfy.sh').replace(/(? 0 && /^[\w-]$/.test(name.charAt(start - 1))) start--;
+ const delimiter = name.indexOf('-', Math.max(1, start));
+ return delimiter !== -1 && dot - delimiter > 8;
+}
+
+function isHashedAsset(filePath: string): boolean {
+ const segments = filePath.split(/[\\/]/);
+ const name = segments.at(-1);
+ if (segments.length < 3 || segments.at(-2) !== 'assets' || !name) return false;
+ return hasHashedStem(name) || (name.endsWith('.br') && hasHashedStem(name.slice(0, -3)));
+}
/**
* Production static serving of the built client (JS/CSS/assets). Split out from
@@ -376,7 +390,7 @@ export function applyPlatformStatic(app: express.Application): void {
setHeaders: (res, filePath) => {
if (filePath.endsWith('index.html')) {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
- } else if (HASHED_ASSET.test(filePath)) {
+ } else if (isHashedAsset(filePath)) {
// Vite puts a content hash in every name under assets/, so a file there
// never changes. Without this the iOS app, which has no service worker,
// cannot start offline: WebKit would revalidate each script and fail.
diff --git a/server/src/nest/plugins/install/safe-extract.ts b/server/src/nest/plugins/install/safe-extract.ts
index 63db65356..bba27173d 100644
--- a/server/src/nest/plugins/install/safe-extract.ts
+++ b/server/src/nest/plugins/install/safe-extract.ts
@@ -83,7 +83,7 @@ function readTarGz(buf: Buffer, lim: Required): Member[] {
let name = block.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
const prefix = block.subarray(345, 500).toString('utf8').replace(/\0.*$/, '');
if (prefix) name = `${prefix}/${name}`;
- const size = Number.parseInt(block.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim() || '0', 8);
+ const size = Number.parseInt(block.subarray(124, 136).toString('utf8').split('\0', 1)[0].trim() || '0', 8);
// A negative size walks the cursor backwards: `off += 512` and then
// `off += Math.ceil(size / 512) * 512` cancel out at -512 and go negative
// below it, so the same header is read forever while every pass appends a
diff --git a/server/src/nest/plugins/mcp-tool-schema.ts b/server/src/nest/plugins/mcp-tool-schema.ts
index b903d03d9..ecf7c8798 100644
--- a/server/src/nest/plugins/mcp-tool-schema.ts
+++ b/server/src/nest/plugins/mcp-tool-schema.ts
@@ -376,6 +376,13 @@ const NUMERIC_KEYWORDS: ReadonlyArray= 0 && dot < address.length - 1;
+}
+
/**
* Formats worth enforcing. An unlisted one would be advertised and never checked.
*
@@ -384,7 +391,7 @@ const NUMERIC_KEYWORDS: ReadonlyArray boolean>([
- ['email', (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)],
+ ['email', looksLikeEmail],
['uuid', (v) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v)],
['uri', (v) => /^[a-z][a-z0-9+.-]*:/i.test(v)],
['date-time', (v) => !Number.isNaN(Date.parse(v))],
diff --git a/server/src/nest/roadtrip/roadtrip-router.service.ts b/server/src/nest/roadtrip/roadtrip-router.service.ts
index d5d395e4b..b07b23cf8 100644
--- a/server/src/nest/roadtrip/roadtrip-router.service.ts
+++ b/server/src/nest/roadtrip/roadtrip-router.service.ts
@@ -21,6 +21,7 @@ import {
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
+ stripTrailingSlashes,
resolveValhallaProvider,
VALHALLA_COSTING,
VALHALLA_RELAY_MAX_LOCATIONS,
@@ -254,9 +255,9 @@ function routersOf(
trekValhalla: string | null,
): { base: string; valhalla: string; everyDay: boolean } {
const base =
- typeof settings.routing_base_url === 'string' ? settings.routing_base_url.trim().replace(/\/+$/, '') : '';
+ typeof settings.routing_base_url === 'string' ? stripTrailingSlashes(settings.routing_base_url.trim()) : '';
const configuredValhalla =
- typeof settings.valhalla_base_url === 'string' ? settings.valhalla_base_url.trim().replace(/\/+$/, '') : '';
+ typeof settings.valhalla_base_url === 'string' ? stripTrailingSlashes(settings.valhalla_base_url.trim()) : '';
const provider = resolveValhallaProvider({
provider: settings.routing_valhalla_provider,
valhallaUrl: configuredValhalla,
diff --git a/server/src/nest/routing-relay/routing-relay.service.ts b/server/src/nest/routing-relay/routing-relay.service.ts
index 094a546e9..94bf8f273 100644
--- a/server/src/nest/routing-relay/routing-relay.service.ts
+++ b/server/src/nest/routing-relay/routing-relay.service.ts
@@ -7,7 +7,12 @@ import { RateLimitService } from '../common/rate-limit.service';
import { ServiceIdentityPort } from '../service-identity/service-identity.interface';
import { Inject, Injectable } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
-import { VALHALLA_RELAY_REQUEST_SCHEMAS, compactValhallaRequest, type ValhallaRelayAction } from '@trek/shared';
+import {
+ stripTrailingSlashes,
+ VALHALLA_RELAY_REQUEST_SCHEMAS,
+ compactValhallaRequest,
+ type ValhallaRelayAction,
+} from '@trek/shared';
/**
* Questions one user may put to the TREK Valhalla a minute, the browser and the server's
@@ -78,7 +83,7 @@ export class RoutingRelayService {
/** Whether an address names the TREK Valhalla, whose questions go through here and nowhere else. */
serves(base: string): boolean {
- return base.trim().replace(/\/+$/, '') === this.config.valhallaUrl;
+ return stripTrailingSlashes(base.trim()) === this.config.valhallaUrl;
}
async ask(
diff --git a/server/src/nest/service-identity/registration-dialect.ts b/server/src/nest/service-identity/registration-dialect.ts
index 74488216b..618fc6b99 100644
--- a/server/src/nest/service-identity/registration-dialect.ts
+++ b/server/src/nest/service-identity/registration-dialect.ts
@@ -36,7 +36,7 @@ function spruce(input: Buffer): string {
const bits = [...input].map((byte) => byte.toString(2).padStart(8, '0')).join('');
let out = '';
for (let i = 0; i < bits.length; i += 5) {
- out += FROST_CRATER.charAt(parseInt(bits.slice(i, i + 5).padEnd(5, '0'), 2));
+ out += FROST_CRATER.charAt(Number.parseInt(bits.slice(i, i + 5).padEnd(5, '0'), 2));
}
return out;
}
diff --git a/server/src/nest/service-identity/service-identity.helpers.ts b/server/src/nest/service-identity/service-identity.helpers.ts
index 39ee2d8b5..95e3900f8 100644
--- a/server/src/nest/service-identity/service-identity.helpers.ts
+++ b/server/src/nest/service-identity/service-identity.helpers.ts
@@ -1,4 +1,4 @@
-import { serviceTierSchema, type ServiceQuotaView, type ServiceTier } from '@trek/shared';
+import { stripTrailingSlashes, serviceTierSchema, type ServiceQuotaView, type ServiceTier } from '@trek/shared';
import { createHash } from 'node:crypto';
@@ -17,7 +17,7 @@ function serviceAddress(raw: string): string | null {
if (!trimmed) return null;
try {
const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`);
- return `${url.host}${url.pathname.replace(/\/+$/, '')}`.toLowerCase();
+ return `${url.host}${stripTrailingSlashes(url.pathname)}`.toLowerCase();
} catch {
return null;
}
diff --git a/server/src/nest/sessions/sessions.service.ts b/server/src/nest/sessions/sessions.service.ts
index 4b709d994..b94bd0620 100644
--- a/server/src/nest/sessions/sessions.service.ts
+++ b/server/src/nest/sessions/sessions.service.ts
@@ -50,7 +50,7 @@ export interface RenewableSessionClaims {
*/
export function legacySessionId(token: string): string {
const h = createHash('sha256').update(token).digest('hex');
- const variant = ((parseInt(h.charAt(16), 16) & 0x3) | 0x8).toString(16);
+ const variant = ((Number.parseInt(h.charAt(16), 16) & 0x3) | 0x8).toString(16);
return `${h.slice(0, 8)}-${h.slice(8, 12)}-8${h.slice(13, 16)}-${variant}${h.slice(17, 20)}-${h.slice(20, 32)}`;
}
diff --git a/server/src/nest/ski-routing/ski-graph.contract.ts b/server/src/nest/ski-routing/ski-graph.contract.ts
index dcbaca974..3139d6936 100644
--- a/server/src/nest/ski-routing/ski-graph.contract.ts
+++ b/server/src/nest/ski-routing/ski-graph.contract.ts
@@ -11,7 +11,7 @@ export const SGR_FORMAT = 1;
/** What an edge may be used for, per direction (`edgeFwdUses` a to b, `edgeBackUses` b to a). */
export const Use = {
- DOWNHILL: 1 << 0,
+ DOWNHILL: 1,
LIFT_UP: 1 << 1,
LIFT_DOWN: 1 << 2,
NORDIC_CLASSIC: 1 << 3,
@@ -55,7 +55,7 @@ export const DIFF_EXPERT = 4;
/** `edgeGroom` bits. */
export const Groom = {
- CLASSIC: 1 << 0,
+ CLASSIC: 1,
SKATING: 1 << 1,
SCOOTER: 1 << 2,
BACKCOUNTRY: 1 << 3,
@@ -100,7 +100,7 @@ export const Lift = {
/** `nodeFlags` bits. */
export const NodeFlag = {
- STATION: 1 << 0,
+ STATION: 1,
PORTAL: 1 << 1,
DISMOUNT_YES: 1 << 2,
DISMOUNT_SOMETIMES: 1 << 3,
@@ -116,7 +116,7 @@ export const NodeFlag = {
* way tagged `piste:type=yes`, usable as a connection only (cost x1.5).
*/
export const EdgeFlag = {
- DIR_FROM_DEM: 1 << 0,
+ DIR_FROM_DEM: 1,
DIR_CONFLICT: 1 << 1,
RELATION_INHERITED: 1 << 2,
TECHNIQUE_ASSUMED: 1 << 3,
diff --git a/server/src/nest/storage/storage-reclaim.ledger.ts b/server/src/nest/storage/storage-reclaim.ledger.ts
index 76822e420..d07b04490 100644
--- a/server/src/nest/storage/storage-reclaim.ledger.ts
+++ b/server/src/nest/storage/storage-reclaim.ledger.ts
@@ -1,6 +1,7 @@
import type { StorageReclaimableCategory, StorageReferenceSourceId } from './storage-reclaim.types';
import type { BackendSnapshot, StorageRegistryService } from './storage-registry.service';
import { SERVED_CATEGORIES, type ServedCategory } from './storage.types';
+import { stripTrailingSlashes } from '@trek/shared';
import fs from 'node:fs';
import path from 'node:path';
@@ -177,7 +178,7 @@ function realOrNull(target: string): string | null {
/** A resolved folder with forward slashes and one trailing slash. */
function slashed(folder: string): string {
- return `${folder.replace(/\\/g, '/').replace(/\/+$/, '')}/`;
+ return `${stripTrailingSlashes(folder.replace(/\\/g, '/'))}/`;
}
function asList(value: string | number | string[] | undefined): string[] {
diff --git a/server/src/nest/tours/tours-import.controller.ts b/server/src/nest/tours/tours-import.controller.ts
index 1b2d60733..2825711fb 100644
--- a/server/src/nest/tours/tours-import.controller.ts
+++ b/server/src/nest/tours/tours-import.controller.ts
@@ -95,10 +95,16 @@ export class ToursImportController {
@UploadedFile() file: Express.Multer.File | undefined,
@Headers('x-socket-id') socketId?: string,
// None is a hike, as every import was before the type could be chosen.
- @Body() fields: TourGpxImportFieldsDto = { tour_type: 'hike' },
+ @Body() fields?: TourGpxImportFieldsDto,
) {
const buffer = await this.checkedFile(user, tripId, file);
- const result = await this.tours.importGpxAsTour(tripId, buffer, file?.originalname, socketId, fields);
+ const result = await this.tours.importGpxAsTour(
+ tripId,
+ buffer,
+ file?.originalname,
+ socketId,
+ fields ?? { tour_type: 'hike' },
+ );
if (!result) {
throw noTrackFound(file?.originalname);
}
diff --git a/server/src/nest/wallet-pass/wallet-pass.service.ts b/server/src/nest/wallet-pass/wallet-pass.service.ts
index f2ada6e0a..fc30ec9f4 100644
--- a/server/src/nest/wallet-pass/wallet-pass.service.ts
+++ b/server/src/nest/wallet-pass/wallet-pass.service.ts
@@ -296,7 +296,7 @@ export function filenameOf(title: string): string {
.normalize('NFKD')
.replace(/\p{M}/gu, '')
.replace(/[^\p{L}\p{N}]+/gu, '-')
- .replace(/^-+|-+$/g, '')
+ .replace(/^-|-$/g, '')
.slice(0, 60);
return slug || 'booking';
}
diff --git a/server/src/nest/wanderer/wanderer.client.ts b/server/src/nest/wanderer/wanderer.client.ts
index 5c839bf42..9df700d39 100644
--- a/server/src/nest/wanderer/wanderer.client.ts
+++ b/server/src/nest/wanderer/wanderer.client.ts
@@ -1,7 +1,12 @@
import { readCappedJson } from '../../utils/cappedFetch';
import { ResponseTooLargeError, safeFetch, SsrfBlockedError } from '../../utils/ssrfGuard';
import { Injectable } from '@nestjs/common';
-import { WANDERER_SEARCH_PAGE_SIZE, type WandererBbox, type WandererErrorCode } from '@trek/shared';
+import {
+ stripTrailingSlashes,
+ WANDERER_SEARCH_PAGE_SIZE,
+ type WandererBbox,
+ type WandererErrorCode,
+} from '@trek/shared';
import { z } from 'zod';
@@ -110,9 +115,7 @@ export type WandererTrailRecord = z.infer;
* full `/api/v1` are all taken off, so the client can append its own.
*/
export function instanceOrigin(baseUrl: string): string {
- return baseUrl
- .trim()
- .replace(/\/+$/, '')
+ return stripTrailingSlashes(baseUrl.trim())
.replace(/\/api\/v1$/i, '')
.replace(/\/api$/i, '');
}
diff --git a/shared/src/book/design/design-framing.ts b/shared/src/book/design/design-framing.ts
index bf3b54aed..b7f86fb4c 100644
--- a/shared/src/book/design/design-framing.ts
+++ b/shared/src/book/design/design-framing.ts
@@ -52,11 +52,12 @@ export function composeCover(
c: ComposeCtx,
words: CoverWords,
photo: AutoPhoto | null,
- more: CoverMaterial = { photos: photo ? [photo] : [], entries: [] },
+ more?: CoverMaterial,
): BookSpread {
const archetype = c.directives.cover?.archetype;
- if (archetype) return composeArchetypeCover(c, archetype, words, more);
- if (c.directives.cover?.lockup) return lockupCover(c, words, more);
+ const material = more ?? { photos: photo ? [photo] : [], entries: [] };
+ if (archetype) return composeArchetypeCover(c, archetype, words, material);
+ if (c.directives.cover?.lockup) return lockupCover(c, words, material);
const { pageWidth: PW, pageHeight: H, bleed: b, margin: m } = c.grid;
const els: BookElement[] = [];
const title = titleWords(words.ownTitle, words.title);
diff --git a/shared/src/book/design/design-random.ts b/shared/src/book/design/design-random.ts
index 11338343c..b415f9b80 100644
--- a/shared/src/book/design/design-random.ts
+++ b/shared/src/book/design/design-random.ts
@@ -38,7 +38,7 @@ function hash(seed: number, key: string): number {
export function designRng(seed: number, key: string): DesignRng {
let state = hash(seed, key);
const next = () => {
- state = (state + 0x6d2b79f5) | 0;
+ state = Math.imul(state + 0x6d2b79f5, 1);
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
diff --git a/shared/src/common/strip-markdown.spec.ts b/shared/src/common/strip-markdown.spec.ts
index 8653d0907..8a3080aa4 100644
--- a/shared/src/common/strip-markdown.spec.ts
+++ b/shared/src/common/strip-markdown.spec.ts
@@ -1,4 +1,4 @@
-import { stripMarkdown } from './strip-markdown';
+import { replaceInlineMarkdownLinks, stripMarkdown, stripPreviewTags } from './strip-markdown';
import { describe, expect, it } from 'vitest';
@@ -51,3 +51,17 @@ describe('stripMarkdown', () => {
expect(Date.now() - started).toBeLessThan(1_000);
});
});
+
+describe('plain text previews', () => {
+ it('passes the label and target of adjacent links to the formatter', () => {
+ const render = (label: string, target: string) => `${label}: ${target}`;
+ expect(replaceInlineMarkdownLinks('[A](one)[B](two)', render)).toBe('A: oneB: two');
+ expect(replaceInlineMarkdownLinks('[A](one\ntwo)', render)).toBe('[A](one\ntwo)');
+ expect(replaceInlineMarkdownLinks('[A](one\ntwo)', render, true)).toBe('A: one\ntwo');
+ });
+
+ it('separates surrounding words and keeps unfinished tags', () => {
+ expect(stripPreviewTags('onetwothreetwo', false)).toBe('one<>two');
+ });
+});
diff --git a/shared/src/common/strip-markdown.ts b/shared/src/common/strip-markdown.ts
index 76ffef865..6cb169df6 100644
--- a/shared/src/common/strip-markdown.ts
+++ b/shared/src/common/strip-markdown.ts
@@ -11,7 +11,7 @@ export function stripMarkdown(md: string): string {
// instead of being retried against every later "](". Same matches, no backtracking
.replace(/!\[(?:(?!\]\().)*\]\(.*?\)/g, ''); // images
- return stripLinks(withoutImages) // links → text
+ return replaceInlineMarkdownLinks(withoutImages, (label) => label)
.replace(/(`{3}[\s\S]*?`{3})/g, '') // code blocks
.replace(/`([^`]+)`/g, '$1') // inline code
.replace(/\*\*(.+?)\*\*/g, '$1') // bold **
@@ -53,7 +53,11 @@ const notALineTerminator = /./;
* - the target ends at the first `)`, and `.` cannot cross a line terminator, so a `(`
* whose first `)` only turns up on a later line is not a link at all.
*/
-function stripLinks(input: string): string {
+export function replaceInlineMarkdownLinks(
+ input: string,
+ replace: (label: string, target: string, original: string, offset: number) => string,
+ multilineTargets = false,
+): string {
let out = '';
let cursor = 0; // everything before this has already been copied into `out`
let search = 0; // where the next `[` is looked for
@@ -79,16 +83,38 @@ function stripLinks(input: string): string {
}
if (stop < close + 2) stop = close + 2;
- while (stop < input.length && input[stop] !== ')' && notALineTerminator.test(input.charAt(stop))) stop++;
+ while (
+ stop < input.length &&
+ input[stop] !== ')' &&
+ (multilineTargets || notALineTerminator.test(input.charAt(stop)))
+ )
+ stop++;
if (input[stop] !== ')') {
search = close + 1;
continue;
}
- out += input.slice(cursor, open) + input.slice(open + 1, close);
+ out +=
+ input.slice(cursor, open) +
+ replace(input.slice(open + 1, close), input.slice(close + 2, stop), input.slice(open, stop + 1), open);
cursor = stop + 1;
search = stop + 1;
}
return out + input.slice(cursor);
}
+
+/** Separate words on either side of markup when building a plain text preview. */
+export function stripPreviewTags(input: string, allowEmpty = true): string {
+ const parts: string[] = [];
+ let cursor = 0;
+ for (let open = input.indexOf('<'); open !== -1; open = input.indexOf('<', cursor)) {
+ const close = input.indexOf('>', open + 1);
+ if (close === -1) break;
+ parts.push(input.slice(cursor, allowEmpty || close > open + 1 ? open : close + 1));
+ if (allowEmpty || close > open + 1) parts.push(' ');
+ cursor = close + 1;
+ }
+ parts.push(input.slice(cursor));
+ return parts.join('');
+}
diff --git a/shared/src/common/strip-trailing-slashes.ts b/shared/src/common/strip-trailing-slashes.ts
new file mode 100644
index 000000000..d22cee233
--- /dev/null
+++ b/shared/src/common/strip-trailing-slashes.ts
@@ -0,0 +1,6 @@
+/** Remove every trailing slash from a URL or path in one pass. */
+export function stripTrailingSlashes(value: string): string {
+ let end = value.length;
+ while (end > 0 && value[end - 1] === '/') end--;
+ return value.slice(0, end);
+}
diff --git a/shared/src/index.ts b/shared/src/index.ts
index 100802fc6..03dbbf147 100644
--- a/shared/src/index.ts
+++ b/shared/src/index.ts
@@ -12,6 +12,7 @@ export * from './common/primitives.schema';
export * from './common/pagination.schema';
export * from './common/compare';
export * from './common/strip-markdown';
+export * from './common/strip-trailing-slashes';
// Domain contracts
export * from './weather/weather.schema';
diff --git a/shared/src/trip/day-grid.ts b/shared/src/trip/day-grid.ts
index 24a9ebccb..3717b54bc 100644
--- a/shared/src/trip/day-grid.ts
+++ b/shared/src/trip/day-grid.ts
@@ -16,7 +16,7 @@ const MS_PER_DAY = 86_400_000;
* wherever the clock sits east of Greenwich.
*/
export function addIsoDays(date: string, n: number): string {
- const [y = NaN, m = NaN, d = NaN] = date.split('-').map(Number);
+ const [y = Number.NaN, m = Number.NaN, d = Number.NaN] = date.split('-').map(Number);
const next = new Date(Date.UTC(y, m - 1, d) + n * MS_PER_DAY);
const yyyy = next.getUTCFullYear();
const mm = String(next.getUTCMonth() + 1).padStart(2, '0');
diff --git a/shared/src/trip/trip.schema.ts b/shared/src/trip/trip.schema.ts
index c4d8b374c..c54d2a9bc 100644
--- a/shared/src/trip/trip.schema.ts
+++ b/shared/src/trip/trip.schema.ts
@@ -26,7 +26,7 @@ export const MAX_TRIP_DAYS = 999;
/** Calendar days in an inclusive YYYY-MM-DD range, counted the same way on both sides of the wire. */
export function tripSpanDays(startDate: string, endDate: string): number {
const utcDay = (date: string) => {
- const [y = NaN, m = NaN, d = NaN] = date.split('-').map(Number);
+ const [y = Number.NaN, m = Number.NaN, d = Number.NaN] = date.split('-').map(Number);
return Date.UTC(y, m - 1, d);
};
return Math.floor((utcDay(endDate) - utcDay(startDate)) / 86400000) + 1;