mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
refactor(place-import): file and shared-list readers move into their own domain over one gpx and one kml codec
This commit is contained in:
@@ -4,7 +4,7 @@ import { HttpException } from '@nestjs/common';
|
||||
import { CollectionsController } from '../../../src/nest/collections/collections.controller';
|
||||
import type { CollectionsService } from '../../../src/nest/collections/collections.service';
|
||||
import type { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
import { CollectionGpxError } from '../../../src/nest/collections/collection-gpx.helpers';
|
||||
import { CollectionGpxError } from '../../../src/nest/place-import/place-import.types';
|
||||
import type { User } from '../../../src/types';
|
||||
import type { CollectionGpxProblem } from '@trek/shared';
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ import { createUser, createTrip, createPlace, createCategory, createTag, addTrip
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
import { CollectionsService } from '../../../src/nest/collections/collections.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service';
|
||||
import { makeStorageFixture } from '../../helpers/storage-fixture';
|
||||
import { notificationsStub } from '../../helpers/notifications';
|
||||
@@ -131,6 +132,7 @@ beforeAll(async () => {
|
||||
tripsRepoForSpy, await createTestTripMembersRepo(testDb),
|
||||
await createTestPlacesRepo(testDb), await createTestPlaceRatingsRepo(testDb),
|
||||
await createTestTagsRepo(testDb), await createTestUsersRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
photoCache = new PlacePhotoCacheService(
|
||||
makeStorageFixture('photos/google/').storage,
|
||||
|
||||
+2
-2
@@ -17,9 +17,9 @@ import {
|
||||
collectionFileToGpx,
|
||||
gpxToCollectionFile,
|
||||
type ExportedCollectionFile,
|
||||
} from '../../../src/nest/collections/collection-gpx.helpers';
|
||||
} from '../../../../src/nest/place-import/providers/collection-gpx.provider';
|
||||
|
||||
const fixture = (name: string) => fs.readFileSync(path.join(__dirname, '../../fixtures/gpx', name), 'utf8');
|
||||
const fixture = (name: string) => fs.readFileSync(path.join(__dirname, '../../../fixtures/gpx', name), 'utf8');
|
||||
|
||||
const listFile = (over: Partial<ExportedCollectionFile> = {}): ExportedCollectionFile => ({
|
||||
format: 'trek.collection', version: 1, name: 'Lisbon', places: [], ...over,
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
* that matter, because the full ones run to four hundred characters of protobuf.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { isDirectionsUrl, parseDirectionsUrl, MAX_DIR_WAYPOINTS } from '../../../src/nest/places/maps-dir.helpers';
|
||||
import { isDirectionsUrl, parseDirectionsUrl, MAX_DIR_WAYPOINTS } from '../../../../src/nest/place-import/directions-url.helpers';
|
||||
|
||||
describe('isDirectionsUrl', () => {
|
||||
it('MAPS-DIR-001: tells a route apart from a list and from a single place', () => {
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* The Google list source on its own: the feature-id parsing (moved from
|
||||
* places.helpers.test.ts with its code) and the answers the import route
|
||||
* gets back from it.
|
||||
*/
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
|
||||
const { mockCheckSsrf, mockFollow } = vi.hoisted(() => ({
|
||||
mockCheckSsrf: vi.fn(async (_url: string) => ({ allowed: true })),
|
||||
mockFollow: vi.fn(),
|
||||
}));
|
||||
vi.mock('../../../../src/utils/ssrfGuard', () => ({
|
||||
checkSsrf: mockCheckSsrf,
|
||||
safeFetchFollow: mockFollow,
|
||||
SsrfBlockedError: class SsrfBlockedError extends Error {},
|
||||
}));
|
||||
|
||||
import {
|
||||
GoogleListProvider,
|
||||
googleMapsFeatureIdFromItem,
|
||||
googleMapsHexId,
|
||||
} from '../../../../src/nest/place-import/providers/google-list.provider';
|
||||
import { SsrfBlockedError } from '../../../../src/utils/ssrfGuard';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
mockCheckSsrf.mockReset();
|
||||
mockCheckSsrf.mockResolvedValue({ allowed: true });
|
||||
mockFollow.mockReset();
|
||||
});
|
||||
|
||||
// ── Google Maps feature ids ───────────────────────────────────────────────────
|
||||
|
||||
describe('googleMapsHexId / googleMapsFeatureIdFromItem', () => {
|
||||
it('passes an already-hex id through lower-cased', () => {
|
||||
expect(googleMapsHexId('0x882BF179E806D471')).toBe('0x882bf179e806d471');
|
||||
});
|
||||
|
||||
it("converts Google's signed 64-bit decimals to unsigned hex", () => {
|
||||
expect(googleMapsHexId('-8634542354666695567')).toBe('0x882bf179e806d471');
|
||||
expect(googleMapsHexId(255)).toBe('0xff');
|
||||
});
|
||||
|
||||
it('rejects anything that is not a hex or decimal id', () => {
|
||||
expect(googleMapsHexId('not-an-id')).toBeNull();
|
||||
expect(googleMapsHexId(null)).toBeNull();
|
||||
expect(googleMapsHexId({})).toBeNull();
|
||||
});
|
||||
|
||||
it('reads the ftid pair from either item slot, else null', () => {
|
||||
expect(googleMapsFeatureIdFromItem([null, [0, 0, 0, 0, 0, 0, ['0x1', '0x2']]])).toBe('0x1:0x2');
|
||||
expect(googleMapsFeatureIdFromItem([null, null, null, null, null, null, null, [null, ['0x3', '0x4']]])).toBe('0x3:0x4');
|
||||
expect(googleMapsFeatureIdFromItem([null, [0, 0, 0, 0, 0, 0, ['0x1']]])).toBeNull();
|
||||
expect(googleMapsFeatureIdFromItem('not an array')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('GoogleListProvider.read', () => {
|
||||
it('refuses a URL the SSRF guard blocks, before fetching anything', async () => {
|
||||
mockCheckSsrf.mockResolvedValueOnce({ allowed: false });
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
expect(await new GoogleListProvider().read('https://10.0.0.1/maps')).toEqual({ error: 'URL is not allowed', status: 400 });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('hands a short link that lands on a route back as a directions link', async () => {
|
||||
mockFollow.mockResolvedValueOnce({ url: 'https://www.google.com/maps/dir/Berlin/Dresden/' });
|
||||
expect(await new GoogleListProvider().read('https://maps.app.goo.gl/abc')).toEqual({
|
||||
directions: 'https://www.google.com/maps/dir/Berlin/Dresden/',
|
||||
});
|
||||
});
|
||||
|
||||
it('points a single-place link at the search box', async () => {
|
||||
const out = await new GoogleListProvider().read('https://www.google.com/maps/place/Berlin');
|
||||
expect(out).toMatchObject({ status: 400 });
|
||||
expect((out as { error: string }).error).toContain('single place, not a list');
|
||||
});
|
||||
|
||||
it('reads the list name and the places that carry coordinates', async () => {
|
||||
const items = [
|
||||
[null, [null, null, null, null, null, [null, null, 52.5, 13.4], ['0x1', '0x2']], 'Cafe', 'note'],
|
||||
[null, [null, null, null, null, null, [null, null, null, null]], 'No coords'],
|
||||
];
|
||||
const body = `)]}'\n${JSON.stringify([[null, null, null, null, 'Trip ideas', null, null, null, items]])}`;
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { status: 200 })));
|
||||
expect(await new GoogleListProvider().read('https://www.google.com/maps/placelists/list/ABCDEFGHIJKLMNOP')).toEqual({
|
||||
listName: 'Trip ideas',
|
||||
places: [{ name: 'Cafe', lat: 52.5, lng: 13.4, notes: 'note', googleFtid: '0x1:0x2' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('GoogleListProvider.read: what Google sends back', () => {
|
||||
const LIST = 'https://www.google.com/maps/@52,13,10z/data=!4m3!11m2!2sABCDEFGHIJKLMNOPQRS!3e3';
|
||||
const respond = (body: string, init: ResponseInit = { status: 200 }) => vi.stubGlobal('fetch', vi.fn(async () => new Response(body, init)));
|
||||
const read = () => new GoogleListProvider().read(LIST);
|
||||
|
||||
it('finds the list id in the data parameter too', async () => {
|
||||
const fetchMock = vi.fn(async () => new Response('x', { status: 500 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await read();
|
||||
expect(String((fetchMock.mock.calls[0] as unknown[])[0])).toContain('!1sABCDEFGHIJKLMNOPQRS');
|
||||
});
|
||||
|
||||
it('answers a failed or oversized fetch with the provider message', async () => {
|
||||
respond('x', { status: 500 });
|
||||
expect(await read()).toEqual({ error: 'Failed to fetch list from Google Maps', status: 502 });
|
||||
respond('x', { status: 200, headers: { 'content-length': String(9 * 1024 * 1024) } });
|
||||
expect(await read()).toEqual({ error: 'Failed to fetch list from Google Maps', status: 502 });
|
||||
});
|
||||
|
||||
it('answers an unreadable payload with the invalid-data message', async () => {
|
||||
respond('prefix\nnot json');
|
||||
expect(await read()).toEqual({ error: 'Invalid list data received from Google Maps', status: 400 });
|
||||
respond('prefix\n{"a":1}');
|
||||
expect(await read()).toEqual({ error: 'Invalid list data received from Google Maps', status: 400 });
|
||||
respond('prefix\n[]');
|
||||
expect(await read()).toEqual({ error: 'Invalid list data received from Google Maps', status: 400 });
|
||||
});
|
||||
|
||||
it('refuses an empty list and one without a single coordinate', async () => {
|
||||
respond('prefix\n[[null,null,null,null,"L",null,null,null,[]]]');
|
||||
expect(await read()).toEqual({ error: 'List is empty or could not be read', status: 400 });
|
||||
respond('prefix\n[[null,null,null,null,null,null,null,null,[[null,[],"Nowhere"]]]]');
|
||||
expect(await read()).toEqual({ error: 'No places with coordinates found in list', status: 400 });
|
||||
});
|
||||
|
||||
it('refuses a short link the guard blocks on a hop, and lets a network failure through', async () => {
|
||||
mockFollow.mockRejectedValueOnce(new SsrfBlockedError('blocked'));
|
||||
expect(await new GoogleListProvider().read('https://maps.app.goo.gl/x')).toEqual({ error: 'URL is not allowed', status: 400 });
|
||||
mockFollow.mockRejectedValueOnce(new Error('network'));
|
||||
await expect(new GoogleListProvider().read('https://maps.app.goo.gl/x')).rejects.toThrow('network');
|
||||
});
|
||||
|
||||
it('needs a list id', async () => {
|
||||
expect(await new GoogleListProvider().read('https://www.google.com/maps/@52,13,10z')).toEqual({
|
||||
error: 'Could not extract list ID from URL. Please use a shared Google Maps list link.',
|
||||
status: 400,
|
||||
});
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { XMLParser, XMLValidator } from 'fast-xml-parser';
|
||||
import { buildGpx, gpxFilename, type GpxExportPlace, type GpxExportDay } from '../../../src/nest/places/gpx-export.helpers';
|
||||
import { buildGpx, gpxFilename, type GpxExportPlace, type GpxExportDay } from '../../../../src/nest/place-import/providers/gpx.provider';
|
||||
|
||||
const place = (over: Partial<GpxExportPlace> = {}): GpxExportPlace => ({
|
||||
name: 'Somewhere', description: null, address: null, lat: 48.8566, lng: 2.3522,
|
||||
@@ -0,0 +1,172 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import {
|
||||
decodeUtf8WithWarning,
|
||||
extractKmlPlacemarkNodes,
|
||||
KMZ_DECOMPRESSED_SIZE_LIMIT,
|
||||
parseKmlPointCoordinates,
|
||||
parsePlacemarkNode,
|
||||
readKmlDocument,
|
||||
sanitizeKmlDescription,
|
||||
unpackKmzToKml,
|
||||
} from '../../../../src/nest/place-import/kml.codec';
|
||||
import { buildCategoryNameLookup, resolveCategoryIdForFolder } from '../../../../src/nest/places/places.helpers';
|
||||
|
||||
describe('kmlImportUtils', () => {
|
||||
it('sanitizes HTML descriptions with br to newline', () => {
|
||||
const input = 'Line 1<br>Line <b>2</b> & more';
|
||||
const output = sanitizeKmlDescription(input);
|
||||
expect(output).toBe('Line 1\nLine 2 & more');
|
||||
});
|
||||
|
||||
it('unwraps CDATA sections before stripping tags', () => {
|
||||
const input = '<![CDATA[Great spot<br>for photos <b>and</b> skyline.]]>';
|
||||
expect(sanitizeKmlDescription(input)).toBe('Great spot\nfor photos and skyline.');
|
||||
});
|
||||
|
||||
it('parses KML coordinate order lng,lat,alt', () => {
|
||||
const parsed = parseKmlPointCoordinates('13.4050,52.5200,15');
|
||||
expect(parsed).toEqual({ lat: 52.52, lng: 13.405 });
|
||||
});
|
||||
|
||||
it('extracts placemarks from nested folders', () => {
|
||||
const root = {
|
||||
Document: {
|
||||
Folder: {
|
||||
name: 'Parent',
|
||||
Folder: {
|
||||
name: 'Child',
|
||||
Placemark: { name: 'Nested', Point: { coordinates: '13.4,52.5,0' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const nodes = extractKmlPlacemarkNodes(root);
|
||||
expect(nodes).toHaveLength(1);
|
||||
expect(nodes[0].folderName).toBe('Child');
|
||||
|
||||
const parsed = parsePlacemarkNode(nodes[0]);
|
||||
expect(parsed.name).toBe('Nested');
|
||||
expect(parsed.lat).toBe(52.5);
|
||||
expect(parsed.lng).toBe(13.4);
|
||||
});
|
||||
|
||||
it('builds exact case-insensitive category lookup', () => {
|
||||
const lookup = buildCategoryNameLookup([
|
||||
{ id: 3, name: 'Museums' },
|
||||
{ id: 4, name: 'Parks' },
|
||||
]);
|
||||
|
||||
expect(resolveCategoryIdForFolder('museums', lookup)).toBe(3);
|
||||
expect(resolveCategoryIdForFolder('Museum', lookup)).toBeNull();
|
||||
expect(resolveCategoryIdForFolder('parks', lookup)).toBe(4);
|
||||
});
|
||||
|
||||
it('decodes non-BMP decimal HTML entities (emoji)', () => {
|
||||
// 😀 = U+1F600 = 😀 — requires String.fromCodePoint, not fromCharCode
|
||||
expect(sanitizeKmlDescription('😀')).toBe('😀');
|
||||
});
|
||||
|
||||
it('decodes non-BMP hex HTML entities (emoji)', () => {
|
||||
// 😀 = U+1F600 = 😀
|
||||
expect(sanitizeKmlDescription('😀')).toBe('😀');
|
||||
});
|
||||
|
||||
it('does not produce [object Object] when description is a parsed object with #text', () => {
|
||||
// fast-xml-parser can return an object for mixed-content nodes when stopNodes
|
||||
// is not configured; the fallback in asTrimmedString must extract #text.
|
||||
const result = sanitizeKmlDescription({ '#text': 'Hello <b>world</b>' } as any);
|
||||
expect(result).not.toBe('[object Object]');
|
||||
expect(result).toBe('Hello world');
|
||||
});
|
||||
|
||||
it('returns null when description object has no #text', () => {
|
||||
expect(sanitizeKmlDescription({ i: 'bold' } as any)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns warning for non-UTF8 payload', () => {
|
||||
const buffer = Buffer.concat([
|
||||
Buffer.from('<?xml version="1.0"?><kml><Document><Placemark><name>Caf'),
|
||||
Buffer.from([0xe9]),
|
||||
Buffer.from('</name></Placemark></Document></kml>'),
|
||||
]);
|
||||
|
||||
const decoded = decodeUtf8WithWarning(buffer);
|
||||
expect(decoded.warning).toContain('not valid UTF-8');
|
||||
expect(decoded.text).toContain('<kml>');
|
||||
});
|
||||
});
|
||||
|
||||
const KMZ_FIXTURE = path.join(__dirname, '../../../fixtures/test.kmz');
|
||||
|
||||
describe('unpackKmzToKml', () => {
|
||||
it('extracts the KML entry from a valid KMZ', async () => {
|
||||
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
|
||||
const kmlBuffer = await unpackKmzToKml(kmzBuffer);
|
||||
expect(kmlBuffer.length).toBeGreaterThan(0);
|
||||
expect(kmlBuffer.toString('utf-8')).toContain('<kml');
|
||||
});
|
||||
|
||||
it('rejects a KMZ whose KML entry exceeds the decompressed size limit', async () => {
|
||||
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
|
||||
// test.kmz contains a KML with uncompressedSize 634 — set limit to 1 byte
|
||||
await expect(unpackKmzToKml(kmzBuffer, 1)).rejects.toThrow('exceeds the maximum allowed decompressed size');
|
||||
});
|
||||
|
||||
it('rejects a KMZ that contains no KML file', async () => {
|
||||
// Craft a minimal ZIP containing only a non-KML entry using raw ZIP bytes
|
||||
// We use the test GPX fixture (a real file) re-zipped via Node's zlib/archiver
|
||||
// Simplest: a KMZ whose only file has a .txt extension
|
||||
const Archiver = await import('archiver');
|
||||
const archiver = Archiver.default;
|
||||
const { PassThrough } = await import('stream');
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const output = new PassThrough();
|
||||
output.on('data', (chunk) => chunks.push(chunk));
|
||||
|
||||
const archive = archiver('zip', { zlib: { level: 1 } });
|
||||
archive.pipe(output);
|
||||
archive.append(Buffer.from('not a kml'), { name: 'data.txt' });
|
||||
await archive.finalize();
|
||||
|
||||
const zipBuffer = Buffer.concat(chunks);
|
||||
await expect(unpackKmzToKml(zipBuffer)).rejects.toThrow('does not contain a KML file');
|
||||
});
|
||||
|
||||
it('rejects a buffer that is not a valid ZIP archive', async () => {
|
||||
await expect(unpackKmzToKml(Buffer.from('this is not a zip'))).rejects.toThrow('Invalid KMZ archive');
|
||||
});
|
||||
|
||||
it('exports KMZ_DECOMPRESSED_SIZE_LIMIT as 50 MB', () => {
|
||||
expect(KMZ_DECOMPRESSED_SIZE_LIMIT).toBe(50 * 1024 * 1024);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readKmlDocument', () => {
|
||||
it('reads every placemark (a level before its folders) and counts them in the summary', () => {
|
||||
const kml = `<?xml version="1.0"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document><Folder><name>Food</name>
|
||||
<Placemark><name>Cafe</name><Point><coordinates>13.4,52.5,0</coordinates></Point></Placemark></Folder>
|
||||
<Placemark><name>Walk</name><LineString><coordinates>13.4,52.5 13.5,52.6</coordinates></LineString></Placemark>
|
||||
</Document></kml>`;
|
||||
const read = readKmlDocument(Buffer.from(kml, 'utf-8'));
|
||||
expect(read.summary).toMatchObject({ totalPlacemarks: 2, createdCount: 0, skippedCount: 0, warnings: [], errors: [] });
|
||||
expect(read.placemarks.map((p) => [p.name, p.folderName, p.routeGeometry !== null])).toEqual([
|
||||
['Walk', null, true],
|
||||
['Cafe', 'Food', false],
|
||||
]);
|
||||
});
|
||||
|
||||
it('refuses a document that is not well-formed XML with the route message', () => {
|
||||
expect(() => readKmlDocument(Buffer.from('<kml><Placemark></kml>', 'utf-8'))).toThrow('Malformed KML: invalid XML structure');
|
||||
});
|
||||
|
||||
it('keeps reading a file that is not valid UTF-8 and says so in the summary', () => {
|
||||
const bytes = Buffer.concat([Buffer.from('<kml><Placemark><name>'), Buffer.from([0xff]), Buffer.from('</name></Placemark></kml>')]);
|
||||
expect(readKmlDocument(bytes).summary.warnings).toEqual([
|
||||
'The uploaded file is not valid UTF-8. Some characters may be shown incorrectly.',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* The Naver list and Google directions sources on their own: every refusal
|
||||
* they hand the import route (status and exact message), the short-link hop
|
||||
* through the SSRF guard, and what a good link reads as. The persistence half
|
||||
* is PlacesService's and covered in places.service.test.ts.
|
||||
*/
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
|
||||
const { mockCheckSsrf, mockFollow, SsrfBlocked } = vi.hoisted(() => {
|
||||
class SsrfBlocked extends Error {}
|
||||
return {
|
||||
mockCheckSsrf: vi.fn(async (_url: string) => ({ allowed: true })),
|
||||
mockFollow: vi.fn(),
|
||||
SsrfBlocked,
|
||||
};
|
||||
});
|
||||
vi.mock('../../../../src/utils/ssrfGuard', () => ({
|
||||
checkSsrf: mockCheckSsrf,
|
||||
safeFetchFollow: mockFollow,
|
||||
SsrfBlockedError: SsrfBlocked,
|
||||
}));
|
||||
|
||||
import { NaverListProvider } from '../../../../src/nest/place-import/providers/naver-list.provider';
|
||||
import { GoogleDirectionsProvider } from '../../../../src/nest/place-import/providers/google-directions.provider';
|
||||
import { MAX_LIST_RESPONSE_BYTES } from '../../../../src/nest/place-import/providers/google-list.provider';
|
||||
|
||||
const FOLDER_URL = 'https://map.naver.com/p/favorite/myPlace/folder/abc123';
|
||||
|
||||
const page = (bookmarkList: Record<string, unknown>[], folder: Record<string, unknown> = { name: 'Seoul', bookmarkCount: bookmarkList.length }) =>
|
||||
new Response(JSON.stringify({ folder, bookmarkList }), { status: 200 });
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
mockCheckSsrf.mockReset();
|
||||
mockCheckSsrf.mockResolvedValue({ allowed: true });
|
||||
mockFollow.mockReset();
|
||||
});
|
||||
|
||||
describe('NaverListProvider.read', () => {
|
||||
const naver = () => new NaverListProvider();
|
||||
|
||||
it('refuses what the SSRF guard blocks and an unparseable URL', async () => {
|
||||
mockCheckSsrf.mockResolvedValueOnce({ allowed: false });
|
||||
expect(await naver().read(FOLDER_URL)).toEqual({ error: 'URL is not allowed', status: 400 });
|
||||
expect(await naver().read('not a url')).toEqual({ error: 'Invalid URL', status: 400 });
|
||||
});
|
||||
|
||||
it('follows a naver.me short link through the guard, and refuses a hop it blocks', async () => {
|
||||
mockFollow.mockResolvedValueOnce({ url: FOLDER_URL });
|
||||
vi.stubGlobal('fetch', vi.fn(async () => page([{ name: 'Cafe', py: '37.5', px: '127.0' }])));
|
||||
expect(await naver().read('https://naver.me/xyz')).toEqual({
|
||||
listName: 'Seoul',
|
||||
places: [{ name: 'Cafe', lat: 37.5, lng: 127, notes: null, address: null }],
|
||||
});
|
||||
|
||||
mockFollow.mockRejectedValueOnce(new SsrfBlocked('blocked'));
|
||||
expect(await naver().read('https://naver.me/xyz')).toEqual({ error: 'URL is not allowed', status: 400 });
|
||||
|
||||
mockFollow.mockRejectedValueOnce(new Error('network'));
|
||||
await expect(naver().read('https://naver.me/xyz')).rejects.toThrow('network');
|
||||
});
|
||||
|
||||
it('needs a folder id in the link', async () => {
|
||||
expect(await naver().read('https://map.naver.com/p/somewhere')).toEqual({
|
||||
error: 'Could not extract folder ID from URL. Please use a shared Naver Maps list link.',
|
||||
status: 400,
|
||||
});
|
||||
});
|
||||
|
||||
it('answers a failed, oversized or unreadable page with the provider message', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('nope', { status: 500 })));
|
||||
expect(await naver().read(FOLDER_URL)).toEqual({ error: 'Failed to fetch list from Naver Maps', status: 502 });
|
||||
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 200, headers: { 'content-length': String(MAX_LIST_RESPONSE_BYTES + 1) } })));
|
||||
expect(await naver().read(FOLDER_URL)).toEqual({ error: 'Failed to fetch list from Naver Maps', status: 502 });
|
||||
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('not json', { status: 200 })));
|
||||
expect(await naver().read(FOLDER_URL)).toEqual({ error: 'Invalid list data received from Naver Maps', status: 400 });
|
||||
});
|
||||
|
||||
it('pages through a folder bigger than one page and keeps what has coordinates', async () => {
|
||||
const first = Array.from({ length: 20 }, (_, i) => ({ name: `P${i}`, py: '37', px: '127', memo: i === 0 ? ' note ' : '', address: i === 0 ? ' Addr ' : '' }));
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(page(first, { name: 'Big', bookmarkCount: 22 }))
|
||||
.mockResolvedValueOnce(page([{ displayName: ' Second ', py: '36', px: '128' }, { name: 'No coords' }]));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const out = await naver().read(FOLDER_URL);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(String(fetchMock.mock.calls[1][0])).toContain('start=20');
|
||||
expect(out).toMatchObject({ listName: 'Big' });
|
||||
const places = (out as { places: unknown[] }).places;
|
||||
expect(places).toHaveLength(21);
|
||||
expect(places[0]).toEqual({ name: 'P0', lat: 37, lng: 127, notes: 'note', address: 'Addr' });
|
||||
expect(places[20]).toEqual({ name: 'Second', lat: 36, lng: 128, notes: null, address: null });
|
||||
});
|
||||
|
||||
it('stops paging on an empty page and fails on a failed one', async () => {
|
||||
const twenty = Array.from({ length: 20 }, (_, i) => ({ name: `P${i}`, py: '37', px: '127' }));
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(page(twenty, { bookmarkCount: 60 })).mockResolvedValueOnce(page([])));
|
||||
expect(((await naver().read(FOLDER_URL)) as { places: unknown[]; listName: string }).listName).toBe('Naver Maps List');
|
||||
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(page(twenty, { bookmarkCount: 60 })).mockResolvedValueOnce(new Response('', { status: 503 })));
|
||||
expect(await naver().read(FOLDER_URL)).toEqual({ error: 'Failed to fetch list from Naver Maps', status: 502 });
|
||||
});
|
||||
|
||||
it('refuses an empty folder and one without a single coordinate', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ folder: { name: 'Empty' } }), { status: 200 })));
|
||||
expect(await naver().read(FOLDER_URL)).toEqual({ error: 'List is empty or could not be read', status: 400 });
|
||||
|
||||
vi.stubGlobal('fetch', vi.fn(async () => page([{ name: 'Nowhere' }])));
|
||||
expect(await naver().read(FOLDER_URL)).toEqual({ error: 'No places with coordinates found in list', status: 400 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('GoogleDirectionsProvider.read', () => {
|
||||
const directions = () => new GoogleDirectionsProvider();
|
||||
const ROUTE = 'https://www.google.com/maps/dir/52.52,13.405/51.05,13.74/';
|
||||
|
||||
it('reads the stops of a route link, in driving order', async () => {
|
||||
expect(await directions().read(ROUTE)).toEqual([
|
||||
{ name: null, lat: 52.52, lng: 13.405 },
|
||||
{ name: null, lat: 51.05, lng: 13.74 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('refuses what the SSRF guard blocks and an unparseable URL', async () => {
|
||||
mockCheckSsrf.mockResolvedValueOnce({ allowed: false });
|
||||
expect(await directions().read(ROUTE)).toEqual({ error: 'URL is not allowed', status: 400 });
|
||||
expect(await directions().read('not a url')).toEqual({ error: 'Invalid URL', status: 400 });
|
||||
});
|
||||
|
||||
it('follows a short link through the guard and judges the host it lands on', async () => {
|
||||
mockFollow.mockResolvedValueOnce({ url: ROUTE });
|
||||
expect(await directions().read('https://maps.app.goo.gl/abc')).toHaveLength(2);
|
||||
|
||||
mockFollow.mockResolvedValueOnce({ url: 'https://evil.example.com/maps/dir/A/B/' });
|
||||
expect(await directions().read('https://maps.app.goo.gl/abc')).toEqual({ error: 'That link is not a Google Maps link.', status: 400 });
|
||||
|
||||
mockFollow.mockRejectedValueOnce(new SsrfBlocked('blocked'));
|
||||
expect(await directions().read('https://maps.app.goo.gl/abc')).toEqual({ error: 'URL is not allowed', status: 400 });
|
||||
|
||||
mockFollow.mockRejectedValueOnce(new Error('network'));
|
||||
await expect(directions().read('https://maps.app.goo.gl/abc')).rejects.toThrow('network');
|
||||
});
|
||||
|
||||
it('refuses a link with fewer than two stops', async () => {
|
||||
expect(await directions().read('https://www.google.com/maps/dir/Berlin/')).toEqual({
|
||||
error: 'Could not read any stops from that directions link. Open the route in Google Maps and use its Share button.',
|
||||
status: 400,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* PlaceImportService: the facade the importing domains call. Each read and
|
||||
* write reaches its provider, the KML/KMZ upload is dispatched by extension,
|
||||
* and a directions link's named stops are placed through the geocoder the
|
||||
* caller hands in, a failed or missing answer costing only that stop.
|
||||
*/
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
|
||||
const { mockCheckSsrf } = vi.hoisted(() => ({ mockCheckSsrf: vi.fn(async (_url: string) => ({ allowed: true })) }));
|
||||
vi.mock('../../../../src/utils/ssrfGuard', () => ({
|
||||
checkSsrf: mockCheckSsrf,
|
||||
safeFetchFollow: vi.fn(),
|
||||
SsrfBlockedError: class SsrfBlockedError extends Error {},
|
||||
}));
|
||||
|
||||
import { buildPlaceImportService } from '../../../helpers/place-import';
|
||||
import { gpxGeometryParser, gpxTextParser, createGpxParser, writeGpx } from '../../../../src/nest/place-import/gpx.codec';
|
||||
import { COLLECTION_FILE_FORMAT, COLLECTION_FILE_VERSION } from '@trek/shared';
|
||||
|
||||
const KMZ_FIXTURE = path.join(__dirname, '../../../fixtures/test.kmz');
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
mockCheckSsrf.mockReset();
|
||||
mockCheckSsrf.mockResolvedValue({ allowed: true });
|
||||
});
|
||||
|
||||
describe('PlaceImportService: directions', () => {
|
||||
const ROUTE = 'https://www.google.com/maps/dir/Berlin/52.52,13.405/Dresden/Prague/';
|
||||
|
||||
it('places named stops through the geocoder it is handed, coordinates as they stand', async () => {
|
||||
const geocode = vi.fn(async (q: string) => (q === 'Berlin' ? { lat: 52.5, lng: 13.4 } : q === 'Dresden' ? null : Promise.reject(new Error('down'))));
|
||||
const out = await buildPlaceImportService().readGoogleDirections(ROUTE, geocode);
|
||||
expect(geocode).toHaveBeenCalledTimes(3);
|
||||
expect(out).toEqual({
|
||||
places: [
|
||||
{ name: 'Berlin', lat: 52.5, lng: 13.4, notes: null, googleFtid: null },
|
||||
{ name: '52.52000, 13.40500', lat: 52.52, lng: 13.405, notes: null, googleFtid: null },
|
||||
],
|
||||
unplaceable: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a route of which fewer than two stops could be placed', async () => {
|
||||
const out = await buildPlaceImportService().readGoogleDirections('https://www.google.com/maps/dir/A/B/', async () => null);
|
||||
expect(out).toEqual({ error: 'None of the stops in that link could be placed on the map.', status: 400 });
|
||||
});
|
||||
|
||||
it('hands a provider refusal straight back without geocoding', async () => {
|
||||
mockCheckSsrf.mockResolvedValueOnce({ allowed: false });
|
||||
const geocode = vi.fn();
|
||||
expect(await buildPlaceImportService().readGoogleDirections(ROUTE, geocode)).toEqual({ error: 'URL is not allowed', status: 400 });
|
||||
expect(geocode).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlaceImportService: files and lists', () => {
|
||||
const svc = buildPlaceImportService();
|
||||
|
||||
it('dispatches a map upload by its extension, and refuses anything else', async () => {
|
||||
const kml = Buffer.from('<kml><Placemark><name>A</name><Point><coordinates>13.4,52.5</coordinates></Point></Placemark></kml>');
|
||||
expect((await svc.readMapFile(kml, 'trip.KML')).placemarks).toHaveLength(1);
|
||||
expect((await svc.readMapFile(fs.readFileSync(KMZ_FIXTURE), 'trip.kmz')).summary.totalPlacemarks).toBeGreaterThan(0);
|
||||
await expect(svc.readMapFile(kml, 'trip.txt')).rejects.toThrow('Unsupported map file format: .txt. Please upload a .kml or .kmz file.');
|
||||
});
|
||||
|
||||
it('reads a trip GPX and writes one back under a filename', () => {
|
||||
const gpx = Buffer.from('<gpx><wpt lat="1" lon="2"><name>Here</name></wpt></gpx>');
|
||||
expect(svc.readGpx(gpx)).toEqual([{ lat: 1, lng: 2, name: 'Here', description: null }]);
|
||||
const doc = svc.writeTripGpx({ tripTitle: 'T', places: [{ name: 'Here', description: null, address: null, lat: 1, lng: 2, route_geometry: null, category: null }], days: [] });
|
||||
expect(doc).toContain('<wpt lat="1" lon="2">');
|
||||
expect(svc.tripGpxFilename('My Trip')).toBe('My-Trip.gpx');
|
||||
});
|
||||
|
||||
it('writes a list as GPX and reads it back', () => {
|
||||
const exported = svc.writeCollectionGpx({
|
||||
format: COLLECTION_FILE_FORMAT,
|
||||
version: COLLECTION_FILE_VERSION,
|
||||
name: 'Coffee',
|
||||
exported_at: '2026-01-01T00:00:00.000Z',
|
||||
places: [{ name: 'Bar', lat: 1, lng: 2 }],
|
||||
} as never);
|
||||
expect(exported.waypoints).toBe(1);
|
||||
expect(svc.readCollectionGpx(exported.gpx, 'coffee.gpx').file.places[0]).toMatchObject({ name: 'Bar', lat: 1, lng: 2 });
|
||||
});
|
||||
|
||||
it('answers a blocked list link before fetching anything', async () => {
|
||||
mockCheckSsrf.mockResolvedValue({ allowed: false });
|
||||
expect(await svc.readGoogleList('https://www.google.com/maps/placelists/list/x')).toEqual({ error: 'URL is not allowed', status: 400 });
|
||||
expect(await svc.readNaverList('https://map.naver.com/p/favorite/myPlace/folder/x')).toEqual({ error: 'URL is not allowed', status: 400 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('gpx.codec', () => {
|
||||
it('reads the same document two ways: geometry parses values, text keeps them', () => {
|
||||
const xml = '<gpx><wpt lat="1" lon="2"><name>007</name><link href="a"/><link href="b"/></wpt></gpx>';
|
||||
const geometry = gpxGeometryParser.parse(xml).gpx.wpt[0];
|
||||
const text = gpxTextParser.parse(xml).gpx.wpt[0];
|
||||
expect(geometry.name).toBe(7);
|
||||
expect(text.name).toBe('007');
|
||||
// `link` repeats only for the list reader.
|
||||
expect(Array.isArray(text.link)).toBe(true);
|
||||
expect(Array.isArray(createGpxParser('geometry').parse('<gpx><wpt><link href="a"/></wpt></gpx>').gpx.wpt[0].link)).toBe(false);
|
||||
});
|
||||
|
||||
it('writes one envelope: namespaces after the default one, empty element lists left out', () => {
|
||||
const doc = writeGpx({ namespaces: { trek: 'https://trek.example/gpx' }, metadata: { name: 'X' }, wpt: [], trk: [{ name: 'T' }] });
|
||||
expect(doc).toContain('xmlns="http://www.topografix.com/GPX/1/1" xmlns:trek="https://trek.example/gpx" xmlns:xsi=');
|
||||
expect(doc).not.toContain('<wpt');
|
||||
expect(doc).toContain('<trk>');
|
||||
});
|
||||
});
|
||||
@@ -34,6 +34,7 @@ import { accommodationsOver } from '../../helpers/accommodations-service';
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
import { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import type { MapsService } from '../../../src/nest/maps/maps.service';
|
||||
import type { OsmClient } from '../../../src/nest/maps/providers/osm.client';
|
||||
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
|
||||
@@ -63,24 +64,25 @@ const hit = (name: string, lat: number, lng: number) => ({
|
||||
});
|
||||
|
||||
async function svc(searchNominatim: OsmClient['searchNominatim']): Promise<PlacesService> {
|
||||
// The address backfill runs fire-and-forget after every import, so the stub answers
|
||||
// it too — otherwise every passing test prints a rejected promise.
|
||||
// geocodeQuery is what the importer calls now: it asks the TREK index first
|
||||
// and falls through to Nominatim on the background lane. Stubbed in terms of
|
||||
// the searchNominatim each case already provides, so the cases keep driving
|
||||
// one seam while the code under test uses the real one.
|
||||
const maps = {
|
||||
searchNominatim,
|
||||
geocodeQuery: async (query: string) => {
|
||||
const hit = (await searchNominatim(query, undefined, 'background'))
|
||||
.find((h: { lat: number | null; lng: number | null }) => h.lat !== null && h.lng !== null);
|
||||
return hit ? { lat: hit.lat as number, lng: hit.lng as number } : null;
|
||||
},
|
||||
reverseGeocode: vi.fn(async () => null),
|
||||
} as unknown as MapsService;
|
||||
return new PlacesService(
|
||||
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
|
||||
new RealtimeService(),
|
||||
// The address backfill runs fire-and-forget after every import, so the stub answers
|
||||
// it too — otherwise every passing test prints a rejected promise.
|
||||
// geocodeQuery is what the importer calls now: it asks the TREK index first
|
||||
// and falls through to Nominatim on the background lane. Stubbed in terms of
|
||||
// the searchNominatim each case already provides, so the cases keep driving
|
||||
// one seam while the code under test uses the real one.
|
||||
{
|
||||
searchNominatim,
|
||||
geocodeQuery: async (query: string) => {
|
||||
const hit = (await searchNominatim(query, undefined, 'background'))
|
||||
.find((h: { lat: number | null; lng: number | null }) => h.lat !== null && h.lng !== null);
|
||||
return hit ? { lat: hit.lat as number, lng: hit.lng as number } : null;
|
||||
},
|
||||
reverseGeocode: vi.fn(async () => null),
|
||||
} as unknown as MapsService,
|
||||
maps,
|
||||
new QueryHelpersService(await createTestTagsRepo(testDb), await createTestPlaceRatingsRepo(testDb), await createTestAssignmentParticipantsRepo(testDb)),
|
||||
new UnsplashService(await createTestAppSettingsRepo(testDb), await createTestUsersRepo(testDb), new RuntimeEnvService(), storageFx.storage),
|
||||
photoCacheStub,
|
||||
@@ -102,6 +104,7 @@ async function svc(searchNominatim: OsmClient['searchNominatim']): Promise<Place
|
||||
await createTestTripsRepo(testDb),
|
||||
await createTestBudgetItemsRepo(testDb),
|
||||
await createTestCollectionPlacesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
/**
|
||||
* Unit tests for the pure places helpers (moved from
|
||||
* tests/unit/services/kmzUnpack.test.ts when placeService went DI-native — the
|
||||
* KMZ unpacker touches no DB, so it lives in places.helpers.ts).
|
||||
* Unit tests for the pure places helpers: the import dedup predicates and the
|
||||
* enrichment plumbing. The KMZ unpacker and the Google list id parsing moved
|
||||
* with their code to place-import/ (kml.codec.test.ts, google-list.provider.test.ts).
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
vi.mock('../../../src/db/database', () => ({
|
||||
db: { prepare: vi.fn() },
|
||||
@@ -19,64 +17,14 @@ vi.mock('../../../src/config', () => ({
|
||||
|
||||
import {
|
||||
COORD_DEDUP_TOLERANCE,
|
||||
googleMapsFeatureIdFromItem,
|
||||
googleMapsHexId,
|
||||
externalIdsOf,
|
||||
isPlaceDuplicate,
|
||||
KMZ_DECOMPRESSED_SIZE_LIMIT,
|
||||
mapWithConcurrency,
|
||||
trackInsertedInDedupSet,
|
||||
trimOrNull,
|
||||
unpackKmzToKml,
|
||||
type DedupSet,
|
||||
} from '../../../src/nest/places/places.helpers';
|
||||
|
||||
const KMZ_FIXTURE = path.join(__dirname, '../../fixtures/test.kmz');
|
||||
|
||||
describe('unpackKmzToKml', () => {
|
||||
it('extracts the KML entry from a valid KMZ', async () => {
|
||||
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
|
||||
const kmlBuffer = await unpackKmzToKml(kmzBuffer);
|
||||
expect(kmlBuffer.length).toBeGreaterThan(0);
|
||||
expect(kmlBuffer.toString('utf-8')).toContain('<kml');
|
||||
});
|
||||
|
||||
it('rejects a KMZ whose KML entry exceeds the decompressed size limit', async () => {
|
||||
const kmzBuffer = fs.readFileSync(KMZ_FIXTURE);
|
||||
// test.kmz contains a KML with uncompressedSize 634 — set limit to 1 byte
|
||||
await expect(unpackKmzToKml(kmzBuffer, 1)).rejects.toThrow('exceeds the maximum allowed decompressed size');
|
||||
});
|
||||
|
||||
it('rejects a KMZ that contains no KML file', async () => {
|
||||
// Craft a minimal ZIP containing only a non-KML entry using raw ZIP bytes
|
||||
// We use the test GPX fixture (a real file) re-zipped via Node's zlib/archiver
|
||||
// Simplest: a KMZ whose only file has a .txt extension
|
||||
const Archiver = await import('archiver');
|
||||
const archiver = Archiver.default;
|
||||
const { PassThrough } = await import('stream');
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const output = new PassThrough();
|
||||
output.on('data', (chunk) => chunks.push(chunk));
|
||||
|
||||
const archive = archiver('zip', { zlib: { level: 1 } });
|
||||
archive.pipe(output);
|
||||
archive.append(Buffer.from('not a kml'), { name: 'data.txt' });
|
||||
await archive.finalize();
|
||||
|
||||
const zipBuffer = Buffer.concat(chunks);
|
||||
await expect(unpackKmzToKml(zipBuffer)).rejects.toThrow('does not contain a KML file');
|
||||
});
|
||||
|
||||
it('rejects a buffer that is not a valid ZIP archive', async () => {
|
||||
await expect(unpackKmzToKml(Buffer.from('this is not a zip'))).rejects.toThrow('Invalid KMZ archive');
|
||||
});
|
||||
|
||||
it('exports KMZ_DECOMPRESSED_SIZE_LIMIT as 50 MB', () => {
|
||||
expect(KMZ_DECOMPRESSED_SIZE_LIMIT).toBe(50 * 1024 * 1024);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Import dedup predicates ───────────────────────────────────────────────────
|
||||
|
||||
const emptyDedup = (): DedupSet => ({ names: new Set(), coords: [], externalIds: new Set() });
|
||||
@@ -149,32 +97,6 @@ describe('isPlaceDuplicate / trackInsertedInDedupSet', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ── Google Maps feature ids ───────────────────────────────────────────────────
|
||||
|
||||
describe('googleMapsHexId / googleMapsFeatureIdFromItem', () => {
|
||||
it('passes an already-hex id through lower-cased', () => {
|
||||
expect(googleMapsHexId('0x882BF179E806D471')).toBe('0x882bf179e806d471');
|
||||
});
|
||||
|
||||
it("converts Google's signed 64-bit decimals to unsigned hex", () => {
|
||||
expect(googleMapsHexId('-8634542354666695567')).toBe('0x882bf179e806d471');
|
||||
expect(googleMapsHexId(255)).toBe('0xff');
|
||||
});
|
||||
|
||||
it('rejects anything that is not a hex or decimal id', () => {
|
||||
expect(googleMapsHexId('not-an-id')).toBeNull();
|
||||
expect(googleMapsHexId(null)).toBeNull();
|
||||
expect(googleMapsHexId({})).toBeNull();
|
||||
});
|
||||
|
||||
it('reads the ftid pair from either item slot, else null', () => {
|
||||
expect(googleMapsFeatureIdFromItem([null, [0, 0, 0, 0, 0, 0, ['0x1', '0x2']]])).toBe('0x1:0x2');
|
||||
expect(googleMapsFeatureIdFromItem([null, null, null, null, null, null, null, [null, ['0x3', '0x4']]])).toBe('0x3:0x4');
|
||||
expect(googleMapsFeatureIdFromItem([null, [0, 0, 0, 0, 0, 0, ['0x1']]])).toBeNull();
|
||||
expect(googleMapsFeatureIdFromItem('not an array')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Enrichment plumbing ───────────────────────────────────────────────────────
|
||||
|
||||
describe('mapWithConcurrency / trimOrNull', () => {
|
||||
|
||||
@@ -62,6 +62,7 @@ import fs from 'fs';
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
import { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { legacyBoundIntegerText } from '../../../src/nest/common/row-id';
|
||||
import { MapsService } from '../../../src/nest/maps/maps.service';
|
||||
import { buildMapsService } from '../../helpers/maps-service';
|
||||
@@ -163,6 +164,7 @@ async function makePlacesService(
|
||||
await createTestTripsRepo(testDb),
|
||||
await createTestBudgetItemsRepo(testDb),
|
||||
await createTestCollectionPlacesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
buildCategoryNameLookup,
|
||||
decodeUtf8WithWarning,
|
||||
extractKmlPlacemarkNodes,
|
||||
parseKmlPointCoordinates,
|
||||
parsePlacemarkNode,
|
||||
resolveCategoryIdForFolder,
|
||||
sanitizeKmlDescription,
|
||||
} from '../../../../src/nest/places/kml-import.helpers';
|
||||
|
||||
describe('kmlImportUtils', () => {
|
||||
it('sanitizes HTML descriptions with br to newline', () => {
|
||||
const input = 'Line 1<br>Line <b>2</b> & more';
|
||||
const output = sanitizeKmlDescription(input);
|
||||
expect(output).toBe('Line 1\nLine 2 & more');
|
||||
});
|
||||
|
||||
it('unwraps CDATA sections before stripping tags', () => {
|
||||
const input = '<![CDATA[Great spot<br>for photos <b>and</b> skyline.]]>';
|
||||
expect(sanitizeKmlDescription(input)).toBe('Great spot\nfor photos and skyline.');
|
||||
});
|
||||
|
||||
it('parses KML coordinate order lng,lat,alt', () => {
|
||||
const parsed = parseKmlPointCoordinates('13.4050,52.5200,15');
|
||||
expect(parsed).toEqual({ lat: 52.52, lng: 13.405 });
|
||||
});
|
||||
|
||||
it('extracts placemarks from nested folders', () => {
|
||||
const root = {
|
||||
Document: {
|
||||
Folder: {
|
||||
name: 'Parent',
|
||||
Folder: {
|
||||
name: 'Child',
|
||||
Placemark: { name: 'Nested', Point: { coordinates: '13.4,52.5,0' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const nodes = extractKmlPlacemarkNodes(root);
|
||||
expect(nodes).toHaveLength(1);
|
||||
expect(nodes[0].folderName).toBe('Child');
|
||||
|
||||
const parsed = parsePlacemarkNode(nodes[0]);
|
||||
expect(parsed.name).toBe('Nested');
|
||||
expect(parsed.lat).toBe(52.5);
|
||||
expect(parsed.lng).toBe(13.4);
|
||||
});
|
||||
|
||||
it('builds exact case-insensitive category lookup', () => {
|
||||
const lookup = buildCategoryNameLookup([
|
||||
{ id: 3, name: 'Museums' },
|
||||
{ id: 4, name: 'Parks' },
|
||||
]);
|
||||
|
||||
expect(resolveCategoryIdForFolder('museums', lookup)).toBe(3);
|
||||
expect(resolveCategoryIdForFolder('Museum', lookup)).toBeNull();
|
||||
expect(resolveCategoryIdForFolder('parks', lookup)).toBe(4);
|
||||
});
|
||||
|
||||
it('decodes non-BMP decimal HTML entities (emoji)', () => {
|
||||
// 😀 = U+1F600 = 😀 — requires String.fromCodePoint, not fromCharCode
|
||||
expect(sanitizeKmlDescription('😀')).toBe('😀');
|
||||
});
|
||||
|
||||
it('decodes non-BMP hex HTML entities (emoji)', () => {
|
||||
// 😀 = U+1F600 = 😀
|
||||
expect(sanitizeKmlDescription('😀')).toBe('😀');
|
||||
});
|
||||
|
||||
it('does not produce [object Object] when description is a parsed object with #text', () => {
|
||||
// fast-xml-parser can return an object for mixed-content nodes when stopNodes
|
||||
// is not configured; the fallback in asTrimmedString must extract #text.
|
||||
const result = sanitizeKmlDescription({ '#text': 'Hello <b>world</b>' } as any);
|
||||
expect(result).not.toBe('[object Object]');
|
||||
expect(result).toBe('Hello world');
|
||||
});
|
||||
|
||||
it('returns null when description object has no #text', () => {
|
||||
expect(sanitizeKmlDescription({ i: 'bold' } as any)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns warning for non-UTF8 payload', () => {
|
||||
const buffer = Buffer.concat([
|
||||
Buffer.from('<?xml version="1.0"?><kml><Document><Placemark><name>Caf'),
|
||||
Buffer.from([0xe9]),
|
||||
Buffer.from('</name></Placemark></Document></kml>'),
|
||||
]);
|
||||
|
||||
const decoded = decodeUtf8WithWarning(buffer);
|
||||
expect(decoded.warning).toContain('not valid UTF-8');
|
||||
expect(decoded.text).toContain('<kml>');
|
||||
});
|
||||
});
|
||||
@@ -29,12 +29,13 @@ import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.serv
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
import { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { buildMapsService } from '../../helpers/maps-service';
|
||||
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
|
||||
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
|
||||
import { TrekPhotoRegistrationService } from '../../../src/nest/photos/trek-photo-registration.service';
|
||||
import { ToursService } from '../../../src/nest/tours/tours.service';
|
||||
import { gpxParser } from '../../../src/nest/places/places.helpers';
|
||||
import { gpxGeometryParser } from '../../../src/nest/place-import/gpx.codec';
|
||||
import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';
|
||||
import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
@@ -101,6 +102,7 @@ async function makePlacesService(): Promise<PlacesService> {
|
||||
await createTestTripsRepo(testDb),
|
||||
await createTestBudgetItemsRepo(testDb),
|
||||
await createTestCollectionPlacesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -128,6 +130,7 @@ beforeAll(async () => {
|
||||
places = await makePlacesService();
|
||||
tours = new ToursService(
|
||||
uow, places, await createTestToursRepo(testDb), await createTestTourTypesRepo(testDb), await createTestTourWaypointsRepo(testDb), await createTestPlacesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -221,7 +224,7 @@ describe('Tours GPX atomic persistence and postcommit publication', () => {
|
||||
|
||||
it('propagates parser failures before entering the transaction', async () => {
|
||||
const transactional = vi.spyOn(uow, 'transactional');
|
||||
vi.spyOn(gpxParser, 'parse').mockImplementationOnce(() => { throw new Error('parser failure'); });
|
||||
vi.spyOn(gpxGeometryParser, 'parse').mockImplementationOnce(() => { throw new Error('parser failure'); });
|
||||
await expect(tours.importGpxAsTour(tripId, mixedGpx)).rejects.toThrow('parser failure');
|
||||
expect(transactional).not.toHaveBeenCalled();
|
||||
await expectEmpty();
|
||||
|
||||
@@ -40,6 +40,7 @@ vi.mock('../../../src/nest/auth-core/jwt-verify', () => ({ extractToken: vi.fn()
|
||||
import { PlacesController } from '../../../src/nest/places/places.controller';
|
||||
import { DayAssignmentsController } from '../../../src/nest/assignments/assignments.controller';
|
||||
import { ToursService } from '../../../src/nest/tours/tours.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
|
||||
import { TripAccessGuard, TRIP_PERMISSION_KEY } from '../../../src/nest/permissions/trip-access.guard';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
@@ -230,6 +231,7 @@ function tourRepositoryFixture(ownerTripId: number) {
|
||||
{ isEnabled: vi.fn(async () => true) } as unknown as TourTypesRepository,
|
||||
waypointsRepo as unknown as TourWaypointsRepository,
|
||||
placesRepo as unknown as PlacesRepository,
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
return { uow, toursRepo, waypointsRepo, placesRepo, places, service };
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ vi.mock('../../../src/db/database', () => ({
|
||||
vi.mock('../../../src/nest/places/places.service', () => ({ PlacesService: class {} }));
|
||||
|
||||
import { ToursService } from '../../../src/nest/tours/tours.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { tourCreateRequestSchema, type TourCreateRequest } from '@trek/shared';
|
||||
import type { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import type { PlacesService } from '../../../src/nest/places/places.service';
|
||||
@@ -92,6 +93,7 @@ function makeService() {
|
||||
{ isEnabled: vi.fn(async () => true) } as unknown as TourTypesRepository,
|
||||
waypointsRepo as unknown as TourWaypointsRepository,
|
||||
placesRepo as unknown as PlacesRepository,
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
return { uow, toursRepo, waypointsRepo, placesRepo, places, place, service };
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ vi.mock('../../../src/config', () => ({
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { tourCreateRequestSchema, type TourCreateRequest } from '@trek/shared';
|
||||
import { ToursService } from '../../../src/nest/tours/tours.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import type { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createPlace, createTrip, createUser } from '../../helpers/factories';
|
||||
@@ -72,6 +73,7 @@ beforeAll(async () => {
|
||||
await createTestTourTypesRepo(testDb),
|
||||
await createTestTourWaypointsRepo(testDb),
|
||||
await createTestPlacesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.se
|
||||
import { CollabService } from '../../../src/nest/collab/collab.service';
|
||||
import { RateLimitService } from '../../../src/nest/common/rate-limit.service';
|
||||
import { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service';
|
||||
import { TripMembersService } from '../../../src/nest/trip-members/trip-members.service';
|
||||
import { TripReadModelService } from '../../../src/nest/trip-read-model/trip-read-model.service';
|
||||
@@ -173,6 +174,7 @@ beforeAll(async () => {
|
||||
await createTestTripsRepo(testDb),
|
||||
await createTestBudgetItemsRepo(testDb),
|
||||
await createTestCollectionPlacesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
membersSvc = new TripMembersService(budgetSvc, new UserCleanupService(new MaintenanceRepository((await sharedTestOrm(testDb)).em), budgetSvc, await createTestUnitOfWork(testDb), await createTestUsersRepo(testDb), await createTestTripMembersRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestBudgetSettlementsRepo(testDb), await createTestJourneyShareTokensRepo(testDb), await createTestJourneysRepo(testDb), await createTestJourneyEntriesRepo(testDb), await createTestJourneyContributorsRepo(testDb), await createTestShareTokensRepo(testDb), await createTestPluginsRepo(testDb), await createTestPluginUserErasureQueueRepo(testDb)), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService(), notificationsStub(), await createTestUnitOfWork(testDb), await createTestTripsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb));
|
||||
});
|
||||
|
||||
@@ -59,6 +59,7 @@ import { RateLimitService } from '../../../src/nest/common/rate-limit.service';
|
||||
import { VacayService } from '../../../src/nest/vacay/vacay.service';
|
||||
import { TripsService } from '../../../src/nest/trips/trips.service';
|
||||
import { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service';
|
||||
import { TripMembersService } from '../../../src/nest/trip-members/trip-members.service';
|
||||
import { TripReadModelService } from '../../../src/nest/trip-read-model/trip-read-model.service';
|
||||
@@ -280,6 +281,7 @@ beforeAll(async () => {
|
||||
await createTestTripsRepo(testDb),
|
||||
await createTestBudgetItemsRepo(testDb),
|
||||
await createTestCollectionPlacesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
svc = new TripsService(
|
||||
new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb)), accommodationsSvc, await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb)),
|
||||
|
||||
@@ -31,6 +31,7 @@ import { accommodationsOver } from '../../helpers/accommodations-service';
|
||||
import { isUpdateConflict } from '../../../src/nest/common/conflictResult';
|
||||
import { PackingService } from '../../../src/nest/packing/packing.service';
|
||||
import { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { buildMapsService } from '../../helpers/maps-service';
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
@@ -138,6 +139,7 @@ beforeAll(async () => {
|
||||
await createTestTripsRepo(testDb),
|
||||
await createTestBudgetItemsRepo(testDb),
|
||||
await createTestCollectionPlacesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user