fuzzyworld

tower / interior-flight / files / test / world.test.ts

Branch interior-flight · default branch · all branches

world.test.ts

Blame: the commit that last changed each line · file · history

e5555695 2026-09-07 Pavel Safronov1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import {
3 type Place, PLACE_KINDS, isAreaKind, isAutoId, isLineKind, isTracedKind,
4 makeId, parseWorld, toPublicWorld,
5} from '../src/world/schema.js'
6import { readFileSync } from 'node:fs'
7import { WorldStore, backupFilename } from '../src/world/store.js'
8
9const place = (over: Partial<Place> = {}): Place => ({
10 id: 'p', name: 'P', kind: 'city',
11 geometry: { type: 'point', theta: 1, z: 2 },
12 blurb: '', notes: '', public: true, ...over,
13})
14
15describe('ids', () => {
16 it('slugifies and de-duplicates', () => {
17 expect(makeId('Hallow Crossing', new Set())).toBe('hallow-crossing')
18 expect(makeId('Hallow Crossing', new Set(['hallow-crossing']))).toBe('hallow-crossing-2')
19 expect(makeId('!!!', new Set())).toBe('place')
20 })
21})
22
23describe('isAutoId decides whether an id should follow a rename', () => {
24 it('recognises a plain slug of the name', () => {
25 expect(isAutoId('new-city', 'New city')).toBe(true)
26 expect(isAutoId('hallow-crossing', 'Hallow Crossing')).toBe(true)
27 })
28 it('recognises a de-duplicated slug', () => {
29 expect(isAutoId('new-city-2', 'New city')).toBe(true)
30 expect(isAutoId('new-city-17', 'New city')).toBe(true)
31 })
32 it('leaves a hand-pinned id alone', () => {
33 expect(isAutoId('rimfall-permanent', 'Rimfall')).toBe(false)
34 expect(isAutoId('new-city-x', 'New city')).toBe(false)
35 expect(isAutoId('anything', 'New city')).toBe(false)
36 })
37})
38
39describe('parseWorld tolerates hand-edited and older files', () => {
40 it('survives junk without throwing', () => {
41 for (const junk of [null, 42, {}, { places: 'no' }, { places: [null, 7] }]) {
42 expect(parseWorld(junk).places).toEqual([])
43 }
44 })
45 it('drops entries with unusable geometry', () => {
46 expect(parseWorld({ places: [
47 { name: 'ok', geometry: { type: 'point', theta: 1, z: 2 } },
48 { name: 'nan', geometry: { type: 'point', theta: NaN, z: 2 } },
49 { name: 'short', geometry: { type: 'polygon', points: [[0, 0], [1, 1]] } },
50 ] }).places.map((p) => p.name)).toEqual(['ok'])
51 })
52 it('defaults a missing public flag to true but honours an explicit false', () => {
53 const w = parseWorld({ places: [
54 { name: 'a', geometry: { type: 'point', theta: 0, z: 0 } },
55 { name: 'b', public: false, geometry: { type: 'point', theta: 0, z: 0 } },
56 ] })
57 expect(w.places.map((p) => p.public)).toEqual([true, false])
58 })
59 it('never lets two places share an id', () => {
60 const w = parseWorld({ places: [
61 { id: 'x', name: 'a', geometry: { type: 'point', theta: 0, z: 0 } },
62 { id: 'x', name: 'b', geometry: { type: 'point', theta: 0, z: 0 } },
63 ] })
64 expect(new Set(w.places.map((p) => p.id)).size).toBe(2)
65 })
66})
67
68describe('geometry kinds', () => {
69 it('classifies areas, lines and markers', () => {
70 expect(isAreaKind('lake')).toBe(true)
71 expect(isLineKind('river')).toBe(true)
72 expect(isLineKind('lake')).toBe(false)
73 expect(isTracedKind('canyon')).toBe(true)
74 expect(isTracedKind('city')).toBe(false)
75 })
76 it('accepts a polyline of two points but a polygon needs three', () => {
77 const two = [[0, 0], [1, 1]]
78 expect(parseWorld({ places: [
79 { name: 'line', geometry: { type: 'polyline', points: two } },
80 { name: 'poly', geometry: { type: 'polygon', points: two } },
81 ] }).places.map((p) => p.name)).toEqual(['line'])
82 })
04d6779e 2026-09-07 Pavel Safronov83 it('keeps a band as a band, which a polygon cannot express', () => {
84 // theta 0 and theta 2pi normalise to the same map row, so four corners
85 // collapse to a hairline. Tower's desert and forest both ring the world.
86 const w = parseWorld({ places: [
87 { id: 'd', name: 'D', kind: 'desert',
88 geometry: { type: 'band', zFrom: 148000, zTo: 218000 } }] })
89 expect(w.places[0]!.geometry).toEqual({ type: 'band', zFrom: 148000, zTo: 218000 })
90 expect(toPublicWorld(w).places[0]!.geometry).toEqual(
91 { type: 'band', zFrom: 148000, zTo: 218000 })
92 })
93
94 it('rejects a band with unusable bounds', () => {
95 expect(parseWorld({ places: [
96 { name: 'x', geometry: { type: 'band', zFrom: NaN, zTo: 1 } }] }).places).toEqual([])
97 })
98
e5555695 2026-09-07 Pavel Safronov99 it('round-trips a polyline through the public export', () => {
100 const pts: [number, number][] = [[0.1, 1000], [0.2, 2000], [0.3, 3000]]
101 const w = parseWorld({ places: [
102 { id: 'r', name: 'R', kind: 'river', geometry: { type: 'polyline', points: pts } }] })
103 expect(w.places[0]!.geometry).toEqual({ type: 'polyline', points: pts })
104 expect(toPublicWorld(w).places[0]!.geometry).toEqual({ type: 'polyline', points: pts })
105 })
106})
107
108describe('the seeded world loads without losing anything', () => {
62458672 2026-09-07 Pavel Safronov109 const seed = JSON.parse(readFileSync('static/world.json', 'utf8'))
e5555695 2026-09-07 Pavel Safronov110
111 it('keeps every place the terrain tool emits', () => {
112 expect(parseWorld(seed).places).toHaveLength(seed.places.length)
113 })
114 it('knows every kind and geometry the tool uses', () => {
115 for (const p of seed.places) {
116 expect(PLACE_KINDS).toContain(p.kind)
04d6779e 2026-09-07 Pavel Safronov117 expect(['point', 'polyline', 'polygon', 'band']).toContain(p.geometry.type)
e5555695 2026-09-07 Pavel Safronov118 }
119 })
120 it('keeps the river and the canyon, which are polylines', () => {
121 const names = parseWorld(seed).places.map((p) => p.name)
122 expect(names).toContain('The Long Water')
123 expect(names).toContain('The Narrows')
124 })
04d6779e 2026-09-07 Pavel Safronov125
126 it('keeps the ringing regions as bands', () => {
127 const byName = new Map(parseWorld(seed).places.map((p) => [p.name, p]))
128 for (const n of ['The Dry Reach', 'Greatwood', 'The Sunward Sea', 'The Deepward Sea']) {
129 expect(byName.get(n)?.geometry.type).toBe('band')
130 }
131 })
e5555695 2026-09-07 Pavel Safronov132})
133
134describe('the public export is the privacy boundary', () => {
135 const world = { version: 1, places: [
136 place({ id: 'a', name: 'Shown', notes: 'SECRET', blurb: 'visible' }),
137 place({ id: 'b', name: 'Hidden', public: false, notes: 'ALSO SECRET' }),
138 ] }
139
140 it('drops unpublished places entirely', () =>
141 expect(toPublicWorld(world).places.map((p) => p.id)).toEqual(['a']))
142
143 it('strips private notes from the places it keeps', () => {
144 const json = JSON.stringify(toPublicWorld(world))
145 expect(json).not.toContain('SECRET')
146 expect(json).not.toContain('notes')
147 expect(json).toContain('visible')
148 })
149})
150
151describe('WorldStore', () => {
152 let store: WorldStore
153 beforeEach(() => {
154 const data = new Map<string, string>()
155 vi.stubGlobal('localStorage', {
156 getItem: (k: string) => data.get(k) ?? null,
157 setItem: (k: string, v: string) => void data.set(k, v),
158 removeItem: (k: string) => void data.delete(k),
159 })
160 store = new WorldStore()
161 })
162
163 it('persists across a reload', async () => {
164 store.add(place({ id: 'a', name: 'Kept' }))
165 store.flush()
166 const fresh = new WorldStore()
167 await fresh.load('/world.json')
168 expect(fresh.places.map((p) => p.name)).toEqual(['Kept'])
169 })
170
3b520afd 2026-09-07 Pavel Safronov171 it('treats an empty draft as no draft and loads the seed instead', async () => {
172 // Opening the app once while the seed was empty used to persist an empty world
173 // that then shadowed the real one forever.
174 store.replaceAll({ version: 1, places: [] })
175 store.flush()
176 const fresh = new WorldStore()
177 vi.stubGlobal('fetch', async () => ({ ok: true, json: async () => ({
178 places: [place({ id: 'seed', name: 'Seed' })] }) }))
179 await fresh.load('/world.json')
180 expect(fresh.places.map((p) => p.name)).toEqual(['Seed'])
181 })
182
183 it('reseeds on demand, replacing whatever is there', async () => {
184 store.add(place({ id: 'local', name: 'Local' }))
185 vi.stubGlobal('fetch', async () => ({ ok: true, json: async () => ({
186 places: [place({ id: 'a', name: 'A' }), place({ id: 'b', name: 'B' })] }) }))
187 await expect(store.seedFrom('/world.json')).resolves.toBe(2)
188 expect(store.places.map((p) => p.name)).toEqual(['A', 'B'])
189 })
190
e5555695 2026-09-07 Pavel Safronov191 it('prefers the local draft over the committed seed', async () => {
192 store.add(place({ id: 'draft', name: 'Draft' }))
193 store.flush()
194 const fresh = new WorldStore()
195 vi.stubGlobal('fetch', async () => ({ ok: true, json: async () => ({
196 places: [place({ id: 'seed', name: 'Seed' })] }) }))
197 await fresh.load('/world.json')
198 expect(fresh.places.map((p) => p.name)).toEqual(['Draft'])
199 })
200
201 it('seeds from the committed world when there is no draft', async () => {
202 const fresh = new WorldStore()
203 vi.stubGlobal('fetch', async () => ({ ok: true, json: async () => ({
204 places: [place({ id: 'seed', name: 'Seed' })] }) }))
205 await fresh.load('/world.json')
206 expect(fresh.places.map((p) => p.name)).toEqual(['Seed'])
207 })
208
209 it('starts empty rather than failing when there is no seed file', async () => {
210 const fresh = new WorldStore()
211 vi.stubGlobal('fetch', async () => { throw new Error('404') })
212 await expect(fresh.load('/world.json')).resolves.toBeUndefined()
213 expect(fresh.places).toEqual([])
214 })
215
216 it('reports rather than throws when localStorage is unavailable', () => {
217 vi.stubGlobal('localStorage', {
218 getItem: () => null,
219 setItem: () => { throw new Error('QuotaExceededError') },
220 })
221 const s = new WorldStore()
222 s.add(place())
223 s.flush()
224 expect(s.saveState).toBe('error')
225 expect(s.storageError).toContain('Quota')
226 })
227
228 it('keeps everything in the backup and only public data in the static export', () => {
229 store.add(place({ id: 'a', name: 'Pub', notes: 'SECRET' }))
230 store.add(place({ id: 'b', name: 'Priv', public: false }))
231 expect(store.fullJSON()).toContain('SECRET')
232 expect(store.fullJSON()).toContain('Priv')
233 expect(store.publicJSON()).not.toContain('SECRET')
234 expect(store.publicJSON()).not.toContain('Priv')
235 expect(store.publicCount()).toBe(1)
236 })
237
238 it('renames ids, since they are permalink targets', () => {
239 store.add(place({ id: 'new-city', name: 'New city' }))
240 expect(store.setId('new-city', 'hallow-crossing')).toBe(true)
241 expect(store.get('hallow-crossing')?.name).toBe('New city')
242 expect(store.get('new-city')).toBeUndefined()
243 })
244
245 it('refuses an id collision rather than losing a place', () => {
246 store.add(place({ id: 'a' }))
247 store.add(place({ id: 'b' }))
248 expect(store.setId('a', 'b')).toBe(false)
249 expect(store.places).toHaveLength(2)
250 expect(store.get('a')).toBeDefined()
251 })
252
253 it('dates backup filenames so a schedule of them sorts', () => {
254 expect(backupFilename(new Date('2026-09-05T12:00:00Z'))).toBe('tower-backup-2026-09-05.json')
255 })
256})