diff --git a/package-lock.json b/package-lock.json index b3b2ccb..a48629f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "dependencies": { "@fontsource-variable/bricolage-grotesque": "^5.3.0", "@fontsource/lato": "^5.3.0", - "@onlyworlds/sdk": "4.203.1", + "@onlyworlds/sdk": "4.212.1", "leaflet": "1.9.4", "leaflet.markercluster": "1.5.3", "qrcode-generator": "1.4.4" @@ -81,9 +81,9 @@ "license": "Apache-2.0" }, "node_modules/@onlyworlds/sdk": { - "version": "4.203.1", - "resolved": "https://registry.npmjs.org/@onlyworlds/sdk/-/sdk-4.203.1.tgz", - "integrity": "sha512-19zr6A9OcyE1NLRSiBCK1V8d5qSFC3uH5nK8hX6t+giqsFSGXQL4Lj38erC/z757r4e/KY8Gg5tCZzcxmEKO7A==", + "version": "4.212.1", + "resolved": "https://registry.npmjs.org/@onlyworlds/sdk/-/sdk-4.212.1.tgz", + "integrity": "sha512-9Bz47RIjzPhAcAY5fAr365Vq+649l6F+Pejhq6BRKIKfOy83htixgk1Q0kLkvqnhU0KglyZ2UvROGawAr1KtvA==", "license": "MIT", "dependencies": { "fflate": "^0.8.3" diff --git a/package.json b/package.json index 371d127..df17b8b 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "dependencies": { "@fontsource-variable/bricolage-grotesque": "^5.3.0", "@fontsource/lato": "^5.3.0", - "@onlyworlds/sdk": "4.203.1", + "@onlyworlds/sdk": "4.212.1", "leaflet": "1.9.4", "leaflet.markercluster": "1.5.3", "qrcode-generator": "1.4.4" diff --git a/src/time.ts b/src/time.ts index f20c9c3..e83de74 100644 --- a/src/time.ts +++ b/src/time.ts @@ -5,10 +5,10 @@ // The time line is keel's: a world's now is `time_range_current` (Atlas's folder writes it as // `time_current`), its unit `time_basic_unit`, an Event's dates the integers `start_date` and // `end_date`. Atlas can name those numbers with a calendar (`atlas_calendar`, SDK 4.20's copy of -// Atlas's kernel): a world with exactly one names its dates here as Atlas does on a device that -// never chose (which one a device chose is Atlas's own, not the world's); otherwise the numbers -// with the unit. A calendar never changes the order. -import { formatStep, resolveCalendar, type CalendarConfig, type OwElement } from '@onlyworlds/sdk'; +// Atlas's kernel): on a phone that never chose, the dates speak the calendar the World names in +// `x_calendar`, or its only one when it names none (the calendar profile, "Which calendar speaks"); +// a pick on this phone wins; otherwise the numbers with the unit. A calendar never changes the order. +import { formatStep, resolveCalendar, speakingCalendar, type CalendarConfig, type OwElement } from '@onlyworlds/sdk'; export interface WorldClock { now?: number; @@ -23,53 +23,16 @@ export function clockFrom(world: Record): WorldClock { return { now: num(world.time_range_current) ?? num(world.time_current), unit }; } -/** - * How much a calendar may hold before Lantern stops naming dates by it. A world is anyone's, and the - * SDK's `formatStep` costs more with each era, month, extra day and template character: on SDK - * 4.203.1, 15,000 eras cost 40 ms a label and 150,000 cost seconds. At these bounds a label costs - * under 2 ms. Atlas keeps the same counts (its `CALENDAR_BOUNDS`) until one bound for every tool - * lives in the standard. `yearSteps` was set on SDK 4.176.0, which built a whole year for every - * label (a 5,000,000-day month cost 768 ms); 4.201.2 made that cheap, and the bound stays as a limit. - */ -export const CALENDAR_BOUNDS = Object.freeze({ - eras: 256, - months: 256, - intercalary: 64, - except: 8, - weekdays: 256, - template: 1000, - name: 1000, - yearSteps: 40_000, -}); - -/** Does `cfg` hold more than {@link CALENDAR_BOUNDS}? Reads only what `readCalendarConfig` let through. */ -export function calendarTooCostly(cfg: CalendarConfig): boolean { - const B = CALENDAR_BOUNDS; - const eras = cfg.eras ?? []; - const months = cfg.bundles?.months; - const weekdays = cfg.bundles?.week?.names ?? []; - const extra = cfg.intercalary ?? []; - const yearSteps = (months?.lengths ?? []).reduce((sum, n) => sum + (Number.isFinite(n) ? n : 0), 0) + extra.length; - const names = [cfg.step_name, ...eras.flatMap(e => [e.name, e.abbrev]), ...(months?.names ?? []), ...weekdays, ...extra.map(e => e.name)]; - return eras.length > B.eras - || (months?.names?.length ?? 0) > B.months - || extra.length > B.intercalary - || extra.some(e => (e.except?.length ?? 0) > B.except) - || weekdays.length > B.weekdays - || (cfg.format?.length ?? 0) > B.template - || (cfg.format_intercalary?.length ?? 0) > B.template - || yearSteps > B.yearSteps - || names.some(n => typeof n === 'string' && n.length > B.name); -} - /** * The world's calendar, as Atlas resolves it: the one chosen on this phone (`null`: the numbers), - * else its only one; with several and no choice, none (nothing guessed). A calendar past - * {@link CALENDAR_BOUNDS} names no dates: the numbers, with the unit. + * else the one the World names in `x_calendar` (`world`: the World's keys, a record's `extensions`; + * a name that points at no calendar is the numbers, never another in its place), else its only one; + * with several and no choice, none (nothing guessed). A calendar past the calendar profile's size + * bounds is no calendar, as the SDK's reader refuses it in every tool: the numbers, with the unit. */ -export function calendarOf(elements: Iterable, chosen?: string | null): CalendarConfig | null { - const cfg = resolveCalendar(elements, chosen, { fallbackToOnly: true })?.config ?? null; - return cfg && !calendarTooCostly(cfg) ? cfg : null; +export function calendarOf(world: object | null | undefined, elements: Iterable, chosen?: string | null): CalendarConfig | null { + const keys = world && typeof world === 'object' && !Array.isArray(world) ? world : {}; + return (chosen === undefined ? speakingCalendar(keys, elements) : resolveCalendar(elements, chosen))?.config ?? null; } /** "3 Frost 412 AE" in the world's calendar; else "Year 412", or the bare number when the world names no unit. */ diff --git a/src/world.ts b/src/world.ts index d485757..80e6f66 100644 --- a/src/world.ts +++ b/src/world.ts @@ -176,6 +176,8 @@ export class WorldSession { private listeners = new Set<() => void>(); private backlinkCache: Map | null = null; private calendarCache: CalendarConfig | null | undefined = undefined; + /** The World's `x_calendar` the cached calendar was worked out under. */ + private calendarNamed: unknown = undefined; private lookupCache: OwWorldIndex | null = null; private handOnCache: OwWorldIndex | null = null; private aidsCache: AidsRead | null = null; @@ -691,7 +693,12 @@ export class WorldSession { /** The world's calendar (src/time.ts `calendarOf`), worked out once per change. */ calendar(): CalendarConfig | null { - if (this.calendarCache === undefined) this.calendarCache = calendarOf(this.view.values(), chosenCalendar(this.id)); + // The World's x_calendar rides the record, which a GET /world can replace at any poll. + const named = this.rec.extensions?.x_calendar; + if (this.calendarCache === undefined || this.calendarNamed !== named) { + this.calendarCache = calendarOf(this.rec.extensions, this.view.values(), chosenCalendar(this.id)); + this.calendarNamed = named; + } return this.calendarCache; } diff --git a/src/worldfile.ts b/src/worldfile.ts index fb01c48..1cc4aba 100644 --- a/src/worldfile.ts +++ b/src/worldfile.ts @@ -180,11 +180,23 @@ export async function saveFile(bytes: Uint8Array, name: string): Promise<'shared /** Said for a file the SDK cannot read at all (damaged, cut short, not a zip), in place of its path-and-cause line. */ export const NOT_OPENABLE = 'That file is not a world Lantern can open.'; +/** A file holding world.json, elements/ or spatial/ only in other capitals (the SDK's `name_case`). */ +export const NAME_CASE = 'That file is not a world Lantern can open: it holds world.json, elements/ or spatial/ in other capitals, where the folder format names them in small letters.'; + +/** Said for a file whose world.json is there and cannot be read (the SDK's `worldFault`), never "it has none". */ +export const WORLD_FAULT: Record, string> = { + too_deep: "That file's world.json is nested too deep to read, so Lantern does not open it. Ask whoever sent it for a new copy.", + not_json: "That file's world.json cannot be read, so Lantern does not open it. Ask whoever sent it for a new copy.", + number_out_of_range: "That file's world.json holds a number too large to read, so Lantern does not open it. Ask whoever sent it for a new copy.", +}; + export async function openWorldFile(bytes: Uint8Array): Promise { let read: ReturnType; try { read = readWorldFile(bytes); } catch (e) { + if (e instanceof OwWorldFileError && e.worldFault) throw new Error(WORLD_FAULT[e.worldFault] ?? NOT_OPENABLE); + if (e instanceof OwWorldFileError && e.reason === 'name_case') throw new Error(NAME_CASE); throw e instanceof OwWorldFileError && e.reason === 'not_openable' ? new Error(NOT_OPENABLE) : e; } if (await db.getWorldRecord(read.worldId)) { diff --git a/test/time.test.ts b/test/time.test.ts index 11585f0..7eeaf38 100644 --- a/test/time.test.ts +++ b/test/time.test.ts @@ -1,7 +1,7 @@ // Before now: a world's Events in order, split at the world's now (src/time.ts). import { describe, expect, it } from 'vitest'; import { formatStep, type OwElement } from '@onlyworlds/sdk'; -import { CALENDAR_BOUNDS, calendarOf, clockFrom, dateText, hasDatedEvent, isDateField, ongoing, spanText, timeline } from '../src/time'; +import { calendarOf, clockFrom, dateText, hasDatedEvent, isDateField, ongoing, spanText, timeline } from '../src/time'; const ev = (id: string, name: string, start?: number, end?: number) => ({ id, type: 'event', name, start_date: start, end_date: end }) as unknown as OwElement; @@ -55,25 +55,38 @@ describe("the world's calendar (SDK 4.20, Atlas's kernel)", () => { const calendar = (id: string, value: unknown) => ({ id, type: 'construct', name: id, supertype: 'calendar', atlas_calendar: value }) as unknown as OwElement; it('names dates only when the world holds exactly one calendar, as Atlas does on a device that never chose', () => { - expect(calendarOf([ev('1', 'x', 3), calendar('c1', cfg)])).toEqual(cfg); + expect(calendarOf({}, [ev('1', 'x', 3), calendar('c1', cfg)])).toEqual(cfg); // Moppetopia, Titus's own world, holds two: numbers, nothing guessed. - expect(calendarOf([calendar('c1', cfg), calendar('c2', { version: 1, grain: 'Year' })])).toBeNull(); - expect(calendarOf([ev('1', 'x', 3)])).toBeNull(); + expect(calendarOf({}, [calendar('c1', cfg), calendar('c2', { version: 1, grain: 'Year' })])).toBeNull(); + expect(calendarOf({}, [ev('1', 'x', 3)])).toBeNull(); // A JSON string is read as Atlas's object (another tool may serialize it); a broken one is no calendar. - expect(calendarOf([calendar('c1', JSON.stringify(cfg))])).toEqual(cfg); - expect(calendarOf([calendar('c1', { grain: 7 })])).toBeNull(); + expect(calendarOf({}, [calendar('c1', JSON.stringify(cfg))])).toEqual(cfg); + expect(calendarOf({}, [calendar('c1', { grain: 7 })])).toBeNull(); }); it("follows this phone's choice: a calendar by id, null for the numbers, a removed one as never chosen", () => { const two = [calendar('c1', cfg), calendar('c2', { version: 1, grain: 'Year', step_name: 'Turn' })]; - expect(calendarOf(two, 'c1')).toEqual(cfg); - expect(calendarOf([calendar('c1', cfg)], null)).toBeNull(); + expect(calendarOf({}, two, 'c1')).toEqual(cfg); + expect(calendarOf({}, [calendar('c1', cfg)], null)).toBeNull(); // A dangling choice (the calendar deleted in Atlas) resolves to nothing, as Atlas's lens does. - expect(calendarOf(two, 'gone')).toBeNull(); + expect(calendarOf({}, two, 'gone')).toBeNull(); + }); + + it("speaks the calendar the World names in x_calendar (the calendar profile), this phone's pick first", () => { + const c2 = { version: 1, grain: 'Year', step_name: 'Turn' }; + const two = [calendar('c1', cfg), calendar('c2', c2), { id: 'lore', type: 'construct', name: 'lore' } as unknown as OwElement]; + expect(calendarOf({ x_calendar: 'c2' }, two)).toEqual(c2); + expect(calendarOf({ x_calendar: 'c2' }, two, 'c1')).toEqual(cfg); + expect(calendarOf({ x_calendar: 'c2' }, two, null)).toBeNull(); + // A name that points at no calendar is the numbers, never the only calendar in its place. + for (const x of ['gone', 'lore', '', 'C1', 42]) expect(calendarOf({ x_calendar: x }, [calendar('c1', cfg)])).toBeNull(); + // Named none: the only one. + expect(calendarOf({ x_calendar: null }, [calendar('c1', cfg)])).toEqual(cfg); + expect(calendarOf(undefined, [calendar('c1', cfg)])).toEqual(cfg); }); it("speaks the calendar's words, and the numbers without one", () => { - const cal = calendarOf([calendar('c1', cfg)])!; + const cal = calendarOf({}, [calendar('c1', cfg)])!; expect(dateText(412, 'Year', cal)).toBe(formatStep(cal, 412)); expect(dateText(412, 'Year', cal)).toMatch(/AE/); expect(dateText(412, 'Year', null)).toBe('Year 412'); @@ -92,7 +105,7 @@ describe("the world's calendar (SDK 4.20, Atlas's kernel)", () => { intercalary: [{ name: 'Leap day', after_month: 2, every_years: 4, except: [100, 400], offset: 1 }], eras: [{ name: 'Common Era', abbrev: 'CE', start: 0 }], }; - const cal = calendarOf([calendar('g', greg)]); + const cal = calendarOf({}, [calendar('g', greg)]); expect(cal).not.toBeNull(); // The step after 28 Feb, counted by the proleptic Gregorian rule written out here, not the SDK's. const leap = (y: number) => (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0; @@ -104,7 +117,7 @@ describe("the world's calendar (SDK 4.20, Atlas's kernel)", () => { it('an open era runs to the next up era, a down era listed after it skipped (SDK 4.76)', () => { const eras = { version: 1, grain: 'Year', eras: [{ name: 'After', abbrev: 'AF', start: 0 }, { name: 'Before', abbrev: 'BF', start: 0, direction: 'down' }] }; - expect(dateText(5, 'Year', calendarOf([calendar('e', eras)]))).toContain('6 AF'); + expect(dateText(5, 'Year', calendarOf({}, [calendar('e', eras)]))).toContain('6 AF'); }); it("knows a schema date field by Atlas's rule, never a custom one", () => { @@ -113,11 +126,13 @@ describe("the world's calendar (SDK 4.20, Atlas's kernel)", () => { }); }); -describe("a calendar past the bound names no dates (a world is anyone's)", () => { +// The calendar profile's size bounds (standard serial 149, profiles/calendar.md "Not a calendar"): +// a calendar past one is no calendar in every reader, Lantern's own bounds gone with SDK 4.212.1. +describe("a calendar past the profile's bounds names no dates (a world is anyone's)", () => { const months = (n: number, len = 3) => ({ names: Array.from({ length: n }, (_, i) => `M${i}`), lengths: Array.from({ length: n }, () => len) }); const base = () => ({ version: 2, grain: 'day', bundles: { months: months(2) }, format: '{day} {month} {year}' }); const calendar = (value: unknown) => ({ id: 'c1', type: 'construct', name: 'c1', supertype: 'calendar', atlas_calendar: value }) as unknown as OwElement; - const B = CALENDAR_BOUNDS; + const B = { eras: 256, months: 64, weekdays: 64, intercalary: 16, except: 8, template: 256, name: 256 }; const shapes: Array<[string, (n: number) => object, number]> = [ ['eras', n => ({ ...base(), eras: Array.from({ length: n }, (_, i) => ({ name: `E${i}`, start: i * 10 })) }), B.eras], ['months', n => ({ ...base(), bundles: { months: months(n) } }), B.months], @@ -126,27 +141,26 @@ describe("a calendar past the bound names no dates (a world is anyone's)", () => ['weekdays', n => ({ ...base(), bundles: { months: months(2), week: { length: n, names: Array.from({ length: n }, (_, i) => `W${i}`) } } }), B.weekdays], ['template', n => ({ ...base(), format: '{day}' + ' '.repeat(n - 5) }), B.template], ['a name', n => ({ ...base(), bundles: { months: { names: ['x'.repeat(n), 'B'], lengths: [3, 3] } } }), B.name], - ['steps in a year', n => ({ ...base(), bundles: { months: { names: ['A', 'B'], lengths: [n - 100, 100] } } }), B.yearSteps], ]; for (const [what, make, bound] of shapes) { it(`${what}: ${bound} names dates, one more is the numbers`, () => { - expect(calendarOf([calendar(make(bound))])).not.toBeNull(); - expect(calendarOf([calendar(make(bound + 1))])).toBeNull(); + expect(calendarOf({}, [calendar(make(bound))])).not.toBeNull(); + expect(calendarOf({}, [calendar(make(bound + 1))])).toBeNull(); }); } - it('a 5,000,000-day month is the numbers, at once', () => { + it('a 5,000,000-day month names its dates, at once (the SDK words a label of any year length cheaply)', () => { const t0 = performance.now(); - const cal = calendarOf([calendar({ version: 2, grain: 'day', bundles: { months: { names: ['Long'], lengths: [5_000_000] } } })]); - expect(cal).toBeNull(); - expect(dateText(4_999_999, 'Day', cal)).toBe('Day 4999999'); + const cal = calendarOf({}, [calendar({ version: 2, grain: 'day', bundles: { months: { names: ['Long'], lengths: [5_000_000] } } })]); + expect(cal).not.toBeNull(); + expect(dateText(4_999_999, 'Day', cal)).toBe(formatStep(cal!, 4_999_999)); expect(performance.now() - t0).toBeLessThan(100); }); it("reads the calendar profile's absent-likes as a calendar, never throwing on a months bundle with no names", () => { // The profile's fixture case `absent-likes`: the SDK reads it as a calendar with no months; the bound must too. const value = { version: 1, grain: 'year', bundles: { months: false, week: null }, eras: null, intercalary: null }; - const cal = calendarOf([calendar(value)]); + const cal = calendarOf({}, [calendar(value)]); expect(cal).not.toBeNull(); expect(dateText(0, 'Year', cal)).toBe('Year 0'); }); diff --git a/test/worldfile.test.ts b/test/worldfile.test.ts index e83b77a..031371c 100644 --- a/test/worldfile.test.ts +++ b/test/worldfile.test.ts @@ -5,7 +5,8 @@ import { readFileSync, readdirSync } from 'node:fs'; import { homedir } from 'node:os'; import { join } from 'node:path'; import { readWorldFile, writeWorldFile, type OwElement } from '@onlyworlds/sdk'; -import { lanternProducer, openWorldFile, slugify, toWorldFile, worldCopy } from '../src/worldfile'; +import { zipSync, strToU8 } from 'fflate'; +import { lanternProducer, NAME_CASE, openWorldFile, slugify, toWorldFile, worldCopy, WORLD_FAULT } from '../src/worldfile'; import * as db from '../src/db'; // The standard's own pair for private records (schema-dist fixtures/owworld, OW-8, serial 49): @@ -87,6 +88,22 @@ describe('world files', () => { expect((await db.listWorlds()).length).toBe(before); }); + it("a world.json that is there and cannot be read is said for what it is, in Lantern's words, and nothing is kept", async () => { + const before = (await db.listWorlds()).length; + const file = (worldJson: string) => zipSync({ 'w/world.json': strToU8(worldJson), 'w/elements/character/a--1.json': strToU8('{"id":"1","name":"A"}') }); + const deep = `{"id":"0192b000-0000-7000-8000-000000000148","name":"Deep","x":${'['.repeat(200)}${']'.repeat(200)}}`; + await expect(openWorldFile(file(deep))).rejects.toThrow(WORLD_FAULT.too_deep); + await expect(openWorldFile(file('{"id": '))).rejects.toThrow(WORLD_FAULT.not_json); + expect((await db.listWorlds()).length).toBe(before); + }); + + it('a world file holding elements/ in other capitals is said to be named wrong, and nothing is kept', async () => { + const before = (await db.listWorlds()).length; + const z = zipSync({ 'w/world.json': strToU8('{"id":"0192b000-0000-7000-8000-000000000149","name":"Caps"}'), 'w/Elements/character/a--1.json': strToU8('{"id":"1","name":"A"}') }); + await expect(openWorldFile(z)).rejects.toThrow(NAME_CASE); + expect((await db.listWorlds()).length).toBe(before); + }); + it('names files as Atlas does', () => { expect(slugify('José’s Ferry-Debt!')).toBe('jose-s-ferry-debt'); const { bytes } = toWorldFile({ id: '019f0000-0000-7000-8000-00000000abcd', name: 'Bus stop ideas', kind: 'local', addedAt: '' }, [