@mnbroatch/boardgame.io 0.0.1

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.
Files changed (296) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +102 -0
  3. package/ai/package.json +7 -0
  4. package/client/package.json +7 -0
  5. package/core/package.json +7 -0
  6. package/debug/package.json +7 -0
  7. package/dist/boardgameio.es.js +14238 -0
  8. package/dist/boardgameio.js +14277 -0
  9. package/dist/boardgameio.min.js +16 -0
  10. package/dist/cjs/Debug-9d141c06.js +9586 -0
  11. package/dist/cjs/ai-e0e8a768.js +377 -0
  12. package/dist/cjs/ai.js +20 -0
  13. package/dist/cjs/client-76dec77b.js +258 -0
  14. package/dist/cjs/client-a22d7500.js +524 -0
  15. package/dist/cjs/client.js +26 -0
  16. package/dist/cjs/core.js +52 -0
  17. package/dist/cjs/debug.js +18 -0
  18. package/dist/cjs/filter-player-view-bb02e2f6.js +89 -0
  19. package/dist/cjs/initialize-267fcd69.js +61 -0
  20. package/dist/cjs/internal.js +25 -0
  21. package/dist/cjs/master-2904879d.js +320 -0
  22. package/dist/cjs/master.js +18 -0
  23. package/dist/cjs/multiplayer.js +23 -0
  24. package/dist/cjs/plugin-random-7425844d.js +229 -0
  25. package/dist/cjs/plugins.js +59 -0
  26. package/dist/cjs/react-native.js +182 -0
  27. package/dist/cjs/react.js +727 -0
  28. package/dist/cjs/reducer-16eec232.js +1203 -0
  29. package/dist/cjs/server.js +4087 -0
  30. package/dist/cjs/socketio-7a0837eb.js +478 -0
  31. package/dist/cjs/testing.js +30 -0
  32. package/dist/cjs/transport-b1874dfa.js +37 -0
  33. package/dist/cjs/turn-order-b2ff8740.js +1136 -0
  34. package/dist/cjs/util-fcfd8fb8.js +140 -0
  35. package/dist/esm/Debug-0141fe2d.js +9577 -0
  36. package/dist/esm/ai-5c06e761.js +371 -0
  37. package/dist/esm/ai.js +8 -0
  38. package/dist/esm/client-2e653027.js +522 -0
  39. package/dist/esm/client-5f57c3f2.js +255 -0
  40. package/dist/esm/client.js +16 -0
  41. package/dist/esm/core.js +40 -0
  42. package/dist/esm/debug.js +10 -0
  43. package/dist/esm/filter-player-view-2c6cc96f.js +87 -0
  44. package/dist/esm/initialize-11d626ca.js +59 -0
  45. package/dist/esm/internal.js +10 -0
  46. package/dist/esm/master-fa8f2e43.js +318 -0
  47. package/dist/esm/master.js +10 -0
  48. package/dist/esm/multiplayer.js +14 -0
  49. package/dist/esm/plugin-random-087f861e.js +226 -0
  50. package/dist/esm/plugins.js +55 -0
  51. package/dist/esm/react-native.js +173 -0
  52. package/dist/esm/react.js +716 -0
  53. package/dist/esm/reducer-c46da7e5.js +1198 -0
  54. package/dist/esm/socketio-c22ffa65.js +455 -0
  55. package/dist/esm/testing.js +26 -0
  56. package/dist/esm/transport-ce07b771.js +35 -0
  57. package/dist/esm/turn-order-376d315e.js +1091 -0
  58. package/dist/esm/util-b6147cef.js +135 -0
  59. package/dist/types/packages/ai.d.ts +5 -0
  60. package/dist/types/packages/client.d.ts +3 -0
  61. package/dist/types/packages/core.d.ts +5 -0
  62. package/dist/types/packages/debug.d.ts +2 -0
  63. package/dist/types/packages/internal.d.ts +8 -0
  64. package/dist/types/packages/master.d.ts +2 -0
  65. package/dist/types/packages/multiplayer.d.ts +3 -0
  66. package/dist/types/packages/plugins.d.ts +3 -0
  67. package/dist/types/packages/react-native.d.ts +2 -0
  68. package/dist/types/packages/react.d.ts +3 -0
  69. package/dist/types/packages/server.d.ts +6 -0
  70. package/dist/types/packages/testing.d.ts +1 -0
  71. package/dist/types/src/ai/ai.d.ts +53 -0
  72. package/dist/types/src/ai/ai.test.d.ts +1 -0
  73. package/dist/types/src/ai/bot.d.ts +40 -0
  74. package/dist/types/src/ai/mcts-bot.d.ts +60 -0
  75. package/dist/types/src/ai/random-bot.d.ts +27 -0
  76. package/dist/types/src/client/client.d.ts +104 -0
  77. package/dist/types/src/client/client.test.d.ts +1 -0
  78. package/dist/types/src/client/debug/tests/debug.test.d.ts +1 -0
  79. package/dist/types/src/client/manager.d.ts +61 -0
  80. package/dist/types/src/client/react.d.ts +75 -0
  81. package/dist/types/src/client/react.ssr.test.d.ts +4 -0
  82. package/dist/types/src/client/react.test.d.ts +1 -0
  83. package/dist/types/src/client/transport/dummy.d.ts +18 -0
  84. package/dist/types/src/client/transport/local.d.ts +59 -0
  85. package/dist/types/src/client/transport/local.test.d.ts +1 -0
  86. package/dist/types/src/client/transport/socketio.d.ts +45 -0
  87. package/dist/types/src/client/transport/socketio.test.d.ts +1 -0
  88. package/dist/types/src/client/transport/transport.d.ts +50 -0
  89. package/dist/types/src/client/transport/transport.test.d.ts +1 -0
  90. package/dist/types/src/core/action-creators.d.ts +144 -0
  91. package/dist/types/src/core/action-types.d.ts +10 -0
  92. package/dist/types/src/core/backwards-compatibility.d.ts +12 -0
  93. package/dist/types/src/core/constants.d.ts +6 -0
  94. package/dist/types/src/core/errors.d.ts +15 -0
  95. package/dist/types/src/core/flow.d.ts +28 -0
  96. package/dist/types/src/core/flow.test.d.ts +1 -0
  97. package/dist/types/src/core/game-methods.d.ts +9 -0
  98. package/dist/types/src/core/game.d.ts +26 -0
  99. package/dist/types/src/core/game.test.d.ts +1 -0
  100. package/dist/types/src/core/initialize.d.ts +9 -0
  101. package/dist/types/src/core/logger.d.ts +2 -0
  102. package/dist/types/src/core/player-view.d.ts +7 -0
  103. package/dist/types/src/core/player-view.test.d.ts +1 -0
  104. package/dist/types/src/core/reducer.d.ts +155 -0
  105. package/dist/types/src/core/reducer.test.d.ts +1 -0
  106. package/dist/types/src/core/turn-order.d.ts +179 -0
  107. package/dist/types/src/core/turn-order.test.d.ts +8 -0
  108. package/dist/types/src/lobby/client.d.ts +194 -0
  109. package/dist/types/src/lobby/client.test.d.ts +1 -0
  110. package/dist/types/src/lobby/connection.d.ts +44 -0
  111. package/dist/types/src/lobby/connection.test.d.ts +1 -0
  112. package/dist/types/src/lobby/create-match-form.d.ts +26 -0
  113. package/dist/types/src/lobby/login-form.d.ts +23 -0
  114. package/dist/types/src/lobby/match-instance.d.ts +31 -0
  115. package/dist/types/src/lobby/react.d.ts +113 -0
  116. package/dist/types/src/lobby/react.ssr.test.d.ts +4 -0
  117. package/dist/types/src/lobby/react.test.d.ts +1 -0
  118. package/dist/types/src/master/filter-player-view.d.ts +96 -0
  119. package/dist/types/src/master/filter-player-view.test.d.ts +1 -0
  120. package/dist/types/src/master/master.d.ts +94 -0
  121. package/dist/types/src/master/master.test.d.ts +1 -0
  122. package/dist/types/src/plugins/events/events.d.ts +54 -0
  123. package/dist/types/src/plugins/events/events.test.d.ts +1 -0
  124. package/dist/types/src/plugins/main.d.ts +75 -0
  125. package/dist/types/src/plugins/main.test.d.ts +1 -0
  126. package/dist/types/src/plugins/plugin-events.d.ts +5 -0
  127. package/dist/types/src/plugins/plugin-immer.d.ts +7 -0
  128. package/dist/types/src/plugins/plugin-immer.test.d.ts +1 -0
  129. package/dist/types/src/plugins/plugin-log.d.ts +14 -0
  130. package/dist/types/src/plugins/plugin-log.test.d.ts +1 -0
  131. package/dist/types/src/plugins/plugin-player.d.ts +29 -0
  132. package/dist/types/src/plugins/plugin-player.test.d.ts +1 -0
  133. package/dist/types/src/plugins/plugin-random.d.ts +4 -0
  134. package/dist/types/src/plugins/plugin-serializable.d.ts +7 -0
  135. package/dist/types/src/plugins/plugin-serializable.test.d.ts +1 -0
  136. package/dist/types/src/plugins/random/random.alea.d.ts +19 -0
  137. package/dist/types/src/plugins/random/random.d.ts +54 -0
  138. package/dist/types/src/plugins/random/random.test.d.ts +1 -0
  139. package/dist/types/src/server/api.d.ts +13 -0
  140. package/dist/types/src/server/api.test.d.ts +1 -0
  141. package/dist/types/src/server/auth.d.ts +38 -0
  142. package/dist/types/src/server/auth.test.d.ts +1 -0
  143. package/dist/types/src/server/cors.d.ts +4 -0
  144. package/dist/types/src/server/cors.test.d.ts +1 -0
  145. package/dist/types/src/server/db/base.d.ts +192 -0
  146. package/dist/types/src/server/db/flatfile.d.ts +44 -0
  147. package/dist/types/src/server/db/flatfile.test.d.ts +1 -0
  148. package/dist/types/src/server/db/index.d.ts +4 -0
  149. package/dist/types/src/server/db/index.test.d.ts +1 -0
  150. package/dist/types/src/server/db/inmemory.d.ts +43 -0
  151. package/dist/types/src/server/db/inmemory.test.d.ts +1 -0
  152. package/dist/types/src/server/db/localstorage.d.ts +7 -0
  153. package/dist/types/src/server/db/localstorage.test.d.ts +1 -0
  154. package/dist/types/src/server/index.d.ts +68 -0
  155. package/dist/types/src/server/index.test.d.ts +1 -0
  156. package/dist/types/src/server/transport/pubsub/generic-pub-sub.d.ts +6 -0
  157. package/dist/types/src/server/transport/pubsub/in-memory-pub-sub.d.ts +7 -0
  158. package/dist/types/src/server/transport/pubsub/in-memory-pub-sub.test.d.ts +1 -0
  159. package/dist/types/src/server/transport/socketio-simultaneous.test.d.ts +1 -0
  160. package/dist/types/src/server/transport/socketio.d.ts +65 -0
  161. package/dist/types/src/server/transport/socketio.test.d.ts +1 -0
  162. package/dist/types/src/server/util.d.ts +35 -0
  163. package/dist/types/src/testing/mock-random.d.ts +15 -0
  164. package/dist/types/src/testing/mock-random.test.d.ts +1 -0
  165. package/dist/types/src/types.d.ts +387 -0
  166. package/internal/package.json +7 -0
  167. package/master/package.json +7 -0
  168. package/multiplayer/package.json +7 -0
  169. package/package.json +211 -0
  170. package/plugins/package.json +7 -0
  171. package/react/package.json +7 -0
  172. package/react-native/package.json +7 -0
  173. package/server/package.json +6 -0
  174. package/src/ai/ai.test.ts +433 -0
  175. package/src/ai/ai.ts +84 -0
  176. package/src/ai/bot.ts +122 -0
  177. package/src/ai/mcts-bot.ts +331 -0
  178. package/src/ai/random-bot.ts +20 -0
  179. package/src/client/client.test.ts +993 -0
  180. package/src/client/client.ts +588 -0
  181. package/src/client/debug/Debug.svelte +239 -0
  182. package/src/client/debug/Menu.svelte +65 -0
  183. package/src/client/debug/ai/AI.svelte +215 -0
  184. package/src/client/debug/ai/Options.svelte +48 -0
  185. package/src/client/debug/info/Info.svelte +22 -0
  186. package/src/client/debug/info/Item.svelte +24 -0
  187. package/src/client/debug/log/Log.svelte +157 -0
  188. package/src/client/debug/log/LogEvent.svelte +149 -0
  189. package/src/client/debug/log/LogMetadata.svelte +7 -0
  190. package/src/client/debug/log/PhaseMarker.svelte +27 -0
  191. package/src/client/debug/log/TurnMarker.svelte +23 -0
  192. package/src/client/debug/main/ClientSwitcher.svelte +59 -0
  193. package/src/client/debug/main/Controls.svelte +58 -0
  194. package/src/client/debug/main/Hotkey.svelte +84 -0
  195. package/src/client/debug/main/InteractiveFunction.svelte +85 -0
  196. package/src/client/debug/main/Main.svelte +121 -0
  197. package/src/client/debug/main/Move.svelte +68 -0
  198. package/src/client/debug/main/PlayerInfo.svelte +70 -0
  199. package/src/client/debug/mcts/Action.svelte +22 -0
  200. package/src/client/debug/mcts/MCTS.svelte +78 -0
  201. package/src/client/debug/mcts/Table.svelte +98 -0
  202. package/src/client/debug/tests/JSONTree.mock.svelte +3 -0
  203. package/src/client/debug/tests/debug.test.ts +183 -0
  204. package/src/client/debug/utils/shortcuts.js +50 -0
  205. package/src/client/debug/utils/shortcuts.test.js +49 -0
  206. package/src/client/manager.ts +177 -0
  207. package/src/client/react-native.js +136 -0
  208. package/src/client/react-native.test.js +229 -0
  209. package/src/client/react.ssr.test.tsx +24 -0
  210. package/src/client/react.test.tsx +213 -0
  211. package/src/client/react.tsx +192 -0
  212. package/src/client/transport/dummy.ts +19 -0
  213. package/src/client/transport/local.test.ts +353 -0
  214. package/src/client/transport/local.ts +230 -0
  215. package/src/client/transport/socketio.test.ts +328 -0
  216. package/src/client/transport/socketio.ts +210 -0
  217. package/src/client/transport/transport.test.ts +27 -0
  218. package/src/client/transport/transport.ts +95 -0
  219. package/src/core/action-creators.ts +159 -0
  220. package/src/core/action-types.ts +18 -0
  221. package/src/core/backwards-compatibility.ts +23 -0
  222. package/src/core/constants.ts +6 -0
  223. package/src/core/errors.ts +35 -0
  224. package/src/core/flow.test.ts +2433 -0
  225. package/src/core/flow.ts +897 -0
  226. package/src/core/game-methods.ts +9 -0
  227. package/src/core/game.test.ts +286 -0
  228. package/src/core/game.ts +114 -0
  229. package/src/core/initialize.ts +77 -0
  230. package/src/core/logger.test.js +90 -0
  231. package/src/core/logger.ts +18 -0
  232. package/src/core/player-view.test.ts +50 -0
  233. package/src/core/player-view.ts +39 -0
  234. package/src/core/reducer.test.ts +991 -0
  235. package/src/core/reducer.ts +532 -0
  236. package/src/core/turn-order.test.ts +1123 -0
  237. package/src/core/turn-order.ts +473 -0
  238. package/src/lobby/client.test.ts +385 -0
  239. package/src/lobby/client.ts +358 -0
  240. package/src/lobby/connection.test.ts +207 -0
  241. package/src/lobby/connection.ts +162 -0
  242. package/src/lobby/create-match-form.tsx +122 -0
  243. package/src/lobby/login-form.tsx +75 -0
  244. package/src/lobby/match-instance.tsx +135 -0
  245. package/src/lobby/react.ssr.test.tsx +22 -0
  246. package/src/lobby/react.test.tsx +594 -0
  247. package/src/lobby/react.tsx +402 -0
  248. package/src/master/filter-player-view.test.ts +381 -0
  249. package/src/master/filter-player-view.ts +102 -0
  250. package/src/master/master.test.ts +1068 -0
  251. package/src/master/master.ts +492 -0
  252. package/src/plugins/events/events.test.ts +108 -0
  253. package/src/plugins/events/events.ts +209 -0
  254. package/src/plugins/main.test.ts +411 -0
  255. package/src/plugins/main.ts +314 -0
  256. package/src/plugins/plugin-events.ts +40 -0
  257. package/src/plugins/plugin-immer.test.ts +86 -0
  258. package/src/plugins/plugin-immer.ts +37 -0
  259. package/src/plugins/plugin-log.test.ts +37 -0
  260. package/src/plugins/plugin-log.ts +40 -0
  261. package/src/plugins/plugin-player.test.ts +172 -0
  262. package/src/plugins/plugin-player.ts +100 -0
  263. package/src/plugins/plugin-random.ts +40 -0
  264. package/src/plugins/plugin-serializable.test.ts +40 -0
  265. package/src/plugins/plugin-serializable.ts +55 -0
  266. package/src/plugins/random/random.alea.ts +109 -0
  267. package/src/plugins/random/random.test.ts +167 -0
  268. package/src/plugins/random/random.ts +198 -0
  269. package/src/server/api.test.ts +1699 -0
  270. package/src/server/api.ts +527 -0
  271. package/src/server/auth.test.ts +275 -0
  272. package/src/server/auth.ts +89 -0
  273. package/src/server/cors.test.ts +121 -0
  274. package/src/server/cors.ts +7 -0
  275. package/src/server/db/base.ts +296 -0
  276. package/src/server/db/flatfile.test.ts +221 -0
  277. package/src/server/db/flatfile.ts +228 -0
  278. package/src/server/db/index.test.ts +8 -0
  279. package/src/server/db/index.ts +12 -0
  280. package/src/server/db/inmemory.test.ts +143 -0
  281. package/src/server/db/inmemory.ts +143 -0
  282. package/src/server/db/localstorage.test.ts +73 -0
  283. package/src/server/db/localstorage.ts +44 -0
  284. package/src/server/index.test.ts +265 -0
  285. package/src/server/index.ts +175 -0
  286. package/src/server/transport/pubsub/generic-pub-sub.ts +11 -0
  287. package/src/server/transport/pubsub/in-memory-pub-sub.test.ts +47 -0
  288. package/src/server/transport/pubsub/in-memory-pub-sub.ts +28 -0
  289. package/src/server/transport/socketio-simultaneous.test.ts +603 -0
  290. package/src/server/transport/socketio.test.ts +303 -0
  291. package/src/server/transport/socketio.ts +279 -0
  292. package/src/server/util.ts +85 -0
  293. package/src/testing/mock-random.test.ts +45 -0
  294. package/src/testing/mock-random.ts +27 -0
  295. package/src/types.ts +511 -0
  296. package/testing/package.json +7 -0
