Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : sdk/web/tests/unit/core.test.ts9 * Module : sdk10 * Repository : https://git.spboucher.ai/ka-maps-engine11 * Created : 2026-12-0112 * Last Modified : 2026-12-0113 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { describe, expect, it, vi } from 'vitest';43import { Emitter } from '../../src/events.js';44import { createGeo } from '../../src/geo.js';45import { resolveStrings, STRINGS_EN, STRINGS_FR } from '../../src/i18n.js';46import { cdnAssetsUrl, resolveAssetsUrl, setAssetsUrl } from '../../src/loader.js';47import { describeHeightSource, KaMapError } from '../../src/types.js';48import { VERSION } from '../../src/version.js';4950describe('Emitter', () => {51 it('livre le type et la charge utile, dans l’ordre d’abonnement', () => {52 const e = new Emitter<{ a: { n: number }; b: {} }>();53 const seen: string[] = [];54 e.on('a', (ev) => seen.push(`1:${ev.type}:${ev.n}`));55 e.on('a', (ev) => seen.push(`2:${ev.n}`));56 e.emit('a', { n: 7 });57 expect(seen).toEqual(['1:a:7', '2:7']);58 expect(e.has('a')).toBe(true);59 expect(e.has('b')).toBe(false);60 });6162 it('once ne livre qu’une fois ; off et la fonction rendue désabonnent', () => {63 const e = new Emitter<{ a: { n: number } }>();64 const once = vi.fn();65 const always = vi.fn();66 e.once('a', once);67 const off = e.on('a', always);68 e.emit('a', { n: 1 });69 e.emit('a', { n: 2 });70 off();71 e.emit('a', { n: 3 });72 expect(once).toHaveBeenCalledTimes(1);73 expect(always).toHaveBeenCalledTimes(2);74 });7576 it('un écouteur fautif n’empêche pas les suivants', async () => {77 const e = new Emitter<{ a: {} }>();78 const after = vi.fn();79 const caught: unknown[] = [];80 const onErr = (err: unknown) => caught.push(err);81 process.on('uncaughtException', onErr);82 e.on('a', () => {83 throw new Error('application');84 });85 e.on('a', after);86 e.emit('a', {});87 expect(after).toHaveBeenCalledTimes(1);88 await new Promise((r) => setTimeout(r, 5));89 process.off('uncaughtException', onErr);90 expect(String(caught[0])).toContain('application');91 });9293 it('un écouteur qui se désabonne pendant l’émission ne perturbe pas les autres', () => {94 const e = new Emitter<{ a: {} }>();95 const calls: number[] = [];96 const off1 = e.on('a', () => {97 calls.push(1);98 off1();99 });100 e.on('a', () => calls.push(2));101 e.emit('a', {});102 e.emit('a', {});103 expect(calls).toEqual([1, 2, 2]);104 });105});106107describe('textes', () => {108 it('français par défaut, surcharge partielle', () => {109 expect(resolveStrings()).toBe(STRINGS_FR);110 const s = resolveStrings({ mapLabel: 'Carte des logements' });111 expect(s.mapLabel).toBe('Carte des logements');112 expect(s.zoomIn).toBe('Zoomer');113 });114 it('le jeu anglais couvre exactement les mêmes clés', () => {115 expect(Object.keys(STRINGS_EN).sort()).toEqual(Object.keys(STRINGS_FR).sort());116 for (const v of Object.values(STRINGS_EN)) expect(v.length).toBeGreaterThan(0);117 });118});119120describe('adresse des actifs', () => {121 it('défaut versionné, barre oblique finale garantie, CDN', () => {122 expect(resolveAssetsUrl()).toBe(`/ka-maps/${VERSION}/`);123 expect(resolveAssetsUrl('/static/cartes')).toBe('/static/cartes/');124 expect(resolveAssetsUrl('https://exemple.test/x/')).toBe('https://exemple.test/x/');125 expect(cdnAssetsUrl()).toBe(`https://maps.spboucher.ai/sdk/${VERSION}/`);126 setAssetsUrl('/a');127 expect(resolveAssetsUrl()).toBe('/a/');128 expect(resolveAssetsUrl('/b/')).toBe('/b/');129 });130});131132describe('geo', () => {133 const ok = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });134135 it('search : paramètres, bornes de limit, point de proximité', async () => {136 const calls: string[] = [];137 vi.stubGlobal('fetch', async (url: string) => {138 calls.push(url);139 return ok({ results: [{ id: 'address:1', type: 'address', label: 'x', lon: -73.5, lat: 45.5 }], attribution: 'a' });140 });141 const g = createGeo('https://geo.exemple.test/');142 const r = await g.search(' 1000 rue Sherbrooke ', { near: [-73.56, 45.5], limit: 99, types: ['address', 'street'] });143 expect(r.results).toHaveLength(1);144 const u = new URL(calls[0]);145 expect(u.origin + u.pathname).toBe('https://geo.exemple.test/v1/search');146 expect(u.searchParams.get('q')).toBe('1000 rue Sherbrooke');147 expect(u.searchParams.get('near')).toBe('-73.56,45.5');148 expect(u.searchParams.get('limit')).toBe('25');149 expect(u.searchParams.get('types')).toBe('address,street');150 vi.unstubAllGlobals();151 });152153 it('search : requête vide → aucun appel', async () => {154 const f = vi.fn();155 vi.stubGlobal('fetch', f);156 expect(await createGeo().search(' ')).toEqual({ results: [], attribution: '' });157 expect(f).not.toHaveBeenCalled();158 vi.unstubAllGlobals();159 });160161 it('reverse : lon et lat ; erreurs HTTP et réseau en KaMapError', async () => {162 const calls: string[] = [];163 vi.stubGlobal('fetch', async (url: string) => {164 calls.push(url);165 return ok({ address: null, attribution: 'a' });166 });167 await createGeo().reverse([-73.5674, 45.5019]);168 expect(calls[0]).toBe('https://geo.spboucher.ai/v1/reverse?lon=-73.5674&lat=45.5019');169 // Routes complémentaires du service.170 const g = createGeo('https://geo.exemple.test');171 await g.boundariesAt([-73.5, 45.5]);172 await g.boundary('mrc/66', { zoom: 9 });173 await g.nearby([-73.5, 45.5], { kinds: ['park', 'school'], radius: 500, limit: 3 });174 await g.elevation([-73.5, 45.5]);175 await g.get('/v1/isochrone', { from: '-73.5,45.5', minutes: 10, profile: undefined });176 expect(calls.slice(1)).toEqual([177 'https://geo.exemple.test/v1/boundaries?lon=-73.5&lat=45.5',178 'https://geo.exemple.test/v1/boundaries/mrc/66?zoom=9',179 'https://geo.exemple.test/v1/nearby?lon=-73.5&lat=45.5&kinds=park%2Cschool&radius=500&limit=3',180 'https://geo.exemple.test/v1/elevation?lon=-73.5&lat=45.5',181 'https://geo.exemple.test/v1/isochrone?from=-73.5%2C45.5&minutes=10',182 ]);183 vi.stubGlobal('fetch', async () => new Response(JSON.stringify({ error: 'near : position hors de la zone couverte' }), { status: 400 }));184 await expect(createGeo().search('x')).rejects.toMatchObject({ name: 'KaMapError', code: 'network', message: expect.stringContaining('hors de la zone') });185 vi.stubGlobal('fetch', async () => {186 throw new TypeError('réseau coupé');187 });188 await expect(createGeo().reverse([0, 0])).rejects.toBeInstanceOf(KaMapError);189 vi.unstubAllGlobals();190 });191});192193describe('provenance des hauteurs', () => {194 it('ne dit « mesurée » que pour hs = 1 ; la mesure du bloc reste distincte', () => {195 expect(describeHeightSource({ hs: 1, heightSource: 'mesuree', heightYear: 2018 })).toBe('hauteur mesurée, levé 2018');196 expect(describeHeightSource({ hs: 4, heightSource: 'bloc', heightYear: 2018 })).toBe('hauteur du bloc, levé 2018');197 expect(describeHeightSource({ hs: 2 })).toBe('hauteur déduite du nombre d’étages');198 expect(describeHeightSource({ hs: 3, heightSource: 'estimee' })).toBe('hauteur estimée');199 for (const f of [{ hs: 0 }, { hs: 9 }, {}]) expect(describeHeightSource(f)).toBe('hauteur de provenance inconnue');200 for (const hs of [2, 3, 4, 0]) expect(describeHeightSource({ hs })).not.toContain('mesurée');201 });202});203