@onlyworlds/sdk 4.19.0 → 4.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -50,7 +50,10 @@ against live data). The v1 surface (`OnlyWorldsClient`, the `ElementType` enum)
50
50
  - Sort (since 4.18.0, account token): `account.sort({ worldId, notes, slice })` turns unsorted
51
51
  notes (text, or a picture already uploaded into the world) into rows to review: `make`,
52
52
  `add_to`, `link`, `ask`, plus `not_proposed` with reasons. Ids come only from your `slice`
53
- (up to 100 elements your own lookup found); nothing is written. Counts as one ask.
53
+ (up to 100 elements your own lookup found); nothing is written. Spends from the same
54
+ allowance as ask.
55
+ - Allowance (since 4.21.0, account token): `account.allowance()` reads the daily AI allowance
56
+ without spending: `{ token_rating, tokens_used_today, tokens_remaining, resets_at }`.
54
57
  - Invite links (since 4.12.0): `previewJoin(code)` (no credential sent) shows who invites, to
55
58
  which world, in what role; `acceptJoin(code)` with an `ow_a_` account token joins. Bad code:
56
59
  `err.isNotFound`; `err.isAlreadyMember`, `err.isPinRequired` for the two 409s.
@@ -63,6 +66,10 @@ against live data). The v1 surface (`OnlyWorldsClient`, the `ElementType` enum)
63
66
  world folder and returns `{ worldId, name, world, files: [{ path, data }] }`;
64
67
  `writeWorldFile(files, topDir)` makes one. Refusals throw `OwWorldFileError` with a `reason`.
65
68
  `world.json`'s `api` block (link and key) is removed both ways.
69
+ - World calendars (since 4.20.0): `worldCalendars(elements)` finds the elements carrying
70
+ `atlas_calendar` (Atlas owns the field: read it, never write it); `resolveCalendarLens` picks
71
+ one; `formatStep(config, step)` names a point on the world's integer time line, `parseDate`
72
+ reads one back. No calendar or a broken one is null: show the bare number.
66
73
  - Ids: the client mints **UUIDv7** on an id-less `create` (since 4.2.0; keel mints v7 too).
67
74
  A v4 or v7 id you supply is accepted. **Never sort elements by id**: worlds mix v7, v4
68
75
  and legacy `06x…` ids (nibble 7 too, but seconds-first). For creation order use
