@flare-engine/progression 0.4.10 → 0.4.12

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @flare-engine/progression
2
2
 
3
- Meta-progression primitives: geometric upgrade tracks, pity-aware weighted drop rolling, unlock DAG, tier resolution, and collectible-unlock registry. Pure, zero-alloc on hot paths. Depends on `@flare-engine/math`.
3
+ Meta-progression primitives: geometric upgrade tracks, pity-aware weighted drop rolling, unlock DAG, tier resolution, collectible-unlock registry, and a segmented game-day clock. Pure, zero-alloc on hot paths. Depends on `@flare-engine/math`.
4
4
 
5
5
  ## Install
6
6
 
@@ -18,6 +18,7 @@ import {
18
18
  createUnlockDag,
19
19
  resolveTier,
20
20
  createCollectibleRegistry,
21
+ createGameClock,
21
22
  } from '@flare-engine/progression';
22
23
 
23
24
  // Upgrade track — geometric price curve
@@ -57,6 +58,20 @@ const tier = resolveTier([{ at: 1, tier: 'bronze' }, { at: 10, tier: 'silver' }]
57
58
  const reg = createCollectibleRegistry(['item-1', 'item-2', 'item-3'], 'set-complete');
58
59
  const reg2 = reg.unlock('item-1').unlock('item-2').unlock('item-3');
59
60
  reg2.isCapstone; // true
61
+
62
+ // Game clock — 1440-minute day, each segment runs at its own real-time rate
63
+ const clock = createGameClock({
64
+ segments: [
65
+ { name: 'day', phase: 'day', startMinute: 0, secondsPerGameHour: 90 },
66
+ { name: 'night', phase: 'night', startMinute: 720, secondsPerGameHour: 120 },
67
+ ],
68
+ onPhaseChange: (phase, previous) => console.log(previous, '->', phase),
69
+ });
70
+ const dt = 1 / 60;
71
+ clock.update(dt); // real seconds, zero-alloc; crosses boundaries exactly
72
+ clock.skipTo('night'); // jump forward to the next start of that segment
73
+ clock.hold(); // stop at the next phase boundary until release()
74
+ const saved = clock.serialize(); // { absoluteMinutes, paused } — pass back as the 2nd arg
60
75
  ```
61
76
 
62
77
  See [API spec](https://github.com/grzott/flare-engine/blob/main/docs/design/api-specs.md#flare-engineprogression).
package/dist/index.d.mts CHANGED
@@ -43,13 +43,14 @@ interface CollectibleRegistry<K extends string> {
43
43
  * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an
44
44
  * optional `capstoneId`.
45
45
  *
46
- * Duplicate ids in `ids` throw. `capstoneId` may equal one of the ids in `ids`
47
- * (it is tracked as a separate gate — the capstone fires only on full completion,
48
- * not by direct unlock through `ids` membership alone).
46
+ * Duplicate ids in `ids` throw. The capstone is unlocked automatically once every
47
+ * id in `ids` is unlocked, and `unlock(capstoneId)` also unlocks it directly;
48
+ * either way `isCapstone` becomes true.
49
49
  *
50
- * The capstone MUST be distinct from all ids in `ids` — if not, the capstone
51
- * unlock auto-fires on full completion regardless of whether the capstone id
52
- * was directly unlocked via the `ids` set, which would be semantically ambiguous.
50
+ * Keep `capstoneId` out of `ids` for a capstone that marks completion. If it is
51
+ * listed in `ids`, it is an ordinary member of the set: `isComplete` needs it,
52
+ * `isCapstone` turns true as soon as it is unlocked, and the automatic unlock never
53
+ * has anything to add.
53
54
  */
54
55
  export declare function createCollectibleRegistry<K extends string>(ids: readonly K[], capstoneId?: K): CollectibleRegistry<K>;
55
56
  /**
@@ -106,6 +107,75 @@ export declare function createDropTable<K extends string>(entries: readonly Drop
106
107
  * Use `table.rollInto` on the hot path; this is for tests and cold-path setup.
107
108
  */
108
109
  export declare function rollDrop<K extends string>(table: DropTable<K>, rollTable01: number, rollChance01: number, chancePerRoll: number, pity: DropPity<K>, thresholds: Partial<Record<K, number>>, isAllowed?: (item: K) => boolean): DropRollOut<K>;
110
+ /**
111
+ * Game-day clock with per-segment real-time rates.
112
+ * A day is 1440 game minutes split into ordered segments; each segment
113
+ * runs at its own `secondsPerGameHour`. Supports pause, hold (stop at the
114
+ * next phase boundary), manual advance, skip-to-segment, change callbacks,
115
+ * and a plain serializable state.
116
+ */
117
+ interface GameClockSegment {
118
+ /** Segment name, e.g. 'day', 'dusk'. May repeat (a night that wraps midnight is two rows). */
119
+ readonly name: string;
120
+ /** Coarser grouping, e.g. 'day' | 'night'. */
121
+ readonly phase: string;
122
+ /** Minute of the game day at which the segment starts, integer 0..1439. */
123
+ readonly startMinute: number;
124
+ /** Real seconds per game hour while in this segment. */
125
+ readonly secondsPerGameHour: number;
126
+ }
127
+ interface GameClockConfig {
128
+ /** Ordered by `startMinute`; the first must start at 0. The last runs to 1440. */
129
+ readonly segments: readonly GameClockSegment[];
130
+ readonly onSegmentChange?: (segment: string, previous: string) => void;
131
+ readonly onPhaseChange?: (phase: string, previous: string) => void;
132
+ }
133
+ interface GameClockState {
134
+ readonly absoluteMinutes: number;
135
+ readonly paused: boolean;
136
+ }
137
+ interface GameClock {
138
+ /** Game minutes since day 0 00:00. Fractional, never decreases. */
139
+ readonly absoluteMinutes: number;
140
+ /** `floor(absoluteMinutes / 1440)`. */
141
+ readonly day: number;
142
+ /** 0..23. */
143
+ readonly hour: number;
144
+ /** 0..59, integer. */
145
+ readonly minute: number;
146
+ readonly segment: string;
147
+ readonly phase: string;
148
+ readonly paused: boolean;
149
+ readonly held: boolean;
150
+ /**
151
+ * Advance by `dt` real seconds. No-op while paused, or when `dt` is not finite or <= 0.
152
+ * Throws `RangeError` when `dt` could carry `absoluteMinutes` past `Number.MAX_SAFE_INTEGER`.
153
+ */
154
+ update(dt: number): void;
155
+ /**
156
+ * Advance by `n` game minutes, even while paused. Throws `RangeError` when `n` is negative or
157
+ * not finite, or when `absoluteMinutes + n` exceeds `Number.MAX_SAFE_INTEGER`.
158
+ */
159
+ advanceMinutes(n: number): void;
160
+ /**
161
+ * Jump forward to the next start of `segmentName`, strictly after now, or to now when the
162
+ * clock sits on that start without having entered it (held on the boundary, then released).
163
+ * Throws on an unknown name.
164
+ */
165
+ skipTo(segmentName: string): void;
166
+ pause(): void;
167
+ resume(): void;
168
+ /** Stop at the next phase boundary and stay there until `release()`. */
169
+ hold(): void;
170
+ release(): void;
171
+ /** Allocates a fresh state object (cold path). `held` is not persisted. */
172
+ serialize(): GameClockState;
173
+ }
174
+ /**
175
+ * Returns a `GameClock` backed by `config`, optionally restored from `state`.
176
+ * The returned object is a plain object with getters (no class).
177
+ */
178
+ export declare function createGameClock(config: GameClockConfig, state?: GameClockState): GameClock;
109
179
  /**
110
180
  * Tier resolution: "highest threshold crossed by a running tally."
111
181
  *
@@ -217,5 +287,5 @@ interface UpgradeTrack {
217
287
  * The returned object is a plain object (no class) — safe to freeze or copy.
218
288
  */
219
289
  export declare function createUpgradeTrack(config: UpgradeTrackConfig): UpgradeTrack;
220
- export type { CollectibleRegistry, DagNode, DropEntry, DropPity, DropRollOut, DropTable, TierEntry, UnlockDag, UpgradeBuyResult, UpgradeTrack, UpgradeTrackConfig };
290
+ export type { CollectibleRegistry, DagNode, DropEntry, DropPity, DropRollOut, DropTable, GameClock, GameClockConfig, GameClockSegment, GameClockState, TierEntry, UnlockDag, UpgradeBuyResult, UpgradeTrack, UpgradeTrackConfig };
221
291
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/collectible-registry.ts","../src/drop-roll.ts","../src/tier-resolve.ts","../src/unlock-dag.ts","../src/upgrade-track.ts"],"mappings":";;;;;;UAOiB,oBAAoB;;WAE1B,KAAK,YAAY;;WAEjB,YAAY;;WAEZ,UAAU,YAAY;;WAEtB;;;;;WAKA;;;;;;;EAOT,OAAO,IAAI,IAAI,oBAAoB;;;;;;EAMnC;IAAe,eAAe;IAAK,kBAAkB;;;;;EAIrD,iBAAiB;;;;;;;;;;;;;;wBAiEH,0BAA0B,kBACxC,cAAc,KACd,aAAa,IACZ,oBAAoB;;;;;;;;;;;UC5FN,UAAU;WAChB,MAAM;WACN;;;;;;KAOC,SAAS,oBAAoB,OAAO;UAE/B,YAAY;EAC3B,MAAM;EACN,MAAM,SAAS;;;;;;UAOA,UAAU;WAChB,kBAAkB,UAAU;;;;;;;;;;;;;EAarC,SACE,qBACA,sBACA,uBACA,MAAM,SAAS,IACf,YAAY,QAAQ,OAAO,aAC3B,YAAY,MAAM,eAClB,KAAK,YAAY;;;;;;;wBASL,gBAAgB,kBAAkB,kBAAkB,UAAU,OAAO,UAAU;;;;;wBAuE/E,SAAS,kBACvB,OAAO,UAAU,IACjB,qBACA,sBACA,uBACA,MAAM,SAAS,IACf,YAAY,QAAQ,OAAO,aAC3B,aAAa,MAAM,gBAClB,YAAY;;;;;;;UCvIE,UAAU;;WAEhB;;WAEA,MAAM;;;;;;;;;;wBAWD,YAAY,GAAG,kBAAkB,UAAU,MAAM,gBAAgB;;;;;;wBAiBjE,iBAAiB,GAAG,kBAAkB,UAAU,MAAM;;;;;;;UChCrD;;WAEN;;WAEA;;UAGM;WACN,OAAO,oBAAoB;;;;;;EAMpC,WAAW,SAAS,qBAAqB;;;;;;EAMzC,SAAS,SAAS;;;;;EAKlB,YAAY,SAAS;;;;;;;wBAQP,gBAAgB,gBAAgB,YAAY;;;;;;UClC3C;;WAEN;;WAEA;;WAEA;;UAGM;WACN;WACA;WACA;;UAGM;WACN,QAAQ;;;;;EAKjB,MAAM;;EAEN,OAAO,gBAAgB;;;;;EAKvB,IAAI,gBAAgB,uBAAuB;;;;;;;;EAQ3C,aAAa,kBACX,MAAM,OAAO,YACb,QAAQ,OAAO,YACf,WAAW,KAAK,eACf,OAAO;;;;;;wBAOI,mBAAmB,QAAQ,qBAAqB"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/collectible-registry.ts","../src/drop-roll.ts","../src/game-clock.ts","../src/tier-resolve.ts","../src/unlock-dag.ts","../src/upgrade-track.ts"],"mappings":";;;;;;UAOiB,oBAAoB;;WAE1B,KAAK,YAAY;;WAEjB,YAAY;;WAEZ,UAAU,YAAY;;WAEtB;;;;;WAKA;;;;;;;EAOT,OAAO,IAAI,IAAI,oBAAoB;;;;;;EAMnC;IAAe,eAAe;IAAK,kBAAkB;;;;;EAIrD,iBAAiB;;;;;;;;;;;;;;;wBAkEH,0BAA0B,kBACxC,cAAc,KACd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EAEN,OAAO,gBAAgB;;;;;EAKvB,IAAI,gBAAgB,uBAAuB;;;;;;;;EAQ3C,aAAa,kBACX,MAAM,OAAO,YACb,QAAQ,OAAO,YACf,WAAW,KAAK,eACf,OAAO;;;;;;wBAOI,mBAAmB,QAAQ,qBAAqB"}
package/dist/index.d.ts CHANGED
@@ -43,13 +43,14 @@ interface CollectibleRegistry<K extends string> {
43
43
  * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an
44
44
  * optional `capstoneId`.
45
45
  *
46
- * Duplicate ids in `ids` throw. `capstoneId` may equal one of the ids in `ids`
47
- * (it is tracked as a separate gate — the capstone fires only on full completion,
48
- * not by direct unlock through `ids` membership alone).
46
+ * Duplicate ids in `ids` throw. The capstone is unlocked automatically once every
47
+ * id in `ids` is unlocked, and `unlock(capstoneId)` also unlocks it directly;
48
+ * either way `isCapstone` becomes true.
49
49
  *
50
- * The capstone MUST be distinct from all ids in `ids` — if not, the capstone
51
- * unlock auto-fires on full completion regardless of whether the capstone id
52
- * was directly unlocked via the `ids` set, which would be semantically ambiguous.
50
+ * Keep `capstoneId` out of `ids` for a capstone that marks completion. If it is
51
+ * listed in `ids`, it is an ordinary member of the set: `isComplete` needs it,
52
+ * `isCapstone` turns true as soon as it is unlocked, and the automatic unlock never
53
+ * has anything to add.
53
54
  */
54
55
  export declare function createCollectibleRegistry<K extends string>(ids: readonly K[], capstoneId?: K): CollectibleRegistry<K>;
55
56
  /**
@@ -106,6 +107,75 @@ export declare function createDropTable<K extends string>(entries: readonly Drop
106
107
  * Use `table.rollInto` on the hot path; this is for tests and cold-path setup.
107
108
  */
108
109
  export declare function rollDrop<K extends string>(table: DropTable<K>, rollTable01: number, rollChance01: number, chancePerRoll: number, pity: DropPity<K>, thresholds: Partial<Record<K, number>>, isAllowed?: (item: K) => boolean): DropRollOut<K>;
110
+ /**
111
+ * Game-day clock with per-segment real-time rates.
112
+ * A day is 1440 game minutes split into ordered segments; each segment
113
+ * runs at its own `secondsPerGameHour`. Supports pause, hold (stop at the
114
+ * next phase boundary), manual advance, skip-to-segment, change callbacks,
115
+ * and a plain serializable state.
116
+ */
117
+ interface GameClockSegment {
118
+ /** Segment name, e.g. 'day', 'dusk'. May repeat (a night that wraps midnight is two rows). */
119
+ readonly name: string;
120
+ /** Coarser grouping, e.g. 'day' | 'night'. */
121
+ readonly phase: string;
122
+ /** Minute of the game day at which the segment starts, integer 0..1439. */
123
+ readonly startMinute: number;
124
+ /** Real seconds per game hour while in this segment. */
125
+ readonly secondsPerGameHour: number;
126
+ }
127
+ interface GameClockConfig {
128
+ /** Ordered by `startMinute`; the first must start at 0. The last runs to 1440. */
129
+ readonly segments: readonly GameClockSegment[];
130
+ readonly onSegmentChange?: (segment: string, previous: string) => void;
131
+ readonly onPhaseChange?: (phase: string, previous: string) => void;
132
+ }
133
+ interface GameClockState {
134
+ readonly absoluteMinutes: number;
135
+ readonly paused: boolean;
136
+ }
137
+ interface GameClock {
138
+ /** Game minutes since day 0 00:00. Fractional, never decreases. */
139
+ readonly absoluteMinutes: number;
140
+ /** `floor(absoluteMinutes / 1440)`. */
141
+ readonly day: number;
142
+ /** 0..23. */
143
+ readonly hour: number;
144
+ /** 0..59, integer. */
145
+ readonly minute: number;
146
+ readonly segment: string;
147
+ readonly phase: string;
148
+ readonly paused: boolean;
149
+ readonly held: boolean;
150
+ /**
151
+ * Advance by `dt` real seconds. No-op while paused, or when `dt` is not finite or <= 0.
152
+ * Throws `RangeError` when `dt` could carry `absoluteMinutes` past `Number.MAX_SAFE_INTEGER`.
153
+ */
154
+ update(dt: number): void;
155
+ /**
156
+ * Advance by `n` game minutes, even while paused. Throws `RangeError` when `n` is negative or
157
+ * not finite, or when `absoluteMinutes + n` exceeds `Number.MAX_SAFE_INTEGER`.
158
+ */
159
+ advanceMinutes(n: number): void;
160
+ /**
161
+ * Jump forward to the next start of `segmentName`, strictly after now, or to now when the
162
+ * clock sits on that start without having entered it (held on the boundary, then released).
163
+ * Throws on an unknown name.
164
+ */
165
+ skipTo(segmentName: string): void;
166
+ pause(): void;
167
+ resume(): void;
168
+ /** Stop at the next phase boundary and stay there until `release()`. */
169
+ hold(): void;
170
+ release(): void;
171
+ /** Allocates a fresh state object (cold path). `held` is not persisted. */
172
+ serialize(): GameClockState;
173
+ }
174
+ /**
175
+ * Returns a `GameClock` backed by `config`, optionally restored from `state`.
176
+ * The returned object is a plain object with getters (no class).
177
+ */
178
+ export declare function createGameClock(config: GameClockConfig, state?: GameClockState): GameClock;
109
179
  /**
110
180
  * Tier resolution: "highest threshold crossed by a running tally."
111
181
  *
@@ -217,5 +287,5 @@ interface UpgradeTrack {
217
287
  * The returned object is a plain object (no class) — safe to freeze or copy.
218
288
  */
219
289
  export declare function createUpgradeTrack(config: UpgradeTrackConfig): UpgradeTrack;
220
- export type { CollectibleRegistry, DagNode, DropEntry, DropPity, DropRollOut, DropTable, TierEntry, UnlockDag, UpgradeBuyResult, UpgradeTrack, UpgradeTrackConfig };
290
+ export type { CollectibleRegistry, DagNode, DropEntry, DropPity, DropRollOut, DropTable, GameClock, GameClockConfig, GameClockSegment, GameClockState, TierEntry, UnlockDag, UpgradeBuyResult, UpgradeTrack, UpgradeTrackConfig };
221
291
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/collectible-registry.ts","../src/drop-roll.ts","../src/tier-resolve.ts","../src/unlock-dag.ts","../src/upgrade-track.ts"],"mappings":";;;;;;UAOiB,oBAAoB;;WAE1B,KAAK,YAAY;;WAEjB,YAAY;;WAEZ,UAAU,YAAY;;WAEtB;;;;;WAKA;;;;;;;EAOT,OAAO,IAAI,IAAI,oBAAoB;;;;;;EAMnC;IAAe,eAAe;IAAK,kBAAkB;;;;;EAIrD,iBAAiB;;;;;;;;;;;;;;wBAiEH,0BAA0B,kBACxC,cAAc,KACd,aAAa,IACZ,oBAAoB;;;;;;;;;;;UC5FN,UAAU;WAChB,MAAM;WACN;;;;;;KAOC,SAAS,oBAAoB,OAAO;UAE/B,YAAY;EAC3B,MAAM;EACN,MAAM,SAAS;;;;;;UAOA,UAAU;WAChB,kBAAkB,UAAU;;;;;;;;;;;;;EAarC,SACE,qBACA,sBACA,uBACA,MAAM,SAAS,IACf,YAAY,QAAQ,OAAO,aAC3B,YAAY,MAAM,eAClB,KAAK,YAAY;;;;;;;wBASL,gBAAgB,kBAAkB,kBAAkB,UAAU,OAAO,UAAU;;;;;wBAuE/E,SAAS,kBACvB,OAAO,UAAU,IACjB,qBACA,sBACA,uBACA,MAAM,SAAS,IACf,YAAY,QAAQ,OAAO,aAC3B,aAAa,MAAM,gBAClB,YAAY;;;;;;;UCvIE,UAAU;;WAEhB;;WAEA,MAAM;;;;;;;;;;wBAWD,YAAY,GAAG,kBAAkB,UAAU,MAAM,gBAAgB;;;;;;wBAiBjE,iBAAiB,GAAG,kBAAkB,UAAU,MAAM;;;;;;;UChCrD;;WAEN;;WAEA;;UAGM;WACN,OAAO,oBAAoB;;;;;;EAMpC,WAAW,SAAS,qBAAqB;;;;;;EAMzC,SAAS,SAAS;;;;;EAKlB,YAAY,SAAS;;;;;;;wBAQP,gBAAgB,gBAAgB,YAAY;;;;;;UClC3C;;WAEN;;WAEA;;WAEA;;UAGM;WACN;WACA;WACA;;UAGM;WACN,QAAQ;;;;;EAKjB,MAAM;;EAEN,OAAO,gBAAgB;;;;;EAKvB,IAAI,gBAAgB,uBAAuB;;;;;;;;EAQ3C,aAAa,kBACX,MAAM,OAAO,YACb,QAAQ,OAAO,YACf,WAAW,KAAK,eACf,OAAO;;;;;;wBAOI,mBAAmB,QAAQ,qBAAqB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/collectible-registry.ts","../src/drop-roll.ts","../src/game-clock.ts","../src/tier-resolve.ts","../src/unlock-dag.ts","../src/upgrade-track.ts"],"mappings":";;;;;;UAOiB,oBAAoB;;WAE1B,KAAK,YAAY;;WAEjB,YAAY;;WAEZ,UAAU,YAAY;;WAEtB;;;;;WAKA;;;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lB,YAAY,SAAS;;;;;;;wBAQP,gBAAgB,gBAAgB,YAAY;;;;;;UClC3C;;WAEN;;WAEA;;WAEA;;UAGM;WACN;WACA;WACA;;UAGM;WACN,QAAQ;;;;;EAKjB,MAAM;;EAEN,OAAO,gBAAgB;;;;;EAKvB,IAAI,gBAAgB,uBAAuB;;;;;;;;EAQ3C,aAAa,kBACX,MAAM,OAAO,YACb,QAAQ,OAAO,YACf,WAAW,KAAK,eACf,OAAO;;;;;;wBAOI,mBAAmB,QAAQ,qBAAqB"}
package/dist/index.js CHANGED
@@ -43,13 +43,14 @@ function makeRegistry(all, capstoneId, unlocked) {
43
43
  * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an
44
44
  * optional `capstoneId`.
45
45
  *
46
- * Duplicate ids in `ids` throw. `capstoneId` may equal one of the ids in `ids`
47
- * (it is tracked as a separate gate — the capstone fires only on full completion,
48
- * not by direct unlock through `ids` membership alone).
46
+ * Duplicate ids in `ids` throw. The capstone is unlocked automatically once every
47
+ * id in `ids` is unlocked, and `unlock(capstoneId)` also unlocks it directly;
48
+ * either way `isCapstone` becomes true.
49
49
  *
50
- * The capstone MUST be distinct from all ids in `ids` — if not, the capstone
51
- * unlock auto-fires on full completion regardless of whether the capstone id
52
- * was directly unlocked via the `ids` set, which would be semantically ambiguous.
50
+ * Keep `capstoneId` out of `ids` for a capstone that marks completion. If it is
51
+ * listed in `ids`, it is an ordinary member of the set: `isComplete` needs it,
52
+ * `isCapstone` turns true as soon as it is unlocked, and the automatic unlock never
53
+ * has anything to add.
53
54
  */
54
55
  function createCollectibleRegistry(ids, capstoneId) {
55
56
  const all = /* @__PURE__ */ new Set();
@@ -124,6 +125,188 @@ function rollDrop(table, rollTable01, rollChance01, chancePerRoll, pity, thresho
124
125
  table.rollInto(rollTable01, rollChance01, chancePerRoll, pity, thresholds, isAllowed ?? (() => true), out);
125
126
  return out;
126
127
  }
128
+ // src/game-clock.ts
129
+ /**
130
+ * Game-day clock with per-segment real-time rates.
131
+ * A day is 1440 game minutes split into ordered segments; each segment
132
+ * runs at its own `secondsPerGameHour`. Supports pause, hold (stop at the
133
+ * next phase boundary), manual advance, skip-to-segment, change callbacks,
134
+ * and a plain serializable state.
135
+ */
136
+ const MINUTES_PER_DAY = 1440;
137
+ function validateSegments(segments) {
138
+ if (segments.length === 0) throw new Error("createGameClock: segments must not be empty");
139
+ const first = segments[0];
140
+ if (first.startMinute !== 0) throw new Error(`createGameClock: first segment must start at minute 0, got ${first.startMinute}`);
141
+ let previousStart = -1;
142
+ for (let i = 0; i < segments.length; i++) {
143
+ const seg = segments[i];
144
+ const start = seg.startMinute;
145
+ if (!Number.isInteger(start) || start < 0 || start >= MINUTES_PER_DAY) throw new Error(`createGameClock: segment ${i} ("${seg.name}") startMinute must be an integer in 0..1439, got ${start}`);
146
+ if (start <= previousStart) throw new Error(`createGameClock: segment ${i} ("${seg.name}") startMinute ${start} must be greater than the previous start ${previousStart}`);
147
+ previousStart = start;
148
+ const rate = seg.secondsPerGameHour;
149
+ if (!Number.isFinite(rate) || rate <= 0) throw new Error(`createGameClock: segment ${i} ("${seg.name}") secondsPerGameHour must be finite and > 0, got ${rate}`);
150
+ }
151
+ }
152
+ /**
153
+ * Returns a `GameClock` backed by `config`, optionally restored from `state`.
154
+ * The returned object is a plain object with getters (no class).
155
+ */
156
+ function createGameClock(config, state) {
157
+ const segments = config.segments;
158
+ validateSegments(segments);
159
+ const count = segments.length;
160
+ const onSegmentChange = config.onSegmentChange;
161
+ const onPhaseChange = config.onPhaseChange;
162
+ const ends = new Float64Array(count);
163
+ let fastestRate = Number.POSITIVE_INFINITY;
164
+ for (let i = 0; i < count; i++) {
165
+ ends[i] = i + 1 < count ? segments[i + 1].startMinute : MINUTES_PER_DAY;
166
+ fastestRate = Math.min(fastestRate, segments[i].secondsPerGameHour);
167
+ }
168
+ let absolute = 0;
169
+ let paused = false;
170
+ let held = false;
171
+ let index = 0;
172
+ if (state !== void 0) {
173
+ if (!Number.isFinite(state.absoluteMinutes) || state.absoluteMinutes < 0 || state.absoluteMinutes > Number.MAX_SAFE_INTEGER) throw new Error(`createGameClock: state.absoluteMinutes must be finite, >= 0 and <= Number.MAX_SAFE_INTEGER, got ${state.absoluteMinutes}`);
174
+ if (typeof state.paused !== "boolean") throw new Error(`createGameClock: state.paused must be a boolean, got ${String(state.paused)}`);
175
+ absolute = state.absoluteMinutes;
176
+ paused = state.paused;
177
+ const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;
178
+ for (let i = 0; i < count; i++) if (segments[i].startMinute <= minuteOfDay) index = i;
179
+ }
180
+ /**
181
+ * Move from the current segment to the next one, firing callbacks.
182
+ * Returns false (and leaves everything untouched) when held and the next
183
+ * segment opens a different phase.
184
+ */
185
+ function cross() {
186
+ const next = index + 1 < count ? index + 1 : 0;
187
+ const prev = segments[index];
188
+ const nextSeg = segments[next];
189
+ const phaseChanges = nextSeg.phase !== prev.phase;
190
+ if (held && phaseChanges) return false;
191
+ index = next;
192
+ if (nextSeg.name !== prev.name && onSegmentChange !== void 0) onSegmentChange(nextSeg.name, prev.name);
193
+ if (phaseChanges && onPhaseChange !== void 0) onPhaseChange(nextSeg.phase, prev.phase);
194
+ return true;
195
+ }
196
+ /** Absolute minute at which the current segment ends (an integer while below 2^53). */
197
+ function currentBoundary() {
198
+ let day = Math.floor(absolute / MINUTES_PER_DAY);
199
+ if (absolute - day * MINUTES_PER_DAY < segments[index].startMinute) day -= 1;
200
+ return day * MINUTES_PER_DAY + ends[index];
201
+ }
202
+ /**
203
+ * Game-minute advance to an absolute target. Each boundary is compared against
204
+ * the target itself rather than a carried remainder, so a target that equals a
205
+ * boundary always lands on it and crosses (unless held).
206
+ */
207
+ function advanceTo(target) {
208
+ for (;;) {
209
+ const boundary = currentBoundary();
210
+ if (target < boundary) {
211
+ if (target > absolute) absolute = target;
212
+ return;
213
+ }
214
+ absolute = boundary;
215
+ if (!cross()) return;
216
+ }
217
+ }
218
+ function update(dt) {
219
+ if (paused || !Number.isFinite(dt) || dt <= 0) return;
220
+ if (absolute + dt * 60 / fastestRate > Number.MAX_SAFE_INTEGER) throw new RangeError(`GameClock.update: dt ${dt} would carry absoluteMinutes past Number.MAX_SAFE_INTEGER`);
221
+ let remaining = dt;
222
+ for (;;) {
223
+ const boundary = currentBoundary();
224
+ const toBoundary = boundary - absolute;
225
+ if (toBoundary > 0) {
226
+ const rate = segments[index].secondsPerGameHour;
227
+ const cost = toBoundary * rate / 60;
228
+ if (remaining < cost) {
229
+ const next = absolute + remaining * 60 / rate;
230
+ if (next < boundary) {
231
+ absolute = next;
232
+ return;
233
+ }
234
+ remaining = 0;
235
+ } else remaining -= cost;
236
+ absolute = boundary;
237
+ }
238
+ if (!cross() || paused) return;
239
+ }
240
+ }
241
+ function advanceMinutes(n) {
242
+ if (!Number.isFinite(n) || n < 0) throw new RangeError(`GameClock.advanceMinutes: n must be finite and >= 0, got ${n}`);
243
+ const target = absolute + n;
244
+ if (target > Number.MAX_SAFE_INTEGER) throw new RangeError(`GameClock.advanceMinutes: absoluteMinutes + n must not exceed Number.MAX_SAFE_INTEGER, got ${target}`);
245
+ advanceTo(target);
246
+ }
247
+ function skipTo(segmentName) {
248
+ const day = Math.floor(absolute / MINUTES_PER_DAY);
249
+ let target = Number.POSITIVE_INFINITY;
250
+ for (let i = 0; i < count; i++) {
251
+ const seg = segments[i];
252
+ if (seg.name !== segmentName) continue;
253
+ let candidate = day * MINUTES_PER_DAY + seg.startMinute;
254
+ if (candidate < absolute || candidate === absolute && index === i) candidate += MINUTES_PER_DAY;
255
+ if (candidate < target) target = candidate;
256
+ }
257
+ if (target === Number.POSITIVE_INFINITY) throw new Error(`GameClock.skipTo: unknown segment "${segmentName}"`);
258
+ advanceTo(target);
259
+ }
260
+ return {
261
+ get absoluteMinutes() {
262
+ return absolute;
263
+ },
264
+ get day() {
265
+ return Math.floor(absolute / MINUTES_PER_DAY);
266
+ },
267
+ get hour() {
268
+ const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;
269
+ return Math.floor(minuteOfDay / 60);
270
+ },
271
+ get minute() {
272
+ const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;
273
+ return Math.floor(minuteOfDay - Math.floor(minuteOfDay / 60) * 60);
274
+ },
275
+ get segment() {
276
+ return segments[index].name;
277
+ },
278
+ get phase() {
279
+ return segments[index].phase;
280
+ },
281
+ get paused() {
282
+ return paused;
283
+ },
284
+ get held() {
285
+ return held;
286
+ },
287
+ update,
288
+ advanceMinutes,
289
+ skipTo,
290
+ pause() {
291
+ paused = true;
292
+ },
293
+ resume() {
294
+ paused = false;
295
+ },
296
+ hold() {
297
+ held = true;
298
+ },
299
+ release() {
300
+ held = false;
301
+ },
302
+ serialize() {
303
+ return {
304
+ absoluteMinutes: absolute,
305
+ paused
306
+ };
307
+ }
308
+ };
309
+ }
127
310
  // src/tier-resolve.ts
128
311
  /**
129
312
  * Returns the highest tier whose `at` threshold is met or exceeded by `tally`,
@@ -134,13 +317,8 @@ function rollDrop(table, rollTable01, rollChance01, chancePerRoll, pity, thresho
134
317
  * Ties (identical `at`) are broken by iteration order (last entry wins).
135
318
  */
136
319
  function resolveTier(entries, tally) {
137
- let best = null;
138
- let bestAt = Number.NEGATIVE_INFINITY;
139
- for (const e of entries) if (tally >= e.at && e.at >= bestAt) {
140
- best = e.tier;
141
- bestAt = e.at;
142
- }
143
- return best;
320
+ const i = resolveTierIndex(entries, tally);
321
+ return i < 0 ? null : entries[i].tier;
144
322
  }
145
323
  /**
146
324
  * Returns the index (0-based) of the highest satisfied tier entry,
@@ -238,6 +416,7 @@ function createUpgradeTrack(config) {
238
416
  }
239
417
  exports.createCollectibleRegistry = createCollectibleRegistry;
240
418
  exports.createDropTable = createDropTable;
419
+ exports.createGameClock = createGameClock;
241
420
  exports.createUnlockDag = createUnlockDag;
242
421
  exports.createUpgradeTrack = createUpgradeTrack;
243
422
  exports.resolveTier = resolveTier;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["weightedIndexBy"],"sources":["../src/collectible-registry.ts","../src/drop-roll.ts","../src/tier-resolve.ts","../src/unlock-dag.ts","../src/upgrade-track.ts"],"sourcesContent":["/**\n * Collectible-unlock registry: immutable unlock-set + partition + capstone.\n *\n * The registry is generic over a string id type.\n * All operations return new registry instances — no mutation.\n */\n\nexport interface CollectibleRegistry<K extends string> {\n /** The complete set of collectible ids (excluding the capstone). */\n readonly all: ReadonlySet<K>;\n /** The capstone id, or null when no capstone is defined. */\n readonly capstoneId: K | null;\n /** Currently unlocked ids (a subset of `all`, plus capstone when triggered). */\n readonly unlocked: ReadonlySet<K>;\n /** True when every collectible in `all` is unlocked. */\n readonly isComplete: boolean;\n /**\n * True when the capstone is in `unlocked`. Always false when `capstoneId`\n * is null.\n */\n readonly isCapstone: boolean;\n /**\n * Returns a new registry with `id` added to `unlocked`. Idempotent.\n * Automatically adds the capstone when `isComplete` transitions to true\n * and a capstone is defined.\n * Throws on unknown ids (not in `all` and not the capstoneId).\n */\n unlock(id: K): CollectibleRegistry<K>;\n /**\n * Partition the unlocked set into `{ have, missing }`.\n * `have` = ids in `all` that are in `unlocked` (capstone excluded).\n * `missing` = ids in `all` not yet unlocked.\n */\n partition(): { have: readonly K[]; missing: readonly K[] };\n /**\n * Returns all ids in `all` in insertion order.\n */\n list(): readonly K[];\n}\n\nfunction makeRegistry<K extends string>(\n all: ReadonlySet<K>,\n capstoneId: K | null,\n unlocked: ReadonlySet<K>,\n): CollectibleRegistry<K> {\n const isComplete = [...all].every((id) => unlocked.has(id));\n const isCapstone = capstoneId !== null && unlocked.has(capstoneId);\n\n function unlock(id: K): CollectibleRegistry<K> {\n if (!all.has(id) && id !== capstoneId) {\n throw new Error(`CollectibleRegistry: unknown id \"${String(id)}\"`);\n }\n if (unlocked.has(id)) return reg;\n const next = new Set<K>(unlocked);\n next.add(id);\n // Auto-unlock capstone on completion.\n if (capstoneId !== null && !next.has(capstoneId)) {\n const allComplete = [...all].every((k) => next.has(k));\n if (allComplete) next.add(capstoneId);\n }\n return makeRegistry(all, capstoneId, next);\n }\n\n function partition(): { have: readonly K[]; missing: readonly K[] } {\n const have: K[] = [];\n const missing: K[] = [];\n for (const id of all) {\n if (unlocked.has(id)) have.push(id);\n else missing.push(id);\n }\n return { have, missing };\n }\n\n function list(): readonly K[] {\n return [...all];\n }\n\n const reg: CollectibleRegistry<K> = {\n all,\n capstoneId,\n unlocked,\n isComplete,\n isCapstone,\n unlock,\n partition,\n list,\n };\n return reg;\n}\n\n/**\n * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an\n * optional `capstoneId`.\n *\n * Duplicate ids in `ids` throw. `capstoneId` may equal one of the ids in `ids`\n * (it is tracked as a separate gate — the capstone fires only on full completion,\n * not by direct unlock through `ids` membership alone).\n *\n * The capstone MUST be distinct from all ids in `ids` — if not, the capstone\n * unlock auto-fires on full completion regardless of whether the capstone id\n * was directly unlocked via the `ids` set, which would be semantically ambiguous.\n */\nexport function createCollectibleRegistry<K extends string>(\n ids: readonly K[],\n capstoneId?: K,\n): CollectibleRegistry<K> {\n const all = new Set<K>();\n for (const id of ids) {\n if (all.has(id)) {\n throw new Error(`createCollectibleRegistry: duplicate id \"${String(id)}\"`);\n }\n all.add(id);\n }\n return makeRegistry<K>(all, capstoneId ?? null, new Set<K>());\n}\n","/**\n * Pity-aware weighted drop roller.\n *\n * `rollInto` is zero-alloc on the hot path: the `weightAt` accessor and the\n * `dryPrev` scratch buffer are allocated once inside the factory closure and\n * reused across calls. The `out` parameter receives the result in-place;\n * aliasing `out.pity` against the input `pity` is safe because the function\n * reads all input pity fields into `dryPrev` before writing any output pity\n * fields.\n */\n\nimport { weightedIndexBy } from '@flare-engine/math';\n\nexport interface DropEntry<K extends string> {\n readonly item: K;\n readonly weight: number;\n}\n\n/**\n * Per-item dry-roll counters feeding the pity guarantees.\n * Keys are the item ids whose pity is being tracked.\n */\nexport type DropPity<K extends string> = Record<K, number>;\n\nexport interface DropRollOut<K extends string> {\n item: K | 'none';\n pity: DropPity<K>;\n}\n\n/**\n * A `DropTable` is a factory that closes over a weight accessor to avoid\n * per-call allocations. Create once; reuse across frames.\n */\nexport interface DropTable<K extends string> {\n readonly entries: readonly DropEntry<K>[];\n /**\n * Zero-alloc weighted drop. Writes result into `out`.\n *\n * Algorithm:\n * 1. Check pity thresholds (first matching pity item fires unconditionally).\n * 2. If no pity fires and `rollChance01 >= chancePerRoll`, result = 'none'.\n * 3. Otherwise pick from the weighted table filtered by `isAllowed`.\n * An all-gated pool (every entry filtered out) fizzles to 'none'.\n *\n * `out.pity` counters reset for the dropped item, advance by 1 for all others.\n * Aliasing `out.pity` against the input `pity` is safe.\n */\n rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void;\n}\n\n/**\n * Creates a `DropTable` from `entries`.\n * The `weightAt` accessor and scratch buffer are allocated once inside this\n * factory (not per-roll).\n */\nexport function createDropTable<K extends string>(entries: readonly DropEntry<K>[]): DropTable<K> {\n // Closed-over filter state — set before each weightedIndexBy call.\n // `var` so the binding is function-scoped and hoisted; reassigned each call.\n var currentIsAllowed: (item: K) => boolean = () => true;\n\n const weightAt = (entry: DropEntry<K>): number =>\n currentIsAllowed(entry.item) ? entry.weight : 0;\n\n // Pre-allocated scratch buffer: stores dry counts read from `pity` before\n // any writes, enabling safe aliasing of out.pity === pity.\n const dryPrev = new Float32Array(entries.length);\n\n function rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void {\n let picked: K | 'none' = 'none';\n\n // Read all pity inputs into scratch before writing any output (aliasing guard).\n for (let i = 0; i < entries.length; i++) {\n dryPrev[i] = pity[(entries[i] as DropEntry<K>).item] ?? 0;\n }\n\n // Pity check — first item whose dry count + 1 meets or exceeds threshold.\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n const threshold = thresholds[e.item];\n if (threshold !== undefined && isAllowed(e.item) && (dryPrev[i] as number) + 1 >= threshold) {\n picked = e.item;\n break;\n }\n }\n\n // Chance gate + weighted pick.\n if (picked === 'none') {\n if (rollChance01 < chancePerRoll) {\n currentIsAllowed = isAllowed;\n // Compute allowed total to detect an all-gated pool (fizzles to 'none').\n let allowedTotal = 0;\n for (let i = 0; i < entries.length; i++) {\n allowedTotal += weightAt(entries[i] as DropEntry<K>);\n }\n if (allowedTotal > 0) {\n const idx = weightedIndexBy(entries, weightAt, rollTable01);\n const entry = entries[idx];\n if (entry !== undefined) picked = entry.item;\n }\n }\n }\n\n // Write output — pity counters.\n out.item = picked;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n (out.pity as Record<string, number>)[e.item] =\n picked === e.item ? 0 : (dryPrev[i] as number) + 1;\n }\n }\n\n return { entries, rollInto };\n}\n\n/**\n * Allocating convenience wrapper. Creates a fresh pity object and returns both.\n * Use `table.rollInto` on the hot path; this is for tests and cold-path setup.\n */\nexport function rollDrop<K extends string>(\n table: DropTable<K>,\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed?: (item: K) => boolean,\n): DropRollOut<K> {\n const out: DropRollOut<K> = { item: 'none', pity: { ...pity } };\n table.rollInto(\n rollTable01,\n rollChance01,\n chancePerRoll,\n pity,\n thresholds,\n isAllowed ?? (() => true),\n out,\n );\n return out;\n}\n","/**\n * Tier resolution: \"highest threshold crossed by a running tally.\"\n *\n * The tally tiers are caller-defined (generic `T`) so the same resolver\n * works for score brackets, XP thresholds, unlock gates, etc.\n */\n\nexport interface TierEntry<T> {\n /** Minimum tally value (inclusive) required to reach this tier. */\n readonly at: number;\n /** The tier value associated with this threshold. */\n readonly tier: T;\n}\n\n/**\n * Returns the highest tier whose `at` threshold is met or exceeded by `tally`,\n * or `null` when `tally` is below all thresholds.\n *\n * `entries` need not be sorted — the function scans all entries and returns the\n * one with the largest `at` that satisfies `tally >= at`.\n * Ties (identical `at`) are broken by iteration order (last entry wins).\n */\nexport function resolveTier<T>(entries: readonly TierEntry<T>[], tally: number): T | null {\n let best: T | null = null;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (const e of entries) {\n if (tally >= e.at && e.at >= bestAt) {\n best = e.tier;\n bestAt = e.at;\n }\n }\n return best;\n}\n\n/**\n * Returns the index (0-based) of the highest satisfied tier entry,\n * or -1 when `tally` is below all thresholds.\n * Same tie-breaking rules as `resolveTier`.\n */\nexport function resolveTierIndex<T>(entries: readonly TierEntry<T>[], tally: number): number {\n let bestIdx = -1;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i];\n if (e !== undefined && tally >= e.at && e.at >= bestAt) {\n bestIdx = i;\n bestAt = e.at;\n }\n }\n return bestIdx;\n}\n","/**\n * Prerequisite DAG for unlock/progression graphs.\n *\n * The graph is directed and acyclic by construction (caller contract — no runtime cycle\n * detection). Nodes are string ids; edges are \"requires\" lists.\n */\n\nexport interface DagNode {\n /** Unique string id for this node. */\n readonly id: string;\n /** Ids of nodes that must be in the cleared set before this node unlocks. */\n readonly requires: readonly string[];\n}\n\nexport interface UnlockDag {\n readonly nodes: ReadonlyMap<string, DagNode>;\n /**\n * Whether `id` is unlocked given the set of cleared (previously unlocked) ids.\n * A node with no requirements is always unlocked.\n * An unknown id returns false.\n */\n isUnlocked(cleared: ReadonlySet<string>, id: string): boolean;\n /**\n * The frontier: all nodes whose requirements are fully satisfied by `cleared`,\n * but which are NOT yet in `cleared`. Returned as a sorted array (stable\n * insertion order from `nodes`).\n */\n frontier(cleared: ReadonlySet<string>): readonly string[];\n /**\n * All nodes currently unlocked by `cleared` (including those already in\n * `cleared`). Returned as a sorted array (stable insertion order).\n */\n allUnlocked(cleared: ReadonlySet<string>): readonly string[];\n}\n\n/**\n * Creates an `UnlockDag` from `nodes`.\n * Duplicate ids throw. Unknown `requires` ids are silently tolerated — a node\n * whose prerequisite id doesn't exist in the graph is simply never satisfiable.\n */\nexport function createUnlockDag(nodes: readonly DagNode[]): UnlockDag {\n const map = new Map<string, DagNode>();\n for (const node of nodes) {\n if (map.has(node.id)) {\n throw new Error(`createUnlockDag: duplicate node id \"${node.id}\"`);\n }\n map.set(node.id, node);\n }\n\n function isUnlocked(cleared: ReadonlySet<string>, id: string): boolean {\n const node = map.get(id);\n if (!node) return false;\n for (const req of node.requires) {\n if (!cleared.has(req)) return false;\n }\n return true;\n }\n\n function frontier(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (!cleared.has(id) && isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n function allUnlocked(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n return { nodes: map, isUnlocked, frontier, allUnlocked };\n}\n","/**\n * Geometric upgrade track with an immutable buy operation.\n * price(level) = round(base × growth^level) — the next-level cost from `level`.\n * Consolidates the common geometric-cost upgrade pattern.\n */\n\nexport interface UpgradeTrackConfig {\n /** Base price at level 0 → 1. */\n readonly base: number;\n /** Multiplicative growth factor per level. */\n readonly growth: number;\n /** Hard level cap (inclusive). */\n readonly cap: number;\n}\n\nexport interface UpgradeBuyResult {\n readonly ok: boolean;\n readonly wallet: number;\n readonly level: number;\n}\n\nexport interface UpgradeTrack {\n readonly config: UpgradeTrackConfig;\n /**\n * Cost to advance from `currentLevel` to `currentLevel + 1`.\n * Returns Infinity when at or above cap.\n */\n price(currentLevel: number): number;\n /** Whether `wallet` is sufficient and `currentLevel` is below cap. */\n canBuy(wallet: number, currentLevel: number): boolean;\n /**\n * Pure spend: deduct `price(currentLevel)` from `wallet` and return\n * the new state. Returns `{ ok: false, wallet, level }` when blocked.\n */\n buy(wallet: number, currentLevel: number): UpgradeBuyResult;\n /**\n * Fold all per-level stat deltas into a running accumulator.\n * `getLevel` is a caller-supplied reader so the resolver is unit-testable\n * without any save/store dep. `deltas` maps a stat key to the per-level delta;\n * `base` is the starting value for each key.\n * Returns a plain Record with the accumulated values.\n */\n resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number>;\n}\n\n/**\n * Returns an `UpgradeTrack` backed by `config`.\n * The returned object is a plain object (no class) — safe to freeze or copy.\n */\nexport function createUpgradeTrack(config: UpgradeTrackConfig): UpgradeTrack {\n function price(currentLevel: number): number {\n if (currentLevel >= config.cap) return Number.POSITIVE_INFINITY;\n return Math.round(config.base * config.growth ** currentLevel);\n }\n\n function canBuy(wallet: number, currentLevel: number): boolean {\n if (currentLevel >= config.cap) return false;\n return wallet >= price(currentLevel);\n }\n\n function buy(wallet: number, currentLevel: number): UpgradeBuyResult {\n if (!canBuy(wallet, currentLevel)) {\n return { ok: false, wallet, level: currentLevel };\n }\n return { ok: true, wallet: wallet - price(currentLevel), level: currentLevel + 1 };\n }\n\n function resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number> {\n const out = {} as Record<K, number>;\n for (const key of Object.keys(base) as K[]) {\n const level = Math.max(0, Math.floor(getLevel(key)));\n out[key] = (base[key] ?? 0) + (deltas[key] ?? 0) * level;\n }\n return out;\n }\n\n return { config, price, canBuy, buy, resolveStats };\n}\n"],"mappings":";;;AAwCA,SAAS,aACP,KACA,YACA,UACwB;CACxB,MAAM,aAAa,CAAC,GAAG,GAAG,CAAC,CAAC,OAAO,OAAO,SAAS,IAAI,EAAE,CAAC;CAC1D,MAAM,aAAa,eAAe,QAAQ,SAAS,IAAI,UAAU;CAEjE,SAAS,OAAO,IAA+B;EAC7C,IAAI,CAAC,IAA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CAC3E,SAAS,MAAM,cAA8B;EAC3C,IAAI,gBAAgB,OAAO,KAAK,OAAO,OAAO;EAC9C,OAAO,KAAK,MAAM,OAAO,OAAO,OAAO,UAAU,YAAY;CAC/D;CAEA,SAAS,OAAO,QAAgB,cAA+B;EAC7D,IAAI,gBAAgB,OAAO,KAAK,OAAO;EACvC,OAAO,UAAU,MAAM,YAAY;CACrC;CAEA,SAAS,IAAI,QAAgB,cAAwC;EACnE,IAAI,CAAC,OAAO,QAAQ,YAAY,GAC9B,OAAO;GAAE,IAAI;GAAO;GAAQ,OAAO;EAAa;EAElD,OAAO;GAAE,IAAI;GAAM,QAAQ,SAAS,MAAM,YAAY;GAAG,OAAO,eAAe;EAAE;CACnF;CAEA,SAAS,aACP,MACA,QACA,UACmB;EACnB,MAAM,MAAM,CAAC;EACb,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAAU;GAC1C,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,GAAG,CAAC,CAAC;GACnD,IAAI,QAAQ,KAAK,QAAQ,MAAM,OAAO,QAAQ,KAAK;EACrD;EACA,OAAO;CACT;CAEA,OAAO;EAAE;EAAQ;EAAO;EAAQ;EAAK;CAAa;AACpD"}
