@bct-app/game-engine 0.1.2 → 0.1.6-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -84,33 +84,43 @@ var getValueFromPayloads = (payloads, idx) => {
84
84
  return payloads[idx];
85
85
  };
86
86
  var getSourceValue = (source, payloads) => {
87
- if (source.from === "PAYLOAD") {
87
+ if (source?.from === "PAYLOAD") {
88
88
  if (!isNumberOrNumberArray(source.value)) {
89
89
  return void 0;
90
90
  }
91
91
  return getValueFromPayloads(payloads, source.value);
92
92
  }
93
- if (source.from === "CONSTANT") {
93
+ if (source?.from === "CONSTANT") {
94
94
  return source.value;
95
95
  }
96
96
  return null;
97
97
  };
98
- var resolveSourceValue = (source, writableParts, payloads, effector, snapshotSeatMap, resolveFromPlayer) => {
99
- if (source.from === "PAYLOAD") {
98
+ var resolveSourceValue = (source, writableInputs, payloads, effector, snapshotSeatMap, resolveFromPlayer, isResolvedValue, resolveFromCharacter) => {
99
+ const castOrValidate = (value) => {
100
+ if (!isResolvedValue) {
101
+ return value;
102
+ }
103
+ return isResolvedValue(value) ? value : void 0;
104
+ };
105
+ if (source?.from === "PAYLOAD") {
100
106
  const payloadValue = getSourceValue(source, payloads);
101
107
  const idx = adjustValueAsNumberArray(source.value);
102
- const part = writableParts[idx[0]];
103
- if (part?.type === "PLAYER") {
108
+ const input = writableInputs[idx[0]];
109
+ if (input?.type === "PLAYER") {
104
110
  const seat = adjustValueAsNumber(payloadValue);
105
111
  const player = typeof seat === "number" ? snapshotSeatMap.get(seat) : void 0;
106
112
  return player ? resolveFromPlayer(player) : void 0;
107
113
  }
108
- return payloadValue;
114
+ if (input?.type === "CHARACTER") {
115
+ const characterId = typeof payloadValue === "string" ? payloadValue : void 0;
116
+ return characterId && resolveFromCharacter ? resolveFromCharacter(characterId) : void 0;
117
+ }
118
+ return castOrValidate(payloadValue);
109
119
  }
110
- if (source.from === "CONSTANT") {
111
- return source.value;
120
+ if (source?.from === "CONSTANT") {
121
+ return castOrValidate(source.value);
112
122
  }
113
- if (source.from === "EFFECTOR") {
123
+ if (source?.from === "EFFECTOR") {
114
124
  if (!effector) {
115
125
  return void 0;
116
126
  }
@@ -120,7 +130,607 @@ var resolveSourceValue = (source, writableParts, payloads, effector, snapshotSea
120
130
  return void 0;
121
131
  };
122
132
 
133
+ // src/effects/handler-types.ts
134
+ var createEffectHandler = (type, handler) => {
135
+ return (context) => {
136
+ if (context.effect.type !== type) {
137
+ console.warn("Invalid effect type for handler:", context.effect.type, "expected:", type);
138
+ return;
139
+ }
140
+ handler({
141
+ ...context,
142
+ effect: context.effect
143
+ });
144
+ };
145
+ };
146
+
147
+ // src/effects/handlers/ability-change.ts
148
+ var toAbilityIdList = (value) => {
149
+ if (typeof value === "string") {
150
+ return value.length > 0 ? [value] : void 0;
151
+ }
152
+ if (Array.isArray(value)) {
153
+ const ids = value.filter((item) => typeof item === "string" && item.length > 0);
154
+ return ids.length > 0 ? ids : void 0;
155
+ }
156
+ return void 0;
157
+ };
158
+ var applyAbilityChange = createEffectHandler("ABILITY_CHANGE", ({
159
+ effect,
160
+ operation,
161
+ payloads,
162
+ effector,
163
+ writableInputs,
164
+ getSnapshotSeatMap,
165
+ abilityMap,
166
+ makePlayersEffect,
167
+ characterMap
168
+ }) => {
169
+ const resolvedRaw = resolveSourceValue(
170
+ effect.source,
171
+ writableInputs,
172
+ payloads,
173
+ effector,
174
+ getSnapshotSeatMap(),
175
+ (player) => player.abilities,
176
+ (value) => typeof value === "string" && value.length > 0 || Array.isArray(value) && value.every((item) => typeof item === "string"),
177
+ (characterId) => {
178
+ const character = characterMap.get(characterId);
179
+ if (!character) {
180
+ console.warn("Character not found for ABILITY_CHANGE effect source:", characterId);
181
+ return [];
182
+ }
183
+ return character.abilities.map((a) => a.id);
184
+ }
185
+ );
186
+ const resolvedAbilityIds = toAbilityIdList(resolvedRaw);
187
+ if (!resolvedAbilityIds) {
188
+ console.warn("Ability ID not found for ABILITY_CHANGE effect:", effect.source);
189
+ return;
190
+ }
191
+ makePlayersEffect.forEach((player) => {
192
+ const overrideRaw = operation.abilityChangeOverrides?.[String(player.seat)];
193
+ const overrideIds = toAbilityIdList(overrideRaw);
194
+ const finalAbilityIds = overrideIds ?? resolvedAbilityIds;
195
+ finalAbilityIds.forEach((finalAbilityId) => {
196
+ const newAbility = abilityMap.get(finalAbilityId);
197
+ if (!newAbility) {
198
+ console.warn("Ability not found for ABILITY_CHANGE effect:", finalAbilityId);
199
+ return;
200
+ }
201
+ const replaceAtSameStage = (abilities) => {
202
+ const idx = abilities.findIndex((aid) => abilityMap.get(aid)?.stage === newAbility.stage);
203
+ if (idx >= 0) {
204
+ abilities[idx] = finalAbilityId;
205
+ } else {
206
+ abilities.push(finalAbilityId);
207
+ }
208
+ };
209
+ replaceAtSameStage(player.abilities);
210
+ if (player.perceivedCharacter?.asCharacter) {
211
+ replaceAtSameStage(player.perceivedCharacter.abilities);
212
+ }
213
+ });
214
+ });
215
+ });
216
+
217
+ // src/effects/handlers/alignment-change.ts
218
+ var applyAlignmentChange = createEffectHandler("ALIGNMENT_CHANGE", ({
219
+ effect,
220
+ payloads,
221
+ effector,
222
+ writableInputs,
223
+ getSnapshotSeatMap,
224
+ makePlayersEffect
225
+ }) => {
226
+ const alignment = resolveSourceValue(
227
+ effect.source,
228
+ writableInputs,
229
+ payloads,
230
+ effector,
231
+ getSnapshotSeatMap(),
232
+ (player) => player.alignment,
233
+ (isResolvedValue) => typeof isResolvedValue === "string" && (isResolvedValue === "GOOD" || isResolvedValue === "EVIL")
234
+ );
235
+ if (!alignment) {
236
+ console.warn("Alignment not found for ALIGNMENT_CHANGE effect:", effect.source);
237
+ return;
238
+ }
239
+ makePlayersEffect.forEach((player) => {
240
+ player.alignment = alignment;
241
+ });
242
+ });
243
+
244
+ // src/effects/handlers/character-change.ts
245
+ var resolveCharacterId = (value) => {
246
+ if (typeof value === "string") {
247
+ return value;
248
+ }
249
+ if (Array.isArray(value) && typeof value[0] === "string") {
250
+ return value[0];
251
+ }
252
+ return void 0;
253
+ };
254
+ var applyCharacterChange = createEffectHandler("CHARACTER_CHANGE", ({
255
+ effect,
256
+ payloads,
257
+ effector,
258
+ writableInputs,
259
+ getSnapshotSeatMap,
260
+ characterMap,
261
+ makePlayersEffect
262
+ }) => {
263
+ const resolvedCharacterId = resolveSourceValue(
264
+ effect.source,
265
+ writableInputs,
266
+ payloads,
267
+ effector,
268
+ getSnapshotSeatMap(),
269
+ (player) => player.characterId
270
+ );
271
+ const characterId = resolveCharacterId(resolvedCharacterId);
272
+ if (!characterId) {
273
+ console.warn("Character ID not found for CHARACTER_CHANGE effect:", effect.source);
274
+ return;
275
+ }
276
+ const newCharacter = characterMap.get(characterId);
277
+ if (!newCharacter) {
278
+ console.warn("Character not found for CHARACTER_CHANGE effect:", characterId);
279
+ return;
280
+ }
281
+ const abilityIds = newCharacter.abilities.map((ability) => ability.id);
282
+ makePlayersEffect.forEach((player) => {
283
+ player.characterId = newCharacter.id;
284
+ player.abilities = abilityIds;
285
+ });
286
+ });
287
+
288
+ // src/effects/handlers/character-count-change.ts
289
+ var applyCharacterCountChange = createEffectHandler("CHARACTER_COUNT_CHANGE", () => {
290
+ console.warn("CHARACTER_COUNT_CHANGE effect handling not implemented yet.");
291
+ });
292
+
293
+ // src/effects/handlers/game-change.ts
294
+ var applyGameChange = createEffectHandler("GAME_CHANGE", () => {
295
+ console.warn("GAME_CHANGE effect handling not implemented yet.");
296
+ });
297
+
298
+ // src/effects/handlers/perceived-character-change.ts
299
+ var resolveCharacterId2 = (value) => {
300
+ if (typeof value === "string") {
301
+ return value;
302
+ }
303
+ if (Array.isArray(value) && typeof value[0] === "string") {
304
+ return value[0];
305
+ }
306
+ return void 0;
307
+ };
308
+ var applyPerceivedCharacterChange = createEffectHandler("PERCEIVED_CHARACTER_CHANGE", ({
309
+ effect,
310
+ payloads,
311
+ effector,
312
+ writableInputs,
313
+ getSnapshotSeatMap,
314
+ characterMap,
315
+ makePlayersEffect
316
+ }) => {
317
+ const resolvedCharacterId = resolveSourceValue(
318
+ effect.source,
319
+ writableInputs,
320
+ payloads,
321
+ effector,
322
+ getSnapshotSeatMap(),
323
+ (player) => player.characterId
324
+ );
325
+ const characterId = resolveCharacterId2(resolvedCharacterId);
326
+ if (!characterId) {
327
+ console.warn("Character ID not found for PERCEIVED_CHARACTER_CHANGE effect:", effect.source);
328
+ return;
329
+ }
330
+ const newCharacter = characterMap.get(characterId);
331
+ if (!newCharacter) {
332
+ console.warn("Character not found for PERCEIVED_CHARACTER_CHANGE effect:", characterId);
333
+ return;
334
+ }
335
+ makePlayersEffect.forEach((player) => {
336
+ player.perceivedCharacter = {
337
+ characterId: newCharacter.id,
338
+ abilities: newCharacter.abilities.map((ability) => ability.id),
339
+ asCharacter: effect.followPriority || false
340
+ };
341
+ });
342
+ });
343
+
344
+ // src/effects/handlers/reminder-add.ts
345
+ var applyReminderAdd = createEffectHandler("REMINDER_ADD", ({
346
+ effect,
347
+ payloads,
348
+ nowTimelineIndex,
349
+ operationInTimelineIdx,
350
+ makePlayersEffect
351
+ }) => {
352
+ const maybeReminder = getSourceValue(effect.source, payloads);
353
+ if (!isReminder(maybeReminder)) {
354
+ console.warn("Invalid reminder data for REMINDER_ADD effect:", maybeReminder);
355
+ return;
356
+ }
357
+ const timelineDistance = nowTimelineIndex - operationInTimelineIdx;
358
+ if (typeof maybeReminder.duration === "number" && maybeReminder.duration > 0 && timelineDistance >= maybeReminder.duration) {
359
+ return;
360
+ }
361
+ makePlayersEffect.forEach((player) => {
362
+ if (!player.reminders) {
363
+ player.reminders = [];
364
+ }
365
+ player.reminders.push(maybeReminder);
366
+ });
367
+ });
368
+
369
+ // src/effects/handlers/reminder-remove.ts
370
+ var applyReminderRemove = createEffectHandler("REMINDER_REMOVE", ({ effect, payloads, playerSeatMap }) => {
371
+ const maybeReminder = getSourceValue(effect.source, payloads);
372
+ if (!isPlayerReminderArray(maybeReminder)) {
373
+ console.warn("Invalid reminder data for REMINDER_REMOVE effect:", maybeReminder);
374
+ return;
375
+ }
376
+ maybeReminder.sort((left, right) => right.index - left.index).forEach((reminder) => {
377
+ const player = playerSeatMap.get(reminder.playerSeat);
378
+ if (!player) {
379
+ console.warn("Player not found for REMINDER_REMOVE effect:", reminder.playerSeat);
380
+ return;
381
+ }
382
+ if (!player.reminders) {
383
+ player.reminders = [];
384
+ }
385
+ player.reminders = player.reminders.filter((_value, index) => index !== reminder.index);
386
+ });
387
+ });
388
+
389
+ // src/effects/handlers/seat-change.ts
390
+ var applySeatChange = createEffectHandler("SEAT_CHANGE", () => {
391
+ console.warn("SEAT_CHANGE effect handling not implemented yet.");
392
+ });
393
+
394
+ // src/effects/handlers/status-change.ts
395
+ var applyStatusChange = createEffectHandler("STATUS_CHANGE", ({ effect, payloads, makePlayersEffect }) => {
396
+ const maybeStatus = getSourceValue(effect.source, payloads);
397
+ if (maybeStatus === "DEAD") {
398
+ makePlayersEffect.forEach((player) => {
399
+ player.isDead = true;
400
+ });
401
+ return;
402
+ }
403
+ if (maybeStatus === "ALIVE") {
404
+ makePlayersEffect.forEach((player) => {
405
+ player.isDead = false;
406
+ });
407
+ return;
408
+ }
409
+ console.warn("Invalid status value for STATUS_CHANGE effect:", maybeStatus);
410
+ });
411
+
412
+ // src/effects/registry.ts
413
+ var effectHandlers = {
414
+ ABILITY_CHANGE: applyAbilityChange,
415
+ ALIGNMENT_CHANGE: applyAlignmentChange,
416
+ CHARACTER_CHANGE: applyCharacterChange,
417
+ CHARACTER_COUNT_CHANGE: applyCharacterCountChange,
418
+ GAME_CHANGE: applyGameChange,
419
+ PERCEIVED_CHARACTER_CHANGE: applyPerceivedCharacterChange,
420
+ REMINDER_ADD: applyReminderAdd,
421
+ REMINDER_REMOVE: applyReminderRemove,
422
+ SEAT_CHANGE: applySeatChange,
423
+ STATUS_CHANGE: applyStatusChange
424
+ };
425
+
426
+ // src/effects/resolve-targets.ts
427
+ var isPayloadRef = (value) => {
428
+ if (!value || typeof value !== "object") {
429
+ return false;
430
+ }
431
+ const candidate = value;
432
+ if (candidate.from !== "PAYLOAD") {
433
+ return false;
434
+ }
435
+ return typeof candidate.value === "number" || Array.isArray(candidate.value);
436
+ };
437
+ var resolveDynamicValue = (value, payloads, isExpected) => {
438
+ if (typeof value === "undefined") {
439
+ return void 0;
440
+ }
441
+ if (!isPayloadRef(value)) {
442
+ return isExpected(value) ? value : void 0;
443
+ }
444
+ const resolved = getValueFromPayloads(payloads, value.value);
445
+ if (!isExpected(resolved)) {
446
+ return void 0;
447
+ }
448
+ return resolved;
449
+ };
450
+ var getSortedPlayers = (playerSeatMap) => {
451
+ return [...playerSeatMap.values()].sort((left, right) => left.seat - right.seat);
452
+ };
453
+ var getCircularDistance = (anchorIdx, targetIdx, total) => {
454
+ const clockwise = (targetIdx - anchorIdx + total) % total;
455
+ const anticlockwise = (anchorIdx - targetIdx + total) % total;
456
+ return Math.min(clockwise, anticlockwise);
457
+ };
458
+ var getAnchorSeat = (dynamicTarget, payloads, effector) => {
459
+ const anchor = dynamicTarget.anchor;
460
+ if (!anchor || anchor.from === "EFFECTOR") {
461
+ return effector?.seat;
462
+ }
463
+ if (anchor.from === "STATIC") {
464
+ return anchor.value;
465
+ }
466
+ const payloadSeat = getValueFromPayloads(payloads, anchor.value);
467
+ return typeof payloadSeat === "number" ? payloadSeat : void 0;
468
+ };
469
+ var resolveSelectorScope = (dynamicTarget, payloads) => {
470
+ return resolveDynamicValue(
471
+ dynamicTarget.selector?.scope,
472
+ payloads,
473
+ (value) => value === "BOTH_SIDES" || value === "LEFT_SIDE" || value === "RIGHT_SIDE"
474
+ ) ?? "BOTH_SIDES";
475
+ };
476
+ var getCandidatesBySelector = (dynamicTarget, sortedPlayers, anchorSeat, payloads) => {
477
+ const selector = dynamicTarget.selector;
478
+ if (!selector) {
479
+ return sortedPlayers;
480
+ }
481
+ const scope = resolveSelectorScope(dynamicTarget, payloads);
482
+ if (!anchorSeat) {
483
+ return [];
484
+ }
485
+ const anchorIdx = sortedPlayers.findIndex((player) => player.seat === anchorSeat);
486
+ if (anchorIdx < 0) {
487
+ return [];
488
+ }
489
+ const total = sortedPlayers.length;
490
+ if (scope === "LEFT_SIDE") {
491
+ const left2 = [];
492
+ for (let step = 1; step < total; step += 1) {
493
+ left2.push(sortedPlayers[(anchorIdx - step + total) % total]);
494
+ }
495
+ return left2;
496
+ }
497
+ if (scope === "RIGHT_SIDE") {
498
+ const right2 = [];
499
+ for (let step = 1; step < total; step += 1) {
500
+ right2.push(sortedPlayers[(anchorIdx + step) % total]);
501
+ }
502
+ return right2;
503
+ }
504
+ const left = [];
505
+ const right = [];
506
+ for (let step = 1; step < total; step += 1) {
507
+ left.push(sortedPlayers[(anchorIdx - step + total) % total]);
508
+ right.push(sortedPlayers[(anchorIdx + step) % total]);
509
+ }
510
+ return [...left, ...right];
511
+ };
512
+ var matchesCondition = (player, condition, payloads, characterMap) => {
513
+ if (condition.field === "IS_DEAD") {
514
+ const expected = resolveDynamicValue(condition.value, payloads, (value) => typeof value === "boolean");
515
+ if (typeof expected !== "boolean") {
516
+ return false;
517
+ }
518
+ return Boolean(player.isDead) === expected;
519
+ }
520
+ if (condition.field === "SEAT") {
521
+ if (condition.operator === "IN") {
522
+ const expectedSeats = resolveDynamicValue(condition.value, payloads, (value) => Array.isArray(value) && value.every((item) => typeof item === "number"));
523
+ return Array.isArray(expectedSeats) && expectedSeats.includes(player.seat);
524
+ }
525
+ const expectedSeat = resolveDynamicValue(condition.value, payloads, (value) => typeof value === "number");
526
+ return typeof expectedSeat === "number" && player.seat === expectedSeat;
527
+ }
528
+ const character = characterMap.get(player.characterId);
529
+ const kind = character?.kind;
530
+ if (!kind) {
531
+ return false;
532
+ }
533
+ if (condition.operator === "IN") {
534
+ const expectedKinds = resolveDynamicValue(condition.value, payloads, (value) => Array.isArray(value) && value.every((item) => typeof item === "string"));
535
+ return Array.isArray(expectedKinds) && expectedKinds.includes(kind);
536
+ }
537
+ const expectedKind = resolveDynamicValue(condition.value, payloads, (value) => typeof value === "string");
538
+ return typeof expectedKind === "string" && kind === expectedKind;
539
+ };
540
+ var filterByWhere = (candidates, dynamicTarget, payloads, characterMap) => {
541
+ const where = dynamicTarget.where;
542
+ const conditions = where?.conditions ?? [];
543
+ if (conditions.length === 0) {
544
+ return candidates;
545
+ }
546
+ const isAllMode = where?.mode !== "ANY";
547
+ return candidates.filter((player) => {
548
+ const results = conditions.map((condition) => matchesCondition(player, condition, payloads, characterMap));
549
+ return isAllMode ? results.every(Boolean) : results.some(Boolean);
550
+ });
551
+ };
552
+ var applySort = (candidates, dynamicTarget, payloads, sortedPlayers, anchorSeat) => {
553
+ const scope = resolveSelectorScope(dynamicTarget, payloads);
554
+ if (scope !== "BOTH_SIDES") {
555
+ return [...candidates];
556
+ }
557
+ if (!anchorSeat || sortedPlayers.length <= 1) {
558
+ return [...candidates].sort((left, right) => left.seat - right.seat);
559
+ }
560
+ const seatIndexMap = new Map(sortedPlayers.map((player, idx) => [player.seat, idx]));
561
+ const anchorIdx = seatIndexMap.get(anchorSeat);
562
+ if (typeof anchorIdx !== "number") {
563
+ return [...candidates].sort((left, right) => left.seat - right.seat);
564
+ }
565
+ return [...candidates].sort((left, right) => {
566
+ const leftIdx = seatIndexMap.get(left.seat);
567
+ const rightIdx = seatIndexMap.get(right.seat);
568
+ if (typeof leftIdx !== "number" || typeof rightIdx !== "number") {
569
+ return left.seat - right.seat;
570
+ }
571
+ const leftDistance = getCircularDistance(anchorIdx, leftIdx, sortedPlayers.length);
572
+ const rightDistance = getCircularDistance(anchorIdx, rightIdx, sortedPlayers.length);
573
+ if (leftDistance !== rightDistance) {
574
+ return leftDistance - rightDistance;
575
+ }
576
+ return left.seat - right.seat;
577
+ });
578
+ };
579
+ var pickTargets = (sortedCandidates, dynamicTarget, payloads) => {
580
+ const dedupedCandidates = [...new Map(sortedCandidates.map((player) => [player.seat, player])).values()];
581
+ const configuredLimit = resolveDynamicValue(dynamicTarget.limit, payloads, (value) => typeof value === "number");
582
+ if (typeof configuredLimit === "undefined") {
583
+ return dedupedCandidates;
584
+ }
585
+ if (configuredLimit <= 0) {
586
+ return [];
587
+ }
588
+ return dedupedCandidates.slice(0, configuredLimit);
589
+ };
590
+ var resolveEffectTargets = ({
591
+ effect,
592
+ operation,
593
+ payloads,
594
+ effector,
595
+ playerSeatMap,
596
+ characterMap
597
+ }) => {
598
+ if (!("target" in effect)) {
599
+ return [];
600
+ }
601
+ if (effect.target.from === "EFFECTOR") {
602
+ if (!effector) {
603
+ console.warn("Effector player not found for operation:", operation, "effector index:", operation.effector);
604
+ return null;
605
+ }
606
+ return [effector];
607
+ }
608
+ if (effect.target.from === "PAYLOAD") {
609
+ const seatValue = getValueFromPayloads(payloads, effect.target.value);
610
+ if (typeof seatValue !== "number" && !Array.isArray(seatValue)) {
611
+ console.warn("Expected seat number or array of seat numbers from payloads, got:", seatValue);
612
+ return null;
613
+ }
614
+ const seats = Array.isArray(seatValue) ? seatValue : [seatValue];
615
+ return seats.map((seat) => playerSeatMap.get(seat)).filter((player) => Boolean(player));
616
+ }
617
+ if (effect.target.from === "DYNAMIC") {
618
+ const dynamicTarget = effect.target;
619
+ const sortedPlayers = getSortedPlayers(playerSeatMap);
620
+ const anchorSeat = getAnchorSeat(dynamicTarget, payloads, effector);
621
+ const candidates = getCandidatesBySelector(dynamicTarget, sortedPlayers, anchorSeat, payloads);
622
+ const filtered = filterByWhere(candidates, dynamicTarget, payloads, characterMap);
623
+ const ordered = applySort(filtered, dynamicTarget, payloads, sortedPlayers, anchorSeat);
624
+ return pickTargets(ordered, dynamicTarget, payloads);
625
+ }
626
+ return [];
627
+ };
628
+
629
+ // src/effects/evaluate-lifetime.ts
630
+ var getLifetime = (effect) => {
631
+ if ("lifetime" in effect) {
632
+ return effect.lifetime;
633
+ }
634
+ return void 0;
635
+ };
636
+ var matchesLifetimeCondition = (player, condition, characterMap) => {
637
+ const { field, operator } = condition;
638
+ const value = condition.value;
639
+ if (field === "IS_DEAD") {
640
+ return Boolean(player.isDead) === Boolean(value);
641
+ }
642
+ if (field === "CHARACTER_ID") {
643
+ if (operator === "IN" && Array.isArray(value)) {
644
+ return value.includes(player.characterId);
645
+ }
646
+ return typeof value === "string" && player.characterId === value;
647
+ }
648
+ if (field === "CHARACTER_KIND") {
649
+ const kind = characterMap.get(player.characterId)?.kind;
650
+ if (!kind) return false;
651
+ if (operator === "IN" && Array.isArray(value)) {
652
+ return value.includes(kind);
653
+ }
654
+ return typeof value === "string" && kind === value;
655
+ }
656
+ if (field === "HAS_ABILITY") {
657
+ if (operator === "IN" && Array.isArray(value)) {
658
+ return value.some((id) => player.abilities.includes(id));
659
+ }
660
+ return typeof value === "string" && player.abilities.includes(value);
661
+ }
662
+ return false;
663
+ };
664
+ var evaluateConditions = (player, conditions, mode, characterMap) => {
665
+ if (!player) return false;
666
+ if (conditions.length === 0) return true;
667
+ const results = conditions.map((c) => matchesLifetimeCondition(player, c, characterMap));
668
+ return mode === "ALL" ? results.every(Boolean) : results.some(Boolean);
669
+ };
670
+ var evaluateLifetime = ({
671
+ effect,
672
+ operationTimelineIdx,
673
+ nowTimelineIndex,
674
+ timelines,
675
+ effector,
676
+ targets,
677
+ snapshotSeatMap,
678
+ characterMap
679
+ }) => {
680
+ const lifetime = getLifetime(effect);
681
+ if (!lifetime || lifetime.kind === "PERMANENT") {
682
+ return targets;
683
+ }
684
+ if (lifetime.kind === "TURNS") {
685
+ const opTurn = operationTimelineIdx >= 0 ? timelines[operationTimelineIdx]?.turn : void 0;
686
+ const nowTurn = nowTimelineIndex >= 0 ? timelines[nowTimelineIndex]?.turn : void 0;
687
+ if (typeof opTurn !== "number" || typeof nowTurn !== "number") {
688
+ return targets;
689
+ }
690
+ return nowTurn - opTurn < lifetime.count ? targets : [];
691
+ }
692
+ if (lifetime.kind === "UNTIL_EVENT") {
693
+ if (operationTimelineIdx < 0) return targets;
694
+ for (let idx = operationTimelineIdx + 1; idx <= nowTimelineIndex; idx += 1) {
695
+ const tl = timelines[idx];
696
+ if (!tl) continue;
697
+ if (lifetime.event === "NEXT_DAY" && tl.time === "day") return [];
698
+ if (lifetime.event === "NEXT_NIGHT" && tl.time === "night") return [];
699
+ if (lifetime.event === "NEXT_EXECUTION" && (tl.nominations?.length ?? 0) > 0) return [];
700
+ }
701
+ return targets;
702
+ }
703
+ if (lifetime.kind === "WHILE") {
704
+ if (!snapshotSeatMap) {
705
+ return targets;
706
+ }
707
+ const subject = lifetime.subject ?? "EFFECTOR";
708
+ const mode = lifetime.mode ?? "ALL";
709
+ const conditions = lifetime.conditions ?? [];
710
+ if (subject === "EFFECTOR") {
711
+ const current = effector ? snapshotSeatMap.get(effector.seat) : void 0;
712
+ return evaluateConditions(current, conditions, mode, characterMap) ? targets : [];
713
+ }
714
+ return targets.filter((target) => {
715
+ const current = snapshotSeatMap.get(target.seat);
716
+ return evaluateConditions(current, conditions, mode, characterMap);
717
+ });
718
+ }
719
+ return targets;
720
+ };
721
+
123
722
  // src/apply-operation.ts
723
+ var isDeferredOperation = (operation, abilityMap) => {
724
+ const ability = abilityMap.get(operation.abilityId);
725
+ return ability?.executionTiming === "DEFER_TO_END";
726
+ };
727
+ var hasGatedLifetime = (allAbilities) => {
728
+ return allAbilities.some((ability) => ability.effects.some((effect) => {
729
+ if (!("lifetime" in effect)) return false;
730
+ const lifetime = effect.lifetime;
731
+ return Boolean(lifetime) && lifetime?.kind !== "PERMANENT";
732
+ }));
733
+ };
124
734
  var applyOperationToPlayers = ({
125
735
  players,
126
736
  operations,
@@ -136,7 +746,6 @@ var applyOperationToPlayers = ({
136
746
  const characterMap = new Map(characters.map((character) => [character.id, character]));
137
747
  const operationTimelineMap = /* @__PURE__ */ new Map();
138
748
  timelines.forEach((timeline, idx) => timeline.operations?.forEach((op) => operationTimelineMap.set(op, idx)));
139
- const playersWithStatus = copyPlayers(players);
140
749
  const nowTimelineIndex = typeof timelineIndexAtNow === "number" ? timelineIndexAtNow : timelines.length - 1;
141
750
  const operationsByTimeline = /* @__PURE__ */ new Map();
142
751
  operations.forEach((operation) => {
@@ -146,216 +755,124 @@ var applyOperationToPlayers = ({
146
755
  }
147
756
  operationsByTimeline.get(timelineIndex)?.push(operation);
148
757
  });
149
- const applyOps = (ops) => {
150
- ops.forEach((operation) => {
151
- const operationInTimelineIdx = operationTimelineMap.get(operation) ?? -1;
152
- const ability = abilityMap.get(operation.abilityId);
153
- if (!ability) {
154
- console.warn("Ability not found for operation:", operation);
155
- return;
156
- }
157
- const playerSeatMap = buildPlayerSeatMap(playersWithStatus);
158
- const effector = playerSeatMap.get(operation.effector);
159
- const payloads = operation.payloads || [];
160
- const writableParts = ability.inputs.filter((part) => !part.readonly);
161
- let snapshotSeatMap = null;
162
- const getSnapshotSeatMap = () => {
163
- if (!snapshotSeatMap) {
164
- snapshotSeatMap = buildPlayerSeatMap(copyPlayers(playersWithStatus));
165
- }
166
- return snapshotSeatMap;
167
- };
168
- ability.effects.forEach((effect) => {
169
- const makePlayersEffect = [];
170
- if (effect.type === "GAME_CHANGE" || effect.type === "CHARACTER_COUNT_CHANGE") {
171
- console.warn(effect.type + " effect handling not implemented yet.");
758
+ const runReplay = (lifetimeSnapshotSeatMap) => {
759
+ const playersWithStatus = copyPlayers(players);
760
+ const applyOpsSequence = (ops) => {
761
+ ops.forEach((operation) => {
762
+ const operationInTimelineIdx = operationTimelineMap.get(operation) ?? -1;
763
+ const ability = abilityMap.get(operation.abilityId);
764
+ if (!ability) {
765
+ console.warn("Ability not found for operation:", operation);
172
766
  return;
173
767
  }
174
- if (effect.target.from === "EFFECTOR") {
175
- if (!effector) {
176
- console.warn("Effector player not found for operation:", operation, "effector index:", operation.effector);
177
- return;
768
+ const playerSeatMap = buildPlayerSeatMap(playersWithStatus);
769
+ const effector = playerSeatMap.get(operation.effector);
770
+ const payloads = operation.payloads || [];
771
+ const writableInputs = ability.inputs.filter((part) => !part.readonly);
772
+ let snapshotSeatMap = null;
773
+ const getSnapshotSeatMap = () => {
774
+ if (!snapshotSeatMap) {
775
+ snapshotSeatMap = buildPlayerSeatMap(copyPlayers(playersWithStatus));
178
776
  }
179
- makePlayersEffect.push(effector);
180
- } else if (effect.target.from === "PAYLOAD") {
181
- const seatValue = getValueFromPayloads(payloads, effect.target.value);
182
- if (typeof seatValue !== "number" && !Array.isArray(seatValue)) {
183
- console.warn("Expected seat number or array of seat numbers from payloads, got:", seatValue);
777
+ return snapshotSeatMap;
778
+ };
779
+ ability.effects.forEach((effect) => {
780
+ const resolvedTargets = resolveEffectTargets({
781
+ effect,
782
+ operation,
783
+ payloads,
784
+ effector,
785
+ playerSeatMap,
786
+ characterMap
787
+ });
788
+ if (!resolvedTargets) {
184
789
  return;
185
790
  }
186
- const seats = Array.isArray(seatValue) ? seatValue : [seatValue];
187
- seats.forEach((seat) => {
188
- const player = playerSeatMap.get(seat);
189
- if (player) {
190
- makePlayersEffect.push(player);
191
- }
791
+ const makePlayersEffect = evaluateLifetime({
792
+ effect,
793
+ operationTimelineIdx: operationInTimelineIdx,
794
+ nowTimelineIndex,
795
+ timelines,
796
+ effector,
797
+ targets: resolvedTargets,
798
+ snapshotSeatMap: lifetimeSnapshotSeatMap,
799
+ characterMap
192
800
  });
193
- } else if (effect.target.from === "CUSTOM") {
194
- console.warn("Custom target handling not implemented yet.");
195
- }
196
- switch (effect.type) {
197
- case "ABILITY_CHANGE": {
198
- console.warn("ABILITY_CHANGE effect handling not implemented yet.");
199
- break;
200
- }
201
- case "ALIGNMENT_CHANGE": {
202
- const resolved = resolveSourceValue(
203
- effect.source,
204
- writableParts,
205
- payloads,
206
- effector,
207
- getSnapshotSeatMap(),
208
- (player) => player.alignment
209
- );
210
- let alignment;
211
- if (resolved === "GOOD" || resolved === "EVIL") {
212
- alignment = resolved;
213
- }
214
- if (!alignment) {
215
- console.warn("Alignment not found for ALIGNMENT_CHANGE effect:", effect.source);
216
- return;
217
- }
218
- makePlayersEffect.forEach((player) => {
219
- player.alignment = alignment;
220
- });
221
- break;
222
- }
223
- case "CHARACTER_CHANGE":
224
- case "PERCEIVED_CHARACTER_CHANGE": {
225
- const resolvedCharacterId = resolveSourceValue(
226
- effect.source,
227
- writableParts,
228
- payloads,
229
- effector,
230
- getSnapshotSeatMap(),
231
- (player) => player.characterId
232
- );
233
- let characterId;
234
- if (typeof resolvedCharacterId === "string") {
235
- characterId = resolvedCharacterId;
236
- } else if (Array.isArray(resolvedCharacterId) && typeof resolvedCharacterId[0] === "string") {
237
- characterId = resolvedCharacterId[0];
238
- }
239
- if (!characterId) {
240
- console.warn("Character ID not found for " + effect.type + " effect:", effect.source);
241
- return;
242
- }
243
- const newCharacter = characterMap.get(characterId);
244
- if (!newCharacter) {
245
- console.warn("Character not found for " + effect.type + " effect:", characterId);
246
- return;
247
- }
248
- if (effect.type === "CHARACTER_CHANGE") {
249
- const abilityIds = newCharacter.abilities.map((ability2) => ability2.id);
250
- makePlayersEffect.forEach((player) => {
251
- player.characterId = newCharacter.id;
252
- player.abilities = abilityIds;
253
- });
254
- } else {
255
- makePlayersEffect.forEach((player) => {
256
- player.perceivedCharacter = {
257
- characterId: newCharacter.id,
258
- abilities: newCharacter.abilities.map((ability2) => ability2.id),
259
- asCharacter: effect.followPriority || false
260
- };
261
- });
262
- }
263
- break;
264
- }
265
- case "REMINDER_ADD": {
266
- const maybeReminder = getSourceValue(effect.source, payloads);
267
- if (!isReminder(maybeReminder)) {
268
- console.warn("Invalid reminder data for REMINDER_ADD effect:", maybeReminder);
269
- return;
270
- }
271
- const timelineDistance = nowTimelineIndex - operationInTimelineIdx;
272
- if (typeof maybeReminder.duration === "number" && maybeReminder.duration > 0 && timelineDistance >= maybeReminder.duration) {
273
- break;
274
- }
275
- makePlayersEffect.forEach((player) => {
276
- if (!player.reminders) {
277
- player.reminders = [];
278
- }
279
- player.reminders.push(maybeReminder);
280
- });
281
- break;
282
- }
283
- case "REMINDER_REMOVE": {
284
- const maybeReminder = getSourceValue(effect.source, payloads);
285
- if (!isPlayerReminderArray(maybeReminder)) {
286
- console.warn("Invalid reminder data for REMINDER_REMOVE effect:", maybeReminder);
287
- return;
288
- }
289
- maybeReminder.sort((left, right) => right.index - left.index).forEach((reminder) => {
290
- const player = playerSeatMap.get(reminder.playerSeat);
291
- if (!player) {
292
- console.warn("Player not found for REMINDER_REMOVE effect:", reminder.playerSeat);
293
- return;
294
- }
295
- if (!player.reminders) {
296
- player.reminders = [];
297
- }
298
- player.reminders = player.reminders.filter((_value, index) => index !== reminder.index);
299
- });
300
- break;
301
- }
302
- case "SEAT_CHANGE": {
303
- console.warn("SEAT_CHANGE effect handling not implemented yet.");
304
- break;
305
- }
306
- case "STATUS_CHANGE": {
307
- const maybeStatus = getSourceValue(effect.source, payloads);
308
- if (maybeStatus === "DEAD") {
309
- makePlayersEffect.forEach((player) => {
310
- player.isDead = true;
311
- });
312
- } else if (maybeStatus === "ALIVE") {
313
- makePlayersEffect.forEach((player) => {
314
- player.isDead = false;
315
- });
316
- } else {
317
- console.warn("Invalid status value for STATUS_CHANGE effect:", maybeStatus);
318
- }
319
- break;
320
- }
321
- default: {
801
+ const handler = effectHandlers[effect.type];
802
+ if (!handler) {
322
803
  console.warn("Unknown effect type:", effect.type);
804
+ return;
323
805
  }
324
- }
806
+ const context = {
807
+ effect,
808
+ operation,
809
+ payloads,
810
+ effector,
811
+ writableInputs,
812
+ playerSeatMap,
813
+ getSnapshotSeatMap,
814
+ characterMap,
815
+ abilityMap,
816
+ nowTimelineIndex,
817
+ operationInTimelineIdx,
818
+ makePlayersEffect
819
+ };
820
+ handler(context);
821
+ });
325
822
  });
326
- });
327
- };
328
- const settingsOps = operationsByTimeline.get(-1);
329
- if (settingsOps) {
330
- applyOps(settingsOps);
331
- }
332
- for (let i = 0; i <= nowTimelineIndex; i += 1) {
333
- const timeline = timelines[i];
334
- if (!timeline) {
335
- continue;
336
- }
337
- const nominations = timeline.nominations;
338
- if (nominations && nominations.length > 0) {
339
- const playerSeatMap = buildPlayerSeatMap(playersWithStatus);
340
- nominations.forEach((nomination) => {
341
- const voterSeats = nomination.voterSeats;
342
- if (!voterSeats || voterSeats.length === 0) {
823
+ };
824
+ const applyOps = (ops) => {
825
+ const normalOps = [];
826
+ const deferredOps = [];
827
+ ops.forEach((operation) => {
828
+ if (isDeferredOperation(operation, abilityMap)) {
829
+ deferredOps.push(operation);
343
830
  return;
344
831
  }
345
- voterSeats.forEach((seat) => {
346
- const player = playerSeatMap.get(seat);
347
- if (player && player.isDead && !player.hasUsedDeadVote) {
348
- player.hasUsedDeadVote = true;
349
- }
350
- });
832
+ normalOps.push(operation);
351
833
  });
834
+ applyOpsSequence(normalOps);
835
+ applyOpsSequence(deferredOps);
836
+ };
837
+ const settingsOps = operationsByTimeline.get(-1);
838
+ if (settingsOps) {
839
+ applyOps(settingsOps);
352
840
  }
353
- const timelineOps = operationsByTimeline.get(i);
354
- if (timelineOps) {
355
- applyOps(timelineOps);
841
+ for (let i = 0; i <= nowTimelineIndex; i += 1) {
842
+ const timeline = timelines[i];
843
+ if (!timeline) {
844
+ continue;
845
+ }
846
+ const nominations = timeline.nominations;
847
+ if (nominations && nominations.length > 0) {
848
+ const playerSeatMap = buildPlayerSeatMap(playersWithStatus);
849
+ nominations.forEach((nomination) => {
850
+ const voterSeats = nomination.voterSeats;
851
+ if (!voterSeats || voterSeats.length === 0) {
852
+ return;
853
+ }
854
+ voterSeats.forEach((seat) => {
855
+ const player = playerSeatMap.get(seat);
856
+ if (player && player.isDead && !player.hasUsedDeadVote) {
857
+ player.hasUsedDeadVote = true;
858
+ }
859
+ });
860
+ });
861
+ }
862
+ const timelineOps = operationsByTimeline.get(i);
863
+ if (timelineOps) {
864
+ applyOps(timelineOps);
865
+ }
356
866
  }
867
+ return playersWithStatus;
868
+ };
869
+ if (!hasGatedLifetime(allAbilities)) {
870
+ return transformEmptyArray(runReplay(null));
357
871
  }
358
- return transformEmptyArray(playersWithStatus);
872
+ const groundTruth = runReplay(null);
873
+ const groundTruthSeatMap = buildPlayerSeatMap(groundTruth);
874
+ const final = runReplay(groundTruthSeatMap);
875
+ return transformEmptyArray(final);
359
876
  };
360
877
  export {
361
878
  adjustValueAsNumber,