@dreamboard-games/sdk 0.5.0-alpha.34 → 0.5.0-alpha.35

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.
@@ -11,7 +11,7 @@ import {
11
11
  boardSpaceHostId,
12
12
  isCardReferenceNamespace,
13
13
  parseBoardSpaceHostId
14
- } from "./chunk-BSS4ORU3.js";
14
+ } from "./chunk-G4MY5YMA.js";
15
15
  import {
16
16
  AuthoredTileDisclosureSchema,
17
17
  BoardProjectionSchema,
@@ -23,6 +23,7 @@ import {
23
23
  SeatTileRefSchema,
24
24
  TileDisclosureSchema,
25
25
  TilePlacementSchema,
26
+ canonicalizeInputSelection,
26
27
  canonicalizePluginRuntimeJson,
27
28
  createBoardTopologyCache,
28
29
  createHexTopologyCache,
@@ -39,7 +40,7 @@ import {
39
40
  requireLookup,
40
41
  tileSpaceId,
41
42
  zonePositions
42
- } from "./chunk-CZRPUWCT.js";
43
+ } from "./chunk-7GX27XU6.js";
43
44
 
44
45
  // src/reducer/model/error-codes.ts
45
46
  var FrameworkErrorCodes = {
@@ -180,6 +181,216 @@ function normalizeCommandParams(schema, input) {
180
181
  return schema.parse(normalizeSchemaInput(schema, input));
181
182
  }
182
183
 
184
+ // src/reducer/inputs/combinations.ts
185
+ function* enumerateCombinations(values, count) {
186
+ if (!Number.isSafeInteger(count) || count < 0) {
187
+ throw new RangeError("Combination count must be a nonnegative integer.");
188
+ }
189
+ yield* combinationsFrom(values, count, 0, []);
190
+ }
191
+ function* combinationsFrom(values, remaining, start, current) {
192
+ if (remaining === 0) {
193
+ yield [...current];
194
+ return;
195
+ }
196
+ for (let index = start; index <= values.length - remaining; index += 1) {
197
+ yield* combinationsFrom(values, remaining - 1, index + 1, [
198
+ ...current,
199
+ values[index]
200
+ ]);
201
+ }
202
+ }
203
+
204
+ // src/reducer/bundle/define-bots.ts
205
+ var registeredStrategies = /* @__PURE__ */ Symbol(
206
+ "registeredStrategies"
207
+ );
208
+ var diagnosticMessages = {
209
+ unsupported_interaction: "Unsupported interaction for bot scoring.",
210
+ missing_handler: "Missing bot score handler.",
211
+ invalid_binding: "Card input name or resolver is incompatible with bot scoring.",
212
+ resolver_failed: "Bot card resolver failed. Every eligible card must resolve exactly once.",
213
+ scorer_failed: "Bot scorer failed.",
214
+ invalid_score: "Bot score must be finite.",
215
+ candidate_generator_failed: "Bot candidate generator failed.",
216
+ invalid_candidate: "Bot proposal must contain the required number of distinct eligible cards."
217
+ };
218
+ var BotStrategyError = class extends Error {
219
+ constructor(category, interactionKey) {
220
+ super(diagnosticMessages[category]);
221
+ this.category = category;
222
+ this.interactionKey = interactionKey;
223
+ }
224
+ category;
225
+ interactionKey;
226
+ name = "BotStrategyError";
227
+ };
228
+ function resolvedCards(resolve, view, ids, interactionKey) {
229
+ const byId = /* @__PURE__ */ new Map();
230
+ const wanted = new Set(ids);
231
+ try {
232
+ for (const card of resolve(view)) {
233
+ const { id: id2 } = card;
234
+ if (!wanted.has(id2)) continue;
235
+ if (byId.has(id2)) {
236
+ throw new BotStrategyError("resolver_failed", interactionKey);
237
+ }
238
+ byId.set(id2, card);
239
+ }
240
+ } catch {
241
+ throw new BotStrategyError("resolver_failed", interactionKey);
242
+ }
243
+ return Array.from(wanted, (id2) => {
244
+ const card = byId.get(id2);
245
+ if (!card) throw new BotStrategyError("resolver_failed", interactionKey);
246
+ return { id: id2, card };
247
+ });
248
+ }
249
+ function* generatedProposals(handler, context, interactionKey) {
250
+ try {
251
+ yield* handler.candidates(context);
252
+ } catch {
253
+ throw new BotStrategyError("candidate_generator_failed", interactionKey);
254
+ }
255
+ }
256
+ function* proposedSelections(handler, eligible, count, alias, view, interactionKey) {
257
+ const context = {
258
+ view,
259
+ eligible: { [alias]: eligible.map(({ card }) => card) },
260
+ selection: { [alias]: { count } }
261
+ };
262
+ for (const proposal of generatedProposals(handler, context, interactionKey)) {
263
+ let ordered;
264
+ try {
265
+ const cards = proposal?.[alias];
266
+ if (!Array.isArray(cards) || cards.length !== count) {
267
+ throw new BotStrategyError("invalid_candidate", interactionKey);
268
+ }
269
+ const proposedIds = new Set(cards.map(({ id: id2 }) => id2));
270
+ ordered = eligible.filter(({ id: id2 }) => proposedIds.has(id2));
271
+ } catch {
272
+ throw new BotStrategyError("invalid_candidate", interactionKey);
273
+ }
274
+ if (ordered.length !== count) {
275
+ throw new BotStrategyError("invalid_candidate", interactionKey);
276
+ }
277
+ yield ordered;
278
+ }
279
+ }
280
+ function* candidates(offer, view, resolve, handler) {
281
+ if (offer.step || offer.inputs.length > 1) {
282
+ throw new BotStrategyError("unsupported_interaction", offer.interactionKey);
283
+ }
284
+ const [input] = offer.inputs;
285
+ const generate = typeof handler !== "function";
286
+ if (generate && input?.domain.selection?.mode !== "many") {
287
+ throw new BotStrategyError("unsupported_interaction", offer.interactionKey);
288
+ }
289
+ if (!input) {
290
+ yield { args: {}, params: {} };
291
+ return;
292
+ }
293
+ if (input.kind !== "card" || input.domain.type !== "cardTarget" || !resolve) {
294
+ throw new BotStrategyError("invalid_binding", offer.interactionKey);
295
+ }
296
+ const { key, domain } = input;
297
+ const selection = domain.selection;
298
+ const multiple = selection?.mode === "many";
299
+ const suffix = multiple ? "Ids" : "Id";
300
+ const name = key.endsWith(suffix) ? key.slice(0, -suffix.length) : "";
301
+ const alias = multiple ? name + "s" : name;
302
+ if (!name || alias === "view") {
303
+ throw new BotStrategyError("invalid_binding", offer.interactionKey);
304
+ }
305
+ const eligible = resolvedCards(
306
+ resolve,
307
+ view,
308
+ domain.eligibleTargets,
309
+ offer.interactionKey
310
+ );
311
+ if (!multiple) {
312
+ for (const { card, id: id2 } of eligible) {
313
+ yield { args: { [alias]: card }, params: { [key]: id2 } };
314
+ }
315
+ return;
316
+ }
317
+ if (!selection.distinct || selection.min !== selection.max) {
318
+ throw new BotStrategyError("unsupported_interaction", offer.interactionKey);
319
+ }
320
+ const selections = generate ? proposedSelections(
321
+ handler,
322
+ eligible,
323
+ selection.min,
324
+ alias,
325
+ view,
326
+ offer.interactionKey
327
+ ) : enumerateCombinations(eligible, selection.min);
328
+ for (const cards of selections) {
329
+ yield {
330
+ args: { [alias]: cards.map(({ card }) => card) },
331
+ params: { [key]: cards.map(({ id: id2 }) => id2) }
332
+ };
333
+ }
334
+ }
335
+ function scoredStrategy(strategy, resolve) {
336
+ const score = new Map(
337
+ Object.entries(
338
+ strategy.score
339
+ )
340
+ );
341
+ return {
342
+ id: strategy.id,
343
+ name: strategy.name,
344
+ description: strategy.description,
345
+ decide(frame) {
346
+ const { view } = frame;
347
+ if (view == null) return null;
348
+ let bestScore = -Infinity;
349
+ let decision = null;
350
+ for (const offer of frame.availableInteractions) {
351
+ if (offer.availability.status !== "available") continue;
352
+ const handler = score.get(offer.interactionKey);
353
+ if (handler === "skip") continue;
354
+ if (!handler) {
355
+ throw new BotStrategyError("missing_handler", offer.interactionKey);
356
+ }
357
+ for (const { args, params } of candidates(
358
+ offer,
359
+ view,
360
+ resolve,
361
+ handler
362
+ )) {
363
+ let value;
364
+ try {
365
+ const context = { ...args, view };
366
+ value = typeof handler === "function" ? handler(context) : handler.score(context);
367
+ } catch {
368
+ throw new BotStrategyError("scorer_failed", offer.interactionKey);
369
+ }
370
+ if (!Number.isFinite(value)) {
371
+ throw new BotStrategyError("invalid_score", offer.interactionKey);
372
+ }
373
+ if (value > bestScore) {
374
+ bestScore = value;
375
+ decision = {
376
+ interactionId: offer.interactionId,
377
+ params
378
+ };
379
+ }
380
+ }
381
+ }
382
+ return decision;
383
+ }
384
+ };
385
+ }
386
+ function defineBots(_game, config) {
387
+ return {
388
+ [registeredStrategies]: config.strategies.map(
389
+ (strategy) => scoredStrategy(strategy, config.resolve.card)
390
+ )
391
+ };
392
+ }
393
+
183
394
  // src/shared/worker-contract.ts
184
395
  import * as z3 from "zod";
185
396
  var REDUCER_CONTRACT_VERSION = "0.11.0";
@@ -1535,8 +1746,14 @@ function createStateQueries(state, definitions) {
1535
1746
  }
1536
1747
 
1537
1748
  // src/reducer/bundle/bot-strategies.ts
1538
- function createBotCapability(strategies) {
1539
- if (!strategies?.length) return {};
1749
+ function createBotCapability(registration) {
1750
+ if (!registration) return {};
1751
+ const strategies = registration[registeredStrategies];
1752
+ if (!strategies)
1753
+ throw new TypeError(
1754
+ "Register bot strategies with defineBots(game, config)."
1755
+ );
1756
+ if (!strategies.length) return {};
1540
1757
  const botStrategies = BotStrategyCatalogSchema.parse(
1541
1758
  strategies.map(({ id: id2, name, description }) => ({ id: id2, name, description }))
1542
1759
  );
@@ -3304,11 +3521,22 @@ function makeValidationError(errorCode, message) {
3304
3521
  }
3305
3522
 
3306
3523
  // src/reducer/bundle/trusted/collector-params.ts
3307
- function parseInteractionParams(interaction, rawParams, options = {}) {
3524
+ function parseInteractionParams(interaction, rawParams, options) {
3308
3525
  const collectors = interactionInputsOf(interaction);
3309
3526
  const record3 = rawParams ?? {};
3310
3527
  if (interaction.paramsSchema) {
3311
- const result = interaction.paramsSchema.safeParse(record3);
3528
+ const normalized = { ...record3 };
3529
+ let q;
3530
+ for (const [key, collector] of Object.entries(collectors)) {
3531
+ const selection = collector.selection;
3532
+ if (selection?.mode !== "many") continue;
3533
+ const value = normalized[key];
3534
+ if (!Array.isArray(value)) continue;
3535
+ q ??= createStateQueries(options.state, options.definitions);
3536
+ const domain = collector.domain?.(options.state, options.playerId, q);
3537
+ normalized[key] = canonicalizeInputSelection(value, selection, domain);
3538
+ }
3539
+ const result = interaction.paramsSchema.safeParse(normalized);
3312
3540
  if (!result.success) {
3313
3541
  return {
3314
3542
  ok: false,
@@ -3365,14 +3593,25 @@ function validateCollectorTargets(interaction, domainState, playerId, params, de
3365
3593
  let queriesLazy = null;
3366
3594
  const queries = () => queriesLazy ??= createStateQueries(domainState, definitions);
3367
3595
  for (const [key, collector] of Object.entries(collectors)) {
3596
+ const value = params[key];
3597
+ const q = queries();
3598
+ const domain = collector.domain?.(domainState, playerId, q);
3368
3599
  const issue = validateCollectorValue(
3369
3600
  collector,
3370
3601
  domainState,
3371
3602
  playerId,
3372
- queries(),
3373
- params[key]
3603
+ q,
3604
+ value,
3605
+ domain
3374
3606
  );
3375
3607
  if (issue) return makeValidationError(issue.errorCode, issue.message);
3608
+ if (collector.selection?.mode === "many") {
3609
+ params[key] = canonicalizeInputSelection(
3610
+ value,
3611
+ collector.selection,
3612
+ domain
3613
+ );
3614
+ }
3376
3615
  }
3377
3616
  return { valid: true };
3378
3617
  }
@@ -3610,9 +3849,15 @@ function evaluateStepPrefix(steps, state, playerId, values, definitions) {
3610
3849
  issue = `Value for step '${entry.key}' is no longer eligible.`;
3611
3850
  break;
3612
3851
  }
3613
- selected[entry.key] = parsed.data;
3852
+ selected[entry.key] = canonicalizeInputSelection(
3853
+ parsed.data,
3854
+ collector.selection,
3855
+ domain
3856
+ );
3614
3857
  collectors[entry.key] = collector;
3615
- validValues.push(value);
3858
+ validValues.push(
3859
+ canonicalizeInputSelection(value, collector.selection, domain)
3860
+ );
3616
3861
  current = void 0;
3617
3862
  }
3618
3863
  if (values.length > steps.entries.length)
@@ -3786,16 +4031,19 @@ function valueSourceForCollector(context, inputKey, collector) {
3786
4031
  );
3787
4032
  const base = baseValuesForDomain(domain, collector, context);
3788
4033
  const selection = collector.selection ?? domain.selection;
3789
- const selected = applySelection(base, selection);
4034
+ const selected = applySelection(base, selection, domain);
3790
4035
  const resolved = collector.schema.safeParse(void 0).success ? withAbsentCollectorValue(selected) : selected;
3791
4036
  if (!hasFixedValue) return resolved;
3792
4037
  if (selection?.mode === "many" && Array.isArray(fixedValue) && base.complete) {
3793
4038
  const keys = fixedValue.map(canonicalJson);
3794
4039
  const valid = collector.schema.safeParse(fixedValue).success && fixedValue.length >= selection.min && (selection.max === void 0 || fixedValue.length <= selection.max) && (!selection.distinct || new Set(keys).size === keys.length) && fixedValue.every((value) => sourceContainsValue(base, value));
3795
- return { complete: true, values: () => valid ? [fixedValue] : [] };
4040
+ return {
4041
+ complete: true,
4042
+ values: () => valid ? [canonicalizeInputSelection(fixedValue, selection, domain)] : []
4043
+ };
3796
4044
  }
3797
4045
  if (!resolved.complete) {
3798
- return fixedCollectorValueSource(context, collector, fixedValue);
4046
+ return fixedCollectorValueSource(context, collector, fixedValue, domain);
3799
4047
  }
3800
4048
  if (selection?.mode === "many" && !Array.isArray(fixedValue)) {
3801
4049
  const eligible = sourceContainsValue(base, fixedValue);
@@ -3822,7 +4070,7 @@ function sourceContainsValue(source, value) {
3822
4070
  }
3823
4071
  return false;
3824
4072
  }
3825
- function fixedCollectorValueSource(context, collector, fixedValue) {
4073
+ function fixedCollectorValueSource(context, collector, fixedValue, domain) {
3826
4074
  const schemaResult = collector.schema.safeParse(fixedValue);
3827
4075
  const targetValues = collector.selection?.mode === "many" && Array.isArray(fixedValue) ? fixedValue : [fixedValue];
3828
4076
  const targetValid = targetValues.every(
@@ -3836,7 +4084,13 @@ function fixedCollectorValueSource(context, collector, fixedValue) {
3836
4084
  return {
3837
4085
  complete: true,
3838
4086
  values: function* () {
3839
- if (schemaResult.success && targetValid) yield fixedValue;
4087
+ if (schemaResult.success && targetValid) {
4088
+ yield canonicalizeInputSelection(
4089
+ fixedValue,
4090
+ collector.selection,
4091
+ domain
4092
+ );
4093
+ }
3840
4094
  }
3841
4095
  };
3842
4096
  }
@@ -3981,12 +4235,12 @@ function choiceListValueSource(domain) {
3981
4235
  complete: true,
3982
4236
  values: function* () {
3983
4237
  for (let count = min; count <= cappedMax; count += 1) {
3984
- yield* enumerateCombinations(choices, count, 0, []);
4238
+ yield* enumerateCombinations(choices, count);
3985
4239
  }
3986
4240
  }
3987
4241
  };
3988
4242
  }
3989
- function applySelection(source, selection) {
4243
+ function applySelection(source, selection, domain) {
3990
4244
  if (selection?.mode !== "many") return source;
3991
4245
  if (!source.complete) return incompleteValueSource();
3992
4246
  const min = selection.min;
@@ -3995,44 +4249,29 @@ function applySelection(source, selection) {
3995
4249
  if (max !== void 0 && (!Number.isSafeInteger(max) || max < min)) {
3996
4250
  return incompleteValueSource();
3997
4251
  }
3998
- if (max === void 0 && !selection.distinct) {
3999
- return {
4000
- complete: false,
4001
- values: function* () {
4002
- yield* enumerateSequencesFromSource(source.values, min, []);
4003
- }
4004
- };
4005
- }
4252
+ const distinct = selection.distinct === true;
4006
4253
  return {
4007
- complete: true,
4254
+ complete: max !== void 0 || distinct,
4008
4255
  values: function* () {
4009
- if (selection.distinct && max === void 0) {
4010
- for (let count = min; ; count += 1) {
4011
- let yielded = false;
4012
- for (const combination of enumerateCombinationsFromSource(
4013
- source.values,
4014
- count,
4015
- 0,
4016
- []
4017
- )) {
4018
- yielded = true;
4019
- yield combination;
4020
- }
4021
- if (!yielded) return;
4022
- }
4023
- }
4024
- const finiteMax = max ?? min;
4025
- for (let count = min; count <= finiteMax; count += 1) {
4026
- if (selection.distinct) {
4027
- yield* enumerateCombinationsFromSource(source.values, count, 0, []);
4028
- } else {
4029
- yield* enumerateSequencesFromSource(source.values, count, []);
4256
+ const upper = max ?? (distinct ? Infinity : min);
4257
+ for (let count = min; count <= upper; count += 1) {
4258
+ let yielded = false;
4259
+ for (const combination of enumerateCombinationsFromSource(
4260
+ source.values,
4261
+ count,
4262
+ distinct,
4263
+ 0,
4264
+ []
4265
+ )) {
4266
+ yielded = true;
4267
+ yield canonicalizeInputSelection(combination, selection, domain);
4030
4268
  }
4269
+ if (!yielded) return;
4031
4270
  }
4032
4271
  }
4033
4272
  };
4034
4273
  }
4035
- function* enumerateCombinationsFromSource(values, count, start, current) {
4274
+ function* enumerateCombinationsFromSource(values, count, distinct, start, current) {
4036
4275
  if (current.length === count) {
4037
4276
  yield [...current];
4038
4277
  return;
@@ -4040,35 +4279,17 @@ function* enumerateCombinationsFromSource(values, count, start, current) {
4040
4279
  let index = 0;
4041
4280
  for (const value of values()) {
4042
4281
  if (index >= start) {
4043
- yield* enumerateCombinationsFromSource(values, count, index + 1, [
4044
- ...current,
4045
- value
4046
- ]);
4282
+ yield* enumerateCombinationsFromSource(
4283
+ values,
4284
+ count,
4285
+ distinct,
4286
+ distinct ? index + 1 : index,
4287
+ [...current, value]
4288
+ );
4047
4289
  }
4048
4290
  index += 1;
4049
4291
  }
4050
4292
  }
4051
- function* enumerateSequencesFromSource(values, count, current) {
4052
- if (current.length === count) {
4053
- yield [...current];
4054
- return;
4055
- }
4056
- for (const value of values()) {
4057
- yield* enumerateSequencesFromSource(values, count, [...current, value]);
4058
- }
4059
- }
4060
- function* enumerateCombinations(values, count, start, current) {
4061
- if (current.length === count) {
4062
- yield [...current];
4063
- return;
4064
- }
4065
- for (let index = start; index < values.length; index += 1) {
4066
- yield* enumerateCombinations(values, count, index + 1, [
4067
- ...current,
4068
- values[index]
4069
- ]);
4070
- }
4071
- }
4072
4293
  function canonicalJson(value) {
4073
4294
  return JSON.stringify(canonicalizeJson(value));
4074
4295
  }
@@ -4601,7 +4822,10 @@ function createInteractionDecisionResolver(scope, authorization, options = {}) {
4601
4822
  ok: true,
4602
4823
  params: finalStepSchema?.success ? finalStepSchema.data : submittedPrefix.selected
4603
4824
  } : parseForSubmit ? parseInteractionParams(interaction, params, {
4604
- skipRng: true
4825
+ skipRng: true,
4826
+ state: projection?.domainState ?? scope.toDomainState(state),
4827
+ playerId,
4828
+ definitions: scope.manifest
4605
4829
  }) : {
4606
4830
  ok: true,
4607
4831
  params: prepareInteractionProjectionParams(interaction, params)
@@ -5622,7 +5846,7 @@ function createSeatDisclosure(table, definitions, playerId, referenceBasis) {
5622
5846
  if (!boardAccess(boardId).inventory) continue;
5623
5847
  const instance = table.boards[boardId];
5624
5848
  const definition = definitions.boardDefinitions[instance.baseId];
5625
- const candidates = Object.keys(table.tiles).flatMap((tileId) => {
5849
+ const candidates2 = Object.keys(table.tiles).flatMap((tileId) => {
5626
5850
  const location = table.componentLocations[tileId];
5627
5851
  if (location?.type !== "OnBoard" || location.boardId !== boardId)
5628
5852
  return [];
@@ -5639,7 +5863,7 @@ function createSeatDisclosure(table, definitions, playerId, referenceBasis) {
5639
5863
  }
5640
5864
  ] : [];
5641
5865
  }).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
5642
- const placed = candidates.flatMap(({ tileId, location }, index) => {
5866
+ const placed = candidates2.flatMap(({ tileId, location }, index) => {
5643
5867
  const tile = issueTile(tileId, { boardId }, index);
5644
5868
  if (!tile) return [];
5645
5869
  const placement = location.layout === "hex" ? {
@@ -5655,7 +5879,7 @@ function createSeatDisclosure(table, definitions, playerId, referenceBasis) {
5655
5879
  };
5656
5880
  return [{ ...tile, placement }];
5657
5881
  });
5658
- const visibleIds = candidates.filter(({ tileId }) => disclosure(tileId) === "visible").map(({ tileId }) => tileId);
5882
+ const visibleIds = candidates2.filter(({ tileId }) => disclosure(tileId) === "visible").map(({ tileId }) => tileId);
5659
5883
  const visibleSpaces = new Set(
5660
5884
  definition.layout === "generic" ? Object.keys(definition.spaces) : visibleIds.flatMap(
5661
5885
  (tileId) => definitions.tileDefinitions[table.tiles[tileId].tileTypeId].cells.map((cell) => tileSpaceId(tileId, cell.id))
@@ -7249,6 +7473,7 @@ export {
7249
7473
  resolveZoneAccess,
7250
7474
  assertContainmentAcyclic,
7251
7475
  assertZoneConsistency,
7476
+ defineBots,
7252
7477
  REDUCER_CONTRACT_VERSION,
7253
7478
  assertReducerBundleContract,
7254
7479
  ZoneVisibilitySchema,
@@ -7270,4 +7495,4 @@ export {
7270
7495
  createProjectionBuilder,
7271
7496
  createReducerBundle
7272
7497
  };
7273
- //# sourceMappingURL=chunk-KYQQIFXN.js.map
7498
+ //# sourceMappingURL=chunk-UGWQKBR6.js.map