1
+ {"version":3,"file":"index.js","names":["weightedIndexBy"],"sources":["../src/collectible-registry.ts","../src/drop-roll.ts","../src/game-clock.ts","../src/tier-resolve.ts","../src/unlock-dag.ts","../src/upgrade-track.ts"],"sourcesContent":["/**\n * Collectible-unlock registry: immutable unlock-set + partition + capstone.\n *\n * The registry is generic over a string id type.\n * All operations return new registry instances — no mutation.\n */\n\nexport interface CollectibleRegistry<K extends string> {\n /** The complete set of collectible ids (excluding the capstone). */\n readonly all: ReadonlySet<K>;\n /** The capstone id, or null when no capstone is defined. */\n readonly capstoneId: K | null;\n /** Currently unlocked ids (a subset of `all`, plus capstone when triggered). */\n readonly unlocked: ReadonlySet<K>;\n /** True when every collectible in `all` is unlocked. */\n readonly isComplete: boolean;\n /**\n * True when the capstone is in `unlocked`. Always false when `capstoneId`\n * is null.\n */\n readonly isCapstone: boolean;\n /**\n * Returns a new registry with `id` added to `unlocked`. Idempotent.\n * Automatically adds the capstone when `isComplete` transitions to true\n * and a capstone is defined.\n * Throws on unknown ids (not in `all` and not the capstoneId).\n */\n unlock(id: K): CollectibleRegistry<K>;\n /**\n * Partition the unlocked set into `{ have, missing }`.\n * `have` = ids in `all` that are in `unlocked` (capstone excluded).\n * `missing` = ids in `all` not yet unlocked.\n */\n partition(): { have: readonly K[]; missing: readonly K[] };\n /**\n * Returns all ids in `all` in insertion order.\n */\n list(): readonly K[];\n}\n\nfunction makeRegistry<K extends string>(\n all: ReadonlySet<K>,\n capstoneId: K | null,\n unlocked: ReadonlySet<K>,\n): CollectibleRegistry<K> {\n const isComplete = [...all].every((id) => unlocked.has(id));\n const isCapstone = capstoneId !== null && unlocked.has(capstoneId);\n\n function unlock(id: K): CollectibleRegistry<K> {\n if (!all.has(id) && id !== capstoneId) {\n throw new Error(`CollectibleRegistry: unknown id \"${String(id)}\"`);\n }\n if (unlocked.has(id)) return reg;\n const next = new Set<K>(unlocked);\n next.add(id);\n // Auto-unlock capstone on completion.\n if (capstoneId !== null && !next.has(capstoneId)) {\n const allComplete = [...all].every((k) => next.has(k));\n if (allComplete) next.add(capstoneId);\n }\n return makeRegistry(all, capstoneId, next);\n }\n\n function partition(): { have: readonly K[]; missing: readonly K[] } {\n const have: K[] = [];\n const missing: K[] = [];\n for (const id of all) {\n if (unlocked.has(id)) have.push(id);\n else missing.push(id);\n }\n return { have, missing };\n }\n\n function list(): readonly K[] {\n return [...all];\n }\n\n const reg: CollectibleRegistry<K> = {\n all,\n capstoneId,\n unlocked,\n isComplete,\n isCapstone,\n unlock,\n partition,\n list,\n };\n return reg;\n}\n\n/**\n * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an\n * optional `capstoneId`.\n *\n * Duplicate ids in `ids` throw. The capstone is unlocked automatically once every\n * id in `ids` is unlocked, and `unlock(capstoneId)` also unlocks it directly;\n * either way `isCapstone` becomes true.\n *\n * Keep `capstoneId` out of `ids` for a capstone that marks completion. If it is\n * listed in `ids`, it is an ordinary member of the set: `isComplete` needs it,\n * `isCapstone` turns true as soon as it is unlocked, and the automatic unlock never\n * has anything to add.\n */\nexport function createCollectibleRegistry<K extends string>(\n ids: readonly K[],\n capstoneId?: K,\n): CollectibleRegistry<K> {\n const all = new Set<K>();\n for (const id of ids) {\n if (all.has(id)) {\n throw new Error(`createCollectibleRegistry: duplicate id \"${String(id)}\"`);\n }\n all.add(id);\n }\n return makeRegistry<K>(all, capstoneId ?? null, new Set<K>());\n}\n","/**\n * Pity-aware weighted drop roller.\n *\n * `rollInto` is zero-alloc on the hot path: the `weightAt` accessor and the\n * `dryPrev` scratch buffer are allocated once inside the factory closure and\n * reused across calls. The `out` parameter receives the result in-place;\n * aliasing `out.pity` against the input `pity` is safe because the function\n * reads all input pity fields into `dryPrev` before writing any output pity\n * fields.\n */\n\nimport { weightedIndexBy } from '@flare-engine/math';\n\nexport interface DropEntry<K extends string> {\n readonly item: K;\n readonly weight: number;\n}\n\n/**\n * Per-item dry-roll counters feeding the pity guarantees.\n * Keys are the item ids whose pity is being tracked.\n */\nexport type DropPity<K extends string> = Record<K, number>;\n\nexport interface DropRollOut<K extends string> {\n item: K | 'none';\n pity: DropPity<K>;\n}\n\n/**\n * A `DropTable` is a factory that closes over a weight accessor to avoid\n * per-call allocations. Create once; reuse across frames.\n */\nexport interface DropTable<K extends string> {\n readonly entries: readonly DropEntry<K>[];\n /**\n * Zero-alloc weighted drop. Writes result into `out`.\n *\n * Algorithm:\n * 1. Check pity thresholds (first matching pity item fires unconditionally).\n * 2. If no pity fires and `rollChance01 >= chancePerRoll`, result = 'none'.\n * 3. Otherwise pick from the weighted table filtered by `isAllowed`.\n * An all-gated pool (every entry filtered out) fizzles to 'none'.\n *\n * `out.pity` counters reset for the dropped item, advance by 1 for all others.\n * Aliasing `out.pity` against the input `pity` is safe.\n */\n rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void;\n}\n\n/**\n * Creates a `DropTable` from `entries`.\n * The `weightAt` accessor and scratch buffer are allocated once inside this\n * factory (not per-roll).\n */\nexport function createDropTable<K extends string>(entries: readonly DropEntry<K>[]): DropTable<K> {\n // Closed-over filter state — set before each weightedIndexBy call.\n // `var` so the binding is function-scoped and hoisted; reassigned each call.\n var currentIsAllowed: (item: K) => boolean = () => true;\n\n const weightAt = (entry: DropEntry<K>): number =>\n currentIsAllowed(entry.item) ? entry.weight : 0;\n\n // Pre-allocated scratch buffer: stores dry counts read from `pity` before\n // any writes, enabling safe aliasing of out.pity === pity.\n const dryPrev = new Float32Array(entries.length);\n\n function rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void {\n let picked: K | 'none' = 'none';\n\n // Read all pity inputs into scratch before writing any output (aliasing guard).\n for (let i = 0; i < entries.length; i++) {\n dryPrev[i] = pity[(entries[i] as DropEntry<K>).item] ?? 0;\n }\n\n // Pity check — first item whose dry count + 1 meets or exceeds threshold.\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n const threshold = thresholds[e.item];\n if (threshold !== undefined && isAllowed(e.item) && (dryPrev[i] as number) + 1 >= threshold) {\n picked = e.item;\n break;\n }\n }\n\n // Chance gate + weighted pick.\n if (picked === 'none') {\n if (rollChance01 < chancePerRoll) {\n currentIsAllowed = isAllowed;\n // Compute allowed total to detect an all-gated pool (fizzles to 'none').\n let allowedTotal = 0;\n for (let i = 0; i < entries.length; i++) {\n allowedTotal += weightAt(entries[i] as DropEntry<K>);\n }\n if (allowedTotal > 0) {\n const idx = weightedIndexBy(entries, weightAt, rollTable01);\n const entry = entries[idx];\n if (entry !== undefined) picked = entry.item;\n }\n }\n }\n\n // Write output — pity counters.\n out.item = picked;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n (out.pity as Record<string, number>)[e.item] =\n picked === e.item ? 0 : (dryPrev[i] as number) + 1;\n }\n }\n\n return { entries, rollInto };\n}\n\n/**\n * Allocating convenience wrapper. Creates a fresh pity object and returns both.\n * Use `table.rollInto` on the hot path; this is for tests and cold-path setup.\n */\nexport function rollDrop<K extends string>(\n table: DropTable<K>,\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed?: (item: K) => boolean,\n): DropRollOut<K> {\n const out: DropRollOut<K> = { item: 'none', pity: { ...pity } };\n table.rollInto(\n rollTable01,\n rollChance01,\n chancePerRoll,\n pity,\n thresholds,\n isAllowed ?? (() => true),\n out,\n );\n return out;\n}\n","/**\n * Game-day clock with per-segment real-time rates.\n * A day is 1440 game minutes split into ordered segments; each segment\n * runs at its own `secondsPerGameHour`. Supports pause, hold (stop at the\n * next phase boundary), manual advance, skip-to-segment, change callbacks,\n * and a plain serializable state.\n */\n\nconst MINUTES_PER_DAY = 1440;\n\nexport interface GameClockSegment {\n /** Segment name, e.g. 'day', 'dusk'. May repeat (a night that wraps midnight is two rows). */\n readonly name: string;\n /** Coarser grouping, e.g. 'day' | 'night'. */\n readonly phase: string;\n /** Minute of the game day at which the segment starts, integer 0..1439. */\n readonly startMinute: number;\n /** Real seconds per game hour while in this segment. */\n readonly secondsPerGameHour: number;\n}\n\nexport interface GameClockConfig {\n /** Ordered by `startMinute`; the first must start at 0. The last runs to 1440. */\n readonly segments: readonly GameClockSegment[];\n readonly onSegmentChange?: (segment: string, previous: string) => void;\n readonly onPhaseChange?: (phase: string, previous: string) => void;\n}\n\nexport interface GameClockState {\n readonly absoluteMinutes: number;\n readonly paused: boolean;\n}\n\nexport interface GameClock {\n /** Game minutes since day 0 00:00. Fractional, never decreases. */\n readonly absoluteMinutes: number;\n /** `floor(absoluteMinutes / 1440)`. */\n readonly day: number;\n /** 0..23. */\n readonly hour: number;\n /** 0..59, integer. */\n readonly minute: number;\n readonly segment: string;\n readonly phase: string;\n readonly paused: boolean;\n readonly held: boolean;\n /**\n * Advance by `dt` real seconds. No-op while paused, or when `dt` is not finite or <= 0.\n * Throws `RangeError` when `dt` could carry `absoluteMinutes` past `Number.MAX_SAFE_INTEGER`.\n */\n update(dt: number): void;\n /**\n * Advance by `n` game minutes, even while paused. Throws `RangeError` when `n` is negative or\n * not finite, or when `absoluteMinutes + n` exceeds `Number.MAX_SAFE_INTEGER`.\n */\n advanceMinutes(n: number): void;\n /**\n * Jump forward to the next start of `segmentName`, strictly after now, or to now when the\n * clock sits on that start without having entered it (held on the boundary, then released).\n * Throws on an unknown name.\n */\n skipTo(segmentName: string): void;\n pause(): void;\n resume(): void;\n /** Stop at the next phase boundary and stay there until `release()`. */\n hold(): void;\n release(): void;\n /** Allocates a fresh state object (cold path). `held` is not persisted. */\n serialize(): GameClockState;\n}\n\nfunction validateSegments(segments: readonly GameClockSegment[]): void {\n if (segments.length === 0) {\n throw new Error('createGameClock: segments must not be empty');\n }\n const first = segments[0] as GameClockSegment;\n if (first.startMinute !== 0) {\n throw new Error(\n `createGameClock: first segment must start at minute 0, got ${first.startMinute}`,\n );\n }\n let previousStart = -1;\n for (let i = 0; i < segments.length; i++) {\n const seg = segments[i] as GameClockSegment;\n const start = seg.startMinute;\n if (!Number.isInteger(start) || start < 0 || start >= MINUTES_PER_DAY) {\n throw new Error(\n `createGameClock: segment ${i} (\"${seg.name}\") startMinute must be an integer in 0..1439, got ${start}`,\n );\n }\n if (start <= previousStart) {\n throw new Error(\n `createGameClock: segment ${i} (\"${seg.name}\") startMinute ${start} must be greater than the previous start ${previousStart}`,\n );\n }\n previousStart = start;\n const rate = seg.secondsPerGameHour;\n if (!Number.isFinite(rate) || rate <= 0) {\n throw new Error(\n `createGameClock: segment ${i} (\"${seg.name}\") secondsPerGameHour must be finite and > 0, got ${rate}`,\n );\n }\n }\n}\n\n/**\n * Returns a `GameClock` backed by `config`, optionally restored from `state`.\n * The returned object is a plain object with getters (no class).\n */\nexport function createGameClock(config: GameClockConfig, state?: GameClockState): GameClock {\n const segments = config.segments;\n validateSegments(segments);\n const count = segments.length;\n const onSegmentChange = config.onSegmentChange;\n const onPhaseChange = config.onPhaseChange;\n\n // Per-segment end minute: the next segment's start, or 1440 for the last.\n const ends = new Float64Array(count);\n let fastestRate = Number.POSITIVE_INFINITY;\n for (let i = 0; i < count; i++) {\n ends[i] = i + 1 < count ? (segments[i + 1] as GameClockSegment).startMinute : MINUTES_PER_DAY;\n fastestRate = Math.min(fastestRate, (segments[i] as GameClockSegment).secondsPerGameHour);\n }\n\n let absolute = 0;\n let paused = false;\n let held = false;\n let index = 0;\n\n if (state !== undefined) {\n if (\n !Number.isFinite(state.absoluteMinutes) ||\n state.absoluteMinutes < 0 ||\n state.absoluteMinutes > Number.MAX_SAFE_INTEGER\n ) {\n throw new Error(\n `createGameClock: state.absoluteMinutes must be finite, >= 0 and <= Number.MAX_SAFE_INTEGER, got ${state.absoluteMinutes}`,\n );\n }\n if (typeof state.paused !== 'boolean') {\n throw new Error(\n `createGameClock: state.paused must be a boolean, got ${String(state.paused)}`,\n );\n }\n absolute = state.absoluteMinutes;\n paused = state.paused;\n const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;\n for (let i = 0; i < count; i++) {\n if ((segments[i] as GameClockSegment).startMinute <= minuteOfDay) index = i;\n }\n }\n\n /**\n * Move from the current segment to the next one, firing callbacks.\n * Returns false (and leaves everything untouched) when held and the next\n * segment opens a different phase.\n */\n function cross(): boolean {\n const next = index + 1 < count ? index + 1 : 0;\n const prev = segments[index] as GameClockSegment;\n const nextSeg = segments[next] as GameClockSegment;\n const phaseChanges = nextSeg.phase !== prev.phase;\n if (held && phaseChanges) return false;\n index = next;\n if (nextSeg.name !== prev.name && onSegmentChange !== undefined) {\n onSegmentChange(nextSeg.name, prev.name);\n }\n if (phaseChanges && onPhaseChange !== undefined) {\n onPhaseChange(nextSeg.phase, prev.phase);\n }\n return true;\n }\n\n /** Absolute minute at which the current segment ends (an integer while below 2^53). */\n function currentBoundary(): number {\n let day = Math.floor(absolute / MINUTES_PER_DAY);\n // Sitting on the midnight boundary with the last segment still current\n // (a held clock): that is minute 1440 of the previous day.\n if (absolute - day * MINUTES_PER_DAY < (segments[index] as GameClockSegment).startMinute) {\n day -= 1;\n }\n return day * MINUTES_PER_DAY + (ends[index] as number);\n }\n\n /**\n * Game-minute advance to an absolute target. Each boundary is compared against\n * the target itself rather than a carried remainder, so a target that equals a\n * boundary always lands on it and crosses (unless held).\n */\n function advanceTo(target: number): void {\n for (;;) {\n const boundary = currentBoundary();\n if (target < boundary) {\n // A callback may already have advanced the clock past `target`.\n if (target > absolute) absolute = target;\n return;\n }\n absolute = boundary;\n if (!cross()) return;\n }\n }\n\n function update(dt: number): void {\n if (paused || !Number.isFinite(dt) || dt <= 0) return;\n if (absolute + (dt * 60) / fastestRate > Number.MAX_SAFE_INTEGER) {\n throw new RangeError(\n `GameClock.update: dt ${dt} would carry absoluteMinutes past Number.MAX_SAFE_INTEGER`,\n );\n }\n // Rates differ per segment, so real seconds are carried as a remainder.\n let remaining = dt;\n for (;;) {\n const boundary = currentBoundary();\n const toBoundary = boundary - absolute;\n if (toBoundary > 0) {\n const rate = (segments[index] as GameClockSegment).secondsPerGameHour;\n const cost = (toBoundary * rate) / 60;\n if (remaining < cost) {\n const next = absolute + (remaining * 60) / rate;\n if (next < boundary) {\n absolute = next;\n return;\n }\n // Rounding reached the boundary: land on it and cross, like an exact step.\n remaining = 0;\n } else {\n remaining -= cost;\n }\n absolute = boundary;\n }\n // A callback that paused the clock stops this step at the boundary just crossed.\n if (!cross() || paused) return;\n }\n }\n\n function advanceMinutes(n: number): void {\n if (!Number.isFinite(n) || n < 0) {\n throw new RangeError(`GameClock.advanceMinutes: n must be finite and >= 0, got ${n}`);\n }\n const target = absolute + n;\n if (target > Number.MAX_SAFE_INTEGER) {\n throw new RangeError(\n `GameClock.advanceMinutes: absoluteMinutes + n must not exceed Number.MAX_SAFE_INTEGER, got ${target}`,\n );\n }\n advanceTo(target);\n }\n\n function skipTo(segmentName: string): void {\n const day = Math.floor(absolute / MINUTES_PER_DAY);\n let target = Number.POSITIVE_INFINITY;\n for (let i = 0; i < count; i++) {\n const seg = segments[i] as GameClockSegment;\n if (seg.name !== segmentName) continue;\n let candidate = day * MINUTES_PER_DAY + seg.startMinute;\n // A start the clock sits on without having entered it (held on the boundary,\n // then released) is still ahead; one it has entered is a full day away.\n if (candidate < absolute || (candidate === absolute && index === i)) {\n candidate += MINUTES_PER_DAY;\n }\n if (candidate < target) target = candidate;\n }\n if (target === Number.POSITIVE_INFINITY) {\n throw new Error(`GameClock.skipTo: unknown segment \"${segmentName}\"`);\n }\n advanceTo(target);\n }\n\n return {\n get absoluteMinutes() {\n return absolute;\n },\n get day() {\n return Math.floor(absolute / MINUTES_PER_DAY);\n },\n get hour() {\n const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;\n return Math.floor(minuteOfDay / 60);\n },\n get minute() {\n const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;\n return Math.floor(minuteOfDay - Math.floor(minuteOfDay / 60) * 60);\n },\n get segment() {\n return (segments[index] as GameClockSegment).name;\n },\n get phase() {\n return (segments[index] as GameClockSegment).phase;\n },\n get paused() {\n return paused;\n },\n get held() {\n return held;\n },\n update,\n advanceMinutes,\n skipTo,\n pause() {\n paused = true;\n },\n resume() {\n paused = false;\n },\n hold() {\n held = true;\n },\n release() {\n held = false;\n },\n serialize(): GameClockState {\n return { absoluteMinutes: absolute, paused };\n },\n };\n}\n","/**\n * Tier resolution: \"highest threshold crossed by a running tally.\"\n *\n * The tally tiers are caller-defined (generic `T`) so the same resolver\n * works for score brackets, XP thresholds, unlock gates, etc.\n */\n\nexport interface TierEntry<T> {\n /** Minimum tally value (inclusive) required to reach this tier. */\n readonly at: number;\n /** The tier value associated with this threshold. */\n readonly tier: T;\n}\n\n/**\n * Returns the highest tier whose `at` threshold is met or exceeded by `tally`,\n * or `null` when `tally` is below all thresholds.\n *\n * `entries` need not be sorted — the function scans all entries and returns the\n * one with the largest `at` that satisfies `tally >= at`.\n * Ties (identical `at`) are broken by iteration order (last entry wins).\n */\nexport function resolveTier<T>(entries: readonly TierEntry<T>[], tally: number): T | null {\n const i = resolveTierIndex(entries, tally);\n return i < 0 ? null : entries[i]!.tier;\n}\n\n/**\n * Returns the index (0-based) of the highest satisfied tier entry,\n * or -1 when `tally` is below all thresholds.\n * Same tie-breaking rules as `resolveTier`.\n */\nexport function resolveTierIndex<T>(entries: readonly TierEntry<T>[], tally: number): number {\n let bestIdx = -1;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i];\n if (e !== undefined && tally >= e.at && e.at >= bestAt) {\n bestIdx = i;\n bestAt = e.at;\n }\n }\n return bestIdx;\n}\n","/**\n * Prerequisite DAG for unlock/progression graphs.\n *\n * The graph is directed and acyclic by construction (caller contract — no runtime cycle\n * detection). Nodes are string ids; edges are \"requires\" lists.\n */\n\nexport interface DagNode {\n /** Unique string id for this node. */\n readonly id: string;\n /** Ids of nodes that must be in the cleared set before this node unlocks. */\n readonly requires: readonly string[];\n}\n\nexport interface UnlockDag {\n readonly nodes: ReadonlyMap<string, DagNode>;\n /**\n * Whether `id` is unlocked given the set of cleared (previously unlocked) ids.\n * A node with no requirements is always unlocked.\n * An unknown id returns false.\n */\n isUnlocked(cleared: ReadonlySet<string>, id: string): boolean;\n /**\n * The frontier: all nodes whose requirements are fully satisfied by `cleared`,\n * but which are NOT yet in `cleared`. Returned as a sorted array (stable\n * insertion order from `nodes`).\n */\n frontier(cleared: ReadonlySet<string>): readonly string[];\n /**\n * All nodes currently unlocked by `cleared` (including those already in\n * `cleared`). Returned as a sorted array (stable insertion order).\n */\n allUnlocked(cleared: ReadonlySet<string>): readonly string[];\n}\n\n/**\n * Creates an `UnlockDag` from `nodes`.\n * Duplicate ids throw. Unknown `requires` ids are silently tolerated — a node\n * whose prerequisite id doesn't exist in the graph is simply never satisfiable.\n */\nexport function createUnlockDag(nodes: readonly DagNode[]): UnlockDag {\n const map = new Map<string, DagNode>();\n for (const node of nodes) {\n if (map.has(node.id)) {\n throw new Error(`createUnlockDag: duplicate node id \"${node.id}\"`);\n }\n map.set(node.id, node);\n }\n\n function isUnlocked(cleared: ReadonlySet<string>, id: string): boolean {\n const node = map.get(id);\n if (!node) return false;\n for (const req of node.requires) {\n if (!cleared.has(req)) return false;\n }\n return true;\n }\n\n function frontier(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (!cleared.has(id) && isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n function allUnlocked(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n return { nodes: map, isUnlocked, frontier, allUnlocked };\n}\n","/**\n * Geometric upgrade track with an immutable buy operation.\n * price(level) = round(base × growth^level) — the next-level cost from `level`.\n * Consolidates the common geometric-cost upgrade pattern.\n */\n\nexport interface UpgradeTrackConfig {\n /** Base price at level 0 → 1. */\n readonly base: number;\n /** Multiplicative growth factor per level. */\n readonly growth: number;\n /** Hard level cap (inclusive). */\n readonly cap: number;\n}\n\nexport interface UpgradeBuyResult {\n readonly ok: boolean;\n readonly wallet: number;\n readonly level: number;\n}\n\nexport interface UpgradeTrack {\n readonly config: UpgradeTrackConfig;\n /**\n * Cost to advance from `currentLevel` to `currentLevel + 1`.\n * Returns Infinity when at or above cap.\n */\n price(currentLevel: number): number;\n /** Whether `wallet` is sufficient and `currentLevel` is below cap. */\n canBuy(wallet: number, currentLevel: number): boolean;\n /**\n * Pure spend: deduct `price(currentLevel)` from `wallet` and return\n * the new state. Returns `{ ok: false, wallet, level }` when blocked.\n */\n buy(wallet: number, currentLevel: number): UpgradeBuyResult;\n /**\n * Fold all per-level stat deltas into a running accumulator.\n * `getLevel` is a caller-supplied reader so the resolver is unit-testable\n * without any save/store dep. `deltas` maps a stat key to the per-level delta;\n * `base` is the starting value for each key.\n * Returns a plain Record with the accumulated values.\n */\n resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number>;\n}\n\n/**\n * Returns an `UpgradeTrack` backed by `config`.\n * The returned object is a plain object (no class) — safe to freeze or copy.\n */\nexport function createUpgradeTrack(config: UpgradeTrackConfig): UpgradeTrack {\n function price(currentLevel: number): number {\n if (currentLevel >= config.cap) return Number.POSITIVE_INFINITY;\n return Math.round(config.base * config.growth ** currentLevel);\n }\n\n function canBuy(wallet: number, currentLevel: number): boolean {\n if (currentLevel >= config.cap) return false;\n return wallet >= price(currentLevel);\n }\n\n function buy(wallet: number, currentLevel: number): UpgradeBuyResult {\n if (!canBuy(wallet, currentLevel)) {\n return { ok: false, wallet, level: currentLevel };\n }\n return { ok: true, wallet: wallet - price(currentLevel), level: currentLevel + 1 };\n }\n\n function resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number> {\n const out = {} as Record<K, number>;\n for (const key of Object.keys(base) as K[]) {\n const level = Math.max(0, Math.floor(getLevel(key)));\n out[key] = (base[key] ?? 0) + (deltas[key] ?? 0) * level;\n }\n return out;\n }\n\n return { config, price, canBuy, buy, resolveStats };\n}\n"],"mappings":";;;AAwCA,SAAS,aACP,KACA,YACA,UACwB;CACxB,MAAM,aAAa,CAAC,GAAG,GAAG,CAAC,CAAC,OAAO,OAAO,SAAS,IAAI,EAAE,CAAC;CAC1D,MAAM,aAAa,eAAe,QAAQ,SAAS,IAAI,UAAU;CAEjE,SAAS,OAA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,IAAI,QAAQ,KAAK,QAAQ,MAAM,OAAO,QAAQ,KAAK;EACrD;EACA,OAAO;CACT;CAEA,OAAO;EAAE;EAAQ;EAAO;EAAQ;EAAK;CAAa;AACpD"}
package/dist/index.mjs CHANGED
@@ -42,13 +42,14 @@ function makeRegistry(all, capstoneId, unlocked) {
42
42
  * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an
43
43
  * optional `capstoneId`.
44
44
  *
45
- * Duplicate ids in `ids` throw. `capstoneId` may equal one of the ids in `ids`
46
- * (it is tracked as a separate gate — the capstone fires only on full completion,
47
- * not by direct unlock through `ids` membership alone).
45
+ * Duplicate ids in `ids` throw. The capstone is unlocked automatically once every
46
+ * id in `ids` is unlocked, and `unlock(capstoneId)` also unlocks it directly;
47
+ * either way `isCapstone` becomes true.
48
48
  *
49
- * The capstone MUST be distinct from all ids in `ids` — if not, the capstone
50
- * unlock auto-fires on full completion regardless of whether the capstone id
51
- * was directly unlocked via the `ids` set, which would be semantically ambiguous.
49
+ * Keep `capstoneId` out of `ids` for a capstone that marks completion. If it is
50
+ * listed in `ids`, it is an ordinary member of the set: `isComplete` needs it,
51
+ * `isCapstone` turns true as soon as it is unlocked, and the automatic unlock never
52
+ * has anything to add.
52
53
  */
53
54
  function createCollectibleRegistry(ids, capstoneId) {
54
55
  const all = /* @__PURE__ */ new Set();
@@ -123,6 +124,188 @@ function rollDrop(table, rollTable01, rollChance01, chancePerRoll, pity, thresho
123
124
  table.rollInto(rollTable01, rollChance01, chancePerRoll, pity, thresholds, isAllowed ?? (() => true), out);
124
125
  return out;
125
126
  }
127
+ // src/game-clock.ts
128
+ /**
129
+ * Game-day clock with per-segment real-time rates.
130
+ * A day is 1440 game minutes split into ordered segments; each segment
131
+ * runs at its own `secondsPerGameHour`. Supports pause, hold (stop at the
132
+ * next phase boundary), manual advance, skip-to-segment, change callbacks,
133
+ * and a plain serializable state.
134
+ */
135
+ const MINUTES_PER_DAY = 1440;
136
+ function validateSegments(segments) {
137
+ if (segments.length === 0) throw new Error("createGameClock: segments must not be empty");
138
+ const first = segments[0];
139
+ if (first.startMinute !== 0) throw new Error(`createGameClock: first segment must start at minute 0, got ${first.startMinute}`);
140
+ let previousStart = -1;
141
+ for (let i = 0; i < segments.length; i++) {
142
+ const seg = segments[i];
143
+ const start = seg.startMinute;
144
+ if (!Number.isInteger(start) || start < 0 || start >= MINUTES_PER_DAY) throw new Error(`createGameClock: segment ${i} ("${seg.name}") startMinute must be an integer in 0..1439, got ${start}`);
145
+ if (start <= previousStart) throw new Error(`createGameClock: segment ${i} ("${seg.name}") startMinute ${start} must be greater than the previous start ${previousStart}`);
146
+ previousStart = start;
147
+ const rate = seg.secondsPerGameHour;
148
+ if (!Number.isFinite(rate) || rate <= 0) throw new Error(`createGameClock: segment ${i} ("${seg.name}") secondsPerGameHour must be finite and > 0, got ${rate}`);
149
+ }
150
+ }
151
+ /**
152
+ * Returns a `GameClock` backed by `config`, optionally restored from `state`.
153
+ * The returned object is a plain object with getters (no class).
154
+ */
155
+ function createGameClock(config, state) {
156
+ const segments = config.segments;
157
+ validateSegments(segments);
158
+ const count = segments.length;
159
+ const onSegmentChange = config.onSegmentChange;
160
+ const onPhaseChange = config.onPhaseChange;
161
+ const ends = new Float64Array(count);
162
+ let fastestRate = Number.POSITIVE_INFINITY;
163
+ for (let i = 0; i < count; i++) {
164
+ ends[i] = i + 1 < count ? segments[i + 1].startMinute : MINUTES_PER_DAY;
165
+ fastestRate = Math.min(fastestRate, segments[i].secondsPerGameHour);
166
+ }
167
+ let absolute = 0;
168
+ let paused = false;
169
+ let held = false;
170
+ let index = 0;
171
+ if (state !== void 0) {
172
+ if (!Number.isFinite(state.absoluteMinutes) || state.absoluteMinutes < 0 || state.absoluteMinutes > Number.MAX_SAFE_INTEGER) throw new Error(`createGameClock: state.absoluteMinutes must be finite, >= 0 and <= Number.MAX_SAFE_INTEGER, got ${state.absoluteMinutes}`);
173
+ if (typeof state.paused !== "boolean") throw new Error(`createGameClock: state.paused must be a boolean, got ${String(state.paused)}`);
174
+ absolute = state.absoluteMinutes;
175
+ paused = state.paused;
176
+ const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;
177
+ for (let i = 0; i < count; i++) if (segments[i].startMinute <= minuteOfDay) index = i;
178
+ }
179
+ /**
180
+ * Move from the current segment to the next one, firing callbacks.
181
+ * Returns false (and leaves everything untouched) when held and the next
182
+ * segment opens a different phase.
183
+ */
184
+ function cross() {
185
+ const next = index + 1 < count ? index + 1 : 0;
186
+ const prev = segments[index];
187
+ const nextSeg = segments[next];
188
+ const phaseChanges = nextSeg.phase !== prev.phase;
189
+ if (held && phaseChanges) return false;
190
+ index = next;
191
+ if (nextSeg.name !== prev.name && onSegmentChange !== void 0) onSegmentChange(nextSeg.name, prev.name);
192
+ if (phaseChanges && onPhaseChange !== void 0) onPhaseChange(nextSeg.phase, prev.phase);
193
+ return true;
194
+ }
195
+ /** Absolute minute at which the current segment ends (an integer while below 2^53). */
196
+ function currentBoundary() {
197
+ let day = Math.floor(absolute / MINUTES_PER_DAY);
198
+ if (absolute - day * MINUTES_PER_DAY < segments[index].startMinute) day -= 1;
199
+ return day * MINUTES_PER_DAY + ends[index];
200
+ }
201
+ /**
202
+ * Game-minute advance to an absolute target. Each boundary is compared against
203
+ * the target itself rather than a carried remainder, so a target that equals a
204
+ * boundary always lands on it and crosses (unless held).
205
+ */
206
+ function advanceTo(target) {
207
+ for (;;) {
208
+ const boundary = currentBoundary();
209
+ if (target < boundary) {
210
+ if (target > absolute) absolute = target;
211
+ return;
212
+ }
213
+ absolute = boundary;
214
+ if (!cross()) return;
215
+ }
216
+ }
217
+ function update(dt) {
218
+ if (paused || !Number.isFinite(dt) || dt <= 0) return;
219
+ if (absolute + dt * 60 / fastestRate > Number.MAX_SAFE_INTEGER) throw new RangeError(`GameClock.update: dt ${dt} would carry absoluteMinutes past Number.MAX_SAFE_INTEGER`);
220
+ let remaining = dt;
221
+ for (;;) {
222
+ const boundary = currentBoundary();
223
+ const toBoundary = boundary - absolute;
224
+ if (toBoundary > 0) {
225
+ const rate = segments[index].secondsPerGameHour;
226
+ const cost = toBoundary * rate / 60;
227
+ if (remaining < cost) {
228
+ const next = absolute + remaining * 60 / rate;
229
+ if (next < boundary) {
230
+ absolute = next;
231
+ return;
232
+ }
233
+ remaining = 0;
234
+ } else remaining -= cost;
235
+ absolute = boundary;
236
+ }
237
+ if (!cross() || paused) return;
238
+ }
239
+ }
240
+ function advanceMinutes(n) {
241
+ if (!Number.isFinite(n) || n < 0) throw new RangeError(`GameClock.advanceMinutes: n must be finite and >= 0, got ${n}`);
242
+ const target = absolute + n;
243
+ if (target > Number.MAX_SAFE_INTEGER) throw new RangeError(`GameClock.advanceMinutes: absoluteMinutes + n must not exceed Number.MAX_SAFE_INTEGER, got ${target}`);
244
+ advanceTo(target);
245
+ }
246
+ function skipTo(segmentName) {
247
+ const day = Math.floor(absolute / MINUTES_PER_DAY);
248
+ let target = Number.POSITIVE_INFINITY;
249
+ for (let i = 0; i < count; i++) {
250
+ const seg = segments[i];
251
+ if (seg.name !== segmentName) continue;
252
+ let candidate = day * MINUTES_PER_DAY + seg.startMinute;
253
+ if (candidate < absolute || candidate === absolute && index === i) candidate += MINUTES_PER_DAY;
254
+ if (candidate < target) target = candidate;
255
+ }
256
+ if (target === Number.POSITIVE_INFINITY) throw new Error(`GameClock.skipTo: unknown segment "${segmentName}"`);
257
+ advanceTo(target);
258
+ }
259
+ return {
260
+ get absoluteMinutes() {
261
+ return absolute;
262
+ },
263
+ get day() {
264
+ return Math.floor(absolute / MINUTES_PER_DAY);
265
+ },
266
+ get hour() {
267
+ const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;
268
+ return Math.floor(minuteOfDay / 60);
269
+ },
270
+ get minute() {
271
+ const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;
272
+ return Math.floor(minuteOfDay - Math.floor(minuteOfDay / 60) * 60);
273
+ },
274
+ get segment() {
275
+ return segments[index].name;
276
+ },
277
+ get phase() {
278
+ return segments[index].phase;
279
+ },
280
+ get paused() {
281
+ return paused;
282
+ },
283
+ get held() {
284
+ return held;
285
+ },
286
+ update,
287
+ advanceMinutes,
288
+ skipTo,
289
+ pause() {
290
+ paused = true;
291
+ },
292
+ resume() {
293
+ paused = false;
294
+ },
295
+ hold() {
296
+ held = true;
297
+ },
298
+ release() {
299
+ held = false;
300
+ },
301
+ serialize() {
302
+ return {
303
+ absoluteMinutes: absolute,
304
+ paused
305
+ };
306
+ }
307
+ };
308
+ }
126
309
  // src/tier-resolve.ts
127
310
  /**
128
311
  * Returns the highest tier whose `at` threshold is met or exceeded by `tally`,
@@ -133,13 +316,8 @@ function rollDrop(table, rollTable01, rollChance01, chancePerRoll, pity, thresho
133
316
  * Ties (identical `at`) are broken by iteration order (last entry wins).
134
317
  */
135
318
  function resolveTier(entries, tally) {
136
- let best = null;
137
- let bestAt = Number.NEGATIVE_INFINITY;
138
- for (const e of entries) if (tally >= e.at && e.at >= bestAt) {
139
- best = e.tier;
140
- bestAt = e.at;
141
- }
142
- return best;
319
+ const i = resolveTierIndex(entries, tally);
320
+ return i < 0 ? null : entries[i].tier;
143
321
  }
144
322
  /**
145
323
  * Returns the index (0-based) of the highest satisfied tier entry,
@@ -235,6 +413,6 @@ function createUpgradeTrack(config) {
235
413
  resolveStats
236
414
  };
237
415
  }
238
- export { createCollectibleRegistry, createDropTable, createUnlockDag, createUpgradeTrack, resolveTier, resolveTierIndex, rollDrop };
416
+ export { createCollectibleRegistry, createDropTable, createGameClock, createUnlockDag, createUpgradeTrack, resolveTier, resolveTierIndex, rollDrop };
239
417
 
240
418
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/collectible-registry.ts","../src/drop-roll.ts","../src/tier-resolve.ts","../src/unlock-dag.ts","../src/upgrade-track.ts"],"sourcesContent":["/**\n * Collectible-unlock registry: immutable unlock-set + partition + capstone.\n *\n * The registry is generic over a string id type.\n * All operations return new registry instances — no mutation.\n */\n\nexport interface CollectibleRegistry<K extends string> {\n /** The complete set of collectible ids (excluding the capstone). */\n readonly all: ReadonlySet<K>;\n /** The capstone id, or null when no capstone is defined. */\n readonly capstoneId: K | null;\n /** Currently unlocked ids (a subset of `all`, plus capstone when triggered). */\n readonly unlocked: ReadonlySet<K>;\n /** True when every collectible in `all` is unlocked. */\n readonly isComplete: boolean;\n /**\n * True when the capstone is in `unlocked`. Always false when `capstoneId`\n * is null.\n */\n readonly isCapstone: boolean;\n /**\n * Returns a new registry with `id` added to `unlocked`. Idempotent.\n * Automatically adds the capstone when `isComplete` transitions to true\n * and a capstone is defined.\n * Throws on unknown ids (not in `all` and not the capstoneId).\n */\n unlock(id: K): CollectibleRegistry<K>;\n /**\n * Partition the unlocked set into `{ have, missing }`.\n * `have` = ids in `all` that are in `unlocked` (capstone excluded).\n * `missing` = ids in `all` not yet unlocked.\n */\n partition(): { have: readonly K[]; missing: readonly K[] };\n /**\n * Returns all ids in `all` in insertion order.\n */\n list(): readonly K[];\n}\n\nfunction makeRegistry<K extends string>(\n all: ReadonlySet<K>,\n capstoneId: K | null,\n unlocked: ReadonlySet<K>,\n): CollectibleRegistry<K> {\n const isComplete = [...all].every((id) => unlocked.has(id));\n const isCapstone = capstoneId !== null && unlocked.has(capstoneId);\n\n function unlock(id: K): CollectibleRegistry<K> {\n if (!all.has(id) && id !== capstoneId) {\n throw new Error(`CollectibleRegistry: unknown id \"${String(id)}\"`);\n }\n if (unlocked.has(id)) return reg;\n const next = new Set<K>(unlocked);\n next.add(id);\n // Auto-unlock capstone on completion.\n if (capstoneId !== null && !next.has(capstoneId)) {\n const allComplete = [...all].every((k) => next.has(k));\n if (allComplete) next.add(capstoneId);\n }\n return makeRegistry(all, capstoneId, next);\n }\n\n function partition(): { have: readonly K[]; missing: readonly K[] } {\n const have: K[] = [];\n const missing: K[] = [];\n for (const id of all) {\n if (unlocked.has(id)) have.push(id);\n else missing.push(id);\n }\n return { have, missing };\n }\n\n function list(): readonly K[] {\n return [...all];\n }\n\n const reg: CollectibleRegistry<K> = {\n all,\n capstoneId,\n unlocked,\n isComplete,\n isCapstone,\n unlock,\n partition,\n list,\n };\n return reg;\n}\n\n/**\n * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an\n * optional `capstoneId`.\n *\n * Duplicate ids in `ids` throw. `capstoneId` may equal one of the ids in `ids`\n * (it is tracked as a separate gate — the capstone fires only on full completion,\n * not by direct unlock through `ids` membership alone).\n *\n * The capstone MUST be distinct from all ids in `ids` — if not, the capstone\n * unlock auto-fires on full completion regardless of whether the capstone id\n * was directly unlocked via the `ids` set, which would be semantically ambiguous.\n */\nexport function createCollectibleRegistry<K extends string>(\n ids: readonly K[],\n capstoneId?: K,\n): CollectibleRegistry<K> {\n const all = new Set<K>();\n for (const id of ids) {\n if (all.has(id)) {\n throw new Error(`createCollectibleRegistry: duplicate id \"${String(id)}\"`);\n }\n all.add(id);\n }\n return makeRegistry<K>(all, capstoneId ?? null, new Set<K>());\n}\n","/**\n * Pity-aware weighted drop roller.\n *\n * `rollInto` is zero-alloc on the hot path: the `weightAt` accessor and the\n * `dryPrev` scratch buffer are allocated once inside the factory closure and\n * reused across calls. The `out` parameter receives the result in-place;\n * aliasing `out.pity` against the input `pity` is safe because the function\n * reads all input pity fields into `dryPrev` before writing any output pity\n * fields.\n */\n\nimport { weightedIndexBy } from '@flare-engine/math';\n\nexport interface DropEntry<K extends string> {\n readonly item: K;\n readonly weight: number;\n}\n\n/**\n * Per-item dry-roll counters feeding the pity guarantees.\n * Keys are the item ids whose pity is being tracked.\n */\nexport type DropPity<K extends string> = Record<K, number>;\n\nexport interface DropRollOut<K extends string> {\n item: K | 'none';\n pity: DropPity<K>;\n}\n\n/**\n * A `DropTable` is a factory that closes over a weight accessor to avoid\n * per-call allocations. Create once; reuse across frames.\n */\nexport interface DropTable<K extends string> {\n readonly entries: readonly DropEntry<K>[];\n /**\n * Zero-alloc weighted drop. Writes result into `out`.\n *\n * Algorithm:\n * 1. Check pity thresholds (first matching pity item fires unconditionally).\n * 2. If no pity fires and `rollChance01 >= chancePerRoll`, result = 'none'.\n * 3. Otherwise pick from the weighted table filtered by `isAllowed`.\n * An all-gated pool (every entry filtered out) fizzles to 'none'.\n *\n * `out.pity` counters reset for the dropped item, advance by 1 for all others.\n * Aliasing `out.pity` against the input `pity` is safe.\n */\n rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void;\n}\n\n/**\n * Creates a `DropTable` from `entries`.\n * The `weightAt` accessor and scratch buffer are allocated once inside this\n * factory (not per-roll).\n */\nexport function createDropTable<K extends string>(entries: readonly DropEntry<K>[]): DropTable<K> {\n // Closed-over filter state — set before each weightedIndexBy call.\n // `var` so the binding is function-scoped and hoisted; reassigned each call.\n var currentIsAllowed: (item: K) => boolean = () => true;\n\n const weightAt = (entry: DropEntry<K>): number =>\n currentIsAllowed(entry.item) ? entry.weight : 0;\n\n // Pre-allocated scratch buffer: stores dry counts read from `pity` before\n // any writes, enabling safe aliasing of out.pity === pity.\n const dryPrev = new Float32Array(entries.length);\n\n function rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void {\n let picked: K | 'none' = 'none';\n\n // Read all pity inputs into scratch before writing any output (aliasing guard).\n for (let i = 0; i < entries.length; i++) {\n dryPrev[i] = pity[(entries[i] as DropEntry<K>).item] ?? 0;\n }\n\n // Pity check — first item whose dry count + 1 meets or exceeds threshold.\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n const threshold = thresholds[e.item];\n if (threshold !== undefined && isAllowed(e.item) && (dryPrev[i] as number) + 1 >= threshold) {\n picked = e.item;\n break;\n }\n }\n\n // Chance gate + weighted pick.\n if (picked === 'none') {\n if (rollChance01 < chancePerRoll) {\n currentIsAllowed = isAllowed;\n // Compute allowed total to detect an all-gated pool (fizzles to 'none').\n let allowedTotal = 0;\n for (let i = 0; i < entries.length; i++) {\n allowedTotal += weightAt(entries[i] as DropEntry<K>);\n }\n if (allowedTotal > 0) {\n const idx = weightedIndexBy(entries, weightAt, rollTable01);\n const entry = entries[idx];\n if (entry !== undefined) picked = entry.item;\n }\n }\n }\n\n // Write output — pity counters.\n out.item = picked;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n (out.pity as Record<string, number>)[e.item] =\n picked === e.item ? 0 : (dryPrev[i] as number) + 1;\n }\n }\n\n return { entries, rollInto };\n}\n\n/**\n * Allocating convenience wrapper. Creates a fresh pity object and returns both.\n * Use `table.rollInto` on the hot path; this is for tests and cold-path setup.\n */\nexport function rollDrop<K extends string>(\n table: DropTable<K>,\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed?: (item: K) => boolean,\n): DropRollOut<K> {\n const out: DropRollOut<K> = { item: 'none', pity: { ...pity } };\n table.rollInto(\n rollTable01,\n rollChance01,\n chancePerRoll,\n pity,\n thresholds,\n isAllowed ?? (() => true),\n out,\n );\n return out;\n}\n","/**\n * Tier resolution: \"highest threshold crossed by a running tally.\"\n *\n * The tally tiers are caller-defined (generic `T`) so the same resolver\n * works for score brackets, XP thresholds, unlock gates, etc.\n */\n\nexport interface TierEntry<T> {\n /** Minimum tally value (inclusive) required to reach this tier. */\n readonly at: number;\n /** The tier value associated with this threshold. */\n readonly tier: T;\n}\n\n/**\n * Returns the highest tier whose `at` threshold is met or exceeded by `tally`,\n * or `null` when `tally` is below all thresholds.\n *\n * `entries` need not be sorted — the function scans all entries and returns the\n * one with the largest `at` that satisfies `tally >= at`.\n * Ties (identical `at`) are broken by iteration order (last entry wins).\n */\nexport function resolveTier<T>(entries: readonly TierEntry<T>[], tally: number): T | null {\n let best: T | null = null;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (const e of entries) {\n if (tally >= e.at && e.at >= bestAt) {\n best = e.tier;\n bestAt = e.at;\n }\n }\n return best;\n}\n\n/**\n * Returns the index (0-based) of the highest satisfied tier entry,\n * or -1 when `tally` is below all thresholds.\n * Same tie-breaking rules as `resolveTier`.\n */\nexport function resolveTierIndex<T>(entries: readonly TierEntry<T>[], tally: number): number {\n let bestIdx = -1;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i];\n if (e !== undefined && tally >= e.at && e.at >= bestAt) {\n bestIdx = i;\n bestAt = e.at;\n }\n }\n return bestIdx;\n}\n","/**\n * Prerequisite DAG for unlock/progression graphs.\n *\n * The graph is directed and acyclic by construction (caller contract — no runtime cycle\n * detection). Nodes are string ids; edges are \"requires\" lists.\n */\n\nexport interface DagNode {\n /** Unique string id for this node. */\n readonly id: string;\n /** Ids of nodes that must be in the cleared set before this node unlocks. */\n readonly requires: readonly string[];\n}\n\nexport interface UnlockDag {\n readonly nodes: ReadonlyMap<string, DagNode>;\n /**\n * Whether `id` is unlocked given the set of cleared (previously unlocked) ids.\n * A node with no requirements is always unlocked.\n * An unknown id returns false.\n */\n isUnlocked(cleared: ReadonlySet<string>, id: string): boolean;\n /**\n * The frontier: all nodes whose requirements are fully satisfied by `cleared`,\n * but which are NOT yet in `cleared`. Returned as a sorted array (stable\n * insertion order from `nodes`).\n */\n frontier(cleared: ReadonlySet<string>): readonly string[];\n /**\n * All nodes currently unlocked by `cleared` (including those already in\n * `cleared`). Returned as a sorted array (stable insertion order).\n */\n allUnlocked(cleared: ReadonlySet<string>): readonly string[];\n}\n\n/**\n * Creates an `UnlockDag` from `nodes`.\n * Duplicate ids throw. Unknown `requires` ids are silently tolerated — a node\n * whose prerequisite id doesn't exist in the graph is simply never satisfiable.\n */\nexport function createUnlockDag(nodes: readonly DagNode[]): UnlockDag {\n const map = new Map<string, DagNode>();\n for (const node of nodes) {\n if (map.has(node.id)) {\n throw new Error(`createUnlockDag: duplicate node id \"${node.id}\"`);\n }\n map.set(node.id, node);\n }\n\n function isUnlocked(cleared: ReadonlySet<string>, id: string): boolean {\n const node = map.get(id);\n if (!node) return false;\n for (const req of node.requires) {\n if (!cleared.has(req)) return false;\n }\n return true;\n }\n\n function frontier(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (!cleared.has(id) && isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n function allUnlocked(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n return { nodes: map, isUnlocked, frontier, allUnlocked };\n}\n","/**\n * Geometric upgrade track with an immutable buy operation.\n * price(level) = round(base × growth^level) — the next-level cost from `level`.\n * Consolidates the common geometric-cost upgrade pattern.\n */\n\nexport interface UpgradeTrackConfig {\n /** Base price at level 0 → 1. */\n readonly base: number;\n /** Multiplicative growth factor per level. */\n readonly growth: number;\n /** Hard level cap (inclusive). */\n readonly cap: number;\n}\n\nexport interface UpgradeBuyResult {\n readonly ok: boolean;\n readonly wallet: number;\n readonly level: number;\n}\n\nexport interface UpgradeTrack {\n readonly config: UpgradeTrackConfig;\n /**\n * Cost to advance from `currentLevel` to `currentLevel + 1`.\n * Returns Infinity when at or above cap.\n */\n price(currentLevel: number): number;\n /** Whether `wallet` is sufficient and `currentLevel` is below cap. */\n canBuy(wallet: number, currentLevel: number): boolean;\n /**\n * Pure spend: deduct `price(currentLevel)` from `wallet` and return\n * the new state. Returns `{ ok: false, wallet, level }` when blocked.\n */\n buy(wallet: number, currentLevel: number): UpgradeBuyResult;\n /**\n * Fold all per-level stat deltas into a running accumulator.\n * `getLevel` is a caller-supplied reader so the resolver is unit-testable\n * without any save/store dep. `deltas` maps a stat key to the per-level delta;\n * `base` is the starting value for each key.\n * Returns a plain Record with the accumulated values.\n */\n resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number>;\n}\n\n/**\n * Returns an `UpgradeTrack` backed by `config`.\n * The returned object is a plain object (no class) — safe to freeze or copy.\n */\nexport function createUpgradeTrack(config: UpgradeTrackConfig): UpgradeTrack {\n function price(currentLevel: number): number {\n if (currentLevel >= config.cap) return Number.POSITIVE_INFINITY;\n return Math.round(config.base * config.growth ** currentLevel);\n }\n\n function canBuy(wallet: number, currentLevel: number): boolean {\n if (currentLevel >= config.cap) return false;\n return wallet >= price(currentLevel);\n }\n\n function buy(wallet: number, currentLevel: number): UpgradeBuyResult {\n if (!canBuy(wallet, currentLevel)) {\n return { ok: false, wallet, level: currentLevel };\n }\n return { ok: true, wallet: wallet - price(currentLevel), level: currentLevel + 1 };\n }\n\n function resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number> {\n const out = {} as Record<K, number>;\n for (const key of Object.keys(base) as K[]) {\n const level = Math.max(0, Math.floor(getLevel(key)));\n out[key] = (base[key] ?? 0) + (deltas[key] ?? 0) * level;\n }\n return out;\n }\n\n return { config, price, canBuy, buy, resolveStats };\n}\n"],"mappings":";;AAwCA,SAAS,aACP,KACA,YACA,UACwB;CACxB,MAAM,aAAa,CAAC,GAAG,GAAG,CAAC,CAAC,OAAO,OAAO,SAAS,IAAI,EAAE,CAAC;CAC1D,MAAM,aAAa,eAAe,QAAQ,SAAS,IAAI,UAAU;CAEjE,SAAS,OAAO,IAA+B;EAC7C,IAAI,CAAC,IAAI,IAAI,EAAE,KAAK,OAAO,YACzB,MAAM,IAAI,MAAM,oCAAoC,OAAO,EAAE,EAAE,EAAE;EAEnE,IAAI,SAAS,IAAI,EAAE,GAAG,OAAO;EAC7B,MAAM,OAAO,IAAI,IAAO,QAAQ;EAChC,KAAK,IAAI,E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EACvC,OAAO,UAAU,MAAM,YAAY;CACrC;CAEA,SAAS,IAAI,QAAgB,cAAwC;EACnE,IAAI,CAAC,OAAO,QAAQ,YAAY,GAC9B,OAAO;GAAE,IAAI;GAAO;GAAQ,OAAO;EAAa;EAElD,OAAO;GAAE,IAAI;GAAM,QAAQ,SAAS,MAAM,YAAY;GAAG,OAAO,eAAe;EAAE;CACnF;CAEA,SAAS,aACP,MACA,QACA,UACmB;EACnB,MAAM,MAAM,CAAC;EACb,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAAU;GAC1C,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,GAAG,CAAC,CAAC;GACnD,IAAI,QAAQ,KAAK,QAAQ,MAAM,OAAO,QAAQ,KAAK;EACrD;EACA,OAAO;CACT;CAEA,OAAO;EAAE;EAAQ;EAAO;EAAQ;EAAK;CAAa;AACpD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/collectible-registry.ts","../src/drop-roll.ts","../src/game-clock.ts","../src/tier-resolve.ts","../src/unlock-dag.ts","../src/upgrade-track.ts"],"sourcesContent":["/**\n * Collectible-unlock registry: immutable unlock-set + partition + capstone.\n *\n * The registry is generic over a string id type.\n * All operations return new registry instances — no mutation.\n */\n\nexport interface CollectibleRegistry<K extends string> {\n /** The complete set of collectible ids (excluding the capstone). */\n readonly all: ReadonlySet<K>;\n /** The capstone id, or null when no capstone is defined. */\n readonly capstoneId: K | null;\n /** Currently unlocked ids (a subset of `all`, plus capstone when triggered). */\n readonly unlocked: ReadonlySet<K>;\n /** True when every collectible in `all` is unlocked. */\n readonly isComplete: boolean;\n /**\n * True when the capstone is in `unlocked`. Always false when `capstoneId`\n * is null.\n */\n readonly isCapstone: boolean;\n /**\n * Returns a new registry with `id` added to `unlocked`. Idempotent.\n * Automatically adds the capstone when `isComplete` transitions to true\n * and a capstone is defined.\n * Throws on unknown ids (not in `all` and not the capstoneId).\n */\n unlock(id: K): CollectibleRegistry<K>;\n /**\n * Partition the unlocked set into `{ have, missing }`.\n * `have` = ids in `all` that are in `unlocked` (capstone excluded).\n * `missing` = ids in `all` not yet unlocked.\n */\n partition(): { have: readonly K[]; missing: readonly K[] };\n /**\n * Returns all ids in `all` in insertion order.\n */\n list(): readonly K[];\n}\n\nfunction makeRegistry<K extends string>(\n all: ReadonlySet<K>,\n capstoneId: K | null,\n unlocked: ReadonlySet<K>,\n): CollectibleRegistry<K> {\n const isComplete = [...all].every((id) => unlocked.has(id));\n const isCapstone = capstoneId !== null && unlocked.has(capstoneId);\n\n function unlock(id: K): CollectibleRegistry<K> {\n if (!all.has(id) && id !== capstoneId) {\n throw new Error(`CollectibleRegistry: unknown id \"${String(id)}\"`);\n }\n if (unlocked.has(id)) return reg;\n const next = new Set<K>(unlocked);\n next.add(id);\n // Auto-unlock capstone on completion.\n if (capstoneId !== null && !next.has(capstoneId)) {\n const allComplete = [...all].every((k) => next.has(k));\n if (allComplete) next.add(capstoneId);\n }\n return makeRegistry(all, capstoneId, next);\n }\n\n function partition(): { have: readonly K[]; missing: readonly K[] } {\n const have: K[] = [];\n const missing: K[] = [];\n for (const id of all) {\n if (unlocked.has(id)) have.push(id);\n else missing.push(id);\n }\n return { have, missing };\n }\n\n function list(): readonly K[] {\n return [...all];\n }\n\n const reg: CollectibleRegistry<K> = {\n all,\n capstoneId,\n unlocked,\n isComplete,\n isCapstone,\n unlock,\n partition,\n list,\n };\n return reg;\n}\n\n/**\n * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an\n * optional `capstoneId`.\n *\n * Duplicate ids in `ids` throw. The capstone is unlocked automatically once every\n * id in `ids` is unlocked, and `unlock(capstoneId)` also unlocks it directly;\n * either way `isCapstone` becomes true.\n *\n * Keep `capstoneId` out of `ids` for a capstone that marks completion. If it is\n * listed in `ids`, it is an ordinary member of the set: `isComplete` needs it,\n * `isCapstone` turns true as soon as it is unlocked, and the automatic unlock never\n * has anything to add.\n */\nexport function createCollectibleRegistry<K extends string>(\n ids: readonly K[],\n capstoneId?: K,\n): CollectibleRegistry<K> {\n const all = new Set<K>();\n for (const id of ids) {\n if (all.has(id)) {\n throw new Error(`createCollectibleRegistry: duplicate id \"${String(id)}\"`);\n }\n all.add(id);\n }\n return makeRegistry<K>(all, capstoneId ?? null, new Set<K>());\n}\n","/**\n * Pity-aware weighted drop roller.\n *\n * `rollInto` is zero-alloc on the hot path: the `weightAt` accessor and the\n * `dryPrev` scratch buffer are allocated once inside the factory closure and\n * reused across calls. The `out` parameter receives the result in-place;\n * aliasing `out.pity` against the input `pity` is safe because the function\n * reads all input pity fields into `dryPrev` before writing any output pity\n * fields.\n */\n\nimport { weightedIndexBy } from '@flare-engine/math';\n\nexport interface DropEntry<K extends string> {\n readonly item: K;\n readonly weight: number;\n}\n\n/**\n * Per-item dry-roll counters feeding the pity guarantees.\n * Keys are the item ids whose pity is being tracked.\n */\nexport type DropPity<K extends string> = Record<K, number>;\n\nexport interface DropRollOut<K extends string> {\n item: K | 'none';\n pity: DropPity<K>;\n}\n\n/**\n * A `DropTable` is a factory that closes over a weight accessor to avoid\n * per-call allocations. Create once; reuse across frames.\n */\nexport interface DropTable<K extends string> {\n readonly entries: readonly DropEntry<K>[];\n /**\n * Zero-alloc weighted drop. Writes result into `out`.\n *\n * Algorithm:\n * 1. Check pity thresholds (first matching pity item fires unconditionally).\n * 2. If no pity fires and `rollChance01 >= chancePerRoll`, result = 'none'.\n * 3. Otherwise pick from the weighted table filtered by `isAllowed`.\n * An all-gated pool (every entry filtered out) fizzles to 'none'.\n *\n * `out.pity` counters reset for the dropped item, advance by 1 for all others.\n * Aliasing `out.pity` against the input `pity` is safe.\n */\n rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void;\n}\n\n/**\n * Creates a `DropTable` from `entries`.\n * The `weightAt` accessor and scratch buffer are allocated once inside this\n * factory (not per-roll).\n */\nexport function createDropTable<K extends string>(entries: readonly DropEntry<K>[]): DropTable<K> {\n // Closed-over filter state — set before each weightedIndexBy call.\n // `var` so the binding is function-scoped and hoisted; reassigned each call.\n var currentIsAllowed: (item: K) => boolean = () => true;\n\n const weightAt = (entry: DropEntry<K>): number =>\n currentIsAllowed(entry.item) ? entry.weight : 0;\n\n // Pre-allocated scratch buffer: stores dry counts read from `pity` before\n // any writes, enabling safe aliasing of out.pity === pity.\n const dryPrev = new Float32Array(entries.length);\n\n function rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void {\n let picked: K | 'none' = 'none';\n\n // Read all pity inputs into scratch before writing any output (aliasing guard).\n for (let i = 0; i < entries.length; i++) {\n dryPrev[i] = pity[(entries[i] as DropEntry<K>).item] ?? 0;\n }\n\n // Pity check — first item whose dry count + 1 meets or exceeds threshold.\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n const threshold = thresholds[e.item];\n if (threshold !== undefined && isAllowed(e.item) && (dryPrev[i] as number) + 1 >= threshold) {\n picked = e.item;\n break;\n }\n }\n\n // Chance gate + weighted pick.\n if (picked === 'none') {\n if (rollChance01 < chancePerRoll) {\n currentIsAllowed = isAllowed;\n // Compute allowed total to detect an all-gated pool (fizzles to 'none').\n let allowedTotal = 0;\n for (let i = 0; i < entries.length; i++) {\n allowedTotal += weightAt(entries[i] as DropEntry<K>);\n }\n if (allowedTotal > 0) {\n const idx = weightedIndexBy(entries, weightAt, rollTable01);\n const entry = entries[idx];\n if (entry !== undefined) picked = entry.item;\n }\n }\n }\n\n // Write output — pity counters.\n out.item = picked;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n (out.pity as Record<string, number>)[e.item] =\n picked === e.item ? 0 : (dryPrev[i] as number) + 1;\n }\n }\n\n return { entries, rollInto };\n}\n\n/**\n * Allocating convenience wrapper. Creates a fresh pity object and returns both.\n * Use `table.rollInto` on the hot path; this is for tests and cold-path setup.\n */\nexport function rollDrop<K extends string>(\n table: DropTable<K>,\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed?: (item: K) => boolean,\n): DropRollOut<K> {\n const out: DropRollOut<K> = { item: 'none', pity: { ...pity } };\n table.rollInto(\n rollTable01,\n rollChance01,\n chancePerRoll,\n pity,\n thresholds,\n isAllowed ?? (() => true),\n out,\n );\n return out;\n}\n","/**\n * Game-day clock with per-segment real-time rates.\n * A day is 1440 game minutes split into ordered segments; each segment\n * runs at its own `secondsPerGameHour`. Supports pause, hold (stop at the\n * next phase boundary), manual advance, skip-to-segment, change callbacks,\n * and a plain serializable state.\n */\n\nconst MINUTES_PER_DAY = 1440;\n\nexport interface GameClockSegment {\n /** Segment name, e.g. 'day', 'dusk'. May repeat (a night that wraps midnight is two rows). */\n readonly name: string;\n /** Coarser grouping, e.g. 'day' | 'night'. */\n readonly phase: string;\n /** Minute of the game day at which the segment starts, integer 0..1439. */\n readonly startMinute: number;\n /** Real seconds per game hour while in this segment. */\n readonly secondsPerGameHour: number;\n}\n\nexport interface GameClockConfig {\n /** Ordered by `startMinute`; the first must start at 0. The last runs to 1440. */\n readonly segments: readonly GameClockSegment[];\n readonly onSegmentChange?: (segment: string, previous: string) => void;\n readonly onPhaseChange?: (phase: string, previous: string) => void;\n}\n\nexport interface GameClockState {\n readonly absoluteMinutes: number;\n readonly paused: boolean;\n}\n\nexport interface GameClock {\n /** Game minutes since day 0 00:00. Fractional, never decreases. */\n readonly absoluteMinutes: number;\n /** `floor(absoluteMinutes / 1440)`. */\n readonly day: number;\n /** 0..23. */\n readonly hour: number;\n /** 0..59, integer. */\n readonly minute: number;\n readonly segment: string;\n readonly phase: string;\n readonly paused: boolean;\n readonly held: boolean;\n /**\n * Advance by `dt` real seconds. No-op while paused, or when `dt` is not finite or <= 0.\n * Throws `RangeError` when `dt` could carry `absoluteMinutes` past `Number.MAX_SAFE_INTEGER`.\n */\n update(dt: number): void;\n /**\n * Advance by `n` game minutes, even while paused. Throws `RangeError` when `n` is negative or\n * not finite, or when `absoluteMinutes + n` exceeds `Number.MAX_SAFE_INTEGER`.\n */\n advanceMinutes(n: number): void;\n /**\n * Jump forward to the next start of `segmentName`, strictly after now, or to now when the\n * clock sits on that start without having entered it (held on the boundary, then released).\n * Throws on an unknown name.\n */\n skipTo(segmentName: string): void;\n pause(): void;\n resume(): void;\n /** Stop at the next phase boundary and stay there until `release()`. */\n hold(): void;\n release(): void;\n /** Allocates a fresh state object (cold path). `held` is not persisted. */\n serialize(): GameClockState;\n}\n\nfunction validateSegments(segments: readonly GameClockSegment[]): void {\n if (segments.length === 0) {\n throw new Error('createGameClock: segments must not be empty');\n }\n const first = segments[0] as GameClockSegment;\n if (first.startMinute !== 0) {\n throw new Error(\n `createGameClock: first segment must start at minute 0, got ${first.startMinute}`,\n );\n }\n let previousStart = -1;\n for (let i = 0; i < segments.length; i++) {\n const seg = segments[i] as GameClockSegment;\n const start = seg.startMinute;\n if (!Number.isInteger(start) || start < 0 || start >= MINUTES_PER_DAY) {\n throw new Error(\n `createGameClock: segment ${i} (\"${seg.name}\") startMinute must be an integer in 0..1439, got ${start}`,\n );\n }\n if (start <= previousStart) {\n throw new Error(\n `createGameClock: segment ${i} (\"${seg.name}\") startMinute ${start} must be greater than the previous start ${previousStart}`,\n );\n }\n previousStart = start;\n const rate = seg.secondsPerGameHour;\n if (!Number.isFinite(rate) || rate <= 0) {\n throw new Error(\n `createGameClock: segment ${i} (\"${seg.name}\") secondsPerGameHour must be finite and > 0, got ${rate}`,\n );\n }\n }\n}\n\n/**\n * Returns a `GameClock` backed by `config`, optionally restored from `state`.\n * The returned object is a plain object with getters (no class).\n */\nexport function createGameClock(config: GameClockConfig, state?: GameClockState): GameClock {\n const segments = config.segments;\n validateSegments(segments);\n const count = segments.length;\n const onSegmentChange = config.onSegmentChange;\n const onPhaseChange = config.onPhaseChange;\n\n // Per-segment end minute: the next segment's start, or 1440 for the last.\n const ends = new Float64Array(count);\n let fastestRate = Number.POSITIVE_INFINITY;\n for (let i = 0; i < count; i++) {\n ends[i] = i + 1 < count ? (segments[i + 1] as GameClockSegment).startMinute : MINUTES_PER_DAY;\n fastestRate = Math.min(fastestRate, (segments[i] as GameClockSegment).secondsPerGameHour);\n }\n\n let absolute = 0;\n let paused = false;\n let held = false;\n let index = 0;\n\n if (state !== undefined) {\n if (\n !Number.isFinite(state.absoluteMinutes) ||\n state.absoluteMinutes < 0 ||\n state.absoluteMinutes > Number.MAX_SAFE_INTEGER\n ) {\n throw new Error(\n `createGameClock: state.absoluteMinutes must be finite, >= 0 and <= Number.MAX_SAFE_INTEGER, got ${state.absoluteMinutes}`,\n );\n }\n if (typeof state.paused !== 'boolean') {\n throw new Error(\n `createGameClock: state.paused must be a boolean, got ${String(state.paused)}`,\n );\n }\n absolute = state.absoluteMinutes;\n paused = state.paused;\n const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;\n for (let i = 0; i < count; i++) {\n if ((segments[i] as GameClockSegment).startMinute <= minuteOfDay) index = i;\n }\n }\n\n /**\n * Move from the current segment to the next one, firing callbacks.\n * Returns false (and leaves everything untouched) when held and the next\n * segment opens a different phase.\n */\n function cross(): boolean {\n const next = index + 1 < count ? index + 1 : 0;\n const prev = segments[index] as GameClockSegment;\n const nextSeg = segments[next] as GameClockSegment;\n const phaseChanges = nextSeg.phase !== prev.phase;\n if (held && phaseChanges) return false;\n index = next;\n if (nextSeg.name !== prev.name && onSegmentChange !== undefined) {\n onSegmentChange(nextSeg.name, prev.name);\n }\n if (phaseChanges && onPhaseChange !== undefined) {\n onPhaseChange(nextSeg.phase, prev.phase);\n }\n return true;\n }\n\n /** Absolute minute at which the current segment ends (an integer while below 2^53). */\n function currentBoundary(): number {\n let day = Math.floor(absolute / MINUTES_PER_DAY);\n // Sitting on the midnight boundary with the last segment still current\n // (a held clock): that is minute 1440 of the previous day.\n if (absolute - day * MINUTES_PER_DAY < (segments[index] as GameClockSegment).startMinute) {\n day -= 1;\n }\n return day * MINUTES_PER_DAY + (ends[index] as number);\n }\n\n /**\n * Game-minute advance to an absolute target. Each boundary is compared against\n * the target itself rather than a carried remainder, so a target that equals a\n * boundary always lands on it and crosses (unless held).\n */\n function advanceTo(target: number): void {\n for (;;) {\n const boundary = currentBoundary();\n if (target < boundary) {\n // A callback may already have advanced the clock past `target`.\n if (target > absolute) absolute = target;\n return;\n }\n absolute = boundary;\n if (!cross()) return;\n }\n }\n\n function update(dt: number): void {\n if (paused || !Number.isFinite(dt) || dt <= 0) return;\n if (absolute + (dt * 60) / fastestRate > Number.MAX_SAFE_INTEGER) {\n throw new RangeError(\n `GameClock.update: dt ${dt} would carry absoluteMinutes past Number.MAX_SAFE_INTEGER`,\n );\n }\n // Rates differ per segment, so real seconds are carried as a remainder.\n let remaining = dt;\n for (;;) {\n const boundary = currentBoundary();\n const toBoundary = boundary - absolute;\n if (toBoundary > 0) {\n const rate = (segments[index] as GameClockSegment).secondsPerGameHour;\n const cost = (toBoundary * rate) / 60;\n if (remaining < cost) {\n const next = absolute + (remaining * 60) / rate;\n if (next < boundary) {\n absolute = next;\n return;\n }\n // Rounding reached the boundary: land on it and cross, like an exact step.\n remaining = 0;\n } else {\n remaining -= cost;\n }\n absolute = boundary;\n }\n // A callback that paused the clock stops this step at the boundary just crossed.\n if (!cross() || paused) return;\n }\n }\n\n function advanceMinutes(n: number): void {\n if (!Number.isFinite(n) || n < 0) {\n throw new RangeError(`GameClock.advanceMinutes: n must be finite and >= 0, got ${n}`);\n }\n const target = absolute + n;\n if (target > Number.MAX_SAFE_INTEGER) {\n throw new RangeError(\n `GameClock.advanceMinutes: absoluteMinutes + n must not exceed Number.MAX_SAFE_INTEGER, got ${target}`,\n );\n }\n advanceTo(target);\n }\n\n function skipTo(segmentName: string): void {\n const day = Math.floor(absolute / MINUTES_PER_DAY);\n let target = Number.POSITIVE_INFINITY;\n for (let i = 0; i < count; i++) {\n const seg = segments[i] as GameClockSegment;\n if (seg.name !== segmentName) continue;\n let candidate = day * MINUTES_PER_DAY + seg.startMinute;\n // A start the clock sits on without having entered it (held on the boundary,\n // then released) is still ahead; one it has entered is a full day away.\n if (candidate < absolute || (candidate === absolute && index === i)) {\n candidate += MINUTES_PER_DAY;\n }\n if (candidate < target) target = candidate;\n }\n if (target === Number.POSITIVE_INFINITY) {\n throw new Error(`GameClock.skipTo: unknown segment \"${segmentName}\"`);\n }\n advanceTo(target);\n }\n\n return {\n get absoluteMinutes() {\n return absolute;\n },\n get day() {\n return Math.floor(absolute / MINUTES_PER_DAY);\n },\n get hour() {\n const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;\n return Math.floor(minuteOfDay / 60);\n },\n get minute() {\n const minuteOfDay = absolute - Math.floor(absolute / MINUTES_PER_DAY) * MINUTES_PER_DAY;\n return Math.floor(minuteOfDay - Math.floor(minuteOfDay / 60) * 60);\n },\n get segment() {\n return (segments[index] as GameClockSegment).name;\n },\n get phase() {\n return (segments[index] as GameClockSegment).phase;\n },\n get paused() {\n return paused;\n },\n get held() {\n return held;\n },\n update,\n advanceMinutes,\n skipTo,\n pause() {\n paused = true;\n },\n resume() {\n paused = false;\n },\n hold() {\n held = true;\n },\n release() {\n held = false;\n },\n serialize(): GameClockState {\n return { absoluteMinutes: absolute, paused };\n },\n };\n}\n","/**\n * Tier resolution: \"highest threshold crossed by a running tally.\"\n *\n * The tally tiers are caller-defined (generic `T`) so the same resolver\n * works for score brackets, XP thresholds, unlock gates, etc.\n */\n\nexport interface TierEntry<T> {\n /** Minimum tally value (inclusive) required to reach this tier. */\n readonly at: number;\n /** The tier value associated with this threshold. */\n readonly tier: T;\n}\n\n/**\n * Returns the highest tier whose `at` threshold is met or exceeded by `tally`,\n * or `null` when `tally` is below all thresholds.\n *\n * `entries` need not be sorted — the function scans all entries and returns the\n * one with the largest `at` that satisfies `tally >= at`.\n * Ties (identical `at`) are broken by iteration order (last entry wins).\n */\nexport function resolveTier<T>(entries: readonly TierEntry<T>[], tally: number): T | null {\n const i = resolveTierIndex(entries, tally);\n return i < 0 ? null : entries[i]!.tier;\n}\n\n/**\n * Returns the index (0-based) of the highest satisfied tier entry,\n * or -1 when `tally` is below all thresholds.\n * Same tie-breaking rules as `resolveTier`.\n */\nexport function resolveTierIndex<T>(entries: readonly TierEntry<T>[], tally: number): number {\n let bestIdx = -1;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i];\n if (e !== undefined && tally >= e.at && e.at >= bestAt) {\n bestIdx = i;\n bestAt = e.at;\n }\n }\n return bestIdx;\n}\n","/**\n * Prerequisite DAG for unlock/progression graphs.\n *\n * The graph is directed and acyclic by construction (caller contract — no runtime cycle\n * detection). Nodes are string ids; edges are \"requires\" lists.\n */\n\nexport interface DagNode {\n /** Unique string id for this node. */\n readonly id: string;\n /** Ids of nodes that must be in the cleared set before this node unlocks. */\n readonly requires: readonly string[];\n}\n\nexport interface UnlockDag {\n readonly nodes: ReadonlyMap<string, DagNode>;\n /**\n * Whether `id` is unlocked given the set of cleared (previously unlocked) ids.\n * A node with no requirements is always unlocked.\n * An unknown id returns false.\n */\n isUnlocked(cleared: ReadonlySet<string>, id: string): boolean;\n /**\n * The frontier: all nodes whose requirements are fully satisfied by `cleared`,\n * but which are NOT yet in `cleared`. Returned as a sorted array (stable\n * insertion order from `nodes`).\n */\n frontier(cleared: ReadonlySet<string>): readonly string[];\n /**\n * All nodes currently unlocked by `cleared` (including those already in\n * `cleared`). Returned as a sorted array (stable insertion order).\n */\n allUnlocked(cleared: ReadonlySet<string>): readonly string[];\n}\n\n/**\n * Creates an `UnlockDag` from `nodes`.\n * Duplicate ids throw. Unknown `requires` ids are silently tolerated — a node\n * whose prerequisite id doesn't exist in the graph is simply never satisfiable.\n */\nexport function createUnlockDag(nodes: readonly DagNode[]): UnlockDag {\n const map = new Map<string, DagNode>();\n for (const node of nodes) {\n if (map.has(node.id)) {\n throw new Error(`createUnlockDag: duplicate node id \"${node.id}\"`);\n }\n map.set(node.id, node);\n }\n\n function isUnlocked(cleared: ReadonlySet<string>, id: string): boolean {\n const node = map.get(id);\n if (!node) return false;\n for (const req of node.requires) {\n if (!cleared.has(req)) return false;\n }\n return true;\n }\n\n function frontier(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (!cleared.has(id) && isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n function allUnlocked(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n return { nodes: map, isUnlocked, frontier, allUnlocked };\n}\n","/**\n * Geometric upgrade track with an immutable buy operation.\n * price(level) = round(base × growth^level) — the next-level cost from `level`.\n * Consolidates the common geometric-cost upgrade pattern.\n */\n\nexport interface UpgradeTrackConfig {\n /** Base price at level 0 → 1. */\n readonly base: number;\n /** Multiplicative growth factor per level. */\n readonly growth: number;\n /** Hard level cap (inclusive). */\n readonly cap: number;\n}\n\nexport interface UpgradeBuyResult {\n readonly ok: boolean;\n readonly wallet: number;\n readonly level: number;\n}\n\nexport interface UpgradeTrack {\n readonly config: UpgradeTrackConfig;\n /**\n * Cost to advance from `currentLevel` to `currentLevel + 1`.\n * Returns Infinity when at or above cap.\n */\n price(currentLevel: number): number;\n /** Whether `wallet` is sufficient and `currentLevel` is below cap. */\n canBuy(wallet: number, currentLevel: number): boolean;\n /**\n * Pure spend: deduct `price(currentLevel)` from `wallet` and return\n * the new state. Returns `{ ok: false, wallet, level }` when blocked.\n */\n buy(wallet: number, currentLevel: number): UpgradeBuyResult;\n /**\n * Fold all per-level stat deltas into a running accumulator.\n * `getLevel` is a caller-supplied reader so the resolver is unit-testable\n * without any save/store dep. `deltas` maps a stat key to the per-level delta;\n * `base` is the starting value for each key.\n * Returns a plain Record with the accumulated values.\n */\n resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number>;\n}\n\n/**\n * Returns an `UpgradeTrack` backed by `config`.\n * The returned object is a plain object (no class) — safe to freeze or copy.\n */\nexport function createUpgradeTrack(config: UpgradeTrackConfig): UpgradeTrack {\n function price(currentLevel: number): number {\n if (currentLevel >= config.cap) return Number.POSITIVE_INFINITY;\n return Math.round(config.base * config.growth ** currentLevel);\n }\n\n function canBuy(wallet: number, currentLevel: number): boolean {\n if (currentLevel >= config.cap) return false;\n return wallet >= price(currentLevel);\n }\n\n function buy(wallet: number, currentLevel: number): UpgradeBuyResult {\n if (!canBuy(wallet, currentLevel)) {\n return { ok: false, wallet, level: currentLevel };\n }\n return { ok: true, wallet: wallet - price(currentLevel), level: currentLevel + 1 };\n }\n\n function resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number> {\n const out = {} as Record<K, number>;\n for (const key of Object.keys(base) as K[]) {\n const level = Math.max(0, Math.floor(getLevel(key)));\n out[key] = (base[key] ?? 0) + (deltas[key] ?? 0) * level;\n }\n return out;\n }\n\n return { config, price, canBuy, buy, resolveStats };\n}\n"],"mappings":";;AAwCA,SAAS,aACP,KACA,YACA,UACwB;CACxB,MAAM,aAAa,CAAC,GAAG,GAAG,CAAC,CAAC,OAAO,OAAO,SAAS,IAAI,EAAE,CAAC;CAC1D,MAAM,aAAa,eAAe,QAAQ,SAAS,IAAI,UAAU;CAEjE,SAAS,OAAO,IAA+B;EAC7C,IAAI,CAAC,IAAI,IAAI,EAAE,KAAK,OAAO,YACzB,MAAM,IAAI,MAAM,oCAAoC,OAAO,EAAE,EAAE,EAAE;EAEnE,IAAI,SAAS,IAAI,EAAE,GAAG,OAAO;EAC7B,MAAM,OAAO,IAAI,IAAO,QAAQ;EAChC,KAAK,IAAI,E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"description": "Meta-progression primitives: upgrade tracks, drop-roll with pity, unlock DAG, tier resolution, collectible registry",
5
5
  "keywords": [
6
6
  "flare-engine",
@@ -60,6 +60,6 @@
60
60
  },
61
61
  "sideEffects": false,
62
62
  "dependencies": {
63
- "@flare-engine/math": "^0.4.10"
63
+ "@flare-engine/math": "^0.4.12"
64
64
  }
65
65
  }