package/CHANGELOG.md CHANGED
@@ -5,6 +5,34 @@ earlier history lives in git log only.
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [4.21.0] — 2026-10-14
9
+
10
+ ### Added
11
+ - **`client.allowance()`**: GET /account/allowance (keel 872431f, Skeld h37 #4308), the
12
+ account's daily AI allowance read without spending: `token_rating`, `tokens_used_today`,
13
+ `tokens_remaining`, `resets_at` (the next midnight UTC). Account token only, like ask and
14
+ sort. Type `OwAllowance`, held by Assembly's wire gate to the route's declared schema, as
15
+ `OwAskAnswer`, `OwSortAnswer` and `OwJoinPreview` now are to theirs.
16
+
17
+ ### Fixed
18
+ - README and AGENTS.md no longer say a sort counts as one ask: since keel a6244db both spend
19
+ tokens from the allowance.
20
+
21
+ ## [4.20.0] — 2026-10-14
22
+
23
+ ### Added
24
+ - **World calendars**, Atlas's calendar code in the SDK so Lantern can name dates (Temper,
25
+ h37 #4284): `formatStep`, `formatYearLabel`, `breakdownStep`, `parseDate` and the rest of
26
+ Atlas's `src/core/calendar.ts` (Atlas 02d6a6d), plus `worldCalendars`,
27
+ `resolveCalendarLens` and `readCalendarValue` from its `calendar-lens.ts`, on any element
28
+ shape. `CALENDAR_FIELD` is `atlas_calendar`: Atlas owns the field, its meaning and its
29
+ writes, and other tools read it (Skeld, h37 #4286).
30
+ - `src/calendar/calendar.ts` is Atlas's file byte for byte, recorded in
31
+ `src/calendar/SOURCES.json` (Assembly's copy-drift); `codegen/atlas-calendar.mjs` re-copies it
32
+ and ports Atlas's 48 kernel tests (TypeScript's transpiler, a five-matcher `test/expect.mjs`
33
+ over node:test). Watched failing: a planted `floorMod` edit failed two tests and the record
34
+ (EDITED); a lens edit failed its test. An app that imports none of it bundles none of it.
35
+
8
36
  ## [4.19.0] — 2026-10-14
9
37
 
10
38
  ### Added
package/README.md CHANGED
@@ -174,7 +174,7 @@ const reply = await account.ask({ worldId, question, context }); // account: a c
174
174
  reply.answer; // from those elements only, or "The world doesn't say."
175
175
  ```
176
176
 
177
- The same proxy sorts loose notes into changes for the user to review. Send the elements your own lookup found for them as the `slice`; every id in a row comes from it, and nothing is written until your app applies what the user accepts. A sort counts as one question.
177
+ The same proxy sorts loose notes into changes for the user to review. Send the elements your own lookup found for them as the `slice`; every id in a row comes from it, and nothing is written until your app applies what the user accepts.
178
178
 
179
179
  ```typescript
180
180
  const slice = hits.slice(0, 100).map(({ element: e }) => ({ id: e.id, type: e.type, name: e.name }));
@@ -182,6 +182,12 @@ const { rows, not_proposed } = await account.sort({ worldId, notes: ['Mira moved
182
182
  // rows: make (a new element), add_to (text for a field), link (one element to another), ask (which one?)
183
183
  ```
184
184
 
185
+ Asking and sorting spend tokens from the account's daily AI allowance, the same meter the Council uses. Each answer carries `tokens_remaining` and `token_rating`; `allowance()` reads the meter without spending anything (since 4.21.0):
186
+
187
+ ```typescript
188
+ const { token_rating, tokens_remaining, resets_at } = await account.allowance(); // resets_at: the next midnight UTC
189
+ ```
190
+
185
191
  ## World files
186
192
 
187
193
  A world file is one `.zip` holding a whole world folder (`world.json` and `elements/<type>/*.json`, as Atlas keeps a world on disk), the way Atlas downloads and opens one. It needs no account and works in the browser and in Node.
@@ -198,6 +204,24 @@ const zip = writeWorldFile(world.files, 'hollow-reach-0192a000'); // one top-lev
198
204
 
199
205
  The reader refuses a file before returning anything: a path that could land outside the folder, more than 1 GiB or 200,000 files uncompressed (`maxBytes`, `maxEntries` to change them), no `world.json` with an `id`, or more than one world. Check `err.reason` on the `OwWorldFileError` it throws. The world's OnlyWorlds link and key (`world.json`'s `api`) never travel: both functions remove them. A tool's own folder (`.atlas/` and the like) comes back like any other file; pass `skip: path => …` to leave files out.
200
206
 
207
+ ## World calendars
208
+
209
+ A world's time is an integer line (`time_range_current` is a point on it, and so is an Event's `start_date`). A calendar names its points: months, days, eras. Atlas keeps a calendar on an element (a Construct by convention) in its `atlas_calendar` field, and the SDK reads it with Atlas's own calendar code (since 4.20.0). Atlas owns that field and is its only writer; read it, never write it.
210
+
211
+ ```typescript
212
+ import { worldCalendars, resolveCalendarLens, formatStep, formatYearLabel, parseDate } from '@onlyworlds/sdk';
213
+
214
+ const calendars = worldCalendars(elements); // [{ id, name, config }]: every element with a valid atlas_calendar
215
+ const cal = resolveCalendarLens(elements, chosenId, { fallbackToOnly: true }); // a world with one calendar uses it
216
+ if (cal) {
217
+ formatStep(cal.config, 400); // "4 Alturiak, 1 DR" (with Harptos, from Atlas's tests)
218
+ formatYearLabel(cal.config, 400); // "1 DR"
219
+ parseDate(cal.config, '4 Alturiak, 1 DR'); // { step: 400 }; a bare number is always the raw step
220
+ }
221
+ ```
222
+
223
+ No calendar, or a broken one, gives null: show the bare number. `breakdownStep` gives the parts (year, era, month, day, weekday, an intercalary day). The rules are Atlas's calendar design, §5 and §5b.
224
+
201
225
  ## Errors
202
226
 
203
227
  Every non-2xx response throws `OwApiError` with the API's envelope: `.status`, `.type`, `.code`, `.param` (the field that failed) and `.docUrl`, which is worth showing to your users. A transport failure throws `OwNetworkError`. `err.isValidationError` covers the common case. A write sent with `ifMatch` that found the element moved throws `OwPreconditionFailedError` (412, `err.isPreconditionFailed`), an `OwApiError` that also carries `current`.
package/dist/index.d.ts CHANGED
@@ -2104,6 +2104,18 @@ interface OwSortAnswer {
2104
2104
  token_rating: number;
2105
2105
  [k: string]: unknown;
2106
2106
  }
2107
+ /** GET /account/allowance: the account's daily AI allowance (keel 872431f, 2026-10-14). */
2108
+ interface OwAllowance {
2109
+ /** The account's daily allowance in tokens. */
2110
+ token_rating: number;
2111
+ /** Tokens spent today (UTC); may pass the rating by the size of the last call. */
2112
+ tokens_used_today: number;
2113
+ /** Tokens left today, never below 0. */
2114
+ tokens_remaining: number;
2115
+ /** When the allowance resets: the next midnight UTC (ISO 8601). */
2116
+ resets_at: string;
2117
+ [k: string]: unknown;
2118
+ }
2107
2119
  /** POST /join/preview: what a join code holds, read without using it (keel #212). */
2108
2120
  interface OwJoinPreview {
2109
2121
  /** `person`: an invite link, accepted with acceptJoin. `agent`: redeemed by an AI agent at POST /join. */
@@ -2583,7 +2595,7 @@ declare class OwV2Client {
2583
2595
  * lookupWorld's hits), sorted by the same proxy as ask into rows to review: `make`, `add_to`,
2584
2596
  * `link`, `ask`. Nothing is written; the app applies what the user accepts. Every id in a
2585
2597
  * row is from the slice; keel moves any other row to `not_proposed` with its reason.
2586
- * A sort counts as one ask: the same account token, allowance and refusals as ask. 422
2598
+ * The same account token, allowance (it spends the tokens it uses) and refusals as ask. 422
2587
2599
  * names the param: notes 1 to 8, each up to 4,000 characters and 16,000 in all (text
2588
2600
  * only), at most four pictures, each uploaded into this world; slice up to 100, names up
2589
2601
  * to 200 characters, anchors up to 120.
@@ -2593,6 +2605,12 @@ declare class OwV2Client {
2593
2605
  notes: OwSortNote[];
2594
2606
  slice: OwSortRef[];
2595
2607
  }): Promise<OwSortAnswer>;
2608
+ /**
2609
+ * GET /account/allowance -- the account's daily AI allowance, the one meter ask, sort and
2610
+ * the Council spend from (keel 872431f): the rating, what is used and left today, and
2611
+ * when it resets (the next midnight UTC). Spends nothing. Needs the client's `ow_a_` token.
2612
+ */
2613
+ allowance(): Promise<OwAllowance>;
2596
2614
  /**
2597
2615
  * Raw authenticated request against this client's baseUrl. Public since 4.0
2598
2616
  * so auxiliary resources can ride the same transport — it structurally
@@ -2989,6 +3007,267 @@ declare function planPhoto(source: {
2989
3007
  */
2990
3008
  declare function preparePhoto(input: Blob, opts?: OwPhotoOptions): Promise<OwPreparedPhoto>;
2991
3009
 
3010
+ /**
3011
+ * Calendar kernel — pure arithmetic, formatting, and parsing over the world's
3012
+ * integer time line.
3013
+ *
3014
+ * Contract: Forge/Notes/2026-07-14-calendar-design-final.md §5 + §5b (3-lens
3015
+ * gated 2026-07-14). The binding rules, restated where they bite:
3016
+ *
3017
+ * - The number line is the only truth. A calendar names it; it never owns it.
3018
+ * - Absolute year index is ZERO-based: step 0 opens absolute year 0. All
3019
+ * division is Euclidean floor (negatives depend on it).
3020
+ * - format(step) is total and O(config) — it never walks history.
3021
+ * - Intercalary days belong to no month and render via `format_intercalary`.
3022
+ * - A KNOWN token with no applicable value renders empty (with separator
3023
+ * collapse); an UNKNOWN token renders literally.
3024
+ * - parse() matches calendar words case-insensitively; bare numbers are ALWAYS
3025
+ * the raw stored step. Guaranteed property: format(parse(format(n))) ===
3026
+ * format(n). Exact integer recovery is NOT promised under lossy formats.
3027
+ *
3028
+ * Everything here is pure. No atlas imports beyond nothing — this module is
3029
+ * consumed by the charts room, popovers, and (via freeze) the publish path.
3030
+ */
3031
+ interface CalendarEra {
3032
+ name: string;
3033
+ abbrev?: string;
3034
+ /** Up-era: domain start (inclusive). Down-era: the PIVOT (exclusive upper bound). */
3035
+ start: number;
3036
+ /** Up-era: domain end (exclusive); defaults to the next era's start. Down-era: lower bound (inclusive); defaults to -infinity. */
3037
+ end?: number;
3038
+ /** true (default): years number from `start`. false: pure label, {year} shows the absolute year index. */
3039
+ restart?: boolean;
3040
+ /** First year number of a restart era: 0 or 1 (default 1). */
3041
+ year_base?: 0 | 1;
3042
+ /** 'up' (default) or 'down' (BC / Dune B.G. — counts toward the pivot). */
3043
+ direction?: 'up' | 'down';
3044
+ /** Closed eras format old dates but are never offered at date entry. */
3045
+ closed?: boolean;
3046
+ }
3047
+ interface CalendarMonths {
3048
+ names: string[];
3049
+ /** Same length as names. */
3050
+ lengths: number[];
3051
+ }
3052
+ interface CalendarWeek {
3053
+ length: number;
3054
+ names: string[];
3055
+ /** 'free' (default): runs across month boundaries, anchor step 0 = names[0].
3056
+ * 'nested': weekday = (day_of_month - 1) mod length; ragged final week legal. */
3057
+ mode?: 'free' | 'nested';
3058
+ }
3059
+ interface CalendarIntercalary {
3060
+ name: string;
3061
+ /** 0 = before month 1; k = after month k. Requires months. */
3062
+ after_month: number;
3063
+ /** Present only in years where floorMod(absYear, N) === 0 (the leap rule). */
3064
+ every_years?: number;
3065
+ /** Counts in the free-running week (default true). The Shire lock = opting
3066
+ * exactly Mid-year's Day + Overlithe out (364 = 52 × 7). */
3067
+ in_week?: boolean;
3068
+ }
3069
+ interface CalendarConfig {
3070
+ version: number;
3071
+ /** Immutable sentinel: the world's time_basic_unit at creation. Machinery only. */
3072
+ grain: string;
3073
+ /** The culture's display word for one step ("Sol"). Defaults to grain. */
3074
+ step_name?: string;
3075
+ eras?: CalendarEra[];
3076
+ bundles?: {
3077
+ /** Coarse-calendar year length. Legal ONLY when months are absent. */
3078
+ year?: {
3079
+ steps: number;
3080
+ };
3081
+ months?: CalendarMonths;
3082
+ week?: CalendarWeek;
3083
+ };
3084
+ intercalary?: CalendarIntercalary[];
3085
+ /** Regular-day template. Tokens: {day} {month} {weekday} {year} {era} {step}. */
3086
+ format?: string;
3087
+ /** Intercalary-day template; may also use {intercalary}. */
3088
+ format_intercalary?: string;
3089
+ }
3090
+ /** A step, taken apart. Fields are null when the structure doesn't exist. */
3091
+ interface StepBreakdown {
3092
+ step: number;
3093
+ /** Absolute year index (zero-based from step 0). */
3094
+ absYear: number;
3095
+ /** The era-local display year (restart arithmetic applied), or absYear when no era / restart:false. */
3096
+ year: number;
3097
+ era: CalendarEra | null;
3098
+ /** 1-based month index, or null (intercalary day / no months). */
3099
+ month: number | null;
3100
+ monthName: string | null;
3101
+ /** 1-based day within the month, or null. */
3102
+ day: number | null;
3103
+ /** Intercalary day name when the step IS one, else null. */
3104
+ intercalary: string | null;
3105
+ weekday: string | null;
3106
+ }
3107
+ interface ParseResult {
3108
+ step: number;
3109
+ }
3110
+ interface ParseError {
3111
+ error: string;
3112
+ }
3113
+ declare function floorDiv(a: number, b: number): number;
3114
+ declare function floorMod(a: number, b: number): number;
3115
+ declare function validateCalendarConfig(cfg: CalendarConfig): string[];
3116
+ /**
3117
+ * Defensive reader for wild configs (hand-edited files, other tools). Returns
3118
+ * null when the value is not a structurally usable calendar — callers fall
3119
+ * back to bare numbers, never a broken axis.
3120
+ */
3121
+ declare function readCalendarConfig(value: unknown): CalendarConfig | null;
3122
+ /** True when absolute year y contains the leap entry with period N. */
3123
+ declare function isLeapYear(y: number, N: number): boolean;
3124
+ /** First step of absolute year y. yearStart(0) === 0 by construction. */
3125
+ declare function yearStartStep(cfg: CalendarConfig, y: number): number;
3126
+ /** Length in steps of absolute year y. */
3127
+ declare function yearLength(cfg: CalendarConfig, y: number): number;
3128
+ /** Absolute year index of a step. Zero-based; closed-form seed + bounded correction. */
3129
+ declare function absoluteYear(cfg: CalendarConfig, step: number): number;
3130
+ interface EraDomain {
3131
+ era: CalendarEra;
3132
+ lo: number;
3133
+ hi: number;
3134
+ }
3135
+ declare function resolveEraDomains(eras: CalendarEra[]): EraDomain[];
3136
+ /** The era owning a step: domain containment; wild overlaps resolve to latest start (up wins ties). */
3137
+ declare function eraForStep(cfg: CalendarConfig, step: number): CalendarEra | null;
3138
+ /** The display year for a step under an era (or the absolute year without one). */
3139
+ declare function displayYear(cfg: CalendarConfig, step: number, era: CalendarEra | null): number;
3140
+ interface DaySlot {
3141
+ kind: 'month' | 'intercalary';
3142
+ month?: number;
3143
+ day?: number;
3144
+ intercalary?: CalendarIntercalary;
3145
+ }
3146
+ /** Weekday name for a step, or null (no week / nested outside months / skipped intercalary day). */
3147
+ declare function weekdayForStep(cfg: CalendarConfig, step: number, pre?: StepPosition): string | null;
3148
+ interface StepPosition {
3149
+ absYear: number;
3150
+ offset: number;
3151
+ slot: DaySlot | null;
3152
+ slots: DaySlot[] | null;
3153
+ }
3154
+ declare function breakdownStep(cfg: CalendarConfig, step: number): StepBreakdown;
3155
+ /** Format a step. Total: every integer formats to a string under every readable config. */
3156
+ declare function formatStep(cfg: CalendarConfig, step: number): string;
3157
+ /**
3158
+ * Compact year-level label: "{year} {era-abbrev}" — the axis-tick wording when
3159
+ * zoomed wide (full formatStep at tick density would be a wall of month names).
3160
+ * Outside every era: the absolute year index alone.
3161
+ */
3162
+ declare function formatYearLabel(cfg: CalendarConfig, step: number): string;
3163
+ /**
3164
+ * The base year length in steps (leap days excluded), or null when the
3165
+ * calendar has no year structure above the step. Consumers use it as a
3166
+ * zoom threshold (ticks tighter than a year → full dates, else year labels).
3167
+ */
3168
+ declare function approxYearLength(cfg: CalendarConfig): number | null;
3169
+ /**
3170
+ * A duration in steps, spoken: "19 years" when the calendar has year
3171
+ * structure and the span reaches it, else "12 days" in the step word. Uses
3172
+ * the BASE year length (leap days are noise at duration granularity); one
3173
+ * decimal below 10 years, whole above. Pure.
3174
+ */
3175
+ declare function formatDuration(cfg: CalendarConfig, steps: number): string;
3176
+ /**
3177
+ * The first step of each month in absolute year y, in order. O(config) — walks
3178
+ * month lengths + intercalary placement, never the year's days. Empty when the
3179
+ * calendar has no months.
3180
+ */
3181
+ declare function monthStartSteps(cfg: CalendarConfig, y: number): {
3182
+ month: number;
3183
+ name: string;
3184
+ step: number;
3185
+ }[];
3186
+ /**
3187
+ * Mid-rung label for dense axis ticks: "11 Greening 454" — day, month, display
3188
+ * year, NO era word (the era bands carry the era; a label wall repeating "FT"
3189
+ * is noise). Intercalary steps read "Hearthmoot 454". Monthless calendars fall
3190
+ * back to the year label.
3191
+ */
3192
+ declare function formatMidLabel(cfg: CalendarConfig, step: number): string;
3193
+ interface ParseOptions {
3194
+ /** The world's now (used to default a missing year, per contract rule 9). */
3195
+ now?: number | null;
3196
+ }
3197
+ /** Absolute year for an era-local display year (inverse of displayYear). */
3198
+ declare function absYearForEraYear(cfg: CalendarConfig, era: CalendarEra, Y: number): number;
3199
+ /**
3200
+ * Parse a written date to a step.
3201
+ *
3202
+ * Accepted shapes (calendar words case-insensitive):
3203
+ * "-454" / "454" -> the raw stored step, always
3204
+ * "454 AE" / "Year 12 FT" -> year (+ era)
3205
+ * "Frostwane 454" / "12 Frostwane 454" (+ era)
3206
+ * "Shieldmeet 1372" (+ era) -> intercalary day
3207
+ * "Frostwane 12" (no year) -> resolved against the now's year
3208
+ * Partial dates snap to the period's first step. Missing year with no now =
3209
+ * error (never guess). p(f(n)) == n is NOT promised; f(p(f(n))) == f(n) is.
3210
+ */
3211
+ declare function parseDate(cfg: CalendarConfig, input: string, opts?: ParseOptions): ParseResult | ParseError;
3212
+ declare function isParseError(r: ParseResult | ParseError): r is ParseError;
3213
+
3214
+ /**
3215
+ * World calendars: Atlas's calendar kernel, and which calendars a world holds.
3216
+ *
3217
+ * `calendar.ts` beside this file is Atlas's `src/core/calendar.ts`, byte for byte
3218
+ * (Forge/tools/atlas; recorded in `SOURCES.json`, checked with Assembly's copy-drift).
3219
+ * Never edit it here: change Atlas's, then copy and re-record. This file adapts Atlas's
3220
+ * `src/core/calendar-lens.ts` (readCalendarValue, worldCalendars, resolveCalendarLens) to
3221
+ * any element shape, since the SDK has no Atlas `Element`.
3222
+ *
3223
+ * The field: a calendar is an element (a Construct by convention) carrying `atlas_calendar`.
3224
+ * Atlas owns the field, its meaning and its writes (its calendar design, §5 and §5b); every
3225
+ * other tool reads it and never writes it (Skeld, h37 #4286: a prefix names the owner, not
3226
+ * who may read). Detection keys on the field's presence, never on the supertype.
3227
+ * Everything degrades to bare numbers: a missing, dangling or malformed calendar is null,
3228
+ * never an error.
3229
+ */
3230
+
3231
+ /** The supertype Atlas gives a calendar Construct: convention and display only. */
3232
+ declare const CALENDAR_SUPERTYPE = "calendar";
3233
+ /** Atlas's field for a calendar's config (owned by Atlas: read it, never write it). */
3234
+ declare const CALENDAR_FIELD = "atlas_calendar";
3235
+ /** Any element: an id, a name, and the rest of its fields. */
3236
+ interface OwCalendarElement {
3237
+ id: string;
3238
+ name?: string | null;
3239
+ [field: string]: unknown;
3240
+ }
3241
+ interface WorldCalendar {
3242
+ /** The calendar element's id. */
3243
+ id: string;
3244
+ /** The element's name: the calendar's display name. */
3245
+ name: string;
3246
+ config: CalendarConfig;
3247
+ }
3248
+ /**
3249
+ * The tolerant `atlas_calendar` read: an object or a JSON string (another tool may
3250
+ * serialize it; Atlas writes objects). Null for anything unusable. Read the field only
3251
+ * through this: a reader that took objects alone would blank a string config.
3252
+ */
3253
+ declare function readCalendarValue(raw: unknown): CalendarConfig | null;
3254
+ /**
3255
+ * Every usable calendar in the world: the elements with a valid `atlas_calendar`.
3256
+ * A malformed config is skipped: a broken calendar is invisible, not an error.
3257
+ */
3258
+ declare function worldCalendars(elements: Iterable<OwCalendarElement>): WorldCalendar[];
3259
+ /**
3260
+ * Resolve a chosen calendar id against the elements. A null id, a dangling id or an
3261
+ * invalid config resolve to null: bare numbers.
3262
+ *
3263
+ * `fallbackToOnly`: when no calendar was ever chosen (`activeId` is `undefined`, not
3264
+ * `null`) and the world holds exactly one, use it. `null` is an explicit "no calendar" and
3265
+ * stays null. With several calendars and no choice, nothing is guessed.
3266
+ */
3267
+ declare function resolveCalendarLens(elements: Iterable<OwCalendarElement>, activeId: string | null | undefined, opts?: {
3268
+ fallbackToOnly?: boolean;
3269
+ }): WorldCalendar | null;
3270
+
2992
3271
  /**
2993
3272
  * OnlyWorlds Token Management API Types
2994
3273
  *
@@ -3273,4 +3552,4 @@ declare class TokenResource {
3273
3552
  getEncryptionInfo(): Promise<EncryptionInfo>;
3274
3553
  }
3275
3554
 
3276
- export { ASK_LIMITS, type AccessKeyResponse, ELEMENT_FAMILIES, ELEMENT_ICONS, ELEMENT_LABELS, ELEMENT_SECTIONS, ELEMENT_TYPES, type ElementFamily, type ElementType, type EncryptionInfo, FAMILY_COLORS, FAMILY_ORDER, FIELD_SCHEMA, type FieldInfo, type FieldType, GameTier, type ListParams, ONLYWORLDS_VERSION, OwApiError, type OwAskAnswer, type OwAskContext, type OwAuthErrorCode, type OwBulkItem, type OwBulkItemResult, type OwBulkResponse, type OwChange, type OwChangesPage, type OwClientConfig, type OwElement, type OwElementBase, type OwErrorBody, type OwJoinPreview, type OwJoinedMembership, type OwKeyKind, type OwLinkEdit, type OwLookupElement, type OwLookupHit, type OwLookupLink, type OwLookupOptions, type OwLookupReason, type OwMediaTicket, type OwMemberRole, OwNetworkError, type OwPage, type OwPhotoOptions, type OwPhotoPlan, OwPreconditionFailedError, type OwPreparedPhoto, type OwReadWorldFile, type OwReadWorldFileOptions, type OwRemovalTicket, type OwRemovedImage, type OwRenderOptions, type OwSortAddToRow, type OwSortAnswer, type OwSortAskRow, type OwSortLinkRow, type OwSortMakeRow, type OwSortNote, type OwSortRef, type OwSortRow, type OwUploadedImage, OwV2Client, type OwWorldFileEntry, OwWorldFileError, type OwWorldFileReason, type OwWorldIndex, type OwWorldMeta, PHOTO_MAX_BYTES, PHOTO_TYPES, type RevokeAllSessionsResponse, type RevokeSessionResponse, SPATIAL_TYPES, type SectionInfo, type TokenConsumeParams, type TokenConsumeResponse, TokenResource, type TokenStatus, type TokenTransport, WORLD_FILE_MAX_BYTES, WORLD_FILE_MAX_ENTRIES, buildAskContext, buildWorldIndex, detectKeyKind, elementColor, errorFromResponse, familyOf, getElementIcon, getElementLabel, isDemoKey, kindCanWrite, lookupWorld, parseErrorEnvelope, pinExpectation, planPhoto, preparePhoto, readWorldFile, renderElement, writeWorldFile };
3555
+ export { ASK_LIMITS, type AccessKeyResponse, CALENDAR_FIELD, CALENDAR_SUPERTYPE, type CalendarConfig, type CalendarEra, type CalendarIntercalary, type CalendarMonths, type CalendarWeek, ELEMENT_FAMILIES, ELEMENT_ICONS, ELEMENT_LABELS, ELEMENT_SECTIONS, ELEMENT_TYPES, type ElementFamily, type ElementType, type EncryptionInfo, type EraDomain, FAMILY_COLORS, FAMILY_ORDER, FIELD_SCHEMA, type FieldInfo, type FieldType, GameTier, type ListParams, ONLYWORLDS_VERSION, type OwAllowance, OwApiError, type OwAskAnswer, type OwAskContext, type OwAuthErrorCode, type OwBulkItem, type OwBulkItemResult, type OwBulkResponse, type OwCalendarElement, type OwChange, type OwChangesPage, type OwClientConfig, type OwElement, type OwElementBase, type OwErrorBody, type OwJoinPreview, type OwJoinedMembership, type OwKeyKind, type OwLinkEdit, type OwLookupElement, type OwLookupHit, type OwLookupLink, type OwLookupOptions, type OwLookupReason, type OwMediaTicket, type OwMemberRole, OwNetworkError, type OwPage, type OwPhotoOptions, type OwPhotoPlan, OwPreconditionFailedError, type OwPreparedPhoto, type OwReadWorldFile, type OwReadWorldFileOptions, type OwRemovalTicket, type OwRemovedImage, type OwRenderOptions, type OwSortAddToRow, type OwSortAnswer, type OwSortAskRow, type OwSortLinkRow, type OwSortMakeRow, type OwSortNote, type OwSortRef, type OwSortRow, type OwUploadedImage, OwV2Client, type OwWorldFileEntry, OwWorldFileError, type OwWorldFileReason, type OwWorldIndex, type OwWorldMeta, PHOTO_MAX_BYTES, PHOTO_TYPES, type ParseError, type ParseOptions, type ParseResult, type RevokeAllSessionsResponse, type RevokeSessionResponse, SPATIAL_TYPES, type SectionInfo, type StepBreakdown, type TokenConsumeParams, type TokenConsumeResponse, TokenResource, type TokenStatus, type TokenTransport, WORLD_FILE_MAX_BYTES, WORLD_FILE_MAX_ENTRIES, type WorldCalendar, absYearForEraYear, absoluteYear, approxYearLength, breakdownStep, buildAskContext, buildWorldIndex, detectKeyKind, displayYear, elementColor, eraForStep, errorFromResponse, familyOf, floorDiv, floorMod, formatDuration, formatMidLabel, formatStep, formatYearLabel, getElementIcon, getElementLabel, isDemoKey, isLeapYear, isParseError, kindCanWrite, lookupWorld, monthStartSteps, parseDate, parseErrorEnvelope, pinExpectation, planPhoto, preparePhoto, readCalendarConfig, readCalendarValue, readWorldFile, renderElement, resolveCalendarLens, resolveEraDomains, validateCalendarConfig, weekdayForStep, worldCalendars, writeWorldFile, yearLength, yearStartStep };
package/dist/index.js CHANGED
@@ -500,7 +500,7 @@ var OwV2Client = class {
500
500
  * lookupWorld's hits), sorted by the same proxy as ask into rows to review: `make`, `add_to`,
501
501
  * `link`, `ask`. Nothing is written; the app applies what the user accepts. Every id in a
502
502
  * row is from the slice; keel moves any other row to `not_proposed` with its reason.
503
- * A sort counts as one ask: the same account token, allowance and refusals as ask. 422
503
+ * The same account token, allowance (it spends the tokens it uses) and refusals as ask. 422
504
504
  * names the param: notes 1 to 8, each up to 4,000 characters and 16,000 in all (text
505
505
  * only), at most four pictures, each uploaded into this world; slice up to 100, names up
506
506
  * to 200 characters, anchors up to 120.
@@ -513,6 +513,17 @@ var OwV2Client = class {
513
513
  body: { world_id: req.worldId, notes: req.notes, slice: req.slice }
514
514
  });
515
515
  }
516
+ /**
517
+ * GET /account/allowance -- the account's daily AI allowance, the one meter ask, sort and
518
+ * the Council spend from (keel 872431f): the rating, what is used and left today, and
519
+ * when it resets (the next midnight UTC). Spends nothing. Needs the client's `ow_a_` token.
520
+ */
521
+ async allowance() {
522
+ if (this.keyKind !== "account") {
523
+ throw new TypeError("allowance needs an account token (ow_a_): the allowance is per account");
524
+ }
525
+ return this.request("GET", "/account/allowance");
526
+ }
516
527
  // -- Core request machinery ----------------------------------------------
517
528
  /**
518
529
  * Raw authenticated request against this client's baseUrl. Public since 4.0
@@ -2135,6 +2146,456 @@ async function preparePhoto(input, opts = {}) {
2135
2146
  }
2136
2147
  }
2137
2148
 
2149
+ // src/calendar/calendar.ts
2150
+ function floorDiv(a, b) {
2151
+ return Math.floor(a / b);
2152
+ }
2153
+ function floorMod(a, b) {
2154
+ return (a % b + b) % b;
2155
+ }
2156
+ function validateCalendarConfig(cfg) {
2157
+ const errors = [];
2158
+ if (cfg.version !== 1) errors.push(`Unsupported calendar version: ${cfg.version}`);
2159
+ if (!cfg.grain || typeof cfg.grain !== "string") errors.push("Grain is required");
2160
+ const months = cfg.bundles?.months;
2161
+ if (months) {
2162
+ if (!Array.isArray(months.names) || !Array.isArray(months.lengths) || months.names.length === 0 || months.names.length !== months.lengths.length) {
2163
+ errors.push("months.names and months.lengths must be same-length non-empty arrays");
2164
+ } else if (months.lengths.some((l) => !Number.isInteger(l) || l < 1)) {
2165
+ errors.push("Every month length must be a whole number, 1 or more");
2166
+ }
2167
+ if (cfg.bundles?.year) errors.push("year.steps is legal only when no months are defined (year length is derived from months)");
2168
+ } else if (cfg.bundles?.year) {
2169
+ if (!Number.isInteger(cfg.bundles.year.steps) || cfg.bundles.year.steps < 1) {
2170
+ errors.push("year.steps must be a positive integer");
2171
+ }
2172
+ }
2173
+ const week = cfg.bundles?.week;
2174
+ if (week) {
2175
+ if (!Number.isInteger(week.length) || week.length < 1) errors.push("The week length must be a whole number, 1 or more");
2176
+ else if (!Array.isArray(week.names) || week.names.length !== week.length) errors.push("Give the week as many day names as its length");
2177
+ }
2178
+ const inter = cfg.intercalary ?? [];
2179
+ if (inter.length > 0 && !months) errors.push("Festival days need months");
2180
+ const monthCount = months?.names.length ?? 0;
2181
+ for (const ic of inter) {
2182
+ if (!Number.isInteger(ic.after_month) || ic.after_month < 0 || ic.after_month > monthCount) {
2183
+ errors.push(`Festival day "${ic.name}": pick the month it follows`);
2184
+ }
2185
+ if (ic.every_years != null && (!Number.isInteger(ic.every_years) || ic.every_years < 1)) {
2186
+ errors.push(`Festival day "${ic.name}": every N yrs must be a whole number, 1 or more`);
2187
+ }
2188
+ }
2189
+ const eras = cfg.eras ?? [];
2190
+ for (const era of eras) {
2191
+ if (!era.name) errors.push("Every era needs a name");
2192
+ if (!Number.isFinite(era.start)) errors.push(`Era "${era.name}": start must be a number`);
2193
+ if (era.end != null && !Number.isFinite(era.end)) errors.push(`Era "${era.name}": end must be a number`);
2194
+ if ((era.direction ?? "up") === "up" && era.end != null && era.end <= era.start) {
2195
+ errors.push(`Era "${era.name}": end must be after start`);
2196
+ }
2197
+ if ((era.direction ?? "up") === "down" && era.end != null && era.end >= era.start) {
2198
+ errors.push(`Era "${era.name}": a counting-down era must end below its start`);
2199
+ }
2200
+ }
2201
+ const domains = resolveEraDomains(eras);
2202
+ for (let i = 0; i < domains.length; i++) {
2203
+ for (let j = i + 1; j < domains.length; j++) {
2204
+ const a = domains[i];
2205
+ const b = domains[j];
2206
+ if (a.lo < b.hi && b.lo < a.hi) {
2207
+ errors.push(`Eras "${a.era.name}" and "${b.era.name}" overlap`);
2208
+ }
2209
+ }
2210
+ }
2211
+ return errors;
2212
+ }
2213
+ function readCalendarConfig(value) {
2214
+ if (typeof value !== "object" || value === null) return null;
2215
+ const cfg = value;
2216
+ if (cfg.version !== 1 || typeof cfg.grain !== "string") return null;
2217
+ const months = cfg.bundles?.months;
2218
+ if (months && (!Array.isArray(months.names) || !Array.isArray(months.lengths) || months.names.length !== months.lengths.length || months.names.length === 0)) return null;
2219
+ if (cfg.eras && !Array.isArray(cfg.eras)) return null;
2220
+ if (cfg.eras?.some((e) => typeof e?.name !== "string" || !Number.isFinite(e?.start))) return null;
2221
+ if (cfg.intercalary && (!Array.isArray(cfg.intercalary) || cfg.intercalary.some((i) => typeof i?.name !== "string" || !Number.isInteger(i?.after_month)))) return null;
2222
+ if (months && !months.lengths.every(isPositiveInt)) return null;
2223
+ const year = cfg.bundles?.year;
2224
+ if (year != null && !isPositiveInt(year.steps)) return null;
2225
+ const week = cfg.bundles?.week;
2226
+ if (week != null && (!isPositiveInt(week.length) || !Array.isArray(week.names))) return null;
2227
+ if (cfg.intercalary?.some((i) => i.every_years != null && !isPositiveInt(i.every_years))) return null;
2228
+ return cfg;
2229
+ }
2230
+ function isPositiveInt(n) {
2231
+ return Number.isSafeInteger(n) && n >= 1;
2232
+ }
2233
+ function yearShape(cfg) {
2234
+ const months = cfg.bundles?.months;
2235
+ const inter = cfg.intercalary ?? [];
2236
+ const leapPeriods = inter.filter((i) => i.every_years != null).map((i) => i.every_years);
2237
+ if (months) {
2238
+ const base = months.lengths.reduce((a, b) => a + b, 0) + inter.filter((i) => i.every_years == null).length;
2239
+ return { baseLen: base, leapPeriods };
2240
+ }
2241
+ return { baseLen: cfg.bundles?.year?.steps ?? 1, leapPeriods };
2242
+ }
2243
+ function leapYearsBefore(y, N) {
2244
+ if (y > 0) return floorDiv(y - 1, N) + 1;
2245
+ if (y === 0) return 0;
2246
+ return -floorDiv(-y, N);
2247
+ }
2248
+ function isLeapYear(y, N) {
2249
+ return floorMod(y, N) === 0;
2250
+ }
2251
+ function yearStartStep(cfg, y) {
2252
+ const shape = yearShape(cfg);
2253
+ let start = y * shape.baseLen;
2254
+ for (const N of shape.leapPeriods) start += leapYearsBefore(y, N);
2255
+ return start;
2256
+ }
2257
+ function yearLength(cfg, y) {
2258
+ const shape = yearShape(cfg);
2259
+ let len = shape.baseLen;
2260
+ for (const N of shape.leapPeriods) if (isLeapYear(y, N)) len += 1;
2261
+ return len;
2262
+ }
2263
+ var MAX_YEAR_CORRECTION = 1e4;
2264
+ function absoluteYear(cfg, step) {
2265
+ const shape = yearShape(cfg);
2266
+ const meanLen = shape.leapPeriods.reduce((a, N) => a + 1 / N, shape.baseLen);
2267
+ let y = floorDiv(step, meanLen);
2268
+ if (!Number.isFinite(y)) return y;
2269
+ for (let i = 0; i < MAX_YEAR_CORRECTION && step < yearStartStep(cfg, y); i++) y -= 1;
2270
+ for (let i = 0; i < MAX_YEAR_CORRECTION && step >= yearStartStep(cfg, y + 1); i++) y += 1;
2271
+ return y;
2272
+ }
2273
+ function resolveEraDomains(eras) {
2274
+ const sorted = [...eras].sort((a, b) => a.start - b.start);
2275
+ const out = [];
2276
+ for (let i = 0; i < sorted.length; i++) {
2277
+ const era = sorted[i];
2278
+ if ((era.direction ?? "up") === "down") {
2279
+ out.push({ era, lo: era.end ?? -Infinity, hi: era.start });
2280
+ } else {
2281
+ const nextStart = sorted[i + 1]?.start;
2282
+ out.push({ era, lo: era.start, hi: era.end ?? nextStart ?? Infinity });
2283
+ }
2284
+ }
2285
+ return out;
2286
+ }
2287
+ function eraForStep(cfg, step) {
2288
+ const eras = cfg.eras ?? [];
2289
+ if (eras.length === 0) return null;
2290
+ const holding = resolveEraDomains(eras).filter((d) => step >= d.lo && step < d.hi);
2291
+ if (holding.length === 0) return null;
2292
+ holding.sort((a, b) => b.era.start - a.era.start || ((a.era.direction ?? "up") === "up" ? -1 : 1));
2293
+ return holding[0].era;
2294
+ }
2295
+ function displayYear(cfg, step, era) {
2296
+ const abs = absoluteYear(cfg, step);
2297
+ if (!era || era.restart === false) return abs;
2298
+ const base = era.year_base ?? 1;
2299
+ if ((era.direction ?? "up") === "down") {
2300
+ return absoluteYear(cfg, era.start) - abs + base - 1;
2301
+ }
2302
+ return abs - absoluteYear(cfg, era.start) + base;
2303
+ }
2304
+ function yearSlots(cfg, y) {
2305
+ const months = cfg.bundles?.months;
2306
+ if (!months) return [];
2307
+ const inter = cfg.intercalary ?? [];
2308
+ const active = (ic) => ic.every_years == null || isLeapYear(y, ic.every_years);
2309
+ const slots = [];
2310
+ const push = (afterMonth) => {
2311
+ for (const ic of inter) if (ic.after_month === afterMonth && active(ic)) slots.push({ kind: "intercalary", intercalary: ic });
2312
+ };
2313
+ push(0);
2314
+ for (let m = 1; m <= months.names.length; m++) {
2315
+ for (let d = 1; d <= months.lengths[m - 1]; d++) slots.push({ kind: "month", month: m, day: d });
2316
+ push(m);
2317
+ }
2318
+ return slots;
2319
+ }
2320
+ function skippedWeekDaysPerYear(cfg) {
2321
+ const inter = (cfg.intercalary ?? []).filter((i) => i.in_week === false);
2322
+ return {
2323
+ base: inter.filter((i) => i.every_years == null).length,
2324
+ leapPeriods: inter.filter((i) => i.every_years != null).map((i) => i.every_years)
2325
+ };
2326
+ }
2327
+ function weekdayForStep(cfg, step, pre) {
2328
+ const week = cfg.bundles?.week;
2329
+ if (!week || week.length < 1 || week.names.length !== week.length) return null;
2330
+ const pos = pre ?? positionOf(cfg, step);
2331
+ if ((week.mode ?? "free") === "nested") {
2332
+ if (pos.slot?.kind !== "month") return null;
2333
+ return week.names[floorMod(pos.slot.day - 1, week.length)];
2334
+ }
2335
+ if (pos.slot?.kind === "intercalary" && pos.slot.intercalary?.in_week === false) return null;
2336
+ const skipped = skippedWeekDaysPerYear(cfg);
2337
+ const y = pos.absYear;
2338
+ let skippedBeforeYear = y * skipped.base;
2339
+ for (const N of skipped.leapPeriods) skippedBeforeYear += leapYearsBefore(y, N);
2340
+ let skippedInYear = 0;
2341
+ if (pos.slots) {
2342
+ for (let i = 0; i < pos.offset; i++) {
2343
+ const s = pos.slots[i];
2344
+ if (s.kind === "intercalary" && s.intercalary?.in_week === false) skippedInYear += 1;
2345
+ }
2346
+ }
2347
+ const counted = step - skippedBeforeYear - skippedInYear;
2348
+ return week.names[floorMod(counted, week.length)];
2349
+ }
2350
+ function positionOf(cfg, step) {
2351
+ const y = absoluteYear(cfg, step);
2352
+ const offset = step - yearStartStep(cfg, y);
2353
+ if (!cfg.bundles?.months) return { absYear: y, offset, slot: null, slots: null };
2354
+ const slots = yearSlots(cfg, y);
2355
+ return { absYear: y, offset, slot: slots[offset] ?? null, slots };
2356
+ }
2357
+ function breakdownStep(cfg, step) {
2358
+ const pos = positionOf(cfg, step);
2359
+ const era = eraForStep(cfg, step);
2360
+ const months = cfg.bundles?.months;
2361
+ const slot = pos.slot;
2362
+ return {
2363
+ step,
2364
+ absYear: pos.absYear,
2365
+ year: displayYear(cfg, step, era),
2366
+ era,
2367
+ month: slot?.kind === "month" ? slot.month : null,
2368
+ monthName: slot?.kind === "month" && months ? months.names[slot.month - 1] : null,
2369
+ day: slot?.kind === "month" ? slot.day : null,
2370
+ intercalary: slot?.kind === "intercalary" ? slot.intercalary.name : null,
2371
+ weekday: weekdayForStep(cfg, step, pos)
2372
+ };
2373
+ }
2374
+ var KNOWN_TOKENS = ["day", "month", "weekday", "year", "era", "step", "intercalary"];
2375
+ var DEFAULT_FORMAT_MONTHS = "{day} {month}, {year} {era}";
2376
+ var DEFAULT_FORMAT_PLAIN = "{year} {era}";
2377
+ var DEFAULT_FORMAT_INTERCALARY = "{intercalary}, {year} {era}";
2378
+ var EMPTY_KNOWN = "\uE000";
2379
+ function renderTemplate(template, values) {
2380
+ let out = template.replace(/\{([a-z_]+)\}/g, (whole, token) => {
2381
+ if (!KNOWN_TOKENS.includes(token)) return whole;
2382
+ const v = values[token];
2383
+ return v == null || v === "" ? EMPTY_KNOWN : v;
2384
+ });
2385
+ out = out.replace(/\s*[,;·]?\s*\uE000\s*[,;·]?\s*/g, " ").replace(/\s{2,}/g, " ").trim().replace(/^[\s,;·]+|[\s,;·]+$/g, "");
2386
+ return out;
2387
+ }
2388
+ function formatStep(cfg, step) {
2389
+ const b = breakdownStep(cfg, step);
2390
+ const values = {
2391
+ day: b.day != null ? String(b.day) : null,
2392
+ month: b.monthName,
2393
+ weekday: b.weekday,
2394
+ year: String(b.year),
2395
+ era: b.era ? b.era.abbrev ?? b.era.name : null,
2396
+ step: String(step),
2397
+ intercalary: b.intercalary
2398
+ };
2399
+ const template = b.intercalary != null ? cfg.format_intercalary ?? DEFAULT_FORMAT_INTERCALARY : cfg.format ?? (cfg.bundles?.months ? DEFAULT_FORMAT_MONTHS : DEFAULT_FORMAT_PLAIN);
2400
+ return renderTemplate(template, values);
2401
+ }
2402
+ function formatYearLabel(cfg, step) {
2403
+ const era = eraForStep(cfg, step);
2404
+ const year = displayYear(cfg, step, era);
2405
+ const eraLabel = era ? era.abbrev ?? era.name : "";
2406
+ return eraLabel ? `${year} ${eraLabel}` : String(year);
2407
+ }
2408
+ function approxYearLength(cfg) {
2409
+ if (cfg.bundles?.months) {
2410
+ return cfg.bundles.months.lengths.reduce((a, b) => a + b, 0) + (cfg.intercalary ?? []).filter((i) => i.every_years == null).length;
2411
+ }
2412
+ return cfg.bundles?.year?.steps ?? null;
2413
+ }
2414
+ function formatDuration(cfg, steps) {
2415
+ const n = Math.abs(steps);
2416
+ const unit = (cfg.step_name ?? cfg.grain ?? "step").trim() || "step";
2417
+ const plural = (word, v) => v === 1 ? word : `${word}s`;
2418
+ const yearLen = cfg.bundles?.months ? cfg.bundles.months.lengths.reduce((a, b) => a + b, 0) + (cfg.intercalary ?? []).filter((i) => i.every_years == null).length : cfg.bundles?.year?.steps ?? (unit.toLowerCase() === "year" ? 1 : null);
2419
+ if (yearLen != null && yearLen > 1 && n >= yearLen) {
2420
+ const years = n / yearLen;
2421
+ const rounded = years >= 10 ? Math.round(years) : Math.round(years * 10) / 10;
2422
+ return `${rounded} ${plural("year", rounded)}`;
2423
+ }
2424
+ const shown = Math.round(n * 100) / 100;
2425
+ return `${shown} ${plural(unit, shown)}`;
2426
+ }
2427
+ function monthStartSteps(cfg, y) {
2428
+ const months = cfg.bundles?.months;
2429
+ if (!months) return [];
2430
+ const inter = cfg.intercalary ?? [];
2431
+ const active = (ic) => ic.every_years == null || isLeapYear(y, ic.every_years);
2432
+ const out = [];
2433
+ let offset = inter.filter((i) => i.after_month === 0 && active(i)).length;
2434
+ const start = yearStartStep(cfg, y);
2435
+ for (let m = 1; m <= months.names.length; m++) {
2436
+ out.push({ month: m, name: months.names[m - 1], step: start + offset });
2437
+ offset += months.lengths[m - 1] + inter.filter((i) => i.after_month === m && active(i)).length;
2438
+ }
2439
+ return out;
2440
+ }
2441
+ function formatMidLabel(cfg, step) {
2442
+ const b = breakdownStep(cfg, step);
2443
+ if (b.intercalary != null) return `${b.intercalary} ${b.year}`;
2444
+ if (b.monthName != null && b.day != null) return `${b.day} ${b.monthName} ${b.year}`;
2445
+ return formatYearLabel(cfg, step);
2446
+ }
2447
+ function absYearForEraYear(cfg, era, Y) {
2448
+ if (era.restart === false) return Y;
2449
+ const base = era.year_base ?? 1;
2450
+ if ((era.direction ?? "up") === "down") return absoluteYear(cfg, era.start) - (Y - base + 1);
2451
+ return absoluteYear(cfg, era.start) + (Y - base);
2452
+ }
2453
+ function defaultEra(cfg, now) {
2454
+ const eras = cfg.eras ?? [];
2455
+ if (eras.length === 0) return null;
2456
+ if (now != null) {
2457
+ const holder = eraForStep(cfg, now);
2458
+ if (holder) return holder;
2459
+ }
2460
+ const open = eras.filter((e) => !e.closed);
2461
+ const pool = open.length > 0 ? open : eras;
2462
+ return [...pool].sort((a, b) => b.start - a.start)[0];
2463
+ }
2464
+ function parseDate(cfg, input, opts = {}) {
2465
+ const raw = input.trim();
2466
+ if (raw === "") return { error: "empty date" };
2467
+ if (/^-?\d+$/.test(raw)) return { step: parseInt(raw, 10) };
2468
+ const normalize2 = (s) => ` ${s.toLowerCase().replace(/[,.]/g, " ").replace(/\s+/g, " ").trim()} `;
2469
+ const months = cfg.bundles?.months;
2470
+ const inter = cfg.intercalary ?? [];
2471
+ let era = null;
2472
+ let monthIndex = null;
2473
+ let intercalary = null;
2474
+ let rest = normalize2(raw).replace(/ year /g, " ");
2475
+ const eat = (name) => {
2476
+ const needle = normalize2(name);
2477
+ if (rest.includes(needle)) {
2478
+ rest = rest.replace(needle, " ");
2479
+ return true;
2480
+ }
2481
+ return false;
2482
+ };
2483
+ const eraCandidates = [...cfg.eras ?? []].flatMap((e) => [{ key: e.name, e }, ...e.abbrev ? [{ key: e.abbrev, e }] : []]).sort((a, b) => b.key.length - a.key.length);
2484
+ for (const c of eraCandidates) if (eat(c.key)) {
2485
+ era = c.e;
2486
+ break;
2487
+ }
2488
+ const interCandidates = [...inter].sort((a, b) => b.name.length - a.name.length);
2489
+ for (const c of interCandidates) if (eat(c.name)) {
2490
+ intercalary = c;
2491
+ break;
2492
+ }
2493
+ if (!intercalary && months) {
2494
+ for (let m = 1; m <= months.names.length; m++) {
2495
+ if (eat(months.names[m - 1])) {
2496
+ monthIndex = m;
2497
+ break;
2498
+ }
2499
+ }
2500
+ }
2501
+ const numbers = [];
2502
+ for (const p of rest.trim().split(/\s+/).filter(Boolean)) {
2503
+ if (/^-?\d+$/.test(p)) numbers.push(parseInt(p, 10));
2504
+ else return { error: `unrecognized: "${p}"` };
2505
+ }
2506
+ let day = null;
2507
+ let year = null;
2508
+ if (monthIndex != null) {
2509
+ if (numbers.length === 2) {
2510
+ const len = months ? months.lengths[monthIndex - 1] : 0;
2511
+ const [a, b] = numbers;
2512
+ if (a >= 1 && a <= len) {
2513
+ day = a;
2514
+ year = b;
2515
+ } else if (b >= 1 && b <= len) {
2516
+ day = b;
2517
+ year = a;
2518
+ } else return { error: `no day in ${months?.names[monthIndex - 1]} matches ${a}/${b}` };
2519
+ } else if (numbers.length === 1) {
2520
+ const len = months ? months.lengths[monthIndex - 1] : 0;
2521
+ const n = numbers[0];
2522
+ if (n >= 1 && n <= len) {
2523
+ day = n;
2524
+ year = null;
2525
+ } else {
2526
+ year = n;
2527
+ }
2528
+ } else if (numbers.length !== 0) {
2529
+ return { error: "too many numbers" };
2530
+ }
2531
+ } else if (intercalary != null) {
2532
+ if (numbers.length > 1) return { error: "too many numbers" };
2533
+ year = numbers[0] ?? null;
2534
+ } else {
2535
+ if (numbers.length !== 1) return { error: "expected a year" };
2536
+ year = numbers[0];
2537
+ }
2538
+ const resolveInYear = (abs) => {
2539
+ const start = yearStartStep(cfg, abs);
2540
+ if (monthIndex == null && intercalary == null) return { step: start };
2541
+ const slots = yearSlots(cfg, abs);
2542
+ if (intercalary != null) {
2543
+ const idx2 = slots.findIndex((s) => s.kind === "intercalary" && s.intercalary === intercalary);
2544
+ if (idx2 === -1) return { error: `${intercalary.name} does not occur in that year` };
2545
+ return { step: start + idx2 };
2546
+ }
2547
+ const idx = slots.findIndex((s) => s.kind === "month" && s.month === monthIndex && s.day === (day ?? 1));
2548
+ if (idx === -1) return { error: "that day does not exist in that month" };
2549
+ return { step: start + idx };
2550
+ };
2551
+ if (year == null) {
2552
+ if (opts.now == null) return { error: "add a year (the world clock has no now set)" };
2553
+ return resolveInYear(absoluteYear(cfg, opts.now));
2554
+ }
2555
+ const target = era ?? defaultEra(cfg, opts.now);
2556
+ if (!target) return resolveInYear(year);
2557
+ const viaEra = resolveInYear(absYearForEraYear(cfg, target, year));
2558
+ if (isParseError(viaEra)) return viaEra;
2559
+ if (eraForStep(cfg, viaEra.step) === target) return viaEra;
2560
+ return resolveInYear(year);
2561
+ }
2562
+ function isParseError(r) {
2563
+ return r.error !== void 0;
2564
+ }
2565
+
2566
+ // src/calendar/index.ts
2567
+ var CALENDAR_SUPERTYPE = "calendar";
2568
+ var CALENDAR_FIELD = "atlas_calendar";
2569
+ function readCalendarValue(raw) {
2570
+ if (raw == null) return null;
2571
+ let value = raw;
2572
+ if (typeof raw === "string") {
2573
+ try {
2574
+ value = JSON.parse(raw);
2575
+ } catch {
2576
+ return null;
2577
+ }
2578
+ }
2579
+ return readCalendarConfig(value);
2580
+ }
2581
+ function worldCalendars(elements) {
2582
+ const out = [];
2583
+ for (const el of elements) {
2584
+ const config = readCalendarValue(el[CALENDAR_FIELD]);
2585
+ if (!config) continue;
2586
+ out.push({ id: el.id, name: el.name || "(unnamed calendar)", config });
2587
+ }
2588
+ return out;
2589
+ }
2590
+ function resolveCalendarLens(elements, activeId, opts) {
2591
+ if (activeId === void 0 && opts?.fallbackToOnly) {
2592
+ const all = worldCalendars(elements);
2593
+ return all.length === 1 ? all[0] : null;
2594
+ }
2595
+ if (!activeId) return null;
2596
+ return worldCalendars(elements).find((c) => c.id === activeId) ?? null;
2597
+ }
2598
+
2138
2599
  // src/token-resource.ts
2139
2600
  var TokenResource = class {
2140
2601
  constructor(client) {
@@ -2307,6 +2768,8 @@ var GameTier = /* @__PURE__ */ ((GameTier2) => {
2307
2768
  })(GameTier || {});
2308
2769
  export {
2309
2770
  ASK_LIMITS,
2771
+ CALENDAR_FIELD,
2772
+ CALENDAR_SUPERTYPE,
2310
2773
  ELEMENT_FAMILIES,
2311
2774
  ELEMENT_ICONS,
2312
2775
  ELEMENT_LABELS,
@@ -2328,22 +2791,47 @@ export {
2328
2791
  TokenResource,
2329
2792
  WORLD_FILE_MAX_BYTES,
2330
2793
  WORLD_FILE_MAX_ENTRIES,
2794
+ absYearForEraYear,
2795
+ absoluteYear,
2796
+ approxYearLength,
2797
+ breakdownStep,
2331
2798
  buildAskContext,
2332
2799
  buildWorldIndex,
2333
2800
  detectKeyKind,
2801
+ displayYear,
2334
2802
  elementColor,
2803
+ eraForStep,
2335
2804
  errorFromResponse,
2336
2805
  familyOf,
2806
+ floorDiv,
2807
+ floorMod,
2808
+ formatDuration,
2809
+ formatMidLabel,
2810
+ formatStep,
2811
+ formatYearLabel,
2337
2812
  getElementIcon,
2338
2813
  getElementLabel,
2339
2814
  isDemoKey,
2815
+ isLeapYear,
2816
+ isParseError,
2340
2817
  kindCanWrite,
2341
2818
  lookupWorld,
2819
+ monthStartSteps,
2820
+ parseDate,
2342
2821
  parseErrorEnvelope,
2343
2822
  pinExpectation,
2344
2823
  planPhoto,
2345
2824
  preparePhoto,
2825
+ readCalendarConfig,
2826
+ readCalendarValue,
2346
2827
  readWorldFile,
2347
2828
  renderElement,
2348
- writeWorldFile
2829
+ resolveCalendarLens,
2830
+ resolveEraDomains,
2831
+ validateCalendarConfig,
2832
+ weekdayForStep,
2833
+ worldCalendars,
2834
+ writeWorldFile,
2835
+ yearLength,
2836
+ yearStartStep
2349
2837
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onlyworlds/sdk",
3
- "version": "4.19.0",
3
+ "version": "4.21.0",
4
4
  "description": "TypeScript SDK for the OnlyWorlds API - build world-building applications with type safety",
5
5
  "type": "module",
6
6
  "exports": {