@@ -0,0 +1,353 @@
1
+ /*
2
+ * Copyright 2018 The boardgame.io Authors
3
+ *
4
+ * Use of this source code is governed by a MIT-style
5
+ * license that can be found in the LICENSE file or at
6
+ * https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { LocalTransport, LocalMaster, Local, GetBotPlayer } from './local';
10
+ import { gameEvent } from '../../core/action-creators';
11
+ import { ProcessGameConfig } from '../../core/game';
12
+ import { Client } from '../client';
13
+ import { RandomBot } from '../../ai/random-bot';
14
+ import { Stage } from '../../core/turn-order';
15
+ import type { Game, State } from '../../types';
16
+
17
+ const sleep = (ms = 500) => new Promise((resolve) => setTimeout(resolve, ms));
18
+
19
+ describe('bots', () => {
20
+ const game: Game = {
21
+ moves: {
22
+ A: ({ events }) => {
23
+ events.endTurn();
24
+ },
25
+ },
26
+ ai: {
27
+ enumerate: () => [{ move: 'A' }],
28
+ },
29
+ };
30
+
31
+ test('make bot move', async () => {
32
+ const client = Client({
33
+ game: { ...game },
34
+ playerID: '0',
35
+ multiplayer: Local({ bots: { '1': RandomBot } }),
36
+ });
37
+
38
+ client.start();
39
+ expect(client.getState().ctx.turn).toBe(1);
40
+
41
+ // Make it Player 1's turn and trigger the bot move.
42
+ client.events.endTurn();
43
+ expect(client.getState().ctx.turn).toBe(2);
44
+
45
+ // Wait until the bot has hopefully completed its move.
46
+ await sleep();
47
+ expect(client.getState().ctx.turn).toBe(3);
48
+ });
49
+
50
+ test('no bot move', async () => {
51
+ const client = Client({
52
+ numPlayers: 3,
53
+ game: { ...game },
54
+ playerID: '0',
55
+ multiplayer: Local({ bots: { '2': RandomBot } }),
56
+ });
57
+
58
+ client.start();
59
+ expect(client.getState().ctx.turn).toBe(1);
60
+
61
+ // Make it Player 1's turn. No bot move.
62
+ client.events.endTurn();
63
+ expect(client.getState().ctx.currentPlayer).toBe('1');
64
+
65
+ // Wait until the bot has hopefully completed its move.
66
+ await sleep();
67
+ expect(client.getState().ctx.currentPlayer).toBe('1');
68
+ expect(client.getState().ctx.numMoves).toBe(0);
69
+ });
70
+ });
71
+
72
+ describe('GetBotPlayer', () => {
73
+ test('stages', () => {
74
+ const result = GetBotPlayer(
75
+ {
76
+ ctx: {
77
+ activePlayers: {
78
+ '1': Stage.NULL,
79
+ },
80
+ },
81
+ } as unknown as State,
82
+ {
83
+ '0': {},
84
+ '1': {},
85
+ }
86
+ );
87
+ expect(result).toEqual('1');
88
+ });
89
+
90
+ test('no stages', () => {
91
+ const result = GetBotPlayer(
92
+ {
93
+ ctx: {
94
+ currentPlayer: '0',
95
+ },
96
+ } as unknown as State,
97
+ { '0': {} }
98
+ );
99
+ expect(result).toEqual('0');
100
+ });
101
+
102
+ test('null', () => {
103
+ const result = GetBotPlayer(
104
+ {
105
+ ctx: {
106
+ currentPlayer: '1',
107
+ },
108
+ } as unknown as State,
109
+ { '0': {} }
110
+ );
111
+ expect(result).toEqual(null);
112
+ });
113
+
114
+ test('gameover', () => {
115
+ const result = GetBotPlayer(
116
+ {
117
+ ctx: {
118
+ currentPlayer: '0',
119
+ gameover: true,
120
+ },
121
+ } as unknown as State,
122
+ { '0': {} }
123
+ );
124
+ expect(result).toEqual(null);
125
+ });
126
+ });
127
+
128
+ describe('Local', () => {
129
+ test('transports for same game use shared master', () => {
130
+ const gameKey = {};
131
+ const game = ProcessGameConfig(gameKey);
132
+ const transport1 = Local()({
133
+ game,
134
+ gameKey,
135
+ transportDataCallback: () => {},
136
+ });
137
+ const transport2 = Local()({
138
+ game,
139
+ gameKey,
140
+ transportDataCallback: () => {},
141
+ });
142
+ expect(transport1.master).toBe(transport2.master);
143
+ });
144
+
145
+ test('transports use shared master with bots', () => {
146
+ const gameKey = {};
147
+ const game = ProcessGameConfig(gameKey);
148
+ const bots = {};
149
+ const transport1 = Local({ bots })({
150
+ game,
151
+ gameKey,
152
+ transportDataCallback: () => {},
153
+ });
154
+ const transport2 = Local({ bots })({
155
+ game,
156
+ gameKey,
157
+ transportDataCallback: () => {},
158
+ });
159
+ expect(transport1.master).toBe(transport2.master);
160
+ });
161
+
162
+ test('transports use different master for different bots', () => {
163
+ const gameKey = {};
164
+ const game = ProcessGameConfig(gameKey);
165
+ const transport1 = Local({ bots: {} })({
166
+ game,
167
+ gameKey,
168
+ transportDataCallback: () => {},
169
+ });
170
+ const transport2 = Local({ bots: {} })({
171
+ game,
172
+ gameKey,
173
+ transportDataCallback: () => {},
174
+ });
175
+ expect(transport1.master).not.toBe(transport2.master);
176
+ });
177
+
178
+ describe('with localStorage persistence', () => {
179
+ const game: Game = {
180
+ setup: () => ({ count: 0 }),
181
+ moves: {
182
+ A: ({ G }) => {
183
+ G.count++;
184
+ },
185
+ },
186
+ };
187
+
188
+ afterEach(() => {
189
+ localStorage.clear();
190
+ });
191
+
192
+ test('writes to localStorage', () => {
193
+ const matchID = 'persists-to-ls';
194
+ const multiplayer = Local({ persist: true });
195
+ const client = Client({ playerID: '0', matchID, game, multiplayer });
196
+ client.start();
197
+ expect(client.getState().G).toEqual({ count: 0 });
198
+ client.moves.A();
199
+ expect(client.getState().G).toEqual({ count: 1 });
200
+ client.stop();
201
+ const stored = JSON.parse(localStorage.getItem('bgio_state'));
202
+ const [id, state] = stored.find(([id]) => id === matchID);
203
+ expect(id).toBe(matchID);
204
+ expect(state.G).toEqual({ count: 1 });
205
+ });
206
+
207
+ test('reads from localStorage', () => {
208
+ const matchID = 'reads-from-ls';
209
+ const storageKey = 'rfls';
210
+ const stateMap = {
211
+ [matchID]: {
212
+ G: { count: 'foo' },
213
+ ctx: {},
214
+ },
215
+ };
216
+ const entriesString = JSON.stringify(Object.entries(stateMap));
217
+ localStorage.setItem(`${storageKey}_state`, entriesString);
218
+ const multiplayer = Local({ persist: true, storageKey });
219
+ const client = Client({ playerID: '0', matchID, game, multiplayer });
220
+ client.start();
221
+ expect(client.getState().G).toEqual({ count: 'foo' });
222
+ client.stop();
223
+ });
224
+ });
225
+ });
226
+
227
+ describe('LocalMaster', () => {
228
+ let master: LocalMaster;
229
+ let player0Callback: jest.Mock;
230
+ let player1Callback: jest.Mock;
231
+
232
+ beforeEach(() => {
233
+ master = new LocalMaster({ game: {} });
234
+ player0Callback = jest.fn();
235
+ player1Callback = jest.fn();
236
+ master.connect('0', player0Callback);
237
+ master.connect('1', player1Callback);
238
+ master.onSync('matchID', '0');
239
+ master.onSync('matchID', '1');
240
+ });
241
+
242
+ test('sync', () => {
243
+ expect(player0Callback).toHaveBeenCalledWith(
244
+ expect.objectContaining({ type: 'sync' })
245
+ );
246
+ expect(player1Callback).toHaveBeenCalledWith(
247
+ expect.objectContaining({ type: 'sync' })
248
+ );
249
+ });
250
+
251
+ test('update', () => {
252
+ master.onUpdate(gameEvent('endTurn'), 0, 'matchID', '0');
253
+ expect(player0Callback).toBeCalledWith(
254
+ expect.objectContaining({ type: 'update' })
255
+ );
256
+ expect(player1Callback).toBeCalledWith(
257
+ expect.objectContaining({ type: 'update' })
258
+ );
259
+ });
260
+
261
+ test('connect without callback', () => {
262
+ expect(() => {
263
+ master.connect('0', undefined);
264
+ master.onSync('matchID', '0');
265
+ }).not.toThrow();
266
+ });
267
+ });
268
+
269
+ describe('LocalTransport', () => {
270
+ describe('update matchID / playerID', () => {
271
+ const master = {
272
+ connect: jest.fn(),
273
+ onSync: jest.fn(),
274
+ } as unknown as LocalMaster;
275
+ class WrappedLocalTransport extends LocalTransport {
276
+ getMatchID() {
277
+ return this.matchID;
278
+ }
279
+ getPlayerID() {
280
+ return this.playerID;
281
+ }
282
+ }
283
+ const transport = new WrappedLocalTransport({
284
+ master,
285
+ transportDataCallback: () => {},
286
+ game: ProcessGameConfig({}),
287
+ gameKey: {},
288
+ });
289
+ jest.spyOn(transport, 'requestSync');
290
+
291
+ beforeEach(() => {
292
+ jest.resetAllMocks();
293
+ });
294
+
295
+ test('matchID', () => {
296
+ transport.updateMatchID('test');
297
+ expect(transport.getMatchID()).toBe('test');
298
+ expect(transport.requestSync).toBeCalled();
299
+ });
300
+
301
+ test('playerID', () => {
302
+ transport.updatePlayerID('player');
303
+ expect(transport.getPlayerID()).toBe('player');
304
+ expect(master.connect).toBeCalled();
305
+ });
306
+ });
307
+
308
+ describe('multiplayer', () => {
309
+ const game: Game = {
310
+ setup: () => ({ initial: true }),
311
+ moves: {
312
+ A: () => ({ A: true }),
313
+ },
314
+ };
315
+ const multiplayer = Local();
316
+ const matchID = 'local-multiplayer';
317
+ const client1 = Client({ game, multiplayer, matchID, playerID: '0' });
318
+ const client2 = Client({ game, multiplayer, matchID, playerID: '1' });
319
+
320
+ beforeAll(() => {
321
+ client1.start();
322
+ client2.start();
323
+ });
324
+
325
+ afterAll(() => {
326
+ client1.stop();
327
+ client2.stop();
328
+ });
329
+
330
+ test('send/receive update', () => {
331
+ expect(client1.getState().G).toStrictEqual({ initial: true });
332
+ expect(client2.getState().G).toStrictEqual({ initial: true });
333
+ client1.moves.A();
334
+ expect(client1.getState().G).toStrictEqual({ A: true });
335
+ expect(client2.getState().G).toStrictEqual({ A: true });
336
+ });
337
+
338
+ test('receive sync', () => {
339
+ const newClient = Client({ game, multiplayer, matchID });
340
+ newClient.start();
341
+ expect(newClient.getState().G).toStrictEqual({ A: true });
342
+ newClient.stop();
343
+ });
344
+
345
+ test('send chat-message', () => {
346
+ const payload = { message: 'foo' };
347
+ client1.sendChatMessage(payload);
348
+ expect(client2.chatMessages).toStrictEqual([
349
+ { id: expect.any(String), sender: '0', payload },
350
+ ]);
351
+ });
352
+ });
353
+ });
@@ -0,0 +1,230 @@
1
+ /*
2
+ * Copyright 2018 The boardgame.io Authors
3
+ *
4
+ * Use of this source code is governed by a MIT-style
5
+ * license that can be found in the LICENSE file or at
6
+ * https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { InMemory } from '../../server/db/inmemory';
10
+ import { LocalStorage } from '../../server/db/localstorage';
11
+ import { Master } from '../../master/master';
12
+ import type { TransportAPI, TransportData } from '../../master/master';
13
+ import { Transport } from './transport';
14
+ import type { TransportOpts } from './transport';
15
+ import type {
16
+ ChatMessage,
17
+ CredentialedActionShape,
18
+ Game,
19
+ PlayerID,
20
+ State,
21
+ } from '../../types';
22
+ import { getFilterPlayerView } from '../../master/filter-player-view';
23
+
24
+ /**
25
+ * Returns null if it is not a bot's turn.
26
+ * Otherwise, returns a playerID of a bot that may play now.
27
+ */
28
+ export function GetBotPlayer(state: State, bots: Record<PlayerID, any>) {
29
+ if (state.ctx.gameover !== undefined) {
30
+ return null;
31
+ }
32
+
33
+ if (state.ctx.activePlayers) {
34
+ for (const key of Object.keys(bots)) {
35
+ if (key in state.ctx.activePlayers) {
36
+ return key;
37
+ }
38
+ }
39
+ } else if (state.ctx.currentPlayer in bots) {
40
+ return state.ctx.currentPlayer;
41
+ }
42
+
43
+ return null;
44
+ }
45
+
46
+ interface LocalOpts {
47
+ bots?: Record<PlayerID, any>;
48
+ persist?: boolean;
49
+ storageKey?: string;
50
+ }
51
+
52
+ type LocalMasterOpts = LocalOpts & {
53
+ game: Game;
54
+ };
55
+
56
+ /**
57
+ * Creates a local version of the master that the client
58
+ * can interact with.
59
+ */
60
+ export class LocalMaster extends Master {
61
+ connect: (
62
+ playerID: PlayerID,
63
+ callback: (data: TransportData) => void
64
+ ) => void;
65
+
66
+ constructor({ game, bots, storageKey, persist }: LocalMasterOpts) {
67
+ const clientCallbacks: Record<PlayerID, (data: TransportData) => void> = {};
68
+ const initializedBots = {};
69
+
70
+ if (game && game.ai && bots) {
71
+ for (const playerID in bots) {
72
+ const bot = bots[playerID];
73
+ initializedBots[playerID] = new bot({
74
+ game,
75
+ enumerate: game.ai.enumerate,
76
+ seed: game.seed,
77
+ });
78
+ }
79
+ }
80
+
81
+ const send: TransportAPI['send'] = ({ playerID, ...data }) => {
82
+ const callback = clientCallbacks[playerID];
83
+ if (callback !== undefined) {
84
+ callback(filterPlayerView(playerID, data));
85
+ }
86
+ };
87
+
88
+ const filterPlayerView = getFilterPlayerView(game);
89
+ const transportAPI: TransportAPI = {
90
+ send,
91
+ sendAll: (payload) => {
92
+ for (const playerID in clientCallbacks) {
93
+ send({ playerID, ...payload });
94
+ }
95
+ },
96
+ };
97
+ const storage = persist ? new LocalStorage(storageKey) : new InMemory();
98
+ super(game, storage, transportAPI);
99
+
100
+ this.connect = (playerID, callback) => {
101
+ clientCallbacks[playerID] = callback;
102
+ };
103
+
104
+ this.subscribe(({ state, matchID }) => {
105
+ if (!bots) {
106
+ return;
107
+ }
108
+ const botPlayer = GetBotPlayer(state, initializedBots);
109
+ if (botPlayer !== null) {
110
+ setTimeout(async () => {
111
+ const botAction = await initializedBots[botPlayer].play(
112
+ state,
113
+ botPlayer
114
+ );
115
+ await this.onUpdate(
116
+ botAction.action,
117
+ state._stateID,
118
+ matchID,
119
+ botAction.action.payload.playerID
120
+ );
121
+ }, 100);
122
+ }
123
+ });
124
+ }
125
+ }
126
+
127
+ type LocalTransportOpts = TransportOpts & {
128
+ master?: LocalMaster;
129
+ };
130
+
131
+ /**
132
+ * Local
133
+ *
134
+ * Transport interface that embeds a GameMaster within it
135
+ * that you can connect multiple clients to.
136
+ */
137
+ export class LocalTransport extends Transport {
138
+ master: LocalMaster;
139
+
140
+ /**
141
+ * Creates a new Mutiplayer instance.
142
+ * @param {string} matchID - The game ID to connect to.
143
+ * @param {string} playerID - The player ID associated with this client.
144
+ * @param {string} gameName - The game type (the `name` field in `Game`).
145
+ * @param {string} numPlayers - The number of players.
146
+ */
147
+ constructor({ master, ...opts }: LocalTransportOpts) {
148
+ super(opts);
149
+ this.master = master;
150
+ }
151
+
152
+ sendChatMessage(matchID: string, chatMessage: ChatMessage): void {
153
+ const args: Parameters<Master['onChatMessage']> = [
154
+ matchID,
155
+ chatMessage,
156
+ this.credentials,
157
+ ];
158
+ this.master.onChatMessage(...args);
159
+ }
160
+
161
+ sendAction(state: State, action: CredentialedActionShape.Any): void {
162
+ this.master.onUpdate(action, state._stateID, this.matchID, this.playerID);
163
+ }
164
+
165
+ requestSync(): void {
166
+ this.master.onSync(
167
+ this.matchID,
168
+ this.playerID,
169
+ this.credentials,
170
+ this.numPlayers
171
+ );
172
+ }
173
+
174
+ connect(): void {
175
+ this.setConnectionStatus(true);
176
+ this.master.connect(this.playerID, (data) => this.notifyClient(data));
177
+ this.requestSync();
178
+ }
179
+
180
+ disconnect(): void {
181
+ this.setConnectionStatus(false);
182
+ }
183
+
184
+ updateMatchID(id: string): void {
185
+ this.matchID = id;
186
+ this.connect();
187
+ }
188
+
189
+ updatePlayerID(id: PlayerID): void {
190
+ this.playerID = id;
191
+ this.connect();
192
+ }
193
+
194
+ updateCredentials(credentials?: string): void {
195
+ this.credentials = credentials;
196
+ this.connect();
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Global map storing local master instances.
202
+ */
203
+ const localMasters: Map<Game, { master: LocalMaster } & LocalOpts> = new Map();
204
+
205
+ /**
206
+ * Create a local transport.
207
+ */
208
+ export function Local({ bots, persist, storageKey }: LocalOpts = {}) {
209
+ return (transportOpts: TransportOpts) => {
210
+ const { gameKey, game } = transportOpts;
211
+ let master: LocalMaster;
212
+
213
+ const instance = localMasters.get(gameKey);
214
+ if (
215
+ instance &&
216
+ instance.bots === bots &&
217
+ instance.storageKey === storageKey &&
218
+ instance.persist === persist
219
+ ) {
220
+ master = instance.master;
221
+ }
222
+
223
+ if (!master) {
224
+ master = new LocalMaster({ game, bots, persist, storageKey });
225
+ localMasters.set(gameKey, { master, bots, persist, storageKey });
226
+ }
227
+
228
+ return new LocalTransport({ master, ...transportOpts });
229
+ };
230
+ }