[
  {
    "path": ".eslintrc",
    "content": "{\n  \"root\": true,\n  \"parser\": \"@typescript-eslint/parser\",\n  \"plugins\": [\n    \"@typescript-eslint\",\n  ],\n  \"extends\": [\n    \"eslint:recommended\",\n    \"plugin:@typescript-eslint/eslint-recommended\",\n    \"plugin:@typescript-eslint/recommended\",\n    \"plugin:react-hooks/recommended\"\n  ],\n  \"rules\": {\n    '@typescript-eslint/no-unused-vars': [\n      'error', {\n        argsIgnorePattern: '^_',\n        varsIgnorePattern: '^_',\n        caughtErrorsIgnorePattern: '^_',\n      },\n    ],\n    'no-unused-vars': 0,\n    '@typescript-eslint/no-explicit-any': 0,\n    '@typescript-eslint/ban-ts-comment': 0,\n    '@typescript-eslint/no-non-null-assertion': 0,\n    '@typescript-eslint/no-empty-function': 0,\n    'no-underscore-dangle': 0,\n    'arrow-parens': 0,\n    'no-nested-ternary': 0,\n    'max-classes-per-file': 0,\n    'object-curly-newline': 0,\n    'max-len': 0,\n    'prefer-destructuring': 0,\n    'no-console': 0,\n    \"no-constant-condition\": 0,\n    \"prefer-const\": 0,\n  }\n}\n"
  },
  {
    "path": ".github/workflows/check.yml",
    "content": "on:\n  push:\n    branches:\n    - main\n  pull_request:\n    branches:\n    - main\nname: Check\njobs:\n  check:\n    runs-on: ubuntu-latest\n    steps:\n    - name: Use Node.js ${{ matrix.node-version }}\n      uses: actions/setup-node@v3\n      with:\n        node-version: 18.18.2\n    - uses: actions/checkout@v3\n    - run: yarn\n    - run: yarn run compile\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "on:\n  push:\n    branches:\n    - main\n  pull_request:\n    branches:\n    - main\nname: Check\njobs:\n  check:\n    runs-on: ubuntu-latest\n    steps:\n    - name: Use Node.js ${{ matrix.node-version }}\n      uses: actions/setup-node@v3\n      with:\n        node-version: 18.18.2\n    - uses: actions/checkout@v3\n    - run: yarn\n    - run: yarn test\n    - run: yarn run dep-check\n"
  },
  {
    "path": ".gitignore",
    "content": "# temp files\n.DS_Store\n\\#*\n.\\#*\n\n# npm\nnode_modules\nyarn-error.log\n\n# build artifacts\n/dist\n/docs\n\ntodos.txt\nnotes.txt\n**/scratch.*\n"
  },
  {
    "path": ".mocharc.json.ignore",
    "content": "{\n  \"require\": [ \"ts-node/register\" ],\n  \"loader\": \"ts-node/esm\",\n  \"extensions\": [\"ts\", \"tsx\"],\n  \"spec\": [\n    \"src/test/**\"\n  ]\n}\n"
  },
  {
    "path": ".npmignore",
    "content": "!/dist"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# v0.2.14\n* Game elements now have next/previous selectors to find adjacent elements in\n  the same space.\n* Invalid options in selections now retain their position\n* Corrected a bug with nested follow-ups\n\n# v0.2.13\n* Game settings provided now all accept an initial default value\n  (e.g. numberSetting, etc)\n* The `everyPlayer` flow now passes the currently acting player to the flow\n  args, just like `eachPlayer`\n* Corrected an issue with `everyPlayer` hanging when using an array `do` block\n* Corrected a bug with `layout.haphazardly`.\n\n# v0.2.12\n* Added action#confirm as an alternate means to add confirmation prompts\n* Providing a `validate` function in a `chooseFrom` now shows invalid choices\n  with error messages if clicked\n\n# v0.2.11 Hideable Space Layouts\n* Added 3 new layouts for Spaces that save screen real estate\n* `element#layoutAsDrawer` puts Space in a expandable drawer (replaces the\n  drawer 'attribute' in layout)\n* `element#layoutAsTabs` puts several Spaces into a switchable layout of tabs\n* `element#layoutAsPopout` hides a Space behind a button that opens it as a\n  popout modal\n\n# v0.2.10\n* Fixed Info and Debug overlays\n\n# v0.2.9\n* Removed deprecated index.scss import\n\n# v0.2.8 Stack and Flippable\n* Added Stack class for decks within hidden elements and internal moves\n* Added Flippable component with back/front and animated flips\n\n# v0.2.7 Animation overhaul\n* Overhauled the animation logic that decides how elements move for various\n  players, correcting several glitches\n* Pieces now animate on to and off of the board, into and out of the bottom of\n  decks even if unrendered\n\n# v0.2.6 Subflows\n* Subflows allow you to define entire new flows that branch of your main flow,\n  e.g. playing a particular Card causes a set of new actions to happen\n* Follow-ups are still available but these are now actually just Subflows under\n  the hood that automatically perform only a single action\n* Some small flow and animation fixes included\n\n# v0.2.5\n* Added `action.swap` to allow players to exchange Pieces\n* Added `action.reorder` to allow players to reorder a collection of Pieces\n* Also made some improvements in the dragging and moving to remove flicker and\n  quirkiness\n\n# v0.2.4 Component modules\n* Added Component modules. The `D6` class is the first example and it has been\n  moved into a separate self-contained import. See\n  https://docs.boardzilla.io/game/modules\n* It is no longer necessary to include `@boardzilla/core/index.css` in\n  `ui/index.tsx`. This line can be removed.\n* Added `actionStep.continueIfImpossible` to allow a step to be skipped if no\n  actions are valid\n* Added `actionStep.repeatUntil` to make a set of actions repeatable until a\n  'pass' action\n* Added `Player.hiddenAttributes` to make some attributes hidden from other\n  players\n* Some consistency fixes to prompts.\n\n# v0.2.3\n* Board Sizes now accepts more detailed matchers, with a range of \"best fit\"\n  aspect ratios, a setting to choose scrollbars or letterbox and mobile\n  orientation fixing\n* Show/hide methods moved to Piece only\n* Space now has new convenience methods to attach content show/hide event\n  handlers\n* Space now has \"screen\" methods to make contents completely invisible to\n  players\n* Added Test Runner mocks and updatePlayers\n\n# v0.2 Grids\n* Added subclasses of `Space` for various grids, including more options for\n  square, hex and the brand new PieceGrid. These replace `Space#createGrid`.\n* Grids can now be shaped, e.g. to create a hex grid in a square shape\n* `PieceGrid` allows the placement and tiling of irregular shapes, with an\n  extendible grid that correctly sizes shaped pieces inside it.\n* Pieces now have a `setShape` and `setEdges` for adding irregular shapes and\n  labelling the cells and edges for the purposes of adjacency.\n* Connecting spaces now allows bidirectional distances\n* Generics have been given a full rework, removing lots of unnecessary generics\n  and making the importing of more game classes more straightfoward and\n  extendable.\n* `createGameClasses` is gone. `Space` and `Piece` can be imported directly from\n  core.\n* `Game#registerClasses` is no longer necessary and can be removed.\n* `Piece#putInto` now accepts `row`, `column`.\n* Now using incremental Typescript compilation for much faster rebuilds\n* History reprocessing in development has been completely reworked for much\n  better performance\n* Added a new associated starter template using PieceGrid and irregular tiles.\n\n# v0.1 Lobby\n* Brand new lobby with seating controls, allowing self-seating, async game start\n  and better UI.\n* renamed `Board` to `Game` and gave this class all exposed API methods that\n  were previously in `Game`. `Game` renamed to `GameManager` and intended as an\n  internal class.\n"
  },
  {
    "path": "CLA.md",
    "content": "# Contributor Agreement\n\n# Individual Contributor Exclusive License Agreement\n\nThank you for your interest in contributing to Boardzilla (\"We\" or \"Us\").\n\nThe purpose of this contributor agreement (\"Agreement\") is to clarify and\ndocument the rights granted to Us by contributors to the Boardzilla core\nlibrary. To make this document effective, please contact andrew@boardzilla.io.\n\n## How to use this Contributor Agreement\n\nIf You are an employee and have created the Contribution as part of your\nemployment, You need to have Your employer approve this Agreement or sign the\nEntity version of this document. If You do not own the Copyright in the entire\nwork of authorship, any other author of the Contribution should also sign this –\nin any event, please contact Us at andrew@boardzilla.io\n\n## 1. Definitions\n\n\"You\" means the individual Copyright owner who Submits a Contribution to Us.\n\n\"Contribution\" means any original work of authorship, including any original\nmodifications or additions to an existing work of authorship, Submitted by You\nto Us, in which You own the Copyright.\n\n\"Copyright\" means all rights protecting works of authorship, including\ncopyright, moral and neighboring rights, as appropriate, for the full term of\ntheir existence.\n\n\"Material\" means the software or documentation made available by Us to third\nparties. When this Agreement covers more than one software project, the Material\nmeans the software or documentation to which the Contribution was\nSubmitted. After You Submit the Contribution, it may be included in the\nMaterial.\n\n\"Submit\" means any act by which a Contribution is transferred to Us by You by\nmeans of tangible or intangible media, including but not limited to electronic\nmailing lists, source code control systems, and issue tracking systems that are\nmanaged by, or on behalf of, Us, but excluding any transfer that is\nconspicuously marked or otherwise designated in writing by You as \"Not a\nContribution.\"\n\n\"Documentation\" means any non-software portion of a Contribution.\n\n## 2. License grant\n\n### 2.1 Copyright license to Us\n\nSubject to the terms and conditions of this Agreement, You hereby grant to Us a\nworldwide, royalty-free, Exclusive, perpetual and irrevocable (except as stated\nin Section 8.2) license, with the right to transfer an unlimited number of\nnon-exclusive licenses or to grant sublicenses to third parties, under the\nCopyright covering the Contribution to use the Contribution by all means,\nincluding, but not limited to:\n\n- publish the Contribution,\n- modify the Contribution,\n- prepare derivative works based upon or containing the Contribution and/or to\n  combine the Contribution with other Materials,\n- reproduce the Contribution in original or modified form, \n- distribute, to make the Contribution available to the public, display and\n  publicly perform the Contribution in original or modified form.\n\n### 2.2 Moral rights\n\nMoral Rights remain unaffected to the extent they are recognized and not\nwaivable by applicable law. Notwithstanding, You may add your name to the\nattribution mechanism customary used in the Materials you Contribute to, such as\nthe header of the source code files of Your Contribution, and We will respect\nthis attribution when using Your Contribution.\n\n### 2.3 Copyright license back to You\n\nUpon such grant of rights to Us, We immediately grant to You a worldwide,\nroyalty-free, non-exclusive, perpetual and irrevocable license, with the right\nto transfer an unlimited number of non-exclusive licenses or to grant\nsublicenses to third parties, under the Copyright covering the Contribution to\nuse the Contribution by all means, including, but not limited to:\n\n- publish the Contribution,\n- modify the Contribution,\n- prepare derivative works based upon or containing the Contribution and/or to\n  combine the Contribution with other Materials,\n- reproduce the Contribution in original or modified form,\n- distribute, to make the Contribution available to the public, display and\n  publicly perform the Contribution in original or modified form.  This license\n  back is limited to the Contribution and does not provide any rights to the\n  Material.\n\n## 3. Patents\n\n### 3.1 Patent license\n\nSubject to the terms and conditions of this Agreement You hereby grant to Us and\nto recipients of Materials distributed by Us a worldwide, royalty-free,\nnon-exclusive, perpetual and irrevocable (except as stated in Section 3.2)\npatent license, with the right to transfer an unlimited number of non-exclusive\nlicenses or to grant sublicenses to third parties, to make, have made, use,\nsell, offer for sale, import and otherwise transfer the Contribution and the\nContribution in combination with any Material (and portions of such\ncombination). This license applies to all patents owned or controlled by You,\nwhether already acquired or hereafter acquired, that would be infringed by\nmaking, having made, using, selling, offering for sale, importing or otherwise\ntransferring of Your Contribution(s) alone or by combination of Your\nContribution(s) with any Material.\n\n### 3.2 Revocation of patent license\n\nYou reserve the right to revoke the patent license stated in section 3.1 if We\nmake any infringement claim that is targeted at your Contribution and not\nasserted for a Defensive Purpose. An assertion of claims of the Patents shall be\nconsidered for a \"Defensive Purpose\" if the claims are asserted against an\nentity that has filed, maintained, threatened, or voluntarily participated in a\npatent infringement lawsuit against Us or any of Our licensees.\n\n## 4. License obligations by Us\n\nWe agree to license the Contribution only under the terms of the license or\nlicenses that We are using on the Submission Date for the Material (including\nany rights to adopt any future version of a license).\n\nWe agree to license patents owned or controlled by You only to the extent\nnecessary to (sub)license Your Contribution(s) and the combination of Your\nContribution(s) with the Material under the terms of the license or licenses\nthat We are using on the Submission Date.\n\n## 5. Disclaimer\n\nTHE CONTRIBUTION IS PROVIDED \"AS IS\". MORE PARTICULARLY, ALL EXPRESS OR IMPLIED\nWARRANTIES INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTY OF SATISFACTORY\nQUALITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY\nDISCLAIMED BY YOU TO US AND BY US TO YOU. TO THE EXTENT THAT ANY SUCH WARRANTIES\nCANNOT BE DISCLAIMED, SUCH WARRANTY IS LIMITED IN DURATION AND EXTENT TO THE\nMINIMUM PERIOD AND EXTENT PERMITTED BY LAW.\n\n## 6. Consequential damage waiver\n\nTO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL YOU OR WE BE\nLIABLE FOR ANY LOSS OF PROFITS, LOSS OF ANTICIPATED SAVINGS, LOSS OF DATA,\nINDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL AND EXEMPLARY DAMAGES ARISING OUT\nOF THIS AGREEMENT REGARDLESS OF THE LEGAL OR EQUITABLE THEORY (CONTRACT, TORT OR\nOTHERWISE) UPON WHICH THE CLAIM IS BASED.\n\n## 7. Approximation of disclaimer and damage waiver\n\nIF THE DISCLAIMER AND DAMAGE WAIVER MENTIONED IN SECTION 5. AND\nSECTION 6. CANNOT BE GIVEN LEGAL EFFECT UNDER APPLICABLE LOCAL LAW, REVIEWING\nCOURTS SHALL APPLY LOCAL LAW THAT MOST CLOSELY APPROXIMATES AN ABSOLUTE WAIVER\nOF ALL CIVIL OR CONTRACTUAL LIABILITY IN CONNECTION WITH THE CONTRIBUTION.\n\n## 8. Term\n\n8.1 This Agreement shall come into effect upon Your acceptance of the terms and\nconditions.\n\n8.2 This Agreement shall apply for the term of the copyright and patents\nlicensed here. However, You shall have the right to terminate the Agreement if\nWe do not fulfill the obligations as set forth in Section 4. Such termination\nmust be made in writing.\n\n8.3 In the event of a termination of this Agreement Sections 5, 6, 7, 8 and 9\nshall survive such termination and shall remain in full force thereafter. For\nthe avoidance of doubt, Free and Open Source Software (sub)licenses that have\nalready been granted for Contributions at the date of the termination shall\nremain in full force after the termination of this Agreement.\n\n## 9 Miscellaneous\n\n9.1 This Agreement and all disputes, claims, actions, suits or other proceedings\narising out of this agreement or relating in any way to it shall be governed by\nthe laws of Canada excluding its private international law provisions.\n\n9.2 This Agreement sets out the entire agreement between You and Us for Your\nContributions to Us and overrides all other agreements or understandings.\n\n9.3 In case of Your death, this agreement shall continue with Your heirs. In\ncase of more than one heir, all heirs must exercise their rights through a\ncommonly authorized person.\n\n9.4 If any provision of this Agreement is found void and unenforceable, such\nprovision will be replaced to the extent possible with a provision that comes\nclosest to the meaning of the original provision and that is enforceable. The\nterms and conditions set forth in this Agreement shall apply notwithstanding any\nfailure of essential purpose of this Agreement or any limited remedy to the\nmaximum extent possible under law.\n\n9.5 You agree to notify Us of any facts or circumstances of which you become\naware that would make this Agreement inaccurate in any respect.\n\nYou\nDate:    ____________________________________________________\nName:    ____________________________________________________\nTitle:   ____________________________________________________\nAddress: ____________________________________________________\n\nUs\nDate:    ____________________________________________________\nName:    ____________________________________________________\nTitle:   ____________________________________________________\nAddress: ____________________________________________________\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nAny open source product is only as good as the community behind it. You can\nparticipate by sharing code, ideas, or simply helping others. No matter what\nyour skill level is, every contribution counts.\n\n## Games vs Core\n\nThese contributions guidelines do not apply in any way to games submitted to the\nBoardzilla platform. **You retain full copyright for your game code and\nassets.**  This only only applies to code submitted to the actual Boardzilla\ncore library.\n\n## Copyright\n\n**IMPORTANT:** By supplying code to Boardzilla core in issues and pull requests,\nyou agree to assign copyright of that code to us, on the condition that we also\nrelease that code under the AGPL license.\n\nWe ask for this so that the ownership in the license is clear and unambiguous,\nand so that community involvement doesn't stop us from being able to sustain the\nproject by releasing this code under a permissive licenses in addition to the\nopen source AGPL license. This copyright assignment won't prevent you from using\nthe code in any way you see fit.\n\nSee our [Contributor License Agreement](CLA.md) for the legal details.\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>."
  },
  {
    "path": "README.md",
    "content": "👋 This is Boardzilla, a framework to make writing a digital board game easy. Boardzilla takes care of\n\n- player management\n- structuring game rules\n- persisting game & player state\n- animations\n\nand much more!\n\nVisit us at https://boardzilla.io.\n\nSee documentation at https://docs.boardzilla.io.\n\n(c)2024 Andrew Hull\n"
  },
  {
    "path": "decl.d.ts",
    "content": "declare module \"*.ogg\";\n"
  },
  {
    "path": "esbuild.mjs",
    "content": "import * as esbuild from 'esbuild'\nimport {sassPlugin} from 'esbuild-sass-plugin'\n\nawait esbuild.build({\n  entryPoints: ['./src/ui/assets/index.scss'],\n  assetNames: '[name]',\n  bundle: true,\n  format: 'esm',\n  outdir: 'dist/ui/assets/',\n  loader: {\n    '.ogg': 'dataurl',\n    '.jpg': 'file',\n  },\n  sourcemap: 'inline',\n  plugins: [sassPlugin()],\n})\n\nawait esbuild.build({\n  entryPoints: ['./src/components/d6/index.ts'],\n  assetNames: '[name]',\n  bundle: true,\n  format: 'esm',\n  outdir: 'dist/components/d6/assets/',\n  loader: {\n    '.ogg': 'copy',\n  },\n  sourcemap: 'inline',\n  plugins: [sassPlugin()],\n})\n\nawait esbuild.build({\n  entryPoints: ['./src/components/flippable/index.ts'],\n  assetNames: '[name]',\n  bundle: true,\n  format: 'esm',\n  outdir: 'dist/components/flippable/assets/',\n  sourcemap: 'inline',\n  plugins: [sassPlugin()],\n})\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"@boardzilla/core\",\n  \"version\": \"0.2.14\",\n  \"author\": \"Andrew Hull <aghull@gmail.com>\",\n  \"license\": \"AGPL-3.0\",\n  \"scripts\": {\n    \"clean\": \"rm -rf dist docs\",\n    \"build\": \"yarn build:test && rm -rf dist/test\",\n    \"prepublish\": \"git diff-index --quiet HEAD || (echo 'git unclean' && exit 1)\",\n    \"prepack\": \"./scripts/prepack\",\n    \"postpack\": \"./scripts/postpack\",\n    \"build:test\": \"yarn assets && yarn compile && find dist/ -type f|grep js$|xargs grep -l scss|xargs sed -i~ 's/\\\\.scss/.css/g' && find dist/ -type f|grep js~$|xargs rm\",\n    \"assets\": \"node esbuild.mjs\",\n    \"test\": \"NODE_ENV=test yarn run build:test && mocha src/test/setup.js dist/test/*_test.js\",\n    \"test:debug\": \"NODE_ENV=test yarn run build:test && mocha --inspect-brk --timeout 3600000 src/test/setup-debug.js dist/test/*_test.js\",\n    \"compile\": \"tsc\",\n    \"docs\": \"typedoc\",\n    \"lint\": \"eslint . --ext .ts\",\n    \"dep-check\": \"dpdm  --no-warning --no-tree -T ./src/index.ts\"\n  },\n  \"type\": \"module\",\n  \"exports\": {\n    \".\": \"./entry/index.js\",\n    \"./components\": \"./entry/components/index.js\"\n  },\n  \"files\": [\n    \"entry/**/*\"\n  ],\n  \"types\": \"entry/index.d.ts\",\n  \"sideEffects\": [\n    \"./src/ui/assets/index.scss\"\n  ],\n  \"dependencies\": {\n    \"classnames\": \"^2.3.1\",\n    \"graphology\": \"^0.25.4\",\n    \"graphology-shortest-path\": \"^2.0.2\",\n    \"graphology-traversal\": \"^0.3.1\",\n    \"graphology-types\": \"^0.24.7\",\n    \"random-seed\": \"^0.3.0\",\n    \"react\": \"^18.2\",\n    \"react-color\": \"^2.19.3\",\n    \"react-dom\": \"^18.2\",\n    \"react-draggable\": \"^4.4.5\",\n    \"uuid-random\": \"^1.3.2\",\n    \"zustand\": \"^4.4.0\"\n  },\n  \"devDependencies\": {\n    \"@types/chai\": \"^4.3.1\",\n    \"@types/chai-spies\": \"^1.0.3\",\n    \"@types/jest\": \"^28.1.4\",\n    \"@types/node\": \"^20.6.2\",\n    \"@types/random-seed\": \"^0.3.3\",\n    \"@types/react\": \"^18.2.25\",\n    \"@types/react-color\": \"^3.0.6\",\n    \"@types/react-dom\": \"^18.2.14\",\n    \"@typescript-eslint/eslint-plugin\": \"^6.9.1\",\n    \"@typescript-eslint/parser\": \"^6.9.1\",\n    \"chai\": \"^4.3.8\",\n    \"chai-spies\": \"^1.0.0\",\n    \"dpdm\": \"^3.14.0\",\n    \"esbuild\": \"^0.19.5\",\n    \"esbuild-sass-plugin\": \"^2.16.0\",\n    \"eslint\": \"^8.53.0\",\n    \"eslint-plugin-react-hooks\": \"^4.6.0\",\n    \"mocha\": \"^10.2.0\",\n    \"ts-node\": \"^10.8.2\",\n    \"typedoc\": \"^0.25.2\",\n    \"typedoc-plugin-markdown\": \"^3.17.1\",\n    \"typedoc-plugin-merge-modules\": \"^5.1.0\",\n    \"typescript\": \"^5.2.0\"\n  },\n  \"typedocOptions\": {\n    \"entryPoints\": [\n      \"src\",\n      \"src/game.ts\",\n      \"src/board\",\n      \"src/flow\",\n      \"src/action\",\n      \"src/player\",\n      \"src/ui\"\n    ],\n    \"plugin\": [\n      \"typedoc-plugin-markdown\",\n      \"typedoc-plugin-merge-modules\"\n    ],\n    \"sort\": \"source-order\",\n    \"categorizeByGroup\": false,\n    \"excludeInternal\": true,\n    \"excludeNotDocumented\": true,\n    \"out\": \"docs\",\n    \"name\": \"@boardzilla/core\"\n  }\n}\n"
  },
  {
    "path": "scripts/postpack",
    "content": "#!/bin/bash\nset -e\n\nrm -r entry\nln -s src entry\n"
  },
  {
    "path": "scripts/prepack",
    "content": "#!/bin/bash\nset -e\n\nyarn clean\nyarn build\nrm -r entry\nmv dist entry\n"
  },
  {
    "path": "src/action/action.ts",
    "content": "import Selection from './selection.js';\nimport GameElement from '../board/element.js';\nimport Piece from '../board/piece.js';\nimport ElementCollection from '../board/element-collection.js';\nimport { n } from '../utils.js';\n\nimport type { ResolvedSelection, BoardQueryMulti } from './selection.js';\nimport type { Game, PieceGrid } from '../board/index.js';\nimport type { Player } from '../player/index.js';\nimport type { default as GameManager, ActionDebug, PendingMove } from '../game-manager.js';\n\n/**\n * A single argument\n * @category Actions\n */\nexport type SingleArgument = string | number | boolean | GameElement | Player;\n\n/**\n * An argument that can be added to an {@link Action}. Each value is chosen by\n * player or in some cases passed from a previous action. Arguments can be:\n * - a number\n * - a string\n * - a boolean\n * - a {@link GameElement}\n * - a {@link Player}\n * - an array of one these in the case of a multi-choice selection\n * @category Actions\n */\nexport type Argument = SingleArgument | SingleArgument[];\n\n/**\n * A follow-up action\n * @category Actions\n */\nexport type ActionStub = {\n  /**\n   * The name of the action, as defined in `{@link Game#defineactions}`.\n   */\n  name: string,\n  /**\n   * The player to take this action, if different than the current player\n   */\n  player?: Player,\n  /**\n   * Action prompt. If specified, overrides the `action.prompt` in `{@link\n   * Game#defineactions}`.\n   */\n  prompt?: string,\n  /**\n   * Description of taking the action from a 3rd person perspective,\n   * e.g. \"choosing a card\". The string will be automatically prefixed with the\n   * player name and appropriate verb (\"is/are\"). If specified, this will be\n   * used to convey to non-acting players what actions are happening.\n   */\n  description?: string,\n  /**\n   * An object containing arguments to be passed to the follow-up action. This\n   * is useful if there are multiple ways to trigger this follow-up that have\n   * variations.\n   */\n  args?: Record<string, Argument>\n}\n\ntype Group = Record<string,\n  ['number', Parameters<Action['chooseNumber']>[1]?] |\n  ['select', Parameters<Action['chooseFrom']>[1], Parameters<Action['chooseFrom']>[2]?] |\n  ['text', Parameters<Action['enterText']>[1]?]\n>\n\ntype ExpandGroup<A extends Record<string, Argument>, R extends Group> = A & {[K in keyof R]:\n  R[K][0] extends 'number' ? number :\n  R[K][0] extends 'text' ? string :\n  R[K][0] extends 'select' ? (R[K][1] extends Parameters<typeof Action.prototype.chooseFrom<any, infer E extends SingleArgument>>[1] ? E : never) :\n  never\n}\n\n/**\n * Actions represent discreet moves players can make. These contain the choices\n * needed to take this action and the results of the action. Create Actions\n * using the {@link Game#action} function. Actions are evaluated at the time the\n * player has the option to perform the action, so any expressions that involve\n * game state will reflect the state at the time the player is performing the\n * action.\n *\n * @privateRemarks\n * The Action object is responsible for:\n * - providing Selection objects to players to aid in supplying appropriate Arguments\n * - validating player Arguments and returning any Selections needed to complete\n * - accepting player Arguments and altering board state\n *\n * @category Actions\n */\nexport default class Action<A extends Record<string, Argument> = NonNullable<unknown>> {\n  name?: string;\n  prompt?: string;\n  description?: string;\n  selections: Selection[] = [];\n  moves: ((args: Record<string, Argument>) => any)[] = [];\n  condition?: ((args: A) => boolean) | boolean;\n  messages: {text: string, args?: Record<string, Argument> | ((a: A) => Record<string, Argument>), position?: number}[] = [];\n  order: ('move' | 'message')[] = [];\n  mutated = false;\n\n  gameManager: GameManager;\n\n  constructor({ prompt, description, condition }: {\n    prompt?: string,\n    description?: string,\n    condition?: ((args: A) => boolean) | boolean,\n  }) {\n    this.prompt = prompt;\n    this.description = description;\n    this.condition = condition;\n  }\n\n  isPossible(args: A): boolean {\n    return typeof this.condition === 'function' ? this.condition(args) : this.condition ?? true;\n  }\n\n  // given a set of args, return sub-selections possible trying each possible next arg\n  // return undefined if these args are impossible\n  // return 0-length if these args are submittable\n  // return array of follow-up selections if incomplete\n  // skipping/expanding is very complex and this method runs all the rules for what should/must be combined, either as additional selections or as forced args\n  // skippable options will still appear in order to present the choices to the user to select that tree. This will be the final selection if no other selection turned skipping off\n  // TODO memoize\n  _getPendingMoves(args: Record<string, Argument>, debug?: ActionDebug): PendingMove[] | undefined {\n    if (debug) {\n      debug[this.name!] = { args: {} };\n      for (const arg of Object.keys(args)) debug[this.name!].args[arg] = 'sel';\n    }\n    const moves = this._getPendingMovesInner(args, debug);\n    // resolve any combined selections now with only args up until first choice\n    if (moves?.length) {\n      for (const move of moves) {\n        if (debug) {\n          debug[move.name].args[move.selections[0].name] = 'ask';\n        }\n        const combineWith = move.selections[0].clientContext?.combineWith; // guaranteed single selection\n        let confirm: Selection['confirm'] | undefined = move.selections[0].confirm;\n        let validation: Selection['validation'] | undefined = move.selections[0].validation;\n        // look ahead for any selections that can/should be combined\n        for (let i = this.selections.findIndex(s => s.name === move.selections[0].name) + 1; i !== this.selections.length; i++) {\n          if (confirm) break; // do not skip an explicit confirm\n          let selection: Selection | ResolvedSelection = this.selections[i];\n          if (combineWith?.includes(selection.name)) selection = selection.resolve(move.args);\n          if (!selection.isResolved()) break;\n          const arg = selection.isForced();\n          if (arg !== undefined) { // forced future args are added here to shorten the form and pre-prompt any confirmation\n            move.args[selection.name] = arg;\n            if (debug) {\n              debug[move.name].args[selection.name] = 'forced';\n            }\n          } else if (combineWith?.includes(selection.name)) { // future combined selections are added as well\n            move.selections.push(selection);\n            if (debug) {\n              debug[move.name].args[selection.name] = 'ask';\n            }\n          } else {\n            break;\n          }\n          confirm = selection.confirm ?? confirm; // find latest confirm for the overall combination\n          validation = selection.validation ?? validation;\n        }\n        if (confirm) move.selections[0].confirm = confirm; // and put it on top\n        if (validation) move.selections[move.selections.length - 1].validation = validation; // on bottom\n      }\n    }\n    return moves;\n  }\n\n  _getPendingMovesInner(args: Record<string, Argument>, debug?: ActionDebug): PendingMove[] | undefined {\n    let selection = this._nextSelection(args);\n    if (!selection) return [];\n\n    const move = {\n      name: this.name!,\n      prompt: this.prompt,\n      description: this.description,\n      args,\n      selections: [selection]\n    };\n\n    if (!selection.isPossible()) {\n      if (debug) {\n        debug[this.name!].args[selection.name] ??= 'imp';\n      }\n      return;\n    }\n    if (!selection.isUnbounded()) {\n      let possibleOptions: { choice: SingleArgument, error?: string, label?: string }[] = [];\n      let anyValidOption = false;\n      let pruned = false;\n      let pendingMoves: PendingMove[] = [];\n      let hasCompleteMove = false\n      for (const option of selection.options()) {\n        const allArgs = {...args, [selection.name]: option.choice};\n        if (selection.validation && !selection.isMulti()) {\n          const error = this._withDecoratedArgs(allArgs as A, args => selection!.error(args))\n          if (error) {\n            pruned = true;\n            option.error = error;\n            possibleOptions.push(option as { choice: SingleArgument, error?: string, label?: string })\n            continue;\n          }\n        }\n        const submoves = this._getPendingMovesInner(allArgs, debug);\n        if (submoves === undefined) {\n          pruned = true;\n        } else {\n          if (!selection.isMulti()) possibleOptions.push(option as { choice: SingleArgument, error?: string, label?: string });\n          anyValidOption ||= true;\n          hasCompleteMove ||= submoves.length === 0;\n          pendingMoves = pendingMoves.concat(submoves);\n        }\n      }\n      if (!anyValidOption) {\n        if (debug) {\n          debug[this.name!].args[selection.name] = 'tree';\n        }\n        return undefined;\n      }\n      if (pruned && !selection.isMulti()) {\n        selection.resolvedChoices = possibleOptions;\n      }\n\n      // return the next selection(s) if skipIf, provided it exists for all possible choices\n      // special case: do not skip \"apparent\" choices in group even if they are ultimately forced, in order to best present the limited options\n      if (pendingMoves.length && (\n        ((selection.skipIf === 'always' || selection.skipIf === true) && !hasCompleteMove) ||\n          selection.skipIf === 'only-one' && possibleOptions.length === 1 && (!selection.clientContext?.combineWith || selection.options().length <= 1)\n      )) {\n        if (debug) {\n          debug[this.name!].args[selection.name] = selection.skipIf === true ? 'skip' : selection.skipIf;\n        }\n        return pendingMoves;\n      }\n    }\n    if (debug && (debug[this.name!].args[selection.name] ?? 'imp') === 'imp') {\n      debug[this.name!].args[selection.name] ??= 'future';\n    }\n\n    return [move];\n  }\n\n  /**\n   * given a partial arg list, returns a selection object for continuation if one exists.\n   * @internal\n   */\n  _nextSelection(args: Record<string, Argument>): ResolvedSelection | undefined {\n    let nextSelection: ResolvedSelection | undefined = undefined;\n    for (const s of this.selections) {\n      const selection = s.resolve(args);\n      if (selection.skipIf === true) continue;\n      if (!(s.name in args)) {\n        nextSelection = selection;\n        break;\n      }\n    }\n    return nextSelection;\n  }\n\n  /**\n   * process this action with supplied args. returns error if any\n   * @internal\n   */\n  _process(player: Player, args: Record<string, Argument>): string | undefined {\n    // truncate invalid args - is this needed?\n    let error: string | undefined = undefined;\n    if (!this.isPossible(args as A)) return `${this.name} action not possible`;\n    for (const selection of this.selections) {\n      if (args[selection.name] === undefined) {\n        const arg = selection.resolve(args).isForced()\n        if (arg) args[selection.name] = arg;\n      }\n\n      error = this._withDecoratedArgs(args as A, args => selection.error(args))\n      if (error) {\n        console.error(`Invalid choice for ${selection.name}. Got \"${args[selection.name]}\" ${error}`);\n        break;\n      }\n    }\n    if (error) return error;\n\n    // revalidate on server. quite expensive. easier way? I think this might just be counting the args since the validation already passed ^^\n    if (!globalThis.window) {\n      const pendingMoves = this._getPendingMoves(args);\n      if (!pendingMoves) {\n        console.error('attempted to process invalid args', this.name, args);\n        return error || 'unknown error during action._process';\n      }\n      if (pendingMoves.length) {\n        return error || 'incomplete action';\n      }\n    }\n\n    let moveIndex = 0;\n    let messageIndex = 0;\n    for (const seq of this.order) {\n      if (seq === 'move') {\n        this.moves[moveIndex++](args);\n      } else {\n        const message = this.messages[messageIndex++];\n        const messageArgs = ((typeof message.args === 'function') ? message.args(args as A) : message.args);\n        if (message.position) {\n          this.gameManager.game.messageTo(message.position, message.text, {...args, player, ...messageArgs});\n        } else {\n          this.gameManager.game.message(message.text, {...args, player, ...messageArgs});\n        }\n      }\n    }\n  }\n\n  _addSelection(selection: Selection) {\n    if (this.selections.find(s => s.name === selection.name)) throw Error(`Duplicate selection name on action: ${selection.name}`);\n    if (this.mutated) console.warn(`Adding a choice (\"${selection.name}\") after behavior in action is valid but players will need to perform the choices before the behavior.`);\n    this.selections.push(selection);\n    return selection;\n  }\n\n  // fn must be idempotent\n  _withDecoratedArgs(args: A, fn: (args: A) => any) {\n    if (args['__placement__']) {\n      const placementSelection = this.selections.find(s => s.name === '__placement__');\n      if (placementSelection && args[placementSelection.placePiece!]) {\n        args = {...args};\n        // temporarily set piece to place to access position properties\n        const placePiece = (args[placementSelection.placePiece!] as Piece<Game>);\n        const { row, column, _rotation } = placePiece;\n        const [newColumn, newRow, newRotation] = args['__placement__'] as [number, number, number?];\n        placePiece.column = newColumn;\n        placePiece.row = newRow;\n        placePiece.rotation = newRotation ?? 0;\n        const result = fn(args);\n        placePiece.column = column;\n        placePiece.row = row;\n        placePiece._rotation = _rotation;\n        return result;\n      }\n    }\n    return fn(args);\n  }\n\n  _getError(selection: ResolvedSelection, args: A) {\n    return this._withDecoratedArgs(args, args => selection.error(args));\n  }\n\n  _getConfirmation(selection: ResolvedSelection, args: A) {\n    if (!selection.confirm) return;\n    const argList = selection.confirm[1];\n    return n(\n      selection.confirm[0],\n      {...args, ...(typeof argList === 'function' ? this._withDecoratedArgs(args, argList) : argList)}\n    );\n  }\n\n  /**\n   * Add behaviour to this action to alter game state. After adding the choices\n   * to an action, calling `do` causes Boardzilla to use the player choices to\n   * actually do something with those choices. Call this method after all the\n   * methods for player choices so that the choices are properly available to\n   * the `do` function.\n   *\n   * @param move - The action to perform. This function accepts one argument\n   * with key-value pairs for each choice added to the action using the provided\n   * names.\n   *\n   * @example\n   * player => action({\n   *   prompt: 'Take resources',\n   * }).chooseFrom({\n   *   'resource', ['lumber', 'steel'],\n   *   { prompt: 'Select resource' }\n   * }).chooseNumber(\n   *   'amount', {\n   *     prompt: 'Select amount',\n   *     max: 3\n   * }).do(({ resource, amount }) => {\n   *   // the choices are automatically passed in with their proper type\n   *   game.firstN(amount, Resource, {resource}).putInto(\n   *     player.my('stockPile')\n   *   );\n   * })\n   * @category Behaviour\n   */\n  do(move: (args: A) => any): Action<A> {\n    this.mutated = true;\n    this.moves.push(move);\n    this.order.push('move');\n    return this;\n  }\n\n  /**\n   * Add a message to this action that will be broadcast in the chat. Call this\n   * method after all the methods for player choices so that the choices are\n   * properly available to the `message` function. However the message should be\n   * called before or after any `do` behaviour depending on whether you want the\n   * message to reflect the game state before or after the move is performs. The\n   * action's `message` and `do` functions can be intermixed in this way to\n   * generate messages at different points int the execution of a move.\n   *\n   * @param text - The text of the message to send. This can contain interpolated\n   * strings with double braces just as when calling {@link Game#message}\n   * directly. However when using this method, the player performing the action,\n   * plus any choices made in the action are automatically made available.\n   *\n   * @param args - If additional strings are needed in the message besides\n   * 'player' and the player choices, these can be specified here. This can also\n   * be specified as a function that accepts the player choices and returns\n   * key-value pairs of strings for interpolation.\n   *\n   * @example\n   * action({\n   *   prompt: 'Say something',\n   * }).enterText({\n   *   'message',\n   * }).message(\n   *   '{{player}} said {{message}}' // no args needed\n   * ).message(\n   *   \"I said, {{player}} said {{loudMessage}}\",\n   *   ({ message }) => ({ loudMessage: message.toUpperCase() })\n   * )\n   * @category Behaviour\n   */\n  message(text: string, args?: Record<string, Argument> | ((a: A) => Record<string, Argument>)) {\n    this.messages.push({text, args});\n    this.order.push('message');\n    return this;\n  }\n\n  /**\n   * Add a message to this action that will be broadcast in the chat to the\n   * specified player(s). Call this method after all the methods for player\n   * choices so that the choices are properly available to the `message`\n   * function. However the message should be called before or after any `do`\n   * behaviour depending on whether you want the message to reflect the game\n   * state before or after the move is performs. The action's `message` and `do`\n   * functions can be intermixed in this way to generate messages at different\n   * points int the execution of a move.\n   *\n   * @param player - Player or players to receive the message\n   *\n   * @param text - The text of the message to send. This can contain interpolated\n   * strings with double braces just as when calling {@link Game#message}\n   * directly. However when using this method, the player performing the action,\n   * plus any choices made in the action are automatically made available.\n   *\n   * @param args - If additional strings are needed in the message besides\n   * 'player' and the player choices, these can be specified here. This can also\n   * be specified as a function that accepts the player choices and returns\n   * key-value pairs of strings for interpolation.\n   *\n   * @example\n   * action({\n   *   prompt: 'Say something',\n   * }).enterText({\n   *   'message',\n   * }).message(\n   *   '{{player}} said {{message}}' // no args needed\n   * ).message(\n   *   \"I said, {{player}} said {{loudMessage}}\",\n   *   ({ message }) => ({ loudMessage: message.toUpperCase() })\n   * )\n   * @category Behaviour\n   */\n  messageTo(player: (Player | number) | (Player | number)[], text: string, args?: Record<string, Argument> | ((a: A) => Record<string, Argument>)) {\n    if (!(player instanceof Array)) player = [player];\n    for (const p of player) {\n      this.messages.push({position: typeof p === 'number' ? p : p.position, text, args});\n      this.order.push('message');\n    }\n    return this;\n  }\n\n  /**\n   * Add a choice to this action from a list of options. These choices will be\n   * displayed as buttons in the UI.\n   *\n   * @param name - The name of this choice. This name will be used in all\n   * functions that accept the player's choices\n   *\n   * @param choices - An array of choices. This may be an array of simple values\n   * or an array of objects in the form: `{ label: string, choice: value }`\n   * where value is the actual choice that will be passed to the rest of the\n   * action, but label is the text presented to the player that they will be\n   * prompted to click. Use the object style when you want player text to\n   * contain additional logic or differ in some way from the choice, similiar to\n   * `<option value=\"key\">Some text</option>` in HTML. This can also be a\n   * function that returns the choice array. This function will accept arguments\n   * for each choice the player has made up to this point in the action.\n   *\n   * @param {Object} options\n   * @param options.prompt - Prompt displayed to the user for this choice.\n   * @param options.skipIf - One of 'always', 'never' or 'only-one' or a\n   * function returning a boolean. (Default 'only-one').\n   *\n   * <ul>\n   * <li>only-one: If there is only valid choice in the choices given, the game\n   * will skip this choice, prompting the player for subsequent choices, if any,\n   * or completing the action otherwise.\n   * <li>always: Rather than present this choice directly, the player will be\n   * prompted with choices from the *next choice* in the action for each\n   * possible choice here, essentially expanding the choices ahead of time to\n   * save the player a step. This option only has relevance if there are\n   * subsequent choices in the action.\n   * <li>never: Always present this choice, even if the choice is forced\n   * <li>function: A function that accepts all player choices up to this point\n   * and returns a boolean. If returning true, this choice will be skipped.\n   * This form is useful in the rare situations where the choice at the time may\n   * be meaningless, e.g. selecting from a set of identical tokens. In this case\n   * the game will make the choice for the player using the first viable option.\n   * </ul>\n   *\n   * @param options.validate - A function that takes an object of key-value\n   * pairs for all player choices and returns a boolean. If false, the game will\n   * not allow the player to submit this choice. If a string is returned, this\n   * will display as the reason for disallowing these selections.\n   *\n   * @param options.confirm - A confirmation message that the player will always\n   * see before commiting this choice. This can be useful to present additional\n   * information about the consequences of this choice, or simply to force the\n   * player to hit a button with a clear message. This can be a simple string,\n   * or a 2-celled array in the same form as {@link message} with a string\n   * message and a set of key-value pairs for string interpolation, optionally\n   * being a function that takes an object of key-value pairs for all player\n   * choices, and returns the interpolation object.\n   *\n   * @example\n   * action({\n   *   prompt: 'Choose color',\n   * }).chooseFrom(\n   *   'color', ['white', 'blue', 'red'],\n   * ).do(\n   *   ({ color }) => ... color will be equal to the player-selected color ...\n   * )\n   *\n   * // a more complex example:\n   * action({\n   *   prompt: 'Take resources',\n   * }).chooseFrom(\n   *   'resource', ['lumber', 'steel', 'oil'],\n   *   { prompt: 'Select resource' }\n   * ).chooseFrom(\n   *   // Use the functional style to include the resource choice in the text\n   *   // Also use object style to have the value simply be \"high\" or \"low\"\n   *   'grade', ({ resource }) => [\n   *     { choice: 'high', label: `High grade ${resource}` }\n   *     { choice: 'low', label: `Low grade ${resource}` }\n   *   ],\n   *   {\n   *     // A follow-up choice that doesn't apply to \"oil\"\n   *     skipIf: ({ resource }) => resource === 'oil',\n   *     // Add an 'are you sure?' message\n   *     confirm: ['Buy {{grade}} grade {{resource}}?', ({ grade }) = ({ grade: grade.toUpperCase() })]\n   *   }\n   * ).do (\n   *   ({ resource, grade }) => {\n   *     // resource will equal 'lumber', 'steel' or 'oil'\n   *     // grade will equal 'high' or 'low'\n   *   }\n   * )\n   * @category Choices\n   */\n  chooseFrom<N extends string, T extends SingleArgument>(\n    name: N,\n    choices: (T & (string | number | boolean))[] | { label: string, choice: T }[] | ((args: A) => (T & (string | number | boolean))[] | { label: string, choice: T }[]),\n    options?: {\n      prompt?: string | ((args: A) => string)\n      confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: T}) => Record<string, Argument>) | undefined]\n      validate?: ((args: A & {[key in N]: T}) => string | boolean | undefined)\n      // initial?: T | ((...arg: A) => T), // needed for select-boxes?\n      skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);\n    }\n  ): Action<A & {[key in N]: T}> {\n    this._addSelection(new Selection(name, {\n      prompt: options?.prompt,\n      validation: options?.validate,\n      confirm: options?.confirm,\n      skipIf: options?.skipIf,\n      selectFromChoices: { choices }\n    }));\n    return this as unknown as Action<A & {[key in N]: T}>;\n  }\n\n  /**\n   * Prompt the user for text entry. Use this in games where players submit\n   * text, like word-guessing games.\n   *\n   * @param name - The name of this text input. This name will be used in all\n   * functions that accept the player's choices\n   *\n   * @param {Object} options\n   * @param options.initial - Default text that can appear initially before a\n   * user types.\n   * @param options.prompt - Prompt displayed to the user for entering this\n   * text.\n   *\n   * @param options.validate - A function that takes an object of key-value\n   * pairs for all player choices and returns a boolean. If false, the game will\n   * not allow the player to submit this text. If a string is returned, this\n   * will display as the reason for disallowing this text.\n   *\n   * @example\n   * action({\n   *   prompt: 'Guess a word',\n   * }).enterText({\n   *   'guess',\n   *   { prompt: 'Your guess', }\n   * }).message(\n   *   guess => `{{player}} guessed ${guess}`\n   * })\n   * @category Choices\n   */\n  enterText<N extends string>(name: N, options?: {\n    prompt?: string | ((args: A) => string),\n    validate?: ((args: A & {[key in N]: string}) => string | boolean | undefined),\n    regexp?: RegExp,\n    initial?: string | ((args: A) => string)\n  }): Action<A & {[key in N]: string}> {\n    const { prompt, validate, regexp, initial } = options || {}\n    this._addSelection(new Selection(name, { prompt, validation: validate, enterText: { regexp, initial }}));\n    return this as unknown as Action<A & {[key in N]: string}>;\n  }\n\n  /**\n   * Add a numerical choice for this action. This will be presented with a\n   * number picker.\n   *\n   * @param name - The name of this choice. This name will be used in all\n   * functions that accept the player's choices\n   *\n   * @param {Object} options\n   *\n   * @param options.prompt - Prompt displayed to the user for entering this\n   * number.\n   *\n   * @param options.min - Minimum allowed. Default 1.\n   *\n   * @param options.max - Maximum allowed. Default Infinity\n   *\n   * @param options.initial - Initial value to display in the picker\n   *\n   * @param options.skipIf - One of 'always', 'never' or 'only-one' or a\n   * function returning a boolean. (Default 'only-one').\n   *\n   * <ul>\n   * <li>only-one: If there is only valid choice in the choices given, the game\n   * will skip this choice, prompting the player for subsequent choices, if any,\n   * or completing the action otherwise.\n   * <li>always: Rather than present this choice directly, the player will be\n   * prompted with choices from the *next choice* in the action for each\n   * possible choice here, essentially expanding the choices ahead of time to\n   * save the player a step. This option only has relevance if there are\n   * subsequent choices in the action.\n   * <li>never: Always present this choice, even if the choice is forced\n   * <li>function: A function that accepts all player choices up to this point\n   * and returns a boolean. If returning true, this choice will be skipped.\n   * This form is useful in the rare situations where the choice at the time may\n   * be meaningless, e.g. selecting from a set of identical tokens. In this case\n   * the game will make the choice for the player using the first viable option.\n   * </ul>\n   *\n   * @param options.validate - A function that takes an object of key-value\n   * pairs for all player choices and returns a boolean. If false, the game will\n   * not allow the player to submit this choice. If a string is returned, this\n   * will display as the reason for disallowing these selections.\n   *\n   * @param options.confirm - A confirmation message that the player will always\n   * see before commiting this choice. This can be useful to present additional\n   * information about the consequences of this choice, or simply to force the\n   * player to hit a button with a clear message. This can be a simple string,\n   * or a 2-celled array in the same form as {@link message} with a string\n   * message and a set of key-value pairs for string interpolation, optionally\n   * being a function that takes an object of key-value pairs for all player\n   * choices, and returns the interpolation object.\n   *\n   * @example\n   * player => action({\n   *   prompt: 'Buy resources',\n   * }).chooseNumber(\n   *   'amount', {\n   *     min: 5,\n   *     max: 10 // select from 5 - 10\n   * }).do(\n   *   ({ amount }) => player.resource += amount\n   * );\n   * @category Choices\n   */\n  chooseNumber<N extends string>(name: N, options: {\n    min?: number | ((args: A) => number),\n    max?: number | ((args: A) => number),\n    prompt?: string | ((args: A) => string),\n    confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: number}) => Record<string, Argument>) | undefined]\n    validate?: ((args: A & {[key in N]: number}) => string | boolean | undefined),\n    initial?: number | ((args: A) => number),\n    skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);\n  } = {}): Action<A & {[key in N]: number}> {\n    const { min, max, prompt, confirm, validate, initial, skipIf } = options;\n    this._addSelection(new Selection(name, { prompt, confirm, validation: validate, skipIf, selectNumber: { min, max, initial } }));\n    return this as unknown as Action<A & {[key in N]: number}>;\n  }\n\n  /**\n   * Add a choice of game elements to this action. Users will click on the\n   * playing area to make their choice.\n   *\n   * @param {Object} options\n\n   * @param name - The name of this choice. This name will be used in all\n   * functions that accept the player's choices\n\n   * @param choices - Elements that may be chosen. This can either be an array\n   * of elements or a function returning an array, if the choices depend on\n   * previous choices. If using a function, it will accept arguments for each\n   * choice the player has made up to this point in the action.\n   *\n   * @param options.prompt - Prompt displayed to the user for this choice.\n   *\n   * @param options.number - If supplied, the choice is for a *set* of exactly\n   * `number` elements. For example, if the player is being asked to pass 3\n   * cards from their hand, the `choices` should be to the cards in their hand\n   * and the `number` to 3.\n   *\n   * @param options.min - If supplied, the choice is for a *set* of\n   * elements and the minimum required is `min`.\n   *\n   * @param options.max - If supplied, the choice is for a *set* of\n   * elements and the maximum allowed is `max`.\n   *\n   * @param options.initial - Optional list of game elements to be preselected\n   *\n   * @param options.skipIf - One of 'always', 'never' or 'only-one' or a\n   * function returning a boolean. (Default 'only-one').\n   *\n   * <ul>\n   * <li>only-one: If there is only valid choice in the choices given, the game\n   * will skip this choice, prompting the player for subsequent choices, if any,\n   * or completing the action otherwise.\n   * <li>always: Rather than present this choice directly, the player will be\n   * prompted with choices from the *next choice* in the action for each\n   * possible choice here, essentially expanding the choices ahead of time to\n   * save the player a step. This option only has relevance if there are\n   * subsequent choices in the action.\n   * <li>never: Always present this choice, even if the choice is forced\n   * <li>function: A function that accepts all player choices up to this point\n   * and returns a boolean. If returning true, this choice will be skipped.\n   * This form is useful in the rare situations where the choice at the time may\n   * be meaningless, e.g. selecting from a set of identical tokens. In this case\n   * the game will make the choice for the player using the first viable option.\n   * </ul>\n   *\n   * @param options.validate - A function that takes an object of key-value\n   * pairs for all player choices and returns a boolean. If false, the game will\n   * not allow the player to submit this choice. If a string is returned, this\n   * will display as the reason for disallowing these selections.\n   *\n   * @param options.confirm - A confirmation message that the player will always\n   * see before commiting this choice. This can be useful to present additional\n   * information about the consequences of this choice, or simply to force the\n   * player to hit a button with a clear message. This can be a simple string,\n   * or a 2-celled array in the same form as {@link message} with a string\n   * message and a set of key-value pairs for string interpolation, optionally\n   * being a function that takes an object of key-value pairs for all player\n   * choices up to this point, including this one, and returns the interpolation\n   * object.\n   *\n   * @example\n   * player => action({\n   *   prompt: 'Mulligan',\n   * }).chooseOnBoard(\n   *   'cards', player.allMy(Card), {\n   *     prompt: 'Mulligan 1-3 cards',\n   *     // select 1-3 cards from hand\n   *     min: 1,\n   *     max: 3\n   * }).do(\n   *   ({ cards }) => {\n   *     // `cards` is an ElementCollection of the cards selected\n   *     cards.putInto($.discard);\n   *     $.deck.firstN(cards.length, Card).putInto(player.my('hand')!);\n   *   }\n   * )\n   * @category Choices\n   */\n  chooseOnBoard<T extends GameElement, N extends string>(name: N, choices: BoardQueryMulti<T, A>, options?: {\n    prompt?: string | ((args: A) => string);\n    confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: T}) => Record<string, Argument>) | undefined]\n    validate?: ((args: A & {[key in N]: T}) => string | boolean | undefined);\n    initial?: never;\n    min?: never;\n    max?: never;\n    number?: never;\n    skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);\n  }): Action<A & {[key in N]: T}>;\n  chooseOnBoard<T extends GameElement, N extends string>(name: N, choices: BoardQueryMulti<T, A>, options?: {\n    prompt?: string | ((args: A) => string);\n    confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: T[]}) => Record<string, Argument>) | undefined]\n    validate?: ((args: A & {[key in N]: T[]}) => string | boolean | undefined);\n    initial?: T[] | ((args: A) => T[]);\n    min?: number | ((args: A) => number);\n    max?: number | ((args: A) => number);\n    number?: number | ((args: A) => number);\n    skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);\n  }): Action<A & {[key in N]: T[]}>;\n  chooseOnBoard<T extends GameElement, N extends string>(name: N, choices: BoardQueryMulti<T, A>, options?: {\n    prompt?: string | ((args: A) => string);\n    confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: T | T[]}) => Record<string, Argument>) | undefined]\n    validate?: ((args: A & {[key in N]: T | T[]}) => string | boolean | undefined);\n    initial?: T[] | ((args: A) => T[]);\n    min?: number | ((args: A) => number);\n    max?: number | ((args: A) => number);\n    number?: number | ((args: A) => number);\n    skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);\n  }): Action<A & {[key in N]: T | T[]}> {\n    const { prompt, confirm, validate, initial, min, max, number, skipIf } = options || {};\n    this._addSelection(new Selection(\n      name, { prompt, confirm, validation: validate, skipIf, selectOnBoard: { chooseFrom: choices, min, max, number, initial } }\n    ));\n    if (min !== undefined || max !== undefined || number !== undefined) {\n      return this as unknown as Action<A & {[key in N]: T[]}>;\n    }\n    return this as unknown as Action<A & {[key in N]: T}>;\n  }\n\n  choose<N extends string, S extends 'number'>(\n    name: N,\n    type: S,\n    options?: Parameters<this['chooseNumber']>[1]\n  ): Action<A & {[key in N]: number}>;\n  choose<N extends string, S extends 'text'>(\n    name: N,\n    type: S,\n    options?: Parameters<this['enterText']>[1]\n  ): Action<A & {[key in N]: string}>;\n  choose<N extends string, S extends 'select', T extends SingleArgument>(\n    name: N,\n    type: S,\n    choices: T[] | Record<string, T> | ((args: A) => T[] | Record<string, T>),\n    options?: Parameters<this['chooseFrom']>[2]\n  ): Action<A & {[key in N]: T}>;\n  choose<N extends string, S extends 'board', T extends GameElement>(\n    name: N,\n    type: S,\n    choices: BoardQueryMulti<T, A>,\n    options?: Parameters<this['chooseOnBoard']>[2] & { min: never, max: never, number: never }\n  ): Action<A & {[key in N]: T}>;\n  choose<N extends string, S extends 'board', T extends GameElement>(\n    name: N,\n    type: S,\n    choices: BoardQueryMulti<T, A>,\n    options?: Parameters<this['chooseOnBoard']>[2]\n  ): Action<A & {[key in N]: T[]}>;\n  choose<N extends string, S extends 'select' | 'number' | 'text' | 'board'>(\n    name: N,\n    type: S,\n    choices?: any,\n    options?: Record<string, any>\n  ): Action<A & {[key in N]: Argument}> {\n    if (type === 'number') return this.chooseNumber(name, choices as Parameters<this['chooseNumber']>[1]);\n    if (type === 'text') return this.enterText(name, choices as Parameters<this['enterText']>[1]);\n    if (type === 'select') return this.chooseFrom(name, choices as Parameters<this['chooseFrom']>[1], options as Parameters<this['chooseFrom']>[2]);\n    return this.chooseOnBoard(name, choices as Parameters<this['chooseOnBoard']>[1], options as Parameters<this['chooseOnBoard']>[2]);\n  }\n\n  /**\n   * Create a multi-selection choice. These selections will be presented all at\n   * once as a form. This is used for form-like choices that have a number of\n   * choices that are not board choices, i.e. chooseFrom, chooseNumber and\n   * enterText\n   *\n   * @param choices - An object containing the selections. This is a set of\n   * key-value pairs where each key is the name of the selection and each value\n   * is an array of options where the first array element is a string indicating\n   * the type of choice ('number', 'select', 'text') and subsequent elements\n   * contain the options for the appropriate choice function (`chooseNumber`,\n   * `chooseFrom` or `enterText`).\n   *\n   * @param options.validate - A function that takes an object of key-value\n   * pairs for all player choices and returns a boolean. If false, the game will\n   * not allow the player to submit these choices. If a string is returned, this\n   * will display as the reason for disallowing these selections.\n   *\n   * @param options.confirm - A confirmation message that the player will always\n   * see before commiting this choice. This can be useful to present additional\n   * information about the consequences of this choice, or simply to force the\n   * player to hit a button with a clear message. This can be a simple string,\n   * or a 2-celled array in the same form as {@link message} with a string\n   * message and a set of key-value pairs for string interpolation, optionally\n   * being a function that takes an object of key-value pairs for all player\n   * choices, and returns the interpolation object.\n   *\n   * @example\n   * action({\n   *   prompt: 'purchase'\n   * }).chooseGroup({\n   *   lumber: ['number', { min: 2 }],\n   *   steel: ['number', { min: 2 }]\n   * }, {\n   *   // may not purchase more than 10 total resources\n   *   validate: ({ lumber, steel }) => lumber + steel <= 10\n   * });\n   * @category Choices\n   */\n  chooseGroup<R extends Group>(\n    choices: R,\n    options?: {\n      validate?: (args: ExpandGroup<A, R>) => string | boolean | undefined,\n      confirm?: string | [string, Record<string, Argument> | ((args: ExpandGroup<A, R>) => Record<string, Argument>) | undefined]\n    }\n  ): Action<ExpandGroup<A, R>> {\n    for (const [name, choice] of Object.entries(choices)) {\n      if (choice[0] === 'number') this.chooseNumber(name, choice[1]);\n      if (choice[0] === 'select') this.chooseFrom(name, choice[1], choice[2]);\n      if (choice[0] === 'text') this.enterText(name, choice[1]);\n    }\n    if (options?.confirm) this.selections[this.selections.length - 1].confirm = typeof options.confirm === 'string' ? [options.confirm, undefined] : options.confirm;\n    if (options?.validate) this.selections[this.selections.length - 1].validation = options.validate\n    for (let i = 1; i < Object.values(choices).length; i++) {\n      this.selections[this.selections.length - 1 - i].clientContext = {combineWith: this.selections.slice(-i).map(s => s.name)};\n    }\n    return this as unknown as Action<ExpandGroup<A, R>>;\n  }\n\n  /**\n   * Add a confirmtation step to this action. This can be useful if you want to\n   * present additional information to the player related to the consequences of\n   * their choice, like a cost incurred. Or this can simply be used to force the\n   * user to click an additional button on a particular important choice.\n   *\n   * @param prompt - Button text for the confirmation step. This can be a\n   * function returning the text which accepts each choice the player has made\n   * up till now as an argument.\n   *\n   * @example\n   * action({\n   *   prompt: \"Buy resources\",\n   * }).chooseNumber({\n   *   'amount', {\n   *     prompt: \"Amount\",\n   *     max: Math.floor(player.coins / 5)\n   * }).confirm(\n   *   ({ amount }) => `Spend ${amount * 5} coins`\n   * }).do(({ amount }) => {\n   *   player.resource += amount;\n   *   player.coins -= amount * 5;\n   * });\n   */\n  confirm(prompt: string | ((args: A) => string)): Action<A> {\n    this._addSelection(new Selection('__confirm__', {\n      prompt,\n      confirm: typeof prompt === 'string' ? prompt : ['{{__message__}}', (args: A) => ({__message__: prompt(args)})],\n      value: true\n    }));\n    return this;\n  }\n\n  /**\n   * Perform a move with the selected element(s) into a selected\n   * Space/Piece. This is almost the equivalent of calling Action#do and adding\n   * a putInto command, except that the game will also permit the UI to allow a\n   * mouse drag for the move.\n   *\n   * @param piece - A {@link Piece} to move or the name of the piece selection in this action\n   * @param into - A {@link GameElement} to move into or the name of the\n   * destination selection in this action.\n   *\n   * player => action({\n   *   prompt: 'Discard a card from hand'\n   * }).chooseOnBoard(\n   *   'card', player.my(Card)\n   * ).move(\n   *   'card', $.discard\n   * )\n   * @category Behaviour\n   */\n  move(piece: keyof A | Piece<Game>, into: keyof A | GameElement) {\n    this.do((args: A) => {\n      const selectedPiece = piece instanceof Piece ? piece : args[piece] as Piece<Game> | Piece<Game>[];\n      const selectedInto = into instanceof GameElement ? into : args[into] as GameElement;\n      if (selectedPiece instanceof Array) {\n        new ElementCollection(...selectedPiece).putInto(selectedInto);\n      } else {\n        selectedPiece.putInto(selectedInto);\n      }\n    });\n    const pieceSelection = typeof piece === 'string' ? this.selections.find(s => s.name === piece) : undefined;\n    const intoSelection = typeof into === 'string' ? this.selections.find(s => s.name === into) : undefined;\n    if (intoSelection && intoSelection.type !== 'board') throw Error(`Invalid move: \"${into as string}\" must be the name of a previous chooseOnBoard`);\n    if (pieceSelection && pieceSelection.type !== 'board') throw Error(`Invalid move: \"${piece as string}\" must be the name of a previous chooseOnBoard`);\n    if (intoSelection?.isMulti()) throw Error(\"Invalid move: May not move into a multiple choice selection\");\n    if (pieceSelection && !pieceSelection.isMulti()) pieceSelection.clientContext = { dragInto: intoSelection ?? into };\n    if (intoSelection) intoSelection.clientContext = { dragFrom: pieceSelection ?? piece };\n    return this;\n  }\n\n  /**\n   * Swap the location of two Pieces. Each of the two pieces can either be the\n   * name of a previous `chooseOnBoard`, or a simply provide a piece if it is\n   * not a player choice. The game will also allow a mouse drag for the swap.\n   *\n   * @param piece1 - A {@link Piece} to swap or the name of the piece selection in this action\n   * @param piece2 - A {@link Piece} to swap or the name of the piece selection in this action\n   *\n   * player => action({\n   *   prompt: 'Exchange a card from hand with the top of the deck'\n   * }).chooseOnBoard(\n   *   'card', player.my(Card)\n   * ).swap(\n   *   'card', $.deck.first(Card)!\n   * )\n   * @category Behaviour\n   */\n  swap(piece1: keyof A | Piece<Game>, piece2: keyof A | Piece<Game>) {\n    this.do((args: A) => {\n      const p1 = piece1 instanceof Piece ? piece1 : args[piece1] as Piece<Game>;\n      const p2 = piece2 instanceof Piece ? piece2 : args[piece2] as Piece<Game>;\n      const parent1 = p1._t.parent!;\n      const parent2 = p2._t.parent!;\n      const pos1 = p1.position();\n      const pos2 = p2.position();\n      const row1 = p1.row;\n      const column1 = p1.column;\n      const row2 = p2.row;\n      const column2 = p2.column;\n      p1.putInto(parent2, { position: pos2, row: row2, column: column2 });\n      p2.putInto(parent1, { position: pos1, row: row1, column: column1 });\n    });\n    const piece1Selection = typeof piece1 === 'string' ? this.selections.find(s => s.name === piece1) : undefined;\n    const piece2Selection = typeof piece2 === 'string' ? this.selections.find(s => s.name === piece2) : undefined;\n    if (piece1Selection && piece1Selection.type !== 'board') throw Error(`Invalid swap: \"${piece1 as string}\" must be the name of a previous chooseOnBoard`);\n    if (piece2Selection && piece2Selection.type !== 'board') throw Error(`Invalid swap: \"${piece2 as string}\" must be the name of a previous chooseOnBoard`);\n    if (piece1Selection) piece1Selection.clientContext = { dragInto: piece2Selection ?? piece2 };\n    return this;\n  }\n\n  /**\n   * Have the player select one of the Pieces in the collection and select a new\n   * position within the collection while keeping everything else in the same\n   * order. The game will also permit a mouse drag for the reorder.\n   *\n   * @param collection - A collection of {@link Piece}s to reorder\n   *\n   * @param options.prompt - Prompt displayed to the user for this reorder\n   * choice.\n   *\n   * player => action({\n   *   prompt: 'Reorder cards in hand'\n   * }).reorder(\n   *   player.my(Card)\n   * )\n   * @category Behaviour\n   */\n  reorder(collection: Piece<Game>[], options?: {\n    prompt?: string | ((args: A) => string),\n  }) {\n    const { prompt } = options || {};\n    if (this.selections.some(s => s.name === '__reorder_from__')) throw Error(`Invalid reorder: only one reorder allowed`);\n    if (collection.some(c => c._t.parent !== collection[0]._t.parent)) throw Error(`Invalid reorder: all elements must belong to the same parent`);\n    const pieceSelection = this._addSelection(new Selection(\n      '__reorder_from__', { prompt, selectOnBoard: { chooseFrom: collection }}\n    ));\n    const intoSelection = this._addSelection(new Selection(\n      '__reorder_to__', { prompt, selectOnBoard: { chooseFrom: ({ __reorder_from__ }) => collection.filter(e => e !== __reorder_from__) }}\n    ));\n    pieceSelection.clientContext = { dragInto: intoSelection };\n    intoSelection.clientContext = { dragFrom: pieceSelection };\n    this.do((args: A) => {\n      const reorderFrom = args['__reorder_from__'] as Piece<Game>;\n      const reorderTo = args['__reorder_to__'] as Piece<Game>;\n      let position = reorderTo.position();\n      reorderFrom.putInto(reorderFrom._t.parent!, { position });\n    });\n    return this as unknown as Action<A & {__reorder_to__: Piece<Game>, __reorder_from__: number}>;\n  }\n\n  /**\n   * Add a placement selection to this action. This will be presented as a piece\n   * that players can move into the desired location, snapping to the grid of\n   * the destination as the player moves.\n   *\n   * @param piece - The name of the piece selection in this action from a\n   * `chooseOnBoard` prior to this\n   * @param into - A {@link GameElement} to move into\n   *\n   * @param options.prompt - Prompt displayed to the user for this placement\n   * choice.\n   *\n   * @param options.validate - A function that takes an object of key-value\n   * pairs for all player choices and returns a boolean. The position selected\n   * during the piece placement can be checked by reading the 'column', 'row'\n   * and `rotation` properties of the `piece` as provided in the first\n   * argument. If false, the game will not allow the player to submit these\n   * choices. If a string is returned, this will display as the reason for\n   * disallowing these selections.\n   *\n   * @param options.confirm - A confirmation message that the player will always\n   * see before commiting this choice. This can be useful to present additional\n   * information about the consequences of this choice, or simply to force the\n   * player to hit a button with a clear message. This can be a simple string,\n   * or a 2-celled array in the same form as {@link message} with a string\n   * message and a set of key-value pairs for string interpolation, optionally\n   * being a function that takes an object of key-value pairs for all player\n   * choices, and returns the interpolation object.\n   *\n   * @param options.rotationChoices = An array of valid rotations in\n   * degrees. These choices must be normalized to numbers between 0-359°. If\n   * supplied the piece will be given rotation handles for the player to set the\n   * rotation and position together.\n   *\n   * player => action({\n   *   prompt: 'Place your tile'\n   * }).chooseOnBoard(\n   *   'tile', player.my(Tile)\n   * ).placePiece(\n   *   'tile', $.map, {\n   *     confirm: ({ tile }) => [\n   *       'Place tile into row {{row}} and column {{column}}?',\n   *       tile\n   *     ]\n   * })\n   * @category Choices\n   */\n  placePiece<T extends keyof A & string>(piece: T, into: PieceGrid<Game>, options?: {\n    prompt?: string | ((args: A) => string),\n    confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in T]: { column: number, row: number }}) => Record<string, Argument>) | undefined]\n    validate?: ((args: A & {[key in T]: { column: number, row: number }}) => string | boolean | undefined),\n    rotationChoices?: number[],\n  }) {\n    const { prompt, confirm, validate } = options || {};\n    if (this.selections.some(s => s.name === '__placement__')) throw Error(`Invalid placePiece: only one placePiece allowed`);\n    const pieceSelection = this.selections.find(s => s.name === piece);\n    if (!pieceSelection) throw (`No selection named ${String(piece)} for placePiece`)\n    const positionSelection = this._addSelection(new Selection(\n      '__placement__', { prompt, confirm, validation: validate, selectPlaceOnBoard: {piece, rotationChoices: options?.rotationChoices} }\n    ));\n    positionSelection.clientContext = { placement: { piece, into } };\n    this.do((args: A & {__placement__: number[]}) => {\n      const selectedPiece = args[piece];\n      if (!(selectedPiece instanceof Piece)) throw Error(`Cannot place piece selection named ${String(piece)}. Returned ${selectedPiece} instead of a piece`);\n      selectedPiece.putInto(into, { column: args['__placement__'][0], row: args['__placement__'][1] });\n      selectedPiece.rotation = args['__placement__'][2];\n    });\n    if (pieceSelection) pieceSelection.clientContext = { dragInto: into };\n    return this as unknown as Action<A & {__placement__: number[]} & {[key in T]: { column: number, row: number }}>;\n  }\n}\n"
  },
  {
    "path": "src/action/index.ts",
    "content": "export {default as Action} from './action.js';\nexport {default as Selection} from './selection.js';\n\nexport type { Argument, ActionStub } from './action.js';\n\nexport {\n  serializeArg,\n  deserializeArg\n} from './utils.js';\n"
  },
  {
    "path": "src/action/selection.ts",
    "content": "import { range } from '../utils.js';\nimport { combinations } from './utils.js';\nimport GameElement from '../board/element.js';\nimport Player from '../player/player.js';\n\nimport type { SingleArgument, Argument } from './action.js';\n\nexport type BoardQuerySingle<T extends GameElement, A extends Record<string, Argument> = Record<string, Argument>> = T | undefined | ((args: A) => T | undefined)\nexport type BoardQueryMulti<T extends GameElement, A extends Record<string, Argument> = Record<string, Argument>> = T[] | ((args: A) => T[])\nexport type BoardQuery<T extends GameElement, A extends Record<string, Argument> = Record<string, Argument>> = BoardQuerySingle<T, A> | BoardQueryMulti<T, A>\n\nexport type BoardSelection<T extends GameElement, A extends Record<string, Argument> = Record<string, Argument>> = {\n  chooseFrom: BoardQueryMulti<T, A>;\n  min?: number | ((args: A) => number);\n  max?: number | ((args: A) => number);\n  number?: number | ((args: A) => number);\n  initial?: T[] | ((args: A) => T[]);\n}\n\nexport type ChoiceSelection<A extends Record<string, Argument> = Record<string, Argument>> = {\n  choices: SingleArgument[] | { label: string, choice: SingleArgument }[] | ((args: A) => SingleArgument[] | { label: string, choice: SingleArgument }[]);\n  initial?: Argument | ((args: A) => Argument);\n  // min?: number | ((args: A) => number);\n  // max?: number | ((args: A) => number);\n  // number?: number | ((args: A) => number);\n}\n\nexport type NumberSelection<A extends Record<string, Argument> = Record<string, Argument>> = {\n  min?: number | ((args: A) => number);\n  max?: number | ((args: A) => number);\n  initial?: number | ((args: A) => number);\n}\n\nexport type TextSelection<A extends Record<string, Argument> = Record<string, Argument>> = {\n  regexp?: RegExp;\n  initial?: string | ((args: A) => string);\n}\n\nexport type ButtonSelection = Argument;\n\nexport type SelectionDefinition<A extends Record<string, Argument> = Record<string, Argument>> = {\n  prompt?: string | ((args: A) => string);\n  confirm?: string | [string, Record<string, Argument> | ((args: A) => Record<string, Argument>) | undefined]\n  validation?: ((args: A) => string | boolean | undefined);\n  clientContext?: Record<any, any>; // additional meta info that describes the context for this selection\n} & ({\n  skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);\n  selectOnBoard: BoardSelection<GameElement>;\n  selectPlaceOnBoard?: never;\n  selectFromChoices?: never;\n  selectNumber?: never;\n  enterText?: never;\n  value?: never;\n} | {\n  skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);\n  selectOnBoard?: never;\n  selectPlaceOnBoard?: never;\n  selectFromChoices: ChoiceSelection;\n  selectNumber?: never;\n  enterText?: never;\n  value?: never;\n} | {\n  skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);\n  selectOnBoard?: never;\n  selectPlaceOnBoard?: never;\n  selectFromChoices?: never;\n  selectNumber: NumberSelection;\n  enterText?: never;\n  value?: never;\n} | {\n  selectOnBoard?: never;\n  selectPlaceOnBoard?: never;\n  selectFromChoices?: never;\n  selectNumber?: never;\n  enterText: TextSelection;\n  value?: never;\n} | {\n  selectOnBoard?: never;\n  selectPlaceOnBoard?: never;\n  selectFromChoices?: never;\n  selectNumber?: never;\n  enterText?: never;\n  value: ButtonSelection;\n} | {\n  selectOnBoard?: never;\n  selectPlaceOnBoard: {piece: string, rotationChoices?: number[]};\n  selectFromChoices?: never;\n  selectNumber?: never;\n  enterText?: never;\n  value?: never;\n});\n\n// any lambdas have been resolved to actual values\nexport type ResolvedSelection = Omit<Selection, 'prompt' | 'min' | 'max' | 'initial' | 'skipIf'> & {\n  prompt?: string;\n  resolvedChoices?: { label?: string, choice: SingleArgument, error?: string }[]; // selection.choices or selection.boardChoices resolve to this array\n  min?: number;\n  max?: number;\n  initial?: Argument;\n  skipIf?: 'never' | 'always' | 'only-one' | boolean;\n}\n\n/**\n * Selection objects represent player choices. They either specify the options\n * or provide enough information for the client to contextually show options to\n * players at runtime\n * @internal\n */\nexport default class Selection {\n  type: 'board' | 'choices' | 'text' | 'number' | 'button' | 'place';\n  name: string;\n  prompt?: string | ((args: Record<string, Argument>) => string);\n  confirm?: [string, Record<string, Argument> | ((args: Record<string, Argument>) => Record<string, Argument>) | undefined]\n  validation?: ((args: Record<string, Argument>) => string | boolean | undefined);\n  clientContext: Record<any, any> = {}; // additional meta info that describes the context for this selection\n  skipIf?: 'never' | 'always' | 'only-one' | ((args: Record<string, Argument>) => boolean);\n  choices?: SingleArgument[] | { label: string, choice: SingleArgument }[] | ((args: Record<string, Argument>) => SingleArgument[] | { label: string, choice: SingleArgument }[]);\n  boardChoices?: BoardQueryMulti<GameElement>\n  min?: number | ((args: Record<string, Argument>) => number);\n  max?: number | ((args: Record<string, Argument>) => number);\n  initial?: Argument | ((args: Record<string, Argument>) => Argument);\n  regexp?: RegExp;\n  placePiece?: string;\n  rotationChoices?: number[];\n  value?: Argument;\n\n  constructor(name: string, s: SelectionDefinition | Selection) {\n    this.name = name;\n    if (s instanceof Selection) {\n      Object.assign(this, s);\n    } else {\n      if (s.selectFromChoices) {\n        this.type = 'choices';\n        this.choices = s.selectFromChoices.choices;\n        //this.min = s.selectFromChoices.min;\n        //this.max = s.selectFromChoices.max;\n        this.initial = s.selectFromChoices.initial;\n      } else if (s.selectOnBoard) {\n        this.type = 'board';\n        this.boardChoices = s.selectOnBoard.chooseFrom;\n        if (s.selectOnBoard.number !== undefined) {\n          this.min = s.selectOnBoard.number;\n          this.max = s.selectOnBoard.number;\n        }\n        this.min ??= s.selectOnBoard.min;\n        this.max ??= s.selectOnBoard.max;\n        this.initial ??= s.selectOnBoard.initial;\n      } else if (s.selectNumber) {\n        this.type = 'number';\n        this.min = s.selectNumber.min;\n        this.max = s.selectNumber.max;\n        this.initial = s.selectNumber.initial ?? s.selectNumber.min ?? 1;\n      } else if (s.enterText) {\n        this.type = 'text';\n        this.regexp = s.enterText.regexp;\n        this.initial = s.enterText.initial;\n      } else if (s.selectPlaceOnBoard) {\n        this.type = 'place';\n        this.placePiece = s.selectPlaceOnBoard.piece;\n        this.rotationChoices = s.selectPlaceOnBoard.rotationChoices;\n      } else {\n        this.type = 'button';\n        this.value = s.value;\n        this.skipIf ??= 'only-one';\n      }\n    }\n    this.prompt = s.prompt;\n    this.confirm = typeof s.confirm === 'string' ? [s.confirm, undefined] : s.confirm;\n    this.validation = s.validation;\n    this.skipIf = ('skipIf' in s && s.skipIf) || 'only-one';\n    this.clientContext = s.clientContext ?? {};\n  }\n\n  /**\n   * check specific selection with a given arg. evaluates within the context of\n   * previous args, so any selection elements that have previous-arg-function\n   * forms are here evaluated with the previous args. returns new selection and\n   * error if any\n   */\n  error(args: Record<string, Argument>): string | undefined {\n    const arg = args[this.name];\n    const s = this.resolve(args);\n\n    if (s.validation) {\n      const error = s.validation(args);\n      if (error !== undefined && error !== true) return error || 'Invalid selection';\n    }\n\n    if (s.type === 'choices' && s.resolvedChoices) {\n      if (arg instanceof Array) return \"multi-choice stil unsupported\"; // TODO\n      return s.resolvedChoices.find(c => c.choice === arg) ? undefined : \"Not a valid choice\";\n    }\n\n    if (s.type === 'board' && s.resolvedChoices) {\n      const results = s.resolvedChoices.map(c => c.choice);\n      if (!results) console.warn('Attempted to validate an impossible move', s);\n      if (this.isMulti()) {\n        if (!(arg instanceof Array)) throw Error(\"Required multi select\");\n        if (results && arg.some(a => !results.includes(a as GameElement))) return \"Selected elements are not valid\";\n        if (s.min !== undefined && arg.length < s.min) return \"Below minimum\";\n        if (s.max !== undefined && arg.length > s.max) return \"Above maximum\";\n      } else {\n        return (results && results.includes(arg as GameElement)) ? undefined : \"Selected element is not valid\";\n      }\n    }\n\n    if (s.type === 'text') {\n      return (typeof arg === 'string' && (!s.regexp || arg.match(s.regexp))) ? undefined : \"Invalid text entered\";\n    }\n\n    if (s.type === 'number') {\n      if (typeof arg !== 'number') return \"Not a number\";\n      if (s.min !== undefined && arg < s.min) return \"Below minimum\";\n      if (s.max !== undefined && arg > s.max) return \"Above maximum\";\n      return undefined;\n    }\n\n    return undefined;\n  }\n\n  // All possible valid Arguments to this selection. Have to make some assumptions here to tree shake possible moves\n  // Argument to handle array of combo selections arrays\n  options(this: ResolvedSelection): {choice: Argument, error?: string, label?: string}[] {\n    if (this.isUnbounded()) return [];\n    if (this.type === 'number') return range(this.min ?? 1, this.max!).map(choice => ({ choice }));\n    if (this.isMulti() && this.resolvedChoices) {\n      return combinations(this.resolvedChoices.map(c => c.choice), this.min ?? 1, this.max ?? Infinity).map(choice => ({ choice }));\n    }\n    if (this.resolvedChoices) return this.resolvedChoices;\n    return [];\n  }\n\n  isUnbounded(this: ResolvedSelection): boolean {\n    if (this.type === 'number') return this.max === undefined || this.max - (this.min ?? 1) > 100;\n    return this.type === 'text' || this.type === 'button' || this.type === 'place';\n  }\n\n  isResolved(): this is ResolvedSelection {\n    return typeof this.prompt !== 'function' &&\n      typeof this.min !== 'function' &&\n      typeof this.max !== 'function' &&\n      typeof this.initial !== 'function' &&\n      typeof this.skipIf !== 'function' &&\n      typeof this.choices !== 'function' &&\n      typeof this.boardChoices !== 'function' &&\n      (!this.choices && !this.boardChoices || 'resolvedChoices' in this);\n  }\n\n  isMulti() {\n    return (this.type === 'choices' || this.type === 'board') && (this.min !== undefined || this.max !== undefined);\n  }\n\n  isBoardChoice() {\n    return this.type === 'board' || this.type ==='place';\n  }\n\n  resolve(args: Record<string, Argument>): ResolvedSelection {\n    const resolved = new Selection(this.name, this) as ResolvedSelection;\n    if (this.choices) {\n      const choices = typeof this.choices === 'function' ? this.choices(args) : this.choices;\n      if (choices instanceof Array && typeof choices[0] === 'object' && !(choices[0] instanceof GameElement) && !(choices[0] instanceof Player)) {\n        resolved.resolvedChoices = choices as { label: string, choice: SingleArgument }[];\n      } else {\n        resolved.resolvedChoices = (choices as SingleArgument[]).map(choice => ({ choice }));\n      }\n    }\n    if (typeof this.prompt === 'function') resolved.prompt = this.prompt(args);\n    if (typeof this.min === 'function') resolved.min = this.min(args)\n    if (typeof this.max === 'function') resolved.max = this.max(args)\n    if (typeof this.initial === 'function') resolved.initial = this.initial(args)\n    if (typeof this.skipIf === 'function') resolved.skipIf = this.skipIf(args)\n    if (this.boardChoices) {\n      const choices = typeof this.boardChoices === 'function' ? this.boardChoices(args) : this.boardChoices;\n      resolved.resolvedChoices = choices.map(choice => ({ choice }));\n    }\n    return resolved;\n  }\n\n  isPossible(this: ResolvedSelection): boolean {\n    if (this.type === 'choices' && this.resolvedChoices) return this.resolvedChoices.length > 0\n\n    const isInBounds = this.max !== undefined ? (this.min ?? 1) <= this.max : true;\n    if (this.type === 'board' && this.resolvedChoices) return isInBounds && this.resolvedChoices.length >= (this.min ?? 1);\n    if (this.type === 'number') return isInBounds;\n\n    return true;\n  }\n\n  isForced(this: ResolvedSelection): Argument | undefined {\n    if (this.skipIf === 'never') return;\n    if (this.type === 'button') {\n      return this.value;\n    } else if (this.type === 'board') {\n      if (this.resolvedChoices && (this.skipIf === true || this.resolvedChoices?.length === 1) && !this.isMulti()) {\n        return this.resolvedChoices[0].choice;\n      } else if (this.resolvedChoices && this.isMulti() && (this.skipIf === true || (this.resolvedChoices.length === (this.min ?? 1)) || this.max === 0)) {\n        return this.resolvedChoices.slice(0, this.min).map(c => c.choice);\n      }\n    } else if (this.type === 'number' && this.min !== undefined && this.min === this.max) {\n      return this.min;\n    } else if (this.type === 'choices' && this.resolvedChoices) {\n      if (this.resolvedChoices.length === 1 || this.skipIf === true) return this.resolvedChoices[0].choice\n    }\n  }\n\n  toString(): string {\n    if (!this.isResolved()) return `unresolved selection ${this.type}`;\n    return `${this.type === 'board' ? `click ${this.resolvedChoices![0]?.choice.constructor.name || 'board element'}` : `pick ${this.type}`}${(this.choices || this.boardChoices) ? ` (${(this.choices || this.boardChoices)!.length} choices)` : ''}`;\n  }\n}\n"
  },
  {
    "path": "src/action/utils.ts",
    "content": "import type { Argument, SingleArgument } from './action.js';\nimport type { Player } from '../player/index.js';\nimport type { BaseGame } from '../board/game.js';\nimport type GameElement from '../board/element.js';\n\nexport type SerializedSingleArg = string | number | boolean;\nexport type SerializedArg = SerializedSingleArg | SerializedSingleArg[];\nexport type Serializable = SingleArgument | null | undefined | Serializable[] | { [key: string]: Serializable };\n\nexport const serialize = (arg: Serializable, forPlayer=true, name?: string): any => {\n  if (arg === undefined) return undefined;\n  if (arg === null) return null;\n  if (arg instanceof Array) return arg.map(a => serialize(a, forPlayer));\n  if (typeof arg === 'object' && 'constructor' in arg && ('isPlayer' in arg.constructor || 'isGameElement' in arg.constructor)) {\n    return serializeSingleArg(arg as GameElement | Player, forPlayer);\n  }\n  if (typeof arg === 'object') return serializeObject(arg, forPlayer);\n  if (typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'boolean') return serializeSingleArg(arg, forPlayer);\n  throw Error(`Unable to serialize the property ${name ? '\"' + name + '\": ' : ''} ${arg}. Only primitives, Player's, GameElement's or arrays/objects containing such can be used.`);\n}\n\nexport const serializeArg = (arg: Argument, forPlayer=true): SerializedArg => {\n  if (arg instanceof Array) return arg.map(a => serializeSingleArg(a, forPlayer));\n  return serializeSingleArg(arg, forPlayer);\n}\n\nexport const serializeSingleArg = (arg: SingleArgument, forPlayer=true): SerializedSingleArg => {\n  if (typeof arg === 'object' && 'constructor' in arg) {\n    if ('isPlayer' in arg.constructor) return `$p[${(arg as Player).position}]`;\n    if ('isGameElement' in arg.constructor) return forPlayer ? `$el[${(arg as GameElement).branch()}]` : `$eid[${(arg as GameElement)._t.id}]`;\n  }\n  return arg as SerializedSingleArg;\n}\n\nexport const serializeObject = (obj: Record<string, any>, forPlayer=true) => {\n  return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, serialize(v, forPlayer, k)]));\n}\n\nexport const escapeArgument = (arg: Argument): string => {\n  if (arg instanceof Array) {\n    const escapees = arg.map(escapeArgument);\n    return escapees.slice(0, -1).join(', ') + (escapees.length > 1 ? ' and ' : '') + (escapees[escapees.length - 1] || '');\n  }\n  if (typeof arg === 'object') return `[[${serializeSingleArg(arg)}|${arg.toString()}]]`;\n  return String(arg);\n}\n\nexport const deserializeArg = (arg: SerializedArg, game: BaseGame): Argument => {\n  if (arg instanceof Array) return arg.map(a => deserializeSingleArg(a, game)) as GameElement[];\n  return deserializeSingleArg(arg, game);\n}\n\nexport const deserializeSingleArg = (arg: SerializedSingleArg, game: BaseGame): SingleArgument => {\n  if (typeof arg === 'number' || typeof arg === 'boolean') return arg;\n  let deser: SingleArgument | undefined;\n  if (arg.slice(0, 3) === '$p[') {\n    deser = game.players.atPosition(parseInt(arg.slice(3, -1)));\n  } else if (arg.slice(0, 4) === '$el[') {\n    deser = game.atBranch(arg.slice(4, -1));\n  } else if (arg.slice(0, 5) === '$eid[') {\n    deser = game.atID(parseInt(arg.slice(5, -1)));\n  } else {\n    return arg;\n  }\n  if (!deser) throw Error(`Unable to find arg: ${arg}`);\n  return deser;\n}\n\nexport const deserializeObject = (obj: Record<string, any>, game: BaseGame) => {\n  return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, deserialize(v, game)]));\n}\n\nexport const deserialize = (arg: any, game: BaseGame): Serializable => {\n  if (arg === undefined) return undefined;\n  if (arg === null) return null;\n  if (arg instanceof Array) return arg.map(a => deserialize(a, game));\n  if (typeof arg === 'object') return deserializeObject(arg, game);\n  if (typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'boolean') return deserializeSingleArg(arg, game);\n  throw Error(`unable to deserialize ${arg}`);\n}\n\nexport const combinations = <T>(set: T[], min: number, max: number): T[][] => {\n  const combos = [] as T[][];\n  const poss = (curr: T[], i: number) => {\n    if (set.length - i < min - curr.length) return;\n    if (curr.length >= min) combos.push(curr);\n    if (curr.length < max) {\n      for (let j = i; j !== set.length; j++) {\n        poss(curr.concat([set[j]]), j + 1);\n      }\n    }\n  }\n  poss([], 0);\n  return combos;\n}\n"
  },
  {
    "path": "src/board/adjacency-space.ts",
    "content": "import GameElement from './element.js';\n\nimport type { BaseGame } from './game.js';\nimport type { ElementUI, LayoutAttributes } from './element.js';\nimport SingleLayout from './single-layout.js';\n\n/**\n * Abstract base class for all adjacency spaces\n */\nexport default abstract class AdjacencySpace<G extends BaseGame> extends SingleLayout<G> {\n\n  _ui: ElementUI<this> = {\n    layouts: [],\n    appearance: {},\n    getBaseLayout: () => ({\n      sticky: true,\n      alignment: 'center',\n      direction: 'square'\n    })\n  };\n\n  isAdjacent(_el1: GameElement, _el2: GameElement): boolean {\n    throw Error(\"Abstract AdjacencySpace has no implementation\");\n  }\n\n  _positionOf(element: GameElement) {\n    const positionedParent = this._positionedParentOf(element);\n    return {column: positionedParent.column, row: positionedParent.row};\n  }\n\n  _positionedParentOf(element: GameElement): GameElement {\n    if (!element._t.parent) throw Error(`Element not found within adjacency space \"${this.name}\"`);\n    return element._t.parent === this ? element : this._positionedParentOf(element._t.parent);\n  }\n\n  /**\n   * Change the layout attributes for this space's layout.\n   * @category UI\n   */\n  configureLayout(layoutConfiguration: Partial<LayoutAttributes>) {\n    const keys = Object.keys(layoutConfiguration);\n    if (keys.includes('scaling') || keys.includes('alignment')) {\n      throw Error(\"Layouts for grids cannot have alignment, scaling\");\n    }\n    super.configureLayout(layoutConfiguration);\n  }\n}\n"
  },
  {
    "path": "src/board/connected-space-map.ts",
    "content": "import AdjacencySpace from './adjacency-space.js';\nimport graphology, { DirectedGraph } from 'graphology';\nimport { dijkstra, edgePathFromNodePath } from 'graphology-shortest-path';\nimport Piece from './piece.js';\nimport GameElement from './element.js';\nimport { bfsFromNode } from 'graphology-traversal';\nimport ElementCollection from './element-collection.js';\n\nimport type { BaseGame } from './game.js';\nimport type Space from './space.js';\nimport type { ElementContext, ElementClass } from './element.js';\nimport type { ElementFinder } from './element-collection.js';\n\n/**\n * Space element that has child Space elements with an adjacency relationship\n * with each other. Only Spaces can be directly added to an AdjacencySpace. No\n * adjacency is automically created with this class. Instead, each space\n * adjacency is created manually with {@link ConnectedSpaceMap#connect}. This is\n * useful for arbitrary adjacencies. See also {@link SquareGrid}, {@link\n * HexGrid} for standard adjacency layouts.\n * @category Board\n */\nexport default class ConnectedSpaceMap<G extends BaseGame> extends AdjacencySpace<G> {\n  _graph: DirectedGraph;\n\n  static unserializableAttributes = [...AdjacencySpace.unserializableAttributes, '_graph'];\n\n  constructor(ctx: ElementContext) {\n    super(ctx);\n    this._graph = new graphology.DirectedGraph<{space: Space<G>}, {distance: number}>();\n    this.onEnter(Piece, () => { throw Error(`Only spaces can be added to space ${this.name}`); });\n  }\n\n  /**\n   * Returns whether 2 elements contained within this space have an adjacency to\n   * each other. The elements are considered adjacent if they are child Spaces\n   * that have been connected, or if the provided elements are placed inside\n   * such connected Spaces.\n   * @category Adjacency\n   */\n  isAdjacent(el1: GameElement, el2: GameElement) {\n    const n1 = this._positionedParentOf(el1);\n    const n2 = this._positionedParentOf(el2);\n    return this._graph.areNeighbors(n1._t.ref, n2._t.ref);\n  }\n\n  /**\n   * Make these two Spaces adjacent. This creates a two-way adjacency\n   * relationship. If called twice with the Spaces reversed, different distances\n   * can be created for the adjacency in each direction.\n   * @category Adjacency\n   *\n   * @param space1 - {@link Space} to connect\n   * @param space2 - {@link Space} to connect\n   * @param distance - Add a custom distance to this connection for the purposes\n   * of distance-measuring. This distance is when measuring from space1 to space2.\n   */\n  connect(space1: Space<G>, space2: Space<G>, distance: number = 1) {\n    this.connectOneWay(space1, space2, distance);\n    // assume bidirectional unless directly called in reverse\n    if (!this._graph.hasDirectedEdge(space2._t.ref, space1._t.ref)) this._graph.addDirectedEdge(space2._t.ref, space1._t.ref, {distance});\n  }\n\n  // @internal\n  connectOneWay(space1: Space<G>, space2: Space<G>, distance: number = 1) {\n    if (this !== space1._t.parent || this !== space2._t.parent) throw Error(\"Both spaces must be children of the space to be connected\");\n\n    if (!this._graph.hasNode(space1._t.ref)) this._graph.addNode(space1._t.ref, {space: space1});\n    if (!this._graph.hasNode(space2._t.ref)) this._graph.addNode(space2._t.ref, {space: space2});\n\n    this._graph.mergeEdge(space1._t.ref, space2._t.ref, {distance});\n  }\n\n  /**\n   * Finds the shortest distance between two elements using this space. Elements\n   * must be connected Spaces of this element or be elements inside such spaces.\n   * @category Adjacency\n   *\n   * @param el1 - {@link GameElement} to measure distance from\n   * @param el2 - {@link GameElement} to measure distance to\n   * @returns shortest distance measured by the `distance` values added to each\n   * connection in {@link connectTo}\n   */\n  distanceBetween(el1: GameElement, el2: GameElement) {\n    const n1 = this._positionedParentOf(el1);\n    const n2 = this._positionedParentOf(el2);\n    return this._distanceBetweenNodes(String(n1._t.ref), String(n2._t.ref));\n  }\n\n  _distanceBetweenNodes(n1: string, n2: string): number {\n    try {\n      const path = dijkstra.bidirectional(this._graph, n1, n2, 'distance');\n      const edgePath = edgePathFromNodePath(this._graph, path);\n      return edgePath.reduce((distance, edge) => distance + this._graph.getEdgeAttribute(edge, 'distance'), 0);\n    } catch(e) {\n      return Infinity;\n    }\n  }\n\n  /**\n   * Finds all elements of the query type given that are adjacent to the\n   * provided element, searching recursively through the adjacent Spaces. Uses\n   * the same query parameters as {@link all}.\n   * @category Adjacency\n   *\n   * @param element - {@link GameElement} to measure distance from\n   * @param {class} className - Optionally provide a class as the first argument\n   * as a class filter. This will only match elements which are instances of the\n   * provided class\n   * @param finders - All other parameters are filters. See {@link\n   * ElementFinder} for more information.\n   */\n  allAdjacentTo<F extends GameElement>(element: GameElement, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  allAdjacentTo(element: GameElement, className?: ElementFinder<GameElement>, ...finders: ElementFinder<GameElement>[]): ElementCollection;\n  allAdjacentTo(element: GameElement, className?: any, ...finders: ElementFinder[]) {\n    const source = this._positionedParentOf(element);\n    return this._t.children.filter(c => this.isAdjacent(source, c)).all(className, ...finders);\n  }\n\n  /**\n   * Finds all elements of the query type given that are within the provided\n   * distance from the provided element, searching recursively through the\n   * connected Spaces. This does *not* include the supplied element. Uses the\n   * same query parameters as {@link all}.\n   * @category Adjacency\n   *\n   * @param element - {@link GameElement} to measure distance from\n   * @param distance - Distance to measure using the adjacency distances\n   * @param {class} className - Optionally provide a class as the first argument\n   * as a class filter. This will only match elements which are instances of the\n   * provided class\n   * @param finders - All other parameters are filters. See {@link\n   * ElementFinder} for more information.\n   */\n  allWithinDistanceOf<F extends GameElement>(element: GameElement, distance: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  allWithinDistanceOf(element: GameElement, distance: number, className?: ElementFinder<GameElement>, ...finders: ElementFinder<GameElement>[]): ElementCollection;\n  allWithinDistanceOf(element: GameElement, distance: number, className?: any, ...finders: ElementFinder[]) {\n    const source = String(this._positionedParentOf(element)._t.ref);\n    const nodes = new ElementCollection();\n    bfsFromNode(this._graph, source, target => {\n      const d = this._distanceBetweenNodes(source, target);\n      if (d > distance) return true;\n      nodes.push(this._graph.getNodeAttributes(target).space);\n    });\n    return nodes.all(className, (el: GameElement) => el !== element, ...finders);\n  }\n\n  /**\n   * Finds all elements of the query type that are connected to the provided\n   * element by any path, searching recursively through the connected\n   * spaces. This includes the supplied element. This is useful for determining\n   * the size of a contiguous connected area. Uses the same query parameters as\n   * {@link all}.\n   * @category Adjacency\n   *\n   * @param element - {@link GameElement} to measure distance from\n   * @param {class} className - Optionally provide a class as the first argument\n   * as a class filter. This will only match elements which are instances of the\n   * provided class\n   * @param finders - All other parameters are filters. See {@link\n   * ElementFinder} for more information.\n   */\n  allConnectedTo<F extends GameElement>(element: GameElement, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  allConnectedTo(element: GameElement, className?: ElementFinder<GameElement>, ...finders: ElementFinder<GameElement>[]): ElementCollection;\n  allConnectedTo(element: GameElement, className?: any, ...finders: ElementFinder[]) {\n    const source = String(this._positionedParentOf(element)._t.ref);\n    const nodes = new ElementCollection();\n    bfsFromNode(this._graph, source, target => {\n      nodes.push(this._graph.getNodeAttributes(target).space);\n    });\n    return nodes.all(className, ...finders);\n  }\n\n  /**\n   * Finds the nearest element of the query type given to the provided element,\n   * searching recursively through the connected Spaces.\n   * @category Adjacency\n   *\n   * @param element - {@link GameElement} to measure distance from\n   * @param {class} className - Optionally provide a class as the first argument\n   * as a class filter. This will only match elements which are instances of the\n   * provided class\n   * @param finders - All other parameters are filters. See {@link\n   * ElementFinder} for more information.\n   */\n  closestTo<F extends GameElement>(element: GameElement, className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  closestTo(element: GameElement, className?: ElementFinder<GameElement>, ...finders: ElementFinder<GameElement>[]): GameElement | undefined;\n  closestTo<F extends GameElement>(element: GameElement, className?: any, ...finders: ElementFinder[]): F | GameElement | undefined {\n    const source = this._positionedParentOf(element);\n    let collection: ElementCollection;\n    collection = this._t.children.all(className, (el: GameElement) => el !== element, ...finders);\n    return collection.sortBy(el => this.distanceBetween(source, el))[0];\n  }\n}\n"
  },
  {
    "path": "src/board/element-collection.ts",
    "content": "import type {\n  ElementClass,\n  ElementUI,\n  ElementAttributes,\n} from './element.js';\nimport type Piece from './piece.js';\nimport type Game from './game.js';\nimport type { GameElement } from './index.js'\n\n/**\n * Either the name of a property of the object that can be lexically sorted, or\n * a function that will be called with the object to sort and must return a\n * lexically sortable value.\n * @category Board\n */\nexport type Sorter<T> = keyof T | ((e: T) => number | string)\n\nimport type { Player } from '../player/index.js';\nimport { BaseGame } from './game.js';\n\n/**\n * A query filter can be one of 3 different forms:\n * - *string*: will match elements with this name\n * - *function*: A function that accept an element as its argument and returns a\n *     boolean indicating whether it is a match, similar to `Array#filter`.\n * - *object*: will match elements whose properties match the provided\n *     properties. For example, `deck.all(Card, {suit: 'H'})` would match all\n *     `Card` elements in `deck` with a `suit` property equal to `\"H\"`. There are\n *     some special property names allowed here:\n *   - *mine*: true/false whether this element belongs to the player in whose context the query is made\n *   - *empty* true/false whether this element is empty\n *   - *adjacent* true/false whether this element is adjacent by a connection to the\n *       element on which the query method was\n *       called. E.g. `france.other(Country, {adjacent: true})` will match\n *       `Country` elements that are connected to `france` by {@link\n *       Space#connectTo}\n *   - *withinDistance* Similar to adjacent but uses the provided number to\n *       determine if a connection is possible between elements whose cost is\n *       not greater than the provided value\n * @category Board\n */\nexport type ElementFinder<T extends GameElement = GameElement> = (\n  ((e: T) => boolean) |\n    (ElementAttributes<T> & {mine?: boolean, owner?: T['player'], empty?: boolean}) |\n    string\n);\n\n/**\n * Operations that return groups of {@link GameElement}'s return\n * this Array-like class.\n * @noInheritDoc\n * @category Board\n */\nexport default class ElementCollection<T extends GameElement = GameElement> extends Array<T> {\n\n  slice(...a: Parameters<Array<T>['slice']>):ElementCollection<T> {return super.slice(...a) as ElementCollection<T>}\n  filter(...a: Parameters<Array<T>['filter']>):ElementCollection<T> {return super.filter(...a) as ElementCollection<T>}\n\n  /**\n   * As {@link GameElement#all}, but finds all elements within this collection\n   * and its contained elements recursively.\n   * @category Queries\n   *\n   * @param {class} className - Optionally provide a class as the first argument\n   * as a class filter. This will only match elements which are instances of the\n   * provided class\n   *\n   * @param finders - All other parameters are filters. See {@link\n   * ElementFinder} for more information.\n   *\n   * @returns An {@link ElementCollection} of as many matching elements as can be\n   * found. The collection is typed to `ElementCollection<className>` if one was\n   * provided.\n   */\n  all<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  all(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;\n  all(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return this._finder(undefined, {}, ...finders);\n    }\n    return this._finder(className, {}, ...finders);\n  }\n\n  _finder<F extends GameElement>(\n    className: ElementClass<F> | undefined,\n    options: {limit?: number, order?: 'asc' | 'desc', noRecursive?: boolean},\n    ...finders: ElementFinder<F>[]\n  ): ElementCollection<F> {\n    const coll = new ElementCollection<F>();\n    if (options.limit !== undefined && options.limit <= 0) return coll;\n\n    const fns: ((e: F) => boolean)[] = finders.map(finder => {\n      if (typeof finder === 'object') {\n        const attrs = finder;\n        return el => Object.entries(attrs).every(([k1, v1]) => (\n          (k1 === 'empty' ? el.isEmpty() : el[k1 as keyof typeof el]) === v1\n        ))\n      }\n      if (typeof finder === 'string') {\n        const name = finder;\n        return el => el.name === name;\n      }\n      return finder;\n    })\n\n    const finderFn = (el: T, order: 'asc' | 'desc') => {\n      if ((!className || el instanceof className) && fns.every(fn => fn(el as unknown as F))) {\n        if (order === 'asc') {\n          coll.push(el as unknown as F);\n        } else {\n          coll.unshift(el as unknown as F);\n        }\n      }\n      if (!options.noRecursive) {\n        if (options.limit !== undefined) {\n          coll.push(...el._t.children._finder(className, {limit: options.limit - coll.length, order: options.order}, ...finders));\n        } else {\n          coll.push(...el._t.children._finder(className, {}, ...finders));\n        }\n      }\n    };\n\n    if (options.order === 'desc') {\n      for (let e = this.length - 1; e >= 0; e--) {\n        const el = this[e];\n        if (options.limit !== undefined && coll.length >= options.limit) break;\n        finderFn(el, 'desc');\n      }\n    } else {\n      for (const el of this) {\n        if (options.limit !== undefined && coll.length >= options.limit) break;\n        finderFn(el, 'asc');\n      }\n    }\n\n    return coll;\n  }\n\n  /**\n   * As {@link GameElement#first}, except finds the first element within this\n   * collection and its contained elements recursively that matches the\n   * arguments provided. See {@link GameElement#all} for parameter details.\n   * @category Queries\n   * @returns A matching element, if found\n   */\n  first<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  first(className?: ElementFinder, ...finders: ElementFinder[]): T | undefined;\n  first(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): GameElement | undefined {\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return this._finder(undefined, {limit: 1}, ...finders)[0];\n    }\n    return this._finder(className, {limit: 1}, ...finders)[0];\n  }\n\n  /**\n   * As {@link GameElement#firstn}, except finds the first `n` elements within\n   * this collection and its contained elements recursively that match the\n   * arguments provided. See {@link all} for parameter details.\n   * @category Queries\n   * @param n - number of matches\n   *\n   * @returns An {@link ElementCollection} of as many matching elements as can be\n   * found, up to `n`. The collection is typed to `ElementCollection<className>`\n   * if one was provided.\n   */\n  firstN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  firstN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;\n  firstN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {\n    if (typeof n !== 'number') throw Error('first argument must be number of matches');\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return this._finder<GameElement>(undefined, {limit: n}, ...finders);\n    }\n    return this._finder(className, {limit: n}, ...finders);\n  }\n\n  /**\n   * As {@link GameElement#last}, expect finds the last element within this\n   * collection and its contained elements recursively that matches the\n   * arguments provided. See {@link all} for parameter details.\n   * @category Queries\n   * @returns A matching element, if found\n   */\n  last<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  last(className?: ElementFinder, ...finders: ElementFinder[]): T | undefined;\n  last(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): GameElement | undefined {\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return this._finder<GameElement>(undefined, {limit: 1, order: 'desc'}, ...finders)[0];\n    }\n    return this._finder(className, {limit: 1, order: 'desc'}, ...finders)[0];\n  }\n\n  /**\n   * As {@link GameElement#lastn}, expect finds the last n elements within this\n   * collection and its contained elements recursively that match the arguments\n   * provided. See {@link all} for parameter details.\n   * @category Queries\n   * @param n - number of matches\n   *\n   * @returns An {@link ElementCollection} of as many matching elements as can be\n   * found, up to `n`. The collection is typed to `ElementCollection<className>`\n   * if one was provided.\n   */\n  lastN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  lastN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;\n  lastN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {\n    if (typeof n !== 'number') throw Error('first argument must be number of matches');\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return this._finder<GameElement>(undefined, {limit: n, order: 'desc'}, ...finders);\n    }\n    return this._finder(className, {limit: n, order: 'desc'}, ...finders);\n  }\n\n  /**\n   * Alias for {@link first}\n   * @category Queries\n   */\n  top<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  top(className?: ElementFinder, ...finders: ElementFinder[]): T | undefined;\n  top(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): GameElement | undefined {\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return this._finder<GameElement>(undefined, {limit: 1}, ...finders)[0];\n    }\n    return this._finder(className, {limit: 1}, ...finders)[0];\n  }\n\n  /**\n   * Alias for {@link firstN}\n   * @category Queries\n   */\n  topN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  topN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;\n  topN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {\n    if (typeof n !== 'number') throw Error('first argument must be number of matches');\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return this._finder<GameElement>(undefined, {limit: n}, ...finders);\n    }\n    return this._finder(className, {limit: n}, ...finders);\n  }\n\n  /**\n   * Alias for {@link last}\n   * @category Queries\n   */\n  bottom<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  bottom(className?: ElementFinder, ...finders: ElementFinder[]): T | undefined;\n  bottom(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): GameElement<any> | undefined {\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return this._finder<GameElement>(undefined, {limit: 1, order: 'desc'}, ...finders)[0];\n    }\n    return this._finder(className, {limit: 1, order: 'desc'}, ...finders)[0];\n  }\n\n  /**\n   * Alias for {@link lastN}\n   * @category Queries\n   */\n  bottomN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  bottomN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;\n  bottomN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {\n    if (typeof n !== 'number') throw Error('first argument must be number of matches');\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return this._finder<GameElement>(undefined, {limit: n, order: 'desc'}, ...finders);\n    }\n    return this._finder(className, {limit: n, order: 'desc'}, ...finders);\n  }\n\n  /**\n   * Show these elements to all players\n   * @category Visibility\n   */\n  showToAll(this: ElementCollection<Piece<BaseGame>>) {\n    for (const el of this) {\n      delete(el._visible);\n    }\n  }\n\n  /**\n   * Show these elements only to the given player\n   * @category Visibility\n   */\n  showOnlyTo(this: ElementCollection<Piece<BaseGame>>, player: Player | number) {\n    if (typeof player !== 'number') player = player.position;\n    for (const el of this) {\n      el._visible = {\n        default: false,\n        except: [player]\n      };\n    }\n  }\n\n  /**\n   * Show these elements to the given players without changing it's visibility to\n   * any other players.\n   * @category Visibility\n   */\n  showTo(this: ElementCollection<Piece<BaseGame>>, ...player: Player[] | number[]) {\n    if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position);\n    for (const el of this) {\n      if (el._visible === undefined) continue;\n      if (el._visible.default) {\n        if (!el._visible.except) continue;\n        el._visible.except = el._visible.except.filter(i => !(player as number[]).includes(i));\n      } else {\n        el._visible.except = Array.from(new Set([...(el._visible.except instanceof Array ? el._visible.except : []), ...(player as number[])]))\n      }\n    }\n  }\n\n  /**\n   * Hide this element from all players\n   * @category Visibility\n   */\n  hideFromAll(this: ElementCollection<Piece<BaseGame>>) {\n    for (const el of this) {\n      el._visible = {default: false};\n    }\n  }\n\n  /**\n   * Hide these elements from the given players without changing it's visibility to\n   * any other players.\n   * @category Visibility\n   */\n  hideFrom(this: ElementCollection<Piece<BaseGame>>, ...player: Player[] | number[]) {\n    if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position);\n    for (const el of this) {\n      if (el._visible?.default === false && !el._visible.except) continue;\n      if (el._visible === undefined || el._visible.default === true) {\n        el._visible = {\n          default: true,\n          except: Array.from(new Set([...(el._visible?.except instanceof Array ? el._visible.except : []), ...(player as number[])]))\n        };\n      } else {\n        if (!el._visible.except) continue;\n        el._visible.except = el._visible.except.filter(i => !(player as number[]).includes(i));\n      }\n    }\n  }\n\n  /**\n   * Sorts this collection by some {@link Sorter}.\n   * @category Structure\n   */\n  sortBy<E extends T>(key: Sorter<E> | Sorter<E>[], direction?: \"asc\" | \"desc\") {\n    const rank = (e: E, k: Sorter<E>) => typeof k === 'function' ? k(e) : e[k as keyof E]\n    const [up, down] = direction === 'desc' ? [-1, 1] : [1, -1];\n    return this.sort((a, b) => {\n      const keys = key instanceof Array ? key : [key];\n      for (const k of keys) {\n        const r1 = rank(a as E, k);\n        const r2 = rank(b as E, k);\n        if (r1 > r2) return up;\n        if (r1 < r2) return down;\n      }\n      return 0;\n    });\n  }\n\n  /**\n   * Returns a copy of this collection sorted by some {@link Sorter}.\n   * @category Structure\n   */\n  sortedBy(key: Sorter<T> | (Sorter<T>)[], direction: \"asc\" | \"desc\" = \"asc\") {\n    return (this.slice(0, this.length) as this).sortBy(key, direction);\n  }\n\n  /**\n   * Returns the sum of all elements in this collection measured by a provided key\n   * @category Queries\n   *\n   * @example\n   * deck.create(Card, '2', { pips: 2 });\n   * deck.create(Card, '3', { pips: 3 });\n   * deck.all(Card).sum('pips'); // => 5\n   */\n  sum(key: ((e: T) => number) | (keyof {[K in keyof T]: T[K] extends number ? never: K})) {\n    return this.reduce((sum, n) => sum + (typeof key === 'function' ? key(n) : n[key] as unknown as number), 0);\n  }\n\n  /**\n   * Returns the element in this collection with the highest value of the\n   * provided key(s).\n   * @category Queries\n   *\n   * @param attributes - any number of {@link Sorter | Sorter's} used for\n   * comparing. If multiple are provided, subsequent ones are used to break ties\n   * on earlier ones.\n   *\n   * @example\n   * army.create(Soldier, 'a', { strength: 2, initiative: 3 });\n   * army.create(Soldier, 'b', { strength: 3, initiative: 1 });\n   * army.create(Soldier, 'c', { strength: 3, initiative: 2 });\n   * army.all(Solider).withHighest('strength', 'initiative'); // => Soldier 'c'\n   */\n  withHighest(...attributes: Sorter<T>[]): T | undefined {\n    return this.sortedBy(attributes, 'desc')[0];\n  }\n\n  /**\n   * Returns the element in this collection with the lowest value of the\n   * provided key(s).\n   * @category Queries\n   *\n   * @param attributes - any number of {@link Sorter | Sorter's} used for\n   * comparing. If multiple are provided, subsequent ones are used to break ties\n   * on earlier ones.\n   *\n   * @example\n   * army.create(Soldier, 'a', { strength: 2, initiative: 3 });\n   * army.create(Soldier, 'b', { strength: 3, initiative: 1 });\n   * army.create(Soldier, 'c', { strength: 2, initiative: 2 });\n   * army.all(Solider).withLowest('strength', 'initiative'); // => Soldier 'c'\n   */\n  withLowest(...attributes: Sorter<T>[]): T | undefined {\n    return this.sortedBy(attributes, 'asc')[0];\n  }\n\n  /**\n   * Returns the highest value of the provided key(s) found on any element in\n   * this collection.\n   * @category Queries\n   *\n   * @param key - a {@link Sorter | Sorter's} used for comparing and extracting\n   * the max.\n   *\n   * @example\n   * army.create(Soldier, 'a', { strength: 2, initiative: 3 });\n   * army.create(Soldier, 'b', { strength: 3, initiative: 1 });\n   * army.create(Soldier, 'c', { strength: 2, initiative: 2 });\n   * army.all(Solider).max('strength'); // => 3\n   */\n  max<K extends number | string>(key: {[K2 in keyof T]: T[K2] extends K ? K2 : never}[keyof T] | ((t: T) => K)): K | undefined {\n    const el = this.sortedBy(key, 'desc')[0];\n    if (!el) return;\n    return typeof key === 'function' ? key(el) : el[key] as K;\n  }\n\n  /**\n   * Returns the lowest value of the provided key(s) found on any element in\n   * this collection.\n   * @category Queries\n   *\n   * @param key - a {@link Sorter | Sorter's} used for comparing and extracting\n   * the minimum.\n   *\n   * @example\n   * army.create(Soldier, 'a', { strength: 2, initiative: 3 });\n   * army.create(Soldier, 'b', { strength: 3, initiative: 1 });\n   * army.create(Soldier, 'c', { strength: 2, initiative: 2 });\n   * army.all(Solider).min('initiative'); // => 1\n   */\n  min<K extends number | string>(key: {[K2 in keyof T]: T[K2] extends K ? K2 : never}[keyof T] | ((t: T) => K)): K | undefined {\n    const el = this.sortedBy(key, 'asc')[0]\n    if (!el) return;\n    return typeof key === 'function' ? key(el) : el[key] as K;\n  }\n\n  /**\n   * Returns whether all elements in this collection have the same value for key.\n   * @category Queries\n   */\n  areAllEqual(key: keyof T): boolean {\n    if (this.length === 0) return true;\n    return this.every(el => el[key] === this[0][key]);\n  }\n\n  /**\n   * Remove all elements in this collection from the playing area and place them\n   * into {@link Game#pile}\n   * @category Structure\n   */\n  remove() {\n    for (const el of this) {\n      if ('isSpace' in el) throw Error('cannot move Space');\n      (el as unknown as Piece<Game>).remove();\n    }\n  }\n\n  /**\n   * Move all pieces in this collection into another element. See {@link Piece#putInto}.\n   * @category Structure\n   */\n  putInto(to: GameElement, options?: {position?: number, fromTop?: number, fromBottom?: number}) {\n    if (this.some(el => el.hasMoved()) || to.hasMoved()) to.game.addDelay();\n    for (const el of this) {\n      if ('isSpace' in el) throw Error('cannot move Space');\n      (el as unknown as Piece<Game>).putInto(to, options);\n    }\n  }\n\n  // UI\n\n  /**\n   * Apply a layout to some of the elements directly contained within the elements\n   * in this collection. See {@link GameElement#layout}\n   * @category UI\n   */\n  layout(\n    applyTo: T['_ui']['layouts'][number]['applyTo'],\n    attributes: Partial<GameElement['_ui']['layouts'][number]['attributes']>\n  ) {\n    for (const el of this) el.layout(applyTo, attributes);\n  }\n\n\n  /**\n   * Configure the layout for all elements contained within this collection. See\n   * {@link GameElement#configureLayout}\n   * @category UI\n   */\n  configureLayout(\n    attributes: Partial<GameElement['_ui']['layouts'][number]['attributes']>\n  ) {\n    for (const el of this) el.configureLayout(attributes);\n  }\n\n  /**\n   * Define the appearance of the elements in this collection. Any values\n   * provided override previous ones. See {@link GameElement#appearance}.\n   * @category UI\n   */\n  appearance(appearance: ElementUI<T>['appearance']) {\n    for (const el of this) el.appearance(appearance);\n  }\n}\n"
  },
  {
    "path": "src/board/element.ts",
    "content": "import ElementCollection from './element-collection.js';\nimport { shuffleArray, times } from '../utils.js';\nimport { serializeObject, deserializeObject } from '../action/utils.js';\nimport uuid from 'uuid-random';\n\nimport type GameManager from '../game-manager.js';\nimport type { default as Player, BasePlayer } from '../player/player.js';\nimport type { default as Game, BaseGame } from './game.js';\nimport type Space from './space.js';\nimport type ConnectedSpaceMap from './connected-space-map.js';\nimport type { ElementFinder, Sorter } from './element-collection.js';\nimport type AdjacencySpace from './adjacency-space.js';\nimport type { Argument } from '../action/action.js';\n\nexport type ElementJSON = ({className: string, children?: ElementJSON[]} & Record<string, any>);\n\nexport type ElementClass<T extends GameElement = GameElement> = {\n  new(ctx: Partial<ElementContext>): T;\n  isGameElement: boolean; // here to help enforce types\n  visibleAttributes?: string[];\n}\n\n/**\n * Either the name of a property of the object that can be lexically sorted, or\n * a function that will be called with the object to sort and must return a\n * lexically sortable value.\n * @category Board\n */\nexport type GenericSorter = string | ((e: GameElement) => number | string)\n\n/**\n * The attributes of this class that inherits GameElement, excluding internal\n * ones from the base GameElement\n */\nexport type ElementAttributes<T extends GameElement> =\n  Partial<Pick<T, {[K in keyof T]: K extends keyof GameElement ? never : (T[K] extends (...a:any[]) => any ? never : K)}[keyof T] | 'name' | 'player' | 'row' | 'column' | 'rotation'>>\n\nexport type ElementContext = {\n  gameManager: GameManager;\n  top: GameElement;\n  namedSpaces: Record<string, Space<Game>>\n  uniqueNames: Record<string, boolean>\n  removed: GameElement;\n  sequence: number;\n  player?: Player;\n  classRegistry: ElementClass[];\n  moves: Record<string, string>;\n  trackMovement: boolean;\n};\n\n/**\n * A Box size and position relative to a container\n * @category UI\n */\nexport type Box = { left: number, top: number, width: number, height: number };\n/**\n * An (x, y) Vector\n * @category UI\n */\nexport type Vector = { x: number, y: number };\n\nexport type Direction = 'up' | 'down' | 'left' | 'right'\nexport type DirectionWithDiagonals = Direction | 'upleft' | 'upright' | 'downleft' | 'downright';\n\nexport type ElementUI<T extends GameElement> = {\n  layouts: {\n    applyTo: ElementClass | GameElement | ElementCollection | string,\n    attributes: LayoutAttributes\n  }[],\n  appearance: {\n    className?: string,\n    render?: ((el: T) => JSX.Element | null) | false,\n    aspectRatio?: number,\n    effects?: { trigger: (element: T, oldAttributes: ElementAttributes<T>) => boolean, name: string }[],\n    info?: ((el: T) => JSX.Element | null | boolean) | boolean,\n    connections?: {\n      thickness?: number,\n      style?: 'solid' | 'double',\n      color?: string,\n      fill?: string,\n      label?: ({distance, to, from}: {distance: number, to: Space<Game>, from: Space<Game> }) => React.ReactNode,\n      labelScale?: number,\n    },\n  },\n  getBaseLayout: () => LayoutAttributes,\n  ghost?: boolean,\n};\n\n/**\n * List of attributes used to create a new layout in {@link GameElement#layout}.\n * @category UI\n */\nexport type LayoutAttributes = {\n  /**\n   * Instead of providing `area`, providing a `margin` defines the bounding box\n   * in terms of a margin around the edges of this element. This value is an\n   * absolute percentage of the board's size so that margins specified on\n   * different layouts with the same value will exactly match.\n   */\n margin?: number | { top: number, bottom: number, left: number, right: number },\n  /**\n   * A box defining the layout's bounds within this element. Unless `size` is\n   * set too large, no elements will ever overflow this area. If unspecified,\n   * the entire area is used, i.e. `{ left: 0, top: 0, width: 100, height: 100\n   * }`\n   */\n  area?: Box,\n  /**\n   * The number of rows to allot for placing elements in this layout. If a\n   * number is provided, this is fixed. If min/max values are provided, the\n   * layout will allot at least `min` and up to `max` as needed. If `min` is\n   * omitted, a minimum of 1 is implied. If `max` is omitted, as many are used\n   * as needed. Default is no limits on either.\n   */\n  rows?: number | {min: number, max?: number} | {min?: number, max: number},\n  /**\n   * Columns, as per `rows`\n   */\n  columns?: number | {min: number, max?: number} | {min?: number, max: number},\n  /**\n   * If supplied, this overrides all other attributes to define a set of\n   * strictly defined boxes for placing each element. Any elements that exceed\n   * the number of slots provided are not displayed.\n   */\n  slots?: Box[],\n  /**\n   * Size alloted for each element placed in this layout. Overrides `scaling`\n   * and all defined aspect ratios for these elements, fixing the size for each\n   * element at the specified size.\n   */\n  size?: { width: number, height: number },\n  /**\n   * Aspect ratio for each element placed in this layout. This value is a ratio\n   * of width over height. Elements will adhere to this ratio unless they have\n   * their own specified `aspectRatio` in their {@link\n   * GameElement#appearance}. This value is ignored if `size` is provided.\n   */\n  aspectRatio?: number, // w / h\n  /**\n   * Scaling strategy for the elements placed in this layout.\n   * - *fit*: Elements scale up or down to fit within the area alloted without\n   *    squshing\n   * - *fill*: Elements scale up or down to completely fill the area, squishing\n   *    themselves together as needed along one dimension.\n   */\n  scaling?: 'fit' | 'fill'\n  /**\n   * If provided, this places a gap between elements. If scaling is 'fill', this\n   * is considered a maximum but may shrink or even become negative in order to\n   * fill the area. This value is an absolute percentage of the board's size so\n   * that gaps specified on different layouts with the same value will exactly\n   * match\n   */\n  gap?: number | { x: number, y: number },\n  /**\n   * If more room is provided than needed, this determines how the elements will\n   * align themselves within the area.\n   */\n  alignment: 'top' | 'bottom' | 'left' | 'right' | 'top left' | 'bottom left' | 'top right' | 'bottom right' | 'center',\n  /**\n   * Instead of `gap`, providing an `offsetColumn`/`offsetRow` specifies that\n   * the contained elements must offset one another by a specified amount as a\n   * percentage of the elements size, i.e. `offsetColumn=100` is equivalent to a\n   * `gap` of 0. This allows non-orthogonal grids like hex or diamond. If one of\n   * `offsetColumn`/`offsetRow` is provided but not the other, the unspecified\n   * one will be 90° to the one specified. Like `gap`, if `scaling` is set to\n   * `fill`, these offsets may squish to fill space.\n   */\n  offsetColumn?: Vector | number,\n  /**\n   * As `offsetColumn`\n   */\n  offsetRow?: Vector | number,\n  /**\n   * Specifies the direction in which elements placed here should fill up the\n   * rows and columns of the layout. Rows or columns will increase to their\n   * specified maximum as needed. Therefore if, for example, `direction` is\n   * `\"ltr\"` and `columns` has no maximum, there will never be a second row\n   * added. Values are:\n   * - *square*: fill rows and columns equally to maintain as square a grid as possible (default)\n   * - *ltr*: fill columns left to right, then rows top to bottom once maximum columns reached\n   * - *rtl*: fill columns right to left, then rows top to bottom once maximum columns reached\n   * - *ltr-btt*: fill columns left to right, then rows bottom to top once maximum columns reached\n   * - *rtl-btt*: fill columns right to left, then rows bottom to top once maximum columns reached\n   * - *ttb*: fill rows top to bottom, then columns left to right once maximum rows reached\n   * - *btt*: fill rows bottom to top, then columns left to right once maximum rows reached\n   * - *ttb-rtl*: fill rows top to bottom, then columns right to left once maximum rows reached\n   * - *btt-rtl*: fill rows bottom to top, then columns right to left once maximum rows reached\n   */\n  direction: 'square' | 'ltr' | 'rtl' | 'rtl-btt' | 'ltr-btt' | 'ttb' | 'ttb-rtl' | 'btt' | 'btt-rtl',\n  /**\n   * If specified, no more than `limit` items will be visible. This is useful\n   * for displaying e.g. decks of cards where showing only 2 or 3 cards provides\n   * a deck-like appearance without needed to render more cards underneath that\n   * aren't visible.\n   */\n  limit?: number,\n  /**\n   * If `scaling` is `\"fill\"`, this will limit the total amount of overlap if\n   * elements are squished together in their space before they will start to\n   * shrink to fit. This is useful for e.g. cards that can overlap but that must\n   * leave a certain amount visible to clearly identify the card.\n   */\n  maxOverlap?: number,\n  /**\n   * A number specifying an amount of randomness added to the layout to provide\n   * a more natural looking placement\n   */\n  haphazardly?: number,\n  /**\n   * Set to true to prevent these elements from automatically changing position\n   * within the container grid.\n   */\n  sticky?: boolean,\n  /**\n   * Set to true for debugging. Creates a visible box on screen around the\n   * defined `area`, tagged with the provided string.\n   */\n  showBoundingBox?: string | boolean,\n  __container__?: {\n    type: 'drawer' | 'popout' | 'tabs',\n    attributes: Record<string, any>,\n    id?: string,\n    key?: string,\n  }\n};\n\n/**\n * Abstract base class for all Game elements. Do not subclass this\n * directly. Instead use {@link Space} or {@link Piece} as the base for\n * subclassing your own elements.\n * @category Board\n */\nexport default class GameElement<G extends BaseGame = BaseGame, P extends BasePlayer = BasePlayer> {\n  /**\n   * Element name, used to distinguish elements. Elements with the same name are\n   * generally considered indistibuishable. Names are also used for easy\n   * searching of elements.\n   * @category Queries\n   */\n  name: string;\n\n  /**\n   * Player with which this element is identified. This does not affect\n   * behaviour but will mark the element as `mine` in queries in the context of\n   * this player (during an action taken by a player or while the game is\n   * viewed by a given player.).\n   * @category Queries\n   */\n  player?: P;\n\n  /**\n   * Row of element within its layout grid if specified directly or by a\n   * \"sticky\" layout.\n   * @category Structure\n   */\n  row?: number;\n\n  /**\n   * Column of element within its layout grid if specified directly or by a\n   * \"sticky\" layout.\n   * @category Structure\n   */\n  column?: number;\n\n  _rotation?: number; // degrees\n\n  /**\n   * The {@link Game} to which this element belongs\n   * @category Structure\n   */\n  game: G;\n\n  /**\n   * ctx shared for all elements in the tree\n   * @internal\n   */\n  _ctx: ElementContext\n\n  /**\n   * tree info\n   * @internal\n   */\n  _t: {\n    children: ElementCollection<GameElement>,\n    parent?: GameElement,\n    id: number, // unique and immuatable\n    ref: number, // unique and may change to hide moves\n    wasRef?: number, // previous ref to track changes, only populated if reorder during trackMovement\n    moved?: boolean, // track if already moved (changed parent)\n    order?: 'normal' | 'stacking',\n    setId: (id: number) => void,\n  } = {\n    children: new ElementCollection<GameElement>(),\n    id: 0,\n    ref: 0,\n    setId: () => {}\n  };\n\n  _size?: {\n    width: number,\n    height: number,\n    shape: string[],\n    edges?: Record<string, Partial<Record<Direction, string>>>\n  }\n\n  static isGameElement = true;\n\n  static unserializableAttributes = ['_ctx', '_t', '_ui', 'game'];\n\n  static visibleAttributes: string[] | undefined;\n\n  /**\n   * Do not use the constructor directly. Instead Call {@link\n   * GameElement#create} or {@link GameElement#createMany} on the element in\n   * which you want to create a new element.\n   * @category Structure\n   */\n  constructor(ctx: Partial<ElementContext>) {\n    this._ctx = ctx as ElementContext;\n    this._ctx.classRegistry ??= [];\n    if (!ctx.top) {\n      this._ctx.top = this as unknown as GameElement;\n      this._ctx.sequence = 0;\n    }\n    if (!this._ctx.namedSpaces) {\n      this._ctx.uniqueNames = {};\n      this._ctx.namedSpaces = {};\n    }\n\n    this._t = {\n      children: new ElementCollection(),\n      id: this._ctx.sequence,\n      ref: this._ctx.sequence,\n      setId: (id?: number) => {\n        if (id !== undefined) {\n          this._t.id = id;\n          if (this._ctx.sequence < id) this._ctx.sequence = id;\n        }\n      },\n    };\n    this._ctx.sequence += 1;\n  }\n\n  /**\n   * String used for representng this element in game messages when the object\n   * is passed directly, e.g. when taking the choice directly from a\n   * chooseOnBoard choice.\n   * @category Structure\n   */\n  toString() {\n    return this.name || this.constructor.name.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\");\n  }\n\n  isVisibleTo(_player: Player | number) {\n    return true;\n  }\n\n  isVisible() {\n    return true;\n  }\n\n  /**\n   * Finds all elements within this element recursively that match the arguments\n   * provided.\n   * @category Queries\n   *\n   * @param {class} className - Optionally provide a class as the first argument\n   * as a class filter. This will only match elements which are instances of the\n   * provided class\n   *\n   * @param finders - All other parameters are filters. See {@link\n   * ElementFinder} for more information.\n   *\n   * @returns An {@link ElementCollection} of as many matching elements as can be\n   * found. The collection is typed to `ElementCollection<className>` if one was\n   * provided.\n   */\n  all<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  all(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;\n  all(className?: any, ...finders: ElementFinder[]) {\n    return this._t.children.all(className, ...finders);\n  }\n\n  /**\n   * Finds the first element within this element recursively that matches the arguments\n   * provided. See {@link all} for parameter details.\n   * @category Queries\n   * @returns A matching element, if found\n   */\n  first<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  first(className?: ElementFinder, ...finders: ElementFinder[]): GameElement<G, P> | undefined;\n  first(className?: any, ...finders: ElementFinder[]) {\n    return this._t.children.first(className, ...finders);\n  }\n\n  /**\n   * Finds the first `n` elements within this element recursively that match the arguments\n   * provided. See {@link all} for parameter details.\n   * @category Queries\n   * @param n - number of matches\n   *\n   * @returns An {@link ElementCollection} of as many matching elements as can be\n   * found, up to `n`. The collection is typed to `ElementCollection<className>`\n   * if one was provided.\n   */\n  firstN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  firstN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;\n  firstN(n: number, className?: any, ...finders: ElementFinder[]) {\n    return this._t.children.firstN(n, className, ...finders);\n  }\n\n  /**\n   * Finds the last element within this element recursively that matches the arguments\n   * provided. See {@link all} for parameter details.\n   * @category Queries\n   * @returns A matching element, if found\n   */\n  last<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  last(className?: ElementFinder, ...finders: ElementFinder[]): GameElement<G, P> | undefined;\n  last(className?: any, ...finders: ElementFinder[]) {\n    return this._t.children.last(className, ...finders);\n  }\n\n  /**\n   * Finds the last `n` elements within this element recursively that match the arguments\n   * provided. See {@link all} for parameter details.\n   * @category Queries\n   * @param n - number of matches\n   *\n   * @returns An {@link ElementCollection} of as many matching elements as can be\n   * found, up to `n`. The collection is typed to `ElementCollection<className>`\n   * if one was provided.\n   */\n  lastN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  lastN(n: number, className: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;\n  lastN(n: number, className: any, ...finders: ElementFinder[]) {\n    return this._t.children.lastN(n, className, ...finders);\n  }\n\n\n  /**\n   * Alias for {@link first}\n   * @category Queries\n   */\n  top<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  top(className?: ElementFinder, ...finders: ElementFinder[]): GameElement<G, P> | undefined;\n  top(className?: any, ...finders: ElementFinder[]) {\n    return this._t.children.top(className, ...finders);\n  }\n\n  /**\n   * Alias for {@link firstN}\n   * @category Queries\n   */\n  topN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  topN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;\n  topN(n: number, className?: any, ...finders: ElementFinder[]) {\n    return this._t.children.topN(n, className, ...finders);\n  }\n\n  /**\n   * Alias for {@link last}\n   * @category Queries\n   */\n  bottom<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  bottom(className?: ElementFinder, ...finders: ElementFinder[]): GameElement<G, P> | undefined;\n  bottom(className?: any, ...finders: ElementFinder[]) {\n    return this._t.children.bottom(className, ...finders);\n  }\n\n  /**\n   * Alias for {@link lastN}\n   * @category Queries\n   */\n  bottomN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  bottomN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;\n  bottomN(n: number, className?: any, ...finders: ElementFinder[]) {\n    return this._t.children.bottomN(n, className, ...finders);\n  }\n\n  /**\n   * Finds next element in this element's Space of the same class that matches\n   * the arguments provided, e.g. the next card after this one in the same\n   * pile.\n   * @param finders - any number of {@link ElementFinder} arguments to filter\n   * @category Queries\n   */\n  next<F extends GameElement>(this: F, ...finders: ElementFinder<F>[]): F | undefined {\n    if (!this._t.parent) return undefined;\n    const thisIndex = this._t.parent!._t.children.indexOf(this);\n    return this._t.parent!._t.children.slice(thisIndex + 1).first(this.constructor as ElementClass<F>, ...finders);\n  }\n\n  /**\n   * Finds previous element in this element's Space of the same class that\n   * matches the arguments provided, e.g. the previous card before this one in\n   * the same pile.\n   * @param finders - any number of {@link ElementFinder} arguments to filter\n   * @category Queries\n   */\n  previous<F extends GameElement>(this: F, ...finders: ElementFinder<F>[]): F | undefined {\n    if (!this._t.parent) return undefined;\n    const thisIndex = this._t.parent!._t.children.indexOf(this);\n    return this._t.parent!._t.children.slice(0, thisIndex - 1).last(this.constructor as ElementClass<F>, ...finders);\n  }\n\n  /**\n   * Finds \"sibling\" elements (elements that are directly inside the parent of this element) that match the arguments\n   * provided. See {@link all} for parameter details.\n   * @category Queries\n   */\n  others<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  others(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;\n  others(className?: any, ...finders: ElementFinder[]) {\n    if (!this._t.parent) return new ElementCollection();\n    return this._t.parent!._t.children.all(className, (el: GameElement) => el !== this, ...finders);\n  }\n\n  /**\n   * Return whether any element within this element recursively matches the arguments\n   * provided. See {@link all} for parameter details.\n   * @category Queries\n   */\n  has<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): boolean;\n  has(className?: ElementFinder, ...finders: ElementFinder[]): boolean;\n  has(className?: any, ...finders: ElementFinder[]) {\n    if ((typeof className !== 'function') || !('isGameElement' in className)) {\n      if (className) finders = [className, ...finders];\n      return !!this.first(GameElement, ...finders);\n    }\n    return !!this.first(className, ...finders);\n  }\n\n  /**\n   * If this element is adjacent to some other element, using the nearest\n   * containing space that has an adjacency map.\n   * @category Adjacency\n   */\n  isAdjacentTo(element: GameElement): boolean {\n    const graph = this.containerWithProperty('isAdjacent');\n    if (!graph) return false;\n    return (graph as AdjacencySpace<G>).isAdjacent(this, element);\n  }\n\n  /**\n   * Finds the shortest distance between two spaces\n   * @category Adjacency\n   *\n   * @param element - {@link element} to measure distance to\n   */\n  distanceTo(element: GameElement): number {\n    const graph = this.containerWithProperty('distanceBetween');\n    if (!graph) return Infinity;\n    return (graph as ConnectedSpaceMap<G>).distanceBetween(this, element);\n  }\n\n  /**\n   * Find all elements adjacent based on row/column placement or based on this\n   * element having connections created by Space#connectTo. Uses the same\n   * parameters as {@link GameElement#all}\n   * @category Adjacency\n   */\n  adjacencies<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  adjacencies(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;\n  adjacencies(className?: any, ...finders: ElementFinder[]) {\n    const graph = this.containerWithProperty('isAdjacent') as AdjacencySpace<G> | undefined;\n    if (!graph) return false;\n    return (graph as ConnectedSpaceMap<G>).allAdjacentTo(this, className, ...finders);\n  }\n\n  /**\n   * Finds all spaces connected to this space by a distance no more than\n   * `distance`\n   *\n   * @category Adjacency\n   */\n  withinDistance<F extends GameElement>(distance: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  withinDistance(distance: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;\n  withinDistance(distance: number, className?: any, ...finders: ElementFinder[]) {\n    const graph = this.containerWithProperty('allWithinDistanceOf');\n    if (!graph) return new ElementCollection();\n    return (graph as ConnectedSpaceMap<G>).allWithinDistanceOf(this, distance, className, ...finders);\n  }\n\n  /**\n   * Set this class to use a different ordering style.\n   * @category Structure\n   * @param order - ordering style\n   * - \"normal\": Elements placed into this element are put at the end of the\n   *   list (default)\n   * - \"stacking\": Used primarily for stacks of cards. Elements placed into this\n   *   element are put at the beginning of the list. E.g. if a stack of cards\n   *   has `order` set to `stacking` the {@link first} method will return the\n   *   last card placed in the stack, rather than the first one placed in the\n   *   stack. Hidden items in the stack are not tracked or animated while\n   *   reordered to prevent their identity from being exposed as they move\n   */\n  setOrder(order: typeof this._t.order) {\n    this._t.order = order;\n  }\n\n  /**\n   * Returns this elements parent.\n   * @category Queries\n   * @param className - If provided, searches up the parent tree to find the first\n   * matching element. E.g. if a Token is placed on a Card in a players\n   * Tableau. calling `token.container(Tableau)` can be used to find the\n   * grandparent.\n   */\n  container<T extends GameElement>(className?: ElementClass<T>): T | undefined {\n    if (!className) return this._t.parent as T;\n    if (this._t.parent) return this._t.parent instanceof className ?\n      this._t.parent as T:\n      this._t.parent.container(className);\n  }\n\n  /**\n   * Returns this elements containing element that also has a given property.\n   * @category Queries\n   */\n  containerWithProperty(property: string, value?: any): GameElement | undefined {\n    const parent = this._t.parent;\n    if (parent) return property in parent && (value === undefined || parent[property as keyof typeof parent] === value) ?\n      parent:\n      parent.containerWithProperty(property, value);\n  }\n\n  /**\n   * Returns whether this element has no elements placed within it.\n   * @category Structure\n   */\n  isEmpty() {\n    return !this._t.children.length;\n  }\n\n  /**\n   * Sorts the elements directly contained within this element by some {@link Sorter}.\n   * @category Structure\n   */\n  sortBy(key: GenericSorter | GenericSorter[], direction?: \"asc\" | \"desc\"): ElementCollection<GameElement<G, P>> {\n    return this._t.children.sortBy(key as Sorter<GameElement> | Sorter<GameElement>[], direction) as ElementCollection<GameElement<G, P>>\n  }\n\n  /**\n   * re-orders the elements directly contained within this element randomly.\n   * @category Structure\n   */\n  shuffle() {\n    const refs = this.childRefsIfObscured();\n    shuffleArray(this._t.children, this._ctx.gameManager?.random || Math.random);\n    if (refs) this.assignChildRefs(refs);\n  }\n\n  /**\n   * The player that owns this element, or the first element that contains this\n   * element searching up through the parent hierarchy. This is related to, but\n   * different than {@link player}. E.g. if a standard playing card is in a\n   * player's hand, typically the `hand.player` will be assigned to that player\n   * but the card itself would not have a `player`. In this case the\n   * card.owner() will equal the player in whose hand the card is placed.\n   * @category Structure\n   */\n  get owner(): P | undefined {\n    return this.player !== undefined ? this.player as P : this._t.parent?.owner as P;\n  }\n\n  /**\n   * Whether this element belongs to the player viewing the game. A player is\n   * considered to be currently viewing the game if this is called in the\n   * context of an action taken by a given player (during an action taken by a\n   * player or while the game is viewed by a given player.) It is an error to\n   * call this method when not in the context of a player action. When querying\n   * for elements using {@link ElementFinder} such as {@link all} and {@link\n   * first}, {@link mine} is available as a search key that accepts a value of\n   * true/false\n   @category Queries\n   */\n  get mine() {\n    if (!this._ctx.player) return false; // throw?\n    return this.owner === this._ctx.player;\n  }\n\n  /**\n   * Create an element inside this element. This can only be called during the\n   * game setup (see {@link createGame}. Any game elements that are required\n   * must be created before the game starts. Elements that only appear later in\n   * the game can be created inside the {@link Game#pile} or made invisible.\n   * @category Structure\n   *\n   * @param className - Class to create. This class must be included in the `elementClasses` in {@link createGame}.\n   * @param name - Sets {@link GameElement#name | name}\n   * @param attributes - Sets any attributes of the class that are defined in\n   * your own class that extend {@link Space}, {@link Piece}, or {@link\n   * Game}. Can also include {@link player}.\n   *\n   * @example\n   * deck.create(Card, 'ace-of-hearts', { suit: 'H', value: '1' });\n   */\n  create<T extends GameElement>(className: ElementClass<T>, name: string, attributes?: ElementAttributes<T>): T {\n    if (this._ctx.gameManager?.phase === 'started') throw Error('Game elements cannot be created once game has started.');\n    const el = this.createElement(className, name, attributes);\n    el._t.parent = this;\n    const firstPiece = this._t.children.findIndex(c => !('isSpace' in c));\n    if (this._t.order === 'stacking' && !('isSpace' in el)) {\n      if (firstPiece > 0) {\n        this._t.children.splice(firstPiece, 0, el);\n      } else {\n        this._t.children.unshift(el);\n      }\n    } else {\n      if ('isSpace' in el && firstPiece !== -1) {\n        this._t.children.splice(firstPiece, 0, el)\n      } else {\n        this._t.children.push(el);\n      }\n    }\n    if ('isSpace' in el && name) {\n      if (name in this._ctx.uniqueNames) { // no longer unique\n        delete this._ctx.namedSpaces[name];\n        this._ctx.uniqueNames[name] = false\n      } else {\n        this._ctx.namedSpaces[name] = el as unknown as Space<Game>;\n        this._ctx.uniqueNames[name] = true;\n      }\n    }\n    return el as T;\n  }\n\n  /**\n   * Create n elements inside this element of the same class. This can only be\n   * called during the game setup (see {@link createGame}. Any game elements\n   * that are required must be created before the game starts. Elements that\n   * only appear later in the game can be created inside the {@link Game#pile}\n   * or made invisible.\n   * @category Structure\n   *\n   * @param n - Number to create\n   * @param className - Class to create. This class must be included in the `elementClasses` in {@link createGame}.\n   * @param name - Sets {@link GameElement#name | name}\n   * @param attributes - Sets any attributes of the class that are defined in\n   * your own class that extend {@link Space}, {@link Piece}, or {@link\n   * Game}. Can also include {@link player}. If a function is supplied here, a\n   * single number argument will be passed with the number of the added element,\n   * starting with 1.\n   */\n  createMany<T extends GameElement>(n: number, className: ElementClass<T>, name: string, attributes?: ElementAttributes<T> | ((n: number) => ElementAttributes<T>)): ElementCollection<T> {\n    return new ElementCollection<T>(...times(n, i => this.create(className, name, typeof attributes === 'function' ? attributes(i) : attributes)));\n  }\n\n  /**\n   * Base element creation method\n   * @internal\n   */\n  createElement<T extends GameElement>(className: ElementClass<T>, name: string, attrs?: ElementAttributes<T>): T {\n    if (!this._ctx.classRegistry.includes(className)) {\n      this._ctx.classRegistry.push(className);\n    }\n    const el = new className(this._ctx);\n    el.game = this.game;\n    el.name = name;\n    Object.assign(el, attrs);\n    if ('afterCreation' in el) (el.afterCreation as () => void).bind(el)();\n    return el;\n  }\n\n  /**\n   * Permanently remove an element. This can only be done while defining the\n   * game, and is usually only useful when creating groups of elements, such as\n   * {@link createMany} or {@link createGrid} where some of the created elements\n   * are not needed.\n   * @category Structure\n   */\n  destroy() {\n    if (this._ctx.gameManager?.phase === 'started') throw Error('Game elements cannot be destroy once game has started.');\n    const position = this.position();\n    this._t.parent?._t.children.splice(position, 1);\n  }\n\n  /**\n   * Rotation of element if set, normalized to 0-359 degrees\n   * @category Structure\n   */\n  get rotation() {\n    if (this._rotation === undefined) return 0;\n    return (this._rotation % 360 + 360) % 360;\n  }\n\n  set rotation(r: number) {\n    this._rotation = r;\n  }\n\n  /**\n   * Returns the index of this element within its parent, starting at zero\n   * @category Structure\n   */\n  position() {\n    return this._t.parent?._t.children.indexOf(this) ?? -1;\n  }\n\n  /**\n   * Returns a string identifying the tree position of the element suitable for\n   * anonymous reference\n   * @internal\n   */\n  branch() {\n    const branches = [];\n    let node = this as GameElement;\n    while (node._t.parent) {\n      const index = node.position();\n      if (index === -1) throw Error(`Reference to element ${this.constructor.name}${this.name ? ':' + this.name : ''} is no longer current`);\n      branches.unshift(index);\n      node = node._t.parent;\n    }\n    branches.unshift(this._ctx.removed === node ? 1 : 0);\n    return branches.join(\"/\");\n  }\n\n  /**\n   * Returns the element at the given position returned by {@link branch}\n   * @internal\n   */\n  atBranch(b: string) {\n    let branch = b.split('/');\n    let index = parseInt(branch[0]);\n    let node = index === 0 ? this._ctx.top : this._ctx.removed._t.children[index - 1];\n    branch.shift();\n    while (branch[0] !== undefined) {\n      node = node._t.children[parseInt(branch[0])];\n      branch.shift();\n    }\n    return node;\n  }\n\n  /**\n   * Returns the element for the given id\n   * @internal\n   */\n  atID(id: number): GameElement | undefined {\n    let el = this._t.children.find(c => c._t.id === id);\n    if (el) return el;\n    for (const child of this._t.children) {\n      el = child.atID(id);\n      if (el) return el;\n    }\n  }\n\n  /**\n   * Returns the element for the given ref\n   * @internal\n   */\n  atRef(ref: number): GameElement | undefined {\n    let el = this._t.children.find(c => c._t.ref === ref);\n    if (el) return el;\n    for (const child of this._t.children) {\n      el = child.atRef(ref);\n      if (el) return el;\n    }\n  }\n\n  _cellAt(pos: Vector): string | undefined {\n    if (!this._size) return pos.x === 0 && pos.y === 0 ? '.' : undefined;\n    if (this.rotation === 0) return this._size.shape[pos.y]?.[pos.x];\n    if (this.rotation === 90) return this._size.shape[this._size.height - 1 - pos.x]?.[pos.y];\n    if (this.rotation === 180) return this._size.shape[this._size.height - 1 - pos.y]?.[this._size.width - 1 - pos.x];\n    if (this.rotation === 270) return this._size.shape[pos.x]?.[this._size.width - 1 - pos.y];\n  }\n\n  _sizeNeededFor(_element: GameElement) {\n    return {width: 1, height: 1};\n  }\n\n  /**\n   * Set an irregular shape for this element. This is only meaningful for the\n   * purposes of finding specifically adjacent cells when placed into a\n   * PieceGrid. See {@link PieceGrid#adjacenciesByCell}. When rendered in a\n   * PieceGrid, the element will have a size large enough to fill the\n   * appropriate number of spaces in the grid, but it's appearance is otherwise\n   * unaffected and will be based on {@link appearance}. When not rendered in a\n   * PieceGrid, the element will take up a single cell but will be scaled\n   * relatively to other elements with a shape in the same layout.\n   *\n   * @param shape - A set of single characters used as labels for each cell. The\n   * cell label characters are provided as an array of strings, with each string\n   * being one row of cell labels, with spaces used to indicate empty \"holes\" in\n   * the shape. Each row must be the same length. The specific non-space\n   * characters used are used for labelling the adjacencies in {@link\n   * PieceGrid#adjacenciesByCell} but are otherwise unimportant.\n   * @category Adjacency\n   *\n   * @example\n   *\n   * domino12.setShape(\n   *   '12'\n   * );\n\n   * tetrisPiece.setShape(\n   *   'XX ',\n   *   ' XX'\n   * );\n   */\n  setShape(...shape: string[]) {\n    if (this._ctx.gameManager?.phase === 'started') throw Error('Cannot change shape once game has started.');\n    if (shape.some(s => s.length !== shape[0].length)) throw Error(\"Each row in shape must be same size. Invalid shape:\\n\" + shape);\n    this._size = {\n      shape,\n      width: shape[0].length,\n      height: shape.length\n    }\n  }\n\n  /**\n   * Set the edge labels for this element. These are only meaningful for the\n   * purposes of finding specifically adjacent edges when placed into a\n   * PieceGrid. See {@link PieceGrid#adjacenciesByEdge}.\n   * @category Adjacency\n   *\n   * @param edges - A set of edge labels for each cell label provided by {@link\n   * setShape}. For simple 1-celled shapes, the edges can be provided without\n   * cell labels.\n   *\n   * @example\n   *\n   * // a bridge tile with a road leading from left to right and a river leading\n   * // from top to bottom.\n   * simpleTile.setEdge(\n   *   up: 'river',\n   *   down: 'river',\n   *   left: 'road'\n   *   right: 'road'\n   * });\n   *\n   * // A tetris-shaped tile with sockets coming out either \"end\"\n   * tetrisPiece.setShape(\n   *   'AX ',\n   *   ' XB'\n   * );\n   * tetrisPiece.setEdge({\n   *   A: {\n   *     left: 'socket'\n   *   },\n   *   B: {\n   *     right: 'socket'\n   *   }\n   * });\n   */\n  setEdges(edges: Record<string, Partial<Record<Direction, string>>> | Partial<Record<Direction, string>>) {\n    if (this._ctx.gameManager?.phase === 'started') throw Error('Cannot change shape once game has started.');\n    if (Object.keys(edges)[0].length === 1) {\n      const missingCell = Object.keys(edges).find(c => this._size?.shape.every(s => !s.includes(c)));\n      if (missingCell) throw Error(`No cell '${missingCell}' defined in shape`);\n      this._size!.edges = edges as Record<string, Record<Direction, string>>;\n    } else {\n      if (this._size) throw Error(\"setEdges must use the cell characters from setShape as keys\");\n      this._size = {shape: ['.'], width: 1, height: 1, edges: {'.': edges}};\n    }\n  }\n\n  /**\n   * Whether this element has the given element in its parent hierarchy\n   * @category Structure\n   */\n  isDescendantOf(el: GameElement): boolean {\n    return this._t.parent === el || !!this._t.parent?.isDescendantOf(el)\n  }\n\n  attributeList<T extends GameElement>(this: T): ElementAttributes<T> {\n    let attrs: Record<string, any>;\n    ({ ...attrs } = this);\n    for (const attr of (this.constructor as typeof GameElement).unserializableAttributes as string[]) delete attrs[attr];\n\n    // remove methods\n    return Object.fromEntries(Object.entries(attrs).filter(\n      ([, value]) => typeof value !== 'function'\n    )) as ElementAttributes<T>;\n  }\n\n  /**\n   * JSON representation\n   * @param seenBy - optional player position viewing the game\n   * @internal\n   */\n  toJSON(seenBy?: number) {\n    let attrs = this.attributeList();\n\n    // remove hidden attributes\n    if (seenBy !== undefined && !this.isVisibleTo(seenBy)) {\n      attrs = Object.fromEntries(Object.entries(attrs).filter(\n        ([attr]) => ['_visible', 'row', 'column', '_rotation', '_size'].includes(attr) ||\n          (attr !== 'name' && (this.constructor as typeof GameElement).visibleAttributes?.includes(attr))\n      )) as typeof attrs;\n    }\n    const json: ElementJSON = Object.assign(serializeObject(attrs, seenBy !== undefined), { className: this.constructor.name });\n    if (this._t.order) json.order = this._t.order;\n    if (seenBy === undefined) json._id = this._t.id;\n    if (json._id !== this._t.ref) json._ref = this._t.ref;\n    // do not expose moves within deck (shuffles)\n    if (seenBy !== undefined && this._t.wasRef !== undefined && this.isVisibleTo(seenBy)) json._wasRef = this._t.wasRef;\n    if (this._t.children.length && (\n      !seenBy || !('_screen' in this) || this._screen === undefined ||\n        (this._screen === 'all-but-owner' && this.owner?.position === seenBy) ||\n        (this._screen instanceof Array && this._screen.includes(this.owner?.position))\n    )) {\n      json.children = Array.from(this._t.children.map(c => c.toJSON(seenBy)));\n    }\n\n    if (globalThis.window) { // guard-rail in dev\n      try {\n        structuredClone(json);\n      } catch (e) {\n        console.error(`invalid properties on ${this}:\\n${JSON.stringify(json, undefined, 2)}`);\n        throw(e);\n      }\n    }\n    return json;\n  }\n\n  createChildrenFromJSON(childrenJSON: ElementJSON[], branch: string) {\n    // preserve previous children references\n    const childrenRefs = [...this._t.children];\n    this._t.children = new ElementCollection<GameElement<G, P>>();\n\n    for (let i = 0; i !== childrenJSON.length; i++) {\n      const json = childrenJSON[i];\n      const childBranch = branch + '/' + i;\n      let { className, children, _id, _ref, _wasRef, name, order } = json;\n      // try to match and preserve the object and any references.\n      let child = childrenRefs.find(c => _id !== undefined ? (c._t.id === _id) : (c._t.ref === (_wasRef ?? _ref)));\n      if (!child) {\n        const elementClass = this._ctx.classRegistry.find(c => c.name === className);\n        if (!elementClass) throw Error(`No class found ${className}. Declare any classes in \\`game.registerClasses\\``);\n        child = this.createElement(elementClass, name);\n        child._t.setId(_id);\n        child._t.parent = this;\n        child._t.order = order;\n        child._t.ref = _ref ?? _id;\n      } else {\n        // remove absent attributes\n        const emptyAttrs = Object.keys(child).filter(k => !(k in json) && !['_rotation', 'column', 'row'].includes(k) && !(child!.constructor as typeof GameElement).unserializableAttributes.includes(k));\n        if (emptyAttrs.length) {\n          const blank = Reflect.construct(child.constructor, [{}]);\n          for (const attr of emptyAttrs) Object.assign(child, {[attr]: blank[attr]});\n        }\n      }\n      if (_id !== undefined) child._t.ref = _ref ?? _id;\n      if (_wasRef !== undefined && !this._ctx.trackMovement) child._t.wasRef = _wasRef;\n      this._t.children.push(child);\n      child.createChildrenFromJSON(children || [], childBranch);\n    }\n  }\n\n  assignAttributesFromJSON(childrenJSON: ElementJSON[], branch: string) {\n    for (let i = 0; i !== childrenJSON.length; i++) {\n      const json = childrenJSON[i];\n      let { className: _cn, children, _ref, _wasRef, _id, order: _o, ...rest } = json;\n      rest = deserializeObject({...rest}, this.game);\n      let child = this._t.children[i];\n      Object.assign(child, rest);\n      child.assignAttributesFromJSON(children || [], branch + '/' + i);\n    }\n  }\n\n  /**\n   * UI\n   * @internal\n   */\n\n  _ui: ElementUI<this> = {\n    layouts: [],\n    appearance: {},\n    getBaseLayout: () => ({\n      alignment: 'center',\n      direction: 'square'\n    }),\n  };\n\n  resetUI() {\n    this._ui.layouts = [{\n      applyTo: GameElement,\n      attributes: this._ui.getBaseLayout()\n    }];\n    this._ui.appearance = {};\n    for (const child of this._t.children) child.resetUI();\n  }\n\n  /**\n   * Apply a layout to some of the elements directly contained within this\n   * element. See also {@link ElementCollection#layout}\n   * @category UI\n   *\n   * @param applyTo - Which elements this layout applies to. Provided value can be:\n   * - A specific {@link GameElement}\n   * - The name of an element\n   * - A specific set of elements ({@link ElementCollection})\n   * - A class of elements\n   *\n   * If multiple layout declarations would apply to the same element, only one\n   * will be used. The order of specificity is as above. If a class is used and\n   * mutiple apply, the more specific class will be used.\n   *\n   * @param {Object} attributes - A list of attributes describing the\n   * layout. All units of measurement are percentages of this elements width and\n   * height from 0-100, unless otherwise noted (See `margin` and `gap`)\n   */\n  layout(\n    applyTo: typeof this._ui.layouts[number]['applyTo'],\n    attributes: Partial<LayoutAttributes>\n  ) {\n    let {slots, area, size, aspectRatio, scaling, gap, margin, offsetColumn, offsetRow} = attributes\n    if (slots && (area || margin || scaling || gap || margin || offsetColumn || offsetRow)) {\n      console.warn('Layout has `slots` which overrides supplied grid parameters');\n      delete attributes.area;\n      delete attributes.margin;\n      delete attributes.gap;\n      delete attributes.scaling;\n      delete attributes.offsetRow;\n      delete attributes.offsetColumn;\n    }\n    if (area && margin) {\n      console.warn('Both `area` and `margin` supplied in layout. `margin` is ignored');\n      delete attributes.margin;\n    }\n    if (size && aspectRatio) {\n      console.warn('Both `size` and `aspectRatio` supplied in layout. `aspectRatio` is ignored');\n      delete attributes.aspectRatio;\n    }\n    if (size && scaling) {\n      console.warn('Both `size` and `scaling` supplied in layout. `scaling` is ignored');\n      delete attributes.scaling;\n    }\n    if (gap && (offsetColumn || offsetRow)) {\n      console.warn('Both `gap` and `offset` supplied in layout. `gap` is ignored');\n      delete attributes.gap;\n    }\n    this._ui.layouts.push({ applyTo, attributes: { alignment: 'center', direction: 'square', ...attributes} });\n  }\n\n  /**\n   * Creates a collapsible drawer layout for a Space within this Element. This\n   * is like {@link GameElement#layout} except for one specific Space, with\n   * additional parameters that set the behaviour/appearance of the drawer. A\n   * tab will be attached the drawer that will allow it be opened/closed.\n   *\n   * @param applyTo - The Space for the drawer. Either the Space itself or its\n   * name.\n   * @param area - The area for the drawer when opened expressed in percentage\n   * sizes of this element.\n   * @param openDirection - the direction the drawer will open\n   * @param tab - JSX for the appearance of the tab\n   * @param closedTab - JSX for the appearance of the tab when closed if\n   * different\n   * @param openIf - A function that will be checked at each game state. If it\n   * returns true, the drawer will automatically open.\n   * @param closeIf - A function that will be checked at each game state. If it\n   * returns true, the drawer will automatically close.\n   */\n  layoutAsDrawer(applyTo: Space<G, P> | string, attributes: {\n    area?: Box,\n    openDirection: 'left' | 'right' | 'down' | 'up',\n    tab?: React.ReactNode,\n    closedTab?: React.ReactNode,\n    openIf?: (actions: { name: string, args: Record<string, Argument> }[]) => boolean,\n    closeIf?: (actions: { name: string, args: Record<string, Argument> }[]) => boolean,\n  }) {\n    const { area, ...container } = attributes;\n    this.layout(applyTo, { area, __container__: { type: 'drawer', attributes: container }});\n  }\n\n  /**\n   * Creates a tabbed layout for a set of Space's within this Element. This is\n   * like {@link GameElement#layout} except for a set of Spaces, with additional\n   * parameters that set the behaviour/appearance of the tabs. Each Space will\n   * be laid out into the same area, with a set of tabs attached to allow the\n   * Player or the game rules to select which tab is shown.\n   *\n   * @param applyTo - The Spaces for the drawer as a set of key-value\n   * pairs. Each value is a Space or a name of a Space.\n   * @param area - The area for the tabs expressed in percentage sizes of this\n   * element.\n   * @param tabDirection - the side on which the tabs will be placed\n   * @param tabs - JSX for the appearance of the tabs as a set of key-value pairs\n   * @param setTabTo - A function that will be checked at each game state. If it\n   * returns a string, the tab with the matching key will be shown.\n   */\n  layoutAsTabs(tabs: Record<string, Space<G, P> | string>, attributes: {\n    area?: Box,\n    tabDirection: 'left' | 'right' | 'down' | 'up',\n    tabs?: Record<string, React.ReactNode>,\n    setTabTo?: (actions: { name: string, args: Record<string, Argument> }[]) => string,\n  }) {\n    const { area, ...container } = attributes;\n    const id = uuid();\n    for (const [key, tab] of Object.entries(tabs)) {\n      this.layout(tab, { area, __container__: { type: 'tabs', id, key, attributes: container }});\n    }\n  }\n\n  /**\n   * Hides a Space within this element and replaces it with popout\n   * button. Clicking on the button opens this Space in a full-board modal. This\n   * is like {@link GameElement#layout} except for one Space, with additional\n   * parameters that set the behaviour/appearance of the popout modal.\n   *\n   * @param applyTo - The Space for the popout. Either a Space or the name of a\n   * Space.\n   * @param area - The area for the tabs expressed in percentage sizes of this\n   * element.\n   * @param button - JSX for the appearance of the popout button\n   * @param popoutMargin - Alter the default margin around the opened\n   * popout. Takes a percentage or an object with percentages for top, bottom,\n   * left and right.\n   */\n  layoutAsPopout(applyTo: Space<G, P> | string, attributes: {\n    area?: Box,\n    button: React.ReactNode,\n    popoutMargin?: number | { top: number, bottom: number, left: number, right: number },\n  }) {\n    const { area, ...container } = attributes;\n    this.layout(applyTo, { area, __container__: { type: 'popout', attributes: container }});\n  }\n\n  /**\n   * Change the layout attributes for this space's layout.\n   * @category UI\n   */\n  configureLayout(layoutConfiguration: Partial<LayoutAttributes>) {\n    this._ui.layouts[0] = {\n      applyTo: GameElement,\n      attributes: {\n        ...this._ui.getBaseLayout(),\n        ...layoutConfiguration,\n      }\n    };\n  }\n\n  /**\n   * Define the appearance of this element. Any values provided override\n   * previous ones. See also {@link ElementCollection#appearance}\n   * @category UI\n   *\n   * @param appearance - Possible values are:\n   * @param appearance.className - A class name to add to the dom element\n   *\n   * @param appearance.render - A function that takes this element as its only\n   * argument and returns JSX for the element. See {@link ../ui/appearance} for\n   * more on usage.\n   *\n   * @param appearance.aspectRatio - The aspect ratio for this element. This\n   * value is a ratio of width over height. All layouts defined in {@link\n   * layout} will respect this aspect ratio.\n   *\n   * @param appearance.info - Return JSX for more info on this element. If\n   * returning true, an info modal will be available for this element but with\n   * only the rendered element and no text\n   *\n   * @param appearance.connections - If the elements immediately within this\n   * element are connected using {@link Space#connectTo}, this makes those\n   * connections visible as connecting lines. Providing a `label` will place a\n   * label over top of this line by calling the provided function with the\n   * distance of the connection specified in {@link Space#connectTo} and using\n   * the retured JSX. If `labelScale` is provided, the label is scaled by this\n   * amount.\n   *\n   * @param appearance.effects - Provides a CSS class that will be applied to\n   * this element if its attributes change to match the provided ones.\n   */\n  appearance(appearance: ElementUI<this>['appearance']) {\n    Object.assign(this._ui.appearance, appearance);\n  }\n\n  childRefsIfObscured() {\n    if (this._t.order !== 'stacking') return;\n    const refs = [];\n    for (const child of this._t.children) {\n      if (this._ctx.trackMovement) child._t.wasRef ??= child._t.ref;\n      refs.push(child._t.ref);\n    }\n    return refs;\n  }\n\n  assignChildRefs(refs: number[]) {\n    for (let i = 0; i != refs.length; i++) {\n      this._t.children[i]._t.ref = refs[i];\n    }\n  }\n\n  hasMoved(): boolean {\n    return this._t.moved || !!this._t.parent?.hasMoved();\n  }\n\n  resetMovementTracking() {\n    this._t.moved = false\n    for (const child of this._t.children) child.resetMovementTracking();\n  }\n\n  resetRefTracking() {\n    delete this._t.wasRef;\n    for (const child of this._t.children) child.resetRefTracking();\n  }\n}\n"
  },
  {
    "path": "src/board/fixed-grid.ts",
    "content": "import ConnectedSpaceMap from \"./connected-space-map.js\";\nimport Space from './space.js';\n\nimport type Game from './game.js';\nimport type { default as GameElement, ElementClass, ElementUI } from \"./element.js\";\n\n/**\n * Abstract base class for {@link SquareGrid} and {@link HexGrid}\n * @category Board\n */\nexport default abstract class FixedGrid<G extends Game> extends ConnectedSpaceMap<G> {\n\n  rows: number = 1;\n  columns: number = 1;\n  space: ElementClass<Space<G>> = Space<G>;\n\n  _ui: ElementUI<this> = {\n    layouts: [],\n    appearance: {},\n    getBaseLayout: () => ({\n      rows: this.rows,\n      columns: this.columns,\n      sticky: true,\n      alignment: 'center',\n      direction: 'square'\n    })\n  };\n\n  static unserializableAttributes = [...ConnectedSpaceMap.unserializableAttributes, 'space'];\n\n  afterCreation() {\n    const name = this.name + '-' + this.space.name.toLowerCase();\n    const grid: Space<G>[][] = [];\n    for (const [column, row] of this._gridPositions()) {\n      const space = this.createElement(this.space, name, {column, row});\n      space._t.parent = this;\n      this._t.children.push(space);\n      this._graph.addNode(space._t.id, {space});\n      grid[column] ??= [];\n      grid[column][row] = space;\n    }\n    for (const space of this._t.children) {\n      for (const [column, row, distance] of this._adjacentGridPositionsTo(space.column!, space.row!)) {\n        if (grid[column]?.[row]) this._graph.addDirectedEdge(space._t.id, grid[column][row]._t.id, {distance: distance ?? 1});\n      }\n    }\n    this.configureLayout({ rows: this.rows, columns: this.columns });\n  }\n\n  create<T extends GameElement>(_className: ElementClass, _name: string): T {\n    throw Error(\"Fixed grids automatically create it's own spaces. Spaces can be destroyed but not created\");\n  }\n\n  _adjacentGridPositionsTo(_column: number, _row: number): [number, number, number?][] {\n    return []; // unimplemented\n  }\n\n  _gridPositions(): [number, number][] {\n    return []; // unimplemented\n  }\n}\n"
  },
  {
    "path": "src/board/game.ts",
    "content": "import Space from './space.js'\nimport { Action, Argument, ActionStub } from '../action/index.js';\nimport { deserializeObject } from '../action/utils.js';\nimport Flow from '../flow/flow.js';\nimport { n } from '../utils.js';\nimport { PlayerCollection } from '../player/index.js';\nimport {\n  ActionStep,\n  WhileLoop,\n  ForEach,\n  ForLoop,\n  EachPlayer,\n  EveryPlayer,\n  IfElse,\n  SwitchCase,\n  Do,\n} from '../flow/index.js';\n\nimport type { BasePlayer } from '../player/player.js';\nimport type {\n  default as GameElement,\n  ElementJSON,\n  ElementClass,\n  ElementContext,\n  Box,\n  ElementUI,\n} from './element.js';\nimport type { FlowStep } from '../flow/flow.js';\nimport type { Serializable } from '../action/utils.js';\n\n/**\n * Type for layout of player controls\n * @category UI\n */\nexport type ActionLayout = {\n  /**\n   * The element to which the controls will anchor themselves\n   */\n  element: GameElement,\n  /**\n   * Maximum width of the controls as a percentage of the anchor element\n   */\n  width?: number,\n  /**\n   * Maximum height of the controls as a percentage of the anchor element\n   */\n  height?: number,\n  /**\n   * Boardzilla will automatically anchor the controls to {@link GameElement}'s\n   * selected as part of the action. Include the name of the selection here to\n   * prevent that behaviour.\n   */\n  noAnchor?: string[],\n  /**\n   * Position of the controls\n   * <ul>\n   * <li>inset: Inside the element\n   * <li>beside: To the left or right of the element\n   * <li>stack: Above or below the element\n   * </ul>\n   */\n  position?: 'inset' | 'beside' | 'stack'\n  /**\n   * Distance from the left edge of the anchor element as a percentage of the\n   * element's width\n   */\n  left?: number,\n  /**\n   * Distance from the right edge of the anchor element as a percentage of the\n   * element's width\n   */\n  right?: number,\n  /**\n   * Distance from the top edge of the anchor element as a percentage of the\n   * element's height\n   */\n  center?: number,\n  /**\n   * Distance from the left edge of the anchor element to the center of the\n   * controls as a percentage of the element's width\n   */\n  top?: number,\n  /**\n   * Distance from the bottom edge of the anchor element as a percentage of the\n   * element's height\n   */\n  bottom?: number,\n  /**\n   * For `'beside'` or `'stack'`, `gap` is the distance between the controls and\n   * the element as a percentage of the entire board's size.\n   */\n  gap?: number,\n};\n\nexport type BoardSize = {\n  name: string,\n  aspectRatio: number,\n  orientation?: 'landscape' | 'portrait',\n  scaling?: 'fit' | 'scroll',\n  flipped?: boolean,\n  frame: { x: number, y: number },\n  screen: { x: number, y: number },\n};\n\nexport type BoardSizeMatcher = {\n  name: string,\n  aspectRatio: number | { min: number, max: number },\n  mobile?: boolean,\n  desktop?: boolean,\n  orientation?: 'landscape' | 'portrait',\n  scaling?: 'fit' | 'scroll'\n};\n\nexport interface BaseGame extends Game<BaseGame, BasePlayer> {}\n\n/**\n * Base class for the game. Represents the current state of the game and\n * contains all game elements (spaces and pieces). All games contain a single\n * Game class that inherits from this class and on which custom properties and\n * methods for a specific game can be added.\n *\n * @category Board\n */\nexport default class Game<G extends BaseGame = BaseGame, P extends BasePlayer = BasePlayer> extends Space<G, P> {\n  /**\n   * An element containing all game elements that are not currently in\n   * play. When elements are removed from the game, they go here, and can be\n   * retrieved, using\n   * e.g. `game.pile.first('removed-element').putInto('destination-area')`.\n   * @category Structure\n   */\n  pile: GameElement;\n\n  /**\n   * The players in this game. See {@link Player}\n   * @category Definition\n   */\n  players: PlayerCollection<P> = new PlayerCollection<P>;\n\n  player?: P;\n\n  /**\n   * Use instead of Math.random to ensure random number seed is consistent when\n   * replaying from history.\n   * @category Definition\n   */\n  random: () => number;\n\n  static unserializableAttributes = [...Space.unserializableAttributes, 'pile', 'flowCommands', 'flowGuard', 'players', 'random'];\n\n  constructor(ctx: Partial<ElementContext>) {\n    super({ ...ctx, trackMovement: false });\n    this.game = this as unknown as G;\n    this.random = ctx.gameManager?.random || Math.random;\n    if (ctx.gameManager) this.players = ctx.gameManager.players as unknown as PlayerCollection<P>;\n    this._ctx.removed = this.createElement(Space<this>, 'removed'),\n    this.pile = this._ctx.removed;\n  }\n\n  // no longer needed - remove in next minor release\n  registerClasses(...classList: ElementClass[]) {\n    this._ctx.classRegistry = this._ctx.classRegistry.concat(classList);\n  }\n\n  /**\n   * Define your game's main flow. May contain any of the following:\n   * - {@link playerActions}\n   * - {@link loop}\n   * - {@link whileLoop}\n   * - {@link forEach}\n   * - {@link forLoop}\n   * - {@link eachPlayer}\n   * - {@link everyPlayer}\n   * - {@link ifElse}\n   * - {@link switchCase}\n   * @category Definition\n   */\n  defineFlow(...flow: FlowStep[]) {\n    this.defineSubflow('__main__', ...flow);\n  }\n\n  /**\n   * Define an addtional flow that the main flow can enter. A subflow has a\n   * unique name and can be entered at any point by calling {@link\n   * Do|Do.subflow}.\n   *\n   * @param name - Unique name of flow\n   * @param flow - Steps of the flow\n   */\n  defineSubflow(name: string, ...flow: FlowStep[]) {\n    if (this._ctx.gameManager.phase !== 'new') throw Error('cannot call defineFlow once started');\n    this._ctx.gameManager.flows[name] = new Flow({ name, do: flow });\n    this._ctx.gameManager.flows[name].gameManager = this._ctx.gameManager;\n  }\n\n  /**\n   * Define your game's actions.\n   * @param actions - An object consisting of actions where the key is the name\n   * of the action and value is a function that accepts a player taking the\n   * action and returns the result of calling {@link action} and chaining\n   * choices, results and messages onto the result\n   * @category Definition\n   */\n  defineActions(actions: Record<string, (player: P) => Action<Record<string, Argument>>>) {\n    if (this._ctx.gameManager.phase !== 'new') throw Error('cannot call defineActions once started');\n    this._ctx.gameManager.actions = actions;\n  }\n\n  /**\n   * Retrieve the selected setting value for a setting defined in {@link\n   * render}.\n   * @category Definition\n   */\n  setting(key: string) {\n    return this._ctx.gameManager.settings[key];\n  }\n\n  /**\n   * Create an {@link Action}. An action is a single move that a player can\n   * take. Some actions require choices, sometimes several, before they can be\n   * executed. Some don't have any choices, like if a player can simply\n   * 'pass'. What defines where one action ends and another begins is how much\n   * you as a player can decide before you \"commit\". For example, in chess you\n   * select a piece to move and then a place to put it. These are a single move,\n   * not separate. (Unless playing touch-move, which is rarely done in digital\n   * chess.) In hearts, you pass 3 cards to another players. These are a single\n   * move, not 3. You can change your mind as you select the cards, rather than\n   * have to commit to each one. Similarly, other players do not see any\n   * information about your choices until you actually commit the entire move.\n   *\n   * This function is called for each action in the game `actions` you define in\n   * {@link defineActions}. These actions are initially declared with an optional\n   * prompt and condition. Further information is added to the action by chaining\n   * methods that add choices and behaviour. See {@link Action}.\n   *\n   * If this action accepts prior arguments besides the ones chosen by the\n   * player during the execution of this action (especially common for {@link\n   * followUp} actions) then a generic can be added for these arguments to help\n   * Typescript type these parameters, e.g.:\n   * `player => action<{ cards: number}>(...)`\n   *\n   * @param definition.prompt - The prompt that will appear for the player to\n   * explain what the action does. Further prompts can be defined for each choice\n   * they subsequently make to complete the action.\n   *\n   * @param definition.condition - A boolean or a function returning a boolean\n   * that determines whether the action is currently allowed. Note that the\n   * choices you define for your action will further determine if the action is\n   * allowed. E.g. if you have a play card action and you add a choice for cards\n   * in your hand, Boardzilla will automatically disallow this action if there\n   * are no cards in your hand based on the face that there are no valid choices\n   * to complete the action. You do not need to specify a `condition` for these\n   * types of limitations. If using the function form, the function will receive\n   * an object with any arguments passed to this action, e.g. from {@link\n   * followUp}.\n   *\n   * @example\n   * action({\n   *   prompt: 'Flip one of your cards'\n   * }).chooseOnBoard({\n   *   choices: game.all(Card, {mine: true})\n   * }).do(\n   *   card => card.hideFromAll()\n   * )\n   *\n   * @category Definition\n   */\n  action<A extends Record<string, Argument> = NonNullable<unknown>>(definition: {\n    prompt?: string,\n    description?: string,\n    condition?: Action<A>['condition'],\n  } = {}) {\n    return new Action<A>(definition);\n  }\n\n  /**\n   * Queue up a follow-up action while processing an action. If called during\n   * the processing of a game action, the follow-up action given will be added\n   * as a new action immediately following the current one, before the game's\n   * flow can resume normally. This is common for card games where the play of a\n   * certain card may require more actions be taken.\n   *\n   * @param {Object} action - The action added to the follow-up queue.\n   *\n   * @example\n   * defineAction({\n   *   ...\n   *   playCard: player => action()\n   *     .chooseOnBoard('card', cards)\n   *     .do(\n   *       ({ card }) => {\n   *         if (card.damage) {\n   *           // this card allows another action to do damage to another Card\n   *           game.followUp({\n   *             name: 'doDamage',\n   *             args: { amount: card.damage }\n   *           });\n   *         }\n   *       }\n   *     )\n   * @category Game Management\n   */\n  followUp(action: ActionStub) {\n    Do.subflow('__followup__', action);\n  }\n\n  flowGuard = (name: string): true => {\n    if (this._ctx.gameManager.phase !== 'new') {\n      throw Error(`Cannot use \"${name}\" once game has started. It is likely that this function is in the wrong place and must be called directly in defineFlow as a FlowDefinition`);\n    }\n    return true;\n  };\n\n  /**\n   * The flow commands available for this game. See:\n   * - {@link playerActions}\n   * - {@link loop}\n   * - {@link whileLoop}\n   * - {@link forEach}\n   * - {@link forLoop}\n   * - {@link eachPlayer}\n   * - {@link everyPlayer}\n   * - {@link ifElse}\n   * - {@link switchCase}\n   * @category Definition\n   */\n  flowCommands = {\n    playerActions: (options: ConstructorParameters<typeof ActionStep>[0]) => this.flowGuard('playerActions') && new ActionStep(options),\n    loop: (...block: FlowStep[]) => this.flowGuard('loop') && new WhileLoop({do: block, while: () => true}),\n    whileLoop: (options: ConstructorParameters<typeof WhileLoop>[0]) => this.flowGuard('whileloop') && new WhileLoop(options),\n    forEach: <T extends Serializable>(options: ConstructorParameters<typeof ForEach<T>>[0]) => this.flowGuard('forEach') && new ForEach<T>(options),\n    forLoop: <T = Serializable>(options: ConstructorParameters<typeof ForLoop<T>>[0]) => this.flowGuard('forloop') && new ForLoop<T>(options),\n    eachPlayer: (options: ConstructorParameters<typeof EachPlayer<P>>[0]) => this.flowGuard('eachPlayer') && new EachPlayer<P>(options),\n    everyPlayer: (options: ConstructorParameters<typeof EveryPlayer<P>>[0]) => this.flowGuard('everyplayer') && new EveryPlayer<P>(options),\n    ifElse: (options: ConstructorParameters<typeof IfElse>[0]) => this.flowGuard('ifelse') && new IfElse(options),\n    switchCase: <T extends Serializable>(options: ConstructorParameters<typeof SwitchCase<T>>[0]) => this.flowGuard('switchCase') && new SwitchCase<T>(options),\n  };\n\n  /**\n   * End the game\n   *\n   * @param winner - a player or players that are the winners of the game. In a\n   * solo game if no winner is provided, this is considered a loss.\n   * @param announcement - an optional announcement from {@link render} to\n   * replace the standard boardzilla announcement.\n   * @category Game Management\n   */\n  finish(winner?: P | P[], announcement?: string) {\n    this._ctx.gameManager.phase = 'finished';\n    if (winner) this._ctx.gameManager.winner = winner instanceof Array ? winner : [winner];\n    this._ctx.gameManager.announcements.push(announcement ?? '__finish__');\n  }\n\n  /**\n   * Return array of game winners, or undefined if game is not yet finished\n   * @category Game Management\n   */\n  getWinners() {\n    let winner = this._ctx.gameManager.winner;\n    if (!(winner instanceof Array)) winner = [winner];\n    return this._ctx.gameManager.phase === 'finished' ? winner : undefined;\n  }\n\n  /**\n   * Add a delay in the animation of the state change at this point for player\n   * as they receive game updates.\n   * @category Game Management\n   */\n  addDelay() {\n    this.resetMovementTracking();\n    if (this.game._ctx.trackMovement) {\n      this._ctx.gameManager.sequence += 1;\n    } else if (this._ctx.gameManager.intermediateUpdates.length) {\n      return; // even if not tracking, record one intermediate to allow UI to extract proper state to animate towards\n    }\n    this._ctx.gameManager.intermediateUpdates.push(this.players.map(\n      p => this._ctx.gameManager.getState(p) // TODO unnecessary for all players if in context of player\n    ));\n  }\n\n  /**\n   * Add a message that will be broadcast in the chat at the next game update,\n   * based on the current state of the game.\n   *\n   * @param text - The text of the message to send. This can contain interpolated strings\n   * with double braces, i.e. {{player}} that are defined in args. Of course,\n   * strings can be interpolated normally using template literals. However game\n   * objects (e.g. players or pieces) passed in as args will be displayed\n   * specially by Boardzilla.\n   *\n   * @param args - An object of key-value pairs of strings for interpolation in\n   * the message.\n   *\n   * @example\n   * game.message(\n   *   '{{player}} has a score of {{score}}',\n   *   { player, score: player.score() }\n   * );\n   *\n   * @category Game Management\n   */\n  message(text: string, args?: Record<string, Argument>) {\n    this._ctx.gameManager.messages.push({body: n(text, args, true)});\n  }\n\n  /**\n   * Add a message that will be broadcast to the given player(s) in the chat at\n   * the next game update, based on the current state of the game.\n   *\n   * @param player - Player or players to receive the message\n   *\n   * @param text - The text of the message to send. This can contain interpolated strings\n   * with double braces, i.e. {{player}} that are defined in args. Of course,\n   * strings can be interpolated normally using template literals. However game\n   * objects (e.g. players or pieces) passed in as args will be displayed\n   * specially by Boardzilla.\n   *\n   * @param args - An object of key-value pairs of strings for interpolation in\n   * the message.\n   *\n   * @example\n   * game.message(\n   *   '{{player}} has a score of {{score}}',\n   *   { player, score: player.score() }\n   * );\n   *\n   * @category Game Management\n   */\n  messageTo(player: (BasePlayer | number) | (BasePlayer | number)[], text: string, args?: Record<string, Argument>) {\n    if (!(player instanceof Array)) player = [player];\n    for (const p of player) {\n      this._ctx.gameManager.messages.push({\n        body: n(text, args, true),\n        position: typeof p === 'number' ? p : p.position\n      });\n    }\n  }\n\n  /**\n   * Broadcast a message to all players that interrupts the game and requires\n   * dismissal before actions can be taken.\n   *\n   * @param announcement - The modal name to announce, as provided in {@link render}.\n   *\n   * @example\n   * game.message(\n   *   '{{player}} has a score of {{score}}',\n   *   { player, score: player.score() }\n   * );\n   *\n   * @category Game Management\n   */\n  announce(announcement: string) {\n    this._ctx.gameManager.announcements.push(announcement);\n    this.addDelay();\n    this._ctx.gameManager.announcements = [];\n  }\n\n  // also gets removed elements\n  allJSON(seenBy?: number): ElementJSON[] {\n    return [this.toJSON(seenBy)].concat(\n      this._ctx.removed._t.children.map(el => el.toJSON(seenBy))\n    );\n  }\n\n  // hydrate from json, and assign all attrs. requires that players be hydrated first\n  fromJSON(boardJSON: ElementJSON[]) {\n    let { className, children, _id, order, ...rest } = boardJSON[0];\n    if (this.constructor.name !== className) throw Error(`Cannot create board from JSON. ${className} must equal ${this.constructor.name}`);\n\n    // reset all on self - think this is unnecessary? if it is, need to figure out how to use unserializableAttributes\n    for (const key of Object.keys(this)) {\n      if (!Game.unserializableAttributes.includes(key) && !(key in rest))\n        rest[key] = undefined;\n    }\n    this.createChildrenFromJSON(children || [], '0');\n    this._ctx.removed.createChildrenFromJSON(boardJSON.slice(1), '1');\n    if (order) this._t.order = order;\n\n    if (this._ctx.gameManager) rest = deserializeObject({...rest}, this);\n    Object.assign(this, {...rest});\n    this.assignAttributesFromJSON(children || [], '0');\n    this._ctx.removed.assignAttributesFromJSON(boardJSON.slice(1), '1');\n  }\n\n  // UI\n\n  _ui: ElementUI<this> & {\n    boardSize?: BoardSize,\n    boardSizes?: (screenX: number, screenY: number, mobile: boolean) => BoardSize\n    setupLayout?: (game: G, player: P, boardSize: string) => void;\n    frame?: Box; // size of the board in abs coords\n    disabledDefaultAppearance?: boolean;\n    boundingBoxes?: boolean;\n    stepLayouts: Record<string, ActionLayout>;\n    announcements: Record<string, (game: G) => JSX.Element>;\n    infoModals: {\n      title: string,\n      condition?: (game: G) => boolean,\n      modal: (game: G) => JSX.Element\n    }[];\n  } = {\n    layouts: [],\n    appearance: {},\n    stepLayouts: {},\n    announcements: {},\n    infoModals: [],\n    getBaseLayout: () => ({\n      alignment: 'center',\n      direction: 'square'\n    })\n  };\n\n  // restore default layout rules before running setupLayout\n  resetUI() {\n    super.resetUI();\n    this._ui.stepLayouts = {};\n  }\n\n  setBoardSize(boardSize: BoardSize) {\n    if (boardSize.name !== this._ui.boardSize?.name || boardSize.aspectRatio !== this._ui.boardSize?.aspectRatio) {\n      this._ui.boardSize = boardSize;\n    }\n  }\n\n  getBoardSize(screenX: number, screenY: number, mobile: boolean) {\n    return this._ui.boardSizes?.(screenX, screenY, mobile) ?? {\n      name: '_default',\n      aspectRatio: 1,\n      frame: {x:100, y:100},\n      screen: {x:100, y:100}\n    };\n  }\n\n  /**\n   * Apply default layout rules for all the placement of all player prompts and\n   * choices, in relation to the playing area\n   *\n   * @param attributes - see {@link ActionLayout}\n   *\n   * @category UI\n   */\n  layoutControls(attributes: ActionLayout) {\n    this._ui.stepLayouts[\"*\"] = attributes;\n  }\n\n  /**\n   * Apply layout rules to a particular step in the flow, controlling where\n   * player prompts and choices appear in relation to the playing area\n   *\n   * @param step - the name of the step as defined in {@link playerActions}\n   * @param attributes - see {@link ActionLayout}\n   *\n   * @category UI\n   */\n  layoutStep(step: string, attributes: ActionLayout) {\n    if (!this._ctx.gameManager.getFlowStep(step)) throw Error(`No such step: ${step}`);\n    this._ui.stepLayouts[\"step:\" + step] = attributes;\n  }\n\n  /**\n   * Apply layout rules to a particular action, controlling where player prompts\n   * and choices appear in relation to the playing area\n   *\n   * @param action - the name of the action as defined in {@link game#defineActions}\n   * @param attributes - see {@link ActionLayout}\n   *\n   * @category UI\n   */\n  layoutAction(action: string, attributes: ActionLayout) {\n    this._ui.stepLayouts[\"action:\" + action] = attributes;\n  }\n\n  /**\n   * Remove all built-in default appearance. If any elements have not been given a\n   * custom appearance, this causes them to be hidden.\n   *\n   * @category UI\n   */\n  disableDefaultAppearance() {\n    this._ui.disabledDefaultAppearance = true;\n  }\n\n  /**\n   * Show bounding boxes around every layout\n   *\n   * @category UI\n   */\n  showLayoutBoundingBoxes() {\n    this._ui.boundingBoxes = true;\n  }\n}\n"
  },
  {
    "path": "src/board/hex-grid.ts",
    "content": "import FixedGrid from \"./fixed-grid.js\";\nimport { times } from '../utils.js';\n\nimport type Game from './game.js';\nimport type { ElementUI } from \"./element.js\";\n\n/**\n * A Hex grid. Create the HexGrid with 'rows' and 'columns' values to\n * automatically create the spaces. Optionally use {@link shape} and {@link\n * axes} to customize the type of hex.\n * @category Board\n *\n * @example\n * game.create(HexGrid, 'catan-board', { rows: 5, columns: 5, shape: 'hex' })\n */\nexport default class HexGrid<G extends Game> extends FixedGrid<G> {\n\n  /**\n   * Determines which direction the rows and columns go within the\n   * hex. E.g. with east-by-southwest axes, The cell at {row: 1, column: 2} is\n   * directly east of {row: 1, column: 1}. The cell at {row: 2, column: 1} is\n   * directly southwest of {row: 1, column: 1}.\n   * @category Adjacency\n   */\n  axes: 'east-by-southwest' | 'east-by-southeast' | 'southeast-by-south' | 'northeast-by-south' = 'east-by-southwest';\n  /**\n   * Determines the overall shape of the spaces created.\n   *\n   * rhomboid - A rhomboid shape. This means a cell will exist at every row and\n   * column combination. A 3x3 rhomboid hex contains 9 cells.\n   *\n   * hex - A hex shape. This means the hex will be at most row x columns but\n   * will be missing cells at the corners. A 3x3 hex shape contains 7 cells.\n   *\n   * square - A square shape. This means the hex will be at most row x columns\n   * but will be shaped to keep a square shape. Some cells will therefore have a\n   * column value outside the range of columns. A 3x3 square hex contains 8\n   * cells, 3 on each side, and two in the middle.\n   * @category Adjacency\n   */\n  shape: 'square' | 'hex' | 'rhomboid' = 'rhomboid';\n\n  _ui: ElementUI<this> = {\n    layouts: [],\n    appearance: {},\n    getBaseLayout: () => ({\n      rows: this.rows,\n      columns: this.columns,\n      sticky: true,\n      alignment: 'center',\n      direction: 'square',\n      offsetColumn: {\n        'east-by-southwest': {x: 100, y: 0},\n        'east-by-southeast': {x: 100, y: 0},\n        'southeast-by-south': {x: 100, y: 50},\n        'northeast-by-south': {x: 100, y: -50}\n      }[this.axes],\n      offsetRow: {\n        'east-by-southwest': {x: -50, y: 100},\n        'east-by-southeast': {x: 50, y: 100},\n        'southeast-by-south': {x: 0, y: 100},\n        'northeast-by-south': {x: 0, y: 100}\n      }[this.axes]\n    })\n  };\n\n  _adjacentGridPositionsTo(column: number, row: number): [number, number][] {\n    const positions: [number, number][] = [];\n    if (column > 1) {\n      positions.push([column - 1, row]);\n      if (['east-by-southwest', 'northeast-by-south'].includes(this.axes)) {\n        positions.push([column - 1, row - 1]);\n      }\n      if (['east-by-southeast', 'southeast-by-south'].includes(this.axes)) {\n        positions.push([column - 1, row + 1]);\n      }\n    }\n    if (column < this.columns) {\n      positions.push([column + 1, row]);\n      if (['east-by-southeast', 'southeast-by-south'].includes(this.axes)) {\n        positions.push([column + 1, row - 1]);\n      }\n      if (['east-by-southwest', 'northeast-by-south'].includes(this.axes)) {\n        positions.push([column + 1, row + 1]);\n      }\n    }\n    if (row > 1) positions.push([column, row - 1]);\n    if (row < this.rows) positions.push([column, row + 1]);\n    return positions;\n  }\n\n  _gridPositions(): [number, number][] {\n    const positions: [number, number][] = [];\n    if (this.shape === 'hex') {\n      const topCorner = Math.ceil((Math.min(this.rows, this.columns) - 1) / 2);\n      const bottomCorner = Math.floor((Math.min(this.rows, this.columns) - 1) / 2);\n      const topRight = ['east-by-southwest', 'northeast-by-south'].includes(this.axes);\n      times(this.rows, row => times(this.columns - Math.max(topCorner + 1 - row, 0) - Math.max(row - this.rows + bottomCorner, 0), col => {\n        positions.push([col + Math.max(topRight ? bottomCorner + row - this.rows : topCorner - row + 1, 0), row]);\n      }));\n    } else if (this.shape === 'square') {\n      const squished = ['east-by-southeast', 'southeast-by-south'].includes(this.axes);\n      if (['east-by-southwest', 'east-by-southeast'].includes(this.axes)) {\n        times(this.rows, row => times(this.columns - (row % 2 ? 0 : 1), col => {\n          positions.push([col + (squished ? 1 - Math.ceil(row / 2) : Math.floor(row / 2)), row])\n        }));\n      } else {\n        times(this.columns, col => times(this.rows - (col % 2 ? 0 : 1), row => {\n          positions.push([col, row + (squished ? Math.floor(col / 2) : 1 - Math.ceil(col / 2))])\n        }));\n      }\n    } else {\n      times(this.rows, row => times(this.columns, col => positions.push([col, row])));\n    }\n    return positions;\n  }\n\n  _cornerPositions(): [number, number][] {\n    if (this.shape === 'hex') {\n      const topCorner = Math.ceil((Math.min(this.rows, this.columns) - 1) / 2);\n      const bottomCorner = Math.floor((Math.min(this.rows, this.columns) - 1) / 2);\n      if (['east-by-southwest', 'northeast-by-south'].includes(this.axes)) {\n        return [\n          [1, 1],\n          [this.columns - topCorner, 1],\n          [1, Math.floor(this.rows / 2) + 1],\n          [this.columns, Math.floor(this.rows / 2) + 1],\n          [1 + bottomCorner, this.rows],\n          [this.columns, this.rows],\n        ];\n      } else {\n        return [\n          [1 + topCorner, 1],\n          [this.columns, 1],\n          [1, Math.floor(this.rows / 2) + 1],\n          [this.columns, Math.floor(this.rows / 2) + 1],\n          [1, this.rows],\n          [this.columns - bottomCorner, this.rows],\n        ];\n      }\n    } else if (this.shape === 'square') {\n      if (['east-by-southwest'].includes(this.axes)) {\n        return [\n          [1, 1],\n          [this.columns, 1],\n          [1 + Math.floor(this.rows / 2), this.rows],\n          [this.columns - 1 + Math.ceil(this.rows / 2), this.rows],\n        ];\n      } else if (['east-by-southeast'].includes(this.axes)) {\n        return [\n          [1, 1],\n          [this.columns, 1],\n          [2 - Math.ceil(this.rows / 2), this.rows],\n          [this.columns - Math.floor(this.rows / 2), this.rows],\n        ];\n      } else if (['southeast-by-south'].includes(this.axes)) {\n        return [\n          [1, 1],\n          [1, this.rows],\n          [this.columns, 2 - Math.ceil(this.columns / 2)],\n          [this.columns, this.rows - Math.floor(this.columns / 2)],\n        ];\n      } else {\n        return [\n          [1, 1],\n          [1, this.rows],\n          [this.columns, 1 + Math.floor(this.columns / 2)],\n          [this.columns, this.rows - 1 + Math.ceil(this.columns / 2)],\n        ];\n      }\n    }\n    return [\n      [1, 1],\n      [this.columns, 1],\n      [1, this.rows],\n      [this.columns, this.rows],\n    ];\n  }\n}\n"
  },
  {
    "path": "src/board/index.ts",
    "content": "import GameElement from './element.js';\nimport ElementCollection from './element-collection.js';\nexport { GameElement, ElementCollection };\nexport { default as Space } from './space.js';\nexport { default as Piece } from './piece.js';\nexport { default as Stack } from './stack.js';\nexport { default as AdjacencySpace } from './adjacency-space.js';\nexport { default as ConnectedSpaceMap } from './connected-space-map.js';\nexport { default as FixedGrid } from './fixed-grid.js';\nexport { default as SquareGrid } from './square-grid.js';\nexport { default as HexGrid } from './hex-grid.js';\nexport { default as PieceGrid } from './piece-grid.js';\nexport { default as Game } from './game.js';\n\nexport type { ActionLayout } from './game.js';\nexport type { LayoutAttributes, Box, Vector } from './element.js';\nexport type { ElementFinder, Sorter } from './element-collection.js';\n\n/**\n * Returns an {@link ElementCollection} by combining a list of {@link\n * GameElement}'s or {@link ElementCollection}'s,\n * @category Flow\n */\nexport function union<T extends GameElement>(...queries: (T | ElementCollection<T> | undefined)[]): ElementCollection<T> {\n  let c = new ElementCollection<T>();\n  for (const q of queries) {\n    if (q) {\n      if ('forEach' in q) {\n        q.forEach(e => c.includes(e) || c.push(e));\n      } else if (!c.includes(q)) {\n        c.push(q);\n      }\n    }\n  }\n  return c;\n}\n"
  },
  {
    "path": "src/board/piece-grid.ts",
    "content": "import AdjacencySpace from \"./adjacency-space.js\";\nimport { rotateDirection } from './utils.js';\nimport Space from '../board/space.js';\n\nimport type Game from './game.js'\nimport type Piece from './piece.js'\nimport type { default as GameElement, Vector, Direction, DirectionWithDiagonals } from \"./element.js\";\nimport type { ElementContext, ElementUI } from './element.js';\n\n/**\n * A grid that tracks adjacency for pieces placed within it. This is useful for\n * tile placement games, e.g. dominoes. Only pieces can be placed in a PieceGrid\n * and each must have a column and row. Pieces that have been assigned irregular\n * shapes using {@link Piece#setShape} will be rendered as taking up more than a\n * single cell in the grid, depending on their shape. Adjacency is calculated\n * for the entire shape.\n * @category Board\n */\nexport default class PieceGrid<G extends Game> extends AdjacencySpace<G> {\n\n  /**\n   * If true, the space will be automatically enlarged when new places are added\n   * using {@link Action#placePiece}.\n   * @category Adjacency\n   */\n  extendableGrid: boolean = true;\n  /**\n   * Initial number of rows to render, but this can increase if {@link\n   * extendableGrid} is true.\n   * @category Adjacency\n   */\n  rows: number = 1;\n  /**\n   * Initial number of columns to render, but this can increase if {@link\n   * extendableGrid} is true.\n   * @category Adjacency\n   */\n  columns: number = 1;\n  /**\n   * Whether to consider tiles that touch at the corners to be adjacent when\n   * using adjacenciesByCell.\n   * @category Adjacency\n   */\n  diagonalAdjacency: boolean = false\n\n  _ui: ElementUI<this> = {\n    layouts: [],\n    appearance: {},\n    getBaseLayout: () => ({\n      rows: this.rows,\n      columns: this.columns,\n      aspectRatio: 1,\n      alignment: 'center',\n      direction: 'square'\n    })\n  };\n\n  constructor(ctx: ElementContext) {\n    super(ctx);\n    this.onEnter(Space, () => { throw Error(`Only pieces can be added to the PieceGrid ${this.name}`) });\n  }\n\n  isAdjacent(el1: GameElement, el2: GameElement): boolean {\n    return this.adjacenciesByCell(el1 as Piece<G>, el2 as Piece<G>).length > 0;\n  }\n\n  _sizeNeededFor(element: GameElement) {\n    if (!element._size) return {width: 1, height: 1};\n    if (element.rotation % 180 === 90) return {\n      width: element._size.height,\n      height: element._size.width\n    }\n    return {\n      width: element._size.width,\n      height: element._size.height\n    }\n  }\n\n  // internal\n  cellsAround(piece: Piece<G>, pos: Vector) {\n    const adjacencies: Partial<Record<DirectionWithDiagonals, string>> = {\n      up: piece._cellAt({y: pos.y - 1, x: pos.x}),\n      down: piece._cellAt({y: pos.y + 1, x: pos.x}),\n      left: piece._cellAt({y: pos.y, x: pos.x - 1}),\n      right: piece._cellAt({y: pos.y, x: pos.x + 1})\n    };\n    if (this.diagonalAdjacency) {\n      adjacencies.upleft = piece._cellAt({y: pos.y - 1, x: pos.x - 1});\n      adjacencies.upright = piece._cellAt({y: pos.y - 1, x: pos.x + 1});\n      adjacencies.downleft = piece._cellAt({y: pos.y + 1, x: pos.x - 1});\n      adjacencies.downright = piece._cellAt({y: pos.y + 1, x: pos.x + 1});\n    }\n    return adjacencies;\n  }\n\n  // internal\n  isOverlapping(piece: Piece<G>, other?: Piece<G>): boolean {\n    if (!other) {\n      return this._t.children.some(p => p !== piece && this.isOverlapping(piece, p as Piece<G>));\n    }\n    const p1: Vector = {x: piece.column!, y: piece.row!};\n    const p2: Vector = {x: other.column!, y: other.row!};\n    if (!piece._size && !other._size) return p2.y === p1.y && p2.x === p1.x;\n    if (piece.rotation % 90 !== 0 || other.rotation % 90 !== 0) return false; // unsupported to calculate for irregular shapes at non-orthoganal orientations\n    if (!piece._size) return (other._cellAt({y: p1.y - p2.y, x: p1.x - p2.x}) ?? ' ') !== ' ';\n    if (!other._size) return (piece._cellAt({y: p2.y - p1.y, x: p2.x - p1.x}) ?? ' ') !== ' ';\n    const gridSize1 = this._sizeNeededFor(piece);\n    const gridSize2 = this._sizeNeededFor(other);\n    if (\n      p2.y >= p1.y + gridSize1.height ||\n      p2.y + gridSize2.height <= p1.y ||\n      p2.x >= p1.x + gridSize1.width ||\n      p2.x + gridSize2.width <= p1.x\n    ) return false;\n    const size = Math.max(piece._size.height, piece._size.width);\n    for (let x = 0; x !== size; x += 1) {\n      for (let y = 0; y !== size; y += 1) {\n        if ((piece._cellAt({x, y}) ?? ' ') !== ' ' && (other._cellAt({x: x + p1.x - p2.x, y: y + p1.y - p2.y}) ?? ' ') !== ' ') {\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n\n  // internal\n  _fitPieceInFreePlace(piece: Piece<G>, rows: number, columns: number, origin: {column: number, row: number}) {\n    const tryLaterally = (vertical: boolean, d: number): boolean => {\n      for (let lateral = 0; lateral < d + (vertical ? 0 : 1); lateral = -lateral + (lateral < 1 ? 1 : 0)) {\n        if (vertical) {\n          if (row + lateral <= 0 || row + lateral + gridSize.height - 1 > rows) continue;\n          piece.row = row + lateral + origin.row - 1;\n        } else {\n          if (column + lateral <= 0 || column + lateral + gridSize.width - 1 > columns) continue;\n          piece.column = column + lateral + origin.column - 1;\n        }\n        if (!this.isOverlapping(piece)) return true;\n      }\n      return false;\n    }\n\n    let gridSize = this._sizeNeededFor(piece);\n    piece._rotation ??= 0;\n    const row = piece.row === undefined ? Math.floor((rows - gridSize.height) / 2) : piece.row - origin.row + 1;\n    const column = piece.column === undefined ? Math.floor((columns - gridSize.width) / 2) : piece.column - origin.column + 1;\n    let possibleRotations = [piece._rotation, ...(piece._size ? [piece._rotation + 90, piece._rotation + 180, piece._rotation + 270] : [])];\n    while (possibleRotations.length) {\n      piece._rotation = possibleRotations.shift()!;\n      gridSize = this._sizeNeededFor(piece);\n      for (let distance = 0; distance < rows || distance < columns; distance += 1) {\n        if (column - distance > 0 && column - distance + gridSize.width - 1 <= columns) {\n          piece.column = column - distance + origin.column - 1;\n          if (tryLaterally(true, distance || 1)) return;\n        }\n        if (distance && column + distance > 0 && column + distance + gridSize.width - 1 <= columns) {\n          piece.column = column + distance + origin.column - 1;\n          if (tryLaterally(true, distance)) return;\n        }\n        if (distance && row - distance > 0 && row - distance + gridSize.height - 1 <= rows) {\n          piece.row = row - distance + origin.row - 1;\n          if (tryLaterally(false, distance)) return;\n        }\n        if (distance && row + distance > 0 && row + distance + gridSize.height - 1 <= rows) {\n          piece.row = row + distance + origin.row - 1;\n          if (tryLaterally(false, distance)) return;\n        }\n      }\n    }\n    piece.row = undefined;\n    piece.column = undefined;\n  }\n\n  /**\n   * Returns a list of other Pieces in the grid that have a touching edge (or\n   * touching corner if {@link diagonalAdjacency} is true} with this shape. Each\n   * item in the list contains the adjacent Piece, as well as the string\n   * representation of cells in both pieces, as provided in {@link\n   * Piece#setShape}.\n   * @category Adjacency\n   *\n   * @param piece - The piece to check for adjacency\n   * @param other - An optional other piece to check against. If undefined, it\n   * will check for all pieces against the first argument\n   *\n   * @example\n   *\n   * A domino named \"domino12\" is adjacent to a domino named \"domino34\" with the\n   * 2 touching the 3:\n   *\n   * domino12.setShape('12');\n   * domino34.setShape('34');\n   * board.adjacenciesByCell(domino12) =>\n   *    [\n   *      {\n   *        piece: domino34,\n   *        from: '2',\n   *        to: '3'\n   *      }\n   *    ]\n   */\n  adjacenciesByCell(piece: Piece<G>, other?: Piece<G>): {piece: Piece<G>, from: string, to: string}[] {\n    if (!other) {\n      return this._t.children.reduce(\n        (all, p) => all.concat(p !== piece ? this.adjacenciesByCell(piece, p as Piece<G>) : []),\n        [] as {piece: Piece<G>, from: string, to: string}[]\n      );\n    }\n    const p1: Vector = {x: piece.column!, y: piece.row!};\n    const p2: Vector = {x: other.column!, y: other.row!};\n\n    // unsupported to calculate at non-orthoganal orientations\n    if (p1.y === undefined || p1.x === undefined || piece.rotation % 90 !== 0 || p2.y === undefined || p2.x === undefined || other.rotation % 90 !== 0) return [];\n\n    if (!piece._size) {\n      return Object.values(this.cellsAround(other, {x: p1.x - p2.x, y: p1.y - p2.y})).reduce(\n        (all, adj) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: '.', to: adj}] : []),\n        [] as {piece: Piece<G>, from: string, to: string}[]\n      );\n    }\n    if (!other._size) {\n      return Object.values(this.cellsAround(piece, {x: p2.x - p1.x, y: p2.y - p1.y})).reduce(\n        (all, adj) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: adj, to: '.'}] : []),\n        [] as {piece: Piece<G>, from: string, to: string}[]\n      );\n    }\n    const gridSize1 = this._sizeNeededFor(piece);\n    const gridSize2 = this._sizeNeededFor(other);\n    if (\n      p2.y >= p1.y + 1 + gridSize1.height ||\n      p2.y + 1 + gridSize2.height <= p1.y ||\n      p2.x >= p1.x + 1 + gridSize1.width ||\n      p2.x + 1 + gridSize2.width <= p1.x\n    ) return [];\n    const size = Math.max(piece._size.height, piece._size.width);\n    const adjacencies = [] as {piece: Piece<G>, from: string, to: string}[];\n    for (let x = 0; x !== size; x += 1) {\n      for (let y = 0; y !== size; y += 1) {\n        const thisCell = piece._cellAt({x, y});\n        if (thisCell === undefined || thisCell === ' ') continue;\n        for (const cell of Object.values(this.cellsAround(other, {x: x + p1.x - p2.x, y: y + p1.y - p2.y}))) {\n          if (cell !== undefined && cell !== ' ') {\n            adjacencies.push({piece: other, from: thisCell, to: cell});\n          }\n        }\n      }\n    }\n    return adjacencies;\n  }\n\n  /**\n   * Returns a list of other Pieces in the grid that have a touching edge with\n   * this shape. Each item in the list contains the adjacent Piece, as well as\n   * the string representation of the edges in both pieces, as provided in\n   * {@link Piece#setEdges}.\n   * @category Adjacency\n   *\n   * @param piece - The piece to check for adjacency\n   * @param other - An optional other piece to check against. If undefined, it\n   * will check for all pieces against the first argument\n   *\n   * @example\n   *\n   * A tile named \"corner\" is adjacent directly to the left of a tile named\n   * \"bridge\".\n   *\n   * corner.setEdges({\n   *   up: 'road',\n   *   right: 'road'\n   * });\n   *\n   * bridge.setEdges({\n   *   up: 'river',\n   *   down: 'river',\n   *   left: 'road'\n   *   right: 'road'\n   * });\n   *\n   * board.adjacenciesByCell(corner) =>\n   *    [\n   *      {\n   *        piece: bridge,\n   *        from: 'road',\n   *        to: 'road'\n   *      }\n   *    ]\n   */\n  adjacenciesByEdge(piece: Piece<G>, other?: Piece<G>): {piece: Piece<G>, from?: string, to?: string}[] {\n    if (!other) {\n      const children = this._t.children;\n      return children.reduce(\n        (all, p) => all.concat(p !== piece ? this.adjacenciesByEdge(piece, p as Piece<G>) : []),\n        [] as {piece: Piece<G>, from?: string, to?: string}[]\n      );\n    }\n    const p1: Vector = {x: piece.column!, y: piece.row!};\n    const p2: Vector = {x: other.column!, y: other.row!};\n    if (p2.y === undefined || p2.x === undefined || other.rotation % 90 !== 0) return [];\n\n    if (piece.rotation % 90 !== 0 || other.rotation % 90 !== 0) return []; // unsupported to calculate at non-orthoganal orientations\n    if (!piece._size) {\n      return (Object.entries(this.cellsAround(other, {x: p1.x - p2.x, y: p1.y - p2.y})) as [Direction, string][]).reduce(\n        (all, [dir, adj]) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: undefined, to: other._size?.edges?.[adj][rotateDirection(dir, 180 - other.rotation)]}] : []),\n        [] as {piece: Piece<G>, from?: string, to?: string}[]\n      );\n    }\n    if (!other._size) {\n      return (Object.entries(this.cellsAround(piece, {x: p2.x - p1.x, y: p2.y - p1.y})) as [Direction, string][]).reduce(\n        (all, [dir, adj]) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: piece._size?.edges?.[adj][rotateDirection(dir, 180 - piece.rotation)], to: undefined}] : []),\n        [] as {piece: Piece<G>, from?: string, to?: string}[]\n      );\n    }\n    const gridSize1 = this._sizeNeededFor(piece);\n    const gridSize2 = this._sizeNeededFor(other);\n    if (\n      p2.y >= p1.y + 1 + gridSize1.height ||\n      p2.y + 1 + gridSize2.height <= p1.y ||\n      p2.x >= p1.x + 1 + gridSize1.width ||\n      p2.x + 1 + gridSize2.width <= p1.x\n    ) return [];\n    const size = Math.max(piece._size.height, piece._size.width);\n    const adjacencies = [] as {piece: Piece<G>, from?: string, to?: string}[];\n    for (let x = 0; x !== size; x += 1) {\n      for (let y = 0; y !== size; y += 1) {\n        const thisCell = piece._cellAt({x, y});\n        if (thisCell === undefined || thisCell === ' ') continue;\n        for (const [dir, cell] of Object.entries(this.cellsAround(other, {x: x + p1.x - p2.x, y: y + p1.y - p2.y})) as [Direction, string][]) {\n          if (cell !== undefined && cell !== ' ') {\n            adjacencies.push({\n              piece: other,\n              from: piece._size?.edges?.[thisCell][rotateDirection(dir, -piece.rotation)],\n              to: other._size?.edges?.[cell][rotateDirection(dir, 180 - other.rotation)]\n            });\n          }\n        }\n      }\n    }\n    return adjacencies;\n  }\n}\n"
  },
  {
    "path": "src/board/piece.ts",
    "content": "import GameElement from './element.js'\nimport Space from './space.js'\n\nimport type { ElementAttributes, ElementClass } from './element.js'\nimport type Game from './game.js'\nimport type Player from '../player/player.js';\nimport type { BaseGame } from './game.js';\n\n/**\n * Pieces are game elements that can move during play\n * @category Board\n */\nexport default class Piece<G extends Game, P extends Player = NonNullable<G['player']>> extends GameElement<G, P> {\n\n  _visible?: {\n    default: boolean,\n    except?: number[]\n  }\n\n  createElement<T extends GameElement>(className: ElementClass<T>, name: string, attrs?: ElementAttributes<T>): T {\n    if (className === Space as unknown as ElementClass<T> || Object.prototype.isPrototypeOf.call(Space, className)) {\n      throw Error(`May not create Space \"${name}\" in Piece \"${this.name}\"`);\n    }\n    return super.createElement(className, name, attrs);\n  }\n\n  /**\n   * Show this piece to all players\n   * @category Visibility\n   */\n  showToAll() {\n    delete(this._visible);\n  }\n\n  /**\n   * Show this piece only to the given player\n   * @category Visibility\n   */\n  showOnlyTo(player: Player | number) {\n    if (typeof player !== 'number') player = player.position;\n    this._visible = {\n      default: false,\n      except: [player]\n    };\n  }\n\n  /**\n   * Show this piece to the given players without changing it's visibility to\n   * any other players.\n   * @category Visibility\n   */\n  showTo(...player: Player[] | number[]) {\n    if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position);\n    if (this._visible === undefined) return;\n    if (this._visible.default) {\n      if (!this._visible.except) return;\n      this._visible.except = this._visible.except.filter(i => !(player as number[]).includes(i));\n    } else {\n      this._visible.except = Array.from(new Set([...(this._visible.except instanceof Array ? this._visible.except : []), ...(player as number[])]))\n    }\n  }\n\n  /**\n   * Hide this piece from all players\n   * @category Visibility\n   */\n  hideFromAll() {\n    this._visible = {default: false};\n  }\n\n  /**\n   * Hide this piece from the given players without changing it's visibility to\n   * any other players.\n   * @category Visibility\n   */\n  hideFrom(...player: Player[] | number[]) {\n    if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position);\n    if (this._visible?.default === false && !this._visible.except) return;\n    if (this._visible === undefined || this._visible.default === true) {\n      this._visible = {\n        default: true,\n        except: Array.from(new Set([...(this._visible?.except instanceof Array ? this._visible.except : []), ...(player as number[])]))\n      };\n    } else {\n      if (!this._visible.except) return;\n      this._visible.except = this._visible.except.filter(i => !(player as number[]).includes(i));\n    }\n  }\n\n  /**\n   * Returns whether this piece is visible to the given player\n   * @category Visibility\n   */\n  isVisibleTo(player: Player | number) {\n    if (typeof player !== 'number') player = player.position;\n    if (this._visible === undefined) return true;\n    if (this._visible.default) {\n      return !this._visible.except || !(this._visible.except.includes(player));\n    } else {\n      return this._visible.except?.includes(player) || false;\n    }\n  }\n\n  /**\n   * Returns whether this piece is visible to all players, or to the current\n   * player if called when in a player context (during an action taken by a\n   * player or while the game is viewed by a given player.)\n   * @category Visibility\n   */\n  isVisible() {\n    if (this._ctx.player) return this.isVisibleTo(this._ctx.player.position);\n    return this._visible?.default !== false && (this._visible?.except ?? []).length === 0;\n  }\n\n  /**\n   * Provide list of attributes that remain visible even when these pieces are\n   * not visible to players. E.g. In a game with multiple card decks with\n   * different backs, identified by Card#deck, the identity of the card when\n   * face-down is hidden, but the deck it belongs to is not, since the card art\n   * on the back would identify the deck. In this case calling\n   * `Card.revealWhenHidden('deck')` will cause all attributes other than 'deck'\n   * to be hidden when the card is face down, while still revealing which deck\n   * it is.\n   * @category Visibility\n   */\n  static revealWhenHidden<T extends Piece<BaseGame>>(this: ElementClass<T>, ...attrs: (string & keyof T)[]): void {\n    this.visibleAttributes = attrs;\n  }\n\n  /**\n   * Move this piece into another element. This triggers any {@link\n   * Space#onEnter | onEnter} callbacks in the destination.\n   * @category Structure\n   *\n   * @param to - Destination element\n   * @param options.position - Place the piece into a specific numbered position\n   * relative to the other elements in this space. Positive numbers count from\n   * the beginning. Negative numbers count from the end.\n   * @param options.fromTop - Place the piece into a specific numbered position counting\n   * from the first element\n   * @param options.fromBottom - Place the piece into a specific numbered position\n   * counting from the last element\n   */\n  putInto(to: GameElement, options?: {position?: number, row?: number, column?: number, fromTop?: number, fromBottom?: number}) {\n    if (to.isDescendantOf(this)) throw Error(`Cannot put ${this} into itself`);\n    let pos: number = to._t.order === 'stacking' ? 0 : to._t.children.length;\n    if (options?.position !== undefined) pos = options.position >= 0 ? options.position : to._t.children.length + options.position + 1;\n    if (options?.fromTop !== undefined) pos = options.fromTop;\n    if (options?.fromBottom !== undefined) pos = to._t.children.length - options.fromBottom;\n    const previousParent = this._t.parent;\n    const position = this.position();\n    if (this.hasMoved() || to.hasMoved()) this.game.addDelay();\n    const refs = previousParent === to && options?.row === undefined && options?.column === undefined && to.childRefsIfObscured();\n    this._t.parent!._t.children.splice(position, 1);\n    this._t.parent = to;\n    to._t.children.splice(pos, 0, this);\n    if (refs) to.assignChildRefs(refs);\n\n    if (previousParent !== to && previousParent instanceof Space) previousParent.triggerEvent(\"exit\", this);\n    if (previousParent !== to && this._ctx.trackMovement) this._t.moved = true;\n\n    delete this.column;\n    delete this.row;\n    if (options?.row !== undefined) this.row = options.row;\n    if (options?.column !== undefined) this.column = options.column;\n\n    if (previousParent !== to && to instanceof Space) to.triggerEvent(\"enter\", this);\n  }\n\n  cloneInto<T extends GameElement>(this: T, into: GameElement): T {\n    let attrs = this.attributeList();\n    delete attrs.column;\n    delete attrs.row;\n\n    const clone = into.createElement(this.constructor as ElementClass<T>, this.name, attrs);\n    if (into._t.order === 'stacking') {\n      into._t.children.unshift(clone);\n    } else {\n      into._t.children.push(clone);\n    }\n    clone._t.parent = into;\n    clone._t.order = this._t.order;\n    for (const child of this._t.children) if (child instanceof Piece) child.cloneInto(clone);\n    return clone;\n  }\n\n  /**\n   * Remove this piece from the playing area and place it into {@link\n   * Game#pile}\n   * @category Structure\n   */\n  remove() {\n    return this.putInto(this._ctx.removed);\n  }\n}\n"
  },
  {
    "path": "src/board/single-layout.ts",
    "content": "import Space from './space.js';\n\nimport type { BaseGame } from './game.js';\nimport type { ElementUI } from './element.js';\n\n/**\n * Abstract base class for all adjacency spaces\n */\nexport default abstract class SingleLayout<G extends BaseGame> extends Space<G> {\n\n  _ui: ElementUI<this> = {\n    layouts: [],\n    appearance: {},\n    getBaseLayout: () => ({\n      alignment: 'center',\n      direction: 'square'\n    })\n  };\n\n  /**\n   * Single layout space can only contain elements of a certain type. Rather\n   * than adding multiple, overlapping layouts for different elements, there is\n   * a single layout that can be modified using {@link configureLayout}.\n   * @category UI\n   */\n  layout() {\n    throw Error(\"Space cannot have additional layouts added. The layout can instead be configured with configureLayout.\");\n  }\n\n  resetUI() {\n    if (!this._ui.layouts.length) this.configureLayout({});\n    this._ui.appearance = {};\n    for (const child of this._t.children) child.resetUI();\n  }\n}\n"
  },
  {
    "path": "src/board/space.ts",
    "content": "import GameElement from './element.js'\n\nimport type { BaseGame } from './game.js';\nimport type Player from '../player/player.js';\nimport type { ElementClass, ElementAttributes } from './element.js';\nimport { Piece } from '../index.js';\n\nexport type ElementEventHandler<T extends GameElement> = {callback: (el: T) => void} & Record<any, any>;\n\n/**\n * Spaces are areas of the game. The spaces of your game are declared during\n * setup in {@link createGame} and never change during play.\n * @category Board\n */\nexport default class Space<G extends BaseGame, P extends Player = NonNullable<G['player']>> extends GameElement<G, P> {\n\n  static unserializableAttributes = [...GameElement.unserializableAttributes, '_eventHandlers', '_visOnEnter', '_screen'];\n\n  _eventHandlers: {\n    enter: ElementEventHandler<GameElement>[],\n    exit: ElementEventHandler<GameElement>[],\n  } = { enter: [], exit: [] };\n\n  _visOnEnter?: {\n    default: boolean,\n    except?: number[] | 'owner'\n  }\n\n  _screen?: 'all' | 'all-but-owner' | number[];\n\n  /**\n   * Show pieces to all players when they enter this space\n   * @category Visibility\n   */\n  contentsWillBeShown() {\n    this._visOnEnter = {default: true};\n  }\n\n  /**\n   * Show pieces when they enter this space to its owner\n   * @category Visibility\n   */\n  contentsWillBeShownToOwner() {\n    this._visOnEnter = {default: false, except: 'owner'};\n  }\n\n  /**\n   * Show piece to these players when they enter this space\n   * @category Visibility\n   */\n  contentsWillBeShownTo(...players: P[]) {\n    this._visOnEnter = {default: false, except: players.map(p => p.position)};\n  }\n\n  /**\n   * Hide pieces to all players when they enter this space\n   * @category Visibility\n   */\n  contentsWillBeHidden() {\n    this._visOnEnter = {default: false};\n  }\n\n  /**\n   * Hide piece to these players when they enter this space\n   * @category Visibility\n   */\n  contentsWillBeHiddenFrom(...players: P[]) {\n    this._visOnEnter = {default: true, except: players.map(p => p.position)};\n  }\n\n  /**\n   * Call this to screen view completely from players. Blocked spaces completely\n   * hide their contents, like a physical screen. No information about the\n   * number, type or movement of contents inside this Space will be revealed to\n   * the specified players\n   *\n   * @param players = Players for whom the view is blocked\n   * @category Visibility\n   */\n  blockViewFor(players: 'all' | 'none' | 'all-but-owner' | Player[]) {\n    this._screen = players === 'none' ? undefined : players instanceof Array ? players.map(p => p.position) : players\n  }\n\n  isSpace() { return true; }\n\n  create<T extends GameElement>(className: ElementClass<T>, name: string, attributes?: ElementAttributes<T>): T {\n    const el = super.create(className, name, attributes);\n    if ('showTo' in el) this.triggerEvent(\"enter\", el as unknown as Piece<G>);\n    return el;\n  }\n\n  addEventHandler<T extends GameElement>(type: keyof Space<G>['_eventHandlers'], handler: ElementEventHandler<T>) {\n    if (this._ctx.gameManager?.phase === 'started') throw Error('Event handlers cannot be added once game has started.');\n    this._eventHandlers[type].push(handler);\n  }\n\n  /**\n   * Attach a callback to this space for every element that enters or is created\n   * within.\n   * @category Structure\n   *\n   * @param type - the class of element that will trigger this callback\n   * @param callback - Callback will be called each time an element enters, with\n   * the entering element as the only argument.\n   *\n   * @example\n   * deck.onEnter(Card, card => card.hideFromAll()) // card placed in the deck are automatically turned face down\n   */\n  onEnter<T extends GameElement>(type: ElementClass<T>, callback: (el: T) => void) {\n    this.addEventHandler<T>(\"enter\", { callback, type });\n  }\n\n  /**\n   * Attach a callback to this space for every element that is moved out of this\n   * space.\n   * @category Structure\n   *\n   * @param type - the class of element that will trigger this callback\n   * @param callback - Callback will be called each time an element exits, with\n   * the exiting element as the only argument.\n   *\n   * @example\n   * deck.onExit(Card, card => card.showToAll()) // cards drawn from the deck are automatically turned face up\n   */\n  onExit<T extends GameElement>(type: ElementClass<T>, callback: (el: T) => void) {\n    this.addEventHandler<T>(\"exit\", { callback, type });\n  }\n\n  triggerEvent(event: keyof Space<G>['_eventHandlers'], element: Piece<G>) {\n    if (this._visOnEnter) {\n      element._visible = {\n        default: this._visOnEnter.default,\n        except: this._visOnEnter.except === 'owner' ? (this.owner ? [this.owner.position] : undefined) : this._visOnEnter.except\n      }\n    }\n\n    for (const handler of this._eventHandlers[event]) {\n      if (event === 'enter' && !(element instanceof handler.type)) continue;\n      if (event === 'exit' && !(element instanceof handler.type)) continue;\n      handler.callback(element);\n    }\n  }\n}\n"
  },
  {
    "path": "src/board/square-grid.ts",
    "content": "import FixedGrid from \"./fixed-grid.js\";\nimport { times } from '../utils.js';\n\nimport type Game from './game.js';\n\n/**\n * A Square grid. Create the SquareGrid with 'rows' and 'columns' values to\n * automatically create the spaces.\n * @category Board\n *\n * @example\n * game.create(SquareGrid, 'chess-board', { rows: 8, columns: 8 })\n */\nexport default class SquareGrid<G extends Game> extends FixedGrid<G> {\n  /**\n   * Optionally add a measurement for diagonal adjacencies on this grid. If\n   * undefined, diagonals are not considered directly adjacent.\n   * @category Adjacency\n   */\n  diagonalDistance?: number;\n\n  _adjacentGridPositionsTo(column: number, row: number): [number, number, number?][] {\n    const positions: [number, number, number?][] = [];\n    if (column > 1) {\n      positions.push([column - 1, row]);\n      if (this.diagonalDistance !== undefined) {\n        positions.push([column - 1, row - 1, this.diagonalDistance]);\n        positions.push([column - 1, row + 1, this.diagonalDistance]);\n      }\n    }\n    if (column < this.columns) {\n      positions.push([column + 1, row]);\n      if (this.diagonalDistance !== undefined) {\n        positions.push([column + 1, row - 1, this.diagonalDistance]);\n        positions.push([column + 1, row + 1, this.diagonalDistance]);\n      }\n    }\n    positions.push([column, row - 1]);\n    positions.push([column, row + 1]);\n    return positions;\n  }\n\n  _gridPositions(): [number, number][] {\n    const positions: [number, number][] = [];\n    times(this.rows, row => times(this.columns, col => positions.push([col, row])));\n    return positions;\n  }\n}\n"
  },
  {
    "path": "src/board/stack.ts",
    "content": "import SingleLayout from './single-layout.js';\n\nimport type { BaseGame } from './game.js';\nimport type { ElementUI } from './element.js';\n\n/**\n * A Stack hides all movement information within to avoid exposing the identity\n * of pieces inside the stack. Useful for decks of cards where calling\n * `shuffle()` should prevent players from knowing the order of the cards. By\n * default elements in a stack are hidden and are rendered as a stack with a\n * small offset and a limited number of items. Use configureLayout to change\n * this.\n */\nexport default class Stack<G extends BaseGame> extends SingleLayout<G> {\n  _ui: ElementUI<this> = {\n    layouts: [],\n    appearance: {},\n    getBaseLayout: () => ({\n      columns: 1,\n      offsetRow: { x: 2, y: 2 },\n      scaling: 'fit',\n      alignment: 'center',\n      direction: 'ltr',\n      limit: 10,\n    })\n  };\n\n  afterCreation() {\n    this._t.order = 'stacking';\n    this.contentsWillBeHidden();\n  }\n}\n"
  },
  {
    "path": "src/board/utils.ts",
    "content": "import type { Direction } from './element.js';\n\nexport function rotateDirection(dir: Direction, rotation: number) {\n  rotation = (rotation % 360 + 360) % 360;\n  if (rotation === 0) return dir;\n  let angle: number;\n  if (dir === 'up') {\n    angle = rotation;\n  } else if (dir === 'down') {\n    angle = (rotation + 180) % 360;\n  } else if (dir === 'right') {\n    angle = (rotation + 90) % 360;\n  } else {\n    angle = (rotation + 270) % 360;\n  }\n\n  if (angle === 0) {\n    return 'up';\n  } else if (angle === 90) {\n    return 'right';\n  } else if (angle === 180) {\n    return 'down';\n  }\n  return 'left';\n}\n"
  },
  {
    "path": "src/components/d6/assets/index.scss",
    "content": ".D6 {\n  > ol {\n    display: grid;\n    grid-template-columns: 1fr;\n    grid-template-rows: 1fr;\n    list-style-type: none;\n    transform-style: preserve-3d;\n    width: 100%;\n    height: 100%;\n    margin: 0;\n    padding: 0;\n    &[data-spin=\"up\"] {\n      transition: transform 2s ease-out;\n    }\n    &[data-spin=\"down\"] {\n      transition: transform 2s ease-out;\n    }\n    .die-face {\n      background: #eee;\n      box-shadow: inset 0 0 0.4em rgba(0, 0, 0, 0.4);\n      border-radius: .3em;\n      display: grid;\n      grid-column: 1;\n      grid-row: 1;\n      grid-template-areas:\n        \"one two three\"\n        \"four five six\"\n        \"sup eight nine\";\n      grid-template-columns: repeat(3, 1fr);\n      grid-template-rows: repeat(3, 1fr);\n      height: 100%;\n      padding: .7em;\n      width: 100%;\n      outline: .01em solid #333;\n      .dot {\n        align-self: center;\n        background-color: #333;\n        border-radius: 50%;\n        box-shadow: inset -0.12em 0.12em 0.25em rgba(255, 255, 255, 0.3);\n        display: block;\n        height: 1.25em;\n        justify-self: center;\n        width: 1.25em;\n      }\n      &[data-face=\"1\"] {\n        transform: rotate3d(0, 0, 0, 90deg) translateZ(3.1em);\n      }\n      &[data-face=\"2\"] {\n        transform: rotate3d(-1, 0, 0, 90deg) translateZ(3.1em);\n      }\n      &[data-face=\"3\"] {\n        transform: rotate3d(0, 1, 0, 90deg) translateZ(3.1em);\n      }\n      &[data-face=\"4\"] {\n        transform: rotate3d(0, -1, 0, 90deg) translateZ(3.1em);\n      }\n      &[data-face=\"5\"] {\n        transform: rotate3d(1, 0, 0, 90deg) translateZ(3.1em);\n      }\n      &[data-face=\"6\"] {\n        transform: rotate3d(0, 1, 0, 180deg) translateZ(3.1em);\n      }\n      &[data-face=\"1\"] .dot:nth-of-type(1) {\n        grid-area: five;\n      }\n      &[data-face=\"2\"] .dot:nth-of-type(1) {\n        grid-area: one;\n      }\n      &[data-face=\"2\"] .dot:nth-of-type(2) {\n        grid-area: nine;\n      }\n      &[data-face=\"3\"] .dot:nth-of-type(1) {\n        grid-area: one;\n      }\n      &[data-face=\"3\"] .dot:nth-of-type(2) {\n        grid-area: five;\n      }\n      &[data-face=\"3\"] .dot:nth-of-type(3) {\n        grid-area: nine;\n      }\n      &[data-face=\"4\"] .dot:nth-of-type(1) {\n        grid-area: one;\n      }\n      &[data-face=\"4\"] .dot:nth-of-type(2) {\n        grid-area: three;\n      }\n      &[data-face=\"4\"] .dot:nth-of-type(3) {\n        grid-area: sup;\n      }\n      &[data-face=\"4\"] .dot:nth-of-type(4) {\n        grid-area: nine;\n      }\n      &[data-face=\"5\"] .dot:nth-of-type(1) {\n        grid-area: one;\n      }\n      &[data-face=\"5\"] .dot:nth-of-type(2) {\n        grid-area: three;\n      }\n      &[data-face=\"5\"] .dot:nth-of-type(3) {\n        grid-area: five;\n      }\n      &[data-face=\"5\"] .dot:nth-of-type(4) {\n        grid-area: sup;\n      }\n      &[data-face=\"5\"] .dot:nth-of-type(5) {\n        grid-area: nine;\n      }\n      &[data-face=\"6\"] .dot:nth-of-type(1) {\n        grid-area: one;\n      }\n      &[data-face=\"6\"] .dot:nth-of-type(2) {\n        grid-area: three;\n      }\n      &[data-face=\"6\"] .dot:nth-of-type(3) {\n        grid-area: four;\n      }\n      &[data-face=\"6\"] .dot:nth-of-type(4) {\n        grid-area: six;\n      }\n      &[data-face=\"6\"] .dot:nth-of-type(5) {\n        grid-area: sup;\n      }\n      &[data-face=\"6\"] .dot:nth-of-type(6) {\n        grid-area: nine;\n      }\n    }\n  }\n  &[data-current=\"1\"] [data-spin=\"up\"] {\n    transform: rotateX(360deg) rotateY(720deg) rotateZ(360deg);\n  }\n  &[data-current=\"2\"] [data-spin=\"up\"] {\n    transform: rotateX(450deg) rotateY(720deg) rotateZ(360deg);\n  }\n  &[data-current=\"3\"] [data-spin=\"up\"] {\n    transform: rotateX(360deg) rotateY(630deg) rotateZ(360deg);\n  }\n  &[data-current=\"4\"] [data-spin=\"up\"] {\n    transform: rotateX(360deg) rotateY(810deg) rotateZ(360deg);\n  }\n  &[data-current=\"5\"] [data-spin=\"up\"] {\n    transform: rotateX(270deg) rotateY(720deg) rotateZ(360deg);\n  }\n  &[data-current=\"6\"] [data-spin=\"up\"] {\n    transform: rotateX(360deg) rotateY(900deg) rotateZ(360deg);\n  }\n  &[data-current=\"1\"] [data-spin=\"down\"] {\n    transform: rotateX(-360deg) rotateY(-720deg) rotateZ(-360deg);\n  }\n  &[data-current=\"2\"] [data-spin=\"down\"] {\n    transform: rotateX(-270deg) rotateY(-720deg) rotateZ(-360deg);\n  }\n  &[data-current=\"3\"] [data-spin=\"down\"] {\n    transform: rotateX(-360deg) rotateY(-810deg) rotateZ(-360deg);\n  }\n  &[data-current=\"4\"] [data-spin=\"down\"] {\n    transform: rotateX(-360deg) rotateY(-630deg) rotateZ(-360deg);\n  }\n  &[data-current=\"5\"] [data-spin=\"down\"] {\n    transform: rotateX(-450deg) rotateY(-720deg) rotateZ(-360deg);\n  }\n  &[data-current=\"6\"] [data-spin=\"down\"] {\n    transform: rotateX(-360deg) rotateY(-900deg) rotateZ(-360deg);\n  }\n}\n"
  },
  {
    "path": "src/components/d6/d6.ts",
    "content": "import Piece from '../../board/piece.js';\n\nimport type Game from '../../board/game.js';\n\n/**\n * Specialized piece for representing 6-sided dice\n *\n * @example\n * import { D6 } from '@boardzilla/core/components';\n * ...\n * game.create(D6, 'my-die');\n * @category Board\n */\nexport default class D6<G extends Game = Game> extends Piece<G> {\n  sides: number = 6;\n\n  /**\n   * Currently shown face\n   * @category D6\n   */\n  current: number = 1;\n  rollSequence: number = 0;\n\n  /**\n   * Randomly choose a new face, causing the roll animation\n   * @category D6\n   */\n  roll() {\n    this.current = Math.ceil((this.game.random || Math.random)() * this.sides);\n    this.rollSequence = this._ctx.gameManager.sequence;\n  }\n}\n"
  },
  {
    "path": "src/components/d6/index.ts",
    "content": "export {default as D6} from './d6.js';\nexport {default as useD6} from './useD6.js';\n"
  },
  {
    "path": "src/components/d6/useD6.tsx",
    "content": "import React, { useEffect, useRef, useState } from 'react';\n\nimport dice from './assets/dice.ogg';\nimport { times } from '../../utils.js';\nimport D6 from './d6.js';\nimport './assets/index.scss';\n\nimport type { BaseGame } from '../../board/game.js';\n\n/**\n * Adds an animated spinning appearance to the {@link D6} class\n *\n * @example\n * import { useD6 } from '@boardzilla/core/components';\n *\n * // then in the layout() method\n *     useD6(game);\n */\nconst D6Component = ({ die }: { die: D6 }) => {\n  const diceAudio = useRef<HTMLAudioElement>(null);\n  const lastRollSequence = useRef<number>();\n  const [flip, setFlip] = useState<boolean>(false);\n\n  useEffect(() => {\n    if (die.rollSequence === Math.ceil(die._ctx.gameManager.sequence - 1) && lastRollSequence.current !== undefined && lastRollSequence.current !== die.rollSequence) {\n      diceAudio.current?.play();\n      setFlip(!flip);\n    }\n    lastRollSequence.current = die.rollSequence;\n  }, [die, die.rollSequence, flip, setFlip]);\n\n  return (\n    <>\n      <audio ref={diceAudio} src={dice} id=\"dice\"/>\n      <ol data-spin={flip ? 'up' : 'down'}>\n        {[1,2,3,4,5,6].map(dots => (\n          <li key={dots} className=\"die-face\" data-face={dots}>\n            {times(dots, d => <span key={d} className=\"dot\"/>)}\n          </li>\n        ))}\n      </ol>\n    </>\n  );\n}\n\nexport default (game: BaseGame) => {\n  game.all(D6).appearance({\n    render: (die: D6) => <D6Component die={die}/>,\n    aspectRatio: 1,\n  });\n}\n"
  },
  {
    "path": "src/components/flippable/Flippable.tsx",
    "content": "import React from 'react';\n\nimport './assets/index.scss';\n\n/**\n * A Piece with two sides: front and back. When the Piece is hidden, the back is\n * shown. When visible, the front is shown. When the visibility changes, the CSS\n * animates a 3d flip.\n *\n * @example\n * import { Flippable } from '@boardzilla/core/components';\n * ...\n *   Piece.appearance({\n *     render: piece => (\n *       <Flippable>\n *         <Flippable.Front>{piece.name}</Flippable.Front>\n *         <Flippable.Back></Flippable.Back>\n *       </Flippable>\n *     );\n *   });\n * // The DOM structure inside the Piece element will be:\n *   <div class=\"bz-flippable\">\n *     <div class=\"front\">{piece.name}</div>\n *     <div class=\"back\"></div>\n *   </div>\n */\nconst Flippable = ({ children }: {\n  children?: React.ReactNode,\n}) => {\n  let frontContent: React.ReactNode = null;\n  let backContent: React.ReactNode = null;\n\n  React.Children.forEach(children, child => {\n    if (!React.isValidElement(child)) return;\n    if (child.type === Flippable.Front) {\n      frontContent = child;\n    } else if (child.type === Flippable.Back) {\n      backContent = child;\n    } else {\n      throw Error(\"Flippable must contain only <Front/> and <Back/>\");\n    }\n  });\n\n  return (\n    <div className='bz-flippable'>\n      <div className=\"front\">\n        {frontContent}\n      </div>\n      <div className=\"back\">\n        {backContent}\n      </div>\n    </div>\n  );\n}\nexport default Flippable;\n\nconst Front = ({ children }: { children: React.ReactNode }) => children;\nFlippable.Front = Front;\n\nconst Back = ({ children }: { children: React.ReactNode }) =>  children;\nFlippable.Back = Back;\n"
  },
  {
    "path": "src/components/flippable/assets/index.scss",
    "content": ".bz-flippable {\n  #game:not(.browser-firefox) & {\n    perspective: 40vw;\n  }\n\n  width: 100%;\n  height: 100%;\n  transition: transform 0.6s;\n  transform-style: preserve-3d;\n  #game:not(.browser-firefox) & {\n    transform-style: preserve-3d;\n  }\n  position: relative;\n\n  .front, .back {\n    position: absolute;\n    top: 0;\n    left: 0;\n    width: 100%;\n    height: 100%;\n    backface-visibility: hidden;\n  }\n\n  /* back, initially hidden pane */\n  .back {\n    transform: rotateY(180deg);\n  }\n\n  /* flip the pane when hovered */\n  :not([data-name]) > & {\n    transform: rotateY(180deg);\n  }\n}\n"
  },
  {
    "path": "src/components/flippable/index.ts",
    "content": "export {default as Flippable} from './Flippable.js';\n"
  },
  {
    "path": "src/components/index.ts",
    "content": "export { D6, useD6 } from './d6/index.js';\nexport { Flippable } from './flippable/index.js';\n"
  },
  {
    "path": "src/flow/action-step.ts",
    "content": "import Flow from './flow.js';\nimport { deserializeObject, serializeObject } from '../action/utils.js';\nimport { FlowControl, InterruptControl, interruptSignal } from './enums.js';\n\nimport type { FlowBranchNode, FlowDefinition, FlowStep } from './flow.js';\nimport type { Player } from '../player/index.js';\nimport type { Argument, ActionStub } from '../action/action.js';\nimport type { InterruptSignal, SubflowSignal } from './enums.js';\n\nexport type ActionStepPosition = { // turn taken by `player`\n  player: number,\n  name: string,\n  args: Record<string, Argument>,\n} | undefined // waiting;\n\nexport default class ActionStep extends Flow {\n  players?: Player | Player[] | ((args: Record<string, any>) => Player | Player[]); // if restricted to a particular player list. otherwise uses current player\n  position: ActionStepPosition;\n  actions: {\n    name: string,\n    prompt?: string | ((args: Record<string, any>) => string),\n    args?: Record<string, Argument> | ((args: Record<string, any>) => Record<string, Argument>),\n    do?: FlowDefinition\n  }[];\n  type: FlowBranchNode['type'] = \"action\";\n  prompt?: string | ((args: Record<string, any>) => string); // needed if multiple board actions\n  condition?: (args: Record<string, any>) => boolean;\n  continueIfImpossible?: boolean;\n  repeatUntil?: boolean;\n  description?: string;\n  skipIf: 'always' | 'never' | 'only-one';\n\n  constructor({ name, player, players, actions, prompt, description, optional, condition, continueIfImpossible, repeatUntil, skipIf }: {\n    name?: string,\n    players?: Player[] | ((args: Record<string, any>) => Player[]),\n    player?: Player | ((args: Record<string, any>) => Player),\n    actions: (string | {\n      name: string,\n      prompt?: string | ((args: Record<string, any>) => string),\n      args?: Record<string, Argument> | ((args: Record<string, any>) => Record<string, Argument>),\n      do?: FlowDefinition\n    })[],\n    prompt?: string | ((args: Record<string, any>) => string),\n    condition?: (args: Record<string, any>) => boolean;\n    continueIfImpossible?: boolean;\n    repeatUntil?: string | ((args: Record<string, any>) => string);\n    description?: string,\n    optional?: string | ((args: Record<string, any>) => string),\n    skipIf?: 'always' | 'never' | 'only-one',\n  }) {\n    super({ name });\n    this.actions = actions.map(a => typeof a === 'string' ? {name: a} : a);\n    this.prompt = prompt;\n    if (repeatUntil) {\n      this.repeatUntil = true;\n      this.actions.push({name: '__pass__', prompt: typeof repeatUntil === 'function' ? repeatUntil(this.flowStepArgs()) : repeatUntil});\n    } else if (optional) {\n      this.actions.push({name: '__pass__', prompt: typeof optional === 'function' ? optional(this.flowStepArgs()) : optional});\n    }\n    this.description = description;\n    this.condition = condition;\n    this.continueIfImpossible = continueIfImpossible ?? false;\n    this.skipIf = skipIf ?? 'always';\n    this.players = players ?? player;\n  }\n\n  reset() {\n    this.setPosition(undefined);\n  }\n\n  thisStepArgs() {\n    if (this.position?.name && this.position?.args) {\n      // want to remove\n      return {[this.position.name]: this.position.args};\n    }\n  }\n\n  setPosition(position: ActionStepPosition, sequence?: number) {\n    super.setPosition(position, sequence);\n    if (this.awaitingAction()) {\n      const players = this.getPlayers();\n      if (players) this.gameManager.players.setCurrent(players);\n    }\n  }\n\n  getPlayers() {\n    if (this.players) {\n      const players = typeof this.players === 'function' ? this.players(this.flowStepArgs()) : this.players;\n      return (players instanceof Array ? players : [players]).map(p => p.position);\n    }\n  }\n\n  awaitingAction() {\n    return !this.position && (!this.condition || this.condition(this.flowStepArgs()));\n  }\n\n  currentBlock() {\n    if (this.position) {\n      const actionName = (this.position as { player: number, name: string, args: Record<string, Argument> }).name; // turn taken by `player`\n      const step = this.actions.find(a => a.name === actionName)?.do;\n      if (step) return step;\n    }\n  }\n\n  // current actions that can process. does not check player\n  allowedActions(): string[] {\n    return this.position ? [] : this.actions.map(a => a.name);\n  }\n\n  actionNeeded(player?: Player): {\n    step?: string,\n    prompt?: string,\n    description?: string,\n    actions: ActionStub[],\n    continueIfImpossible?: boolean,\n    skipIf: 'always' | 'never' | 'only-one';\n  } | undefined {\n    if (!this.position) {\n      if (!player || player.isCurrent()) {\n        return {\n          prompt: typeof this.prompt === 'function' ? this.prompt(this.flowStepArgs()) : this.prompt,\n          description: this.description,\n          step: this.name,\n          actions: this.actions.map(action => ({\n            name: action.name,\n            prompt: typeof action.prompt === 'function' ? action.prompt(this.flowStepArgs()) : action.prompt,\n            args: typeof action.args === 'function' ? action.args(this.flowStepArgs()) : action.args,\n          })),\n          continueIfImpossible: this.continueIfImpossible,\n          skipIf: this.skipIf,\n        }\n      }\n    }\n  }\n\n  // returns error (string) or subflow {args, name} or ok (undefined)\n  processMove(move: {\n    player: number,\n    name: string,\n    args: Record<string, Argument>,\n  }): string | SubflowSignal['data'][] | undefined {\n    if ((move.name !== '__continue__' || !this.continueIfImpossible) && !this.allowedActions().includes(move.name)) {\n      throw Error(`No action ${move.name} available at this point. Waiting for ${this.allowedActions().join(\", \")}`);\n    }\n    const gameManager = this.gameManager;\n\n    if (!gameManager.players.currentPosition.includes(move.player)) {\n      throw Error(`Move ${move.name} from player #${move.player} not allowed. Current players: #${gameManager.players.currentPosition.join('; ')}`);\n    }\n\n    const player = gameManager.players.atPosition(move.player);\n    if (!player) return `No such player position: ${move.player}`;\n\n    if (move.name === '__pass__' || move.name === '__continue__') {\n      this.setPosition(move);\n      return;\n    }\n\n    const gameAction = gameManager.getAction(move.name, player);\n    const error = gameAction._process(player, move.args);\n    if (error) {\n      // failed with a selection required\n      return error;\n    } else {\n      // succeeded\n      this.setPosition(this.position ? {...this.position} : move);\n\n      if (interruptSignal[0]) {\n        const interrupt = interruptSignal.splice(0);\n        if (interrupt[0].signal === InterruptControl.subflow) return (interrupt as SubflowSignal[]).map(s => s.data);\n        const loop = this.currentLoop(interrupt[0].data);\n        if (!loop) {\n          if (interrupt[0].data) throw Error(`No loop found \"${interrupt[0].data}\" for interrupt`);\n          if (interrupt[0].signal === InterruptControl.continue) throw Error(\"Cannot use Do.continue when not in a loop\");\n          if (interrupt[0].signal === InterruptControl.repeat) throw Error(\"Cannot use Do.repeat when not in a loop\");\n          throw Error(\"Cannot use Do.break when not in a loop\");\n        } else {\n          loop.interrupt(interrupt[0].signal);\n          return;\n        }\n      }\n    }\n  }\n\n  playOneStep(): InterruptSignal[] | FlowControl | Flow {\n    return this.awaitingAction() ? this : super.playOneStep();\n  }\n\n  advance() {\n    if (!this.repeatUntil || this.position?.name === '__pass__') return FlowControl.complete;\n    this.reset();\n    return FlowControl.ok;\n  }\n\n  toJSON(forPlayer=true) {\n    if (this.position) {\n      const json: any = {\n        player: this.position.player,\n        name: this.position.name,\n        args: serializeObject(this.position.args, forPlayer),\n      };\n      return json;\n    }\n    return undefined;\n  }\n\n  fromJSON(position: any) {\n    if (!position) return undefined;\n    return !('player' in position) ? position : {\n      ...position,\n      args: deserializeObject(position.args ?? {}, this.gameManager.game) as Record<string, Argument>,\n    };\n  }\n\n  allSteps() {\n    return this.actions.map(a => a.do).reduce<FlowStep[]>((a, f) => f ? a.concat(f) : a, []);\n  }\n\n  toString(): string {\n    return `player-action${this.name ? \":\" + this.name : \"\"} (player #${this.top.gameManager.players.currentPosition}: ${this.allowedActions().join(\", \")}${this.block instanceof Array ? ' item #' + this.sequence : ''})`;\n  }\n\n  visualize(top: Flow) {\n    const args = this.position && '{' + Object.entries(this.position.args).map(([k, v]) => `${k}: ${v}`).join(', ') + '}'\n    return this.visualizeBlocks({\n      type: 'playerActions',\n      name: this.position?.name ?? '',\n      top,\n      blocks: Object.fromEntries(\n        this.actions.filter(a => a.name !== '__pass__').map(a => [a.name, a.do ? (a.do instanceof Array ? a.do : [a.do]) : undefined])\n      ) as Record<string, FlowStep[]>,\n      block: this.position?.name,\n      position: args ?? top.gameManager.players.allCurrent().map(p => p.name).join(', ')\n    });\n  }\n}\n"
  },
  {
    "path": "src/flow/each-player.ts",
    "content": "import ForLoop from './for-loop.js';\nimport { Player } from '../player/index.js';\nimport { serializeSingleArg, deserializeSingleArg } from '../action/utils.js';\n\nimport type { FlowArguments, FlowDefinition } from './flow.js';\nimport type Flow from './flow.js';\n\nexport default class EachPlayer<P extends Player> extends ForLoop<P> {\n  continueUntil?: (p: P) => boolean;\n  turns?: number;\n\n  constructor({ name, startingPlayer, nextPlayer, turns, continueUntil, do: block }: {\n    name: string,\n    startingPlayer?: ((a: FlowArguments) => P) | P,\n    nextPlayer?: (p: P) => P,\n    turns?: number,\n    continueUntil?: (p: P) => boolean,\n    do: FlowDefinition,\n  }) {\n    let initial: (r: Record<any, any>) => P\n    if (startingPlayer) {\n      initial = () => startingPlayer instanceof Function ? startingPlayer(this.flowStepArgs()) : startingPlayer\n    } else {\n      initial = () => this.gameManager.players[0] as P;\n    }\n    let next = (player: P) => (nextPlayer ? nextPlayer(player) : this.gameManager.players.after(player)) as P;\n\n    super({\n      name,\n      initial,\n      next,\n      while: () => true,\n      do: block\n    });\n\n    this.whileCondition = position => continueUntil !== undefined ? !continueUntil(position.value) : position.index < this.gameManager.players.length * (this.turns || 1)\n    this.turns = turns;\n  }\n\n  setPosition(position: typeof this.position, sequence?: number, reset=true) {\n    if (position.value && position.value.position !== this.position?.value.position) {\n      this.gameManager.players.setCurrent(position.value);\n    }\n    super.setPosition(position, sequence, reset);\n  }\n\n  toJSON() {\n    return {\n      index: this.position.index,\n      value: this.position.value ? serializeSingleArg(this.position.value) : undefined\n    };\n  }\n\n  fromJSON(position: any) {\n    return {\n      index: position.index,\n      value: position.value ? deserializeSingleArg(position.value, this.gameManager.game) as P: undefined\n    }\n  }\n\n  allSteps() {\n    return this.block;\n  }\n\n  toString(): string {\n    return `each-player${this.name ? \":\" + this.name : \"\"} (player #${this.position?.value?.position}${this.block instanceof Array ? ', item #' + this.sequence: ''})`;\n  }\n\n  visualize(top: Flow) {\n    return this.visualizeBlocks({\n      type: 'eachPlayer',\n      top,\n      blocks: {\n        do: this.block instanceof Array ? this.block : [this.block]\n      },\n      block: 'do',\n      position: this.position?.value,\n    });\n  }\n}\n"
  },
  {
    "path": "src/flow/enums.ts",
    "content": "/**\n * Functions for interrupting flows\n *\n * These functions all interrupt the flow in some. Upon calling one, the flow\n * will complete its current step and then proceed with whatever type of\n * interrupt was provided.\n *\n * Three of these functions are for interrupting loops: `Do.break`, `Do.repeat`,\n * and `Do.continue`. They can be called from anywhere inside a looping flow\n * ({@link loop}, {@link whileLoop}, {@link forLoop}, {@link forEach}, {@link\n * eachPlayer}) to interrupt the flow, with each one resuming the flow\n * differently.\n *\n * `Do.subflow` can be called anywhere and causes the flow to jump to another\n * subflow. When that subflow completes, the game flow will return to the\n * current flow, at the step immediately after the one that called `Do.subflow`.\n *\n * `Do.break` causes the flow to exit loop and resume after the loop, like the\n * `break` keyword in Javascript.\n *\n * `Do.continue` causes the flow to skip the rest of the current loop iteration\n * and restart the loop at the next iteration, like the `continue` keyword in\n * Javascript.\n *\n * `Do.repeat` causes the flow to skip the rest of the current loop iteration\n * and restart the same iteration of the loop.\n *\n * @example\n * // each player can shout as many times as they like\n * eachPlayer({ name: 'player', do: (\n *   playerActions({ actions: [\n *     { name: 'shout', do: Do.repeat },\n *     'pass'\n *   ]}),\n * ]});\n *\n * // each player can decide to shout, and if so, may subsequently apologize\n * eachPlayer({ name: 'player', do: [\n *   playerActions({ actions: [\n *     { name: 'shout', do: Do.continue },  // if shouting, skip to the next player\n *     'pass'\n *   ]}),\n *   playerActions({ actions: [ 'apologize', 'pass' ] }),\n * ]});\n *\n * // each player can take a card but if the card is a match, it ends this round\n * eachPlayer({ name: 'player', do: (\n *   playerActions({ actions: [\n *     { name: 'takeCard', do: ({ takeCard }) => if (takeCard.card.isMatch()) Do.break() },\n *     'pass'\n *   ]}),\n * ]});\n *\n * @category Flow\n */\nexport const Do = {\n  repeat: (loop?: string | Record<string, any>) => interrupt({ signal: InterruptControl.repeat, data: typeof loop === 'string' ? loop : undefined }),\n  continue: (loop?: string | Record<string, any>) => interrupt({ signal: InterruptControl.continue, data: typeof loop === 'string' ? loop : undefined }),\n  break: (loop?: string | Record<string, any>) => interrupt({ signal: InterruptControl.break, data: typeof loop === 'string' ? loop : undefined }),\n  subflow: (flow: string, args?: Record<string, any>) => interrupt({ signal: InterruptControl.subflow, data: {name: flow, args} }),\n}\n\ntype LoopInterruptSignal = { signal: InterruptControl.repeat | InterruptControl.continue | InterruptControl.break, data?: string }\nexport type SubflowSignal = { signal: InterruptControl.subflow, data: {name: string, args?: Record<string, any>} }\nexport type InterruptSignal = LoopInterruptSignal | SubflowSignal\n\n/** @internal */\nexport const interruptSignal: InterruptSignal[] = [];\n\nfunction interrupt({ signal, data }: InterruptSignal) {\n  if (signal === InterruptControl.subflow) {\n    if (interruptSignal.every(s => s.signal === InterruptControl.subflow)) {\n      interruptSignal.push({data, signal}); // subflows can be queued but will not override loop interrupt\n    }\n  } else {\n    // loop interrupts cancel other signals\n    interruptSignal.splice(0);\n    interruptSignal[0] = {data, signal};\n  }\n}\n\n/** @internal */\nexport enum InterruptControl {\n  repeat = \"__REPEAT__\",\n  continue = \"__CONTINUE__\",\n  break = \"__BREAK__\",\n  subflow = \"__SUBFLOW__\",\n}\n\n/** @internal */\nexport enum FlowControl {\n  ok = \"__OK__\",\n  complete = \"__COMPLETE__\"\n}\n"
  },
  {
    "path": "src/flow/every-player.ts",
    "content": "import Flow from './flow.js';\nimport { FlowControl } from './enums.js';\n\nimport type { FlowDefinition, FlowBranchNode, FlowBranchJSON } from './flow.js';\nimport type { Player, PlayerCollection } from '../player/index.js';\nimport type { Argument } from '../action/action.js';\nimport type { SubflowSignal, InterruptSignal } from './enums.js';\n\nexport type EveryPlayerPosition = {positions: FlowBranchJSON[][], sequences: number[], completed: (boolean | undefined)[]};\n\nexport default class EveryPlayer<P extends Player> extends Flow {\n  position: EveryPlayerPosition;\n  players?: P[];\n  value: number; // player temporarily looking at\n  completed: (boolean | undefined)[] = [];\n  block: FlowDefinition;\n  type: FlowBranchNode['type'] = 'parallel';\n\n  constructor({ players, do: block, name }: {\n    players?: P[],\n    do: FlowDefinition,\n    name?: string\n  }) {\n    super({ do: block, name });\n    this.players = players;\n  }\n\n  reset() {\n    this.value = -1;\n    this.completed = [];\n    this.setPosition({positions: [], sequences: [], completed: []});\n  }\n\n  thisStepArgs() {\n    if (this.name) {\n      const currentPlayer = this.getPlayers()[this.value];\n      if (currentPlayer) return {[this.name]: currentPlayer};\n    }\n  }\n\n  // closure wrapper for super's methods that will setPosition temporarily to a\n  // specific player and pretend to be a normal flow with just one subflow\n  withPlayer<T>(value: number, fn: () => T, mutate=false): T {\n    this.value = value;\n    this.sequence = this.position.sequences[this.value];\n    this.setPosition(this.position, this.sequence);\n    const result = fn();\n    if (mutate) {\n      const currentPlayer = this.getPlayers()[this.value];\n      // capture position from existing player before returning to all player mode\n      this.position.sequences[this.value] = this.sequence;\n      if (currentPlayer && this.step instanceof Flow) this.position.positions[this.value] = this.step.branchJSON();\n    }\n    this.value = -1;\n    this.setPosition(this.position);\n    return result;\n  }\n\n  getPlayers(): P[] {\n    return this.players || this.gameManager.players as PlayerCollection<P>\n  }\n\n  // reimpl ourselves to collect json from all players\n  branchJSON(forPlayer=true): FlowBranchJSON[] {\n    if (this.position === undefined && this.sequence === undefined) return []; // probably invalid\n    let branch: FlowBranchJSON = {\n      type: this.type,\n      position: {positions: [], sequences: this.position.sequences, completed: this.completed}\n    };\n    if (this.name) branch.name = this.name;\n\n    for (let i = 0; i !== this.getPlayers().length; i++) {\n      this.withPlayer(i, () => {\n        if (this.step instanceof Flow) branch.position.positions[i] = this.step.branchJSON(forPlayer);\n      });\n    }\n    return [branch];\n  }\n\n  // add player management, hydration of flow for the correct player, sequences[] management\n  setPosition(positionJSON: any, sequence?: number) {\n    const player = this.getPlayers()[this.value];\n    this.completed = positionJSON.completed;\n    if (player) {\n      player.setCurrent();\n      positionJSON.sequences[this.value] = sequence;\n    } else {\n      // not looking at an individual player. set game state to accept all players\n      const players: P[] = [];\n      for (let i = 0; i !== this.getPlayers().length; i++) {\n        if (this.completed[i] === false) players.push(this.getPlayers()[i]);\n      }\n      this.gameManager.players.setCurrent(players);\n    }\n    super.setPosition(positionJSON, positionJSON.sequences[this.value]);\n    if (this.step instanceof Flow && this.position.positions[this.value]) {\n      this.step.setBranchFromJSON(this.position.positions[this.value]);\n    }\n  }\n\n  currentBlock() {\n    // need to override this within flow methods by setting value. branch\n    // set/get should not advance past here, but step function may\n    return this.value >= 0 && this.value < this.getPlayers().length ? this.block : undefined;\n  }\n\n  actionNeeded(player?: Player) {\n    if (player && this.getPlayers().includes(player as P)) {\n      return this.withPlayer(this.getPlayers().indexOf(player as P), () => super.actionNeeded(player));\n    }\n  }\n\n  processMove(move: {\n    player: number,\n    name: string,\n    args: Record<string, Argument>,\n  }): string | SubflowSignal['data'][] | undefined {\n    const player = this.getPlayers().findIndex(p => p.position === move.player);\n    if (player < 0) throw Error(`Cannot process action from ${move.player}`);\n    return this.withPlayer(player, () => {\n      this.completed[player] = undefined;\n      return super.processMove(move);\n    }, true);\n  }\n\n  // intercept super.playOneStep so a single branch doesn't signal complete\n  // without us checking all branches\n  playOneStep(): InterruptSignal[] | FlowControl | Flow {\n    // step through each player over top of the normal super stepping\n    const player = this.getPlayers().findIndex((_, p) => this.completed[p] === undefined);\n\n    if (player !== -1) {\n      // run for next player without a resolution\n      return this.withPlayer(player, () => {\n        let result = super.playOneStep();\n\n        // capture the complete state ourselves, pretend everything is fine\n        if (result instanceof Flow || result === FlowControl.complete) this.completed![player] = result === FlowControl.complete;\n        return FlowControl.ok;\n      }, true);\n    }\n\n    // no more players to step through. return the all-complete\n    return this.completed.every(r => r) ? FlowControl.complete : this;\n  }\n\n  toString(): string {\n    return `every-player${this.name ? \":\" + this.name : \"\"}`;\n  }\n\n  visualize(top: Flow) {\n    return this.visualizeBlocks({\n      type: 'everyPlayer',\n      top,\n      blocks: {\n        do: this.block instanceof Array ? this.block : [this.block]\n      },\n      block: 'do',\n    });\n  }\n}\n"
  },
  {
    "path": "src/flow/flow.ts",
    "content": "import { InterruptControl, interruptSignal, FlowControl } from './enums.js';\nimport { Do } from './enums.js';\n\nimport type { InterruptSignal, SubflowSignal } from './enums.js';\nimport type GameManager from '../game-manager.js';\nimport type { Player } from '../index.js';\nimport type { WhileLoopPosition } from './while-loop.js';\nimport type { ForLoopPosition } from './for-loop.js';\nimport type { ForEachPosition } from './for-each.js';\nimport type { SwitchCasePostion } from './switch-case.js';\nimport type { ActionStepPosition } from './action-step.js';\nimport type { EveryPlayerPosition } from './every-player.js';\nimport type { ActionStub } from '../action/action.js';\nimport type WhileLoop from './while-loop.js';\nimport type { Serializable } from '../action/utils.js';\n\n/**\n * Several flow methods accept an argument of this type. This is an object\n * containing the current values of any loops or actions that the game is in the\n * middle of. Functions that can add these values are {@link forLoop}, {@link\n * forEach}, {@link switchCase} and {@link playerActions}. The `name` given to\n * these functions will be the key used in the FlowArguments and its value will\n * be the value of the current loop for loops, or the test value for switchCase,\n * or the arguments to the action taken for playerActions.\n *\n * @example\n * forLoop({\n *   name: 'x', // x is declared here\n *   initial: 0,\n *   next: x => x + 1,\n *   while: x => x < 3,\n *   do: forLoop({\n *     name: 'y', // y is declared here\n *     initial: 0,\n *     next: y => y + 1,\n *     while: y => y < 2,\n *     do: ({ x, y }) => {\n *       // x is available here as the value of the outer loop\n *       // and y will be the value of the inner loop\n *     }\n *   })\n * })\n * @category Flow\n */\nexport type FlowArguments = Record<string, any>;\n\n/**\n * FlowStep's are provided to the game and to all flow function to provide\n * further flow logic inside the given flow. Any of the follow qualifies:\n * - a plain function that accepts {@link FlowArguments}\n * - one of the {@link Game#flowCommands}\n * @category Flow\n */\nexport type FlowStep = Flow | ((args: FlowArguments) => any);\n\n/**\n * FlowDefinition's are provided to the game and to all flow function to provide\n * further flow logic inside the given flow. Any of the follow qualifies:\n * - a plain function that accepts {@link FlowArguments}\n * - one of the {@link Game#flowCommands}\n * - an array of any combination of the above\n * @category Flow\n */\nexport type FlowDefinition = FlowStep | FlowStep[]\n\nexport type FlowBranchNode = ({\n  type: 'main',\n} | {\n  type: 'action',\n  position: ActionStepPosition\n} | {\n  type: 'parallel',\n  position: EveryPlayerPosition,\n} | {\n  type: 'loop',\n  position: WhileLoopPosition | ForLoopPosition<any>\n} | {\n  type: 'foreach',\n  position: ForEachPosition<any>\n} | {\n  type: 'switch-case',\n  position: SwitchCasePostion<any>\n}) & {\n  name?: string,\n  sequence?: number,\n}\n\nexport type FlowBranchJSON = ({\n  type: 'main' | 'action' | 'loop' | 'foreach' | 'switch-case' | 'parallel'\n  position?: any,\n}) & {\n  name?: string,\n  sequence?: number,\n}\n\nexport type Position = (\n  ActionStepPosition | ForLoopPosition<any> | WhileLoopPosition | ForEachPosition<any> | SwitchCasePostion<any> | EveryPlayerPosition\n)\n\nexport type FlowVisualization = {\n  type: string,\n  name?: string,\n  blocks: Record<string, (string | FlowVisualization)[] | undefined>,\n  current: {\n    block?: string,\n    position?: any,\n    sequence?: number,\n  }\n}\n\n/** internal */\nexport default class Flow {\n  name?: string;\n  position?: Position;\n  sequence?: number; // if block is an array, indicates the index of execution\n  type: FlowBranchNode['type'] = 'main';\n  step?: FlowStep; // cached by setPositionFromJSON\n  block?: FlowDefinition;\n  args?: Record<string, Serializable>;\n  top: Flow;\n  parent?: Flow;\n  gameManager: GameManager;\n\n  constructor({ name, do: block }: { name?: string, do?: FlowDefinition }) {\n    this.name = name;\n    this.block = block;\n    // each subflow can set itself as top because they will be copied later by each parent as it loads its subflows\n    this.top = this;\n  }\n\n  validateNoDuplicate() {\n    const name = this.name;\n    this.name = undefined;\n    if (name && this.getStep(name)) throw Error(`Duplicate flow name: ${name}`);\n    this.name = name;\n  }\n\n  flowStepArgs(): FlowArguments {\n    const args = {...(this.top.args ?? {})};\n    let flow: FlowStep | undefined = this.top;\n    while (flow instanceof Flow) {\n      Object.assign(args, flow.thisStepArgs());\n      flow = flow.step;\n    }\n    return args;\n  }\n\n  thisStepArgs() {\n    if (this.position && 'value' in this.position && this.name) {\n      return {[this.name]: this.position.value};\n    }\n  }\n\n  branchJSON(forPlayer=true): FlowBranchJSON[] {\n    let branch: Record<string, any> = {\n      type: this.type,\n    };\n    if (this.name) branch.name = this.name;\n    if (this.position !== undefined) branch.position = this.toJSON(forPlayer);\n    if (this.sequence !== undefined && this.currentBlock() instanceof Array) branch.sequence = this.sequence;\n    const thisBranch = branch as FlowBranchJSON;\n    if (this.step instanceof Flow) return [thisBranch].concat(this.step.branchJSON(forPlayer));\n    return [thisBranch];\n  }\n\n  setBranchFromJSON(branch: FlowBranchJSON[]) {\n    const node = branch[0];\n    if (node === undefined) throw Error(`Insufficient position elements sent to flow for ${this.name}`);\n    if (node.type !== this.type || node.name !== this.name) {\n      throw Error(`Flow mismatch. Trying to set ${node.type}:${node.name} on ${this.type}:${this.name}`);\n    }\n    this.setPositionFromJSON(node.position, node.sequence);\n    if (this.step instanceof Flow) {\n      this.step.setBranchFromJSON(branch.slice(1)); // continue down the hierarchy\n    }\n  }\n\n  setPosition(position: any, sequence?: number, reset=true) {\n    this.position = position;\n    const block = this.currentBlock();\n    if (!block) {\n      this.step = undefined; // awaiting action or unreachable step\n    } else if (block instanceof Array) {\n      if (sequence === undefined) sequence = 0;\n      this.sequence = sequence;\n      if (!block[sequence]) throw Error(`Invalid sequence for ${this.type}:${this.name} ${sequence}/${block.length}`);\n      this.step = block[sequence];\n    } else {\n      this.step = block;\n    }\n\n    if (this.step instanceof Flow) {\n      this.step.gameManager = this.gameManager;\n      this.step.top = this.top;\n      this.step.parent = this;\n      if (reset) this.step.reset();\n    }\n  }\n\n  setPositionFromJSON(positionJSON: any, sequence?: number) {\n    this.setPosition(this.fromJSON(positionJSON), sequence, false);\n  }\n\n  currentLoop(name?: string): WhileLoop | undefined {\n    if ('interrupt' in this && (!name || name === this.name)) return this as unknown as WhileLoop;\n    return this.parent?.currentLoop();\n  }\n\n  currentProcessor(): Flow | undefined {\n    if (this.step instanceof Flow) return this.step.currentProcessor();\n    if (this.type === 'action' || this.type === 'parallel') return this;\n  }\n\n  actionNeeded(player?: Player): {\n    step?: string,\n    prompt?: string,\n    description?: string,\n    actions: ActionStub[],\n    continueIfImpossible?: boolean,\n    skipIf: 'always' | 'never' | 'only-one';\n  } | undefined {\n    return this.currentProcessor()?.actionNeeded(player);\n  }\n\n  processMove(move: NonNullable<ActionStepPosition>): string | SubflowSignal['data'][] | undefined {\n    interruptSignal.splice(0);\n    const step = this.currentProcessor();\n    if (!step) throw Error(`Cannot process action currently ${JSON.stringify(this.branchJSON())}`);\n    return step.processMove(move);\n  }\n\n  getStep(name: string): Flow | undefined {\n    if (this.name === name) {\n      this.validateNoDuplicate();\n      return this;\n    }\n    const steps = this.allSteps();\n    if (!steps) return;\n    for (const step of steps instanceof Array ? steps : [steps]) {\n      if (step instanceof Flow) {\n        const found = step.getStep(name);\n        if (found) return found;\n      }\n    }\n  }\n\n  /**\n   * Advance flow one step and return FlowControl.complete if complete,\n   * FlowControl.ok if can continue, Do to interrupt the current loop. Returns\n   * ActionStep if now waiting for player input. override for self-contained\n   * flows that do not have subflows.\n   */\n  playOneStep(): InterruptSignal[] | FlowControl | Flow {\n    const step = this.step;\n    let result: InterruptSignal[] | FlowControl | Flow = FlowControl.complete;\n    if (step instanceof Function) {\n      if (!interruptSignal[0]) step(this.flowStepArgs());\n      result = FlowControl.complete;\n      if (interruptSignal[0] && interruptSignal[0].signal !== InterruptControl.subflow) result = interruptSignal.splice(0);\n    } else if (step instanceof Flow) {\n      result = step.playOneStep();\n    }\n    if (result === FlowControl.ok || result instanceof Flow) return result;\n    if (result !== FlowControl.complete) {\n      if ('interrupt' in this && typeof this.interrupt === 'function' && (!result[0].data || result[0].data === this.name)) return this.interrupt(result[0].signal)\n      return result;\n    }\n\n    // completed step, advance this block if able\n    const block = this.currentBlock();\n    if (block instanceof Array) {\n      if ((this.sequence ?? 0) + 1 !== block.length) {\n        this.setPosition(this.position, (this.sequence ?? 0) + 1);\n        return FlowControl.ok;\n      }\n    }\n\n    // completed block, advance self\n    return this.advance();\n  }\n\n  // play until action required (returns ActionStep) or flow complete (undefined) or subflow started {name, args}\n  play() {\n    interruptSignal.splice(0);\n    let step;\n    do {\n      if (this.gameManager.phase !== 'finished') step = this.playOneStep();\n      if (!(step instanceof Flow)) console.debug(`Advancing flow:\\n ${this.stacktrace()}`);\n    } while (step === FlowControl.ok && interruptSignal[0]?.signal !== InterruptControl.subflow && this.gameManager.phase !== 'finished')\n    if (interruptSignal[0]?.signal === InterruptControl.subflow) return interruptSignal.map(s => s.data as {name: string, args: Record<string, any>});\n    if (step instanceof Flow) return step;\n    if (step instanceof Array) {\n      if (step[0].signal === InterruptControl.continue) throw Error(\"Cannot use Do.continue when not in a loop\");\n      if (step[0].signal === InterruptControl.repeat) throw Error(\"Cannot use Do.repeat when not in a loop\");\n      throw Error(\"Cannot use Do.break when not in a loop\");\n    }\n    // flow complete\n  }\n\n  // must override. reset runs any logic needed and call setPosition. Must not modify own state.\n  reset() {\n    this.setPosition(undefined);\n  }\n\n  // must override. must rely solely on this.position\n  currentBlock(): FlowDefinition | undefined {\n    return this.block;\n  }\n\n  // override if position contains objects that need serialization\n  toJSON(_forPlayer=true): any {\n    return this.position;\n  }\n\n  // override if position contains objects that need deserialization\n  fromJSON(json: any): typeof this.position {\n    return json;\n  }\n\n  // override for steps that advance through their subflows. call setPosition if needed. return ok/complete\n  advance(): FlowControl {\n    return FlowControl.complete;\n  }\n\n  // override return all subflows\n  allSteps(): FlowDefinition | undefined {\n    return this.block;\n  }\n\n  toString() {\n    return `flow${this.name ? \":\" + this.name.replace(/__/g, '') : \"\"}${this.block instanceof Array && this.block.length > 1 ? ' (item #' + this.sequence + ')' : ''}`;\n  }\n\n  stacktrace(indent=0) {\n    let string = this.toString();\n    if (this.step instanceof Flow) string += '\\n ' + ' '.repeat(indent) + '↳ ' + this.step.stacktrace(indent + 2);\n    return string;\n  }\n\n  visualize(top: Flow) {\n    return this.visualizeBlocks({\n      type: 'flow',\n      top,\n      blocks: {\n        do: this.block ? (this.block instanceof Array ? this.block : [this.block]) : undefined\n      },\n      block: 'do'\n    });\n  }\n\n  visualizeBlocks({ type, blocks, name, top, block, position }: {\n    type: string,\n    blocks: Record<string, FlowStep[] | undefined>,\n    name?: string,\n    top: Flow,\n    block?: string,\n    position?: any,\n  }): FlowVisualization {\n    const blockViz = Object.fromEntries(Object.entries(blocks).\n      map(([key, block]) => [\n        key, block?.map(s => {\n          if (s instanceof Flow) return s.visualize(top);\n          if (s === Do.break) return 'Do.break';\n          if (s === Do.repeat) return 'Do.repeat';\n          if (s === Do.continue) return 'Do.continue';\n          return s.toString()\n        })\n      ])\n    );\n\n    return {\n      type,\n      name: name === undefined ? this.name : name,\n      blocks: blockViz,\n      current: {\n        block,\n        position,\n        sequence: this.sequence\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/flow/for-each.ts",
    "content": "import ForLoop from './for-loop.js';\nimport { serialize, deserialize } from '../action/utils.js';\n\nimport type { FlowArguments, FlowDefinition, FlowBranchNode } from './flow.js';\nimport type { ForLoopPosition } from './for-loop.js';\nimport type { Serializable } from '../action/utils.js';\nimport type Flow from './flow.js';\n\nexport type ForEachPosition<T> = ForLoopPosition<T> & { collection: T[] };\n\nexport default class ForEach<T extends Serializable> extends ForLoop<T> {\n  collection: ((a: FlowArguments) => T[]) | T[]\n  position: ForEachPosition<T>;\n  whileCondition: (position: ForEachPosition<T>) => boolean;\n  type: FlowBranchNode['type'] = 'foreach';\n\n  constructor({ name, collection, do: block }: {\n    name: string,\n    collection: ((a: FlowArguments) => T[]) | T[],\n    do: FlowDefinition\n  }) {\n    super({\n      name,\n      initial: () => ((typeof collection === 'function') ? collection(this.flowStepArgs()) : collection)[0],\n      next: () => this.position.collection[this.position.index + 1],\n      while: () => true,\n      do: block\n    });\n    this.collection = collection;\n    this.whileCondition = position => position.index >= 0 && position.index < position.collection.length;\n  }\n\n  reset() {\n    const collection = (typeof this.collection === 'function') ? this.collection(this.flowStepArgs()) : this.collection;\n    this.setPosition({ index: collection.length ? 0 : -1, value: collection[0], collection });\n  }\n\n  toJSON(forPlayer=true) {\n    return {\n      index: this.position.index,\n      value: serialize(this.position.value, forPlayer),\n      collection: serialize(this.position.collection, forPlayer)\n    };\n  }\n\n  fromJSON(position: any) {\n    return {\n      index: position.index,\n      value: deserialize(position.value, this.gameManager.game),\n      collection: deserialize(position.collection, this.gameManager.game)\n    };\n  }\n\n  toString(): string {\n    return `foreach${this.name ? \":\" + this.name : \"\"} (index: ${this.position.index}, value: ${this.position.value}${this.block instanceof Array ? ', item #' + this.sequence: ''})`;\n  }\n\n  visualize(top: Flow) {\n    return this.visualizeBlocks({\n      type: 'forEach',\n      top,\n      blocks: {\n        do: this.block instanceof Array ? this.block : [this.block]\n      },\n      block: 'do',\n      position: this.position?.value,\n    });\n  }\n}\n"
  },
  {
    "path": "src/flow/for-loop.ts",
    "content": "import type { Serializable } from '../action/utils.js';\nimport type { FlowArguments, FlowDefinition, FlowBranchNode } from './flow.js';\nimport WhileLoop from './while-loop.js';\n\nimport type Flow from './flow.js';\n\nexport type ForLoopPosition<T> = { index: number, value: T };\n\nexport default class ForLoop<T = Serializable> extends WhileLoop {\n  block: FlowDefinition;\n  position: ForLoopPosition<T>;\n  initial: ((a: FlowArguments) => T) | T;\n  whileCondition: (position: ForLoopPosition<T>) => boolean;\n  next: (a: T) => T;\n  type: FlowBranchNode['type'] = 'loop';\n\n  constructor({ name, initial, next, do: block, while: whileCondition }: {\n    name: string,\n    initial: ((a: FlowArguments) => T) | T,\n    next: (a: T) => T,\n    while: (a: T) => boolean,\n    do: FlowDefinition\n  }) {\n    super({ do: block, while: () => true });\n    this.name = name;\n    this.initial = initial;\n    this.next = next;\n    this.whileCondition = position => whileCondition(position.value)\n  }\n  \n  currentBlock() {\n    if (this.position.index !== -1) return this.block;\n  }\n\n  toString(): string {\n    return `loop${this.name ? \":\" + this.name : \"\"} (index: ${this.position.index}, value: ${this.position.value}${this.block instanceof Array ? ', item #' + this.sequence: ''})$`;\n  }\n\n  visualize(top: Flow) {\n    return this.visualizeBlocks({\n      type: 'forLoop',\n      top,\n      blocks: {\n        do: this.block instanceof Array ? this.block : [this.block]\n      },\n      block: 'do',\n      position: this.position?.value,\n    });\n  }\n}\n"
  },
  {
    "path": "src/flow/if-else.ts",
    "content": "import SwitchCase from './switch-case.js';\n\nimport type { FlowDefinition, FlowStep } from './flow.js';\nimport type Flow from './flow.js';\n\nexport default class If extends SwitchCase<boolean> {\n  constructor({ name, if: test, do: doExpr, else: elseExpr }: {\n    name?: string,\n    if: (r: Record<any, any>) => boolean,\n    do: FlowDefinition;\n    else?: FlowDefinition\n  }) {\n    super({ name, switch: test, cases: [{ eq: true, do: doExpr }], default: elseExpr });\n  }\n\n  toString(): string {\n    return `if-else${this.name ? \":\" + this.name : \"\"} (${!!this.position.value}${this.block instanceof Array ? ', item #' + this.sequence: ''})`;\n  }\n\n  visualize(top: Flow) {\n    const blocks = {\n      do: this.cases[0].do instanceof Array ? this.cases[0].do : [this.cases[0].do],\n    } as Record<string, FlowStep[]>;\n    if (this.default) blocks.else = this.default instanceof Array ? this.default : [this.default];\n\n    return this.visualizeBlocks({\n      type: 'ifElse',\n      top,\n      blocks,\n      block: this.position ? (this.position.default ? 'else' : 'do') : undefined,\n      position: this.position?.value,\n    });\n  }\n}\n"
  },
  {
    "path": "src/flow/index.ts",
    "content": "import ActionStep from './action-step.js';\nimport WhileLoop from './while-loop.js';\nimport ForLoop from './for-loop.js';\nimport ForEach from './for-each.js';\nimport EachPlayer from './each-player.js';\nimport SwitchCase from './switch-case.js';\nimport IfElse from './if-else.js';\nimport EveryPlayer from './every-player.js';\n\nimport type { Serializable } from '../action/utils.js';\nimport { FlowStep } from './flow.js';\nimport { Do, FlowControl } from './enums.js';\nexport {\n  ActionStep,\n  WhileLoop,\n  ForLoop,\n  ForEach,\n  EachPlayer,\n  SwitchCase,\n  IfElse,\n  EveryPlayer,\n  Do,\n  FlowControl\n};\n\nexport type { FlowStep, FlowDefinition, FlowArguments } from './flow.js';\n\n/**\n * Stop the flow and wait for a player to act.\n *\n * @param options.actions - An array of possible actions. Each action can be\n * either a string or on object. If a string, it is the name of the action as\n * defined in {@link Game#defineActions}. If an object, it consists of the\n * following keys:\n * <ul>\n * <li> `name`: the name of the action\n * <li> `do`: a further {@link FlowDefintion} for the game to run if this action is\n *   taken. This can contain any number of nested Flow functions.\n * <li> `args`: args to pass to the action, or function returning those args. If\n *   provided this pre-selects arguments to the action that the player does not\n *   select themselves. Also see {@link game#action} and {@link game#followUp}.\n * <li> `prompt`: a string prompt, or function returning a string. If provided this\n *   overrides the prompt defined in the action. This can be useful if the same\n *   action should prompt differently at different points in the game\n * </ul>\n *\n * @param options.name - A unique name for this player action. If provided, this\n * can be used for the UI to determine placement of messages for this action in\n * {@link Game#layoutStep}.\n *\n * @param options.prompt - A prompting message for the player to decide between\n * multiple actions that involve clicking on the board. For example, if a player\n * can choose between playing a card from hand, or drawing from the deck, this\n * text can contain a single prompt that indicates this. This is used only if\n * multiple such selections are available and replaces the individual action\n * prompts. May be a string or a function accepting {@link FlowArguments}.\n *\n * @param options.description - A description of this step from a 3rd person\n * perspective, e.g. \"choosing a card\". The string will be automatically\n * prefixed with the player name and verb. If specified, will be used to convey\n * to non-acting players what step is happening.\n *\n * @param options.player - Which player can perform this action. If not\n * provided, this defaults to the {@link PlayerCollection#current | current\n * player}\n *\n * @param options.players - Which players can perform this action, if multiple.\n *\n * @param options.optional - If a string is passed, this becomes a prompt\n * players can use to 'pass' this step, performing no action and letting the\n * flow proceed. May be a string or a function accepting {@link FlowArguments}\n *\n * @param options.skipIf - One of 'always', 'never' or 'only-one' (Default\n * 'always').\n *\n * <ul>\n * <li> only-one: If there is only valid choice in the choices given, the game\n * will skip this choice, prompting the player for subsequent choices, if any,\n * or completing the action otherwise.\n * <li> always: Rather than present this choice directly, the player will be\n * prompted with choices from the *next choice* in each action here, essentially\n * expanding the choices ahead of time to save the player a step.\n * <li> never: Always present this choice, even if the choice is forced\n * </ul>\n *\n * @param options.repeatUntil - Include this option to make this action\n * repeatable until the player passes. The pass prompt will be the supplied\n * string, similar to `optional`\n *\n * @param options.condtion - Include this option to make this action\n * automatically skip if this condition returns false.\n *\n * @param options.continueIfImpossible - Include this option to make this action\n * automatically skip if none of the actions are possible, either due to the\n * action.condition or due to no valid selections being current available in the\n * game.\n *\n * @category Flow\n */\nexport const playerActions = (options: ConstructorParameters<typeof ActionStep>[0]) => new ActionStep(options);\n\n/**\n * Create a loop that continues until some condition is true. This functions\n * like a standard `while` loop.\n *\n * @param options.do - The part that gets repeated. This can contain any type of\n * {@link FlowDefintion}, a list of functions, or more Flow commands. The\n * functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link\n * Do|Do.continue}, can also be used here to cause the current loop to be\n * interupted.\n *\n * @param options.while - Either a simple boolean value or a condition function\n * that must return true for the loop to continue. If this evaluates to false\n * when the loop begins, it will be skipped entirely. The condition will be\n * evaluated at the start of each loop to determine whether it should continue.\n *\n * @example\n * whileLoop({ while: () => !bag.isEmpty(), do: (\n *   playerActions({ actions: {\n *     takeOneFromBag: null,\n *   }}),\n * )});\n *\n * @category Flow\n */\nexport const whileLoop = (options: ConstructorParameters<typeof WhileLoop>[0]) => new WhileLoop(options);\n\n/**\n * Create a loop that continues until {@link Do|Do.break} is called\n *\n * @param options.do - The part that gets repeated. This can contain any type of\n * {@link FlowDefintion}, a list of functions, or more Flow commands. The\n * functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link\n * Do|Do.continue}, can also be used here to cause the current loop to be\n * interupted.\n *\n * @example\n * loop(playerActions({ actions: [\n *   'takeOneFromBag',\n *   { name: 'done', do: Do.break }\n * ]}));\n *\n * @category Flow\n */\nexport const loop = (...block: FlowStep[]) => new WhileLoop({do: block, while: () => true});\n\n/**\n * Create a loop that sets a value and continues until that value meets some\n * condition. This functions like a standard `for` loop.\n *\n * @param options.do - The part that gets repeated. This can contain any type of\n * {@link FlowDefintion}, a list of functions, or more Flow commands. The\n * functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link\n * Do|Do.continue}, can also be used here to cause the current loop to be\n * interupted.\n *\n * @param options.name - The current value of the loop variable will be added to\n * the {@link FlowArguments} under a key with this name.\n *\n * @param options.initial - The initial value of the loop variable\n *\n * @param options.next - A function that will be run on each loop and must\n * return the new value of the loop variable\n *\n * @param options.while - A condition function that must return true for the\n * loop to continue. If this evaluates to false when the loop begins, it will be\n * skipped entirely. The condition will be evaluates at the start of each loop\n * to determine whether it should continue.\n *\n * @example\n * forLoop({\n *   name: 'x',\n *   initial: 0,\n *   next: x => x + 1,\n *   while: x => x < 3,\n *   do: ({ x }) => {\n *     // do something 3 times\n *   }\n * })\n *\n * @category Flow\n */\nexport const forLoop = <T = Serializable>(options: ConstructorParameters<typeof ForLoop<T>>[0]) => new ForLoop<T>(options);\n\n/**\n * Create a loop that iterates over an array. This functions like a standard\n * `Array#forEach` method.\n *\n * @param options.do - The part that gets repeated. This can contain any type of\n * {@link FlowDefintion}, a list of functions, or more Flow commands. The\n * functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link\n * Do|Do.continue}, can also be used here to cause the current loop to be\n * interupted.\n *\n * @param options.name - The current value of collection will be added to the\n * {@link FlowArguments} under a key with this name.\n *\n * @param options.collection - A collection of values to loop over. This can be\n * declared as an array or as a method that accept the {@link FlowArguments}\n * used up to this point in the flow and return the collection Array. This\n * expression is evaluated *only once* at the start of the loop.\n *\n * @example\n * forEach({ name: 'card', collection: () => deck.all(Card), do: [\n *   // show each card from the deck to player in turn\n *   ({ card }) => card.showTo(player),\n *   playerActions({ actions: [\n *     'chooseCard',\n *     'pass',\n *   ]}),\n * ]});\n *\n * @category Flow\n */\nexport const forEach = <T extends Serializable>(options: ConstructorParameters<typeof ForEach<T>>[0]) => new ForEach<T>(options);\n\n/**\n * Create a loop that iterates over each player. This is the same as {@link\n * forEach} with the additional behaviour of setting the {@link\n * PlayerCollection#current | current player} on each iteration of the loop.\n *\n * @param options.do - The part that gets repeated for each player. This can\n * contain any type of {@link FlowDefintion}, a list of functions, or more Flow\n * commands. The functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link\n * Do|Do.continue}, can also be used here to cause the current loop to be\n * interupted.\n *\n * @param options.name - The current player will be added to the {@link\n * FlowArguments} under a key with this name.\n *\n * @param options.startingPlayer - Declare the player to start the loop. If not\n * specified, this will be the first player in turn order.\n *\n * @param options.nextPlayer - Declare a method to select the next player. If\n * not specified this will follow turn order. See {@link\n * PlayerCollection#sortby} for more information.\n *\n * @param options.turns - If specified, loop through each play this many\n * times. Default is 1.\n *\n * @param options.continueUntil - If specified, rather than loop through each\n * player for a certain number of turns, the loop will continue until the\n * provided condition is true. This function accepts the player for the current\n * loop as its only argument.\n *\n * @example\n * eachPlayer({ name: 'biddingPlayer', do: // each player in turn has a chance to bid\n *   playerActions({ actions: [ 'bid', 'pass' ] })\n * });\n *\n * @category Flow\n */\nexport const eachPlayer = (options: ConstructorParameters<typeof EachPlayer>[0]) => new EachPlayer(options);\n\n/**\n * Provides a branching flow on a condition. This operates like a standard\n * `if... else`\n *\n * @param options.if - Condition to test for true/false. This function accepts all\n * {@link FlowArguments}.\n *\n * @param options.do - The part that gets run if the condition is true. This can\n * contain any type of {@link FlowDefintion}, a list of functions, or more Flow\n * commands. The functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link\n * Do|Do.continue}, can also be used here to cause the current loop to be\n * interupted.\n *\n * @param options.else - As `do`, but runs if the condition is false. Optional.\n *\n * @category Flow\n */\nexport const ifElse = (options: ConstructorParameters<typeof IfElse>[0]) => new IfElse(options);\n\n/**\n * Provides a branching flow on a condition with multiple outcomes. This\n * operates like a standard `switch... case`\n *\n * @param options.switch - Expression to evaluate for determining which case\n * should run. This function accepts all {@link FlowArguments}.\n *\n * @param options.name - If a name is provided, the value that results from\n * evaluating `switch` will be added to the {@link FlowArguments} under a key\n * with this name.\n *\n * @param options.cases - An array of conditions that will test whether they\n * meet the conditions based on the evaluated `switch` and execute their `do`\n * block. The case block can contain an `eq` which will test for equality with a\n * provided value, or `test` which will test the value using a provided function\n * that must return a boolean. Only the first one that meets the condition will\n * run. The `do` can contain any type of {@link FlowDefintion}.\n *\n * @param options.default - If no case qualifies, a `default` case can be\n * provided.\n *\n * @example\n * switchCase({\n *   name: 'switch',\n *   switch: () => deck.top(Card)?.suit,\n *   cases: [\n *     { eq: 'D', do: () => { /* ... diamonds *\\/ } },\n *     { eq: 'H', do: () => { /* ... hearts *\\/ } },\n *     { eq: 'S', do: () => { /* ... spades *\\/ } },\n *     { eq: 'C', do: () => { /* ... clubs *\\/ } },\n *   ],\n *   default: () => { /* ... there is no card *\\/ }\n * })\n *\n * @category Flow\n */\nexport const switchCase = <T extends Serializable>(options: ConstructorParameters<typeof SwitchCase<T>>[0]) => new SwitchCase<T>(options);\n\n/**\n * Create a flow for a set of players that can be done by all players\n * simulataneously in any order. This is similiar to {@link eachPlayer} except\n * that the players can act in any order.\n *\n * @param options.do - The part that each player can perform. This can contain\n * any type of {@link FlowDefintion}, a list of functions, or more Flow\n * commands. Each player will go through the defined flows individually and may\n * be at difference stages. The flow will complete when all players have\n * completed this flow. If {@link Do|Do.repeat}, {@link Do|Do.break} or {@link\n * Do|Do.continue} is called, the current loop can be interupted, *regardless of\n * what the other players have done*.\n *\n * @param options.name - The player acting will be added to the {@link\n * FlowArguments} under a key with this name for flows within this `do`.\n *\n * @param options.players - Declare the players to perform this `do`. If not\n * specified, this will be all players.\n *\n * @example\n * everyPlayer({ name: 'passCardPlayer', do: ( // each player selects a card from hand or passes\n *   playerActions({ actions: [ 'selectCard', 'pass' ]}),\n * ]});\n *\n * @category Flow\n */\nexport const everyPlayer = (options: ConstructorParameters<typeof EveryPlayer>[0]) => new EveryPlayer(options);\n"
  },
  {
    "path": "src/flow/switch-case.ts",
    "content": "import Flow from './flow.js';\n\nimport { serialize, deserialize } from '../action/utils.js';\n\nimport type { FlowArguments, FlowDefinition, FlowBranchNode, FlowStep } from './flow.js';\nimport type { Serializable } from '../action/utils.js';\n\nexport type SwitchCasePostion<T> = { index?: number, value?: T, default?: boolean }\nexport type SwitchCaseCases<T> = ({eq: T, do: FlowDefinition} | {test: (a: T) => boolean, do: FlowDefinition})[];\n\nexport default class SwitchCase<T extends Serializable> extends Flow {\n  position: SwitchCasePostion<T>;\n  switch: ((a: FlowArguments) => T) | T;\n  cases: SwitchCaseCases<T>;\n  default?: FlowDefinition;\n  type: FlowBranchNode['type'] = \"switch-case\";\n\n  constructor({ name, switch: switchExpr, cases, default: def }: {\n    name?: string,\n    switch: ((a: FlowArguments) => T) | T,\n    cases: SwitchCaseCases<T>;\n    default?: FlowDefinition\n  }) {\n    super({ name });\n    this.switch = switchExpr;\n    this.cases = cases;\n    this.default = def;\n  }\n\n  reset() {\n    const test = (typeof this.switch === 'function') ? this.switch(this.flowStepArgs()) : this.switch;\n    let position: typeof this.position = { index: -1, value: test }\n    for (let c = 0; c != this.cases.length; c += 1) {\n      const ca = this.cases[c];\n      if ('test' in ca && ca.test(test) || ('eq' in ca && ca.eq === test)) {\n        position.index = c;\n        break;\n      }\n    }\n    if (position.index === -1 && this.default) position.default = true;\n    this.setPosition(position);\n  }\n  \n  currentBlock() {\n    if (this.position.default) return this.default;\n    if (this.position.index !== undefined && this.position.index >= 0) {\n      return this.cases[this.position.index].do;\n    }\n  }\n\n  toJSON(forPlayer=true) {\n    return {\n      index: this.position.index,\n      value: serialize(this.position.value, forPlayer),\n      default: !!this.position.default\n    };\n  }\n\n  fromJSON(position: any) {\n    return {\n      index: position.index,\n      value: deserialize(position.value, this.gameManager.game),\n      default: position.default,\n    };\n  }\n\n  allSteps(): FlowDefinition {\n    const cases = this.cases.reduce<FlowStep[]>((a, f) => a.concat(f.do ? ((f.do instanceof Array) ? f.do : [f.do]) : []), []);\n    const defaultExpr = this.default ? ((this.default instanceof Array) ? this.default : [this.default]) : [];\n    return cases.concat(defaultExpr);\n  }\n\n  toString(): string {\n    return `switch-case${this.name ? \":\" + this.name : \"\"} (${this.position.value}${this.block instanceof Array ? ', item #' + this.sequence: ''})`;\n  }\n\n  visualize(top: Flow) {\n    let block: string | undefined = undefined;\n    if (this.position.default) {\n      block = 'default'\n    } else if (this.position.index !== undefined && this.position.index >= 0) {\n      const c = this.cases[this.position.index];\n      block = String('eq' in c ? c.eq : c.test);\n    }\n\n    return this.visualizeBlocks({\n      type: 'switchCase',\n      top,\n      blocks: Object.fromEntries(\n        this.cases.map(c => [String('eq' in c ? c.eq : c.test), c.do instanceof Array ? c.do : [c.do]]).concat([\n          this.default ? ['default', (this.default instanceof Array ? this.default : [this.default])] : []\n        ])\n      ) as Record<string, FlowStep[]>,\n      block,\n      position: this.position?.value,\n    });\n  }\n}\n"
  },
  {
    "path": "src/flow/while-loop.ts",
    "content": "import Flow from './flow.js';\nimport { FlowControl } from './enums.js';\nimport { InterruptControl } from './enums.js';\n\nimport type { FlowArguments, FlowDefinition, FlowBranchNode } from './flow.js';\n\nexport type WhileLoopPosition = { index: number, value?: any };\n\nexport default class WhileLoop extends Flow {\n  block: FlowDefinition;\n  position: WhileLoopPosition;\n  whileCondition: (position: WhileLoopPosition) => boolean;\n  type: FlowBranchNode['type'] = 'loop';\n  next?: (...a: any) => void;\n  initial?: any;\n\n  constructor({ do: block, while: whileCondition }: {\n    while: (a: FlowArguments) => boolean,\n    do: FlowDefinition,\n  }) {\n    super({ do: block });\n    this.whileCondition = () => whileCondition(this.flowStepArgs());\n  }\n\n  reset() {\n    const position: typeof this.position = { index: 0 };\n    if (this.initial !== undefined) position.value = this.initial instanceof Function ? this.initial(this.flowStepArgs()) : this.initial\n\n    if (!this.whileCondition(position)) {\n      this.setPosition({...position, index: -1});\n    } else {\n      this.setPosition(position);\n    }\n  }\n\n  currentBlock() {\n    if (this.position.index !== -1) return this.block;\n  }\n\n  advance() {\n    if (this.position.index > 10000) throw Error(`Endless loop detected: ${this.name}`);\n    if (this.position.index === -1) {\n      return this.exit();\n    }\n    const position: typeof this.position = { ...this.position, index: this.position.index + 1 };\n    if (this.next && this.position.value !== undefined) position.value = this.next(this.position.value);\n    if (!this.whileCondition(position)) return this.exit();\n    this.setPosition(position);\n    return FlowControl.ok;\n  }\n\n  repeat() {\n    if (!this.whileCondition(this.position)) return this.exit();\n    this.setPosition(this.position);\n    return FlowControl.ok;\n  }\n\n  exit(): FlowControl.complete {\n    this.setPosition({...this.position, index: -1});\n    return FlowControl.complete;\n  }\n\n  interrupt(signal: InterruptControl) {\n    if (signal === InterruptControl.continue) return this.advance();\n    if (signal === InterruptControl.repeat) return this.repeat();\n    if (signal === InterruptControl.break) return this.exit();\n  }\n\n  allSteps() {\n    return this.block;\n  }\n\n  toString(): string {\n    return `loop${this.name ? \":\" + this.name : \"\"} (loop ${this.position.index === -1 ? 'complete' : '#' + this.position.index}${this.block instanceof Array ? ', item #' + this.sequence: ''})`;\n  }\n\n  visualize(top: Flow) {\n    const isLoop = this.whileCondition.toString() === '() => true';\n    return this.visualizeBlocks({\n      type: isLoop ? 'loop' : 'whileLoop',\n      top,\n      blocks: {\n        do: this.block instanceof Array ? this.block : [this.block]\n      },\n      block: 'do',\n      position: this.position ? this.position.index + 1 : undefined,\n    });\n  }\n}\n"
  },
  {
    "path": "src/game-creator.ts",
    "content": "import GameManager from './game-manager.js';\n\nimport type { Game } from './board/index.js';\nimport type { SetupState, GameState } from './interface.js';\nimport type { Player } from './player/index.js';\nimport type { ElementClass } from './board/element.js';\n\nexport type SetupFunction<G extends Game = Game> = (\n  state: SetupState | GameState,\n  options?: {rseed?: string, trackMovement?: boolean, mocks?: (game: G) => void}\n) => GameManager<G>\n\n/**\n * Create your game\n * @param playerClass - Your player class. This must extend {@link Player}. If\n * you do not need any custom Player attributes or behaviour, simply put {@link\n * Player} here. This becomes the `P` type generic used throughout Boardzilla.\n\n * @param gameClass - Your game class. This must extend {@link Game}. If you\n * do not need any custom Game attributes or behaviour, simply put {@link\n * Game} here. This becomes the `B` type generic used throughout Boardzilla.\n\n * @param options.setup - A function that sets up the game. This function\n * accepts a single argument which is the instance of {@link Game} for this game. The\n * function should create all the spaces and pieces you need before your game can\n * start and will typically call:\n * - {@link game#registerClasses} to add custom classes for Spaces and Pieces\n * - {@link game#defineActions} to create the game actions\n * - {@link game#defineFlow} to define the game's flow\n * @category Core\n */\nexport const createGame = <G extends Game>(\n  playerClass: {new(...a: any[]): Player},\n  gameClass: ElementClass<G>,\n  gameCreator: (game: G) => void\n): SetupFunction<G> => (\n  state: SetupState | GameState,\n  options?: {rseed?: string, trackMovement?: boolean, mocks?: (game: G) => void}\n): GameManager<G> => {\n  const gameManager = new GameManager(playerClass, gameClass);\n  const inSetup = !('board' in state);\n\n  globalThis.$ = gameManager.game._ctx.namedSpaces;\n\n  if (options?.rseed) gameManager.setRandomSeed(options.rseed);\n  gameManager.setSettings(state.settings);\n  gameManager.players.fromJSON(state.players);\n\n  // setup board to get all non-serialized setup (spaces, event handlers, graphs)\n  gameCreator(gameManager.game);\n  if (options?.mocks) options.mocks(gameManager.game);\n\n  if (options?.trackMovement) gameManager.trackMovement();\n  if (!inSetup) {\n    gameManager.sequence = state.sequence;\n    gameManager.messages = state.messages;\n    gameManager.announcements = state.announcements;\n    gameManager.game.fromJSON(state.board);\n    gameManager.players.assignAttributesFromJSON(state.players);\n    gameManager.setFlowFromJSON(state.position);\n  } else {\n    gameManager.start();\n    gameManager.players.assignAttributesFromJSON(state.players);\n  }\n\n  return gameManager;\n};\n"
  },
  {
    "path": "src/game-manager.ts",
    "content": "import {\n  Space,\n  Piece,\n  GameElement\n} from './board/index.js';\nimport { Action, Selection } from './action/index.js';\nimport { Player, PlayerCollection } from './player/index.js';\nimport Flow, { FlowBranchJSON } from './flow/flow.js';\nimport ActionStep from './flow/action-step.js';\nimport { deserialize, serialize } from './action/utils.js';\n\nimport random from 'random-seed';\n\nimport type { BaseGame } from './board/game.js';\nimport type { BasePlayer } from './player/player.js';\nimport type { ElementClass } from './board/element.js';\nimport type { PlayerState, GameUpdate, GameState } from './interface.js';\nimport type { SerializedArg } from './action/utils.js';\nimport type { Argument, ActionStub } from './action/action.js';\nimport type { ResolvedSelection } from './action/selection.js';\nimport type { SubflowSignal } from './flow/enums.js';\n\n// find all non-method non-internal attr's\nexport type PlayerAttributes<T extends Player = Player> = {\n  [\n    K in keyof InstanceType<{new(...args: any[]): T}>\n      as InstanceType<{new(...args: any[]): T}>[K] extends (...args: unknown[]) => unknown ? never : (K extends '_players' | 'game' | 'gameManager' ? never : K)\n  ]: InstanceType<{new(...args: any[]): T}>[K]\n}\n\n// a Move is a request from a particular Player to perform a certain Action with supplied args\nexport type Move = {\n  player: Player,\n  name: string,\n  args: Record<string, Argument>\n};\n\nexport type PendingMove = {\n  name: string,\n  prompt?: string,\n  args: Record<string, Argument>,\n  selections: ResolvedSelection[],\n};\n\nexport type SerializedMove = {\n  name: string,\n  args: Record<string, SerializedArg>\n}\n\nexport type Message = {\n  position?: number\n  body: string\n}\n\nexport type ActionDebug = Record<string, {\n  args: Record<string, 'sel' | 'skip' | 'only-one' | 'always' | 'tree' | 'forced' | 'imp' | 'ask' | 'future'>,\n  // pruned?: Record<string, Argument[]>\n  impossible?: boolean\n}>\n\nexport type FlowStackJSON = {\n  name?: string,\n  args?: Record<string, any>,\n  currentPosition: number[],\n  stack: FlowBranchJSON[]\n}\n\n/**\n * Game manager is used to coordinate other classes, the {@link Game}, the\n * {@link Player}'s, the {@link Action}'s and the {@link Flow}.\n * @category Core\n */\nexport default class GameManager<G extends BaseGame = BaseGame, P extends BasePlayer = BasePlayer> {\n  flows: Record<string, Flow> = {}; // list of defined flows, including at minimum __main__. includes any __followup[n]__\n  flowState: FlowStackJSON[] = []; // current state for all flows\n  /**\n   * The players in this game. See {@link Player}\n   */\n  players: PlayerCollection<P> = new PlayerCollection<P>;\n  /**\n   * The game. See {@link Game}\n   */\n  game: G;\n  settings: Record<string, any>;\n  actions: Record<string, (player: P) => Action<Record<string, Argument>>>;\n  sequence: number = 0;\n  /**\n   * Current game phase\n   */\n  phase: 'new' | 'started' | 'finished' = 'new';\n  rseed: string;\n  random: () => number;\n  messages: Message[] = [];\n  announcements: string[] = [];\n  intermediateUpdates: GameState[][] = [];\n  /**\n   * If true, allows any piece to be moved or modified in any way. Used only\n   * during development.\n   */\n  godMode = false;\n  winner: P[] = [];\n\n  constructor(playerClass: {new(...a: any[]): P}, gameClass: ElementClass<G>, elementClasses: ElementClass[] = []) {\n    this.players = new PlayerCollection<P>();\n    this.players.className = playerClass;\n    this.game = new gameClass({ gameManager: this, classRegistry: [GameElement, Space, Piece, ...elementClasses]})\n    this.players.game = this.game;\n  }\n\n  /**\n   * configuration functions\n   */\n\n  setSettings(settings: Record<string, any>) {\n    this.settings = settings;\n  }\n\n  setRandomSeed(rseed: string) {\n    this.rseed = rseed;\n    this.random = random.create(rseed).random;\n    if (this.game.random) this.game.random = this.random;\n  }\n\n  /**\n   * flow functions\n   * @internal\n   */\n\n  // start the game fresh\n  start() {\n    if (this.phase === 'started') throw Error('cannot call start once started');\n    if (!this.players.length) {\n      throw Error(\"No players\");\n    }\n    this.phase = 'started';\n    this.players.currentPosition = [...this.players].map(p => p.position)\n    this.flowState = [{stack: [], currentPosition: this.players.currentPosition}];\n    this.startFlow(this.flowState[0]);\n  }\n\n  play(): void {\n    if (this.phase === 'finished') return;\n    if (this.phase !== 'started') throw Error('cannot call play until started');\n\n    const result = this.flow().play();\n    if (result instanceof Flow) {\n      if ('continueIfImpossible' in result && result.continueIfImpossible) {\n        // check if move is impossible and advance here\n        const possible = this.players.allCurrent().some(player => this.getPendingMoves(player) !== undefined);\n        if (!possible) {\n          console.debug(`Continuing past playerActions \"${result.name}\" with no possible moves`);\n          this.flow().processMove({ player: this.players.currentPosition[0], name: '__continue__', args: {} });\n          this.play();\n        }\n      }\n      // now awaiting action\n    } else if (result) {\n      // proceed to new subflow\n      for (const flow of result.reverse()) this.beginSubflow(flow);\n      this.play();\n    } else {\n      // completed this flow, go up the stack\n      if (this.flowState.length > 1) {\n        // cede to previous flow\n        console.debug(`Completed \"${this.flowState[0].name}\" flow. Returning to \"${this.flowState[1].name ?? 'main' }\" flow`);\n        this.flowState.shift();\n        this.players.currentPosition = this.flowState[0].currentPosition;\n        this.play();\n      } else {\n        this.game.finish();\n      }\n    }\n  }\n\n  flow() {\n    return this.flows[this.flowState[0].name ?? '__main__'];\n  }\n\n  getFlowStep(name: string) {\n    for (const flow of Object.values(this.flows)) {\n      const step = flow.getStep(name);\n      if (step) return step;\n    }\n  }\n\n  beginSubflow(flow: SubflowSignal['data']) {\n    if (flow.name !== '__followup__' && flow.name !== '__main__' && !this.flows[flow.name]) throw Error(`No flow named \"${flow.name}\"`);\n    console.debug(`Proceeding to \"${flow.name}\" flow${flow.args ? ` with { ${Object.entries(flow.args).map(([k, v]) => `${k}: ${v}`).join(', ')} }` : ''}`);\n    // freeze current player in flow state\n    this.flowState[0].currentPosition = this.players.currentPosition;\n    // proceed to new flow on top of stack\n    let name = flow.name;\n    if (flow.name === '__followup__') {\n      let counter = 1;\n      do {\n        name = `__followup_${counter}__`;\n        counter += 1;\n      } while(this.flows[name])\n    }\n    this.flowState.unshift({\n      name,\n      args: serialize(flow.args),\n      currentPosition: this.players.currentPosition,\n      stack: []\n    });\n    this.startFlow(this.flowState[0]);\n  }\n\n  setFlowFromJSON(json: FlowStackJSON[]) {\n    this.flowState = json;\n    this.phase = 'started';\n    [...this.flowState].reverse().forEach(s => this.startFlow(s));\n  }\n\n  // hydrates flow with supplied json\n  startFlow(flowState: FlowStackJSON) {\n    const {name, args, stack} = flowState;\n    let flow: Flow;\n    const deserializedArgs = deserialize(args, this.game) as Record<string, Argument>;\n    if (name?.startsWith('__followup_')) {\n      const actions = deserializedArgs as any as ActionStub;\n      flow = new ActionStep({ name, player: actions.player, actions: [actions] });\n      flow.gameManager = this;\n      this.flows[name] = flow;\n    } else {\n      flow = this.flows[name ?? '__main__'];\n    }\n    if (stack.length) {\n      flow.setBranchFromJSON(stack);\n    } else {\n      flow.reset();\n    }\n    if (args) flow.args = deserializedArgs;\n  }\n\n  flowJSON(player: boolean = false) {\n    return this.flowState.map(flowState => {\n      const currentFlow = this.flows[flowState.name ?? '__main__'];\n      const currentState: FlowStackJSON = {\n        stack: currentFlow.branchJSON(!!player),\n        currentPosition: this.players.currentPosition\n      };\n      if (flowState.name) currentState.name = flowState.name;\n      if (currentFlow.args) currentState.args = serialize(currentFlow.args);\n      return currentState;\n    })\n  }\n\n  /**\n   * state functions\n   * @internal\n   */\n\n  getState(player?: P): GameState {\n    return {\n      players: this.players.map(p => p.toJSON() as PlayerAttributes), // TODO scrub for player\n      settings: this.settings,\n      position: this.flowJSON(!!player),\n      board: this.game.allJSON(player?.position),\n      sequence: this.sequence,\n      messages: this.messages.filter(m => player && (!m.position || m.position === player?.position)),\n      announcements: [...this.announcements],\n      rseed: player ? '' : this.rseed,\n    }\n  }\n\n  getPlayerStates(): PlayerState[] {\n    return this.players.map((p, i) => ({\n      position: p.position,\n      state: this.intermediateUpdates.length ?\n        this.intermediateUpdates.map(state => state[i]).concat([this.getState(p)]) :\n        this.getState(p)\n    }));\n  }\n\n  getUpdate(): GameUpdate {\n    this.sequence += 1;\n    if (this.phase === 'started') {\n      return {\n        game: {\n          state: this.getState(),\n          currentPlayers: this.players.currentPosition,\n          phase: this.phase\n        },\n        players: this.getPlayerStates(),\n        messages: this.messages,\n      }\n    }\n    if (this.phase === 'finished') {\n      return {\n        game: {\n          state: this.getState(),\n          winners: this.winner.map(p => p.position),\n          phase: this.phase\n        },\n        players: this.getPlayerStates(),\n        messages: this.messages,\n      }\n    }\n    throw Error('unable to initialize game');\n  }\n\n  contextualizeBoardToPlayer(player?: Player) {\n    const prev = this.game._ctx.player;\n    this.game._ctx.player = player;\n    return prev;\n  }\n\n  inContextOfPlayer<T>(player: Player, fn: () => T): T {\n    const prev = this.contextualizeBoardToPlayer(player);\n    const results = fn();\n    this.contextualizeBoardToPlayer(prev);\n    return results;\n  }\n\n  trackMovement(track=true) {\n    if (this.game._ctx.trackMovement !== track) {\n      this.game._ctx.trackMovement = track;\n      if (track) this.intermediateUpdates = [];\n    }\n  }\n\n  /**\n   * action functions\n   */\n\n  getAction(name: string, player: P) {\n    if (this.godMode) {\n      const godModeAction = this.godModeActions()[name];\n      if (godModeAction) {\n        godModeAction.name = name;\n        return godModeAction as Action & {name: string};\n      }\n    }\n\n    if (!this.actions[name]) {\n      throw Error(`No action found: \"${name}\". All actions must be specified in defineActions()`);\n    }\n\n    return this.inContextOfPlayer(player, () => {\n      const action = this.actions[name](player);\n      action.gameManager = this;\n      action.name = name;\n      return action as Action & {name: string};\n    });\n  }\n\n  godModeActions(): Record<string, Action> {\n    if (this.phase !== 'started') throw Error('cannot call god mode actions until started');\n    return {\n      _godMove: this.game.action({\n        prompt: \"Move\",\n      }).chooseOnBoard(\n        'piece', this.game.all(Piece),\n      ).chooseOnBoard(\n        'into', this.game.all(GameElement)\n      ).move(\n        'piece', 'into'\n      ),\n      _godEdit: this.game.action({\n        prompt: \"Change\",\n      })\n        .chooseOnBoard('element', this.game.all(GameElement))\n        .chooseFrom<'property', string>(\n          'property',\n          ({ element }) => Object.keys(element).filter(a => !GameElement.unserializableAttributes.concat(['_visible', 'mine', 'owner']).includes(a)),\n          { prompt: \"Change property\" }\n        ).enterText('value', {\n          prompt: ({ property }) => `Change ${property}`,\n          initial: ({ element, property }) => String(element[property as keyof GameElement])\n        }).do(({ element, property, value }) => {\n          let v: any = value\n          if (value === 'true') {\n            v = true;\n          } else if (value === 'false') {\n            v = false;\n          } else if (parseInt(value).toString() === value) {\n            v = parseInt(value);\n          }\n          // @ts-ignore\n          element[property] = v;\n      })\n    };\n  }\n\n  // given a player's move (minimum a selected action), attempts to process\n  // it. if not, returns next selection for that player, plus any implied partial\n  // moves\n  processMove({ player, name, args }: Move): string | undefined {\n    if (this.phase === 'finished') return 'Game is finished';\n    let result: string | SubflowSignal['data'][] | undefined;\n    return this.inContextOfPlayer(player, () => {\n      if (this.godMode && this.godModeActions()[name]) {\n        const godModeAction = this.godModeActions()[name];\n        result = godModeAction._process(player, args);\n      } else {\n        result = this.flow().processMove({\n          name,\n          player: player.position,\n          args\n        });\n      }\n      console.debug(`Received move from player #${player.position} ${name}({${Object.entries(args).map(([k, v]) => `${k}: ${v}`).join(', ')}}) ${result ? (typeof result === 'string' ? '❌ ' + result : `⮕  ${result[0].name}({${Object.entries(result[0].args || {}).map(([k, v]) => `${k}: ${v}`).join(', ')}})`) : '✅'}`);\n      if (result instanceof Array) {\n        for (const flow of result.reverse()) this.beginSubflow(flow);\n      }\n      return typeof result === 'string' ? result : undefined;\n    });\n  }\n\n  allowedActions(player: P, debug?: ActionDebug): {\n    step?: string,\n    prompt?: string,\n    description?: string,\n    skipIf: 'always' | 'never' | 'only-one',\n    continueIfImpossible?: boolean,\n    actions: ActionStub[]\n  } {\n    const actions: ActionStub[] = this.godMode ? Object.keys(this.godModeActions()).map(name => ({ name })) : [];\n    if (!player.isCurrent()) return {\n      actions,\n      skipIf: 'always',\n    };\n\n    const actionStep = this.flow().actionNeeded(player);\n    if (actionStep?.actions) {\n      for (const allowedAction of actionStep.actions) {\n        if (allowedAction.name === '__pass__') {\n          actions.push(allowedAction);\n        } else {\n          const gameAction = this.getAction(allowedAction.name, player);\n          if (gameAction.isPossible(allowedAction.args ?? {})) {\n            // step action config take priority over action config\n            actions.push({ ...gameAction, ...allowedAction, player });\n          } else if (debug) {\n            debug[allowedAction.name] = { impossible: true, args: {} };\n          }\n        }\n      }\n      return {\n        ...actionStep,\n        actions\n      }\n    }\n\n    // check any other current players, if no action possible, warn and skip somehow ???\n    return {\n      skipIf: 'always',\n      actions: []\n    };\n  }\n\n  getPendingMoves(player: P, name?: string, args?: Record<string, Argument>, debug?: ActionDebug): {step?: string, prompt?: string, moves: PendingMove[]} | undefined {\n    if (this.phase === 'finished') return;\n    const allowedActions = this.allowedActions(player, debug);\n    let possibleActions: string[] = [];\n\n    if (allowedActions.actions.length) {\n      const { step, prompt, actions, skipIf } = allowedActions;\n\n      if (!name) {\n        let pendingMoves: PendingMove[] = [];\n        for (const action of actions) {\n          if (action.name === '__pass__') {\n            possibleActions.push('__pass__');\n            pendingMoves.push({\n              name: '__pass__',\n              args: {},\n              selections: [\n                new Selection('__action__', { prompt: action.prompt, value: '__pass__' }).resolve({})\n              ]\n            });\n            if (debug) {\n              debug['__pass__'] = { args: {} };\n            }\n          } else {\n            const playerAction = this.getAction(action.name, player)\n            const args = action.args || {}\n            let submoves = playerAction._getPendingMoves(args, debug);\n            if (submoves !== undefined) {\n              possibleActions.push(action.name);\n              // no sub-selections to show so just create a prompt selection of this action\n              // if an explcit confirm is required, this would be where to add the logic for it, e.g. playerAction.explicit? => selection[0].confirm\n              if (submoves.length === 0 || skipIf === 'never' || (skipIf === 'only-one' && actions.length > 1)) {\n                submoves = [{\n                  name: action.name,\n                  prompt: action.prompt,\n                  args,\n                  selections: [\n                    new Selection('__action__', {\n                      prompt: action.prompt ?? playerAction.prompt,\n                      value: action.name,\n                      skipIf\n                    }).resolve({})\n                  ]\n                }];\n              }\n              pendingMoves = pendingMoves.concat(submoves);\n            } else {\n              console.debug(`Action ${action.name} not allowed because no valid selections exist`);\n            }\n          }\n        }\n\n        if (possibleActions.length) return { step, prompt, moves: pendingMoves};\n\n      } else { // action provided\n        if (name === '__pass__') return { step, prompt, moves: [] };\n        const moves = this.getAction(name, player)?._getPendingMoves(args || {}, debug);\n        if (moves) return { step, prompt, moves };\n      }\n    }\n\n    return undefined;\n  }\n}\n"
  },
  {
    "path": "src/index.ts",
    "content": "import GameManager from './game-manager.js';\nimport { Game, Space } from './board/index.js';\nimport { Player } from './player/index.js';\n\nexport { Game, Space };\n\nexport { union } from './board/index.js';\nexport {\n  Piece,\n  Stack,\n  ConnectedSpaceMap,\n  AdjacencySpace,\n  FixedGrid,\n  SquareGrid,\n  HexGrid,\n  PieceGrid,\n  GameElement\n} from './board/index.js';\n\nexport { Do } from './flow/index.js';\n\nexport { createInterface, colors } from './interface.js';\nexport { times, range, shuffleArray } from './utils.js';\nexport { Player };\nexport { createGame } from './game-creator.js';\nexport {\n  render,\n  ProfileBadge,\n  toggleSetting,\n  numberSetting,\n  textSetting,\n  choiceSetting,\n} from './ui/index.js';\n\nexport { TestRunner } from './test-runner.js';\n\nimport type { ElementClass } from './board/element.js';\nimport type Action from './action/action.js';\n\nexport type { GameManager, Action, ElementClass };\n\ndeclare global {\n  /**\n   * Global reference to all unique named spaces\n   *\n   * @example\n   * game.create(Space, 'deck');\n   * ...\n   * $.deck // =>  equals the Space just created\n   */\n  var $: Record<string, Space<Game>>; // eslint-disable-line no-var\n}\n"
  },
  {
    "path": "src/interface.ts",
    "content": "import { deserializeArg } from './action/utils.js';\nimport { range } from './utils.js';\nimport random from 'random-seed';\n\nimport type { ElementJSON } from './board/element.js';\nimport type { PlayerAttributes, Message, SerializedMove } from './game-manager.js';\nimport type Player from './player/player.js';\nimport type { FlowBranchJSON } from './flow/flow.js';\nimport type { SetupFunction } from './game-creator.js';\nimport type { SerializedArg } from './action/utils.js';\n\nexport type SetupState = {\n  players: (PlayerAttributes & Record<string, any>)[],\n  settings: Record<string, any>,\n  randomSeed: string,\n}\n\nexport type GameState = {\n  players: PlayerAttributes[],\n  settings: Record<string, any>,\n  position: {name?: string, args?: Record<string, any>, currentPosition: number[], stack: FlowBranchJSON[]}[],\n  board: ElementJSON[],\n  sequence: number,\n  rseed: string,\n  messages: Message[],\n  announcements: string[],\n}\n\ntype GameStartedState = {\n  phase: 'started',\n  currentPlayers: number[],\n  state: GameState,\n}\n\ntype GameFinishedState = {\n  phase: 'finished',\n  winners: number[],\n  state: GameState,\n}\n\nexport type PlayerState = {\n  position: number\n  state: GameState | GameState[] // Game state, scrubbed\n  summary?: string\n  score?: number\n}\n\nexport type GameUpdate = {\n  game: GameStartedState | GameFinishedState\n  players: PlayerState[]\n  messages: Message[]\n}\n\ntype ReprocessHistoryResult = {\n  initialState: GameUpdate\n  updates: GameUpdate[]\n  error?: string\n}\n\ntype SerializedInterfaceMove = {\n  position: number\n  data: SerializedMove | SerializedMove[]\n}\n\nexport type GameInterface = {\n  initialState: (state: SetupState) => GameUpdate\n  processMove: (previousState: GameStartedState, move: SerializedInterfaceMove) => GameUpdate\n  seatPlayer(players: Player[], seatCount: number): {position: number, color: string, settings: any} | null\n  reprocessHistory(setup: SetupState, moves: SerializedInterfaceMove[]): ReprocessHistoryResult\n}\n\nexport const colors = [\n  '#d50000', '#00695c', '#304ffe', '#ff6f00', '#7c4dff',\n  '#ffa825', '#f2d330', '#43a047', '#004d40', '#795a4f',\n  '#00838f', '#408074', '#448aff', '#1a237e', '#ff4081',\n  '#bf360c', '#4a148c', '#aa00ff', '#455a64', '#600020'\n];\n\nfunction advanceRseed(rseed?: string) {\n  if (!rseed) {\n    rseed = String(Math.random());\n  } else {\n    rseed = String(random.create(rseed).random());\n  }\n\n  return rseed;\n}\n\nexport const createInterface = (setup: SetupFunction): GameInterface => {\n  return {\n    initialState: (state: SetupState): GameUpdate => {\n      let rseed = state.randomSeed;\n      if (!rseed) {\n        if (globalThis.window?.sessionStorage) { // web context, use a fixed initial seed for dev\n          let fixedRseed = sessionStorage.getItem('rseed') as string;\n          if (!fixedRseed) {\n            fixedRseed = String(Math.random());\n            sessionStorage.setItem('rseed', fixedRseed);\n          }\n          rseed = fixedRseed;\n        }\n        if (!rseed) rseed = advanceRseed(); // set the seed first because createGame may call random()\n      }\n      const gameManager = setup(state, {rseed, trackMovement: true});\n      if (globalThis.window) window.serverGameManager = gameManager;\n      if (gameManager.phase !== 'finished') gameManager.play();\n      return gameManager.getUpdate();\n    },\n    processMove: (\n      previousState: GameStartedState,\n      move: SerializedInterfaceMove,\n    ): GameUpdate => {\n      const rseed = advanceRseed(previousState.state.rseed);\n      previousState.state.rseed = rseed;\n\n      const gameManager = setup(previousState.state, {rseed, trackMovement: true});\n      const player = gameManager.players.atPosition(move.position)!;\n      // @ts-ignore\n      gameManager.messages = [];\n      gameManager.announcements = [];\n      if (!(move.data instanceof Array)) move.data = [move.data];\n\n      let error = undefined;\n      for (let i = 0; i !== move.data.length; i++) {\n        error = gameManager.processMove({\n          player,\n          name: move.data[i].name,\n          args: Object.fromEntries(Object.entries(move.data[i].args).map(([k, v]) => [k, deserializeArg(v as SerializedArg, gameManager.game)]))\n        });\n        if (error) {\n          throw Error(`Unable to process move: ${error}`);\n        }\n        if (gameManager.phase === 'finished') break;\n        gameManager.play();\n      }\n\n      return gameManager.getUpdate();\n    },\n\n    seatPlayer: (players: Player[], seatCount: number): {position: number, color: string, settings: any} | null => {\n      let usedPositions = range(1, seatCount);\n      let usedColors = [...colors];\n      for (const player of players) {\n        usedPositions = usedPositions.filter(position => position !== player.position);\n        usedColors = usedColors.filter(color => color !== player.color);\n      }\n      if (usedPositions.length) {\n        return {\n          position: usedPositions[0],\n          color: usedColors[0],\n          settings: {}\n        };\n      }\n      return null;\n    },\n\n    reprocessHistory(state: SetupState, moves: SerializedInterfaceMove[]): ReprocessHistoryResult {\n      let rseed = state.randomSeed;\n      const gameManager = setup(state, {rseed, trackMovement: false});\n      if (gameManager.phase !== 'finished') gameManager.play();\n      const initialState = gameManager.getUpdate();\n      let error = undefined;\n      const updates: GameUpdate[] = [];\n\n      for (const move of moves) {\n        rseed = advanceRseed(rseed);\n        gameManager.setRandomSeed(rseed);\n        gameManager.messages = [];\n        gameManager.announcements = [];\n        gameManager.intermediateUpdates = [];\n        const player = gameManager.players.atPosition(move.position)!;\n        if (!(move.data instanceof Array)) move.data = [move.data];\n\n        for (let i = 0; i !== move.data.length; i++) {\n          try {\n            error = gameManager.processMove({\n              player,\n              name: move.data[i].name,\n              args: Object.fromEntries(Object.entries(move.data[i].args).map(([k, v]) => [k, deserializeArg(v as SerializedArg, gameManager.game)]))\n            });\n          } catch (e) {\n            error = e.message;\n          }\n          if (error || gameManager.phase === 'finished') break;\n          gameManager.play();\n        }\n        if (error) break;\n        updates.push(gameManager.getUpdate());\n        if (gameManager.phase === 'finished') break;\n      }\n\n      return {\n        initialState,\n        updates,\n        error\n      };\n    }\n  };\n}\n"
  },
  {
    "path": "src/player/collection.ts",
    "content": "import Player from './player.js';\n\nimport { shuffleArray } from '../utils.js';\nimport { deserializeObject } from '../action/utils.js';\n\nimport type { PlayerAttributes } from '../game-manager.js';\nimport type { Sorter } from '../board/index.js';\n\n/**\n * An Array-like collection of the game's players, mainly used in {@link\n * Game#players}. The array is automatically created when the game begins and\n * can be used to determine or alter play order. The order of the array is the\n * order of play, i.e. `game.players[1]` takes their turn right after\n * `game.players[0]`.\n * @noInheritDoc\n * @category Core\n */\nexport default class PlayerCollection<P extends Player> extends Array<P> {\n  /**\n   * An array of table positions that may currently act.\n   */\n  currentPosition: number[] = [];\n  className: {new(...a: any[]): P};\n  /**\n   * A reference to the {@link Game} class\n   */\n  game: P['game']\n\n  addPlayer(attrs: PlayerAttributes & Record<string, any>) {\n    const player = new this.className(attrs);\n    Object.assign(player, attrs, {_players: this});\n    this.push(player);\n    if (this.game) {\n      player.game = this.game;\n    }\n  }\n\n  /**\n   * Returns the player at a given table position.\n   */\n  atPosition(position: number) {\n    return this.find(p => p.position === position);\n  }\n\n  /**\n   * Returns the player that may currently act. It is an error to call current\n   * when multiple players can act\n   */\n  current(): P | undefined {\n    if (this.currentPosition.length > 1) throw Error(`Using players.current when ${this.currentPosition.length} players may act`);\n    return this.atPosition(this.currentPosition[0] ?? -1);\n  }\n\n  /**\n   * Returns the array of all players that may currently act.\n   */\n  allCurrent(): P[] {\n    return this.currentPosition.map(p => this.atPosition(p)!);\n  }\n\n  /**\n   * Returns the host player\n   */\n  host(): P {\n    return this.find(p => p.host)!;\n  }\n\n  /**\n   * Returns the array of players that may not currently act.\n   */\n  notCurrent() {\n    return this.filter(p => !this.currentPosition.includes(p.position));\n  }\n\n  /**\n   * Returns the array of players in the order of table positions. Does not\n   * alter the actual player order.\n   */\n  inPositionOrder() {\n    return this.sort((p1, p2) => (p1.position > p2.position ? 1 : -1));\n  }\n\n  /**\n   * Set the current player(s).\n   *\n   * @param players - The {@link Player} or table position of the player to act,\n   * or an array of either.\n   */\n  setCurrent(players: number | P | number[] | P[]) {\n    if (!(players instanceof Array)) players = [players] as number[] | P[];\n    players = players.map(p => typeof p === 'number' ? p : p.position);\n    this.currentPosition = players;\n  }\n\n  /**\n   * Advance the current player to act to the next player based on player order.\n   */\n  next() {\n    if (this.currentPosition.length === 0) {\n      this.currentPosition = [this[0].position];\n    } else if (this.currentPosition.length === 1) {\n      this.currentPosition = [this.after(this.currentPosition[0]).position];\n    }\n    return this.current()!\n  }\n\n  /**\n   * Return the next player to act based on player order.\n   */\n  after(player: number | P) {\n    return this[(this.turnOrderOf(player) + 1) % this.length];\n  }\n\n  /**\n   * Return the player next to this player at the table.\n   * @param steps - 1 = one step to the left, -1 = one step to the right, etc\n   */\n  seatedNext(player: P, steps = 1) {\n    return this.atPosition((player.position + steps - 1) % this.length + 1)!;\n  }\n\n  /**\n   * Returns the turn order of the given player, starting with 0. This is\n   * distinct from {@link Player#position}. Turn order can be altered during a\n   * game, whereas table position cannot.\n   */\n  turnOrderOf(player: number | P) {\n    if (typeof player !== 'number') player = player.position;\n    const index = this.findIndex(p => p.position === player);\n    if (index === -1) throw Error(\"No such player\");\n    return index;\n  }\n\n  /**\n   * Sorts the players by some means, changing the turn order.\n   * @param key - A key of function for sorting, or a list of such. See {@link\n   * Sorter}\n   * @param direction - `\"asc\"` to cause players to be sorted from lowest to\n   * highest, `\"desc\"` for highest to lower\n   */\n  sortBy(key: Sorter<P> | (Sorter<P>)[], direction?: \"asc\" | \"desc\") {\n    const rank = (p: P, k: Sorter<P>) => typeof k === 'function' ? k(p) : p[k]\n    const [up, down] = direction === 'desc' ? [-1, 1] : [1, -1];\n    return this.sort((a, b) => {\n      const keys = key instanceof Array ? key : [key];\n      for (const k of keys) {\n        const r1 = rank(a, k);\n        const r2 = rank(b, k);\n        if (r1 > r2) return up;\n        if (r1 < r2) return down;\n      }\n      return 0;\n    });\n  }\n\n  /**\n   * Returns a copy of this collection sorted by some {@link Sorter}.\n   */\n  sortedBy(key: Sorter<P> | (Sorter<P>)[], direction: \"asc\" | \"desc\" = \"asc\") {\n    return (this.slice(0, this.length) as this).sortBy(key, direction);\n  }\n\n  sum(key: ((e: P) => number) | (keyof {[K in keyof P]: P[K] extends number ? never: K})) {\n    return this.reduce((sum, n) => sum + (typeof key === 'function' ? key(n) : n[key] as unknown as number), 0);\n  }\n\n  withHighest(...attributes: Sorter<P>[]) {\n    return this.sortedBy(attributes, 'desc')[0];\n  }\n\n  withLowest(...attributes: Sorter<P>[]) {\n    return this.sortedBy(attributes, 'asc')[0];\n  }\n\n  shuffle() {\n    shuffleArray(this, this.game?.random || Math.random);\n  }\n\n  max<K extends keyof P>(key: K): P[K] {\n    return this.sortedBy(key, 'desc')[0][key];\n  }\n\n  min<K extends keyof P>(key: K): P[K] {\n    return this.sortedBy(key, 'asc')[0][key];\n  }\n\n  fromJSON(players: Record<string, any>[]) {\n    // reset all on self\n    this.splice(0);\n\n    for (const p of players) {\n      this.addPlayer({position: p.position} as unknown as PlayerAttributes);\n    }\n  }\n\n  assignAttributesFromJSON(players: PlayerAttributes[]) {\n    for (let p = 0; p !== players.length; p++) {\n      Object.assign(this[p], deserializeObject(players[p], this.game));\n    }\n  }\n}\n"
  },
  {
    "path": "src/player/index.ts",
    "content": "export { default as Player } from './player.js';\nexport { default as PlayerCollection } from './collection.js';\n"
  },
  {
    "path": "src/player/player.ts",
    "content": "import { serializeObject } from '../action/utils.js';\n\nimport type PlayerCollection from './collection.js';\nimport type GameElement from '../board/element.js';\nimport type { BaseGame } from '../board/game.js';\nimport type { ElementClass } from '../board/element.js';\nimport type { ElementFinder, default as ElementCollection } from '../board/element-collection.js';\n\nexport interface BasePlayer extends Player<BaseGame, BasePlayer> {}\n\n/**\n * Base player class. Each game must declare a single player class that extends\n * this to be used for players joining the game. Additional properties and\n * methods on this class will be available in game, when e.g. a player argument\n * is passed to an action for the player taking that action.\n * @category Core\n */\nexport default class Player<G extends BaseGame = BaseGame, P extends BasePlayer = BasePlayer> {\n  /**\n   * A player's unique user id\n   */\n  id: string;\n\n  /**\n   * A player's chosen name\n   */\n  name: string;\n\n  /**\n   * String hex code of the player's chosen color\n   */\n  color: string;\n\n  /**\n   * String URL of the avatar image for this player\n   */\n  avatar: string;\n\n  /**\n   * Whether this player is the gane's host\n   */\n  host: boolean;\n\n  /**\n   * A player's seating position at the table. This is distinct from turn order,\n   * which is the order of `game.players`. Turn order can be altered during a\n   * game, whereas `position` cannot.\n   */\n  position: number;\n  settings?: any;\n  game: G;\n  _players: PlayerCollection<P>;\n\n  static isPlayer = true;\n\n  /**\n   * Provide list of attributes that are hidden from other players\n   */\n  static hide<P extends BasePlayer>(this: {new(): P; hiddenAttributes: string[]}, ...attrs: (keyof P)[]): void {\n    this.hiddenAttributes = attrs as string[];\n  }\n\n  static hiddenAttributes: string[] = [];\n\n  isCurrent() {\n    return this._players.currentPosition.includes(this.position);\n  }\n\n  /**\n   * Set this player as the current player\n   */\n  setCurrent(this: P) {\n    return this._players.setCurrent(this);\n  }\n\n  /**\n   * Returns an array of all other players.\n   */\n  others(): P[] {\n    return Array.from(this._players).filter(p => p as Player !== this);\n  }\n\n  /**\n   * Returns the other player. Only allowed in 2 player games\n   */\n  other(): P {\n    if (this._players.length !== 2) throw Error('Can only use `other` for 2 player games');\n    return this._players.find(p => p as Player !== this)!;\n  }\n\n  /**\n   * Finds all elements of a given type that are owned by this player. This is\n   * equivalent to calling `game.all(...)` with `{owner: this}` as one of the\n   * search terms. Also see {@link GameElement#owner}.\n   */\n  allMy<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;\n  allMy(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;\n  allMy(className?: any, ...finders: ElementFinder[]) {\n    return this.game.all(className, {owner: this}, ...finders);\n  }\n\n  /**\n   * Finds the first element of a given type that is owned by this player. This\n   * is equivalent to calling `game.first(...)` with `{owner: this}` as one of\n   * the search terms. Also see {@link GameElement#owner}.\n   */\n  my<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;\n  my(className?: ElementFinder, ...finders: ElementFinder[]): GameElement<G, P> | undefined;\n  my(className?: any, ...finders: ElementFinder[]) {\n    return this.game.first(className, {owner: this}, ...finders);\n  }\n\n  /**\n   * Returns true if any element of a given type is owned by this player. This\n   * is equivalent to calling `game.has(...)` with `{owner: this}` as one of\n   * the search terms. Also see {@link GameElement#owner}.\n   */\n  has<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): boolean;\n  has(className?: ElementFinder, ...finders: ElementFinder[]): boolean;\n  has(className?: any, ...finders: ElementFinder[]): boolean {\n    return this.game.has(className, {owner: this}, ...finders);\n  }\n\n  toJSON(player?: Player) {\n    let {_players, game: _b, ...attrs}: Record<any, any> = this;\n\n    // remove methods\n    attrs = serializeObject(\n      Object.fromEntries(Object.entries(attrs).filter(\n        ([key, value]) => (\n          typeof value !== 'function' &&\n            (player === undefined || player === this || !(this.constructor as typeof Player).hiddenAttributes.includes(key as keyof Player))\n        )\n      ))\n    );\n\n    if (globalThis.window) { // guard-rail in dev\n      try {\n        structuredClone(attrs);\n      } catch (e) {\n        console.error(`invalid properties on player ${this}:\\n${JSON.stringify(attrs, undefined, 2)}`);\n        throw(e);\n      }\n    }\n    return attrs;\n  }\n\n  toString() {\n    return this.name;\n  }\n}\n"
  },
  {
    "path": "src/test/actions_test.ts",
    "content": "/* global describe, it, beforeEach */\n/* eslint-disable no-unused-expressions */\nimport chai from 'chai';\nimport spies from 'chai-spies';\n\nimport Action from '../action/action.js';\nimport Player from '../player/player.js';\nimport Game from '../board/game.js';\nimport PieceGrid from '../board/piece-grid.js';\nimport Space from '../board/space.js';\nimport Piece from '../board/piece.js';\n\nchai.use(spies);\nconst { expect } = chai;\nconst player = new Player();\n\ndescribe('Actions', () => {\n  let testAction: Action<any>;\n  const actionSpy = chai.spy(({ n, m }: { n: number, m: number }) => {[n, m]});\n  beforeEach(() => {\n    testAction = new Action({\n      prompt: 'add some counters',\n    }).chooseNumber('n', {\n      prompt: 'how many?',\n      min: 0,\n      max: 3,\n    }).chooseNumber('m', {\n      prompt: 'how many more?',\n      min: ({ n }) => n * 1,\n      max: ({ n }) => n * 2,\n    }).do(actionSpy)\n  });\n\n  it('returns moves', () => {\n    const error = testAction._process(player, {});\n    expect(error).to.not.be.undefined;\n    const moves = testAction._getPendingMoves({});\n    expect(moves![0].selections[0].type).to.equal('number');\n    expect(moves![0].selections[0].min).to.equal(0);\n    expect(moves![0].selections[0].max).to.equal(3);\n  });\n\n  it('resolves dependant selections', () => {\n    const error = testAction._process(player, {n: 1});\n    expect(error).to.not.be.undefined;\n    const moves = testAction._getPendingMoves({n: 1});\n    expect(moves![0].selections[0].type).to.equal('number');\n    expect(moves![0].selections[0].min).to.equal(1);\n    expect(moves![0].selections[0].max).to.equal(2);\n  });\n\n  it('processes', () => {\n    testAction._process(player, {n: 1, m: 2});\n    expect(actionSpy).to.have.been.called.with({n: 1, m: 2});\n  });\n\n  describe('nextSelections', () => {\n    it('skipIf', () => {\n      const testAction = new Action({ prompt: 'pick an even number' })\n        .chooseFrom('a', [1, 2])\n        .chooseFrom('b', [3, 4], {skipIf: ({ a }) => a === 1 })\n        .chooseFrom('c', [5, 6])\n      expect(testAction._nextSelection({})?.resolvedChoices).to.deep.equal([{choice: 1}, {choice: 2}]);\n      expect(testAction._nextSelection({a: 2})?.resolvedChoices).to.deep.equal([{choice: 3}, {choice: 4}]);\n      expect(testAction._nextSelection({a: 1})?.resolvedChoices).to.deep.equal([{choice: 5},{choice: 6}]);\n      expect(testAction._nextSelection({a: 2, b: 3})?.resolvedChoices).to.deep.equal([{choice: 5},{choice: 6}]);\n      expect(testAction._nextSelection({a: 2, b: 3, c: 5})).to.be.undefined;\n      expect(testAction._nextSelection({a:1, c: 5})).to.be.undefined;\n    });\n\n    it('skipIf last', () => {\n      const testAction = new Action({ prompt: 'pick an even number' })\n        .chooseFrom('a', [1, 2] )\n        .chooseFrom('b', [5, 6])\n        .chooseFrom('c', [3, 4], { skipIf: ({ a }) => a === 1 })\n      expect(testAction._nextSelection({a: 2, b: 5})?.resolvedChoices).to.deep.equal([{choice: 3},{choice: 4}]);\n      expect(testAction._nextSelection({a: 1, b: 5})).to.be.undefined;\n    });\n  });\n\n  describe('getPendingMoves', () => {\n    let options: number[];\n\n    it('tests choices', () => {\n      const testAction1 = new Action({ prompt: 'pick an even number' }).chooseFrom('n', []);\n      expect(testAction1._getPendingMoves({})).to.be.undefined;\n\n      const testAction2 = new Action({ prompt: 'pick an even number' }).chooseFrom('n', [1]);\n      expect(testAction2._getPendingMoves({})?.length).to.equal(1);\n    });\n\n    it('tests bounds', () => {\n      const testAction1 = new Action({ prompt: 'pick an even number' }).chooseNumber('n', { min: -1, max: 0 });\n      expect(testAction1._getPendingMoves({})?.length).to.equal(1);\n\n      const testAction2 = new Action({ prompt: 'pick an even number' }).chooseNumber('n', { min: 0, max: -1 });\n      expect(testAction2._getPendingMoves({})).to.be.undefined;\n    });\n\n    it('resolves selection to determine viability', () => {\n      const testAction1 = new Action({ prompt: 'pick an even number' })\n        .chooseFrom('n', () => options.filter(n => n % 2 === 0))\n\n      options = [1,2];\n      expect(testAction1._getPendingMoves({})?.length).to.equal(1);\n      options = [1,3,5];\n      expect(testAction1._getPendingMoves({})).to.be.undefined;\n    });\n\n    it('resolves selection deeply to determine viability', () => {\n      const testAction1 = new Action({ prompt: 'pick an even number' })\n        .chooseFrom('n', () => options.filter(n => n % 2 === 0))\n        .chooseNumber('m', {\n          min: ({ n }) => n,\n          max: 4\n        });\n\n      options = [1,8,9,10,11,4];\n      expect(testAction1._getPendingMoves({})?.length).to.equal(1);\n      options = [1,8,9,10,11];\n      expect(testAction1._getPendingMoves({})).to.be.undefined;\n    });\n\n    it('does not fully resolve unbounded args', () => {\n      const testAction1 = new Action({ prompt: 'pick an even number' })\n        .chooseNumber('n', { min: 1 })\n        .chooseNumber('m', {\n          min: ({ n }) => n * 10,\n          max: 4\n        });\n\n      expect(testAction1._getPendingMoves({})?.length).to.equal(1);\n    });\n\n    it('combines', () => {\n      testAction = new Action({ prompt: 'purchase' })\n        .enterText('taunt', { prompt: 'taunt' })\n        .chooseGroup({\n          lumber: ['number'],\n          steel: ['number']\n        }, {\n          validate: ({ lumber, steel }) => lumber + steel < 10\n        });\n      const move1 = testAction._getPendingMoves({});\n      if (!move1) {\n        expect(move1).to.not.be.undefined;\n      } else {\n        expect(move1[0].selections.length).to.equal(1);\n        expect(move1[0].selections[0].name).to.equal('taunt');\n      }\n      const move2 = testAction._getPendingMoves({taunt: 'fu'});\n      if (!move2) {\n        expect(move2).to.not.be.undefined;\n      } else {\n        expect(move2[0].selections.length).to.equal(2);\n        expect(move2[0].selections[0].name).to.equal('lumber');\n        expect(move2[0].selections[1].name).to.equal('steel');\n        expect(move2[0].selections[1].error({ lumber: 5, steel: 5 })).to.not.be.undefined;\n        expect(move2[0].selections[1].error({ lumber: 5, steel: 4 })).to.be.undefined;\n      }\n    });\n\n    it('combines and skips', () => {\n      testAction = new Action({ prompt: 'purchase' })\n        .chooseGroup({\n          lumber: ['number', {min: 0, max: 3}],\n          steel: ['number', {min: 0, max: 0}],\n          meat: ['number', {min: 0, max: 3}],\n          plastic: ['number', {min: 0, max: 0}]\n        }, {\n          validate: ({ lumber, steel, meat, plastic }) => lumber + steel + meat + plastic > 0\n        });\n      const move = testAction._getPendingMoves({});\n      expect(move).to.not.be.undefined;\n      expect(move?.[0].selections.length).to.equal(2);\n      expect(move?.[0].selections[0].name).to.equal('lumber');\n      expect(move?.[0].selections[1].name).to.equal('meat');\n\n      const move2 = testAction._getPendingMoves({lumber: 1, meat: 0});\n      expect(move2).to.not.be.undefined;\n      expect(move2?.[0].selections.length).to.equal(1);\n      // bit odd, returns a forced choice so we can show something, although the UI will skip this ultimately\n      expect(move2?.[0].selections[0].name).to.equal('plastic');\n\n      const move3 = testAction._getPendingMoves({lumber: 0, meat: 0});\n      expect(move3).to.be.undefined;\n    });\n\n    it('combines forced', () => {\n      testAction = new Action({ prompt: 'purchase' })\n        .chooseNumber('lumber', {min: 0, max: 3})\n        .chooseNumber('steel', {min: 0, max: 0})\n        .chooseNumber('meat', {min: 0, max: 3})\n        .chooseNumber('plastic', {min: 0, max: 0,\n          validate: ({ lumber, steel, meat, plastic }) => lumber + steel + meat + plastic > 0\n        });\n      const move = testAction._getPendingMoves({});\n      if (!move) {\n        expect(move).to.not.be.undefined;\n      } else {\n        expect(move[0].selections.length).to.equal(1);\n        expect(move[0].selections[0].name).to.equal('lumber');\n        expect(move[0].args).to.deep.equal({steel: 0});\n      }\n      const move2 = testAction._getPendingMoves({lumber: 0, steel: 0});\n      if (!move2) {\n        expect(move2).to.not.be.undefined;\n      } else {\n        expect(move2[0].selections.length).to.equal(1);\n        expect(move2[0].selections[0].name).to.equal('meat');\n        expect(move2[0].args).to.deep.equal({lumber: 0, steel: 0, plastic: 0});\n      }\n    });\n  });\n\n  describe('getPendingMoves with skip strategies', () => {\n    let testAction: Action<{r: string, n: number}>;\n    beforeEach(() => {\n      testAction = new Action({ prompt: 'p' })\n        .chooseFrom('r', [{ label: 'Oil', choice: 'oil' }, { label: 'Garbage', choice: 'garbage' }])\n        .chooseNumber('n', {\n          max: ({ r }) => r === 'oil' ? 3 : 1\n        })\n    });\n\n    it('shows first selection', () => {\n      const moves = testAction._getPendingMoves({});\n      expect(moves?.length).to.equal(1);\n      expect(moves![0].selections.length).to.equal(1);\n      expect(moves![0].selections[0].type).to.equal('choices');\n      expect(moves![0].selections[0].resolvedChoices).to.deep.equal([{ label: 'Oil', choice: 'oil' }, { label: 'Garbage', choice: 'garbage' }]);\n    });\n\n    it('expands first selection', () => {\n      testAction.selections[0].skipIf = 'always';\n      const moves = testAction._getPendingMoves({});\n      expect(moves?.length).to.equal(2);\n      expect(moves![0].selections.length).to.equal(1);\n      expect(moves![0].selections[0].type).to.equal('number');\n      expect(moves![1].selections[0].type).to.equal('number');\n    });\n\n    it('provides next selection', () => {\n      const moves = testAction._getPendingMoves({r: 'oil'});\n      expect(moves?.length).to.equal(1);\n      expect(moves![0].selections.length).to.equal(1);\n      expect(moves![0].selections[0].type).to.equal('number');\n      expect(moves![0].args).to.deep.equal({r: 'oil'});\n    });\n\n    it('skips next selection', () => {\n      const moves = testAction._getPendingMoves({r: 'garbage'});\n      expect(moves?.length).to.equal(1);\n      expect(moves![0].selections.length).to.equal(1);\n      expect(moves![0].selections[0].type).to.equal('number');\n      expect(moves![0].args).to.deep.equal({r: 'garbage'});\n    });\n\n    it('completes', () => {\n      const moves = testAction._getPendingMoves({r: 'oil', n: 2});\n      expect(moves?.length).to.equal(0);\n    });\n\n    it('skips', () => {\n      testAction.selections[0].choices = ['oil'];\n      const moves = testAction._getPendingMoves({});\n      expect(moves?.length).to.equal(1);\n      expect(moves![0].selections.length).to.equal(1);\n      expect(moves![0].selections[0].type).to.equal('number');\n      expect(moves![0].args).to.deep.equal({r: 'oil'});\n    });\n\n    it('prevents skips', () => {\n      testAction.selections[0].choices = ['oil'];\n      testAction.selections[0].skipIf = 'never';\n      const moves = testAction._getPendingMoves({});\n      expect(moves?.length).to.equal(1);\n      expect(moves![0].selections.length).to.equal(1);\n      expect(moves![0].selections[0].type).to.equal('choices');\n      expect(moves![0].selections[0].resolvedChoices).to.deep.equal([{choice: 'oil'}]);\n    });\n  });\n\n  describe('validation rules', () => {\n    let testAction: Action<{r: string, n: number}>;\n    beforeEach(() => {\n      testAction = new Action({ prompt: 'p' })\n        .chooseFrom(\n          'r', ['oil', 'steel', 'garbage'],\n          {\n            validate: ({r}) => r === 'steel' ? 'no steel allowed' : true\n          }\n        ).chooseNumber(\n          'n', {\n            max: ({ r }) => r === 'oil' ? 3 : 1\n          }\n        );\n    });\n\n    it('validates choices', () => {\n      const moves = testAction._getPendingMoves({});\n      expect(moves?.[0].selections[0].resolvedChoices).to.deep.equal([\n        { choice: 'oil' },\n        { choice: 'steel', error: 'no steel allowed' },\n        { choice: 'garbage' },\n      ]);\n    });\n  });\n\n  describe('_withDecoratedArgs', () => {\n    let game: Game;\n    beforeEach(() => {\n      game = new Game({});\n    });\n\n    it('validates', () => {\n      testAction = new Action({\n        prompt: 'Choose a token',\n      }).chooseOnBoard(\n        'token', game.all(Space),\n      ).placePiece(\n        'token', game as unknown as PieceGrid<Game>,\n        {\n          rotationChoices: [0, 90, 180, 270],\n        }\n      ).chooseFrom('a', [1,2],\n        {\n          validate: ({ token, a }) => !!((token.column + token.row + a) % 2) === !!(token.rotation! % 180) || 'twist+color',\n        }\n      );\n\n      const args = { token: game.create(Space, 'space'), __placement__: [3, 2, 180], a: 2 };\n      expect(testAction._getError(testAction.selections[2].resolve(args), args)).to.equal('twist+color');\n\n      const args2 = { token: game.create(Space, 'space'), __placement__: [3, 2, 90], a: 2 };\n      expect(testAction._getError(testAction.selections[1].resolve(args2), args2)).to.be.undefined;\n    });\n\n    it('confirms', () => {\n      testAction = new Action({\n        prompt: 'Choose a token',\n      }).chooseOnBoard(\n        'token', game.all(Space),\n      ).placePiece(\n        'token', game as unknown as PieceGrid<Game>,\n        {\n          rotationChoices: [0, 90, 180, 270],\n        }\n      ).chooseFrom('a', [1,2],\n        {\n          confirm: [\n            'Place tile into row {{row}} and column {{column}} at {{rotation}} degrees for {{a}}?',\n            ({ token }) => ({ row: token.row, column: token.column, rotation: token.rotation! })\n          ]\n        }\n      );\n\n      const args = { token: game.create(Space, 'space'), __placement__: [3, 2, 180], a: 2 }\n      expect(testAction._getConfirmation(testAction.selections[2].resolve(args), args)).to.equal('Place tile into row 2 and column 3 at 180 degrees for 2?');\n    });\n  });\n\n  describe('board moves', () => {\n    let game: Game;\n    beforeEach(() => {\n      game = new Game({});\n      const space1 = game.create(Space, 'space-1');\n      game.create(Space, 'space-2');\n      space1.create(Piece, 'piece-1');\n      space1.create(Piece, 'piece-2');\n      space1.create(Piece, 'piece-3');\n      space1.create(Piece, 'piece-4');\n    });\n\n    it('chooseOnBoard', () => {\n      const boardAction = new Action({})\n        .chooseOnBoard('piece', game.all(Piece));\n      const moves = boardAction._getPendingMoves({});\n      expect(moves?.length).to.equal(1);\n      expect(moves![0].selections.length).to.equal(1);\n      expect(moves![0].selections[0].type).to.equal('board');\n      expect(moves![0].selections[0].resolvedChoices?.map(c => c.choice)).to.deep.equal(game.all(Piece));\n    });\n\n    it('moves', () => {\n      const boardAction = new Action({})\n        .chooseOnBoard('piece', game.all(Piece))\n        .move('piece', game.first('space-2')!);\n      boardAction._process(player, {piece: game.first('piece-1')!});\n      expect(game.first('space-1')!.all(Piece).length).to.equal(3);\n      expect(game.first('space-2')!.all(Piece).length).to.equal(1);\n    });\n\n    it('swaps', () => {\n      const boardAction = new Action({})\n        .chooseOnBoard('piece', game.all(Piece))\n        .chooseOnBoard('piece2', game.all(Piece))\n        .swap('piece', 'piece2');\n      boardAction._process(player, {piece: game.first('piece-1')!, piece2: game.first('piece-3')!});\n      expect(game.first('space-1')!.first(Piece)!.name).to.equal('piece-3');\n      expect(game.first('space-1')!.firstN(2, Piece)!.last()!.name).to.equal('piece-2');\n      expect(game.first('space-1')!.firstN(3, Piece)!.last()!.name).to.equal('piece-1');\n    });\n\n    it('reorders', () => {\n      const boardAction = new Action({}).reorder(game.all(Piece));\n      boardAction._process(player, {__reorder_from__: game.first('piece-1')!, __reorder_to__: game.first('piece-3')!});\n      expect(game.first('space-1')!.first(Piece)!.name).to.equal('piece-2');\n      expect(game.first('space-1')!.firstN(2, Piece)!.last()!.name).to.equal('piece-3');\n      expect(game.first('space-1')!.firstN(3, Piece)!.last()!.name).to.equal('piece-1');\n    });\n\n    it('places', () => {\n      const boardAction = new Action({})\n        .chooseOnBoard('piece', game.all(Piece))\n        .placePiece('piece', game.first('space-2') as PieceGrid<Game>);\n      boardAction._process(player, {piece: game.first('piece-1')!, \"__placement__\": [3, 2]});\n      expect(game.first('space-1')!.all(Piece).length).to.equal(3);\n      expect(game.first('space-2')!.all(Piece).length).to.equal(1);\n      const piece = game.first('piece-1')!;\n      expect(piece.row).to.equal(2);\n      expect(piece.column).to.equal(3);\n    });\n  });\n});\n"
  },
  {
    "path": "src/test/compiler.cjs",
    "content": "const tsNode = require('ts-node');\n\ntsNode.register({\n  project: './tsconfig.json',\n  ignore: ['.*\\.scss', '.*\\.ogg']\n});\n"
  },
  {
    "path": "src/test/fixtures/games.ts",
    "content": "import Player from '../../player/player.js';\nimport {\n  Game,\n  Space,\n  Piece,\n  PieceGrid,\n} from '../../board/index.js';\n\nexport class TestPlayer extends Player<TestGame, TestPlayer> {\n  tokens: number = 0;\n}\n\nexport class TestGame extends Game<TestGame, TestPlayer> {\n  tokens: number = 0;\n}\n\nexport class Token extends Piece<TestGame> {\n  color: 'red' | 'blue';\n}\n\nlet tiles: PieceGrid<Game>;\n\nconst gameFactory = (creator: (game: TestGame) => void) => (game: TestGame) => {\n  const { playerActions, loop, eachPlayer } = game.flowCommands;\n  tiles = game.create(PieceGrid, 'tiles', { rows: 3, columns: 3});\n\n  for (const player of game.players) {\n    const mat = game.create(Space, 'mat', { player });\n    mat.onEnter(Token, t => t.showToAll());\n  }\n\n  game.create(Space, 'pool');\n  $.pool.onEnter(Token, t => t.hideFromAll());\n  $.pool.createMany(game.setting('tokens') - 1, Token, 'blue', { color: 'blue' });\n  $.pool.create(Token, 'red', { color: 'red' });\n\n  game.defineFlow(\n    loop(\n      eachPlayer({\n        name: 'player',\n        do: playerActions({\n          actions: ['take']\n        }),\n      })\n    )\n  );\n\n  creator(game);\n}\n\n\nexport const starterGame = gameFactory(game => {\n  game.defineActions({\n    take: player => game.action({\n      prompt: 'Choose a token',\n    }).chooseOnBoard(\n      'token', $.pool.all(Token),\n    ).move(\n      'token', player.my('mat')!\n    ).message(\n      `{{player}} drew a {{token}} token.`\n    ).do(({ token }) => {\n      if (token.color === 'red') {\n        game.message(\"{{player}} wins!\", { player });\n        game.finish(player);\n      }\n    }),\n  });\n});\n\nexport const starterGameWithConfirm = gameFactory(game => {\n  game.defineActions({\n    take: player => game.action({\n      prompt: 'Choose a token',\n    }).chooseOnBoard(\n      'token', $.pool.all(Token),\n      { confirm: 'confirm?' }\n    ).move(\n      'token', player.my('mat')!,\n    ),\n  });\n});\n\nexport const starterGameWithValidate = gameFactory(game => {\n  game.defineActions({\n    take: player => game.action({\n      prompt: 'Choose a token',\n    }).chooseOnBoard(\n      'token', $.pool.all(Token),\n      { validate: ({ token }) => token.container()!.first(Token) === token ? 'not first' : undefined }\n    ).move(\n      'token', player.my('mat')!,\n    ),\n  });\n});\n\nexport const starterGameWithCompoundMove = gameFactory(game => {\n  game.defineActions({\n    take: player => game.action({\n      prompt: 'Choose a token',\n    }).chooseOnBoard(\n      'token', $.pool.all(Token),\n    ).chooseFrom(\n      'a', [1,2]\n    ).move(\n      'token', player.my('mat')!\n    ),\n  });\n});\n\nexport const starterGameWithTiles = gameFactory(game => {\n  game.defineActions({\n    take: () => game.action({\n      prompt: 'Choose a token',\n    }).chooseOnBoard(\n      'token', $.pool.all(Token),\n    ).placePiece(\n      'token', tiles\n    ),\n  });\n});\n\nexport const starterGameWithTilesConfirm = gameFactory(game => {\n  game.defineActions({\n    take: () => game.action({\n      prompt: 'Choose a token',\n    }).chooseOnBoard(\n      'token', $.pool.all(Token),\n    ).placePiece(\n      'token', tiles,\n      { confirm: \"confirm placement?\" }\n    ),\n  });\n});\n\nexport const starterGameWithTilesValidate = gameFactory(game => {\n  game.defineActions({\n    take: () => game.action({\n      prompt: 'Choose a token',\n    }).chooseOnBoard(\n      'token', $.pool.all(Token),\n    ).placePiece(\n      'token', tiles,\n      { validate: ({ token }) => (token.column + token.row) % 2 !== 0 ? 'must be black square' : undefined, }\n    ),\n  });\n});\n\nexport const starterGameWithTilesCompound = gameFactory(game => {\n  game.defineActions({\n    take: () => game.action({\n      prompt: 'Choose a token',\n    }).chooseOnBoard(\n      'token', $.pool.all(Token),\n    ).placePiece(\n      'token', tiles,\n    ).chooseFrom(\n      'a', [1,2]\n    ),\n  });\n});\n"
  },
  {
    "path": "src/test/flow_test.ts",
    "content": "import chai from 'chai';\nimport spies from 'chai-spies';\n\nimport Flow from '../flow/flow.js';\nimport {\n  playerActions,\n  loop,\n  whileLoop,\n  forLoop,\n  forEach,\n  switchCase,\n  ifElse,\n} from '../flow/index.js';\n\nimport {\n  Do,\n  FlowControl,\n} from '../flow/enums.js';\n\nimport type { FlowBranchJSON } from '../flow/flow.js';\n\nchai.use(spies);\nconst { expect } = chai;\n\ndescribe('Flow', () => {\n  let testFlow: Flow;\n  let stepSpy1: (...a: any[]) => any;\n  let stepSpy2: (...a: any[]) => any;\n  let actionSpy: (...a: any[]) => any;\n  let playSpy: (...a: any[]) => any;\n\n  beforeEach(() => {\n    stepSpy1 = chai.spy();\n    stepSpy2 = chai.spy();\n    actionSpy = chai.spy(() => {});\n    playSpy = chai.spy((a: string) => {a});\n    testFlow = new Flow({ name: 'test', do: [\n      () => stepSpy1(),\n      () => stepSpy2(),\n      () => {},\n      ifElse({ name: 'step4', if: () => true, do: [\n        () => {},\n        playerActions({\n          name: 'play-or-pass',\n          actions: [\n            {name: 'play', do: ({ play }) => playSpy(play.a)},\n            {name: 'pass', do: [ () => {} ]}\n          ]\n        }),\n        () => {}\n      ]}),\n      () => {}\n    ]});\n    const gameManager = {\n      flow: testFlow,\n      players: {\n        currentPosition: [1],\n        atPosition: () => ({position: 1}),\n        setCurrent: () => {}\n      },\n      getAction: (a: string) => ({\n        play: { _process: actionSpy, messages: [] },\n        pass: { _process: () => {}, messages: [] }\n      }[a]),\n      game: { },\n    };\n    // @ts-ignore mock gameManager\n    testFlow.gameManager = gameManager;\n    testFlow.gameManager.game.players = testFlow.gameManager.players;\n\n    testFlow.reset();\n  })\n  it('initial', () => {\n    expect(testFlow.branchJSON()).to.deep.equal([{ type: 'main', name: 'test', sequence: 0 }]);\n  });\n  it('setPosition', () => {\n    testFlow.setBranchFromJSON([{ type: 'main', name: 'test', sequence: 0 }]);\n    expect(testFlow.branchJSON()).to.deep.equals([{ type: 'main', name: 'test', sequence: 0 }]);\n  });\n  it('play from initial', () => {\n    testFlow.playOneStep();\n    expect(stepSpy1).to.have.been.called();\n    expect(stepSpy2).to.not.have.been.called();\n    expect(testFlow.branchJSON()).to.deep.equal([{ type: 'main', name: 'test', sequence: 1 }]);\n  });\n  it('play twice', () => {\n    testFlow.playOneStep();\n    testFlow.playOneStep();\n    expect(stepSpy1).to.have.been.called();\n    expect(stepSpy2).to.have.been.called();\n    expect(testFlow.branchJSON()).to.deep.equals([{ type: 'main', name: 'test', sequence: 2 }]);\n  });\n  it('play from state', () => {\n    testFlow.setBranchFromJSON([{ type: 'main', name: 'test', sequence: 1 }]);\n    testFlow.playOneStep();\n    expect(stepSpy1).not.to.have.been.called();\n    expect(stepSpy2).to.have.been.called();\n    expect(testFlow.branchJSON()).to.deep.equals([{ type: 'main', name: 'test', sequence: 2 }]);\n  });\n  it('nested', () => {\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 0 }\n    ]);\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 0 }\n    ]);\n  });\n  it('advances into nested', () => {\n    testFlow.setBranchFromJSON([{ type: 'main', name: 'test', sequence: 2 }]);\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 0 }\n    ]);\n  });\n  it('advances out of nested', () => {\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 2 }\n    ]);\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([{ type: 'main', name: 'test', sequence: 4 }]);\n  });\n  it('awaits action', () => {\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass' }\n    ]);\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: \"main\", name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass' }\n    ]);\n  });\n  it('receives action', () => {\n    testFlow.setBranchFromJSON([\n      { type: \"main\", name: \"test\", sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass' }\n    ]);\n    testFlow.processMove({ name: 'play', args: {a: 'violin'}, player: 1 });\n    expect(actionSpy).to.have.been.called();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: \"main\", name: \"test\", sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass', position: { name: 'play', args: {a: 'violin'}, player: 1 }}\n    ]);\n  });\n  it('rejects actions out of turn', () => {\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass' }\n    ]);\n    expect(() => testFlow.processMove({ name: 'play', args: {a: 'violin'}, player: 2 })).to.throw;\n  });\n  it('plays action', () => {\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass', position: { name: 'play', args: {a: 'violin'}, player: 1 }}\n    ]);\n    testFlow.playOneStep();\n    expect(playSpy).to.have.been.called.with('violin');\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 2 },\n    ]);\n  });\n  it('actions continue into other flows', () => {\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass' }\n    ]);\n    testFlow.processMove({ name: 'pass', args: {}, player: 1 });\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass', position: { name: 'pass', args: {}, player: 1 }, sequence: 0 },\n    ]);\n  });\n  it('plays', () => {\n    testFlow.play();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass' }\n    ]);\n    testFlow.processMove({ name: 'pass', args: {}, player: 1 });\n    const result = testFlow.play();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 4 }\n    ]);\n    expect(result).to.be.undefined;\n  });\n  it('serializes', () => {\n    const branch: FlowBranchJSON[] = [\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 },\n      { type: 'action', name: 'play-or-pass', position: { name: 'pass', args: {}, player: 1 }, sequence: 0 }\n    ];\n    testFlow.setBranchFromJSON(branch);\n    expect(testFlow.branchJSON()).to.deep.equals(branch);\n  });\n  it('finds by name', () => {\n    expect(testFlow.getStep('test')?.name).to.equal('test');\n    expect(testFlow.getStep('step4')?.name).to.equal('step4');\n    expect(testFlow.getStep('play-or-pass')?.name).to.equal('play-or-pass');\n  });\n  it('disallows duplicate step names',() => {\n    const duplFlow = new Flow({ name: 'test', do: [\n      () => stepSpy1(),\n      () => stepSpy2(),\n      () => {},\n      ifElse({ name: 'step4', if: () => true, do: [\n        () => {},\n        playerActions({\n          name: 'test',\n          actions: [\n            {name: 'play', do: ({ play }) => playSpy(play.a)},\n            {name: 'pass', do: [ () => {} ]}\n          ]\n        }),\n        () => {}\n      ]}),\n      () => {}\n    ]});\n    expect(() => duplFlow.getStep('test')).to.throw;\n  });\n});\n\ndescribe('Loop', () => {\n  let stepSpy1: (...a: any[]) => any\n  let stepSpy2: (...a: any[]) => any\n  let counter: number\n  let loop: Flow\n  let nonLoop: Flow\n  let testFlow: Flow;\n  beforeEach(() => {\n    stepSpy1 = chai.spy((x:number) => x);\n    stepSpy2 = chai.spy((x:number) => x);\n    counter = 10;\n    loop = whileLoop({ while: () => counter < 13, do: (\n      () => { stepSpy1(counter); counter += 1; }\n    )});\n\n    nonLoop = forLoop({ name: 'nonloop', initial: 0, next: loop => loop + 1, while: loop => loop < 0, do: (\n      ({ nonloop }) => stepSpy2(nonloop)\n    )});\n\n    testFlow = new Flow({ name: 'test', do: [\n      () => {},\n      loop,\n      () => {},\n      nonLoop,\n      () => {},\n    ]});\n    // @ts-ignore\n    testFlow.gameManager = { flow: testFlow, players: { setCurrent: () => {} } };\n\n    testFlow.reset();\n  })\n\n  it('enters loop', () => {\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 0 }\n    ]);\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 1 },\n      { type: 'loop', position: { index: 0 } }\n    ]);\n    expect(stepSpy1).to.not.have.been.called;\n  });\n  it('repeats loop', () => {\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 1 },\n      { type: 'loop', position: { index: 0 } }\n    ]);\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 1 },\n      { type: 'loop', position: { index: 1 } }\n    ]);\n    expect(stepSpy1).to.have.been.called.with(10);\n\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 1 },\n      { type: 'loop', position: { index: 2 } }\n    ]);\n    expect(stepSpy1).to.have.been.called.with(11);\n  });\n  it('exits loop', () => {\n    counter = 12;\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 1 },\n      { type: 'loop', position: { index: 2 } }\n    ]);\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 2 },\n    ]);\n  });\n  it('skips non-loop', () => {\n    testFlow.setBranchFromJSON([\n      { type: 'main', name: 'test', sequence: 2 },\n    ]);\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 3 },\n      { type: 'loop', name: 'nonloop', position: { index: -1, value: 0 } }\n    ]);\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'main', name: 'test', sequence: 4 },\n    ]);\n    expect(stepSpy2).to.not.have.been.called;\n  });\n\n  describe('nested', () => {\n    let stepSpy: (...a: any[]) => any;\n    let nestedLoop: Flow;\n    beforeEach(() => {\n      stepSpy = chai.spy((x: number, y: number) => {x; y});\n      nestedLoop = forLoop({\n        name: 'x',\n        initial: 0,\n        next: x => x + 1,\n        while: x => x < 3,\n        do: forLoop({\n          name: 'y',\n          initial: 0,\n          next: y => y + 1,\n          while: y => y < 2,\n          do: ({ x, y }) => stepSpy(x, y)\n        })\n      });\n\n      nestedLoop.reset();\n    })\n\n    it ('resets counters', () => {\n      while(nestedLoop.playOneStep() === FlowControl.ok);\n      expect(stepSpy).to.have.been.called.exactly(6);\n      expect(stepSpy).on.nth(1).be.called.with(0, 0);\n      expect(stepSpy).on.nth(2).be.called.with(0, 1);\n      expect(stepSpy).on.nth(3).be.called.with(1, 0);\n      expect(stepSpy).on.nth(4).be.called.with(1, 1);\n      expect(stepSpy).on.nth(5).be.called.with(2, 0);\n      expect(stepSpy).on.nth(6).be.called.with(2, 1);\n    });\n  });\n\n  describe('foreach', () => {\n    it ('loops', () => {\n      const stepSpy = chai.spy((x:number) => {x});\n      const loop = forEach({ name: 'foreach', collection: [3, 5, 7], do: ({ foreach }) => stepSpy(foreach) });\n      loop.reset();\n      while(loop.playOneStep() === FlowControl.ok);\n      expect(stepSpy).to.have.been.called.exactly(3);\n      expect(stepSpy).on.nth(1).be.called.with(3);\n      expect(stepSpy).on.nth(2).be.called.with(5);\n      expect(stepSpy).on.nth(3).be.called.with(7);\n    });\n    it ('resumes', () => {\n      const stepSpy = chai.spy((x:number) => {x});\n      const loop = forEach({ name: 'foreach', collection: [3, 5, 7], do: ({ foreach }) => stepSpy(foreach) });\n      // @ts-ignore mock gameManager\n      loop.gameManager = {game: {}}\n      loop.reset();\n      loop.setBranchFromJSON([\n        {\n          type: 'foreach',\n          name: 'foreach',\n          position: { index: 1, value: 5, collection: [3,5,7] }\n        }\n      ]);\n      loop.playOneStep();\n      expect(stepSpy).to.have.been.called.with(5);\n      expect(loop.playOneStep()).to.equal(FlowControl.complete);\n      expect(stepSpy).to.have.been.called.with(7);\n    });\n    it ('allows dynamic collection', () => {\n      const stepSpy = chai.spy((x:number) => {x});\n      const outerLoop = forLoop({ name: 'loop', initial: 1, next: loop => loop + 1, while: loop => loop != 3, do: (\n        forEach({ name: 'foreach', collection: ({ loop }) => [10 + loop, 20 + loop], do: ({ foreach }) => stepSpy(foreach) })\n      )});\n      outerLoop.reset();\n      while(outerLoop.playOneStep() === FlowControl.ok);\n      expect(stepSpy).to.have.been.called.exactly(4);\n      expect(stepSpy).on.nth(1).be.called.with(11);\n      expect(stepSpy).on.nth(2).be.called.with(21);\n      expect(stepSpy).on.nth(3).be.called.with(12);\n      expect(stepSpy).on.nth(4).be.called.with(22);\n    });\n    it ('empty collection', () => {\n      const stepSpy = chai.spy((x:number) => {x});\n      const empty = forEach({ name: 'foreach', collection: [], do: ({ foreach }) => stepSpy(foreach) });\n      empty.reset();\n      while(empty.playOneStep() === FlowControl.ok);\n      expect(stepSpy).not.to.have.been.called;\n    });\n\n  });\n});\n\ndescribe('Loop short-circuiting', () => {\n  it('can repeat', () => {\n    const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.repeat() : undefined);\n    const stepSpy2 = chai.spy((_: string, x:number) => {x});\n    const shortLoop = forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [\n      ({ loop }) => stepSpy2('start', loop),\n      ({ loop }) => stepSpy1(loop),\n      ({ loop }) => stepSpy2('end', loop)\n    ]});\n    shortLoop.reset();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    expect(stepSpy2).to.have.been.called.with('start', 11);\n    expect(stepSpy2).to.have.been.called.with('end', 11);\n    expect(stepSpy2).to.have.been.called.with('start', 12);\n    expect(stepSpy2).not.to.have.been.called.with('end', 12);\n    expect(stepSpy2).not.to.have.been.called.with('start', 13);\n  });\n\n  it('can skip', () => {\n    const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.continue() : undefined);\n    const stepSpy2 = chai.spy((_: string, x:number) => {x});\n    const shortLoop = forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [\n      ({ loop }) => stepSpy2('start', loop),\n      ({ loop }) => stepSpy1(loop),\n      ({ loop }) => stepSpy2('end', loop)\n    ]});\n    shortLoop.reset();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    expect(stepSpy2).to.have.been.called.with('start', 11);\n    expect(stepSpy2).to.have.been.called.with('end', 11);\n    expect(stepSpy2).to.have.been.called.with('start', 12);\n    expect(stepSpy2).not.to.have.been.called.with('end', 12);\n    expect(stepSpy2).to.have.been.called.with('start', 13);\n  });\n\n  it('can break', () => {\n    const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.break() : undefined);\n    const stepSpy2 = chai.spy((_: string, x:number) => {x});\n    const shortLoop = forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [\n      ({ loop }) => stepSpy2('start', loop),\n      ({ loop }) => stepSpy1(loop),\n      ({ loop }) => stepSpy2('end', loop)\n    ]});\n    shortLoop.reset();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    const result = shortLoop.playOneStep();\n    expect(result).to.equal(FlowControl.complete);\n    expect(stepSpy2).to.have.been.called.with('start', 11);\n    expect(stepSpy2).to.have.been.called.with('end', 11);\n    expect(stepSpy2).to.have.been.called.with('start', 12);\n    expect(stepSpy2).not.to.have.been.called.with('end', 12);\n    expect(stepSpy2).not.to.have.been.called.with('start', 13);\n  });\n\n  it('rejects interrupt with no loop', () => {\n    const badLoop = ifElse({ if: () => true, do: Do.break })\n    // @ts-ignore mock gameManager\n    badLoop.gameManager = {phase: 'started'};\n    badLoop.reset();\n    expect(() => badLoop.play()).to.throw(/Do\\.break/);\n  });\n\n  it('can continue to a named loop', () => {\n    const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.continue('loop') : undefined);\n    const stepSpy2 = chai.spy();\n    const stepSpy3 = chai.spy();\n    const shortLoop = forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 2, do: [\n      stepSpy2,\n      forLoop({ name: 'loop2', initial: 10, next: loop2 => loop2 + 1, while: loop2 => loop2 < 20, do: [\n        ({ loop2 }) => stepSpy1(loop2),\n      ]}),\n      stepSpy3\n    ]});\n    shortLoop.reset();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 0, loop2: 12 });\n    expect(stepSpy2).to.have.been.called.exactly(1);\n    expect(stepSpy1).to.have.been.called.exactly(2);\n    expect(stepSpy3).to.have.been.called.exactly(0);\n\n    shortLoop.playOneStep(); // continue to outer loop\n    expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 1 });\n    expect(stepSpy1).to.have.been.called.exactly(3);\n    expect(stepSpy2).to.have.been.called.exactly(1);\n    expect(stepSpy3).to.have.been.called.exactly(0);\n\n    shortLoop.playOneStep();\n    expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 1, loop2: 10 });\n    expect(stepSpy1).to.have.been.called.exactly(3);\n    expect(stepSpy2).to.have.been.called.exactly(2);\n  });\n\n  it('can break to a named loop', () => {\n    const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.break('loop') : undefined);\n    const stepSpy2 = chai.spy();\n    const stepSpy3 = chai.spy();\n    const stepSpy4 = chai.spy();\n    const shortLoop = loop(\n      forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 2, do: [\n        stepSpy2,\n        forLoop({ name: 'loop2', initial: 10, next: loop2 => loop2 + 1, while: loop2 => loop2 < 20, do: [\n          ({ loop2 }) => stepSpy1(loop2),\n        ]}),\n        stepSpy3\n      ]}),\n      stepSpy4\n    )\n    shortLoop.reset();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    shortLoop.playOneStep();\n    expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 0, loop2: 12 });\n    expect(stepSpy2).to.have.been.called.exactly(1);\n    expect(stepSpy1).to.have.been.called.exactly(2);\n    expect(stepSpy3).to.have.been.called.exactly(0);\n    expect(stepSpy4).to.have.been.called.exactly(0);\n\n    shortLoop.playOneStep(); // break out of outer loop\n    shortLoop.playOneStep(); // resume at topmost loop\n    expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 0 });\n    expect(stepSpy2).to.have.been.called.exactly(1);\n    expect(stepSpy1).to.have.been.called.exactly(3);\n    expect(stepSpy3).to.have.been.called.exactly(0);\n    expect(stepSpy4).to.have.been.called.exactly(1);\n\n    shortLoop.playOneStep(); // all loops starting over\n    expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 0, loop2: 10 });\n    expect(stepSpy2).to.have.been.called.exactly(2);\n\n  });\n\n  it('can repeat out of processMove', () => {\n    const stepSpy2 = chai.spy((_: string, x:number) => {x});\n    const shortLoop = forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [\n      playerActions({ actions: ['breakAction'] }),\n      ({ loop }) => {console.log('end', loop); stepSpy2('end', loop)}\n    ]});\n    const gameManager = {\n      flow: shortLoop,\n      players: {\n        currentPosition: [1],\n        atPosition: () => ({position: 1}),\n        setCurrent: () => {}\n      },\n      getAction: (a: string) => ({\n        breakAction: { _process: Do.repeat, messages: [] },\n      }[a]),\n    };\n    // @ts-ignore mock gameManager\n    shortLoop.gameManager = gameManager;\n\n    shortLoop.reset();\n    shortLoop.play();\n    shortLoop.processMove({ name: 'breakAction', args: {}, player: 1 });\n    shortLoop.play();\n    expect(stepSpy2).not.to.have.been.called;\n    expect(shortLoop.position.value).to.equal(10);\n  });\n\n  it('can break out of processMove', () => {\n    const stepSpy1 = chai.spy();\n    const stepSpy2 = chai.spy();\n    const shortLoop = new Flow({\n      name: 'main',\n      do: forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [\n        playerActions({ actions: ['breakAction'] }),\n        ({ loop }) => {console.log('end', loop); stepSpy1()}\n      ]}),\n    });\n    const gameManager = {\n      flow: shortLoop,\n      players: {\n        currentPosition: [1],\n        atPosition: () => ({position: 1}),\n        setCurrent: () => {}\n      },\n      getAction: (a: string) => ({\n        breakAction: { _process: Do.break, messages: [] },\n      }[a]),\n      game: { finish: stepSpy2 },\n    };\n    // @ts-ignore mock gameManager\n    shortLoop.gameManager = gameManager;\n\n    shortLoop.reset();\n    shortLoop.play();\n    shortLoop.processMove({ name: 'breakAction', args: {}, player: 1 });\n    shortLoop.play();\n    expect(stepSpy1).not.to.have.been.called;\n    expect(stepSpy2).to.have.been.called;\n  });\n});\n\ndescribe('SwitchCase', () => {\n  it('switches', () => {\n    const stepSpy1 = chai.spy((x:number) => {x});\n    const testFlow = forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 3, do: (\n      switchCase({ name: 'switcher', switch: ({ loop }) => loop, cases: [\n        { eq: 0, do: ({ switcher }) => stepSpy1(switcher) },\n        { eq: 1, do: ({ switcher }) => stepSpy1(switcher) },\n      ]})\n    )});\n\n    // @ts-ignore\n    testFlow.gameManager = { flow: testFlow };\n    testFlow.reset();\n\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 0, value: 0 } },\n      { type: 'switch-case', name: 'switcher', position: { index: 0, value: 0, default: false } }\n    ]);\n    expect(stepSpy1).not.to.have.been.called;\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 1, value: 1 } },\n      { type: 'switch-case', name: 'switcher', position: { index: 1, value: 1, default: false } }\n    ]);\n    expect(stepSpy1).to.have.been.called.with(0);\n    expect(testFlow.playOneStep()).to.equal(FlowControl.ok);\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 2, value: 2 } },\n      { type: 'switch-case', name: 'switcher', position: { index: -1, value: 2, default: false } }\n    ]);\n    expect(stepSpy1).to.have.been.called.with(1);\n    expect(testFlow.playOneStep()).to.equal(FlowControl.complete);\n    expect(stepSpy1).to.have.been.called.exactly(2);\n  });\n\n  it('sets position', () => {\n    const stepSpy1 = chai.spy((x:number) => {x});\n    const testFlow = forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 3, do: (\n      switchCase({ name: 'switch', switch: ({ loop }) => loop, cases: [\n        { eq: 0, do: () => stepSpy1(0) },\n        { eq: 1, do: () => stepSpy1(1) },\n      ]})\n    )});\n\n    // @ts-ignore\n    testFlow.gameManager = { flow: testFlow };\n    testFlow.reset();\n\n    testFlow.setBranchFromJSON([\n      { type: 'loop', name: 'loop', position: { index: 1, value: 1 } },\n      { type: 'switch-case', name: 'switch', position: { index: 1, value: 1, default: false } }\n    ]);\n    expect(stepSpy1).not.to.have.been.called;\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 2, value: 2 } },\n      { type: 'switch-case', name: 'switch', position: { index: -1, value: 2, default: false } }\n    ]);\n    expect(stepSpy1).to.have.been.called.with(1);\n  });\n\n  it('defaults', () => {\n    const stepSpy1 = chai.spy((x:number) => {x});\n    const testFlow = forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 3, do: (\n      switchCase({\n        name: 'switch',\n        switch: ({ loop }) => loop,\n        cases: [\n          { eq: 0, do: () => stepSpy1(0) },\n          { eq: 1, do: () => stepSpy1(1) },\n        ],\n        default: () => stepSpy1(-1)\n      })\n    )});\n\n    // @ts-ignore\n    testFlow.gameManager = { flow: testFlow };\n    testFlow.reset();\n\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 0, value: 0 } },\n      { type: 'switch-case', name: 'switch', position: { index: 0, value: 0, default: false } }\n    ]);\n    expect(stepSpy1).not.to.have.been.called;\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 1, value: 1 } },\n      { type: 'switch-case', name: 'switch', position: { index: 1, value: 1, default: false } }\n    ]);\n    expect(stepSpy1).to.have.been.called.with(0);\n    expect(testFlow.playOneStep()).to.equal(FlowControl.ok);\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 2, value: 2 } },\n      { type: 'switch-case', name: 'switch', position: { index: -1, value: 2, default: true } }\n    ]);\n    expect(stepSpy1).to.have.been.called.with(1);\n    expect(testFlow.playOneStep()).to.equal(FlowControl.complete);\n    expect(stepSpy1).to.have.been.called.with(-1);\n    expect(stepSpy1).to.have.been.called.exactly(3);\n  });\n});\n\ndescribe('IfElse', () => {\n  it('switches', () => {\n    const stepSpy1 = chai.spy((x:number) => {x});\n    const testFlow = forLoop({\n      name: 'loop',\n      initial: 0,\n      next: loop => loop + 1,\n      while: loop => loop < 3,\n      do: ifElse({\n        name: 'if',\n        if: ({ loop }) => loop === 1,\n        do: () => stepSpy1(0),\n        else: () => stepSpy1(-1)\n      })\n    });\n\n    // @ts-ignore\n    testFlow.gameManager = { flow: testFlow };\n    testFlow.reset();\n\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 0, value: 0 } },\n      { type: 'switch-case', name: 'if', position: { index: -1, default: true, value: false } }\n    ]);\n    expect(stepSpy1).not.to.have.been.called;\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 1, value: 1 } },\n      { type: 'switch-case', name: 'if', position: { index: 0, default: false, value: true } }\n    ]);\n    expect(stepSpy1).to.have.been.called.with(-1);\n    testFlow.playOneStep();\n    expect(testFlow.branchJSON()).to.deep.equals([\n      { type: 'loop', name: 'loop', position: { index: 2, value: 2 } },\n      { type: 'switch-case', name: 'if', position: { index: -1, default: true, value: false } }\n    ]);\n    expect(stepSpy1).to.have.been.called.with(0);\n    testFlow.playOneStep();\n    expect(stepSpy1).to.have.been.called.exactly(3);\n    expect(stepSpy1).on.nth(1).be.called.with(-1);\n    expect(stepSpy1).on.nth(2).be.called.with(0);\n    expect(stepSpy1).on.nth(3).be.called.with(-1);\n  });\n});\n"
  },
  {
    "path": "src/test/game_manager_test.ts",
    "content": "import chai from 'chai';\nimport spies from 'chai-spies';\n\nimport GameManager, { PlayerAttributes } from '../game-manager.js'\nimport Player from '../player/player.js';\nimport { Game, Piece, Space } from '../board/index.js';\nimport { createGame } from '../game-creator.js';\nimport { createInterface } from '../interface.js';\nimport { Do } from '../flow/enums.js';\n\nchai.use(spies);\nconst { expect } = chai;\n\ndescribe('GameManager', () => {\n  const players = [\n    { id: 'joe', name: 'Joe', color: 'red', position: 1, tokens: 0, avatar: '', host: true, },\n    { id: 'jane', name: 'Jane', color: 'green', position: 2, tokens: 0, avatar: '', host: false, },\n    { id: 'jag', name: 'Jag', color: 'yellow', position: 3, tokens: 0, avatar: '', host: false, },\n    { id: 'jin', name: 'Jin', color: 'purple', position: 4, tokens: 0, avatar: '', host: false, },\n  ];\n\n  class TestPlayer extends Player<TestGame, TestPlayer> {\n    tokens: number = 0;\n    rival?: TestPlayer;\n    general?: General;\n  }\n\n  class TestGame extends Game<TestGame, TestPlayer> {\n    tokens: number = 0;\n  }\n\n  class Card extends Piece<TestGame> {\n    suit: string;\n    value: number;\n    flipped: boolean;\n  }\n\n  class Country extends Space<TestGame> {\n    general?: General;\n  }\n\n  class General extends Piece<TestGame> {\n    country?: Country;\n  }\n\n  let gameManager: GameManager<TestGame, TestPlayer>;\n  let game: TestGame;\n  const spendSpy = chai.spy();\n\n  beforeEach(() => {\n    gameManager = new GameManager(TestPlayer, TestGame, [ Card, Country, General ]);\n    game = gameManager.game;\n\n    const {\n      playerActions,\n      whileLoop,\n      eachPlayer,\n    } = game.flowCommands\n\n    game.defineFlow(\n      () => {\n        game.tokens = 4;\n        game.message('Starting game with {{tokens}} tokens', {tokens: game.tokens});\n      },\n      whileLoop({ while: () => game.tokens < 8, do: (\n        playerActions({ actions: ['addSome', 'spend']})\n      )}),\n      whileLoop({ while: () => game.tokens > 0, do: (\n        eachPlayer({ name: 'player', startingPlayer: gameManager.players[0], do: [\n          playerActions({ actions: ['takeOne']}),\n          () => {\n            if (game.tokens <= 0) game.finish(gameManager.players.withHighest('tokens'))\n          },\n        ]})\n      )}),\n    );\n\n    game.defineActions({\n      addSome: () => game.action({\n        prompt: 'add some counters',\n      }).chooseNumber('n', {\n        prompt: 'how many?',\n        min: 1,\n        max: 3,\n      }).do(\n        ({ n }) => { game.tokens += n }\n      ).message('{{player}} added {{n}}'),\n\n      takeOne: player => game.action({\n        prompt: 'take one counter',\n      }).do(() => {\n        game.tokens --;\n        player.tokens ++;\n      }),\n\n      spend: () => game.action({\n        prompt: 'Spend resource',\n      }).chooseFrom('r', ['gold', 'silver'], {\n        prompt: 'which resource',\n      }).chooseNumber('n', {\n        prompt: 'How much?',\n        min: 1,\n        max: 3,\n      }).do(spendSpy),\n    });\n\n    gameManager.players.fromJSON(players);\n    gameManager.game.fromJSON([ { className: 'TestGame', tokens: 0 } ]);\n    gameManager.players.assignAttributesFromJSON(players);\n    gameManager.start();\n    gameManager.setFlowFromJSON([{currentPosition: [1,2,3,4], stack: [ { type: 'main', name: '__main__', sequence: 0 } ]}]);\n  });\n\n  it('plays', () => {\n    gameManager.play();\n    expect(gameManager.flowJSON()).to.deep.equals([\n      {\n        currentPosition: [1,2,3,4],\n        stack: [\n          { type: 'main', name: '__main__', sequence: 1 },\n          { type: \"loop\", position: { index: 0 } },\n          { type: \"action\" }\n        ]\n      }\n    ]);\n    const step = gameManager.flow().actionNeeded();\n    expect(step?.actions).to.deep.equal([{ name: 'addSome', args: undefined, prompt: undefined }, { name: 'spend', args: undefined, prompt: undefined }]);\n  });\n\n  it('messages', () => {\n    gameManager.play();\n    expect(gameManager.messages).to.deep.equals([\n      {\n        \"body\": \"Starting game with 4 tokens\"\n      }\n    ]);\n    gameManager.processMove({ name: 'addSome', args: {n: 3}, player: gameManager.players[0] });\n    gameManager.play();\n    expect(gameManager.messages).to.deep.equals([\n      {\n        \"body\": \"Starting game with 4 tokens\"\n      },\n      {\n        \"body\": \"[[$p[1]|Joe]] added 3\"\n      }\n    ]);\n  });\n\n  it('messages to players', () => {\n    gameManager.actions.addSome = player => game!.action({\n      prompt: 'add some counters',\n    }).chooseNumber('n', {\n      prompt: 'how many?',\n      min: 1,\n      max: 3,\n    }).do(\n      ({ n }) => { game.tokens += n }\n    ).messageTo(\n      player, '{{player}} added {{n}}'\n    ).messageTo(\n      player.others(), '{{player}} added some'\n    );\n\n    gameManager.play();\n    expect(gameManager.messages).to.deep.equals([\n      {\n        \"body\": \"Starting game with 4 tokens\"\n      }\n    ]);\n    gameManager.processMove({ name: 'addSome', args: {n: 3}, player: gameManager.players[0] });\n    gameManager.play();\n    expect(gameManager.messages).to.deep.equals([\n      {\n        \"body\": \"Starting game with 4 tokens\"\n      },\n      {\n        \"body\": \"[[$p[1]|Joe]] added 3\",\n        \"position\": 1\n      },\n      {\n        \"body\": \"[[$p[1]|Joe]] added some\",\n        \"position\": 2\n      },\n      {\n        \"body\": \"[[$p[1]|Joe]] added some\",\n        \"position\": 3\n      },\n      {\n        \"body\": \"[[$p[1]|Joe]] added some\",\n        \"position\": 4\n      }\n    ]);\n  });\n\n  it('finishes', () => {\n    gameManager.setFlowFromJSON([{\n      currentPosition: [2],\n      stack: [\n        { type: 'main', name: '__main__', sequence: 2 },\n        { type: 'loop', position: { index: 0 } },\n        { type: 'loop', name: 'player', position: { index: 1, value: '$p[2]' } },\n        { type: 'action' }\n      ]\n    }]);\n    gameManager.game.fromJSON([ { className: 'TestGame', tokens: 9 } ]);\n    gameManager.players.setCurrent(2);\n    do {\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players.current()! });\n      gameManager.play();\n    } while (gameManager.phase === 'started');\n    expect(gameManager.winner.length).to.equal(1);\n    expect(gameManager.winner[0]).to.equal(gameManager.players[1]);\n  });\n\n  describe('state', () => {\n    it('is stateless', () => {\n      gameManager.play();\n      gameManager.processMove({ name: 'addSome', args: {n: 3}, player: gameManager.players[0] });\n      gameManager.play();\n      const boardState = gameManager.game.allJSON();\n      const flowState = gameManager.flowJSON();\n      gameManager.game.fromJSON(boardState);\n      gameManager.setFlowFromJSON(flowState);\n      expect(gameManager.game.allJSON()).to.deep.equals(boardState);\n      expect(gameManager.flowJSON()).to.deep.equals(flowState);\n      expect(game.tokens).to.equal(7);\n    });\n\n    it(\"does player turns\", () => {\n      gameManager.game.fromJSON([ { className: 'TestGame', tokens: 9 } ]);\n      gameManager.setFlowFromJSON([{\n        currentPosition: [2],\n        stack: [\n          { type: 'main', name: '__main__', sequence: 2 },\n          { type: 'loop', position: { index: 0 } },\n          { type: 'loop', name: 'player', position: { index: 1, value: '$p[2]' } },\n          { type: 'action' }\n        ]}\n      ]);\n      gameManager.players.setCurrent([2]);\n      expect(gameManager.players.currentPosition).to.deep.equal([2]);\n      gameManager.play();\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([3]);\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([4]);\n      expect(gameManager.flowJSON()[0].stack[1].position.index).to.equal(0)\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([1]);\n      expect(gameManager.flowJSON()[0].stack[1].position.index).to.equal(1)\n    });\n  });\n\n  describe('godMode', () => {\n    it(\"does god mode moves\", () => {\n      gameManager.godMode = true;\n      gameManager.phase = 'new';\n      const space1 = gameManager.game.create(Space, 'area1');\n      const space2 = gameManager.game.create(Space, 'area2');\n      const piece = space1.create(Piece, 'piece');\n      gameManager.start();\n      gameManager.play();\n      gameManager.processMove({\n        player: gameManager.players[0],\n        name: '_godMove',\n        args: { piece, into: space2 }\n      });\n      expect(space2.first(Piece)).to.equal(piece);\n    });\n\n    it(\"does god mode edits\", () => {\n      gameManager.godMode = true;\n      gameManager.phase = 'new';\n      const card = gameManager.game.create(Card, 'area1', {suit: \"H\", value: 1, flipped: false});\n      gameManager.start();\n      gameManager.processMove({\n        player: gameManager.players[0],\n        name: '_godEdit',\n        args: { element: card, property: 'suit', value: 'S' }\n      });\n      expect(card.suit).to.equal('S');\n    });\n\n    it(\"restricts god mode moves\", () => {\n      gameManager.phase = 'new';\n      const space1 = gameManager.game.create(Space, 'area1');\n      const space2 = gameManager.game.create(Space, 'area2');\n      const piece = space1.create(Piece, 'piece');\n      gameManager.start();\n      expect(() => gameManager.processMove({\n        player: gameManager.players[0],\n        name: '_godMove',\n        args: { piece, into: space2 }\n      })).to.throw()\n    });\n  });\n\n  describe('processAction', () => {\n    it('runs actions', async () => {\n      gameManager.play();\n      gameManager.processMove({ name: 'spend', args: {r: 'gold', n: 2}, player: gameManager.players[0] });\n      expect(spendSpy).to.have.been.called.with({r: 'gold', n: 2});\n      expect(gameManager.flowJSON()).to.deep.equals([{\n        currentPosition: [1,2,3,4],\n        stack: [\n          { type: 'main', name: '__main__', sequence: 1 },\n          { type: 'loop', position: { index: 0 } },\n          { type: 'action', position: { name: \"spend\", args: {r: \"gold\", n: 2}, player: 1 }}\n        ]\n      }]);\n      gameManager.play();\n      expect(gameManager.flowJSON()).to.deep.equals([{\n        currentPosition: [1,2,3,4],\n        stack: [\n          { type: 'main', name: '__main__', sequence: 1 },\n          { type: 'loop', position: { index: 1 } },\n          { type: \"action\" }\n        ]\n      }]);\n    });\n    it('changes state', async () => {\n      gameManager.play();\n      expect(game.tokens).to.equal(4);\n      gameManager.processMove({ name: 'addSome', args: {n: 2}, player: gameManager.players[0] });\n      expect(gameManager.flowJSON()).to.deep.equals([{\n        currentPosition: [1,2,3,4],\n        stack: [\n          { type: 'main', name: '__main__', sequence: 1 },\n          { type: 'loop', position: { index: 0 } },\n          { type: 'action', position: { name: \"addSome\", args: {n: 2}, player: 1 }}\n        ]\n      }]);\n      expect(game.tokens).to.equal(6);\n    });\n  });\n\n  describe('players', () => {\n    it('sortedBy', () => {\n      expect(gameManager.players.sortedBy('color')[0].color).to.equal('green')\n      expect(gameManager.players.sortedBy('color', 'desc')[0].color).to.equal('yellow')\n      expect(gameManager.players[0].color).to.equal('red')\n    });\n\n    it('sortBy', () => {\n      gameManager.players.sortBy('color');\n      expect(gameManager.players[0].color).to.equal('green')\n    });\n\n    it('withHighest', () => {\n      expect(gameManager.players.withHighest('color')).to.equal(gameManager.players[2])\n    });\n\n    it('withLowest', () => {\n      expect(gameManager.players.withLowest('color')).to.equal(gameManager.players[1])\n    });\n\n    it('min', () => {\n      expect(gameManager.players.min('color')).to.equal('green')\n    });\n\n    it('max', () => {\n      expect(gameManager.players.max('color')).to.equal('yellow')\n    });\n\n    it('shuffles', () => {\n      const player = gameManager.players[0];\n      gameManager.setRandomSeed('a');\n      gameManager.players.shuffle();\n      expect(gameManager.players[0]).to.not.equal(player);\n    });\n\n    it('preserves serializable attributes from json', () => {\n      gameManager.players[0].rival = gameManager.players[1];\n\n      const json = gameManager.players.map(p => p.toJSON() as PlayerAttributes<TestPlayer>);\n\n      gameManager.players.fromJSON(json);\n      gameManager.players.assignAttributesFromJSON(json);\n      expect(gameManager.players.map(p => p.toJSON())).to.deep.equals(json);\n      expect(gameManager.players[0].rival).to.equal(gameManager.players[1]);\n    });\n\n    it('handles serializable references from player to board', () => {\n      gameManager.phase = 'new';\n      const map = game.create(Space, 'map', {});\n      const france = map.create(Country, 'france');\n      const england = map.create(Country, 'england');\n      const napoleon = france.create(General, 'napoleon', { country: france });\n      gameManager.players[0].general = napoleon;\n      france.general = napoleon;\n      gameManager.start();\n\n      const playerJSON = gameManager.players.map(p => p.toJSON() as PlayerAttributes<TestPlayer>);\n      const boardJSON = game.allJSON(1);\n\n      napoleon.putInto(england);\n\n      gameManager.players.fromJSON(playerJSON);\n      game.fromJSON(JSON.parse(JSON.stringify(boardJSON)));\n      gameManager.players.assignAttributesFromJSON(playerJSON);\n\n      expect(game.allJSON(1)).to.deep.equals(boardJSON);\n      expect(gameManager.players.map(p => p.toJSON())).to.deep.equals(playerJSON);\n\n      expect(gameManager.players[0].general?.name).to.equal('napoleon');\n      expect(game.first(Country, 'france')).to.equal(france);\n      expect(game.first(Country, 'france')!.general?.name).to.equal('napoleon');\n      expect(game.first(Country, 'france')!.general?.country).to.equal(france);\n    });\n\n    it('hides attributes', () => {\n      TestPlayer.hide('rival');\n\n      gameManager.players[0].rival = gameManager.players[1];\n      gameManager.players[1].rival = gameManager.players[0];\n\n      const json = gameManager.players.map(p => p.toJSON(gameManager.players[0]) as PlayerAttributes<TestPlayer>);\n\n      gameManager.players.fromJSON(json);\n      gameManager.players.assignAttributesFromJSON(json);\n      expect(gameManager.players[0].rival).to.equal(gameManager.players[1]);\n      expect(gameManager.players[1].rival).to.be.undefined;\n    });\n  });\n\n  describe('action for multiple players', () => {\n    beforeEach(() => {\n      gameManager = new GameManager(TestPlayer, TestGame, [ Card ]);\n      game = gameManager.game;\n\n      game.defineActions({\n        takeOne: player => game.action({\n          prompt: 'take one counter',\n          condition: game.tokens > 0\n        }).do(() => {\n          game.tokens --;\n          player.tokens ++;\n        }),\n        declare: () => game.action({\n          prompt: 'declare',\n        }).enterText('d', {\n          prompt: 'declaration'\n        }),\n        pass: () => game.action({\n          prompt: 'pass'\n        }),\n      });\n\n      gameManager.players.fromJSON(players);\n      gameManager.players.assignAttributesFromJSON(players);\n    });\n\n    it('accepts move from any', () => {\n      const { playerActions } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 4 },\n        playerActions({\n          players: gameManager.players,\n          actions: ['takeOne']\n        }),\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] });\n      gameManager.play();\n      expect(gameManager.phase).to.equal('finished');\n    });\n\n    it('prompt in actionStep', () => {\n      const {\n        playerActions,\n        eachPlayer,\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 1 },\n        eachPlayer({\n          name: 'player',\n          do: playerActions({\n            players: gameManager.players,\n            actions: [{name: 'takeOne', prompt: 'take one!'}]\n          })\n        }),\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].selections[0].prompt).to.equal('take one!');\n    });\n\n    it('args in actionStep', () => {\n      const {\n        playerActions,\n        eachPlayer,\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 1 },\n        eachPlayer({\n          name: 'player',\n          do: playerActions({\n            players: gameManager.players,\n            actions: [{name: 'declare', args: {d: 'hi'}}]\n          })\n        }),\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].args).to.deep.equal({d: 'hi'});\n    });\n\n    it('functional args in actionStep', () => {\n      const {\n        playerActions,\n        eachPlayer,\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 1 },\n        eachPlayer({\n          name: 'player',\n          do: playerActions({\n            players: gameManager.players,\n            actions: [{name: 'declare', args: ({ player }) => ({d: player.name}) }]\n          })\n        }),\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].args).to.deep.equal({d: 'Joe'});\n    });\n\n    it('unskippable initial playerAction', () => {\n      const { playerActions } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 1 },\n        playerActions({\n          player: gameManager.players[0],\n          actions: ['declare'],\n          skipIf: 'never'\n        })\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].selections[0].type).to.equal('button');\n    });\n\n    it('skippable initial playerAction', () => {\n      const { playerActions } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 1 },\n        playerActions({\n          player: gameManager.players[0],\n          actions: ['declare'],\n        })\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].selections[0].type).to.equal('text');\n    });\n\n    it('accepts condition', () => {\n      const { playerActions, eachPlayer } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 4 },\n        eachPlayer({\n          name: 'player',\n          do: playerActions({\n            name: 'take-one',\n            condition: ({ player }) => player.position !== 2,\n            actions: ['takeOne'],\n            continueIfImpossible: true,\n          })\n        })\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([1])\n\n      gameManager.processMove({ player: gameManager.players[0], name: 'takeOne', args: {} });\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([3])\n    });\n\n    it('optional actions', () => {\n      const {\n        playerActions,\n        eachPlayer,\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 1 },\n        eachPlayer({\n          name: 'player',\n          do: playerActions({\n            optional: 'Pass',\n            actions: ['takeOne']\n          })\n        }),\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.moves.length).to.equal(2);\n      const move1 = gameManager.processMove({ player: gameManager.players[0], name: '__pass__', args: {} });\n      expect(move1).to.be.undefined;\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([2])\n      const move2 = gameManager.processMove({ player: gameManager.players[1], name: 'takeOne', args: {} });\n      expect(move2).to.be.undefined;\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([3]);\n      expect(gameManager.getPendingMoves(gameManager.players[2])?.moves.length).to.equal(1);\n      const move3 = gameManager.processMove({ player: gameManager.players[2], name: 'takeOne', args: {} });\n      expect(move3).not.to.be.undefined;\n    });\n\n    it('repeatUntil actions', () => {\n      const actionSpy = chai.spy();\n      const {\n        playerActions,\n        eachPlayer,\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 8 },\n        eachPlayer({\n          name: 'player',\n          do: playerActions({\n            name: 'repeat',\n            repeatUntil: 'Pass',\n            actions: [\n              { name: 'takeOne', do: actionSpy },\n              'declare'\n            ]\n          })\n        }),\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.moves.length).to.equal(3);\n      const move1 = gameManager.processMove({ player: gameManager.players[0], name: '__pass__', args: {} });\n      expect(move1).to.be.undefined;\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([2])\n      const move2 = gameManager.processMove({ player: gameManager.players[1], name: 'takeOne', args: {} });\n      expect(move2).to.be.undefined;\n      gameManager.play();\n      expect(actionSpy).to.have.been.called.once;\n\n      expect(gameManager.players.currentPosition).to.deep.equal([2]);\n      expect(gameManager.getPendingMoves(gameManager.players[1])?.moves.length).to.equal(3);\n      const move3 = gameManager.processMove({ player: gameManager.players[1], name: 'declare', args: {d: 'hi'} });\n      expect(move3).to.be.undefined;\n      gameManager.play();\n      expect(actionSpy).to.have.been.called.once;\n\n      expect(gameManager.players.currentPosition).to.deep.equal([2]);\n      expect(gameManager.getPendingMoves(gameManager.players[1])?.moves.length).to.equal(3);\n      const move4 = gameManager.processMove({ player: gameManager.players[1], name: '__pass__', args: {} });\n      expect(move4).to.be.undefined;\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([3]);\n    });\n\n    it('deadlocked if impossible actions', () => {\n      const { playerActions } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 0 },\n        playerActions({\n          name: 'take-one',\n          players: gameManager.players,\n          actions: ['takeOne'],\n        }),\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])).to.be.undefined;\n      expect(gameManager.phase).to.not.equal('finished');\n    });\n\n    it('continue if impossible actions', () => {\n      const { playerActions } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 0 },\n        playerActions({\n          name: 'take-one',\n          players: gameManager.players,\n          actions: ['takeOne'],\n          continueIfImpossible: true,\n        }),\n      );\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])).to.be.undefined;\n      expect(gameManager.phase).to.equal('finished');\n    });\n\n    it('continue if impossible actions in interface', () => {\n      const { playerActions } = game.flowCommands\n\n      const iface = createInterface(\n        createGame(TestPlayer, TestGame, game => {\n          game.defineActions({\n            takeOne: player => game.action({\n              prompt: 'take one counter',\n              condition: game.tokens > 0\n            }).do(() => {\n              game.tokens --;\n              player.tokens ++;\n            }),\n          });\n          game.defineFlow(\n            () => { game.tokens = 0 },\n            playerActions({\n              name: 'take-one',\n              players: gameManager.players,\n              actions: ['takeOne'],\n              continueIfImpossible: true,\n            }),\n          );\n        })\n      );\n\n      const initialState = iface.initialState({\n        players: players,\n        settings: {},\n        randomSeed: ''\n      });\n\n      expect(initialState.game.phase).to.equal('finished');\n    });\n\n    it('action for every player', () => {\n      const {\n        playerActions,\n        everyPlayer\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 4 },\n        everyPlayer({\n          do: playerActions({\n            actions: ['takeOne']\n          })\n        })\n      );\n\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] });\n      gameManager.play();\n      expect(gameManager.phase).to.equal('started');\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 4])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n      expect(gameManager.phase).to.equal('started');\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 4])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n      expect(gameManager.phase).to.equal('started');\n      expect(gameManager.players.currentPosition).to.deep.equal([4])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] });\n      gameManager.play();\n      expect(gameManager.phase).to.equal('finished');\n    });\n\n    it('action for every player with blocks', () => {\n      const {\n        playerActions,\n        everyPlayer\n      } = game.flowCommands\n      const actionSpy = chai.spy((_p: Player) => {});\n\n      game.defineFlow(\n        () => { game.tokens = 4 },\n        everyPlayer({\n          name: 'testEvery',\n          do: [\n            args => actionSpy(args.testEvery),\n            playerActions({\n              actions: ['takeOne']\n            })\n          ]\n        })\n      );\n\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4]);\n      expect(actionSpy).to.have.been.called.exactly(4);\n      expect(actionSpy).to.have.been.called.with(game.players[0]);\n      expect(actionSpy).to.have.been.called.with(game.players[1]);\n      expect(actionSpy).to.have.been.called.with(game.players[2]);\n      expect(actionSpy).to.have.been.called.with(game.players[3]);\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] });\n      gameManager.play();\n      expect(gameManager.phase).to.equal('started');\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 4])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n      expect(gameManager.phase).to.equal('started');\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 4])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n      expect(gameManager.phase).to.equal('started');\n      expect(gameManager.players.currentPosition).to.deep.equal([4])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] });\n      gameManager.play();\n      expect(gameManager.phase).to.equal('finished');\n    });\n\n    it('action for every player with followups', () => {\n      const {\n        playerActions,\n        everyPlayer\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 4 },\n        everyPlayer({\n          do: playerActions({\n            name: 'take-1',\n            actions: [\n              {\n                name: 'takeOne',\n                do: playerActions({\n                  name: 'declare',\n                  actions: ['declare']\n                }),\n              },\n              'pass'\n            ]\n          })\n        })\n      );\n\n      gameManager.start();\n      gameManager.play();\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1');\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4])\n\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4])\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1');\n      expect(gameManager.getPendingMoves(gameManager.players[2])?.step).to.equal('declare');\n\n      gameManager.processMove({ name: 'declare', args: {d: 'well i never'}, player: gameManager.players[2] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 4])\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1');\n      expect(gameManager.getPendingMoves(gameManager.players[2])).to.equal(undefined);\n\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 4])\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1');\n      expect(gameManager.getPendingMoves(gameManager.players[1])?.step).to.equal('declare');\n      expect(gameManager.getPendingMoves(gameManager.players[2])).to.equal(undefined);\n\n      gameManager.processMove({ name: 'declare', args: {d: 'i do'}, player: gameManager.players[1] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 4])\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1');\n      expect(gameManager.getPendingMoves(gameManager.players[1])).to.equal(undefined);\n      expect(gameManager.getPendingMoves(gameManager.players[2])).to.equal(undefined);\n      expect(gameManager.getPendingMoves(gameManager.players[3])?.step).to.equal('take-1');\n    });\n\n    it('survives ser/deser', () => {\n      const {\n        playerActions,\n        everyPlayer\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => { game.tokens = 4 },\n        everyPlayer({\n          do: playerActions({\n            name: 'take-1',\n            actions: [\n              {\n                name: 'takeOne',\n                do: playerActions({\n                  name: 'declare',\n                  actions: ['declare']\n                })\n              },\n              'pass'\n            ]\n          })\n        })\n      );\n\n      gameManager.start();\n      gameManager.play();\n      let boardState = gameManager.game.allJSON();\n      let flowState = gameManager.flowJSON();\n\n      gameManager.phase = 'new';\n      game.defineFlow(\n        () => { game.tokens = 4 },\n        everyPlayer({\n          do: playerActions({\n            name: 'take-1',\n            actions: [\n              {\n                name: 'takeOne',\n                do: playerActions({\n                  name: 'declare',\n                  actions: ['declare']\n                })\n              },\n              'pass'\n            ]\n          })\n        })\n      );\n      gameManager.start();\n      gameManager.game.fromJSON(boardState);\n      gameManager.setFlowFromJSON(flowState);\n\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1');\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] });\n\n      boardState = gameManager.game.allJSON();\n      flowState = gameManager.flowJSON();\n      gameManager.game.fromJSON(boardState);\n      gameManager.setFlowFromJSON(flowState);\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4])\n      expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1');\n      expect(gameManager.getPendingMoves(gameManager.players[2])?.step).to.equal('declare');\n    });\n  });\n\n  describe('action followups', () => {\n    const actionSpy = chai.spy();\n    beforeEach(() => {\n      gameManager = new GameManager(TestPlayer, TestGame, [ Card ]);\n      game = gameManager.game;\n      const {\n        loop,\n        eachPlayer,\n        playerActions\n      } = game.flowCommands\n\n      game.defineActions({\n        takeOne: player => game.action({\n          prompt: 'take one counter',\n        }).do(() => {\n          game.tokens --;\n          player.tokens ++;\n          if (game.tokens < 10) game.followUp({\n            player: gameManager.players[1],\n            name: 'declare',\n            prompt: 'follow',\n          });\n        }),\n        declare: () => game.action({\n          prompt: 'declare',\n        }).enterText('d', {\n          prompt: 'declaration'\n        }),\n      });\n\n      gameManager.players.fromJSON(players);\n      gameManager.players.assignAttributesFromJSON(players);\n\n      game.defineFlow(loop(eachPlayer({\n        name: 'player',\n        do: playerActions({\n          actions: [{name: 'takeOne', do: actionSpy}]\n        }),\n      })));\n    });\n\n    it('allows followup do', () => {\n      gameManager.game.tokens = 11;\n      gameManager.start();\n      gameManager.play();\n\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n      expect(actionSpy).to.have.been.called.once\n      expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(0);\n      expect(gameManager.allowedActions(gameManager.players[1]).actions.length).to.equal(1);\n\n      // gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      // gameManager.play();\n      // expect(actionSpy).to.have.been.called.once\n      // expect(gameManager.allowedActions(gameManager.players[1]).actions.length).to.equal(1);\n      // expect(gameManager.allowedActions(gameManager.players[1]).actions[0].name).to.equal('declare');\n      // expect(gameManager.allowedActions(gameManager.players[1]).actions[0].player).to.equal(gameManager.players[1]);\n      // expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(0);\n      // expect(gameManager.allowedActions(gameManager.players[1]).actions[0].prompt).to.equal('follow');\n\n      // gameManager.processMove({ name: 'declare', args: {d: 'follow'}, player: gameManager.players[1] });\n      // gameManager.play();\n      // expect(actionSpy).to.have.been.called.twice\n    });\n\n    it('allows followup for other player', () => {\n      const {\n        loop,\n        eachPlayer,\n        playerActions\n      } = game.flowCommands\n      gameManager.game.defineFlow(loop(eachPlayer({\n        name: 'player',\n        do: [\n          playerActions({\n            actions: [{name: 'takeOne', do: actionSpy}]\n          }),\n          playerActions({\n            actions: ['declare']\n          }),\n        ]\n      })));\n\n      gameManager.game.tokens = 12;\n      gameManager.start();\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([1]);\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n      gameManager.processMove({ name: 'declare', args: {d: 'p1'}, player: gameManager.players[0] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([2]);\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n      gameManager.processMove({ name: 'declare', args: {d: 'p1'}, player: gameManager.players[1] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([3]);\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([2]);\n      expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(0);\n      expect(gameManager.allowedActions(gameManager.players[1]).actions.length).to.equal(1);\n      expect(gameManager.allowedActions(gameManager.players[2]).actions.length).to.equal(0);\n\n      gameManager.processMove({ name: 'declare', args: {d: 'follow'}, player: gameManager.players[1] });\n      gameManager.play();\n      expect(gameManager.players.currentPosition).to.deep.equal([3]);\n    });\n\n    it('multi followup', () => {\n      gameManager = new GameManager(TestPlayer, TestGame, [ Card ]);\n      game = gameManager.game;\n      const {\n        loop,\n        eachPlayer,\n        playerActions\n      } = game.flowCommands\n\n      game.defineActions({\n        takeOne: player => game.action({\n          prompt: 'take one counter',\n        }).do(() => {\n          game.tokens --;\n          player.tokens ++;\n          if (game.tokens < 15) game.followUp({ name: 'declare' });\n          if (game.tokens < 10) game.followUp({ name: 'takeOne' });\n        }),\n        declare: () => game.action({\n          prompt: 'declare',\n        }).enterText('d', {\n          prompt: 'declaration'\n        }),\n      });\n      gameManager.players.fromJSON(players);\n      gameManager.players.assignAttributesFromJSON(players);\n\n      game.defineFlow(loop(eachPlayer({\n        name: 'player',\n        do: playerActions({\n          actions: ['takeOne']\n        }),\n      })));\n\n      gameManager.game.tokens = 10;\n      gameManager.start();\n      gameManager.play();\n\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n      gameManager.processMove({ name: 'declare', args: { d: 'first' }, player: gameManager.players[0] });\n      gameManager.play();\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n    });\n  });\n\n  describe('each player', () => {\n    beforeEach(() => {\n      gameManager = new GameManager(TestPlayer, TestGame, [ Card ]);\n      game = gameManager.game;\n\n      game.defineActions({\n        takeOne: player => game.action({\n          prompt: 'take one counter',\n        }).do(() => {\n          game.tokens --;\n          player.tokens ++;\n        }),\n      });\n\n      gameManager.players.fromJSON(players.slice(0, 2));\n      gameManager.players.assignAttributesFromJSON(players.slice(0, 2));\n    });\n\n    it('continuous loop for each player', () => {\n      const {\n        whileLoop,\n        playerActions,\n        eachPlayer\n      } = game.flowCommands\n\n      game.defineFlow(whileLoop({\n        while: () => true,\n        do: eachPlayer({\n          name: 'player',\n          do: playerActions({\n            actions: ['takeOne']\n          }),\n        })\n      }));\n      gameManager.game.tokens = 20;\n      gameManager.start();\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([1])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([2])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([1])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([2])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n    });\n\n    it('nested each player', () => {\n      const {\n        whileLoop,\n        playerActions,\n        eachPlayer\n      } = game.flowCommands\n      const stepSpy = chai.spy((_p1: number, _p2: number) => {});\n\n      game.defineFlow(whileLoop({\n        while: () => true,\n        do: eachPlayer({\n          name: 'player1',\n          do: eachPlayer({\n            name: 'player2',\n            do: playerActions({\n              actions: [{name: 'takeOne', do: ({ player1, player2 }) => stepSpy(player1.position, player2.position)}]\n            }),\n          })\n        })\n      }));\n      gameManager.game.tokens = 20;\n      gameManager.start();\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([1])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n      expect(stepSpy).to.have.been.called.with(1, 1);\n\n      expect(gameManager.players.currentPosition).to.deep.equal([2])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n      expect(stepSpy).to.have.been.called.with(1, 2);\n\n      expect(gameManager.players.currentPosition).to.deep.equal([1])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n      expect(stepSpy).to.have.been.called.with(2, 1);\n\n      expect(gameManager.players.currentPosition).to.deep.equal([2])\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n      expect(stepSpy).to.have.been.called.with(2, 2);\n    });\n  });\n\n  describe(\"subflows\", () => {\n    it(\"proceeds to subflow\", () => {\n      gameManager = new GameManager(TestPlayer, TestGame, [ Card, Country, General ]);\n      game = gameManager.game;\n      const stepSpy = chai.spy();\n\n      const {\n        playerActions,\n        whileLoop,\n        eachPlayer,\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => {\n          game.tokens = 10;\n          game.message('Starting game with {{tokens}} tokens', {tokens: game.tokens});\n        },\n        whileLoop({ while: () => game.tokens > 0, do: (\n          eachPlayer({ name: 'player', do: [\n            playerActions({ actions: ['takeOne']}),\n            () => {\n              if (game.tokens <= 6) Do.subflow('token-flow');\n              if (game.tokens <= 0) game.finish(gameManager.players.withHighest('tokens'))\n            },\n            stepSpy\n          ]})\n        )}),\n      );\n\n      game.defineSubflow(\n        'token-flow',\n        eachPlayer({ name: 'player', startingPlayer: () => game.players.current()!, do: [\n          playerActions({ actions: [\n            {\n              name: 'declare',\n              do: ({ declare, player }) => { if (declare.d === '!') player.tokens = 0 } }\n          ]}),\n        ]}),\n        () => {\n          game.players.withLowest('tokens').tokens += 2;\n        }\n      );\n\n      game.defineActions({\n        takeOne: player => game.action({\n          prompt: 'take one counter',\n        }).do(() => {\n          game.tokens --;\n          player.tokens ++;\n        }),\n\n        declare: () => game.action({\n          prompt: 'declare',\n        }).enterText('d', {\n          prompt: 'declaration'\n        }),\n        pass: () => game.action({\n          prompt: 'pass'\n        }),\n      });\n\n      gameManager.players.fromJSON(players);\n      gameManager.game.fromJSON([ { className: 'TestGame', tokens: 0 } ]);\n      gameManager.players.assignAttributesFromJSON(players);\n      gameManager.start();\n      gameManager.play();\n\n      // start play\n\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] });\n      gameManager.play();\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] });\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([4]);\n      expect(gameManager.allowedActions(gameManager.players[3]).actions.length).to.equal(1);\n      expect(gameManager.allowedActions(gameManager.players[3]).actions[0].name).to.equal('declare');\n      expect(stepSpy).to.have.been.called.exactly(3);\n\n      gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[3] });\n      gameManager.play();\n      gameManager.processMove({ name: 'declare', args: {d: '!'}, player: gameManager.players[0] });\n      gameManager.play();\n      gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[1] });\n      gameManager.play();\n      gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[2] });\n      gameManager.play();\n\n      // cedes to previous flow\n      expect(stepSpy).to.have.been.called.exactly(4);\n      expect(gameManager.players[0].tokens).to.equal(2);\n      expect(gameManager.players.currentPosition).to.deep.equal([1]);\n      expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(1);\n      expect(gameManager.allowedActions(gameManager.players[0]).actions[0].name).to.equal('takeOne');\n    });\n\n    it(\"proceeds to subflow from action do\", () => {\n      gameManager = new GameManager(TestPlayer, TestGame, [ Card, Country, General ]);\n      game = gameManager.game;\n\n      const {\n        playerActions,\n        whileLoop,\n        eachPlayer,\n      } = game.flowCommands\n\n      game.defineFlow(\n        () => {\n          game.tokens = 10;\n          game.message('Starting game with {{tokens}} tokens', {tokens: game.tokens});\n        },\n        whileLoop({ while: () => game.tokens > 0, do: (\n          eachPlayer({ name: 'player', do: [\n            playerActions({ actions: ['takeOne']}),\n            () => {\n              if (game.tokens <= 0) game.finish(gameManager.players.withHighest('tokens'))\n            },\n          ]})\n        )}),\n      );\n\n      game.defineSubflow(\n        'token-flow',\n        eachPlayer({ name: 'player', startingPlayer: () => game.players.current()!, do: [\n          playerActions({ actions: [\n            {\n              name: 'declare',\n              do: ({ declare, player }) => { if (declare.d === '!') player.tokens = 0 } }\n          ]}),\n        ]}),\n        () => {\n          game.players.withLowest('tokens').tokens += 2;\n        }\n      );\n\n      game.defineActions({\n        takeOne: player => game.action({\n          prompt: 'take one counter',\n        }).do(() => {\n          game.tokens --;\n          player.tokens ++;\n          if (game.tokens <= 6) Do.subflow('token-flow');\n        }),\n\n        declare: () => game.action({\n          prompt: 'declare',\n        }).enterText('d', {\n          prompt: 'declaration'\n        }),\n        pass: () => game.action({\n          prompt: 'pass'\n        }),\n      });\n\n      gameManager.players.fromJSON(players);\n      gameManager.game.fromJSON([ { className: 'TestGame', tokens: 0 } ]);\n      gameManager.players.assignAttributesFromJSON(players);\n      gameManager.start();\n      gameManager.play();\n\n      // start play\n\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] });\n      gameManager.play();\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] });\n      gameManager.play();\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] });\n      gameManager.play();\n      gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] });\n      gameManager.play();\n\n      expect(gameManager.players.currentPosition).to.deep.equal([4]);\n      expect(gameManager.allowedActions(gameManager.players[3]).actions.length).to.equal(1);\n      expect(gameManager.allowedActions(gameManager.players[3]).actions[0].name).to.equal('declare');\n\n      // starting player set from current which was still last player\n      gameManager.processMove({ name: 'declare', args: {d: '!'}, player: gameManager.players[3] });\n      gameManager.play();\n      gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[0] });\n      gameManager.play();\n      gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[1] });\n      gameManager.play();\n      gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[2] });\n      gameManager.play();\n\n      // cedes to previous flow\n      expect(gameManager.players[3].tokens).to.equal(2);\n      expect(gameManager.players.currentPosition).to.deep.equal([1]);\n      expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(1);\n      expect(gameManager.allowedActions(gameManager.players[0]).actions[0].name).to.equal('takeOne');\n    });\n  });\n});\n"
  },
  {
    "path": "src/test/game_test.ts",
    "content": "import chai from 'chai';\nimport spies from 'chai-spies';\nimport random from 'random-seed';\n\nimport {\n  Game,\n  Space,\n  Piece,\n  ConnectedSpaceMap,\n  SquareGrid,\n  HexGrid,\n  PieceGrid\n} from '../board/index.js';\n\nimport {\n  Player,\n  PlayerCollection,\n} from '../player/index.js';\nimport type { BaseGame } from '../board/game.js';\nimport { applyLayouts } from '../ui/render.js';\n\nchai.use(spies);\nconst { expect } = chai;\n\ndescribe('Game', () => {\n  let game: BaseGame;\n\n  const players = new PlayerCollection;\n  players.className = Player;\n  players.addPlayer({\n    id: 'joe',\n    name: 'Joe',\n    position: 1,\n    color: 'red',\n    avatar: '',\n    host: true\n  });\n  players.addPlayer({\n    id: 'jane',\n    name: 'Jane',\n    position: 2,\n    color: 'green',\n    avatar: '',\n    host: false\n  });\n\n  beforeEach(() => {\n    game = new Game({\n      // @ts-ignore\n      gameManager: { players, addDelay: () => {}, random: random.create('a').random },\n    });\n    game._ctx.gameManager.game = game;\n    game.setBoardSize({\n      name: '_default',\n      aspectRatio: 1,\n      frame: {x:100, y:100},\n      screen: {x:100, y:100}\n    });\n  });\n\n  it('renders', () => {\n    expect(game.allJSON()).to.deep.equals(\n      [\n        { className: 'Game', _id: 0 },\n      ]\n    );\n  });\n\n  it('creates new spaces', () => {\n    game.create(Space, 'map', {});\n    expect(game.allJSON()).to.deep.equals(\n      [\n        { className: 'Game', _id: 0, children: [\n          { className: 'Space', name: 'map', _id: 2 }\n        ]},\n      ]\n    );\n  });\n\n  it('creates new pieces', () => {\n    game.create(Piece, 'token', { player: players[0] });\n    expect(game.allJSON()).to.deep.equals(\n      [\n        { className: 'Game', _id: 0, children: [\n          { className: 'Piece', name: 'token', _id: 2, player: '$p[1]' }\n        ]},\n      ]\n    );\n  });\n\n  it('destroys pieces', () => {\n    game.create(Piece, 'token', { player: players[1] });\n    game.create(Piece, 'token', { player: players[0] });\n    game.first(Piece)!.destroy();\n    expect(game.allJSON()).to.deep.equals(\n      [\n        { className: 'Game', _id: 0, children: [\n          { className: 'Piece', name: 'token', _id: 3, player: '$p[1]' }\n        ]},\n      ]\n    );\n  });\n\n  it('removes pieces', () => {\n    game.create(Piece, 'token', { player: players[1] });\n    game.create(Piece, 'token', { player: players[0] });\n    game.first(Piece)!.remove();\n    expect(game.allJSON()).to.deep.equals(\n      [\n        { className: 'Game', _id: 0, children: [\n          { className: 'Piece', name: 'token', _id: 3, player: '$p[1]' }\n        ]},\n        { className: 'Piece', name: 'token', _id: 2, player: '$p[2]' }\n      ]\n    );\n  });\n\n  it('removes all', () => {\n    game.create(Piece, 'token', { player: players[1] });\n    game.create(Piece, 'token', { player: players[0] });\n    game.all(Piece).remove();\n    expect(game.allJSON()).to.deep.equals(\n      [\n        { className: 'Game', _id: 0},\n        { className: 'Piece', name: 'token', _id: 2, player: '$p[2]' },\n        { className: 'Piece', name: 'token', _id: 3, player: '$p[1]' }\n      ]\n    );\n  });\n\n  it('builds from json', () => {\n    const map = game.create(Space, 'map', {});\n    const france = map.create(Space, 'france', {});\n    map.create(Piece, 'token3');\n    map.create(Space, 'england', {});\n    game.create(Space, 'play', {});\n    const piece1 = france.create(Piece, 'token1', { player: players[0] });\n    const piece2 = france.create(Piece, 'token2', { player: players[1] });\n    const json = game.allJSON();\n    game.fromJSON(JSON.parse(JSON.stringify(game.allJSON())));\n    expect(game.allJSON()).to.deep.equals(json);\n    expect(game.first(Piece, 'token1')!._t.id).to.equal(piece1._t.id);\n    expect(game.first(Piece, 'token1')!.player).to.equal(players[0]);\n    expect(game.first(Piece, 'token2')!._t.id).to.equal(piece2._t.id);\n    expect(game.first(Piece, 'token2')!.player).to.equal(players[1]);\n    expect(game.first(Space, 'france')).to.equal(france);\n  });\n\n  it('preserves serializable attributes from json', () => {\n    class Country extends Space<Game> {\n      rival: Country;\n      general: Piece<Game>;\n    }\n    const map = game.create(Space, 'map', {});\n    const napolean = map.create(Piece, 'napolean')\n    const england = map.create(Country, 'england', {});\n    const france = map.create(Country, 'france', { rival: england, general: napolean });\n    const json = game.allJSON();\n    game.fromJSON(JSON.parse(JSON.stringify(json)));\n    expect(game.allJSON()).to.deep.equals(json);\n    expect(game.first(Country, 'france')).to.equal(france);\n    expect(game.first(Country, 'france')!.rival).to.equal(england);\n    expect(game.first(Country, 'france')!.general).to.equal(napolean);\n  });\n\n  it('handles cyclical serializable attributes', () => {\n    class Country extends Space<Game> {\n      general?: General;\n    }\n    class General extends Piece<Game> {\n      country?: Country;\n    }\n    const map = game.create(Space, 'map', {});\n    const france = map.create(Country, 'france');\n    const napolean = france.create(General, 'napolean', { country: france });\n    france.general = napolean;\n    const json = game.allJSON(1);\n    game.fromJSON(JSON.parse(JSON.stringify(json)));\n    expect(game.allJSON(1)).to.deep.equals(json);\n    expect(game.first(Country, 'france')).to.equal(france);\n    expect(game.first(Country, 'france')!.general?.name).to.equal('napolean');\n    expect(game.first(Country, 'france')!.general?.country).to.equal(france);\n  });\n\n  it('understands branches', () => {\n    const map = game.create(Space, 'map', {});\n    const france = map.create(Space, 'france', {});\n    map.create(Space, 'england', {});\n    const play = game.create(Space, 'play', {});\n    const piece1 = france.create(Piece, 'token1', { player: players[0] });\n    const piece2 = france.create(Piece, 'token2', { player: players[1] });\n    const piece3 = play.create(Piece, 'token3');\n    expect(piece1.branch()).to.equal('0/0/0/0');\n    expect(piece2.branch()).to.equal('0/0/0/1');\n    expect(piece3.branch()).to.equal('0/1/0');\n    expect(game.atBranch('0/0/0/0')).to.equal(piece1);\n    expect(game.atBranch('0/0/0/1')).to.equal(piece2);\n    expect(game.atBranch('0/1/0')).to.equal(piece3);\n  });\n\n  it('assigns and finds IDs', () => {\n    const map = game.create(Space, 'map', {});\n    const france = map.create(Space, 'france', {});\n    map.create(Space, 'england', {});\n    const play = game.create(Space, 'play', {});\n    const piece1 = france.create(Piece, 'token1', { player: players[0] });\n    const piece2 = france.create(Piece, 'token2', { player: players[1] });\n    const piece3 = play.create(Piece, 'token3');\n    expect(piece1._t.id).to.equal(6);\n    expect(piece2._t.id).to.equal(7);\n    expect(piece3._t.id).to.equal(8);\n    expect(game.atID(6)).to.equal(piece1);\n    expect(game.atID(7)).to.equal(piece2);\n    expect(game.atID(8)).to.equal(piece3);\n  });\n\n  it('clones', () => {\n    const map = game.create(Space, 'map', {});\n    const france = map.create(Space, 'france', {});\n    const england = map.create(Space, 'england', {});\n    const piece1 = france.create(Piece, 'token1', { player: players[0] });\n    const piece2 = piece1.cloneInto(england);\n    expect(piece1.player).to.equal(piece2.player);\n    expect(piece1.name).to.equal(piece2.name);\n    expect(england._t.children).to.include(piece2);\n  });\n\n  describe(\"Element subclasses\", () => {\n    class Card extends Piece<Game> {\n      suit: string;\n      pip: number = 1;\n      flipped?: boolean = false;\n      state?: string = 'initial';\n    }\n\n    it('takes attrs', () => {\n      game.create(Card, '2H', { suit: 'H', pip: 2 });\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 2 }\n          ]},\n        ]\n      );\n    });\n\n    it('takes base attrs', () => {\n      game.create(Card, '2H', { player: players[1], suit: 'H', pip: 2 });\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Card', flipped: false, state: 'initial', name: '2H', player: '$p[2]', suit: 'H', pip: 2, _id: 2 }\n          ]},\n        ]\n      );\n    });\n\n    it('searches', () => {\n      game.create(Card, 'AH', { suit: 'H', pip: 1 });\n      game.create(Card, '2H', { suit: 'H', pip: 2 });\n      game.create(Card, '3H', { suit: 'H', pip: 3 });\n      const card = game.first(Card, {pip: 2});\n      expect(card!.name).equals('2H');\n      const card2 = game.first(Card, {pip: 4});\n      expect(card2).equals(undefined);\n      const card3 = game.first(Card, {pip: 2, suit: 'D'});\n      expect(card3).equals(undefined);\n      const cards = game.all(Card, c => c.pip >= 2);\n      expect(cards.length).equals(2);\n      expect(cards[0].name).equals('2H');\n      expect(cards[1].name).equals('3H');\n      const card4 = game.first(\"2H\");\n      expect(card4!.name).equals('2H');\n    });\n\n    it('searches undefined', () => {\n      game.create(Card, 'AH', { suit: 'H', pip: 1, player: players[0] });\n      game.create(Card, '2H', { suit: 'H', pip: 2, player: players[1] });\n      const h3 = game.create(Card, '3H', { suit: 'H', pip: 3 });\n      expect(game.first(Card, {player: undefined})).to.equal(h3);\n    }),\n\n    it('has', () => {\n      game.create(Card, 'AH', { suit: 'H', pip: 1, player: players[0] });\n      game.create(Card, '2H', { suit: 'H', pip: 2, player: players[1] });\n      expect(game.has(Card, {pip: 2})).to.equal(true);\n      expect(game.has(Card, {pip: 2, suit: 'C'})).to.equal(false);\n    }),\n\n    it('modifies', () => {\n      game.create(Card, 'AH', { suit: 'H', pip: 1 });\n      game.create(Card, '2H', { suit: 'H', pip: 2 });\n      game.create(Card, '3H', { suit: 'H', pip: 3 });\n      const card = game.first(Card, {pip: 2})!;\n      card.suit = 'D';\n      expect(card.suit).equals('D');\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 2 },\n            { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'D', pip: 2, _id: 3 },\n            { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 4 }\n          ]},\n        ]\n      );\n    });\n\n    it('takes from pile', () => {\n      game.create(Card, 'AH', { suit: 'H', pip: 1 });\n      game.create(Card, '2H', { suit: 'H', pip: 2 });\n      const pile = game._ctx.removed;\n      const h3 = pile.create(Card, '3H', { suit: 'H', pip: 3 });\n\n      expect(h3.branch()).to.equal('1/0');\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 2 },\n            { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 3 },\n          ]},\n          { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 4 }\n        ]\n      );\n\n      expect(game.all(Card).length).to.equal(2);\n      expect(pile.all(Card).length).to.equal(1);\n    });\n\n    it('moves', () => {\n      const deck = game.create(Space, 'deck');\n      const discard = game.create(Space, 'discard');\n      deck.create(Card, 'AH', { suit: 'H', pip: 1 });\n      deck.create(Card, '2H', { suit: 'H', pip: 2 });\n      deck.create(Card, '3H', { suit: 'H', pip: 3 });\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Space', name: 'deck', _id: 2, children: [\n              { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 },\n              { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 },\n              { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 }\n            ]},\n            { className: 'Space', name: 'discard', _id: 3}\n          ]},\n        ]\n      );\n\n      deck.lastN(2, Card).putInto(discard);\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Space', name: 'deck', _id: 2, children: [\n              { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 }\n            ]},\n            { className: 'Space', name: 'discard', _id: 3, children: [\n              { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 },\n              { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 }\n            ]}\n          ]},\n        ]\n      );\n    });\n\n    it('moves with stacking order', () => {\n      const deck = game.create(Space, 'deck');\n      const discard = game.create(Space, 'discard');\n      deck.setOrder('stacking');\n      deck.create(Card, 'AH', { suit: 'H', pip: 1 });\n      deck.create(Card, '2H', { suit: 'H', pip: 2 });\n      deck.create(Card, '3H', { suit: 'H', pip: 3 });\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Space', name: 'deck', _id: 2, order: 'stacking', children: [\n              { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 },\n              { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 },\n              { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 }\n            ]},\n            { className: 'Space', name: 'discard', _id: 3}\n          ]},\n        ]\n      );\n\n      deck.lastN(2, Card).putInto(discard);\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Space', name: 'deck', _id: 2, order: 'stacking', children: [\n              { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 }\n            ]},\n            { className: 'Space', name: 'discard', _id: 3, children: [\n              { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 },\n              { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 }\n            ]}\n          ]},\n        ]\n      );\n\n      discard.all(Card).putInto(deck);\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Space', name: 'deck', _id: 2, order: 'stacking', children: [\n              { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 },\n              { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 },\n              { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 }\n            ]},\n            { className: 'Space', name: 'discard', _id: 3}\n          ]},\n        ]\n      );\n    });\n\n    it('moves fromTop', () => {\n      const deck = game.create(Space, 'deck');\n      const discard = game.create(Space, 'discard');\n      deck.create(Card, 'AH', { suit: 'H', pip: 1 });\n      deck.create(Card, '2H', { suit: 'H', pip: 2 });\n      deck.create(Card, '3H', { suit: 'H', pip: 3 });\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Space', name: 'deck', _id: 2, children: [\n              { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 },\n              { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 },\n              { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 }\n            ]},\n            { className: 'Space', name: 'discard', _id: 3}\n          ]},\n        ]\n      );\n\n      deck.lastN(2, Card).putInto(discard, {fromTop: 0});\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Space', name: 'deck', _id: 2, children: [\n              { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 }\n            ]},\n            { className: 'Space', name: 'discard', _id: 3, children: [\n              { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 },\n              { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 }\n            ]}\n          ]},\n        ]\n      );\n    });\n\n    it('tracks movement', () => {\n      const deck = game.create(Space, 'deck');\n      const discard = game.create(Space, 'discard');\n      deck.create(Card, 'AH', { suit: 'H', pip: 1 });\n      deck.create(Card, '2H', { suit: 'H', pip: 2 });\n      deck.create(Card, '3H', { suit: 'H', pip: 3 });\n      const json = game.allJSON();\n      game._ctx.trackMovement = true;\n      game.fromJSON(json);\n\n      deck.lastN(2, Card).putInto(discard);\n      expect(game.allJSON()).to.deep.equals(\n        [\n          { className: 'Game', _id: 0, children: [\n            { className: 'Space', name: 'deck', _id: 2, children: [\n              { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 }\n            ]},\n            { className: 'Space', name: 'discard', _id: 3, children: [\n              { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 },\n              { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 }\n            ]}\n          ]},\n        ]\n      );\n    });\n\n    it(\"understands players\", () => {\n      const players1Mat = game.create(Space, 'mat', {player: players[0]});\n      game.create(Space, 'mat', {player: players[1]});\n\n      players1Mat.create(Card, 'player-1-card', { suit: 'H', pip: 1, player: players[0] });\n      players1Mat.create(Card, 'player-2-card', { suit: 'H', pip: 1, player: players[1] });\n      players1Mat.create(Card, 'neutral-card', { suit: 'H', pip: 2 });\n      players[0].game = game;\n      players[1].game = game;\n\n      expect(() => game.all(Card, { mine: true })).to.throw;\n\n      game._ctx.player = players[0];\n      expect(game.all(Card, { mine: true }).length).to.equal(2);\n      expect(game.all(Card, { mine: false }).length).to.equal(1);\n      expect(game.all(Card, { owner: players[0] }).length).to.equal(2);\n      expect(game.last(Card, { mine: true })!.name).to.equal('neutral-card');\n      expect(game.first('neutral-card')!.owner).to.equal(players[0]);\n\n      game._ctx.player = players[1];\n      expect(game.all(Card, { mine: true }).length).to.equal(1);\n      expect(game.all(Card, { owner: players[1] }).length).to.equal(1);\n      expect(game.all(Card, { mine: false }).length).to.equal(2);\n\n      expect(players[0].allMy(Card).length).to.equal(2);\n      expect(players[1].allMy(Card).length).to.equal(1);\n      expect(players[0].has(Card, {pip: 1})).to.equal(true);\n      expect(players[0].has(Card, 'player-2-card')).to.equal(false);\n      expect(players[0].has(Card, {pip: 2})).to.equal(true);\n      expect(players[1].has(Card, {pip: 1})).to.equal(true);\n      expect(players[1].has(Card, {pip: 2})).to.equal(false);\n    });\n\n    it(\"sorts\", () => {\n      const deck = game.create(Space, 'deck');\n      deck.create(Card, 'AH', { suit: 'H', pip: 1 });\n      deck.create(Card, '2C', { suit: 'C', pip: 2 });\n      deck.create(Card, '3D', { suit: 'D', pip: 3 });\n      deck.create(Card, '2H', { suit: 'H', pip: 2 });\n\n      expect(game.all(Card).withHighest('pip')!.name).to.equal('3D');\n      expect(game.all(Card).withHighest('suit')!.name).to.equal('AH');\n      expect(game.all(Card).withHighest('suit', 'pip')!.name).to.equal('2H');\n      expect(game.all(Card).withHighest(c => c.suit === 'D' ? 100 : 1)!.name).to.equal('3D');\n      expect(game.all(Card).min('pip')).to.equal(1);\n      expect(game.all(Card).max('pip')).to.equal(3);\n      expect(game.all(Card).min('suit')).to.equal('C');\n      expect(game.all(Card).max('suit')).to.equal('H');\n    });\n\n    it(\"shuffles\", () => {\n      const deck = game.create(Space, 'deck');\n      deck.create(Card, 'AH', { suit: 'H', pip: 1 });\n      deck.create(Card, '2C', { suit: 'C', pip: 2 });\n      deck.create(Card, '3D', { suit: 'D', pip: 3 });\n      deck.create(Card, '2H', { suit: 'H', pip: 2 });\n      deck.shuffle();\n      expect(deck.first(Card)!.name).to.not.equal('AH');\n    });\n\n    it(\"isVisibleTo\", () => {\n      const card = game.create(Card, 'AH', { suit: 'H', pip: 1 });\n      expect(card.isVisible()).to.equal(true);\n      card.hideFromAll();\n      expect(card.isVisible()).to.equal(false);\n      expect(card.isVisibleTo(1)).to.equal(false);\n      expect(card.isVisibleTo(2)).to.equal(false);\n      card.showTo(1);\n      expect(card.isVisibleTo(1)).to.equal(true);\n      expect(card.isVisibleTo(2)).to.equal(false);\n      card.hideFrom(1);\n      expect(card.isVisibleTo(1)).to.equal(false);\n      expect(card.isVisibleTo(2)).to.equal(false);\n      card.showToAll();\n      expect(card.isVisibleTo(1)).to.equal(true);\n      expect(card.isVisibleTo(2)).to.equal(true);\n      card.hideFrom(1);\n      expect(card.isVisibleTo(1)).to.equal(false);\n      expect(card.isVisibleTo(2)).to.equal(true);\n      card.showTo(1);\n      expect(card.isVisibleTo(1)).to.equal(true);\n      expect(card.isVisibleTo(2)).to.equal(true);\n    });\n\n    it(\"hides\", () => {\n      Card.revealWhenHidden('pip', 'flipped', 'state');\n      const card = game.create(Card, 'AH', { suit: 'H', pip: 1 });\n      card.showOnlyTo(1);\n      expect(card.toJSON(1)).to.deep.equal(\n        { className: 'Card', _ref: 2, flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _visible: { default: false, except: [1] } },\n      );\n      expect(card.toJSON(2)).to.deep.equal(\n        { className: 'Card', _ref: 2, flipped: false, state: 'initial', pip: 1, _visible: { default: false, except: [1] } },\n      )\n      game.fromJSON(JSON.parse(JSON.stringify(game.allJSON(2))));\n      const card3 = game.first(Card)!;\n      expect(card3.pip).to.equal(1);\n      expect(card3.suit).to.equal(undefined);\n    });\n\n    it(\"hides spaces\", () => {\n      const hand = game.create(Space, 'hand', { player: players[0] });\n      hand.create(Card, 'AH', { suit: 'H', pip: 1 });\n\n      hand.blockViewFor('all-but-owner');\n      expect(hand.toJSON(1)).to.deep.equal(\n        { className: 'Space', name: \"hand\", player: \"$p[1]\", _ref: 2, children: [\n          {className: 'Card', _ref: 3, flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1},\n        ]}\n      );\n      expect(hand.toJSON(2)).to.deep.equal(\n        { className: 'Space', name: \"hand\", player: \"$p[1]\", _ref: 2 }\n      );\n\n      hand.blockViewFor('all');\n      expect(hand.toJSON(1)).to.deep.equal(\n        { className: 'Space', name: \"hand\", player: \"$p[1]\", _ref: 2 }\n      );\n      expect(hand.toJSON(2)).to.deep.equal(\n        { className: 'Space', name: \"hand\", player: \"$p[1]\", _ref: 2 }\n      );\n\n      hand.blockViewFor('none');\n      expect(hand.toJSON(1)).to.deep.equal(\n        { className: 'Space', name: \"hand\", player: \"$p[1]\", _ref: 2, children: [\n          {className: 'Card', _ref: 3, flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1},\n        ]}\n      );\n      expect(hand.toJSON(2)).to.deep.equal(\n        { className: 'Space', name: \"hand\", player: \"$p[1]\", _ref: 2, children: [\n          {className: 'Card', _ref: 3, flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1},\n        ]}\n      );\n    });\n\n    it(\"listens to add events\", () => {\n      const eventSpy = chai.spy();\n      game.onEnter(Card, eventSpy);\n      const card = game.create(Card, \"AH\", {suit: \"H\", pip: 1});\n      expect(eventSpy).to.have.been.called.with(card)\n    });\n\n    it(\"listens to add events from moves\", () => {\n      const eventSpy = chai.spy();\n      const deck = game.create(Space, 'deck');\n      game.create(Space, 'discard');\n      deck.onEnter(Card, eventSpy);\n      const card = game.create(Card, \"AH\", {suit: \"H\", pip: 1});\n      card.putInto(deck);\n      expect(eventSpy).to.have.been.called.with(card)\n    });\n\n    it(\"listens to exit events from moves\", () => {\n      const eventSpy = chai.spy();\n      const deck = game.create(Space, 'deck');\n      game.create(Space, 'discard');\n      deck.onExit(Card, eventSpy);\n      const card = game.create(Card, \"AH\", {suit: \"H\", pip: 1});\n      card.putInto(deck);\n      expect(eventSpy).not.to.have.been.called()\n      card.remove();\n      expect(eventSpy).to.have.been.called.with(card)\n    });\n\n    it(\"preserves events in JSON\", () => {\n      const eventSpy = chai.spy();\n      game.onEnter(Card, eventSpy);\n      game.fromJSON(JSON.parse(JSON.stringify(game.allJSON())));\n      game.create(Card, \"AH\", {suit: \"H\", pip: 1});\n      expect(eventSpy).to.have.been.called()\n    });\n\n    it('query siblings', () => {\n      const space = game.create(Space, 'map', {});\n      const card1 = space.create(Card, 'p1');\n      const piece1 = space.create(Piece, 'c1');\n      const card2 = space.create(Card, 'p2');\n      const card3 = space.create(Card, 'p3');\n\n      expect(card2.others(Card)).to.deep.equal([card1, card3]);\n      expect(card2.others()).to.deep.equal([card1, piece1, card3]);\n\n      expect(card2.next()).to.equal(card3);\n      expect(card2.previous()).to.equal(card1);\n      expect(card3.next()).to.equal(undefined);\n    });\n  });\n\n  describe(\"graph\", () => {\n    let map: ConnectedSpaceMap<BaseGame>;\n    beforeEach(() => {\n      map = game.create(ConnectedSpaceMap, 'map');\n    });\n\n    it(\"adjacency\", () => {\n      const a = map.create(Space, 'a');\n      const b = map.create(Space, 'b');\n      const c = map.create(Space, 'c');\n      map.connect(a, b);\n      expect(a.isAdjacentTo(b)).to.equal(true);\n      expect(a.isAdjacentTo(c)).to.equal(false);\n      expect(map.isAdjacent(a, b)).to.equal(true);\n      expect(map.isAdjacent(a, c)).to.equal(false);\n    })\n\n    it(\"calculates distance\", () => {\n      const a = map.create(Space, 'a');\n      const b = map.create(Space, 'b');\n      const c = map.create(Space, 'c');\n      map.connect(a, b, 2);\n      map.connect(b, c, 3);\n      map.connect(a, c, 6);\n      expect(a.distanceTo(c)).to.equal(5);\n      expect(map.distanceBetween(a, c)).to.equal(5);\n    })\n\n    it(\"calculates closest\", () => {\n      const a = map.create(Space, 'a');\n      const b = map.create(Space, 'b');\n      const c = map.create(Space, 'c');\n      map.connect(a, b, 2);\n      map.connect(b, c, 3);\n      map.connect(a, c, 6);\n      expect(map.closestTo(a)).to.equal(b);\n    })\n\n    it(\"finds adjacencies\", () => {\n      const a = map.create(Space, 'a');\n      const b = map.create(Space, 'b');\n      const c = map.create(Space, 'c');\n      const d = map.create(Space, 'd');\n      map.connect(a, b, 2);\n      map.connect(b, c, 3);\n      map.connect(a, c, 6);\n      map.connect(c, d, 1);\n      expect(a.adjacencies()).to.deep.equal([b, c]);\n      expect(c.adjacencies()).to.deep.equal([a, b, d]);\n      expect(map.allAdjacentTo(a)).to.deep.equal([b, c]);\n      expect(map.allAdjacentTo(c)).to.deep.equal([a, b, d]);\n    })\n\n    it(\"searches by distance\", () => {\n      const a = map.create(Space, 'a');\n      const b = map.create(Space, 'b');\n      const c = map.create(Space, 'c');\n      const d = map.create(Space, 'd');\n      map.connect(a, b, 2);\n      map.connect(b, c, 3);\n      map.connect(a, c, 6);\n      map.connect(c, d, 1);\n      expect(a.withinDistance(5).all(Space)).to.deep.equal([b, c]);\n      expect(map.allWithinDistanceOf(a, 5, Space)).to.deep.equal([b, c]);\n    })\n\n    it(\"searches contiguous\", () => {\n      const a = map.create(Space, 'a');\n      const b = map.create(Space, 'b');\n      const c = map.create(Space, 'c');\n      const d = map.create(Space, 'd');\n      const e = map.create(Space, 'e');\n      const f = map.create(Space, 'f');\n      map.connect(a, b, 2);\n      map.connect(b, c, 3);\n      map.connect(a, c, 6);\n      map.connect(c, d, 1);\n      map.connect(e, f, 1);\n      expect(map.allConnectedTo(a).all(Space)).to.deep.equal([a, b, c, d]);\n    })\n  });\n\n  describe('grids', () => {\n    class Cell extends Space<Game> { color: string }\n\n    it('creates squares', () => {\n      game.create(SquareGrid, 'square', { rows: 3, columns: 3, space: Cell });\n      expect(game.all(Cell).length).to.equal(9);\n      expect(game.first(Cell)!.row).to.equal(1);\n      expect(game.first(Cell)!.column).to.equal(1);\n      expect(game.last(Cell)!.row).to.equal(3);\n      expect(game.last(Cell)!.column).to.equal(3);\n\n      const corner = game.first(Cell, {row: 1, column: 1})!;\n      expect(corner.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1]]);\n\n      const middle = game.first(Cell, {row: 2, column: 2})!;\n      expect(middle.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1], [2,3], [3,2]]);\n    });\n\n    it('creates squares with diagonals', () => {\n      const square = game.create(SquareGrid, 'square', { rows: 3, columns: 3, diagonalDistance: 1.5, space: Cell });\n      expect(game.all(Cell).length).to.equal(9);\n      expect(game.first(Cell)!.row).to.equal(1);\n      expect(game.first(Cell)!.column).to.equal(1);\n      expect(game.last(Cell)!.row).to.equal(3);\n      expect(game.last(Cell)!.column).to.equal(3);\n\n      const corner = game.first(Cell, {row: 1, column: 1})!;\n      expect(corner.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1], [2,2]]);\n\n      const knight = game.first(Cell, {row: 3, column: 2})!;\n      expect(square.distanceBetween(corner, knight)).to.equal(2.5);\n    });\n\n    it('creates hexes', () => {\n      game.create(HexGrid, 'hex', { rows: 3, columns: 3, space: Cell });\n      expect(game.all(Cell).length).to.equal(9);\n      expect(game.first(Cell)!.row).to.equal(1);\n      expect(game.first(Cell)!.column).to.equal(1);\n      expect(game.last(Cell)!.row).to.equal(3);\n      expect(game.last(Cell)!.column).to.equal(3);\n\n      const corner = game.first(Cell, {row: 1, column: 1})!;\n      expect(corner.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1], [2,2]]);\n\n      const middle = game.first(Cell, {row: 2, column: 2})!;\n      expect(middle.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,1], [1,2], [2,1], [2,3], [3,2], [3,3]]);\n    });\n\n    it('creates inverse hexes', () => {\n      game.create(HexGrid, 'hex', { rows: 3, columns: 3, axes: 'east-by-southeast', space: Cell });\n      expect(game.all(Cell).length).to.equal(9);\n      expect(game.first(Cell)!.row).to.equal(1);\n      expect(game.first(Cell)!.column).to.equal(1);\n      expect(game.last(Cell)!.row).to.equal(3);\n      expect(game.last(Cell)!.column).to.equal(3);\n\n      const corner = game.first(Cell, {row: 1, column: 1})!;\n      expect(corner.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1]]);\n\n      const middle = game.first(Cell, {row: 2, column: 2})!;\n      expect(middle.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [1,3], [2,1], [2,3], [3,1], [3,2]]);\n    });\n\n    it('creates hex-shaped hexes', () => {\n      game.create(HexGrid, 'hex', { rows: 4, columns: 5, shape: 'hex', space: Cell });\n      expect(game.all(Cell).length).to.equal(16);\n      expect(game.all(Cell, {row: 1}).length).to.equal(3);\n      expect(game.all(Cell, {row: 2}).length).to.equal(4);\n      expect(game.all(Cell, {row: 3}).length).to.equal(5);\n      expect(game.all(Cell, {row: 4}).length).to.equal(4);\n\n      const cell = game.first(Cell, {row: 2, column: 4})!;\n      expect(cell.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,3], [2,3], [3,4], [3,5]]);\n    });\n\n    it('creates inverse hex-shaped hexes', () => {\n      game.create(HexGrid, 'hex', { rows: 4, columns: 5, shape: 'hex', axes: 'east-by-southeast', space: Cell });\n      expect(game.all(Cell).length).to.equal(16);\n      expect(game.all(Cell, {row: 1}).length).to.equal(3);\n      expect(game.all(Cell, {row: 2}).length).to.equal(4);\n      expect(game.all(Cell, {row: 3}).length).to.equal(5);\n      expect(game.all(Cell, {row: 4}).length).to.equal(4);\n\n      const cell = game.first(Cell, {row: 2, column: 2})!;\n      expect(cell.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,3], [2,3], [3,1], [3,2]]);\n    });\n\n    it('creates square-shaped hexes', () => {\n      game.create(HexGrid, 'hex', { rows: 4, columns: 5, shape: 'square', axes: 'east-by-southeast', space: Cell });\n      expect(game.all(Cell).length).to.equal(18);\n      expect(game.all(Cell, {row: 1}).length).to.equal(5);\n      expect(game.all(Cell, {row: 2}).length).to.equal(4);\n      expect(game.all(Cell, {row: 3}).length).to.equal(5);\n      expect(game.all(Cell, {row: 4}).length).to.equal(4);\n\n      const cell = game.first(Cell, {row: 2, column: 1})!;\n      expect(cell.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,1], [1,2], [2,2], [3,0], [3,1]]);\n    });\n\n    it('adjacencies', () => {\n      game.create(SquareGrid, 'square', { rows: 3, columns: 3, space: Cell });\n      for (const cell of game.all(Cell, {row: 2})) cell.color = 'red';\n      const center = game.first(Cell, {row: 2, column: 2})!;\n      expect(center.adjacencies(Cell).map(c => [c.row, c.column])).to.deep.equal([[1, 2], [2, 1], [2, 3], [3, 2]]);\n      expect(center.adjacencies(Cell, {color: 'red'}).map(c => [c.row, c.column])).to.deep.equal([[2, 1], [2, 3]]);\n      expect(center.isAdjacentTo(game.first(Cell, {row: 1, column: 2})!)).to.be.true;\n      expect(center.isAdjacentTo(game.first(Cell, {row: 1, column: 1})!)).to.be.false;\n    });\n\n    it('deep adjacencies', () => {\n      game.create(SquareGrid, 'square', { rows: 3, columns: 3, space: Cell });\n      const topLeft = game.first(Cell, {row: 1, column: 1})!;\n      const topCenter = game.first(Cell, {row: 1, column: 2})!;\n      const center = game.first(Cell, {row: 2, column: 2})!;\n      const p1 = topLeft.create(Piece, 'p1');\n      const p2 = topCenter.create(Piece, 'p2');\n      const p3 = center.create(Piece, 'p3');\n      expect(p2.adjacencies(Piece)).to.deep.equal([p1, p3]);\n      expect(p1.adjacencies(Piece)).to.deep.equal([p2]);\n      expect(p3.adjacencies(Piece)).to.deep.equal([p2]);\n    });\n  });\n\n  describe('shapes', () => {\n    let p1: Piece<Game>;\n    let p2: Piece<Game>;\n    let map: PieceGrid<Game>;\n\n    beforeEach(() => {\n      map = game.create(PieceGrid, 'map');\n      p1 = map.create(Piece, 'p1');\n      p2 = map.create(Piece, 'p2');\n\n      p1.setShape(\n        'ABC',\n        'D  ',\n        'E  ',\n      );\n\n      p2.setShape(\n        'abcd',\n        'e f ',\n      );\n    });\n\n    describe(\"both zero degrees\", () => {\n      it('finds overlap 1', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = 0;\n        p2.row = 0;\n\n        expect(map.isOverlapping(p1, p2)).to.be.true;\n      });\n\n      it('finds overlap 2', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = 1;\n        p2.row = 1;\n\n        expect(map.isOverlapping(p1, p2)).to.be.false;\n      });\n\n      it('finds overlap 3', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = -1;\n        p2.row = -1;\n\n        expect(map.isOverlapping(p1, p2)).to.be.true;\n      });\n\n      it('finds overlap 4', () => {\n        p1.column = 4;\n        p1.row = 2;\n        p2.column = 1;\n        p2.row = 1;\n\n        expect(map.isOverlapping(p1, p2)).to.be.false;\n      });\n    });\n\n    describe(\"p1 at 90 degrees\", () => {\n      beforeEach(() => p1.rotation = 90);\n      it('finds overlap 5', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = -1;\n        p2.row = 1;\n\n        expect(map.isOverlapping(p1, p2)).to.be.true;\n      });\n\n      it('finds overlap 6', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = -2;\n        p2.row = 1;\n\n        expect(map.isOverlapping(p1, p2)).to.be.false;\n      });\n\n      it('finds overlap 7', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = 2;\n        p2.row = 2;\n\n        expect(map.isOverlapping(p1, p2)).to.be.true;\n      });\n\n      it('finds overlap 8', () => {\n        p1.column = 2;\n        p1.row = 4;\n        p2.column = 3;\n        p2.row = 2;\n\n        expect(map.isOverlapping(p1, p2)).to.be.false;\n      });\n    });\n\n    describe(\"p2 at 270 degrees\", () => {\n      beforeEach(() => p2.rotation = 270);\n      it('finds overlap 9', () => {\n        p1.column = -1;\n        p1.row = 0;\n        p2.column = 1;\n        p2.row = 0;\n\n        expect(map.isOverlapping(p1, p2)).to.be.true;\n      });\n\n      it('finds overlap 10', () => {\n        p1.column = -1;\n        p1.row = 0;\n        p2.column = 0;\n        p2.row = 1;\n\n        expect(map.isOverlapping(p1, p2)).to.be.false;\n      });\n\n      it('finds overlap 11', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = 0;\n        p2.row = 2;\n\n        expect(map.isOverlapping(p1, p2)).to.be.true;\n      });\n\n      it('finds overlap 12', () => {\n        p1.column = 1;\n        p1.row = 0;\n        p2.column = 0;\n        p2.row = 2;\n\n        expect(map.isOverlapping(p1, p2)).to.be.false;\n      });\n    });\n\n    describe(\"p1 at 180 degrees, p2 at 270 degrees\", () => {\n      beforeEach(() => {p1.rotation = 180; p2.rotation = 270});\n      it('finds overlap 13', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = -1;\n        p2.row = -1;\n\n        expect(map.isOverlapping(p1, p2)).to.be.true;\n      });\n\n      it('finds overlap 14', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = -1;\n        p2.row = 0;\n        p1.setEdges({\n          C: {\n            up: 'UP',\n            down: 'DOWN',\n            left: 'LEFT',\n            right: 'RIGHT'\n          }\n        });\n        p2.setEdges({\n          b: {\n            up: 'up',\n            down: 'down',\n            left: 'left',\n            right: 'right'\n          },\n          f: {\n            up: 'Up',\n            down: 'Down',\n            left: 'Left',\n            right: 'Right'\n          },\n          e: {\n            right: 'stuff'\n          }\n        });\n\n        // d  E\n        // cf D\n        // bCBA\n        // ae\n        expect(map.isOverlapping(p1, p2)).to.be.false;\n        expect(map.adjacenciesByCell(p1, p2)).to.deep.equal([\n          {\n            piece: p2,\n            from: 'C',\n            to: 'f'\n          },\n          {\n            piece: p2,\n            from: 'C',\n            to: 'e'\n          },\n          {\n            piece: p2,\n            from: 'C',\n            to: 'b'\n          },\n        ]);\n        expect(map.adjacenciesByEdge(p1, p2)).to.deep.equal([\n          {\n            piece: p2,\n            from: 'DOWN',\n            to: 'Left'\n          },\n          {\n            piece: p2,\n            from: 'UP',\n            to: 'stuff'\n          },\n          {\n            piece: p2,\n            from: 'RIGHT',\n            to: 'down'\n          },\n        ]);\n      });\n\n      it('finds overlap 15', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = -1;\n        p2.row = 1;\n\n        expect(map.isOverlapping(p1, p2)).to.be.true;\n      });\n\n      it('finds overlap 16', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = -1;\n        p2.row = 2;\n        p1.setEdges({\n          C: {\n            up: 'UP',\n            down: 'DOWN',\n            left: 'LEFT',\n            right: 'RIGHT'\n          }\n        });\n        p2.setEdges({\n          d: {\n            up: 'up',\n            down: 'down',\n            left: 'left',\n            right: 'right'\n          },\n          f: {\n            up: 'Up',\n            down: 'Down',\n            left: 'Left',\n            right: 'Right'\n          }\n        });\n\n        //    E\n        //    D\n        // dCBA\n        // cf\n        // b\n        // ae\n        expect(map.isOverlapping(p1, p2)).to.be.false;\n        expect(map.adjacenciesByCell(p1, p2)).to.deep.equal([\n          {\n            piece: p2,\n            from: 'C',\n            to: 'f'\n          },\n          {\n            piece: p2,\n            from: 'C',\n            to: 'd'\n          },\n        ]);\n        expect(map.adjacenciesByEdge(p1, p2)).to.deep.equal([\n          {\n            piece: p2,\n            from: 'UP',\n            to: 'Right'\n          },\n          {\n            piece: p2,\n            from: 'RIGHT',\n            to: 'down'\n          }\n        ]);\n      });\n\n      it('3 body problem', () => {\n        p1.column = 0;\n        p1.row = 0;\n        p2.column = -1;\n        p2.row = 2;\n        const p3 = map.create(Piece, 'p3') // unshaped\n        p3.column = 1;\n        p3.row = 3;\n        p1.setEdges({\n          C: {\n            up: 'UP',\n            down: 'DOWN',\n            left: 'LEFT',\n            right: 'RIGHT'\n          },\n          B: {\n            up: 'UP',\n            down: 'DOWN',\n            left: 'LEFT',\n            right: 'RIGHT'\n          }\n        });\n        p2.setEdges({\n          d: {\n            up: 'up',\n            down: 'down',\n            left: 'left',\n            right: 'right'\n          },\n          f: {\n            up: 'Up',\n            down: 'Down',\n            left: 'Left',\n            right: 'Right'\n          }\n        });\n\n        //    E\n        //    D\n        // dCBA\n        // cf.\n        // b\n        // ae\n        expect(map.isOverlapping(p1, p2)).to.be.false;\n        expect(map.isOverlapping(p1, p3)).to.be.false;\n        expect(map.isOverlapping(p3, p1)).to.be.false;\n        expect(map.isOverlapping(p3, p2)).to.be.false;\n        expect(map.isOverlapping(p1)).to.be.false;\n        expect(map.isOverlapping(p3)).to.be.false;\n        expect(map.adjacenciesByCell(p1)).to.deep.equal([\n          {\n            piece: p2,\n            from: 'C',\n            to: 'f'\n          },\n          {\n            piece: p2,\n            from: 'C',\n            to: 'd'\n          },\n          {\n            piece: p3,\n            from: 'B',\n            to: '.'\n          }\n        ]);\n        expect(map.adjacenciesByEdge(p1)).to.deep.equal([\n          {\n            piece: p2,\n            from: 'UP',\n            to: 'Right'\n          },\n          {\n            piece: p2,\n            from: 'RIGHT',\n            to: 'down'\n          },\n          {\n            piece: p3,\n            from: 'UP',\n            to: undefined\n          }\n        ]);\n        expect(map.adjacenciesByEdge(p3)).to.deep.equal([\n          {\n            piece: p1,\n            from: undefined,\n            to: 'UP'\n          },\n          {\n            piece: p2,\n            from: undefined,\n            to: 'Down'\n          },\n        ]);\n      });\n    });\n\n    it('can place shapes', () => {\n      p1.column = 0;\n      p1.row = 0;\n      p2.column = -1;\n      p2.row = -1;\n\n      const ui = applyLayouts(game);\n      expect(ui.all[p1._t.ref].relPos).to.deep.equal({ left: 25, top: 25, width: 75, height: 75 })\n      expect(ui.all[p2._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 100, height: 50 })\n    });\n\n    it('can place shapes rotated', () => {\n      p1.column = 0;\n      p1.row = 0;\n      p1.rotation = 180;\n      p2.column = 1;\n      p2.row = 1;\n      p2.rotation = 90;\n\n      const ui = applyLayouts(game);\n      expect(ui.all[p1._t.ref].relPos).to.deep.equal({ left: 20, top: 0, width: 60, height: 60, rotation: 180 })\n      expect(ui.all[p2._t.ref].relPos).to.deep.equal({ left: 40, top: 20, width: 80, height: 40, rotation: 90 })\n      expect(ui.all[p2._t.ref].baseStyles?.transformOrigin).to.equal('25% 50%')\n    });\n\n    it('can find place for shapes', () => {\n      p1.column = 4;\n      p1.row = 5;\n      p1.rotation = 0;\n      p2.column = 5;\n      p2.row = 5;\n      p2.rotation = 90;\n      map._fitPieceInFreePlace(p2, 4, 4, {column: 4, row: 4});\n      // ..ea\n      // ABCb\n      // D.fc\n      // E..d\n      expect(p2.column).equal(6);\n      expect(p2.row).equal(4);\n      expect(p2.rotation).equal(90);\n    });\n\n    it('can find place for shapes even if rotation is forced', () => {\n      p1.column = 2;\n      p1.row = 2;\n      p1.rotation = 180;\n      p2.column = 2;\n      p2.row = 2;\n      p2.rotation = 90;\n      map.rows = 5;\n      map.columns = 5;\n      map._fitPieceInFreePlace(p2, 5, 5, {column: 1, row: 1});\n      // .....\n      // d..E.\n      // cf.D.\n      // bCBA.\n      // ae...\n      expect(p2.column).equal(1);\n      expect(p2.row).equal(2);\n      expect(p2.rotation).equal(270);\n    });\n  });\n});\n"
  },
  {
    "path": "src/test/render_test.ts",
    "content": "import chai from 'chai';\nimport spies from 'chai-spies';\n\nimport {\n  Game,\n  Space,\n  Piece,\n  GameElement,\n} from '../board/index.js';\n\nimport {\n  applyLayouts,\n  applyDiff\n} from '../ui/render.js';\n\nimport type { BaseGame } from '../board/game.js';\n\nchai.use(spies);\nconst { expect } = chai;\n\ndescribe('Render', () => {\n  let game: BaseGame;\n\n  describe('layouts', () => {\n    beforeEach(() => {\n      game = new Game({});\n      game.setBoardSize({\n        name: '_default',\n        aspectRatio: 1,\n        frame: {x:100, y:100},\n        screen: {x:100, y:100}\n      });\n      game.layout(GameElement, {\n        margin: 0,\n        gap: 0,\n      });\n    });\n\n    it('applies', () => {\n      const a = game.create(Space, 'a');\n      const b = game.create(Space, 'b');\n      const c = game.create(Space, 'c');\n      const d = game.create(Space, 'd');\n      const ui = applyLayouts(game);\n\n      expect(ui.game.relPos).to.deep.equal({ left: 0, top: 0, width: 100, height: 100 })\n      expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 50 })\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 })\n    });\n\n    it('applies overlaps', () => {\n      game.create(Space, 's1');\n      game.create(Space, 's2');\n      game.create(Space, 's3');\n      game.create(Space, 's4');\n      const p1 = game.create(Piece, 'p1');\n      const p2 = game.create(Piece, 'p2');\n      const p3 = game.create(Piece, 'p3');\n      const p4 = game.create(Piece, 'p4');\n      const ui = applyLayouts(game, () => {\n        game.layout(Piece, {\n          rows: 3,\n          columns: 3,\n          direction: 'ltr'\n        });\n      });\n\n      expect(ui.all[p1._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 100 / 3, height: 100 / 3 })\n      expect(ui.all[p2._t.ref].relPos).to.deep.equal({ left: 100 / 3, top: 0, width: 100 / 3, height: 100 / 3 })\n      expect(ui.all[p3._t.ref].relPos).to.deep.equal({ left: 200 / 3, top: 0, width: 100 / 3, height: 100 / 3 })\n      expect(ui.all[p4._t.ref].relPos).to.deep.equal({ left: 0, top: 100 / 3, width: 100 / 3, height: 100 / 3 })\n    });\n\n    it('adds gaps and margins', () => {\n      const a = game.create(Space, 'a');\n      const b = game.create(Space, 'b');\n      const c = game.create(Space, 'c');\n      const d = game.create(Space, 'd');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          gap: 10,\n          margin: 5\n        });\n      });\n      expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 5, top: 5, width: 40, height: 40 })\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 55, top: 5, width: 40, height: 40 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 5, top: 55, width: 40, height: 40 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 55, top: 55, width: 40, height: 40 })\n    });\n\n    it('adds gaps and margins absolutely to relative sizes', () => {\n      const outer = game.createMany(4, Space, 'outer');\n      const a = outer[3].create(Space, 'a');\n      const b = outer[3].create(Space, 'b');\n      const c = outer[3].create(Space, 'c');\n      const d = outer[3].create(Space, 'd');\n      const ui = applyLayouts(game, () => {\n        outer[3].layout(GameElement, {\n          gap: 4,\n          margin: 2\n        });\n      });\n      expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 4, top: 4, width: 42, height: 42 })\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 54, top: 4, width: 42, height: 42 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 4, top: 54, width: 42, height: 42 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 54, top: 54, width: 42, height: 42 })\n    });\n\n    it('areas are relative to parent', () => {\n      const outer = game.createMany(3, Space, 'outer');\n      const a = outer[2].create(Space, 'a');\n      const b = outer[2].create(Space, 'b');\n      const c = outer[2].create(Space, 'c');\n      const d = outer[2].create(Space, 'd');\n      const ui = applyLayouts(game, () => {\n        outer[2].layout(GameElement, {\n          gap: 4,\n          area: {\n            left: 10,\n            top: 20,\n            width: 80,\n            height: 60,\n          }\n        });\n      });\n      expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 10, top: 20, width: 36, height: 26 })\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 54, top: 20, width: 36, height: 26 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 10, top: 54, width: 36, height: 26 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 54, top: 54, width: 36, height: 26 })\n    });\n\n    it('aligns', () => {\n      const spaces = game.createMany(3, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          aspectRatio: 4 / 5,\n          scaling: 'fit',\n          alignment: 'right',\n        });\n      });\n\n      expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 60, top: 0, width: 40, height: 50 })\n      expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 20, top: 0, width: 40, height: 50 })\n      expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 60, top: 50, width: 40, height: 50 })\n    });\n\n    it('aligns vertical', () => {\n      const spaces = game.createMany(3, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          aspectRatio: 5 / 4,\n          scaling: 'fit',\n          alignment: 'bottom right',\n        });\n      });\n\n      expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 50, top: 60, width: 50, height: 40 })\n      expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 0, top: 60, width: 50, height: 40 })\n      expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 50, top: 20, width: 50, height: 40 })\n    });\n\n    it('sizes to fit', () => {\n      const spaces = game.createMany(3, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          aspectRatio: 4 / 5,\n          scaling: 'fit'\n        });\n      });\n      expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 10, top: 0, width: 40, height: 50 })\n      expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 40, height: 50 })\n      expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 10, top: 50, width: 40, height: 50 })\n    });\n\n    it('sizes to fill', () => {\n      const spaces = game.createMany(3, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          aspectRatio: 4 / 5,\n          scaling: 'fill'\n        });\n      });\n      expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 62.5 })\n      expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 62.5 })\n      expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 0, top: 37.5, width: 50, height: 62.5 })\n    });\n\n    it('retains sizes', () => {\n      const spaces = game.createMany(3, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          size: { width: 20, height: 25 },\n        });\n      });\n      expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 30, top: 25, width: 20, height: 25 })\n      expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 50, top: 25, width: 20, height: 25 })\n      expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 30, top: 50, width: 20, height: 25 })\n    });\n\n    it('fits based on aspect ratios', () => {\n      const spaces = game.createMany(3, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          aspectRatio: 5 / 4,\n          scaling: 'fit'\n        });\n      });\n      expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 0, top: 10, width: 50, height: 40 })\n      expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 50, top: 10, width: 50, height: 40 })\n      expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 40 })\n    });\n\n    it('fills based on aspect ratios', () => {\n      const spaces = game.createMany(3, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          aspectRatio: 5 / 4,\n          scaling: 'fill'\n        });\n      });\n      expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 62.5, height: 50 })\n      expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 37.5, top: 0, width: 62.5, height: 50 })\n      expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 62.5, height: 50 })\n    });\n\n    it('accommodate min row', () => {\n      const spaces = game.createMany(10, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          rows: { min: 2 },\n          columns: 1,\n          aspectRatio: 5 / 4,\n          scaling: 'fill'\n        });\n      });\n      expect(ui.all[spaces[0]._t.ref].relPos?.width).to.equal(62.5);\n      expect(ui.all[spaces[0]._t.ref].relPos?.height).to.equal(50);\n      expect(ui.all[spaces[0]._t.ref].relPos?.top).to.be.approximately(0, 0.0001);\n    });\n\n    it('accommodate min col', () => {\n      const spaces = game.createMany(10, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          columns: { min: 2 },\n          rows: 1,\n          aspectRatio: 4 / 5,\n          scaling: 'fill'\n        });\n      });\n      expect(ui.all[spaces[0]._t.ref].relPos?.height).to.equal(62.5);\n      expect(ui.all[spaces[0]._t.ref].relPos?.width).to.equal(50);\n      expect(ui.all[spaces[0]._t.ref].relPos?.left).to.be.approximately(0, 0.0001);\n    });\n\n    it('size overrides scaling', () => {\n      const spaces = game.createMany(10, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          rows: { min: 2 },\n          columns: 1,\n          size: { width: 5, height: 4 },\n          scaling: 'fill'\n        });\n      });\n      expect(ui.all[spaces[0]._t.ref].relPos?.width).to.equal(5);\n      expect(ui.all[spaces[0]._t.ref].relPos?.height).to.equal(4);\n      expect(ui.all[spaces[0]._t.ref].relPos?.top).to.equal(30);\n    });\n\n    it('isomorphic', () => {\n      const spaces = game.createMany(9, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          aspectRatio: 4 / 5,\n          offsetColumn: {x: 100, y: 100},\n          scaling: 'fit',\n        });\n      });\n\n      expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 42, top: 0 });\n      expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 58, top: 20 });\n      expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 74, top: 40 });\n      expect(ui.all[spaces[3]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 26, top: 20 });\n      expect(ui.all[spaces[4]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 42, top: 40 });\n      expect(ui.all[spaces[5]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 58, top: 60 });\n      expect(ui.all[spaces[6]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 10, top: 40 });\n      expect(ui.all[spaces[7]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 26, top: 60 });\n      expect(ui.all[spaces[8]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 42, top: 80 });\n    });\n\n    it('stacks', () => {\n      const spaces = game.createMany(9, Space, 'space');\n      const ui = applyLayouts(game, () => {\n        game.layout(GameElement, {\n          aspectRatio: 4 / 5,\n          offsetColumn: {x: -5, y: -5},\n          scaling: 'fit',\n          direction: 'ltr'\n        });\n      });\n\n      expect(ui.all[spaces[8]!._t.ref].relPos!.top).to.equal(0);\n      expect(ui.all[spaces[0]!._t.ref].relPos!.top + ui.all[spaces[0]!._t.ref].relPos!.height).to.equal(100);\n    });\n\n    it('align+scale', () => {\n      const pieces = game.createMany(6, Piece, 'piece');\n\n      const ui = applyLayouts(game, () => {\n        game.layout(Piece, {\n          offsetColumn: {x: 10, y: 10},\n          scaling: 'fit',\n        });\n      });\n\n      expect(ui.all[pieces[0]!._t.ref].relPos!.top).to.equal(0);\n      expect(ui.all[pieces[5]!._t.ref].relPos!.top + ui.all[pieces[5]!._t.ref].relPos!.height).to.equal(100);\n      expect(ui.all[pieces[3]!._t.ref].relPos!.left).to.equal(0);\n      expect(ui.all[pieces[2]!._t.ref].relPos!.left + ui.all[pieces[2]!._t.ref].relPos!.width).to.equal(100);\n    });\n\n    it('specificity', () => {\n      class Country extends Space<Game> { }\n      game = new Game({});\n      game.setBoardSize({\n        name: '_default',\n        aspectRatio: 1,\n        frame: {x:100, y:100},\n        screen: {x:100, y:100}\n      });\n\n      const spaces = game.createMany(4, Space, 'space');\n      const space = game.create(Space, 'special');\n      const france = game.create(Country, 'france');\n      const special = game.create(Country, 'special');\n      const el = game.create(GameElement, 'whatev');\n\n      const ui = applyLayouts(game, () => {\n        game.layout(spaces[2], { direction: 'btt-rtl', showBoundingBox: '1' });\n        game.layout('special', { direction: 'ttb-rtl', showBoundingBox: '2' });\n        game.layout(spaces.slice(0, 2), { direction: 'ttb', showBoundingBox: '3' });\n        game.layout(Country, { direction: 'rtl', showBoundingBox: '4' });\n        game.layout(Space, { direction: 'btt', showBoundingBox: '5' });\n        game.layout(GameElement, { direction: 'ltr-btt', showBoundingBox: '6' });\n      });\n\n      expect(ui.game.layouts[6].children.some(r => r.element === el)).to.be.true; // by GameElement\n      expect(ui.game.layouts[5].children.some(r => r.element === spaces[3])).to.be.true; // by Space\n      expect(ui.game.layouts[4].children.some(r => r.element === france)).to.be.true; // by more specific class\n      expect(ui.game.layouts[3].children.some(r => r.element === spaces[0])).to.be.true; // by single ref\n      expect(ui.game.layouts[2].children.some(r => r.element === space)).to.be.true; // by name\n      expect(ui.game.layouts[2].children.some(r => r.element === special)).to.be.true; // by name\n      expect(ui.game.layouts[1].children.some(r => r.element === spaces[2])).to.be.true; // by array ref\n    });\n\n    it('can place', () => {\n      const a = game.create(Space, 'a');\n      const b = game.create(Space, 'b');\n      const c = game.create(Space, 'c');\n      const d = game.create(Space, 'd');\n      a.row = 2;\n      a.column = 2;\n      const ui = applyLayouts(game);\n\n      expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 })\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 50 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 })\n    });\n\n    it('can shift bounds', () => {\n      const a = game.create(Space, 'a');\n      const b = game.create(Space, 'b');\n      const c = game.create(Space, 'c');\n      const d = game.create(Space, 'd');\n      a.row = 4;\n      a.column = 4;\n      const ui = applyLayouts(game);\n\n      expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 })\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 50 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 })\n    });\n\n    it('can shift negative', () => {\n      const a = game.create(Space, 'a');\n      const b = game.create(Space, 'b');\n      const c = game.create(Space, 'c');\n      const d = game.create(Space, 'd');\n      a.row = -4;\n      a.column = -4;\n      const ui = applyLayouts(game);\n\n      expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 50 })\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 })\n    });\n\n    it('can stretch bounds', () => {\n      const a = game.create(Space, 'a');\n      const b = game.create(Space, 'b');\n      const c = game.create(Space, 'c');\n      const d = game.create(Space, 'd');\n      a.row = 1;\n      a.column = 2;\n      d.row = 4;\n      d.column = 2;\n      const ui = applyLayouts(game);\n\n      expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 100, height: 25 })\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 0, top: 25, width: 100, height: 25 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 100, height: 25 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 0, top: 75, width: 100, height: 25 })\n    });\n\n    it('can become sparse', () => {\n      const a = game.create(Space, 'a');\n      const b = game.create(Space, 'b');\n      const c = game.create(Space, 'c');\n      const d = game.create(Space, 'd');\n      a.row = 4;\n      a.column = 1;\n      d.row = 1;\n      d.column = 4;\n      const ui = applyLayouts(game);\n\n      expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 0, top: 75, width: 25, height: 25 })\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 25, height: 25 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 25, top: 0, width: 25, height: 25 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 75, top: 0, width: 25, height: 25 })\n    });\n\n    it('can place sticky', () => {\n      const a = game.create(Piece, 'a');\n      const b = game.create(Piece, 'b');\n      const c = game.create(Piece, 'c');\n      const d = game.create(Piece, 'd');\n      applyLayouts(game, () => {\n        game.layout(Piece, { sticky: true });\n      });\n      a.remove();\n      game.resetUI();\n      const ui = applyLayouts(game, () => {\n        game.layout(Piece, { sticky: true });\n      });\n\n      expect(b.column).to.equal(2);\n      expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 })\n      expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 })\n      expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 })\n    });\n  });\n\n  describe('applyDiff', () => {\n    let client: BaseGame;\n    let server: BaseGame;\n\n    beforeEach(() => {\n      client = new Game({ classRegistry: [Space, Piece] });\n      server = new Game({ classRegistry: [Space, Piece] });\n      server._ctx.trackMovement = true;\n      client.setBoardSize({\n        name: '_default',\n        aspectRatio: 1,\n        frame: {x:100, y:100},\n        screen: {x:100, y:100}\n      });\n    });\n\n    it(\"combines local and server\", () => {\n      const a = server.create(Space, 'a');\n      const b = server.create(Space, 'b');\n      a.create(Piece, 'p1');\n      a.create(Piece, 'p2');\n\n      client.fromJSON(server.allJSON(1));\n      const p1c = client.first(Piece, 'p1')!;\n      const p2c = client.first(Piece, 'p2')!;\n      // client move\n      p1c.putInto(client.first('b')!);\n\n      const ui1 = applyLayouts(client);\n\n      const p1s = server.first(Piece, 'p1')!;\n      // server same move\n      p1s.putInto(b);\n\n      client.fromJSON(server.allJSON(1));\n      const p1c2 = client.first(Piece, 'p1')!;\n      const p2c2 = client.first(Piece, 'p2')!;\n\n      const ui2 = applyLayouts(client);\n      applyDiff(ui2.game, ui2, ui1);\n\n      // pieces are retained\n      expect(p1c).to.equal(p1c2);\n      expect(p2c).to.equal(p2c2);\n      // keys are retained\n      expect(ui2.all[p1c2._t.ref].key).to.equal(ui1.all[p1c._t.ref].key);\n      expect(ui2.all[p2c2._t.ref].key).to.equal(ui1.all[p2c._t.ref].key);\n      // no transform since same move\n      expect(ui2.all[p1c2._t.ref].styles?.transform).to.be.undefined\n      expect(ui2.all[p2c2._t.ref].styles?.transform).to.be.undefined\n    });\n\n    it(\"combines local and server conflicts\", () => {\n      const a = server.create(Space, 'a');\n      server.create(Space, 'b');\n      const c = server.create(Space, 'c');\n      a.create(Piece, 'p1');\n      a.create(Piece, 'p2');\n\n      client.fromJSON(server.allJSON(1));\n      const p1c = client.first(Piece, 'p1')!;\n      const p2c = client.first(Piece, 'p2')!;\n      // client move\n      p1c.putInto(client.first('b')!);\n\n      const ui1 = applyLayouts(client);\n\n      const p1s = server.first(Piece, 'p1')!;\n      // server different move\n      p1s.putInto(c);\n\n      client.fromJSON(server.allJSON(1));\n      const p1c2 = client.first(Piece, 'p1')!;\n      const p2c2 = client.first(Piece, 'p2')!;\n\n      const ui2 = applyLayouts(client);\n      applyDiff(ui2.game, ui2, ui1);\n\n      // piece not retained with conflicting parent moves\n      expect(p1c).to.not.equal(p1c2);\n      // unmoved piece is retained\n      expect(p2c).to.equal(p2c2);\n      // same with keys\n      expect(ui2.all[p1c2._t.ref].key).to.not.equal(ui1.all[p1c._t.ref].key);\n      expect(ui2.all[p2c2._t.ref].key).to.equal(ui1.all[p2c._t.ref].key);\n      // transform for moved\n      expect(ui2.all[p1c2._t.ref].styles?.transform).not.to.be.undefined\n      expect(ui2.all[p2c2._t.ref].styles?.transform).to.be.undefined\n    });\n\n    it(\"tracks reorders\", () => {\n      const a = server.create(Space, 'a');\n      const p1s = a.create(Piece, 'p1');\n      const p2s = a.create(Piece, 'p2'); // on bottom\n\n      client.fromJSON(server.allJSON(1));\n      const ui1 = applyLayouts(client);\n\n      const p1c = client.first(Piece, 'p1')!;\n      const p2c = client.first(Piece, 'p2')!;\n      expect(client.first(Piece)!.name).to.equal('p1');\n\n      // server shuffle\n      expect(server.first(Piece)).to.equal(p1s);\n      p1s.putInto(a, { fromBottom: 0 });\n      expect(server.first(Piece)).to.equal(p2s); // now on top\n\n      client.fromJSON(server.allJSON(1));\n      const p1c2 = client.first(Piece, 'p1')!;\n      const p2c2 = client.first(Piece, 'p2')!;\n\n      const ui2 = applyLayouts(client);\n      applyDiff(ui2.game, ui2, ui1);\n\n      // tracks move\n      expect(client.first(Piece)!.name).to.equal('p2');\n      expect(p1c).to.equal(p1c2);\n      expect(p2c).to.equal(p2c2);\n      // transform for both\n      expect(ui2.all[p1c2._t.ref].styles?.transform).not.to.be.undefined\n      expect(ui2.all[p2c2._t.ref].styles?.transform).not.to.be.undefined\n    });\n\n    it(\"shows stack reorders if visible\", () => {\n      const a = server.create(Space, 'a');\n      a.setOrder('stacking');\n      const p1s = a.create(Piece, 'p1');\n      const p2s = a.create(Piece, 'p2'); // on top\n\n      client.fromJSON(server.allJSON(1));\n      const ui1 = applyLayouts(client);\n\n      const p1c = client.first(Piece, 'p1')!;\n      const p2c = client.first(Piece, 'p2')!;\n      expect(client.first(Piece)!.name).to.equal('p2');\n\n      // server shuffle\n      expect(server.first(Piece)).to.equal(p2s);\n      p2s.putInto(a, { fromBottom: 0 });\n      expect(server.first(Piece)).to.equal(p1s); // now on top\n\n      client.fromJSON(server.allJSON(1));\n      const p1c2 = client.first(Piece, 'p1')!;\n      const p2c2 = client.first(Piece, 'p2')!;\n\n      const ui2 = applyLayouts(client);\n      applyDiff(ui2.game, ui2, ui1);\n\n      // tracks move\n      expect(client.first(Piece)!.name).to.equal('p1');\n      expect(p1c).to.equal(p1c2);\n      expect(p2c).to.equal(p2c2);\n      // transform for both\n      expect(ui2.all[p1c2._t.ref].styles?.transform).not.to.be.undefined\n      expect(ui2.all[p2c2._t.ref].styles?.transform).not.to.be.undefined\n    });\n\n    it(\"hides stack reorders if hidden\", () => {\n      const a = server.create(Space, 'a');\n      a.setOrder('stacking');\n      const p1s = a.create(Piece, 'p1');\n      const p2s = a.create(Piece, 'p2'); // on top\n      a.all(Piece).hideFromAll();\n\n      client.fromJSON(server.allJSON(1));\n      const ui1 = applyLayouts(client);\n\n      const p1c = client.first(Piece)!;\n      const p2c = client.last(Piece)!;\n\n      // server shuffle\n      expect(server.first(Piece)).to.equal(p2s);\n      p2s.putInto(a, { fromBottom: 0 });\n      expect(server.first(Piece)).to.equal(p1s); // now on top\n\n      client.fromJSON(server.allJSON(1));\n      const p1c2 = client.first(Piece)!;\n      const p2c2 = client.last(Piece)!;\n\n      const ui2 = applyLayouts(client);\n      applyDiff(ui2.game, ui2, ui1);\n\n      // no move\n      expect(p1c).to.equal(p1c2);\n      expect(p2c).to.equal(p2c2);\n      // no transform\n      expect(ui2.all[p1c2._t.ref].styles?.transform).to.be.undefined\n      expect(ui2.all[p2c2._t.ref].styles?.transform).to.be.undefined\n    });\n  });\n});\n\n      // console.log('<div style=\"width: 200; height: 200; position: relative; outline: 1px solid black\">');\n      // for (const c of game._t.children) console.log(`<div style=\"position: absolute; left: ${c._t.ref].relPos?.left}%; top: ${c._t.ref].relPos?.top}%; width: ${c._t.ref].relPos?.width}%; height: ${c._t.ref].relPos?.height}%; background: red; outline: 1px solid blue\"></div>`);\n      // console.log('</div>');\n"
  },
  {
    "path": "src/test/setup-debug.js",
    "content": "globalThis.document={\n  createElement:() => {},\n  createTextNode: ()=>{},\n  head: {\n    appendChild:() => ({appendChild:() => {}})\n  }\n};\n"
  },
  {
    "path": "src/test/setup.js",
    "content": "globalThis.console.debug = () => {}\nglobalThis.console.warn = () => {}\n\nglobalThis.document={\n  createElement:() => {},\n  createTextNode: ()=>{},\n  head: {\n    appendChild:() => ({appendChild:() => {}})\n  }\n};\n"
  },
  {
    "path": "src/test/ui_test.ts",
    "content": "import chai from 'chai';\n\nimport Game from '../board/game.js';\nimport Player from '../player/player.js';\nimport { times } from '../utils.js';\nimport { createGame } from '../game-creator.js';\nimport { createGameStore } from '../ui/store.js';\n\nimport type { SerializedMove } from '../game-manager.js';\n\nimport {\n  starterGame,\n  starterGameWithConfirm,\n  starterGameWithValidate,\n  starterGameWithCompoundMove,\n  starterGameWithTiles,\n  starterGameWithTilesConfirm,\n  starterGameWithTilesValidate,\n  starterGameWithTilesCompound,\n  Token\n} from './fixtures/games.js';\n\nconst history: SerializedMove[] = [];\n\nconst { expect } = chai;\n\ndescribe('UI', () => {\n  beforeEach(() => {\n    globalThis.window = {\n      clearTimeout: () => {},\n      top: { postMessage: ({ data }: { data: SerializedMove }) => history.push(data) }\n    } as unknown as typeof globalThis.window;\n    history.splice(0);\n  });\n\n  afterEach(() => {\n    // @ts-ignore\n    delete globalThis.window;\n  });\n\n  it(\"presents moves\", () => {\n\n    const store = getGameStore(starterGame);\n\n    updateStore(store, 2, {tokens: 4});\n    const state = store.getState();\n\n    expect(state.pendingMoves?.[0].name).to.equal('take');\n    expect(state.boardPrompt).to.be.undefined;\n    expect(state.pendingMoves?.[0].prompt).to.equal('Choose a token');\n    expect(Object.values(state.boardSelections).length).to.equal(4);\n  });\n\n  it(\"accepts moves\", () => {\n    const store = getGameStore(starterGame);\n\n    updateStore(store, 2, {tokens: 4});\n\n    let state = store.getState();\n    const token = state.gameManager.game.first(Token)!;\n    expect(state.pendingMoves?.length).to.equal(1);\n    expect(state.pendingMoves?.[0].name).to.equal('take');\n    expect(state.pendingMoves?.[0].requireExplicitSubmit).to.be.false;\n\n    const clickMoves = state.boardSelections[token.branch()].clickMoves;\n    state.selectElement(clickMoves, token);\n    state = store.getState();\n\n    expect(history.length).to.equal(1);\n    expect(history[0].name).to.equal('take');\n\n    expect(state.pendingMoves).to.deep.equal([]);\n    expect(state.gameManager.game.first('mat')!.all(Token).length).to.equal(1);\n    expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(3);\n  });\n\n  it(\"prompts confirm\", () => {\n    const store = getGameStore(starterGameWithConfirm);\n\n    updateStore(store, 2, {tokens: 4});\n    let state = store.getState();\n    let token = state.gameManager.game.first(Token)!;\n    const clickMoves = state.boardSelections[token.branch()].clickMoves;\n    state.selectElement(clickMoves, token);\n    state = store.getState();\n    token = state.gameManager.game.first(Token)!;\n\n    expect(history.length).to.equal(0);\n    expect(state.selected).to.deep.equal([token]);\n    expect(state.pendingMoves?.[0].name).to.equal('take');\n    expect(state.boardPrompt).to.be.undefined;\n    expect(state.pendingMoves?.[0].prompt).to.equal('Choose a token');\n    expect(state.uncommittedArgs.token).to.equal(token);\n\n    state.selectMove(state.pendingMoves?.[0], state.uncommittedArgs);\n    state = store.getState();\n\n    expect(history.length).to.equal(1);\n    expect(state.pendingMoves).to.deep.equal([]);\n  });\n\n  it(\"validates\", () => {\n    const store = getGameStore(starterGameWithValidate);\n\n    updateStore(store, 2, {tokens: 4});\n    let state = store.getState();\n    let token = state.gameManager.game.first(Token)!;\n    const clickMoves = state.boardSelections[token.branch()].clickMoves;\n\n    expect(state.boardSelections[token.branch()].error).to.equal('not first');\n    expect(clickMoves.length).to.equal(0);\n  });\n\n  it(\"cancels confirm\", () => {\n    const store = getGameStore(starterGameWithConfirm);\n\n    updateStore(store, 2, {tokens: 4});\n    let state = store.getState();\n    const token = state.gameManager.game.first(Token)!;\n    const clickMoves = state.boardSelections[token.branch()].clickMoves;\n    state.selectElement(clickMoves, token);\n    state = store.getState();\n\n    expect(history.length).to.equal(0);\n    expect(state.selected?.length).to.equal(1);\n    expect(state.pendingMoves?.[0].name).to.equal('take');\n    expect(state.boardPrompt).to.be.undefined;\n    expect(state.pendingMoves?.[0].prompt).to.equal('Choose a token');\n\n    state.selectMove();\n    state = store.getState();\n\n    expect(history.length).to.equal(0);\n    expect(state.gameManager.game.first('mat')!.all(Token).length).to.equal(0);\n    expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(4);\n  });\n\n  it(\"continues compound move\", () => {\n    const store = getGameStore(starterGameWithCompoundMove);\n\n    updateStore(store, 2, {tokens: 4});\n    let state = store.getState();\n    let token = state.gameManager.game.first(Token)!;\n    const clickMoves = state.boardSelections[token.branch()].clickMoves;\n    state.selectElement(clickMoves, token);\n    state = store.getState();\n    token = state.gameManager.game.first(Token)!;\n\n    expect(history.length).to.equal(0);\n    expect(state.selected).to.be.undefined;\n    expect(state.pendingMoves?.[0].name).to.equal('take');\n    expect(state.pendingMoves?.[0].args.token).to.equal(token);\n    expect(state.pendingMoves?.[0].requireExplicitSubmit).to.be.false;\n    expect(state.pendingMoves?.[0].selections[0].type).to.equal('choices');\n    expect(state.boardPrompt).to.be.undefined; // falls thru to form since no board moves\n\n    state.selectMove(state.pendingMoves?.[0], {a: 1});\n    expect(history.length).to.equal(1);\n    expect(state.gameManager.game.first('mat')!.all(Token).length).to.equal(1);\n    expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(3);\n  });\n\n  it(\"places pieces\", () => {\n    const store = getGameStore(starterGameWithTiles);\n\n    updateStore(store, 2, {tokens: 4});\n    let state = store.getState();\n    let token = state.gameManager.game.first(Token)!;\n    const clickMoves = state.boardSelections[token.branch()].clickMoves;\n    state.selectElement(clickMoves, token);\n    state = store.getState();\n\n    state.setPlacement({ column: 2, row: 2 });\n    const ghost = state.gameManager.game.first(Token)!;\n    token = state.gameManager.game.first('pool')!.first(Token)!;\n\n    expect(history.length).to.equal(0);\n    expect(state.pendingMoves?.[0].selections[0].type).to.equal('place');\n    expect(ghost.column).to.equal(2);\n    expect(ghost.row).to.equal(2);\n    expect(token.column).to.be.undefined;\n    expect(token.row).to.be.undefined;\n\n    state.selectPlacement({ column: 2, row: 2 });\n\n    expect(history.length).to.equal(1);\n    expect(history[0].name).to.equal('take');\n    expect(history[0].args.__placement__).to.deep.equal([2, 2]);\n    expect(state.gameManager.game.first('tiles')!.all(Token).length).to.equal(1);\n    expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(3);\n  });\n\n  it(\"places pieces with confirm\", () => {\n    const store = getGameStore(starterGameWithTilesConfirm);\n\n    updateStore(store, 2, {tokens: 4});\n    let state = store.getState();\n    let token = state.gameManager.game.first(Token)!;\n    const clickMoves = state.boardSelections[token.branch()].clickMoves;\n    state.selectElement(clickMoves, token);\n    state = store.getState();\n\n    state.setPlacement({ column: 2, row: 2 });\n    state.selectPlacement({ column: 2, row: 2 });\n\n    state = store.getState();\n    token = state.gameManager.game.first(Token)!;\n\n    expect(history.length).to.equal(0);\n    expect(state.pendingMoves?.[0].selections[0].type).to.equal('place');\n    expect(state.pendingMoves?.[0].requireExplicitSubmit).to.be.true;\n    expect(token.column).to.equal(2);\n    expect(token.row).to.equal(2);\n    expect(state.gameManager.game.first('tiles')!.all(Token).length).to.equal(1); // ghost piece\n    expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(4);\n  });\n\n  it(\"places pieces with validate\", () => {\n    const store = getGameStore(starterGameWithTilesValidate);\n\n    updateStore(store, 2, {tokens: 4});\n    let state = store.getState();\n    let token = state.gameManager.game.first(Token)!;\n    const clickMoves = state.boardSelections[token.branch()].clickMoves;\n    state.selectElement(clickMoves, token);\n    state = store.getState();\n\n    state.setPlacement({ column: 1, row: 2 });\n    state = store.getState();\n    const ghost = state.placement!.piece\n\n    expect(ghost.column).to.equal(1);\n    expect(ghost.row).to.equal(2);\n    expect(state.placement?.invalid).to.be.true;\n\n    state.selectPlacement({ column: 1, row: 2 });\n\n    state = store.getState();\n    expect(state.error).to.equal('must be black square');\n    expect(history.length).to.equal(0);\n  });\n\n  it(\"continues compound place piece\", () => {\n    const store = getGameStore(starterGameWithTilesCompound);\n\n    updateStore(store, 2, {tokens: 4});\n    let state = store.getState();\n    let token = state.gameManager.game.first(Token)!;\n    const clickMoves = state.boardSelections[token.branch()].clickMoves;\n    state.selectElement(clickMoves, token);\n    state = store.getState();\n\n    state.setPlacement({ column: 2, row: 2 });\n    state.selectPlacement({ column: 2, row: 2 });\n    state = store.getState();\n\n    expect(history.length).to.equal(0);\n    expect(state.pendingMoves?.[0].args.token).to.equal(token);\n    expect(state.pendingMoves?.[0].args.__placement__).to.deep.equal([2, 2]);\n    expect(state.pendingMoves?.[0].requireExplicitSubmit).to.be.false;\n    expect(state.pendingMoves?.[0].selections[0].type).to.equal('choices');\n    expect(state.boardPrompt).to.be.undefined; // falls thru to form since no board moves\n\n    state.selectMove(state.pendingMoves?.[0], {a: 1});\n    expect(history.length).to.equal(1);\n    expect(state.gameManager.game.first('tiles')!.all(Token).length).to.equal(1);\n    expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(3);\n  });\n});\n\nfunction getGameStore(gameCreator: (game: Game) => void) {\n  const store = createGameStore();\n  const setup = createGame(Player, Game, gameCreator);\n  store.getState().setSetup(setup);\n  return store;\n}\n\nfunction updateStore(store: ReturnType<typeof createGameStore>, players: number, settings: Record<string, any>) {\n  const { setup, updateState } = store.getState();\n\n  const playerAttrs = times(players, p => ({\n    id: String(p),\n    name: String(p),\n    position: p,\n    host: p === 1,\n    color: '',\n    avatar: '',\n    tokens: 0\n  }));\n\n  // initial state\n  const gameManager = setup!({\n    players: playerAttrs,\n    settings,\n    randomSeed: 'rseed',\n  })\n\n  gameManager.play();\n\n  let state = gameManager.getPlayerStates()[0].state;\n  if (state instanceof Array) state = state[state.length - 1];\n\n  updateState({\n    type: 'gameUpdate',\n    state,\n    position: 1,\n    currentPlayers: gameManager.players.currentPosition\n  });\n}\n"
  },
  {
    "path": "src/test-runner.ts",
    "content": "import { createGameStore } from './ui/store.js';\nimport { createInterface } from './interface.js';\nimport { times } from './utils.js';\n\nimport type { BaseGame } from './board/game.js';\nimport type { GameInterface, GameState, GameUpdate, SetupState } from './interface.js';\nimport type { Argument } from './action/action.js';\nimport type { SetupFunction } from './game-creator.js';\nimport type { default as GameManager, PlayerAttributes } from './game-manager.js';\n\ndeclare global {\n  interface Window {\n    serverGameManager?: GameManager;\n  }\n}\n\nclass TestRunnerPlayer<G extends BaseGame> {\n  runner: TestRunner<G>\n  store: ReturnType<typeof createGameStore>\n  playerAttrs: PlayerAttributes\n  player: NonNullable<G['player']>\n  game: G\n  position: number\n\n  constructor(runner: TestRunner<G>, position: number, store: ReturnType<typeof createGameStore>, playerAttrs: PlayerAttributes, game: G) {\n    this.runner = runner\n    this.position = position\n    this.store = store\n    this.playerAttrs = playerAttrs\n    this.game = game\n  }\n\n  move(name: string, args: Record<string, Argument>) {\n    if (!this.runner.server.state) throw Error(\"Must call TestRunner#start first\");\n    if (this.runner.server.state!.game.phase === 'finished') throw Error(\"Cannot take a move on a finished game\");\n    if (!this.runner.server.state!.game.currentPlayers.includes(this.position)) throw Error(\"This player cannot take a move\");\n    const state = this.store.getState();\n    globalThis.$ = state.gameManager.game._ctx.namedSpaces;\n    this.runner.currentPosition = this.position;\n    state.selectMove({\n      name,\n      args,\n      selections: [],\n      requireExplicitSubmit: false\n    })\n    this.runner.updatePlayersFromState();\n  }\n\n  actions() {\n    const pendingMoves = this.game._ctx.gameManager.getPendingMoves(this.game._ctx.gameManager.players[this.position - 1]);\n    if (!pendingMoves) return [];\n    return pendingMoves.moves.map(m => m.name);\n  }\n}\n\nexport class TestRunner<G extends BaseGame> {\n  server: {\n    interface: GameInterface;\n    state?: GameUpdate;\n    gameManager: GameManager;\n    game: G\n  };\n\n  currentPosition: number = 1;\n\n  players: TestRunnerPlayer<G>[]\n\n  constructor(private setup: SetupFunction, mocks?: (game: G) => void) {\n    if (mocks) {\n      this.setup = (state: SetupState | GameState, options?: {\n        rseed?: string;\n        trackMovement?: boolean;\n      }) => setup(state, {...options, mocks});\n    }\n    const iface = createInterface(this.setup)\n\n    this.server = {\n      interface: iface,\n    } as typeof this['server'];\n\n    globalThis.window = {\n      setTimeout,\n      clearTimeout,\n      top: {\n        postMessage: ({ data }: { data: any }) => {\n          if (this.server.state!.game.phase === 'finished') throw Error(`Game already finished. Cannot process move ${data.move}`);\n          this.server.state = this.server.interface.processMove(\n            this.server.state!.game,\n            {\n              position: this.currentPosition,\n              data\n            }\n          );\n          this.getCurrentGame();\n        }\n      }\n    } as unknown as typeof globalThis.window;\n  }\n\n  start({players, settings}: {\n    players: number,\n    settings: Record<string, any>\n  }): TestRunnerPlayer<G>[] {\n    const playerAttrs = times(players, p => ({\n      id: String(p),\n      name: String(p),\n      position: p,\n      host: p === 1,\n      color: '',\n      avatar: ''\n    }));\n\n    this.server.state = this.server.interface.initialState({\n      players: playerAttrs,\n      settings,\n      randomSeed: 'test-rseed'\n    });\n\n    this.getCurrentGame();\n    this.players = playerAttrs.map((p, i) => {\n      const store = createGameStore()\n      const {setSetup, gameManager} = store.getState();\n      setSetup(this.setup);\n      return new TestRunnerPlayer(this, i + 1, store, p as unknown as PlayerAttributes, gameManager.game as G)\n    });\n    this.updatePlayersFromState(); // initial\n    return this.players\n  }\n\n  getCurrentGame() {\n    this.server.gameManager = globalThis.window.serverGameManager as GameManager;\n    this.server.game = this.server.gameManager.game as G;\n  }\n\n  updatePlayers() {\n    this.server.state = this.server.gameManager.getUpdate();\n    this.updatePlayersFromState();\n  }\n\n  updatePlayersFromState() {\n    for (const player of this.players) {\n      const { updateState } = player.store.getState();\n      const state = this.server.state!.players.find(state => state.position === player.position)!;\n      const playerState = (state.state instanceof Array) ? state.state[state.state.length - 1] : state.state;\n\n      if (this.server.state!.game.phase === 'started') {\n        updateState({\n          type: 'gameUpdate',\n          state: playerState,\n          position: state.position,\n          currentPlayers: this.server.state!.game.currentPlayers\n        });\n      }\n      if (this.server.state!.game.phase === 'finished') {\n        updateState({\n          type: 'gameFinished',\n          state: playerState,\n          position: state.position,\n          winners: this.server.gameManager.winner.map(p => p.position),\n        });\n      }\n      const { gameManager } = player.store.getState();\n      player.game = gameManager.game as G;\n      player.player = gameManager.players.atPosition(player.position)!;\n    }\n  }\n}\n"
  },
  {
    "path": "src/ui/Main.tsx",
    "content": "import React, { useState, useEffect, useCallback, useMemo } from 'react';\nimport { gameStore } from './store.js';\nimport Game from './game/Game.js';\nimport Setup from './setup/Setup.js';\nimport Queue from './queue.js';\n\nimport type { GameState } from '../interface.js';\nimport type { SetupComponentProps } from './setup/components/settingComponents.js';\n\nexport type User = {\n  id: string;\n  name: string;\n  avatar: string;\n  playerDetails?: {\n    color: string;\n    position: number;\n    ready: boolean;\n    settings?: any;\n    sessionURL?: string;\n  };\n};\n\ntype UsersEvent = {\n  type: \"users\";\n  users: User[];\n};\n\ntype UserOnlineEvent = {\n  type: \"userOnline\";\n  id: string;\n  online: boolean;\n};\n\nexport type GameSettings = Record<string, any>\n\n// an update to the setup state\nexport type SettingsUpdateEvent = {\n  type: \"settingsUpdate\";\n  settings: GameSettings;\n  seatCount: number;\n}\n\nexport type GameUpdateEvent = {\n  type: \"gameUpdate\";\n  state: GameState | GameState[];\n  position: number;\n  currentPlayers: number[];\n}\n\nexport type GameFinishedEvent = {\n  type: \"gameFinished\";\n  state: GameState | GameState[];\n  position: number;\n  winners: number[];\n}\n\n// indicates the disposition of a message that was processed\nexport type MessageProcessedEvent = {\n  type: \"messageProcessed\";\n  id: string;\n  error?: string;\n}\n\nexport type SeatOperation = {\n  type: 'seat';\n  position: number;\n  userID: string;\n  color: string;\n  name: string;\n  settings?: any;\n}\n\nexport type UnseatOperation = {\n  type: 'unseat';\n  userID: string;\n}\n\nexport type UpdateOperation = {\n  type: 'update';\n  userID: string;\n  color?: string;\n  name?: string;\n  ready?: boolean;\n  settings?: any;\n}\n\ntype PlayerOperation = SeatOperation | UnseatOperation | UpdateOperation\n\nexport type UpdatePlayersMessage = {\n  type: \"updatePlayers\";\n  id: string;\n  operations: PlayerOperation[];\n}\n\nexport type UpdateSettingsMessage = {\n  type: \"updateSettings\";\n  id: string;\n  settings: GameSettings;\n  seatCount: number\n}\n\n// used to actually start the game\nexport type StartMessage = {\n  id: string;\n  type: 'start';\n}\n\n// used to tell the top that you're ready to recv events\nexport type ReadyMessage = {\n  type: 'ready';\n}\n\nexport type SwitchPlayerMessage = {\n  type: \"switchPlayer\";\n  index: number;\n}\n\nexport default ({ minPlayers, maxPlayers, defaultPlayers, setupComponents }: {\n  minPlayers: number,\n  maxPlayers: number,\n  defaultPlayers: number,\n  setupComponents: Record<string, (p: SetupComponentProps) => JSX.Element>\n}) => {\n  const [gameManager, updateState, setUserOnline, announcementIndex] = gameStore(s => [s.gameManager, s.updateState, s.setUserOnline, s.announcementIndex]);\n  const [settings, setSettings] = useState<GameSettings>();\n  const [seatCount, setSeatCount] = useState(defaultPlayers);\n  const [users, setUsers] = useState<User[]>([]);\n  const [readySent, setReadySent] = useState<boolean>(false);\n  const players = useMemo(() => users.filter(u => !!u.playerDetails), [users]);\n\n  const moveCallbacks = useMemo<((e: string) => void)[]>(() => [], []);\n\n  const catchError = useCallback((error: string) => {\n    if (!error) return\n    console.error(error);\n  }, []);\n\n  const queue = useMemo(() => new Queue(1) /* speed */, []);\n\n  useEffect(() => {\n    if (gameManager.announcements[announcementIndex]) {\n      queue.pause();\n    } else if (queue.paused) {\n      setTimeout(() => queue.resume(), 500);\n    }\n  }, [queue, gameManager, announcementIndex])\n\n  const listener = useCallback((event: MessageEvent<\n    UsersEvent |\n    UserOnlineEvent |\n    SettingsUpdateEvent |\n    GameUpdateEvent |\n    GameFinishedEvent |\n    MessageProcessedEvent\n  >) => {\n    const data = event.data;\n    switch(data.type) {\n    case 'settingsUpdate':\n      setSettings(data.settings);\n      setSeatCount(data.seatCount);\n      break;\n    case 'users':\n      setUsers(data.users);\n      break;\n    case 'userOnline':\n      setUserOnline(data.id, data.online)\n      break;\n    case 'gameUpdate':\n    case 'gameFinished':\n      {\n        if (data.state instanceof Array) {\n          const states = data.state;\n          let delay = data.state[0].sequence === gameManager.sequence + 1;\n\n          for (let i = 0; i !== states.length; i++) {\n            const state = states[i];\n            queue.schedule(() => updateState({...data, state}, i !== states.length - 1), delay);\n            delay = true;\n          }\n        } else {\n          let delay = data.state.sequence === gameManager.sequence + 1;\n          queue.schedule(() => updateState(data as typeof data & {state: typeof data.state}), delay); // TS needs help here...\n        }\n      }\n      break;\n    case 'messageProcessed':\n      if (data.error) {\n        catchError(data.error);\n        const move = moveCallbacks[parseInt(data.id)];\n        if (move) move(data.error);\n      }\n      delete moveCallbacks[parseInt(data.id)];\n      break;\n    }\n  }, [setUserOnline, moveCallbacks, gameManager, queue, updateState, catchError]);\n\n  useEffect(() => {\n    window.addEventListener('message', listener, false)\n    const message: ReadyMessage = {type: \"ready\"};\n    if (!readySent) {\n      window.top!.postMessage(message, \"*\");\n      setReadySent(true);\n    }\n    return () => window.removeEventListener('message', listener)\n  }, [readySent, listener]);\n\n  const updateSettings = useCallback((update: {settings?: GameSettings, seatCount?: number}) => {\n    if (update.settings) setSettings(update.settings);\n    if (update.seatCount) setSeatCount(update.seatCount);\n    const message: UpdateSettingsMessage = {\n      type: \"updateSettings\",\n      id: 'settings',\n      settings: update.settings ?? settings ?? {},\n      seatCount: update.seatCount ?? seatCount\n    };\n    window.top!.postMessage(message, \"*\");\n  }, [seatCount, settings]);\n\n  const updatePlayers = useCallback((operations: UpdatePlayersMessage['operations']) => {\n    const message: UpdatePlayersMessage = {\n      type: 'updatePlayers',\n      id: 'updatePlayers',\n      operations\n    }\n    window.top!.postMessage(message, \"*\");\n  }, [])\n\n  return (\n    <>\n      {gameManager.phase === 'new' && settings &&\n        <Setup\n          users={users}\n          minPlayers={minPlayers}\n          maxPlayers={maxPlayers}\n          setupComponents={setupComponents}\n          players={players}\n          settings={settings}\n          seatCount={seatCount}\n          onUpdatePlayers={updatePlayers}\n          onUpdateSettings={updateSettings}\n        />\n      }\n      {(gameManager.phase === 'started' || gameManager.phase === 'finished') && <Game/>}\n    </>\n  );\n}\n"
  },
  {
    "path": "src/ui/assets/click.ogg.ts",
    "content": "export default \"data:application/ogg;base64,T2dnUwACAAAAAAAAAAAISQAAAAAAAFRKKQUBHgF2b3JiaXMAAAAAAUSsAAAAAAAAAHcBAAAAAAC4AU9nZ1MAAAAAAAAAAAAACEkAAAEAAAB6l/yzEJf//////////////////8kDdm9yYmlzKwAAAFhpcGguT3JnIGxpYlZvcmJpcyBJIDIwMTIwMjAzIChPbW5pcHJlc2VudCkCAAAADQAAAEFSVElTVD1LZW5uZXlHAAAAQ09NTUVOVFM9U291bmQgZ2VuZXJhdGVkIGJ5IEdhbWVTeW50aCBmcm9tIFRzdWdpICh3d3cudHN1Z2ktc3R1ZGlvLmNvbSkBBXZvcmJpcylCQ1YBAAgAAAAxTCDFgNCQVQAAEAAAYCQpDpNmSSmllKEoeZiUSEkppZTFMImYlInFGGOMMcYYY4wxxhhjjCA0ZBUAAAQAgCgJjqPmSWrOOWcYJ45yoDlpTjinIAeKUeA5CcL1JmNuprSma27OKSUIDVkFAAACAEBIIYUUUkghhRRiiCGGGGKIIYcccsghp5xyCiqooIIKMsggg0wy6aSTTjrpqKOOOuootNBCCy200kpMMdVWY669Bl18c84555xzzjnnnHPOCUJDVgEAIAAABEIGGWQQQgghhRRSiCmmmHIKMsiA0JBVAAAgAIAAAAAAR5EUSbEUy7EczdEkT/IsURM10TNFU1RNVVVVVXVdV3Zl13Z113Z9WZiFW7h9WbiFW9iFXfeFYRiGYRiGYRiGYfh93/d93/d9IDRkFQAgAQCgIzmW4ymiIhqi4jmiA4SGrAIAZAAABAAgCZIiKZKjSaZmaq5pm7Zoq7Zty7Isy7IMhIasAgAAAQAEAAAAAACgaZqmaZqmaZqmaZqmaZqmaZqmaZpmWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWUBoyCoAQAIAQMdxHMdxJEVSJMdyLAcIDVkFAMgAAAgAQFIsxXI0R3M0x3M8x3M8R3REyZRMzfRMDwgNWQUAAAIACAAAAAAAQDEcxXEcydEkT1It03I1V3M913NN13VdV1VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWB0JBVAAAEAAAhnWaWaoAIM5BhIDRkFQCAAAAAGKEIQwwIDVkFAAAEAACIoeQgmtCa8805DprloKkUm9PBiVSbJ7mpmJtzzjnnnGzOGeOcc84pypnFoJnQmnPOSQyapaCZ0JpzznkSmwetqdKac84Z55wOxhlhnHPOadKaB6nZWJtzzlnQmuaouRSbc86JlJsntblUm3POOeecc84555xzzqlenM7BOeGcc86J2ptruQldnHPO+WSc7s0J4ZxzzjnnnHPOOeecc84JQkNWAQBAAAAEYdgYxp2CIH2OBmIUIaYhkx50jw6ToDHIKaQejY5GSqmDUFIZJ6V0gtCQVQAAIAAAhBBSSCGFFFJIIYUUUkghhhhiiCGnnHIKKqikkooqyiizzDLLLLPMMsusw84667DDEEMMMbTSSiw11VZjjbXmnnOuOUhrpbXWWiullFJKKaUgNGQVAAACAEAgZJBBBhmFFFJIIYaYcsopp6CCCggNWQUAAAIACAAAAPAkzxEd0REd0REd0REd0REdz/EcURIlURIl0TItUzM9VVRVV3ZtWZd127eFXdh139d939eNXxeGZVmWZVmWZVmWZVmWZVmWZQlCQ1YBACAAAABCCCGEFFJIIYWUYowxx5yDTkIJgdCQVQAAIACAAAAAAEdxFMeRHMmRJEuyJE3SLM3yNE/zNNETRVE0TVMVXdEVddMWZVM2XdM1ZdNVZdV2Zdm2ZVu3fVm2fd/3fd/3fd/3fd/3fd/XdSA0ZBUAIAEAoCM5kiIpkiI5juNIkgSEhqwCAGQAAAQAoCiO4jiOI0mSJFmSJnmWZ4maqZme6amiCoSGrAIAAAEABAAAAAAAoGiKp5iKp4iK54iOKImWaYmaqrmibMqu67qu67qu67qu67qu67qu67qu67qu67qu67qu67qu67qu67pAaMgqAEACAEBHciRHciRFUiRFciQHCA1ZBQDIAAAIAMAxHENSJMeyLE3zNE/zNNETPdEzPVV0RRcIDVkFAAACAAgAAAAAAMCQDEuxHM3RJFFSLdVSNdVSLVVUPVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVdU0TdM0gdCQlQAAGQAAI0EGGYQQinKQQm49WAgx5iQFoTkGocQYhKcQMww5DSJ0kEEnPbiSOcMM8+BSKBVETIONJTeOIA3CplxJ5TgIQkNWBABRAACAMcgxxBhyzknJoETOMQmdlMg5J6WT0kkpLZYYMyklphJj45yj0knJpJQYS4qdpBJjia0AAIAABwCAAAuh0JAVAUAUAABiDFIKKYWUUs4p5pBSyjHlHFJKOaecU845CB2EyjEGnYMQKaUcU84pxxyEzEHlnIPQQSgAACDAAQAgwEIoNGRFABAnAOBwJM+TNEsUJUsTRc8UZdcTTdeVNM00NVFUVcsTVdVUVdsWTVW2JU0TTU30VFUTRVUVVdOWTVW1bc80ZdlUVd0WVdW2ZdsWfleWdd8zTVkWVdXWTVW1ddeWfV/WbV2YNM00NVFUVU0UVdVUVds2Vde2NVF0VVFVZVlUVVl2ZVn3VVfWfUsUVdVTTdkVVVW2Vdn1bVWWfeF0VV1XZdn3VVkWflvXheH2feEYVdXWTdfVdVWWfWHWZWG3dd8oaZppaqKoqpooqqqpqrZtqq6tW6LoqqKqyrJnqq6syrKvq65s65ooqq6oqrIsqqosq7Ks+6os67aoqrqtyrKwm66r67bvC8Ms67pwqq6uq7Ls+6os67qt68Zx67owfKYpy6ar6rqpurpu67pxzLZtHKOq6r4qy8KwyrLv67ovtHUhUVV13ZRd41dlWfdtX3eeW/eFsm07v637ynHrutL4Oc9vHLm2bRyzbhu/rfvG8ys/YTiOpWeatm2qqq2bqqvrsm4rw6zrQlFVfV2VZd83XVkXbt83jlvXjaKq6roqy76wyrIx3MZvHLswHF3bNo5b152yrQt9Y8j3Cc9r28Zx+zrj9nWjrwwJx48AAIABBwCAABPKQKEhKwKAOAEABiHnFFMQKsUgdBBS6iCkVDEGIXNOSsUclFBKaiGU1CrGIFSOScickxJKaCmU0lIHoaVQSmuhlNZSa7Gm1GLtIKQWSmktlNJaaqnG1FqMEWMQMuekZM5JCaW0FkppLXNOSuegpA5CSqWkFEtKLVbMScmgo9JBSKmkElNJqbVQSmulpBZLSjG2FFtuMdYcSmktpBJbSSnGFFNtLcaaI8YgZM5JyZyTEkppLZTSWuWYlA5CSpmDkkpKrZWSUsyck9JBSKmDjkpJKbaSSkyhlNZKSrGFUlpsMdacUmw1lNJaSSnGkkpsLcZaW0y1dRBaC6W0FkpprbVWa2qtxlBKayWlGEtKsbUWa24x5hpKaa2kEltJqcUWW44txppTazWm1mpuMeYaW2091ppzSq3W1FKNLcaaY2291Zp77yCkFkppLZTSYmotxtZiraGU1koqsZWSWmwx5tpajDmU0mJJqcWSUowtxppbbLmmlmpsMeaaUou15tpzbDX21FqsLcaaU0u11lpzj7n1VgAAwIADAECACWWg0JCVAEAUAABBiFLOSWkQcsw5KglCzDknqXJMQikpVcxBCCW1zjkpKcXWOQglpRZLKi3FVmspKbUWay0AAKDAAQAgwAZNicUBCg1ZCQBEAQAgxiDEGIQGGaUYg9AYpBRjECKlGHNOSqUUY85JyRhzDkIqGWPOQSgphFBKKimFEEpJJaUCAAAKHAAAAmzQlFgcoNCQFQFAFAAAYAxiDDGGIHRUMioRhExKJ6mBEFoLrXXWUmulxcxaaq202EAIrYXWMkslxtRaZq3EmForAADswAEA7MBCKDRkJQCQBwBAGKMUY845ZxBizDnoHDQIMeYchA4qxpyDDkIIFWPOQQghhMw5CCGEEELmHIQQQgihgxBCCKWU0kEIIYRSSukghBBCKaV0EEIIoZRSCgAAKnAAAAiwUWRzgpGgQkNWAgB5AACAMUo5B6GURinGIJSSUqMUYxBKSalyDEIpKcVWOQehlJRa7CCU0lpsNXYQSmktxlpDSq3FWGuuIaXWYqw119RajLXmmmtKLcZaa825AADcBQcAsAMbRTYnGAkqNGQlAJAHAIAgpBRjjDGGFGKKMeecQwgpxZhzzimmGHPOOeeUYow555xzjDHnnHPOOcaYc8455xxzzjnnnHOOOeecc84555xzzjnnnHPOOeecc84JAAAqcAAACLBRZHOCkaBCQ1YCAKkAAAARVmKMMcYYGwgxxhhjjDFGEmKMMcYYY2wxxhhjjDHGmGKMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhba6211lprrbXWWmuttdZaa60AQL8KBwD/BxtWRzgpGgssNGQlABAOAAAYw5hzjjkGHYSGKeikhA5CCKFDSjkoJYRQSikpc05KSqWklFpKmXNSUiolpZZS6iCk1FpKLbXWWgclpdZSaq211joIpbTUWmuttdhBSCml1lqLLcZQSkqttdhijDWGUlJqrcXYYqwxpNJSbC3GGGOsoZTWWmsxxhhrLSm11mKMtcZaa0mptdZiizXWWgsA4G5wAIBIsHGGlaSzwtHgQkNWAgAhAQAEQow555xzEEIIIVKKMeeggxBCCCFESjHmHHQQQgghhIwx56CDEEIIIYSQMeYcdBBCCCGEEDrnHIQQQgihhFJK5xx0EEIIIZRQQukghBBCCKGEUkopHYQQQiihhFJKKSWEEEIJpZRSSimlhBBCCKGEEkoppZQQQgillFJKKaWUEkIIIZRSSimllFJCCKGUUEoppZRSSgghhFJKKaWUUkoJIYRQSimllFJKKSGEEkoppZRSSimlAACAAwcAgAAj6CSjyiJsNOHCA1BoyEoAgAwAAHHYausp1sggxZyElkuEkHIQYi4RUoo5R7FlSBnFGNWUMaUUU1Jr6JxijFFPnWNKMcOslFZKKJGC0nKstXbMAQAAIAgAMBAhM4FAARQYyACAA4QEKQCgsMDQMVwEBOQSMgoMCseEc9JpAwAQhMgMkYhYDBITqoGiYjoAWFxgyAeADI2NtIsL6DLABV3cdSCEIAQhiMUBFJCAgxNueOINT7jBCTpFpQ4CAAAAAAABAB4AAJINICIimjmODo8PkBCREZISkxOUAAAAAADgAYAPAIAkBYiIiGaOo8PjAyREZISkxOQEJQAAAAAAAAAAAAgICAAAAAAABAAAAAgIT2dnUwAEugEAAAAAAAAISQAAAgAAAK53kAkFOjM2Ndekhj2CvV1AgdsXUTYG69yxV3eJobEdXDTI8dnZ3SP6997W4dSa/TeKs53YVbJ930+NR/+/s2A0tuzedIJFCAQA8GsAsuS0NxU/atI8IutdgXAdXR6YwtyfXhEy7aotcXaVVhWsSOw05XELa/MD/EV1CPtQfRTYY70TAFTK3kVzbq8Xs+PBnL5ZdcqW7vrROclWCt72skTeInGBuv/pv48IlEzGhP08EEgggOmTDKDSG17CqLmM6nbBMrTtceV6p3E6A/ynVRMF3DtXkp7VskprO7Pcta+RNgG6ZbwkIeG2T1xaQc7H2eY2buM2buM2buMQAVUVY4gQCJlwBYDVpz5/6cqVK5uy4tOH73/9/3+vvHLp0qVLly5d2jQ/P//3//7f//t//+///UUpFEue7dlLKYHl13//75/oIhQffPZnr0BJSUlJScmzP/uzP3tJSUkJhmnxr3//7//9hRcBilMMPLsxPPjsz/7sdV5CwXp+fn5+fn7+69//+39/cXFx8brXBaampqampqamjgNAmZqampqampqaYtzPz3/3rRYXEeQlU1N+AABQpqampqaqAA==\";\n"
  },
  {
    "path": "src/ui/assets/index.scss",
    "content": "@keyframes fade-in-prompt {\n  0% { opacity: 0; filter: blur(2em); transform: translate(-40vw, 0) }\n  50% { opacity: 0; filter: blur(2em); transform: translate(-20vw, 0) }\n  100% { opacity: 1; filter: none; transform: none }\n}\n\n@keyframes fade-out-prompt {\n  0% { opacity: 1; filter: none; }\n  100% { opacity: 0; filter: blur(10em); }\n}\n\n@keyframes pulse-player-name {\n  0% { opacity: 1; filter: drop-shadow(0 0 .4em #fff) }\n  40% { opacity: 1; filter: drop-shadow(0 0 .4em #fff) }\n  90% { opacity: .7; filter: drop-shadow(0 0 0 #fff) }\n}\n\n@keyframes pulse-ready {\n  0% { transform: scale(1) }\n  80% { transform: scale(1.2); filter: drop-shadow(0 0 .1em #fff) }\n  100% { transform: scale(1) }\n}\n\nhtml, body { height: 100% }\n\n@layer game {\n\n  /* z layers */\n  /* 0: base elements */\n  /* 100: animations */\n  /* 150: player messages */\n  /* 200: system messages */\n\n  html.dark {\n    body {\n      color: #ccd;\n    }\n    #background {\n      filter: brightness(0.45) contrast(1.2);\n    }\n  }\n\n  body {\n    color: #002;\n    margin: 0;\n    padding: 0;\n    overflow: hidden;\n    font-family: 'DM Sans Variable', sans-serif;\n    > #root {\n      position: absolute;\n      width: 100vw;\n      height: 100vh;\n      overflow: auto;\n      &.orientation-flipped {\n        transform: rotate(90deg);\n        width: 100vh;\n        height: 100vw;\n        transform-origin: left bottom;\n        left: 0;\n        bottom: 100%;\n      }\n    }\n  }\n\n  .full-page-cover {\n    width: 100vw;\n    height: 100vh;\n    z-index: 200;\n    #root.orientation-flipped & {\n      width: 100vh;\n      height: 100vw;\n    }\n    #root.orientation-flipped #game.scaling-scroll & {\n      position: absolute;\n      width: 100%;\n      height: 100%;\n    }\n    position: fixed;\n    left: 0;\n    top: 0;\n  }\n\n  #background {\n    background-image: url(./grain.jpg);\n    background-size: cover;\n    filter: brightness(1.3) contrast(0.7);\n    z-index: -10;\n  }\n\n  #game {\n    position: absolute;\n    --aspect-ratio: 1;\n    &:not(.scaling-scroll) {\n      top: calc(50vh - .5 * min(100vw / var(--aspect-ratio), 100vh));\n      left: calc(50vw - .5 * min(100vw, 100vh * var(--aspect-ratio)));\n      width: min(100vw, 100vh * var(--aspect-ratio));\n      height: min(100vw / var(--aspect-ratio), 100vh);\n      #root.orientation-flipped & {\n        top: calc(50vw - .5 * min(100vh / var(--aspect-ratio), 100vw));\n        left: calc(50vh - .5 * min(100vh, 100vw * var(--aspect-ratio)));\n        width: min(100vh, 100vw * var(--aspect-ratio));\n        height: min(100vh / var(--aspect-ratio), 100vw);\n      }\n    }\n    &.scaling-scroll {\n      top: 0;\n      left: 0;\n      width: max(100vw, 100vh * var(--aspect-ratio));\n      height: max(100vw / var(--aspect-ratio), 100vh);\n      #root.orientation-flipped & {\n        width: max(100vh, 100vw * var(--aspect-ratio));\n        height: max(100vh / var(--aspect-ratio), 100vw);\n      }\n    }\n    user-select: none;\n    -webkit-user-select: none;\n    -moz-user-select: none;\n\n    #play-area {\n      position: relative;\n      &.in-drag-movement {\n        .transform-wrapper {\n          transition: none;\n        }\n      }\n    }\n\n    * {\n      box-sizing: border-box;\n    }\n\n    img {\n      -webkit-user-drag: none;\n      pointer-events: none;\n    }\n\n    .Space {\n      > * {\n        visibility: visible;\n        &.bz-default {\n          width: 100%;\n          height: 100%;\n          background: #ccc;\n          html.dark & {\n            background: #333;\n          }\n        }\n      }\n    }\n\n    .Piece {\n      visibility: visible;\n      > * {\n        width: 100%;\n        height: 100%;\n        &.bz-default {\n          background: #ccf;\n          border: .1em solid white;\n          padding: .1em;\n          overflow: hidden;\n        }\n      }\n    }\n\n    .info-hotspot {\n      position: absolute;\n      width: 100%;\n      height: 100%;\n      cursor: help;\n      visibility: visible;\n      z-index: 200;\n      filter: none;\n    }\n\n    .droppable {\n      visibility: visible;\n      > .bz-default {\n        border: .1em solid red;\n      }\n    }\n\n    .transform-wrapper {\n      position: absolute;\n      transform-origin: center;\n      transition: transform .6s, top .6s, left .6s, width .6s, height .6s;\n      visibility: hidden;\n      &.has-info {\n        z-index: 200;\n        > *:not(.info-hotspot) {\n          pointer-events: none;\n        }\n      }\n\n      > div {\n        position: absolute;\n        width: 100%;\n        height: 100%;\n      }\n\n      &.animating {\n        &.cross-parent {\n          z-index: 100;\n        }\n        pointer-events: none;\n      }\n\n      &.dragging {\n        z-index: 100;\n        pointer-events: none;\n        filter: drop-shadow(.2em .2em .2em #0008) drop-shadow(.5em .5em .5em #0008);\n      }\n\n      &.placing {\n        z-index: 100;\n        filter: drop-shadow(0 0 .2em #0008) drop-shadow(0 0  .5em #0008) opacity(.75);\n        cursor: pointer;\n        &:not(.animating) {\n          transition: transform .2s, top .2s, left .2s, width .2s, height .2s;\n        }\n      }\n\n      .rotator {\n        position: absolute;\n        z-index: 200;\n        transition: transform .2s, top .2s, left .2s, width .2s, height .2s;\n        transform-origin: center;\n        > div {\n          position: absolute;\n          width: 1em;\n          height: 1em;\n          top: .2em;\n          visibility: visible;\n          &.left {\n            left: .2em;\n            cursor: sw-resize;\n          }\n          &.right {\n            right: .2em;\n            cursor: se-resize;\n          }\n          path {\n            fill: white;\n            fill-opacity: 1;\n            stroke: black;\n            stroke-width: 50;\n            stroke-linecap: round;\n            stroke-linejoin: round;\n            paint-order: stroke markers fill;\n          }\n          &:hover path {\n            fill: red;\n          }\n        }\n      }\n    }\n\n    .layout-wrapper {\n      visibility: hidden;\n      width: 100%;\n      height: 100%;\n      left: 0;\n      top: 0;\n      position: absolute;\n    }\n\n    .clickable {\n      cursor: pointer;\n    }\n\n    .selectable {\n      > .bz-default {\n        border: .1em solid yellow;\n        &:hover {\n          border: .1em solid red;\n        }\n      }\n    }\n\n    .invalid {\n      > .bz-default {\n        background: #fcc;\n      }\n    }\n\n    .Piece.selected {\n      > .bz-default {\n        transform: scale(1.2);\n      }\n    }\n\n    .Space.selected {\n      > .bz-default {\n        border: .1em solid red;\n      }\n    }\n\n    .bz-show-grid {\n      position: absolute;\n      border: 1px solid #99f;\n      outline: 1px dashed white;\n      outline-offset: -1px;\n      pointer-events: none;\n      > span {\n        position: absolute;\n        font-size: .5rem;\n        background: white;\n        color: black;\n        padding: 2px;\n        top: 0;\n        left: 0;\n      }\n    }\n\n    .drawer {\n      visibility: hidden;\n      position: absolute;\n      > .drawer-tab {\n        position: absolute;\n        visibility: visible;\n        font-size: .5rem;\n        text-align: center;\n        transition: height .2s, width .2s, left .2s, top .2s, bottom .2s, right .2s;\n        background: #0008;\n        color: white;\n        cursor: pointer;\n        height: .75rem;\n        border-radius: .75em .75em 0 0;\n        &.multi {\n          display: flex;\n          flex-wrap: nowrap;\n        }\n        .tabs-tab {\n          position: relative;\n          display: inline-block;\n          padding: 0 .5em;\n          flex: 1 1 auto;\n          overflow: hidden;\n          background: #0004;\n          &.active, &:hover {\n            background: #fff4;\n          }\n          &:first-child {\n            border-radius: .75em 0 0 0;\n          }\n          &:last-child {\n            border-radius: 0 .75em 0 0;\n          }\n        }\n      }\n\n      &.closed > .drawer-tab:hover {\n        height: .85rem;\n      }\n\n      &.open-direction-down > .drawer-tab {\n        border-radius: 0 0 .75em .75em;\n        .tabs-tab {\n          &:first-child {\n            border-radius: 0 0 0 .75em;\n          }\n          &:last-child {\n            border-radius: 0 0 .75em 0;\n          }\n        }\n      }\n\n      > .drawer-content {\n        position: absolute;\n        inset: 0;\n        visibility: visible;\n        border: .1rem solid #0008;\n        background: #fffc;\n        transition: transform .2s;\n        > .drawer-container {\n          position: absolute;\n          visibility: hidden;\n          width: 100%;\n          height: 100%;\n          > * {\n            visibility: visible;\n          }\n        }\n      }\n    }\n\n    .popout-container {\n      position: absolute;\n      .popout-button {\n        position: absolute;\n        inset: 0;\n        background: #0008;\n        &:hover {\n          background: #0004;\n        }\n        color: white;\n        cursor: pointer;\n        border-radius: .75em;\n        text-align: center;\n      }\n      .full-page-cover {\n        background: #444c;\n      }\n      .popout-close {\n        position: absolute;\n        top: .5vh;\n        right: .5vh;\n        height: 5vh;\n        width: 5vh;\n        fill: none;\n        stroke: #666;\n        stroke-width: .15vh;\n        stroke-linecap: round;\n        cursor: pointer;\n        &:hover {\n          stroke: black;\n        }\n      }\n      .popout-modal {\n        position: absolute;\n        background: white;\n        border: .1rem solid black;\n      }\n    }\n\n    .player-controls {\n      z-index: 150;\n      position: absolute;\n      padding: .25rem;\n      font-size: .75rem;\n      background: #fffc;\n      html.dark & {\n        background: #000c;\n      }\n\n      &.fade-out {\n        animation: fade-out-prompt .5s forwards;\n      }\n      &:not(.fade-out) {\n        animation: fade-in-prompt .4s;\n      }\n      form {\n        margin: 0;\n      }\n      input {\n        border-width: .05rem;\n      }\n      input, select, button {\n        padding: 0.2rem 0.4rem;\n        font-family: inherit;\n        font-size: inherit;\n        margin: 0.1rem;\n      }\n      input, select {\n        width: 100%;\n      }\n      input[type=number] {\n        width: 4em;\n      }\n      .error {\n        color: #c00;\n      }\n      button {\n        border: none;\n        background: #ccc;\n        cursor: pointer;\n        transition: transform 0.2s;\n        white-space: normal;\n        &:hover {\n          transform: scale(1.1);\n          box-shadow: 0.2rem 0.2rem .5rem #0008;\n        }\n        &.selected {\n          filter: brightness(1.3);\n        }\n        &.invalid {\n          color: #555;\n          background: #999;\n        }\n      }\n      input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button {\n        opacity: 1;\n      }\n\n      .action-divider {\n        border: 0;\n        font-size: 80%;\n        position: relative;\n        text-align: center;\n        line-height: .75em;\n        &::before {\n          content: \"\";\n          background: #888c;\n          position: absolute;\n          left: 0;\n          top: 50%;\n          width: calc(50% - .6rem);\n          height: .05rem;\n        }\n        &::after {\n          content: \"\";\n          background: #888c;\n          position: absolute;\n          right: 0;\n          top: 50%;\n          width: calc(50% - .6rem);\n          height: .05rem;\n        }\n      }\n    }\n\n    .god-mode-enabled {\n      position: absolute;\n      top: 0;\n      left: 0;\n      font-size: .5rem;\n      padding: 0.2rem;\n      background: red;\n      color: white;\n      z-index: 200;\n    }\n\n    &.mobile {\n      .player-controls {\n        font-size: 1.5rem;\n        padding: .5rem;\n      }\n\n      .drawer .drawer-tab {\n        height: 1.35rem !important;\n        font-size: 1rem;\n      }\n    }\n  }\n\n  #setup {\n    padding: 1rem;\n    max-width: 800px;\n    margin: 0 auto 5rem;\n    .heading {\n      h1, h2, h3 {\n        text-align: center;\n        margin: .3em 0 .5em;\n      }\n      p {\n        text-align: center;\n      }\n      html.dark & {\n        background: #fff3;\n      }\n      font-size: 1.2em;\n      background: #fff8;\n      padding: 0.3rem 1.5rem;\n      border-radius: 1rem;\n      margin-bottom: 1rem;\n    }\n    #seating {\n      margin: .2em;\n      text-align: center;\n      display: flex;\n      flex-direction: row;\n      margin-bottom: 1em;\n\n      #seats {\n        flex: 1;\n\n        .seat {\n          position: relative;\n          select {\n            appearance: none;\n            font-family: 'DM Sans Variable';\n            text-align-last: center;\n            text-align: center;\n            font-size: 1.5em;\n            height: 2.75em;\n            border-radius: 20em;\n            border-width: 0;\n            padding: 0.5em 3em;\n            width: 100%;\n            color: white;\n            cursor: pointer;\n            margin: 0.2em 0;\n            box-shadow: inset .1em .1em 0 #fff4, inset -.1em -.1em 0 #0008;\n            filter: drop-shadow(.1em .1em .2em #0008);\n\n            &:focus {\n              outline: none;\n            }\n\n            &:disabled {\n              opacity: unset;\n            }\n\n            html.dark & {\n              background: #444;\n            }\n          }\n\n          img.avatar {\n            position: absolute;\n            left: 0.5em;\n            top: 0.75em;\n            height: 3.3em;\n            border-radius: 50%;\n          }\n\n          .invite-link {\n            position: absolute;\n            left: 0;\n            top: 3.75em;\n            width: 100%;\n            color: white;\n            font-size: 75%;\n            cursor: pointer;\n            transition: transform .2s;\n            &:hover {\n              transform: scale(1.2);\n            }\n          }\n\n          .rename, .palette, .ready {\n            position: absolute;\n            font-size: 2em;\n            transition: transform .2s;\n          }\n          .rename, .palette {\n            &:hover {\n              cursor: pointer;\n              transform: scale(1.4);\n            }\n          }\n          .ready {\n            left: 1.2em;\n            top: .8em;\n          }\n          .rename {\n            right: .65em;\n            top: .45em;\n          }\n          .palette {\n            right: 1.6em;\n            top: .40em;\n          }\n          .ready {\n            animation: pulse-ready .4s;\n          }\n\n          .github-picker {\n            padding: 1em;\n            position: absolute !important;\n            z-index: 1;\n            text-align: left;\n            left: 75%;\n            width: 142px !important;\n            display: block !important;\n            > span {\n              margin: .1em;\n              display: inline-block;\n            }\n          }\n        }\n\n        svg.addSeat, svg.removeSeat {\n          height: 2.5em;\n          margin: .2em 1em;\n          cursor: pointer;\n          transition: transform .2s;\n          &:hover {\n            transform: scale(1.2);\n          }\n        }\n      }\n\n      #lobby {\n        flex: 1;\n        display: flex;\n        flex-direction: column;\n        margin-left: 1em;\n        background: #666;\n        border-radius: 0.5em;\n        padding: 0.5em;\n        color: white;\n        font-weight: bold;\n        font-size: 1.2em;\n\n        #users {\n          flex: 1;\n          margin: .5em 0 0;\n          background: #fff4;\n          border-radius: 0 0 .2em .2em;\n          padding: .2em;\n          text-align: left;\n          min-height: 50px;\n          font-weight: normal;\n          .user {\n            display: inline-block;\n            margin: .2em;\n            position: relative;\n            background: #666;\n            border-radius: 10em;\n            padding: 0.4em 0.8em 0.4em 2.4em;\n            height: 1.2em;\n            font-size: 1.2em;\n            cursor: pointer;\n            img {\n              height: 1.8em;\n              border-radius: 50%;\n              top: 0.1em;\n              position: absolute;\n              left: 0.1em;\n            }\n          }\n        }\n      }\n\n      @media only screen and (max-width: 600px) {\n        display: block;\n\n        #lobby {\n          margin: .5rem 0 0;\n        }\n      }\n    }\n\n    #settings {\n      margin: .4em .2em;\n      font-size: 1.3em;\n      input, select {\n        font-family: 'DM Sans Variable';\n        font-size: 1em;\n        padding: 0em 0.5em;\n        margin: 0.1em 0;\n        background: #eef;\n        &:focus {\n          outline: none;\n        }\n      }\n      input[type=checkbox] {\n        transform: scale(1.5);\n        transform-origin: left center;\n        margin-right: .5em;\n        &:focus {\n          outline: none;\n        }\n      }\n    }\n\n    button.ready {\n      margin: 0 auto;\n      display: block;\n      white-space: normal;\n      font-family: 'DM Sans Variable';\n      border-radius: .2em;\n      border-width: 0;\n      text-shadow: .1em .1em 0 #fff5;\n      box-shadow: .1em .1em .2em #0008, inset .1em .1em 0 #fff9;\n      background: linear-gradient(to bottom, #ddd,  #aaa 85%, #ccc);\n      padding: 0.3em 1.6em;\n      font-size: 1.4em;\n      font-weight: bold;\n      margin-top: .5em;\n      cursor: pointer;\n      transition: transform .2s;\n      &:hover {\n        transform: scale(1.2);\n      }\n    }\n    &.disabled input, &.disabled select, &.disabled button {\n      pointer-events: none;\n    }\n  }\n\n  .profile-badge {\n    display: flex;\n    flex-direction: row;\n    margin: 0.1em;\n    height: 1em;\n    width: 3em;\n    border-radius: .5em;\n    gap: 0.1em;\n    padding: 0.1em;\n\n    .avatar {\n      height: 100%;\n      width: auto;\n      aspect-ratio: 1;\n      position: relative;\n\n      img {\n        position: absolute;\n        top: 0;\n        left: 0;\n        height: 100%;\n        border-radius: 50%;\n        outline-color: #333;\n        outline-style: solid;\n        outline-width: 1px;\n        filter: saturate(0) contrast(.6) brightness(1.2);\n        html.dark & {\n          outline-color: #aaa;\n        }\n      }\n\n      &:after {\n        content: \"\";\n        background-color: #666;\n        outline-color: black;\n        display: block;\n        position: absolute;\n        border-radius: 50%;\n        outline-style: solid;\n        outline-width: 2px;\n        width: 15%;\n        height: 15%;\n        top: 7%;\n        right: 7%;\n        html.dark & {\n          outline-color: #aaa;\n        }\n      }\n    }\n\n    &.online .avatar img {\n      filter: none;\n    }\n\n    &.online .avatar:after {\n      content: \"\";\n      background-color: #0f0;\n      outline-color: black;\n      outline-style: solid;\n      outline-width: 1px;\n      display: block;\n      position: absolute;\n      border-radius: 50%;\n      width: 15%;\n      height: 15%;\n      top: 7%;\n      right: 7%;\n      html.dark & {\n        outline-color: #aaa;\n      }\n    }\n\n    &.current {\n      border: .03em solid white;\n    }\n\n    .player-name {\n      flex: 1;\n      overflow: hidden;\n      text-align: left;\n      white-space: nowrap;\n      font-size: 35%;\n      text-overflow: ellipsis;\n      color: white;\n      margin: 0.44em 0 0 0.1em;\n    }\n\n    &.current .player-name {\n      animation: pulse-player-name 2s infinite;\n    }\n  }\n\n  #corner-controls {\n    position: fixed;\n    top: 1vh;\n    left: 1vh;\n    z-index: 200;\n\n    #info-toggle {\n      position: absolute;\n      height: 3vh;\n      top: 0;\n      left: 0;\n      svg {\n        display: block;\n        height: 100%;\n        fill: white;\n        cursor: pointer;\n      }\n    }\n\n    #debug-toggle {\n      position: absolute;\n      height: 3vh;\n      top: 0;\n      left: 3.5vh;\n      svg {\n        display: block;\n        height: 100%;\n        fill: white;\n        cursor: pointer;\n      }\n    }\n  }\n\n  #announcement-overlay {\n    z-index: 200;\n  }\n\n  .modal-popup {\n    position: absolute;\n    width: max-content;\n    max-width: 80%;\n    background: white;\n    color: #002;\n    top: 4rem;\n    left: 50%;\n    transform: translateX(-50%);\n    visibility: visible;\n    filter: none;\n    z-index: 210;\n    padding: .5rem;\n    box-shadow: 0.2rem 0.2rem .5rem #0008;\n\n    h1, h2, h3, h4, h5, h6 {\n      text-align: center;\n      margin: .25em 0;\n    }\n\n    html.dark & {\n      background: #cccccf;\n    }\n  }\n\n  #info-overlay {\n    z-index: 199;\n    background: #444c;\n  }\n\n  #info-container {\n    z-index: 210;\n    visibility: hidden;\n    color: #002;\n\n    #info-drawer {\n      font-family: 'DM Sans Variable';\n      position: absolute;\n      left: 0.3rem;\n      top: 0.3rem;\n      width: clamp(20%, 10rem, 100%);\n      background: white;\n      border-radius: 0.3rem;\n      transition: width 0.2s, height 0.2s;\n      visibility: visible;\n      z-index: 200;\n      max-height: calc(100% - 0.6rem);\n      overflow-x: hidden;\n      overflow-y: scroll;\n      box-shadow: 0.2rem 0.2rem .5rem #0008;\n\n      &.collapsed {\n        width: 2.4rem;\n        .header {\n          border-radius: 0.3rem;\n        }\n      }\n\n      .header {\n        width: 100%;\n        height: 1.4rem;\n        background: #ccc;\n        border-radius: 0.3rem 0.3rem 0 0;\n        padding: .1rem 0.25rem;\n        box-sizing: border-box;\n        display: flex;\n\n        .title {\n          flex: 1;\n        }\n\n        .controls {\n          flex: 1;\n          text-align: right;\n        }\n\n        svg {\n          height: .8rem;\n          cursor: pointer;\n          &:hover {\n            transform: scale(1.2);\n          }\n        }\n      }\n\n      .contents {\n        font-size: 65%;\n        padding: .1rem 0.25rem;\n        width: 10rem;\n        border-top: .1rem solid #888;\n\n        h1 {\n          margin: 0.1rem 0;\n          font-size: 1rem;\n          text-align: center;\n        }\n\n        ul {\n          margin: 0 0 0 .5rem;\n          padding: 0 0 0 .25rem;\n          li {\n            list-style: '⏺';\n            padding-left: .1rem;\n            span {\n              color: #002;\n            }\n          }\n        }\n\n        button {\n          width: 94%;\n          padding: 0.2rem 0.4rem;\n          font-family: inherit;\n          font-size: inherit;\n          margin: 0.1rem 3%;\n          border: none;\n          background: #ccc;\n          cursor: pointer;\n          transition: transform 0.2s;\n          white-space: normal;\n          &:hover {\n            transform: scale(1.05);\n            box-shadow: 0.2rem 0.2rem .5rem #0008;\n          }\n        }\n\n        .more-info {\n          padding: .25rem .25rem .5rem;\n        }\n      }\n    }\n\n    #info-modal {\n      &.info-element {\n        min-width: 64%;\n      }\n\n      .element-zoom {\n        display: inline-block;\n        float: right;\n        margin: 0 0 1rem 1rem;\n        position: relative;\n        pointer-events: none;\n        width: 32vw;\n        .Piece, .Space {\n          transform: none !important;\n        }\n        > div {\n          position: relative;\n        }\n      }\n\n      .info-text {\n        font-size: 80%;\n        p, h1, h2, h3, h4 {\n          margin-top: 0;\n        }\n      }\n    }\n  }\n\n  #debug-overlay {\n    font-size: 16px;\n    z-index: 199;\n    background: #fffc;\n\n    #action-debug {\n      overflow-y: scroll;\n      position: absolute;\n      right: .5em;\n      top: 5vmin;\n      width: calc(45% - 1em);\n      height: calc(100% - 4em);\n      top: 3em;\n\n      #action-breakdown {\n        font-family: 'DM Sans Variable', sans-serif;\n        color: black;\n      }\n\n      a {\n        color: #009;\n        cursor: pointer;\n      }\n\n      .argument {\n        padding: .1em .5em;\n        background: #ddf;\n        border: .05em solid #bbe;\n        border-radius: .3em;\n      }\n\n      ul {\n        padding-left: 1.2em;\n      }\n\n      li.action-block {\n        margin-bottom: 1em;\n\n        .name {\n          font-weight: bold;\n        }\n\n        &::marker {\n          content: '► ';\n          color: #900;\n        }\n        &.impossible::marker {\n          content: '🚫 ';\n        }\n        &.impossible {\n          filter: opacity(.5);\n        }\n\n        li {\n          margin-bottom: .4em;\n          &.selection-type-ask::marker {\n            content: '► ';\n            color: #009;\n          }\n          &.selection-type-tree::marker {\n            content: '🚫 ';\n          }\n          &.selection-type-imp::marker {\n            content: '❌ ';\n          }\n          &.selection-type-sel::marker, &.selection-type-only-one::marker, &.selection-type-skip::marker {\n            content: '✓ ';\n            color: #090;\n          }\n          &.selection-type-future::marker, &.selection-type-forced::marker {\n            content: '▷ ';\n          }\n        }\n      }\n    }\n\n    .element-zoom {\n      display: inline-block;\n      margin: 0 0 1rem 1rem;\n      position: relative;\n      pointer-events: none;\n      width: 24vw;\n      .Piece, .Space {\n        transform: none !important;\n      }\n      > div {\n        position: relative;\n      }\n    }\n\n    #flow-debug {\n      font-family: 'DM Sans Variable', sans-serif;\n      overflow-y: scroll;\n      position: absolute;\n      left: .5em;\n      top: 5vmin;\n      width: 55%;\n      height: calc(100% - 4em);\n      top: 3em;\n\n      .subflow {\n        background: black;\n        color: white;\n        width: 90%;\n        padding: .2em 1em;\n        margin: 1em 0;\n        border-radius: 1.5em;\n      }\n\n      > .flow-debug-block {\n        width: 90%;\n      }\n      .flow-debug-block {\n        margin: .2em 0 .2em .4em;\n        border-left: .2em solid var(--color);\n        position: relative;\n\n        &.current {\n          outline: 4px solid #ff0;\n          &::after {\n            content: '';\n            position: absolute;\n            width: 5%;\n            height: 100%;\n            left: 100%;\n            top: 0;\n            background: #ff0;\n            clip-path: polygon(0% 0%, 100% 50%, 0% 100%);\n          };\n          .header {\n            color: #ff0;\n          }\n        }\n\n        .header {\n          display: flex;\n          color: white;\n          background: var(--color);\n          height: 1.5em;\n          padding: 0 .2em;\n          > .name {\n            height: 80%;\n            color: var(--color);\n            background: white;\n            display: inline-block;\n            border-radius: 1em;\n            margin-left: .5em;\n            margin-top: .25em;\n            font-size: .75em;\n            padding: .2em .5em;\n            overflow-x: scroll;\n            white-space: nowrap;\n          }\n        }\n\n        .do-block {\n          > .name {\n            left: -0.15em;\n            position: relative;\n\n            &::before {\n              content: '► '\n            }\n          }\n        }\n\n        .function {\n          font-family: monospace;\n          font-size: 75%;\n          line-height: 1.2em;\n          padding-left: .4em;\n          text-overflow: ellipsis;\n          white-space: nowrap;\n          overflow: hidden;\n          &.current {\n            background: 4px solid #ff0;\n          }\n        }\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/ui/game/Game.tsx",
    "content": "import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';\nimport { gameStore } from '../store.js';\n\nimport Element from './components/Element.js';\nimport PlayerControls from './components/PlayerControls.js';\nimport InfoOverlay from './components/InfoOverlay.js';\nimport Debug from './components/Debug.js';\nimport click from '../assets/click.ogg.js';\nimport { GameElement } from '../../board/index.js'\nimport classnames from 'classnames';\n\nimport type { UIMove } from '../lib.js';\nimport type { Argument } from '../../action/action.js';\nimport AnnouncementOverlay from './components/AnnouncementOverlay.js';\n\nexport default () => {\n  const [gameManager, rendered, dev, position, pendingMoves, step, announcementIndex, dismissAnnouncement, selectMove, move, clearMove, selectElement, setBoardSize, dragElement, disambiguateElement, selected] = gameStore(s => [s.gameManager, s.rendered, s.dev, s.position, s.pendingMoves, s.step, s.announcementIndex, s.dismissAnnouncement, s.selectMove, s.move, s.clearMove, s.selectElement, s.setBoardSize, s.dragElement, s.aspectRatio, s.disambiguateElement, s.selected]);\n  const clickAudio = useRef<HTMLAudioElement>(null);\n  const [mode, setMode] = useState<'game' | 'info' | 'debug'>('game');\n  const announcement = useMemo(() => gameManager.announcements[announcementIndex], [gameManager.announcements, announcementIndex]);\n\n  if (!position) return null;\n  const player = gameManager.players.atPosition(position);\n  if (!player) return null;\n\n  const handleSubmitMove = useCallback((pendingMove?: UIMove, args?: Record<string, Argument>) => {\n    if (move || disambiguateElement || selected) clickAudio.current?.play();\n    clearMove();\n    selectMove(pendingMove, args);\n  }, [move, disambiguateElement, selected, clearMove, selectMove]);\n\n  const handleSelectElement = useCallback((moves: UIMove[], element: GameElement) => {\n    clickAudio.current?.play();\n    selectElement(moves, element);\n  }, [selectElement]);\n\n  const domRef = useCallback((node: HTMLDivElement) => {\n    if (!node) return;\n    const callback: MutationCallback = deletions => {\n      deletions.forEach(m => m.removedNodes.forEach((d: HTMLElement) => {\n        if (d.classList.contains('player-controls') && !d.classList.contains('fade-out')) {\n          const fadeOut = d.cloneNode(true);\n          (fadeOut as HTMLElement).classList.add('fade-out');\n          node.appendChild(fadeOut);\n          setTimeout(() => node.removeChild(fadeOut), 500);\n        }\n      }));\n    };\n\n    const observer = new MutationObserver(callback);\n    observer.observe(node, { childList: true });\n  }, []);\n\n  useEffect(() => {\n    const keydownHandler = (e: KeyboardEvent) => {\n      if (e.repeat) return;\n      if (e.code === 'Escape') {\n        if (mode === 'game') handleSubmitMove();\n      }\n    };\n    window.addEventListener('keydown', keydownHandler);\n    return () => window.removeEventListener('keydown', keydownHandler);\n  }, [handleSubmitMove, mode]);\n\n  useEffect(() => {\n    window.addEventListener('resize', setBoardSize);\n    return () => window.removeEventListener('resize', setBoardSize);\n  }, [setBoardSize]);\n\n  useEffect(() => {\n    if (gameManager.game._ui.boardSize) {\n      window.document.documentElement.style.setProperty(\n        'font-size',\n        `${gameManager.game._ui.boardSize.scaling === 'scroll' ? 'max' : 'min'}(4${gameManager.game._ui.boardSize.flipped ? 'vh' : 'vw'} / var(--aspect-ratio), 4${gameManager.game._ui.boardSize.flipped ? 'vw' : 'vh'})`\n      );\n      window.document.documentElement.style.setProperty(\n        '--aspect-ratio',\n        String(gameManager.game._ui.boardSize.aspectRatio)\n      )\n      if (gameManager.game._ui.boardSize.flipped) {\n        window.document.querySelector('#root')?.classList.add('orientation-flipped');\n      } else {\n        window.document.querySelector('#root')?.classList.remove('orientation-flipped');\n      }\n      return () => {\n        window.document.documentElement.style.removeProperty('font-size');\n        window.document.documentElement.style.removeProperty('--aspect-ratio');\n      }\n    }\n  }, [gameManager.game._ui.boardSize]);\n\n  console.debug('Showing game with pending moves:' +\n    (pendingMoves?.map(m => (\n      `\\n⮕ ${typeof m === 'string' ? m :\n        `${m.name}({${\n          Object.entries(m.args || {}).map(([k, v]) => `${k}: ${v}`).join(', ')\n        }}) ? ${m.selections?.length ? m.selections[0].toString() : 'no choices'}`\n      }`\n    )).join('') || ' none')\n  );\n\n  return (\n    <div\n      id=\"game\"\n      ref={domRef}\n      data-board-size={gameManager.game._ui.boardSize?.name}\n      data-step={step}\n      className={classnames(\n        globalThis.navigator?.userAgent.match(/Mobi/) ? 'mobile' : 'desktop',\n        {\n          'scaling-scroll': gameManager.game._ui.boardSize?.scaling === 'scroll',\n          'browser-chrome': globalThis.navigator?.userAgent.indexOf('Chrome') > -1,\n          'browser-safari': globalThis.navigator?.userAgent.indexOf('Chrome') === -1 && globalThis.navigator?.userAgent.indexOf('Safari') > -1,\n          'browser-edge': globalThis.navigator?.userAgent.indexOf('Edge') > -1,\n          'browser-firefox': globalThis.navigator?.userAgent.indexOf('Firefox') > -1,\n        }\n      )}\n      style={{\n        ['--aspect-ratio' as string]: gameManager.game._ui.boardSize?.aspectRatio,\n        ['--current-player-color' as string]: gameManager.players.currentPosition.length === 1 ? gameManager.players.current()?.color : '',\n        ['--my-player-color' as string]: gameManager.players.atPosition(position)?.color\n      }}\n    >\n      <audio ref={clickAudio} src={click} id=\"click\"/>\n      {mode !== 'debug' && <div id=\"background\" className=\"full-page-cover\" />}\n      <div id=\"play-area\" style={{width: '100%', height: '100%'}} className={dragElement ? \"in-drag-movement\" : \"\"}>\n        {mode !== 'debug' && rendered && (\n          <Element\n            render={rendered.game}\n            mode={announcement ? 'info' : mode}\n            onSelectElement={handleSelectElement}\n          />\n        )}\n      </div>\n\n      {mode === 'game' && !announcement && (\n        <PlayerControls\n          onSubmit={handleSubmitMove}\n        />\n      )}\n\n      {gameManager.godMode && mode === 'game' && !announcement && <div className=\"god-mode-enabled\">God mode enabled</div>}\n\n      {mode !== 'info' && (\n        <div id=\"corner-controls\">\n          <div id=\"info-toggle\">\n            <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"-6 -6 112 112\" onClick={() => setMode('info')}>\n              <path\n                style={{stroke:'black', fill: 'white', strokeWidth: 8}}\n                d=\"M 53.102,4 C 25.983,4 4,25.983 4,53.102 c 0,27.119 21.983,49.103 49.102,49.103 27.119,0 49.101,-21.984 49.101,-49.103 C 102.203,25.983 80.221,4 53.102,4 Z\"\n              />\n              <path\n                fill=\"black\"\n                d=\"m 53.102,34.322 c -5.048,0 -9.141,-4.092 -9.141,-9.142 0,-5.049 4.092,-9.141 9.141,-9.141 5.05,0 9.142,4.092 9.142,9.141 -10e-4,5.05 -4.093,9.142 -9.142,9.142 z\"\n              />\n              <path\n                fill=\"black\"\n                d=\"m 61.669,82.139 c 0,4.402 -3.806,7.969 -8.5,7.969 -4.694,0 -8.5,-3.567 -8.5,-7.969 V 45.577 c 0,-4.401 3.806,-7.969 8.5,-7.969 4.694,0 8.5,3.568 8.5,7.969 z\"\n              />\n            </svg>\n          </div>\n          {dev && (\n            <div id=\"debug-toggle\">\n              <svg\n                viewBox=\"-40 -40 574.04362 578.11265\"\n                xmlns=\"http://www.w3.org/2000/svg\"\n                onClick={() => setMode(mode === 'debug' ? 'game' : 'debug')}\n              >\n                <path\n                  style={{fill: 'white', stroke: 'black', strokeWidth:80, paintOrder:'stroke markers fill'}}\n                  d=\"m 352.48196,213.31221 c 0,78.32378 -63.49396,141.81774 -141.81774,141.81775 -78.32378,0 -141.817754,-63.49397 -141.817754,-141.81775 10e-7,-78.32378 63.493974,-141.817751 141.817754,-141.817749 78.32378,6e-6 141.81774,63.493969 141.81774,141.817749 z M 490.31895,451.24231 378.93053,344.196 c 29.8,-36.3 42.26947,-82.8 42.26947,-133.4 0,-116.3 -94.3,-210.6 -210.6,-210.6 -116.3,0 -210.6,94.3 -210.6,210.6 0,116.3 94.3,210.6 210.6,210.6 50.8,0 88.51578,-8.22736 124.91578,-38.22736 l 112.27685,111.38842 c 12.9,11.8 32.10737,-6.46106 36.30737,-10.66106 8.4,-8.3 14.61895,-24.35369 6.21895,-32.65369 z\"/>\n              </svg>\n            </div>\n          )}\n        </div>\n      )}\n\n      {mode === 'game' && announcement && (\n        <AnnouncementOverlay\n          announcement={announcement}\n          onDismiss={dismissAnnouncement}\n        />\n      )}\n      {mode === 'info' && <InfoOverlay setMode={setMode}/>}\n      {mode === 'debug' && dev && <Debug/>}\n    </div>\n  );\n}\n"
  },
  {
    "path": "src/ui/game/components/ActionForm.tsx",
    "content": "import React, { useState, useMemo, useCallback, useEffect } from 'react';\nimport { gameStore } from '../../store.js';\nimport { n } from '../../../utils.js';\nimport Selection from './Selection.js';\n\nimport type { UIMove } from '../../lib.js';\nimport type { Argument } from '../../../action/action.js';\n\nconst ActionForm = ({ move, stepName, onSubmit }: {\n  move: UIMove,\n  stepName: string,\n  onSubmit: (move?: UIMove, args?: Record<string, Argument>) => void,\n  children?: React.ReactNode,\n}) => {\n  const [gameManager, position, uncommittedArgs, selected, disambiguateElement] = gameStore(s => [s.gameManager, s.position, s.uncommittedArgs, s.selected, s.disambiguateElement]);\n  const [errors, setErrors] = useState<Record<string, string | undefined>>({});\n\n  const action = useMemo(() => move.name === '__pass__' ? undefined : gameManager.getAction(move.name, gameManager.players.atPosition(position!)!), [gameManager, position, move]);\n\n  const initial = useCallback(() => {\n    const args: Record<string, Argument | undefined> = {...move.args};\n    for (const s of move.selections) {\n      if (s.name !== '__action__' && s.name !== '__confirm__' && !s.isBoardChoice()) args[s.name] = s.initial;\n    }\n    return args;\n  }, [move]);\n\n  const [args, setArgs] = useState<Record<string, Argument | undefined>>(initial());\n\n  useEffect(() => setArgs(initial()), [initial, move]);\n\n  const allArgs = useMemo(() => {\n    const allArgs = {...uncommittedArgs, ...args};\n    // provisionally consider the ambiguous board selection as part of this move for confirmation/validation\n    if (disambiguateElement && disambiguateElement.moves.includes(move)) {\n      const selection = move.selections[0];\n      if (selection.type === 'board') {\n        allArgs[move.selections[0].name] = selection.isMulti() ? selected : selected?.[0];\n      }\n    }\n    return allArgs;\n  }, [args, move, selected, uncommittedArgs, disambiguateElement]);\n\n  const submitForm = useCallback((args: Record<string, Argument | undefined>) => {\n    onSubmit(move, args as Record<string, Argument>);\n    setArgs(initial());\n    setErrors({});\n  }, [onSubmit, initial, move])\n\n  // return set of errors per selection from validation rules\n  const validationErrors = useCallback((args: Record<string, Argument | undefined>) => {\n    if (!action) return {};\n    return Object.fromEntries(\n      move.selections.filter(\n        s => s.name !== '__action__' && s.name !== '__confirm__'\n      ).map(\n        s => [\n          s.name,\n          args[s.name] === undefined ? 'Missing' : action._getError(s, args)\n        ]\n      )\n    );\n  }, [action, move.selections]);\n\n  // display errors\n  const validate = useCallback((args: Record<string, Argument | undefined>) => {\n    const errors = validationErrors(args);\n    setErrors(errors);\n\n    return Object.values(errors).every(e => !e);\n  }, [validationErrors]);\n\n  const onSubmitForm = useCallback((e: React.FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    if (validate(allArgs)) submitForm(allArgs);\n    setArgs(initial());\n  }, [allArgs, validate, submitForm, initial])\n\n  const handleChange = useCallback((name: string, arg: Argument) => {\n    let newArgs = allArgs;\n    if (name !== '__action__' && name !== '__confirm__') newArgs[name] = arg;\n\n    if (Object.values(allArgs).every(a => a !== undefined)) {\n      if (validate(newArgs) && !move.requireExplicitSubmit) return submitForm(allArgs);\n    } else {\n      setErrors({});\n    }\n    setArgs(a => ({...a, [name]: arg}));\n  }, [allArgs, validate, submitForm, move]);\n\n  const confirm = useMemo(() => {\n    if (Object.values(validationErrors(allArgs)).some(e => e)) return undefined;\n    if (!move.requireExplicitSubmit || !action) return undefined;\n    if (Object.values(allArgs).some(a => a === undefined)) return undefined;\n    for (const s of move.selections) {\n      if (s.type === 'board' && s.isMulti() && (!selected || (selected.length < (s.min ?? 1) || selected.length > (s.max ?? Infinity)))) return undefined;\n    }\n    let confirm = 'Confirm';\n    const args: Record<string, Argument> = Object.fromEntries(Object.entries(allArgs).filter(([, v]) => v !== undefined)) as Record<string, Argument>;\n    confirm = action._getConfirmation(move.selections[0], args) ?? confirm;\n    return n(confirm, args)\n  }, [move, action, allArgs, selected, validationErrors]);\n\n  const confirmToShow = useMemo(() => {\n    if (confirm) return confirm;\n    if (stepName === 'disambiguate-board-selection') return move.prompt ?? move.name;\n  }, [stepName, confirm, move]);\n\n  const selectionsToShow = useMemo(() => move.selections.filter(s => s.name !== '__confirm__'), [move]);\n\n  return (\n    <form\n      id={move.name}\n      onSubmit={e => onSubmitForm(e)}\n      className={`action ${move.name}`}\n    >\n      {move.prompt && stepName !== 'disambiguate-board-selection' && <div className=\"prompt\">{move.prompt}</div>}\n\n      {selectionsToShow.map(s => (\n        <Selection\n          key={s.name}\n          value={allArgs[s.name]}\n          error={errors[s.name]}\n          setErrors={setErrors}\n          onChange={(value: Argument) => handleChange(s.name, value)}\n          selection={s}\n        />\n      ))}\n\n      {confirmToShow && <button name=\"submit\" type=\"submit\">{confirmToShow}</button>}\n    </form>\n  );\n};\n\nexport default ActionForm;\n"
  },
  {
    "path": "src/ui/game/components/AnnouncementOverlay.tsx",
    "content": "import React, { useEffect, useState } from 'react';\nimport { gameStore } from '../../store.js';\n\nconst AnnouncementOverlay = ({ announcement, onDismiss }: {\n  announcement: string,\n  onDismiss: () => void\n}) => {\n  const [gameManager] = gameStore(s => [s.gameManager]);\n  const [delay, setDelay] = useState(false);\n\n  useEffect(() => {\n    const timer = setTimeout(() => setDelay(true), 1000);\n    return () => clearTimeout(timer);\n  }, []);\n\n  if (!delay) return;\n\n  return (\n    <div id=\"announcement-overlay\" className=\"full-page-cover\" onClick={() => onDismiss()}>\n      <div id=\"announcement\" className=\"modal-popup\" onClick={() => onDismiss()}>\n        {announcement !== '__finish__' && gameManager.game._ui.announcements[announcement](gameManager.game)}\n        {announcement === '__finish__' && (\n          <>\n            <h1>Game finished</h1>\n            {gameManager.winner.length > 0 && (\n              <h2 style={{color: gameManager.winner.length === 1 ? gameManager.winner[0].color : ''}}>\n                {gameManager.players.length === 1 ? 'You' : gameManager.winner.map(p => p.name).join(', ')} win{gameManager.winner.length === 1 && gameManager.players.length !== 1 && 's'}!\n              </h2>\n            )}\n            {gameManager.winner.length === 0 && gameManager.players.length > 1 && <h2>Tie game</h2>}\n            {gameManager.winner.length === 0 && gameManager.players.length === 1 && <h2 style={{color: \"#800\"}}>You lose</h2>}\n          </>\n        )}\n      </div>\n    </div>\n  );\n}\n\nexport default AnnouncementOverlay;\n"
  },
  {
    "path": "src/ui/game/components/BoardDebug.tsx.wip",
    "content": "import React, { useState } from 'react';\nimport { gameStore } from '../../';\n\nimport {\n  GameElement,\n  ElementCollection,\n} from '../../../game/board/';\nimport type { Player } from '../../../game/player';\n\nexport default () => {\n  const [game, updateBoard] = gameStore(s => [s.game, s.updateBoard, s.boardJSON]);\n  if (!game) return null;\n\n  const [error, setError] = useState('');\n\n  // put element classes into scope\n  game.board._ctx.classRegistry.forEach((c, i) => eval(`window.${c.name} = board._ctx.classRegistry[${i}];`));\n\n  const query = (q: string) => {\n    if (!q) return;\n    let result;\n    try {\n      result = eval(`board.${q}`);\n      setError(\"\");\n    } catch (e) {\n      setError(e.message);\n    }\n    updateBoard();\n\n    // if (result) {\n    //   if (result.constructor.name === 'ElementCollection') {\n    //     setHilites(Array.from(result as ElementCollection<Player, GameElement<Player>>));\n    //   }\n    //   if (result.branch) {\n    //     setHilites([result.branch()]);\n    //   }\n    // }\n  };\n\n  return (\n    <div id=\"board-debug\">\n      <code>board.</code>\n      <input style={{width: \"55vw\", display: \"inline\"}} onChange={e => query(e.target.value)}/>\n      <div style={{color: \"red\"}}>{error}</div>\n      <textarea readOnly={true} value={JSON.stringify(game.board.allJSON(), undefined, 2)} />\n<button onClick={() => navigator.clipboard.writeText(JSON.stringify(game.getState(), undefined, 2))}>Copy setState</button>\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/ui/game/components/Debug.tsx",
    "content": "import React, { useCallback, useEffect, useMemo } from 'react';\nimport { gameStore } from '../../store.js';\n\nimport FlowDebug from './FlowDebug.js';\nimport Element from './Element.js';\nimport DebugChoices from './DebugChoices.js';\nimport { ResolvedSelection } from '../../../action/selection.js';\nimport DebugArgument from './DebugArgument.js';\n\nconst Debug = () => {\n  const [position, gameManager, rendered, actionDebug, pendingMoves, infoElement, setInfoElement, selected, disambiguateElement] = gameStore(s => [s.position, s.gameManager, s.rendered, s.actionDebug, s.pendingMoves, s.infoElement, s.setInfoElement, s.selected, s.disambiguateElement]);\n  const player = gameManager.players.atPosition(position!)!;\n\n  useEffect(() => setInfoElement(), [setInfoElement]);\n\n  const getAction = useCallback((name: string) => pendingMoves?.find(m => m.name === name), [pendingMoves]);\n  const getSelection = useCallback((name: string, selection: string) => getAction(name)?.selections.find(s => s.name === selection), [getAction]);\n\n  let elementStyle: React.CSSProperties | undefined = useMemo(() => {\n    if (!infoElement?.element) return {};\n    const scale = rendered!.all[String(infoElement.element._t.ref)].pos!\n    let fontSize = 24 * 0.04;\n    const aspectRatio = scale.width / scale.height;\n\n    if (aspectRatio > 1) {\n      scale.width = 100;\n      fontSize /= aspectRatio;\n    } else {\n      scale.width *= 100 / scale.height;\n    }\n    return {\n      width: scale.width + '%',\n      aspectRatio,\n      fontSize: fontSize + 'rem',\n    };\n  }, [infoElement?.element, rendered]);\n\n  if (!gameManager || !actionDebug) return null;\n\n  return (\n    <div id=\"debug-overlay\" className=\"full-page-cover\" onClick={() => setInfoElement()}>\n      <div id=\"flow-debug\">\n        {Object.entries(gameManager.flows).map(([name, flow]) => (\n          <React.Fragment key={name}>\n            {name !== '__main__' && <div className=\"subflow\">subflow \"{name.replace(/__/g, '')}\"</div>}\n            <FlowDebug flow={flow.visualize(flow)} nest={0} current={true} />\n          </React.Fragment>\n        ))}\n      </div>\n      <div id=\"action-debug\">\n        <div id=\"action-breakdown\">\n          <b>Available Actions for {player.name}</b>\n          <ul>\n            {Object.entries(actionDebug).map(([action, { impossible, args }]) => (\n              <li className={`action-block ${impossible || Object.values(args).some(a => a === 'imp') ? 'impossible' : ''}`} key={action}>\n                <div>\n                  <span className=\"name\">{action === '__pass__' ? 'Implied pass' : action}</span>\n                  {impossible && <span> (Impossible by <code>action.condition</code>)</span>}\n                </div>\n                {action !== '__pass__' && !impossible && (\n                  <ul>\n                    {gameManager.getAction(action, player).selections.map(\n                      s => [s.name, s.type, getSelection(action, s.name)] as [string, string, ResolvedSelection?]\n                    ).map(([name, type, sel]) => (\n                      <li key={name} className={`selection-type-${args[name] ?? 'future'}`}>\n                        <div className=\"function\">\n                          <code>{{number: 'chooseNumber', board: 'chooseOnBoard', 'choices': 'chooseFrom', text: 'enterText', button: 'confirm', place: 'placePiece'}[type]}</code>\n                          &nbsp;<span className=\"name\">\"{name}\"</span>\n                        </div>\n\n                        {['ask', 'imp', 'tree'].includes(args[name]) && (\n                          <div>\n                            <ul>\n                              <li>\n                                Choices: <DebugChoices choices={sel?.resolvedChoices} />\n                              </li>\n                              {(sel?.min !== undefined || sel?.max !== undefined) && <><li>min: {sel.min ?? 1}</li><li>max: {sel.max ?? '∞'}</li></>}\n                            </ul>\n                          </div>\n                        )}\n                        {args[name] === 'imp' && ' (no valid choices)'}\n                        {args[name] === 'tree' && ' (no valid continuation)'}\n                        {['sel', 'skip', 'only-one', 'forced', 'always'].includes(args[name]) && (\n                          <span>\n                            <span className=\"argument\">\n                              <DebugArgument argument={getAction(action)?.args[name]}/>\n                            </span>\n                            {args[name] === 'sel' && ' (player-selected)'}\n                            {args[name] === 'skip' && <span> (skipped by <code>skipIf</code> function)</span>}\n                            {args[name] === 'only-one' && <span> (skipped by <code>\"only-one\"</code>)</span>}\n                            {args[name] === 'forced' && <span> (will skip by <code>\"only-one\"</code>)</span>}\n                          </span>\n                        )}\n                      </li>\n                    ))}\n                  </ul>\n                )}\n              </li>\n            ))}\n          </ul>\n\n          {selected?.length && (\n            <div style={{marginBottom: '1em'}}>\n              <hr/>\n              Selected: <DebugChoices choices={selected.map(s => ({choice: s}))}/>\n              {disambiguateElement && <span>(ambiguous: valid moves are: \"{disambiguateElement.moves.map(m => m.name).join('\", \"')}\")</span>}\n            </div>\n          )}\n\n        </div>\n        {infoElement?.element && (\n          <div className=\"element-zoom\">\n            <div style={elementStyle}>\n              <Element\n                render={rendered!.all[infoElement!.element!._t.ref]}\n                mode='zoom'\n                onSelectElement={() => {}}\n              />\n            </div>\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n\nexport default Debug;\n"
  },
  {
    "path": "src/ui/game/components/DebugArgument.tsx",
    "content": "import React from 'react';\nimport { gameStore } from '../../store.js';\n\nimport type { Argument } from '../../../action/action.js';\nimport type { GameElement } from '../../../index.js';\n\nconst DebugArgument = ({ argument }: {\n  argument?: Argument\n}) => {\n  const [setInfoElement] = gameStore(s => [s.setInfoElement]);\n  if (argument !== undefined) return (\n    typeof argument === 'object' && 'isGameElement' in argument.constructor ? (\n      <a onClick={e => {e.stopPropagation(); setInfoElement({ info: true, element: argument as GameElement })}}>{String(argument)}</a>\n    ) : String(argument)\n  );\n}\n\nexport default DebugArgument;\n"
  },
  {
    "path": "src/ui/game/components/DebugChoices.tsx",
    "content": "import React from 'react';\nimport DebugArgument from './DebugArgument.js';\n\nimport type { Argument } from '../../../action/action.js';\n\nconst DebugChoices = ({ choices }: {\n  choices?: { label?: string; choice: Argument, error?: string}[] ,\n}) => {\n  if (!choices?.length) return null;\n\n  return (\n    <span>\n      {choices.map((c, i) => (\n        <span key={i} style={{ textDecoration: c.error ? 'line-through' : 'none' }}>\n          {i ? ', ' : ''}<DebugArgument argument={c.choice}/>\n          {c.error && ` (${c.error})`}\n        </span>\n      ))}\n    </span>\n  );\n}\n\nexport default DebugChoices;\n"
  },
  {
    "path": "src/ui/game/components/Drawer.tsx",
    "content": "import React, { useEffect, useMemo, useState } from 'react';\nimport { gameStore } from '../../store.js';\n\nimport type { Argument } from '../../../action/action.js';\nimport type { Box, LayoutAttributes } from '../../../board/element.js';\n\nconst Drawer = ({ layout, absolutePosition, children, attributes }: {\n  layout: Partial<LayoutAttributes>,\n  absolutePosition: Box,\n  children: Record<string, JSX.Element[]>,\n  attributes: {\n    tab?: React.ReactNode\n    closedTab?: React.ReactNode,\n    openDirection: 'up' | 'down' | 'left' | 'right',\n    openIf?: (actions: { name: string, args: Record<string, Argument> }[]) => boolean,\n    closeIf?: (actions: { name: string, args: Record<string, Argument> }[]) => boolean,\n  }\n}) => {\n  const [open, setOpen] = useState(false);\n  const [pendingMoves] = gameStore(s => [s.pendingMoves]);\n  const { tab, closedTab, openIf, closeIf, openDirection } = attributes;\n\n  const area = useMemo(() => layout?.area ?? {top: 0, left: 0, width: 100, height: 100}, [layout])\n  const aspectRatio = useMemo(() => absolutePosition ? absolutePosition.width / absolutePosition.height : 1, [absolutePosition])\n\n  useEffect(() => {\n    const actions = pendingMoves?.map(m => ({ name: m.name, args: m.args })) ?? [];\n\n    if (openIf?.(actions)) setOpen(true);\n    if (closeIf?.(actions)) setOpen(false);\n  }, [openIf, closeIf, pendingMoves]);\n\n  const style = useMemo(() => {\n    return {\n      top: area.top + '%',\n      left: area.left + '%',\n      height: area.height + '%',\n      width: area.width + '%',\n    }\n  }, [area]);\n\n  const sliderStyle = useMemo(() => {\n    return {\n      transform: `scaleX(${open || ['up', 'down'].includes(openDirection) ? 1 : 0}) scaleY(${open || ['left', 'right'].includes(openDirection) ? 1 : 0})`,\n      transformOrigin: openDirection === 'down' ? 'top' : (openDirection === 'up' ? 'bottom' : openDirection),\n    }\n  }, [openDirection, open]);\n\n  /** inverse size to provide a relative box that matches the parent that the content was calculated against */\n  const containerStyle = useMemo(() => {\n    return {\n      top: `${-area.top / area.height * 100}%`,\n      left: `${-area.left / area.width * 100}%`,\n      height: `${10000 / area.height}%`,\n      width: `${10000 / area.width}%`,\n    }\n  }, [area]);\n\n  const tabStyle = useMemo(() => {\n    if (openDirection === 'down') {\n      return {\n        top: `${open ? 100 : 0}%`,\n        left: 0,\n        width: `100%`,\n      }\n    }\n    if (openDirection === 'up') {\n      return {\n        bottom: `${open ? 100 : 0}%`,\n        left: 0,\n        width: `100%`,\n      }\n    }\n    if (openDirection === 'right') {\n      return {\n        left: `${open ? 100 : 0}%`,\n        bottom: `100%`,\n        width: `${100 / area.width * area.height / aspectRatio}%`,\n        transform: `rotate(90deg)`,\n        transformOrigin: 'bottom left',\n      }\n    }\n    if (openDirection === 'left') {\n      return {\n        right: `${open ? 100 : 0}%`,\n        bottom: `100%`,\n        width: `${100 / area.width * area.height / aspectRatio}%`,\n        transform: `rotate(-90deg)`,\n        transformOrigin: 'bottom right',\n      }\n    }\n  }, [openDirection, aspectRatio, area, open]);\n\n  return (\n    <div className={`drawer open-direction-${openDirection} ${open ? 'open' : 'closed'}`} style={style}>\n      <div\n        className=\"drawer-tab\"\n        style={tabStyle}\n        onClick={() => setOpen(o => !o)}\n      >\n        {open ? tab : closedTab ?? tab}\n      </div>\n      <div className=\"drawer-content\" style={sliderStyle}>\n        <div className=\"drawer-container\" style={containerStyle}>\n          {children.main}\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport default Drawer;\n"
  },
  {
    "path": "src/ui/game/components/Element.tsx",
    "content": "import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';\nimport classNames from 'classnames';\nimport { DraggableCore } from 'react-draggable';\nimport { gameStore } from '../../store.js';\n\nimport {\n  Piece,\n  GameElement,\n  type Game,\n  type Box,\n} from '../../../board/index.js'\nimport Drawer from './Drawer.js';\nimport Tabs from './Tabs.js';\nimport Popout from './Popout.js';\n\nimport type { UIMove } from '../../lib.js';\nimport type { DraggableData, DraggableEvent } from 'react-draggable';\nimport type { DirectedGraph } from 'graphology';\nimport type { UIRender } from '../../render.js';\n\nconst defaultAppearance = (el: GameElement) => <div className=\"bz-default\">{el.toString()}</div>;\n\nconst Element = ({render, mode, onSelectElement, onMouseLeave}: {\n  render: UIRender,\n  mode: 'game' | 'info' | 'zoom'\n  onSelectElement: (moves: UIMove[], ...elements: GameElement[]) => void,\n  onMouseLeave?: () => void,\n}) => {\n\n  const [rendered, setInfoElement, setError, dragElement, setDragElement, dragOffset, dropSelections, currentDrop, setCurrentDrop, placement, setPlacement, selectPlacement, isMobile, dev] =\n    gameStore(s => [s.rendered, s.setInfoElement, s.setError, s.dragElement, s.setDragElement, s.dragOffset, s.dropSelections, s.currentDrop, s.setCurrentDrop, s.placement, s.setPlacement, s.selectPlacement, s.isMobile, s.dev]);\n\n  const [element, branch] = useMemo(() => [render.element, render.element.branch()], [render]);\n  // TODO future style put all store derived values here and add memo()\n  const [boardSelections, isSelected] = gameStore(s => [\n    s.boardSelections[branch],\n    mode === 'game' && (s.selected?.includes(element) || Object.values(s.move?.args || {}).some(a => a === element || a instanceof Array && a.includes(element)))\n  ]);\n  const absolutePosition = useMemo(() => rendered!.all[String(element._t.ref)].pos!, [element, rendered]);\n\n  const [dragging, setDragging] = useState<{ deltaY: number, deltaX: number } | undefined>(); // currently dragging\n  const [positioning, setPositioning] = useState(false); // currently positioning within a placePiece\n  const wrapper = useRef<HTMLDivElement | null>(null);\n  const domElement = useRef<HTMLDivElement>(null);\n\n  const appearance = element._ui.appearance.render || (element.game._ui.disabledDefaultAppearance ? () => null : defaultAppearance);\n\n  const invalidSelectionError = mode === 'game' && boardSelections?.error;\n  const clickable = mode === 'game' && !invalidSelectionError && !dragElement && boardSelections?.clickMoves.length;\n  const selectable = mode === 'game' && !invalidSelectionError && !dragElement && boardSelections?.clickMoves.filter(m => m.name.slice(0, 4) !== '_god').length;\n  const draggable = mode === 'game' && !invalidSelectionError && !!boardSelections?.dragMoves?.length; // ???\n  const droppable = mode === 'game' && dropSelections.some(move => move.selections[0].resolvedChoices?.find(c => c.choice === element));\n  const placing = useMemo(() => element === placement?.piece && !placement?.selected, [element, placement])\n  const gridSizeNeeded = useMemo(() => (\n    placement?.into._sizeNeededFor(placement.piece) ?? {width: 1, height: 1}\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  ), [placement?.piece.rotation, placement?.piece.row, placement?.piece.column, placement?.into]);\n\n  const attrs = render.previousDataAttributes || render.dataAttributes;\n\n  // directly on the dom: remove the temporary transform-to-old position and set all new attr's\n  useEffect(() => {\n    const node = wrapper.current;\n    if (node?.style.getPropertyValue('--transformed-to-old')) {\n      //console.log('transform remove', element.branch(), node.style.getPropertyValue('transform'), render.previousDataAttributes);\n      node.style.removeProperty('--transformed-to-old');\n      if (domElement.current && render.previousDataAttributes) {\n        for (const [k, v] of Object.entries(render.dataAttributes!)) domElement.current.setAttribute(k, v);\n        for (const attr of domElement.current.getAttributeNames()) {\n          if (attr.slice(0, 5) === 'data-' && render.dataAttributes![attr] === undefined) {\n            domElement.current.removeAttribute(attr);\n          }\n        }\n        if (render.effectClasses !== undefined) {\n          domElement.current.setAttribute('class', domElement.current.getAttribute('class') + ' ' + render.effectClasses);\n        }\n        delete render.previousAttributes;\n        delete render.previousDataAttributes;\n      }\n      if (node.style.getPropertyValue('transform')) {\n        node?.scrollTop; // force reflow\n        // move to 'new' by removing transform and animate\n        node.classList.add('animating');\n        if (render.crossParent) node.classList.add('cross-parent');\n        node.style.removeProperty('transition');\n        node.style.removeProperty('transform');\n        const cancel = (e: TransitionEvent) => {\n          if (e.propertyName === 'transform' && e.target === node) {\n            node.classList.remove('animating', 'cross-parent');\n            node.removeEventListener('transitionend', cancel);\n            if (render.proxy && domElement.current) {\n              domElement.current.style.transform = (domElement.current.style.transform ?? '') + ' scale(0)';\n            }\n          }\n        };\n        node.addEventListener('transitionend', cancel);\n        if (render.styles?.transform) delete render.styles.transform;\n      }\n    }\n    delete render.mutated;\n  }, [element, render]);\n\n  useEffect(() => {\n    if (dragging && dragElement !== branch) setDragging(undefined);\n  }, [dragging, dragElement, branch]);\n\n  const handleClick = useCallback((e: React.MouseEvent | MouseEvent) => {\n    e.stopPropagation();\n    if (placing) {\n      selectPlacement({column: element.column!, row: element.row!, rotation: element._rotation});\n    } else if (invalidSelectionError) {\n      setError(invalidSelectionError)\n    } else {\n      onSelectElement(boardSelections.clickMoves, element);\n    }\n  }, [element, onSelectElement, boardSelections, placing, invalidSelectionError, setError, selectPlacement]);\n\n  const handleDragStart = useCallback((e: DraggableEvent, data: DraggableData) => {\n    e.stopPropagation();\n    if (wrapper.current) {\n      wrapper.current.setAttribute('data-lastx', String(data.lastX));\n      wrapper.current.setAttribute('data-lasty', String(data.lastY))\n    }\n  }, [wrapper]);\n\n  const handleDrag = useCallback((e: DraggableEvent, data: DraggableData) => {\n    e.stopPropagation();\n    if (wrapper.current) {\n      const deltaY = parseInt(wrapper.current.getAttribute('data-lasty') || '') - data.y;\n      const deltaX = parseInt(wrapper.current.getAttribute('data-lastx') || '') - data.x;\n      if (Math.abs(deltaX) + Math.abs(deltaY) > 5) {\n        if (branch !== dragElement) setDragElement(branch);\n        setDragging({deltaY, deltaX});\n      }\n    }\n  }, [wrapper, branch, dragElement, setDragElement]);\n\n  const handleDragStop = useCallback((e: DraggableEvent, data: DraggableData) => {\n    e.stopPropagation();\n    if (dragging) {\n      if (currentDrop) {\n        if (wrapper.current) {\n          dragOffset.ref = element._t.ref;\n          dragOffset.x = data.x - parseInt(wrapper.current.getAttribute('data-lastx') || '');\n          dragOffset.y = data.y - parseInt(wrapper.current.getAttribute('data-lasty') || '');\n        }\n        const move = dropSelections.find(move => move.selections[0].resolvedChoices?.find(c => c.choice === currentDrop));\n        if (move) {\n          onSelectElement([move], currentDrop);\n          return;\n        } else if (wrapper.current && render.styles) {\n          wrapper.current.style.top = render.styles.top as string;\n          wrapper.current.style.left = render.styles.left as string;\n        }\n      }\n      setDragging(undefined);\n      setCurrentDrop(undefined);\n      setDragElement(undefined);\n    }\n  }, [dragging, wrapper, render, currentDrop, dropSelections, onSelectElement, setDragElement, setCurrentDrop, dragOffset, element._t.ref]);\n\n  const handleMouseEnter = useCallback(() => {\n    if (droppable) setCurrentDrop(element);\n  }, [droppable, element, setCurrentDrop]);\n\n  const handleMouseLeave = useCallback(() => {\n    if (droppable) {\n      setCurrentDrop(undefined);\n      if (onMouseLeave) onMouseLeave();\n    }\n  }, [droppable, setCurrentDrop, onMouseLeave]);\n\n  const handlePlacement = useCallback((event: React.MouseEvent) => {\n    const rect = wrapper.current?.getBoundingClientRect();\n    if (!rect || !placement) return;\n    const layout = placement.layout;\n    if (!layout) return;\n    const {area, grid} = layout;\n    if (!grid || !area) return;\n\n    const pointer = {\n      column: ((event.clientX - rect.x) / rect.width * 100 - grid.anchor.x - area.left) / grid.offsetColumn.x + grid.origin.column,\n      row: ((event.clientY - rect.y) / rect.height * 100 - grid.anchor.y - area.top) / grid.offsetRow.y + grid.origin.row\n    };\n\n    let newPlacement: {column: number, row: number};\n    if (placement.piece.row === undefined || placement.piece.column === undefined) {\n      newPlacement = {\n        column: Math.round(pointer.column - gridSizeNeeded.width / 2),\n        row: Math.round(pointer.row - gridSizeNeeded.height / 2),\n      }\n    } else {\n      newPlacement = {column: placement.piece.column, row: placement.piece.row};\n      if (pointer.column < placement.piece.column) {\n        newPlacement.column = Math.max(grid.origin.column, Math.floor(pointer.column));\n      } else if (pointer.column - gridSizeNeeded.width + 1 > placement.piece.column) {\n        newPlacement.column = Math.min(\n          grid.origin.column + grid.columns - gridSizeNeeded.width,\n          Math.floor(pointer.column - gridSizeNeeded.width + 1)\n        );\n      }\n      if (pointer.row < placement.piece.row) {\n        newPlacement.row = Math.max(grid.origin.row, Math.floor(pointer.row));\n      } else if (pointer.row - gridSizeNeeded.height + 1 > placement.piece.row) {\n        newPlacement.row = Math.min(\n          grid.origin.row + grid.rows - gridSizeNeeded.height,\n          Math.floor(pointer.row - gridSizeNeeded.height + 1)\n        );\n      }\n    }\n    if (newPlacement.column !== undefined) {\n      newPlacement.column = Math.max(grid.origin.column,\n        Math.min(grid.origin.column + grid.columns - gridSizeNeeded.width,\n          Math.floor(newPlacement.column)\n        )\n      );\n    }\n    if (newPlacement.row !== undefined) {\n      newPlacement.row = Math.max(grid.origin.row,\n        Math.min(grid.origin.row + grid.rows - gridSizeNeeded.height,\n          Math.floor(newPlacement.row)\n        )\n      );\n    }\n    if (newPlacement.column !== placement.piece.column || newPlacement.row !== placement.piece.row) {\n      setPlacement(newPlacement);\n    }\n\n  }, [placement, setPlacement, gridSizeNeeded])\n\n  const handleRotate = useCallback((direction: number) => {\n    const choices = placement?.rotationChoices;\n    if (!choices) return;\n    let rotation = choices[\n      (choices.indexOf(element.rotation!) + direction + choices.length) % placement!.rotationChoices!.length\n    ];\n    rotation += Math.round(((element._rotation ?? 0) - rotation) / 360) * 360;\n\n    setPlacement({\n      row: element.row ?? 1,\n      column: element.column ?? 1,\n      rotation\n    })\n  }, [element, placement, setPlacement])\n\n  let styles = useMemo(() => {\n    if (mode === 'zoom') return {\n      left: 0,\n      top: 0,\n      width: '100%',\n      height: '100%'\n    }\n\n    let styles = render.styles!;\n    if (positioning) delete styles.transform;\n\n    if (dragging && styles.transform) {\n      styles = {\n        ...styles,\n        top: `calc(${styles.top} - ${dragging.deltaY}px)`,\n        left: `calc(${styles.left} - ${dragging.deltaX}px)`,\n      }\n    }\n\n    if (styles.transform && dragOffset.ref === element._t.ref) {\n      // offset by the last drag position to prevent jump back to original position\n      styles = {\n        ...styles,\n        transform: `translate(${dragOffset.x}px, ${dragOffset.y}px) ` + styles.transform\n      };\n      dragOffset.ref = undefined;\n      dragOffset.x = undefined;\n      dragOffset.y = undefined;\n    }\n\n    return styles;\n  }, [element, render, positioning, dragging, mode, dragOffset]);\n\n  useEffect(() => {\n    if (placing && styles.transform) setPositioning(true);\n  }, [placing, styles.transform]);\n\n  const info = useMemo(() => {\n    if (mode === 'info') {\n      return typeof element._ui.appearance.info === 'function' ? element._ui.appearance.info(element) : element._ui.appearance.info;\n    }\n  }, [mode, element]);\n\n  let contents: React.JSX.Element[] | React.JSX.Element = [];\n  const containerPendingContents: Record<string, React.JSX.Element[]> = {};\n  for (let l = 0; l !== render.layouts.length; l++) {\n    const layout = render.layouts[l]\n    const layoutContents: React.JSX.Element[] = [];\n    for (const render of layout.children) {\n      if (render.proxy !== undefined && !render.mutated) continue;\n      layoutContents.push(\n        <Element\n          key={render.key}\n          render={render}\n          mode={mode === 'zoom' ? 'game' : mode}\n          onMouseLeave={droppable ? () => setCurrentDrop(element) : undefined}\n          onSelectElement={onSelectElement}\n        />\n      );\n    }\n    if (layout.container) {\n      if (layout.container.id) {\n        containerPendingContents[layout?.container.key ?? 'main'] = layoutContents;\n        if (render.layouts.find((layout2, l2) => l2 > l && layout2.container?.id === layout.container?.id)) continue;\n      }\n      const component: React.FC<{} & {\n        game: Game,\n        elements: GameElement[],\n        children: Record<string, JSX.Element[]>,\n        layout: UIRender['layouts'][number],\n        absolutePosition: Box,\n        attributes: any\n      }> = {drawer: Drawer, popout: Popout, tabs: Tabs}[layout.container.type];\n\n      const children = layout.container.id ? containerPendingContents : { main: layoutContents };\n\n      contents.push(React.createElement(component, {\n        key: l,\n        game: element.game,\n        elements: layout.children.map(c => c.element),\n        children,\n        absolutePosition,\n        layout,\n        attributes: layout.container.attributes,\n      }));\n    } else {\n      if (layoutContents.length) contents.push(<div key={l} className=\"layout-wrapper\">{layoutContents}</div>);\n    }\n  }\n\n  if (element._ui.appearance.connections && '_graph' in element) {\n    let { thickness, style, color, fill, label, labelScale } = element._ui.appearance.connections;\n    if (!thickness) thickness = .1;\n    if (!style) style = 'solid';\n    if (!color) color = 'black';\n    if (!fill) color = 'white';\n    if (!labelScale) labelScale = 0.05;\n\n    let i = 0;\n    const lines: React.JSX.Element[] = [];\n    const labels: React.JSX.Element[] = [];\n    (element._graph as DirectedGraph).forEachEdge((...args) => {\n      const source = rendered!.all[args[2]];\n      const target = rendered!.all[args[3]];\n\n      if (source && target) {\n        const origin = {\n          x: (source.relPos!.left + source.relPos!.width / 2) * absolutePosition.width / 100,\n          y: (source.relPos!.top + source?.relPos!.height / 2) * absolutePosition.height / 100\n        }\n        const destination = {\n          x: (target.relPos!.left + target.relPos!.width / 2) * absolutePosition.width / 100,\n          y: (target.relPos!.top + target.relPos!.height / 2) * absolutePosition.height / 100\n        }\n\n        const distance = Math.sqrt(Math.pow(origin.x - destination.x, 2) + Math.pow(origin.y - destination.y, 2))\n\n        if (style === 'double') {\n          lines.push(\n            <line key={i++}\n              className=\"outer\"\n              x1={origin.x} y1={origin.y}\n              x2={destination.x} y2={destination.y}\n              transform={`translate(${(origin.y - destination.y) / distance * thickness!}, ${(origin.x - destination.x) / distance * -thickness!})`}\n              strokeWidth={thickness!} stroke={color}\n            />\n          );\n          lines.push(\n            <line key={i++}\n              className=\"outer\"\n              x1={origin.x} y1={origin.y}\n              x2={destination.x} y2={destination.y}\n              transform={`translate(${(origin.y - destination.y) / distance * -thickness!}, ${(origin.x - destination.x) / distance * thickness!})`}\n              strokeWidth={thickness!} stroke={color}\n            />\n          );\n        }\n        lines.push(\n          <line key={i++}\n            className=\"inner\"\n            x1={origin.x} y1={origin.y}\n            x2={destination.x} y2={destination.y}\n            strokeWidth={2 * thickness!} stroke={fill}\n          />\n        );\n        if (label) {\n          labels.push(\n            <g\n              key={`label${i}`}\n              transform={`translate(${(origin.x + destination.x) / 2 - labelScale! * absolutePosition.width * .5}\n  ${(origin.y + destination.y) / 2 - labelScale! * absolutePosition.height * .5})\n  scale(${labelScale})`}\n            >{label({ distance: args[1].distance, to: args[4].space, from: args[5].space })}</g>);\n        }\n      }\n    });\n    contents.unshift(\n      <svg key=\"svg-edges\" style={{pointerEvents: 'none', position: 'absolute', width: '100%', height: '100%', left: 0, top: 0}} viewBox={`0 0 ${absolutePosition.width} ${absolutePosition.height}`}>{lines}</svg>\n    );\n    if (label) contents.push(\n      <svg key=\"svg-edge-labels\" style={{pointerEvents: 'none', position: 'absolute', width: '100%', height: '100%', left: 0, top: 0}} viewBox={`0 0 ${absolutePosition.width} ${absolutePosition.height}`}>{labels}</svg>\n    );\n  }\n\n  const boundingBoxes = render.layouts?.filter(layout => layout.showBoundingBox).map((layout, k) => (\n    <div key={k} className=\"bz-show-grid\" style={{\n      left: layout.area.left + '%',\n      top: layout.area.top + '%',\n      width: layout.area.width + '%',\n      height: layout.area.height + '%',\n      // backgroundSize: `${(layout.grid?.offsetColumn.x ?? 100) / layout.area.width * 100}% ${(layout.grid?.offsetRow.y ?? 100) / layout.area.height * 100}%`,\n      // backgroundPosition: `calc(${(layout.grid?.anchor.x ?? 0) / layout.area.width * 10000}% - 1px) calc(${(layout.grid?.anchor.y ?? 0) / layout.area.height * 10000}% - 1px)`\n    }}>\n      {typeof layout.showBoundingBox === 'string' && <span>{layout.showBoundingBox}</span>}\n    </div>\n  ));\n\n  let title: string | undefined = undefined;\n  if (dev) {\n    title = `${element.constructor.name} (#${element._t.ref} [${branch}] ${render.key})`;\n    if (element instanceof Piece) {\n      title += `\n  visibility: ${element._visible?.default ?? true ? \"visible\" : \"hidden\"}${element._visible?.except ? ` (except positions ${element._visible?.except.join(', ')})` : \"\"}`;\n    }\n    title += `\n${Object.entries(element.attributeList()).filter(([k, v]) => v !== undefined && !['_size', '_visible', 'was'].includes(k)).map(([k, v]) => `  ${k}: ${typeof v === 'object' && ('isGameElement' in v.constructor || 'isPlayer' in v.constructor) ? v.toString() : JSON.stringify(v)}`).join(\"\\n\")}`;\n  }\n\n  // console.log('RENDER attrs', attrs, styles['--transformed-to-old' as keyof typeof styles]);\n\n  // \"base\" semantic GameElement dom element\n  contents = (\n    <div\n      id={element.name}\n      ref={domElement}\n      title={title}\n      className={classNames(\n        render.classes,\n        {\n          selected: isSelected && mode === 'game',\n          clickable: clickable || invalidSelectionError,\n          invalid: !!invalidSelectionError || (placing && placement?.invalid),\n          selectable,\n          droppable\n        }\n      )}\n      style={render.baseStyles}\n      onClick={clickable || placing || invalidSelectionError ? handleClick : undefined}\n      onMouseEnter={handleMouseEnter}\n      onMouseLeave={handleMouseLeave}\n      onMouseMove={placement?.into === element && !placement.selected ? handlePlacement : undefined}\n      {...attrs}\n    >\n      {appearance(element)}\n      {boundingBoxes}\n      {contents}\n    </div>\n  );\n\n  // wrapper dom element for transforms and animations\n  contents = (\n    <div\n      ref={wrapper}\n      className={classNames(\"transform-wrapper\", { dragging, placing, 'has-info': !!info })}\n      style={styles}\n    >\n      {contents}\n      {!!info && <div className=\"info-hotspot\" onClick={() => setInfoElement({ info, element })}/>}\n    </div>\n  );\n  if (placing && placement?.rotationChoices) {\n    const widthStretch = gridSizeNeeded.width / (element._size?.width ?? 1);\n    const minSquare = Math.min(absolutePosition.width, absolutePosition.height);\n\n    contents = (\n      <>\n        {contents}\n        <div className=\"rotator\" style={{...styles, width: (render.relPos!.width * widthStretch) + '%', fontSize: (0.08 * minSquare) + 'rem', transform: undefined}}>\n          <div className=\"left\" onClick={() => handleRotate(-1)}>\n            <svg\n              viewBox=\"0 0 254.2486 281.95978\"\n              xmlns=\"http://www.w3.org/2000/svg\">\n              <g\n                transform=\"translate(43.69768,-47.016626)\">\n                <path\n                  d=\"m 135.24991,227.00186 -76.975589,76.97558 -76.97559,-76.97558 53.43953,0.48619 c 0,-102.89725 56.23959,-155.471424 150.812659,-155.471424 l -0.0693,38.606184 c -67.82216,0 -113.184769,38.35922 -113.184769,117.17431 z\"\n                />\n              </g>\n            </svg>\n          </div>\n          <div className=\"right\" onClick={() => handleRotate(1)}>\n            <svg\n              viewBox=\"0 0 254.2486 281.95978\"\n              xmlns=\"http://www.w3.org/2000/svg\">\n              <g\n                transform=\"translate(210,-47.016626) scale(-1 1)\">\n                <path\n                  d=\"m 135.24991,227.00186 -76.975589,76.97558 -76.97559,-76.97558 53.43953,0.48619 c 0,-102.89725 56.23959,-155.471424 150.812659,-155.471424 l -0.0693,38.606184 c -67.82216,0 -113.184769,38.35922 -113.184769,117.17431 z\"\n                />\n              </g>\n            </svg>\n          </div>\n        </div>\n      </>\n    );\n  }\n\n  if (!isMobile && element instanceof Piece) {\n    contents = (\n      <DraggableCore\n        disabled={!draggable}\n        onStart={handleDragStart}\n        onDrag={handleDrag}\n        onStop={handleDragStop}\n      >\n        {contents}\n      </DraggableCore>\n    );\n  }\n\n  return contents;\n}// , (prevProps, props) => {\n//   const m = !props.render.mutated && prevProps.mode === props.mode;\n//   console.log(m, props);\n//   return true;\n// })\n\nexport default Element;\n"
  },
  {
    "path": "src/ui/game/components/FlowDebug.tsx",
    "content": "import React from 'react';\nimport type { FlowVisualization } from '../../../flow/flow.js';\n\nconst colors = ['#900', '#060', '#009', '#606']\n\nconst FlowDebug = ({ flow, nest, current }: {\n  flow: FlowVisualization,\n  nest: number,\n  current: boolean\n}) => (\n  <>\n    <div\n      className={`flow-debug-block ${current && !flow.current.block ? 'current' : ''}`}\n      style={{['--color' as string]: colors[nest % 4], color: colors[nest % 4]}}\n    >\n      <div className=\"header\">\n        <span className=\"type\">{flow.type}</span>\n        {(flow.name || flow.current.position !== undefined) && (\n          <span className=\"name\">{flow.name}{flow.name && flow.current.position !== undefined && ' = '}{flow.current.position !== undefined && String(flow.current.position)}</span>\n        )}\n      </div>\n      {Object.entries(flow.blocks).map(([name, block]) => (\n        <div key={name} className=\"do-block\">\n          <div className=\"name\">{name}</div>\n          {block?.map((step, seq) => {\n            const nextCurrent = current && name === flow.current.block && seq === (flow.current.sequence ?? 0);\n            return typeof step === 'string' ?\n              <div key={seq} className={`function ${nextCurrent ? 'current' : ''}`} title={step}>{step.trim().slice(0, 200)}</div> :\n              <FlowDebug key={seq} flow={step} nest={nest + 1} current={nextCurrent}/>\n          })}\n        </div>\n      ))}\n    </div>\n  </>\n);\n\nexport default FlowDebug;\n"
  },
  {
    "path": "src/ui/game/components/InfoOverlay.tsx",
    "content": "import React, { useMemo, useState, useEffect, useCallback } from 'react';\nimport { gameStore } from '../../store.js';\nimport Element from './Element.js';\n\nconst InfoOverlay = ({ setMode }: {\n  setMode: (mode: 'info' | 'game' | 'debug') => void;\n}) => {\n  const [collapsed, setCollapsed] = useState(false);\n  const [infoModal, setInfoModal] = useState<number | undefined>(undefined);\n\n  const [gameManager, rendered, infoElement, setInfoElement, actionDescription] = gameStore(s => [s.gameManager, s.rendered, s.infoElement, s.setInfoElement, s.actionDescription]);\n  useEffect(() => setInfoElement(), [setInfoElement]);\n\n  let elementStyle: React.CSSProperties | undefined = useMemo(() => {\n    if (!infoElement?.element) return {};\n    const scale = rendered!.all[String(infoElement.element._t.ref)].pos!\n    let fontSize = 32 * 0.04;\n    const aspectRatio = scale.width / scale.height;\n\n    if (aspectRatio > 1) {\n      scale.width = 100;\n      fontSize /= aspectRatio;\n    } else {\n      scale.width *= 100 / scale.height;\n    }\n    return {\n      width: scale.width + '%',\n      aspectRatio,\n      fontSize: fontSize + 'rem',\n    };\n  }, [rendered, infoElement?.element]);\n\n  const close = useCallback(() => {\n    if (infoElement || infoModal !== undefined) {\n      setInfoElement();\n      setInfoModal(undefined);\n    } else {\n      setMode('game');\n    }\n  }, [infoElement, infoModal, setInfoElement, setInfoModal, setMode]);\n\n  useEffect(() => {\n    const keydownHandler = (e: KeyboardEvent) => {\n      if (e.repeat) return;\n      if (e.code === 'Escape') close();\n    };\n    window.addEventListener('keydown', keydownHandler);\n    return () => window.removeEventListener('keydown', keydownHandler);\n  }, [close]);\n\n  return (\n    <>\n      <div id=\"info-overlay\" className=\"full-page-cover\" onClick={close}/>\n      <div id=\"info-container\" className=\"full-page-cover\">\n        <div id=\"info-drawer\" className={collapsed ? 'collapsed' : ''}>\n          <div className=\"header\">\n            <div className=\"title\">\n              <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 100 100\" onClick={() => { setMode('game'); setInfoElement(); setInfoModal(undefined) }}>\n                <path fill=\"black\" d=\"M50.433,0.892c-27.119,0-49.102,21.983-49.102,49.102s21.983,49.103,49.102,49.103s49.101-21.984,49.101-49.103S77.552,0.892,50.433,0.892z M59,79.031C59,83.433,55.194,87,50.5,87S42,83.433,42,79.031V42.469c0-4.401,3.806-7.969,8.5-7.969s8.5,3.568,8.5,7.969V79.031z M50.433,31.214c-5.048,0-9.141-4.092-9.141-9.142c0-5.049,4.092-9.141,9.141-9.141c5.05,0,9.142,4.092,9.142,9.141C59.574,27.122,55.482,31.214,50.433,31.214z\"/>\n              </svg>\n            </div>\n            <div className=\"controls\">\n              <svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" onClick={() => setCollapsed(!collapsed)}>\n                <g data-name=\"Layer 2\">\n                  <g data-name=\"collapse\">\n                    <path fill=\"black\" d=\"M19 9h-2.58l3.29-3.29a1 1 0 1 0-1.42-1.42L15 7.57V5a1 1 0 0 0-1-1 1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h5a1 1 0 0 0 0-2z\"/>\n                    <path fill=\"black\" d=\"M10 13H5a1 1 0 0 0 0 2h2.57l-3.28 3.29a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0L9 16.42V19a1 1 0 0 0 1 1 1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1z\"/>\n                  </g>\n                </g>\n              </svg>\n            </div>\n          </div>\n          {!collapsed && (\n            <>\n              <div className=\"contents\">\n                <h1>Currently</h1>\n                <ul>\n                  {gameManager.messages.map((m, i) => {\n                    const player = m.body.match(/\\[\\[\\$p\\[(\\d+)/);\n                    let color: string | undefined = undefined;\n                    if (player) {\n                      color = gameManager.players.atPosition(parseInt(player[1]))?.color;\n                    }\n                    return (\n                      <li style={{color}} key={i}>\n                        <span dangerouslySetInnerHTML={{ __html: m.body.replace(/\\[\\[[^|]*\\|(.*?)\\]\\]/g, '$1')}}/>\n                      </li>\n                    );\n                  })}\n                  {actionDescription && (\n                    <li style={{color: gameManager.players.allCurrent()[0]?.color}}>\n                      <span>{actionDescription}</span>\n                    </li>\n                  )}\n                </ul>\n              </div>\n              <div className=\"contents\">\n                <h1>More game info</h1>\n                {gameManager.game._ui.infoModals?.\n                  filter(({ condition }) => !condition || condition(gameManager.game)).\n                  map(({ title }, key) => (\n                    <button key={key} className=\"info-modal-title\" onClick={() => { setInfoElement(); setInfoModal(key) }}>\n                      {title}\n                    </button>\n                ))}\n                <div className=\"more-info\">See more detail by clicking on highlighted items.</div>\n              </div>\n            </>\n          )}\n        </div>\n\n        {(!!infoElement || infoModal !== undefined) && (\n          <div id=\"info-modal\" className={`modal-popup ${infoElement ? 'info-element' : ''}`}>\n            {infoElement && (\n              <>\n                {infoElement.element && (\n                  <div className=\"element-zoom\">\n                    <div style={elementStyle}>\n                      <Element\n                        render={rendered!.all[infoElement!.element!._t.ref]}\n                        mode='zoom'\n                        onSelectElement={() => {}}\n                      />\n                    </div>\n                  </div>\n                )}\n                <span className=\"info-text\">\n                  {infoElement.element && <h1>{`${infoElement.element}`}</h1>}\n                  {typeof infoElement.info !== 'boolean' && infoElement.info}\n                </span>\n              </>\n            )}\n            {!infoElement && (\n              gameManager.game._ui.infoModals[infoModal!].modal(gameManager.game)\n            )}\n          </div>\n        )}\n      </div>\n    </>\n  );\n}\n\nexport default InfoOverlay;\n"
  },
  {
    "path": "src/ui/game/components/PlayerControls.tsx",
    "content": "import React from 'react';\nimport { gameStore } from '../../store.js';\nimport ActionForm from './ActionForm.js';\n\nimport type { UIMove } from '../../lib.js';\nimport type { Argument } from '../../../action/action.js';\n\nconst PlayerControls = ({onSubmit}: {\n  onSubmit: (move?: UIMove, args?: Record<string, Argument>) => void,\n}) => {\n  const [position, controls, boardPrompt, error, disambiguateElement, cancellable] = gameStore(s => [s.position, s.controls, s.boardPrompt, s.error, s.disambiguateElement, s.cancellable]);\n\n  if (!position || !controls) return null;\n  if (!boardPrompt && controls.moves.length === 0) return null;\n\n  let visibleAction = !!boardPrompt && !disambiguateElement;\n\n  return (\n    <div key={controls.name} className={`player-controls ${controls.name.replace(\":\", \"-\")}`} style={controls.style}>\n\n      {boardPrompt && <div className=\"prompt\">{boardPrompt === '__missing__' ? 'Your move' : boardPrompt}</div>}\n\n      {controls.moves.map((pendingMove, i) => {\n        let actionDivider = false;\n        if (pendingMove.prompt || disambiguateElement || !pendingMove.selections[0]?.isBoardChoice()) {\n          actionDivider = visibleAction;\n          visibleAction = true;\n        }\n        return (\n          <React.Fragment key={i}>\n            {actionDivider && <div className=\"action-divider\">or</div>}\n            <ActionForm\n              move={pendingMove}\n              stepName={controls.name}\n              onSubmit={onSubmit}\n            />\n          </React.Fragment>\n        );\n      })}\n\n      {error && <div className=\"error\">{error}</div>}\n\n      {(cancellable || disambiguateElement) && (\n        <>\n          {visibleAction && <div className=\"action-divider\">or</div>}\n          <button className=\"cancel\" onClick={() => onSubmit()}>Cancel</button>\n        </>\n      )}\n    </div>\n  )\n};\n\nexport default PlayerControls;\n"
  },
  {
    "path": "src/ui/game/components/Popout.tsx",
    "content": "import React, { ReactNode, useEffect, useMemo, useState } from 'react';\n\nimport type { UIRender } from '../../render.js';\n\nconst Popout = ({ layout, children, attributes }: {\n  layout: UIRender['layouts'][number],\n  children: Record<string, JSX.Element[]>,\n  attributes: {\n    button: ReactNode,\n    popoutMargin?: number | { top: number, bottom: number, left: number, right: number },\n  }\n}) => {\n  const [open, setOpen] = useState(false);\n  const area = useMemo(() => layout?.area ?? {top: 0, left: 0, width: 100, height: 100}, [layout])\n\n  const style = useMemo(() => {\n    return {\n      top: area.top + '%',\n      left: area.left + '%',\n      height: area.height + '%',\n      width: area.width + '%',\n      fontSize: layout.area.height + '%',\n    }\n  }, [area, layout]);\n\n  const popoutStyle = useMemo(() => {\n    return { inset: attributes.popoutMargin === undefined ? '4vmin' : (typeof attributes.popoutMargin === 'number' ? `${attributes.popoutMargin}vmin` : `${attributes.popoutMargin.top}vmin ${attributes.popoutMargin.right}vmin ${attributes.popoutMargin.bottom}vmin ${attributes.popoutMargin.left}vmin`) };\n  }, [attributes.popoutMargin]);\n\n  useEffect(() => {\n    const keydownHandler = (e: KeyboardEvent) => {\n      if (e.repeat) return;\n      if (e.code === 'Escape') setOpen(false);\n    };\n    window.addEventListener('keydown', keydownHandler);\n    return () => window.removeEventListener('keydown', keydownHandler);\n  }, [setOpen]);\n\n  return (\n    <div className=\"popout-container\" style={style}>\n      <div className=\"popout-button\" onClick={() => open || setOpen(true)}>{attributes.button}</div>\n      {open && (\n        <div className=\"full-page-cover\" onClick={() => setOpen(false)}>\n          <div className=\"popout-modal\" onClick={e => e.stopPropagation()} style={popoutStyle}>\n            {children.main}\n            <svg className=\"popout-close\" onClick={() => setOpen(false)} xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\">\n              <circle cx=\"12\" cy=\"12\" r=\"10\"></circle>\n              <line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\"></line>\n              <line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\"></line>\n            </svg>\n          </div>\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport default Popout;\n"
  },
  {
    "path": "src/ui/game/components/ProfileBadge.tsx",
    "content": "import React from 'react';\n\nimport Player from '../../../player/player.js';\nimport { gameStore } from '../../store.js';\nimport classNames from 'classnames';\n\n/**\n * Component for rendering a Player's name and avatar in their color. Also\n * capture online status and displays (as `className` `\"online\"`) and flashes\n * when the player is the current player (`className` `\"current\"`).\n *\n * @category UI\n */\nexport function ProfileBadge({player}: {player: Player}) {\n  const [userOnline] = gameStore(s => [s.userOnline]);\n  const online = userOnline.has(player.id)\n  return (\n    <div className={classNames(\"profile-badge\", {online, current: player.isCurrent()})} data-position={player.position} style={{backgroundColor: player.color}}>\n      <div className=\"avatar\"><img src={player.avatar} /></div>\n      <div className=\"player-name\">{player.name}</div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "src/ui/game/components/Selection.tsx",
    "content": "import React from 'react';\n\nimport type { ResolvedSelection } from '../../../action/selection.js';\nimport type { Argument } from '../../../action/action.js';\n\nconst Selection = ({selection, value, error, setErrors, onChange} : {\n  selection: ResolvedSelection,\n  value: Argument | undefined,\n  error?: string,\n  setErrors: (errors: Record<string, string>) => void,\n  onChange: (value: Argument) => void\n}) => (\n  <div className={`selection ${selection.name}`}>\n    {selection.prompt && selection.type !== 'button' && <span className=\"prompt\">{selection.prompt}</span>}\n\n    {selection.type === 'choices' && selection.resolvedChoices?.map(choice => (\n      <button\n        type=\"button\"\n        className={choice.error ? 'invalid' : choice.choice === value ? 'selected' : ''}\n        key={String(choice)}\n        onClick={() => choice.error ? setErrors({ [String(selection.name)]: choice.error }) : onChange(choice.choice)}\n      >\n        {String(choice.label ?? choice.choice)}\n      </button>\n    ))}\n\n    {selection.type === 'number' && (\n      <input\n        name={selection.name}\n        type=\"number\"\n        min={selection.min ?? 1}\n        max={selection.max}\n        onChange={e => onChange(parseInt(e.target.value))}\n        value={String(value)}\n        autoComplete='off'\n      />\n    )}\n\n    {selection.type === 'text' && (\n      <input\n        name={selection.name}\n        onChange={e => onChange(e.target.value)}\n        value={String(value)}\n        autoComplete='off'/>\n    )}\n\n    {selection.type === 'button' &&\n      <button name={selection.name} value='confirm' type=\"submit\">{selection.prompt ?? String(selection.value)}</button>\n    }\n\n    {error && <div className=\"error\">{error}</div>}\n  </div>\n);\n\nexport default Selection;\n"
  },
  {
    "path": "src/ui/game/components/Tabs.tsx",
    "content": "import React, { useEffect, useMemo, useState } from 'react';\nimport { gameStore } from '../../store.js';\n\nimport type { Argument } from '../../../action/action.js';\nimport type { Box, LayoutAttributes } from '../../../board/element.js';\n\nconst Tabs = ({ layout, absolutePosition, children, attributes }: {\n  layout: Partial<LayoutAttributes>,\n  absolutePosition: Box,\n  children: Record<string, JSX.Element[]>,\n  attributes: {\n    tabs: Record<string, React.ReactNode>\n    tabDirection: 'up' | 'down' | 'left' | 'right',\n    setTabTo?: (actions: { name: string, args: Record<string, Argument> }[]) => string,\n  }\n}) => {\n  const [openTab, setOpenTab] = useState(Object.keys(children)[0]);\n  const [pendingMoves] = gameStore(s => [s.pendingMoves]);\n  const { tabs, tabDirection, setTabTo } = attributes;\n\n  const area = useMemo(() => layout?.area ?? {top: 0, left: 0, width: 100, height: 100}, [layout])\n  const aspectRatio = useMemo(() => absolutePosition ? absolutePosition.width / absolutePosition.height : 1, [absolutePosition])\n\n  useEffect(() => {\n    const actions = pendingMoves?.map(m => ({ name: m.name, args: m.args })) ?? [];\n\n    const newTab = setTabTo?.(actions);\n    if (newTab) setOpenTab(newTab);\n  }, [setTabTo, setOpenTab, pendingMoves]);\n\n  const style = useMemo(() => {\n    return {\n      top: area.top + '%',\n      left: area.left + '%',\n      height: area.height + '%',\n      width: area.width + '%',\n    }\n  }, [area]);\n\n  /** inverse size to provide a relative box that matches the parent that the content was calculated against */\n  const containerStyle = useMemo(() => {\n    return {\n      top: `${-area.top / area.height * 100}%`,\n      left: `${-area.left / area.width * 100}%`,\n      height: `${10000 / area.height}%`,\n      width: `${10000 / area.width}%`,\n    }\n  }, [area]);\n\n  const tabStyle = useMemo(() => {\n    if (tabDirection === 'down') {\n      return {\n        top: `100%`,\n        left: 0,\n        width: `100%`,\n      }\n    }\n    if (tabDirection === 'up') {\n      return {\n        bottom: `100%`,\n        left: 0,\n        width: `100%`,\n      }\n    }\n    if (tabDirection === 'right') {\n      return {\n        left: `100%`,\n        bottom: `100%`,\n        width: `${100 / area.width * area.height / aspectRatio}%`,\n        transform: `rotate(90deg)`,\n        transformOrigin: 'bottom left',\n      }\n    }\n    if (tabDirection === 'left') {\n      return {\n        right: `100%`,\n        bottom: `100%`,\n        width: `${100 / area.width * area.height / aspectRatio}%`,\n        transform: `rotate(-90deg)`,\n        transformOrigin: 'bottom right',\n      }\n    }\n  }, [tabDirection, aspectRatio, area]);\n\n  return (\n    <div className={`drawer open-direction-${tabDirection}`} style={style}>\n      <div\n        className=\"drawer-tab multi\"\n        style={tabStyle}\n      >\n        {Object.entries(tabs).map(([key, tab]) => (\n          <div key={key} className={`tabs-tab ${openTab === key ? 'active' : ''}`} onClick={() => {console.log(key);setOpenTab(key)}}>{tab}</div>\n        ))}\n      </div>\n      <div className=\"drawer-content\">\n        <div className=\"drawer-container\" style={containerStyle}>\n          {openTab}\n          {children[openTab]}\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport default Tabs;\n"
  },
  {
    "path": "src/ui/index.tsx",
    "content": "import React from 'react'\nimport { createRoot } from 'react-dom/client';\nimport { gameStore } from './store.js';\nimport Main from './Main.js'\nimport { Game } from '../board/index.js'\nimport './assets/index.scss';\n\nimport type { SetupFunction } from '../game-creator.js'\nimport type { BoardSizeMatcher } from '../board/game.js';\nimport type { SetupComponentProps } from './setup/components/settingComponents.js';\n\nexport { ProfileBadge } from './game/components/ProfileBadge.js';\nexport {\n  toggleSetting,\n  numberSetting,\n  textSetting,\n  choiceSetting\n} from './setup/components/settingComponents.js';\n\n/**\n * The core function called to customize the game's UI.\n *\n * @param {Object} options\n * @param options.settings - Define your game's settings that the host can\n * customize.  This is an object consisting of custom settings. The key is a\n * name for this setting that can be used in {@link Game#setting} to retrieve\n * the setting's value for this game. The object is the result of calling one of\n * the setting functions {@link toggleSetting}, {@link numberSetting}, {@link\n * textSetting} or {@link choiceSetting}.\n *\n * @param options.boardSizes - An array of possible boardsizes depending on the\n * device type and viewport of the player. Each item in the list is a possible\n * board size and must include at least a unique `name` and an\n * `aspectRatio`. When a player joins, or resizes their screen, a layout will be\n * chosen that meets the conditions given and is the closest fit.\n * <ul>\n\n * <li>`name`: A unique name used to identify this board size. The name of the\n * layout chosen for the player will be passed to the `layout` function below.\n * <li>`aspectRatio`: The aspect ratio for this board size. Either a number (width\n * / height), or an object with keys `min` and `max` with numbers that give a\n * a possible range of aspect ratios. If providing a range, any aspect ratio\n * within the range could be selected if it's a match for the player's\n * viewport. You must ensure your game layout looks correct for the entire range\n * provided.\n * <li>`mobile`: If true, this layout will only be used for mobile devices. If\n * false, this layout will not be used for mobile devices. If blank, it may be\n * used in any case.\n * <li>`desktop`: If true, this layout will only be used for desktop screens. If\n * false, this layout will not be used for desktop. If blank, it may be used in\n * any case.\n * <li>`orientation`: If supplied, the layout will match a mobile screen size if\n * either orientation matches the aspect ratio. if chosen as the best match\n * board size, the player's screen will be locked to the given orientation.\n * <li>`scaling`: Specifies how the screen should fit the board if it is not a\n * perfect fit for the aspect ratio. If 'fit' the board size will be fit within\n * the screen, with blank space on the sides or top and bottom. If 'scroll', the\n * board will be fit to maximize it's space and scroll vertically or\n * horizontally.\n * </ul>\n *\n * @param options.layout - A function for declaring all UI customization in the\n * game. The function will receives 3 arguments:\n * <ul>\n * <li>`game`: The {@link Game} instance.\n * <li>`player`: The {@link Player} who is viewing.\n * <li>`boardSize`: The name of the selected `boardSize` from above.\n * </ul>\n * Typically this will include calls to {@link GameElement#layout}, {@link\n * GameElement#appearance}, {@link Game#layoutStep} and {@link\n * Game#layoutAction}.\n *\n * @param options.announcements - A list of announcements. Each is a function\n * that accepts the {@link Game} object and returns the JSX of the\n * announcement. These can be called from {@link Game#announce} or {@link\n * Game#finish}.\n *\n * @param options.infoModals - A list of informational panels that appear in the\n * info sidebar. Each is an object with:\n * <ul>\n * <li>title: The title shown in the sidebar\n * <li>modal: a function that accepts the {@link Game} object and returns the JSX\n *   of the modal.\n * <li>condition: An optional condition function that accepts the {@link Game}\n *   object and returns as a boolean whether the modal should be currently\n *   available\n * </ul>\n *\n * @category UI\n */\nexport const render = <G extends Game>(setup: SetupFunction<G>, options: {\n  settings?: Record<string, (p: SetupComponentProps) => JSX.Element>\n  boardSizes?: BoardSizeMatcher[],\n  layout?: (game: G, player: NonNullable<G['player']>, boardSize: string) => void,\n  announcements?: Record<string, (game: G) => JSX.Element>\n  infoModals?: {title: string, modal: (game: G) => JSX.Element}[]\n}): void => {\n  let { settings, boardSizes, layout, announcements, infoModals } = options;\n  const state = gameStore.getState();\n  const setupGame: SetupFunction<G> = state => {\n    const gameManager = setup(state);\n    boardSizes ??= [{name: '_default', aspectRatio: 1}];\n    const bothOrientations = boardSizes.some(bs => bs.orientation === 'landscape') && boardSizes.some(bs => bs.orientation === 'portrait');\n    const bss = boardSizes.map(bs => ({\n      ...bs,\n      aspectRatio: typeof bs.aspectRatio === 'number' ? bs.aspectRatio : { min: Math.min(bs.aspectRatio.min, bs.aspectRatio.max), max: Math.max(bs.aspectRatio.min, bs.aspectRatio.max) }\n    }))\n    gameManager.game._ui.boardSizes = (screenX, screenY, mobile) => {\n      let screenAspectRatio = screenX / screenY;\n      let flipped: boolean | undefined = undefined;\n      let portrait = screenAspectRatio;\n      let landscape = screenAspectRatio;\n      if (mobile && !bothOrientations) {\n        if (screenAspectRatio < 1) {\n          landscape = 1 / screenAspectRatio;\n        } else {\n          portrait = 1 / screenAspectRatio;\n        }\n      }\n      const boardSize = bss.filter(\n        bs => (bs.mobile ?? mobile) === mobile && (bs.desktop ?? !mobile) === !mobile\n      ).sort(\n        (bs1, bs2) => {\n          const d1 = Math.max(\n            (typeof bs1.aspectRatio === 'number' ? bs1.aspectRatio : bs1.aspectRatio.min) - (bs1.orientation === 'landscape' ? landscape : (bs1.orientation === 'portrait' ? portrait : screenAspectRatio)),\n            (bs1.orientation === 'landscape' ? landscape : (bs1.orientation === 'portrait' ? portrait : screenAspectRatio)) - (typeof bs1.aspectRatio === 'number' ? bs1.aspectRatio : bs1.aspectRatio.max)\n          );\n          const d2 = Math.max(\n            (typeof bs2.aspectRatio === 'number' ? bs2.aspectRatio : bs2.aspectRatio.min) - (bs2.orientation === 'landscape' ? landscape : (bs2.orientation === 'portrait' ? portrait : screenAspectRatio)),\n            (bs2.orientation === 'landscape' ? landscape : (bs2.orientation === 'portrait' ? portrait : screenAspectRatio)) - (typeof bs2.aspectRatio === 'number' ? bs2.aspectRatio : bs2.aspectRatio.max)\n          );\n          return d1 > d2 ? 1 : -1;\n        }\n      )[0];\n      if (boardSize.orientation === 'landscape' && screenAspectRatio < 1 || boardSize.orientation === 'portrait' && screenAspectRatio > 1) {\n        screenAspectRatio = 1 / screenAspectRatio;\n        flipped = true;\n      }\n      let boardAspectRatio: number;\n      let aspectRatioWidened: number;\n      if (typeof boardSize.aspectRatio === 'number') {\n        boardAspectRatio = boardSize.aspectRatio;\n        aspectRatioWidened = 1;\n      } else {\n        boardAspectRatio = Math.min(boardSize.aspectRatio.max, Math.max(boardSize.aspectRatio.min, screenAspectRatio));\n        aspectRatioWidened = boardAspectRatio / boardSize.aspectRatio.min\n      }\n      const boundByWidth = (screenAspectRatio < boardAspectRatio) !== (boardSize.scaling === 'scroll');\n      const frame = boardAspectRatio > 1 ? {\n        x: 100 * aspectRatioWidened,\n        y: 100 / boardAspectRatio * aspectRatioWidened\n      } : {\n        x: 100 * boardAspectRatio * aspectRatioWidened,\n        y: 100 * aspectRatioWidened\n      };\n      const screen = boundByWidth ? {\n        x: frame.x,\n        y: frame.x / screenAspectRatio\n      } : {\n        x: frame.y * screenAspectRatio,\n        y: frame.y\n      }\n      return {\n        ...boardSize,\n        aspectRatio: boardAspectRatio,\n        flipped,\n        frame,\n        screen\n      };\n    }\n    gameManager.game._ui.setupLayout = layout;\n    gameManager.game._ui.announcements = announcements ?? {};\n    gameManager.game._ui.infoModals = infoModals ?? [];\n    return gameManager;\n  }\n  // we can anonymize Player class internally\n  state.setSetup(setupGame);\n\n  const boostrap = JSON.parse(document.body.getAttribute('data-bootstrap-json') || '{}');\n  const { host, userID, minPlayers, maxPlayers, defaultPlayers, dev }: {\n    host: boolean,\n    userID: string,\n    minPlayers: number,\n    maxPlayers: number,\n    defaultPlayers: number,\n    dev?: boolean\n  } = boostrap;\n  state.setHost(host);\n  state.setDev(dev);\n  state.setUserID(userID);\n\n  const root = createRoot(document.getElementById('root')!)\n  root.render(\n    <Main\n      minPlayers={minPlayers}\n      maxPlayers={maxPlayers}\n      defaultPlayers={defaultPlayers}\n      setupComponents={settings || {}}\n    />\n  );\n};\n"
  },
  {
    "path": "src/ui/lib.ts",
    "content": "import { SerializedArg, serializeArg } from '../action/utils.js';\nimport Selection from '../action/selection.js'\nimport { GameElement, Piece } from '../board/index.js'\nimport { applyDiff, applyLayouts } from './render.js';\nimport { createContext } from 'react';\n\nimport type { CSSProperties } from 'react'\nimport type { GameStore } from './store.js';\nimport type { default as GameManager, SerializedMove, PendingMove } from '../game-manager.js'\nimport type { UIRender } from './render.js';\nimport type { Box } from '../board/element.js'\nimport type { ResolvedSelection } from '../action/selection.js';\nimport type { BaseGame } from '../board/game.js'\nimport type { ActionLayout, Game, PieceGrid } from '../board/index.js'\n\ntype GamePendingMoves = ReturnType<GameManager['getPendingMoves']>;\n\nexport type UIMove = PendingMove & {\n  requireExplicitSubmit: boolean; // true if explicit submit has not been provided and is needed\n}\n\n// used to send a move\nexport type MoveMessage = {\n  id: string;\n  type: 'move';\n  data: {\n    name: string,\n    args: Record<string, SerializedArg>\n  } | {\n    name: string,\n    args: Record<string, SerializedArg>\n  }[]\n}\n\nclass NoRandomAllowed extends Error {}\n\nexport const ContainerContext = createContext<{\n  game?: Game,\n  render?: UIRender,\n  layout?: UIRender['layouts'][number],\n  absoluteTransform?: Box,\n}>({});\n\n// refresh move and selections\nexport function updateSelections(store: GameStore): GameStore {\n  let { gameManager, position, move, placement } = store;\n  if (!position) return store;\n\n  const player = gameManager.players.atPosition(position);\n  if (!player) return store;\n  let state: GameStore = {\n    ...store,\n    error: undefined\n  };\n  let pendingMoves: GamePendingMoves\n  let maySubmit = !!move;\n  let autoSubmit = false;\n\n  const debug = {};\n  pendingMoves = gameManager.getPendingMoves(player, move?.name, move?.args, store.dev ? debug : undefined);\n  if (store.dev) state.actionDebug = debug;\n\n  if (move && !pendingMoves?.moves) {\n    // perhaps an update came while we were in the middle of a move\n    console.error('move may no longer be valid. retrying getPendingMoves', move, pendingMoves);\n    move = undefined;\n    pendingMoves = gameManager.getPendingMoves(player, undefined, undefined, debug);\n    if (store.dev) state.actionDebug = debug;\n  }\n\n  let moves = pendingMoves?.moves;\n\n  if (moves?.length === 1 && moves[0].selections.length === 1) {\n    if (!move) move = decorateUIMove(moves[0]);\n\n    const selection = moves[0].selections[0];\n    if (selection.type === 'place' && !placement) {\n      let piece = selection.clientContext.placement.piece as string | Piece<BaseGame>;\n      if (typeof piece === 'string') piece = moves[0].args[piece] as Piece<BaseGame>;\n      const into = selection.clientContext.placement.into as PieceGrid<BaseGame>;\n      const clone = piece.cloneInto(into);\n      clone._ui.ghost = true;\n      if (selection.rotationChoices) {\n        // find the closest allowable rotation to the current rotation\n        clone.rotation = clone.rotation === undefined ?\n          selection.rotationChoices[0] :\n          [...selection.rotationChoices].sort((r1, r2) => {\n            const a1 = Math.abs(((r1 - clone.rotation!) % 360 + 360) % 360 - 180);\n            const a2 = Math.abs(((r2 - clone.rotation!) % 360 + 360) % 360 - 180);\n            return a1 < a2 ? 1 : -1;\n          })[0];\n      }\n\n      state.rendered = applyLayouts(gameManager.game);\n      state.placement = {\n        piece: clone,\n        into,\n        layout: state.rendered.all[into._t.ref].layouts[0], // assume first/only layout - need a Stack class to formalize\n        rotationChoices: selection.rotationChoices,\n      };\n    }\n\n    if (selection.type === 'board' && selection.initial && state.selected === undefined) {\n      state.selected = selection.initial as GameElement[]\n      state.uncommittedArgs[selection.name] = selection.initial;\n    }\n\n    const skipIf = moves[0].selections[0].skipIf;\n    // the only selection is skippable - skip and confirm or autoplay if possible\n    if (skipIf === true || skipIf === 'always' || (moves[0].selections.length === 1 && (skipIf === 'only-one' || skipIf === false))) {\n      const arg = moves[0].selections[0].isForced();\n      if (arg !== undefined) {\n\n        if (moves[0].selections[0].confirm) {\n          // a confirm was added tho, so don't skip that. convert to confirm prompt\n          // TODO: distinguish static from arg-taking? static can probably be skipped\n          moves[0].args[moves[0].selections[0].name] = arg;\n          moves[0].selections[0].name = '__confirm__';\n          moves[0].selections[0].type = 'button';\n        } else {\n          move = decorateUIMove({\n            ...moves[0],\n            args: {...moves[0].args, [moves[0].selections[0].name]: arg}\n          });\n          if (gameManager.getPendingMoves(player, move.name, move.args)?.moves.length === 0) {\n            if (maySubmit === false) {\n              autoSubmit = true;\n              maySubmit = true;\n            }\n            moves = [];\n          }\n        }\n      }\n    }\n  }\n\n  // move is processable\n  if (maySubmit && moves?.length === 0) {\n    if (move) {\n      const player = gameManager.players.atPosition(position);\n      if (player) {\n        state.cancellable = false;\n\n        // serialize now before we alter our state to ensure proper references\n        const serializedMove: SerializedMove = {\n          name: move.name,\n          args: Object.fromEntries(Object.entries(move.args).map(([k, v]) => [k, serializeArg(v)]))\n        }\n\n        console.debug(\n          `${autoSubmit ? 'Autoplay' : 'Submitting'} valid move from player #${position}:\\n` +\n            `⮕ ${move.name}({${Object.entries(move.args).map(([k, v]) => `${k}: ${v}`).join(', ')}})`\n        );\n        //moveCallbacks.push((error: string) => console.error(`move ${moves} failed: ${error}`));\n        const message: MoveMessage = {\n          type: \"move\",\n          id: '0', // String(moveCallbacks.length),\n          data: serializedMove\n        };\n\n        if (autoSubmit) {\n          // no need to run locally, just queue the submit and remove any moves from being presented\n          // not using game queue because updates must come in *before* this if revealed information alters our forced move\n          state.automove = window.setTimeout(() => window.top!.postMessage(message, \"*\"), 500); // speed\n        } else {\n          // run the move locally and submit in parallel\n\n          state = { ...state, ...clearMove() };\n          if (state.placement) {\n            // remove temporary placement piece only once the full move is submitted\n            removePlacementPiece(state.placement);\n            state.placement = undefined;\n          }\n\n          try {\n            const oldRandom = Math.random;\n            const oldGameRandom = gameManager.game.random;\n            gameManager.game.random = Math.random = () => { throw new NoRandomAllowed(); };\n            try {\n              state.error = gameManager.processMove({ player, ...move });\n            } catch (e) {\n              // silently stop if random elements run\n              if (!(e instanceof NoRandomAllowed)) throw e;\n            } finally {\n              Math.random = oldRandom;\n              gameManager.game.random = oldGameRandom;\n            }\n\n            if (state.error) {\n              // should probably never reach this point since the error would\n              // have been caught with any possible choices presented\n              throw Error(state.error);\n            } else {\n              let json: any = undefined;\n              if (gameManager.intermediateUpdates.length) {\n                json = gameManager.intermediateUpdates[0][0].board\n                gameManager.game.fromJSON(json);\n                gameManager.intermediateUpdates = [];\n              }\n              const rendered = applyLayouts(gameManager.game);\n              if (state.rendered) applyDiff(rendered.game, rendered, state.rendered);\n              state.rendered = rendered;\n              gameManager.game.resetRefTracking();\n\n              window.top!.postMessage(message, \"*\");\n            }\n          } catch (e) {\n            // first line of defense for bad game logic. cancel all moves and\n            // surface the error but update board anyways to prevent more errors\n            console.error(\n              `Game attempted to complete move but was unable to process:\\n` +\n                `⮕ ${move!.name}({ ${Object.entries(move!.args).map(([k, v]) => `${k}: ${v}`).join(', ')} })\\n`\n            );\n            console.error(e.message);\n            console.debug(e.stack);\n          }\n        }\n      }\n      move = undefined;\n    }\n  }\n\n  if (autoSubmit) return state;\n\n  if (pendingMoves) {\n    pendingMoves.moves = pendingMoves.moves.map(move => decorateUIMove(move));\n  }\n\n  state = {\n    ...state,\n    move,\n    step: pendingMoves?.step,\n    prompt: pendingMoves?.prompt,\n    pendingMoves: pendingMoves?.moves as UIMove[],\n  };\n\n  if (gameManager.players.currentPosition.length > 0) {\n    const allowedActions = gameManager.allowedActions(gameManager.players.allCurrent()[0]);\n    state.step = allowedActions.step;\n    let description = allowedActions.description || 'taking their turn';\n\n    const actionsWithDescription = allowedActions.actions.filter(a => a.description);\n    if (actionsWithDescription.length === 1) {\n      description = actionsWithDescription[0].description!;\n      if (!gameManager.players.currentPosition.includes(position)) state.otherPlayerAction = actionsWithDescription[0].name;\n    }\n    state.actionDescription = `${gameManager.players.currentPosition.length > 1 ? 'Players are' : gameManager.players.current() + ' is'} ${description}`;\n  }\n\n  Object.assign(state, updateBoardSelections(state));\n  Object.assign(state, updateControls(state));\n  Object.assign(state, updatePrompts(state));\n\n  return state;\n}\n\n// find the best layout for the current moves, going in this order:\n// - the last selected, visible game element as part of the current move(s) that hasn't been disabled via layoutAction.noAnchor\n// - a supplied layoutAction for the only current move\n// - a supplied layoutStep belonging to the step to which the current move(s) belong\nexport function updateControls(store: GameStore): Pick<GameStore, \"controls\"> {\n  const { gameManager, position, pendingMoves, selected, move, boardSelections, disambiguateElement, otherPlayerAction, step } = store;\n\n  if (!pendingMoves?.length && (!position || gameManager.players.currentPosition.includes(position))) {\n    return { controls: undefined };\n  }\n\n  let layout: ActionLayout | undefined = undefined;\n  let name: string = '';\n  let moves = pendingMoves || [];\n  let style: CSSProperties = { };\n\n  if (!layout && disambiguateElement?.element) {\n    layout = { element: disambiguateElement.element, position: 'beside', gap: 2 };\n    moves = disambiguateElement.moves;\n    name = 'disambiguate-board-selection';\n  }\n\n  if (!layout && selected?.length === 1) {\n    const clickMoves = boardSelections[selected[0].branch()]?.clickMoves;\n    if (clickMoves?.length === 1 && !clickMoves[0].selections[0].isMulti()) {\n      layout = { element: selected[0], position: 'beside', gap: 2 };\n      name = 'action:' + moves[0].name;\n      moves = clickMoves;\n    }\n  }\n\n  // anchor to last element in arg list\n  if (!layout && move && !pendingMoves?.[0].selections[0].isBoardChoice()) {\n    const element = Object.entries(move.args).reverse().find(([name, el]) => (\n      !gameManager.game._ui.stepLayouts[\"action:\" + move.name]?.noAnchor?.includes(name) && el instanceof GameElement\n    ));\n    if (element && store.rendered!.all[(element[1] as GameElement)._t.ref]) {\n      layout = { element: element[1] as GameElement, position: 'beside', gap: 2 };\n      name = 'action:' + element[0];\n    }\n  }\n\n  if (!layout && pendingMoves?.length) {\n    const moves = pendingMoves.filter(m => move || m.name.slice(0, 4) !== '_god'); // no display for these normally\n\n    if (moves.length === 1) {\n      // skip non-board moves if board elements already selected (cant this be more specific? just moves that could apply?)\n      if (!selected?.length || moves[0].selections.some(s => s.type !== 'board')) {\n        const actionLayout = gameManager.game._ui.stepLayouts[\"action:\" + moves[0].name];\n        if (store.rendered!.all[actionLayout?.element._t.ref]) {\n          layout = actionLayout;\n          name = 'action:' + moves[0].name;\n        }\n      }\n    }\n  }\n\n  if (!layout && otherPlayerAction) {\n    const actionLayout = gameManager.game._ui.stepLayouts[\"action:\" + otherPlayerAction];\n    if (store.rendered!.all[actionLayout?.element._t.ref]) {\n      layout = actionLayout;\n      name = 'action:' + otherPlayerAction;\n    }\n  }\n\n  if (!layout && step) {\n    name = 'step:' + step;\n    layout = gameManager.game._ui.stepLayouts[name];\n  }\n\n  if (!layout) {\n    name = '*';\n    layout = gameManager.game._ui.stepLayouts[name];\n  }\n\n  const box: Box | undefined = store.rendered!.all[layout?.element._t.ref]?.pos;\n  if (layout && box) {\n    if (layout.position === 'beside' || layout.position === 'stack') {\n      if (box.left > 100 - box.left - box.width) {\n        style.right = `clamp(0%, calc(${100 - box.left - (layout.position === 'beside' ? 0 : box.width)}% + ${layout.position === 'beside' ? layout.gap : 0}vw), 100%)`;\n        style.left = undefined;\n      } else {\n        style.left = `clamp(0%, calc(${box.left + (layout.position === 'beside' ? box.width : 0)}% + ${layout.position === 'beside' ? layout.gap : 0}vw), 100%)`;\n      }\n\n      if (box.top > 100 - box.top - box.height) {\n        style.bottom = `clamp(0%, calc(${100 - box.top - (layout.position === 'beside' ? box.height : 0)}% + ${layout.position === 'beside' ? 0 : layout.gap}vw), 100%)`;\n        style.top = undefined;\n      } else {\n        style.top = `clamp(0%, calc(${box.top + (layout.position === 'beside' ? 0: box.height)}% + ${layout.position === 'beside' ? 0 : layout.gap}vw), 100%)`;\n      }\n    } else {\n      // inset\n      if (layout.right !== undefined) {\n        style.right = 100 + ((layout.right * box.width / 100) - box.left - box.width) + '%';\n      } else if (layout.center !== undefined) {\n        style.left ??= ((layout.center - 50) * box.width / 100) + box.left + '%';\n        style.right = 100 + ((50 - layout.center) * box.width / 100) - box.left - box.width + '%';\n        style.margin = '0 auto';\n      } else {\n        style.left ??= ((layout.left ?? 0) * box.width / 100) + box.left + '%';\n      }\n\n      if (layout.bottom !== undefined) {\n        style.bottom = 100 + ((layout.bottom * box.height / 100) - box.top - box.height) + '%';\n      } else {\n        style.top = ((layout.top ?? 0) * box.height / 100) + box.top + '%';\n      }\n    }\n\n    if (layout.width !== undefined) style.maxWidth = (layout.width * box.width / 100) + '%';\n    if (layout.height !== undefined) style.maxHeight = (layout.height * box.height / 100) + '%';\n  } else {\n    style = {left: 0, bottom: 0};\n  }\n\n  return { controls: {style, name, moves} };\n}\n\nexport function updateBoardSelections(store: GameStore): Pick<GameStore, \"boardSelections\"> {\n  const { pendingMoves, move } = store;\n  if (!pendingMoves?.length) return { boardSelections: {} };\n\n  // populate boardSelections\n  const boardSelections: Record<string, {\n    clickMoves: UIMove[],\n    dragMoves: {\n      move: UIMove,\n      drag: Selection | ResolvedSelection,\n    }[],\n    error?: string\n  }> = {};\n  for (const p of pendingMoves) {\n    for (const sel of p.selections) {\n      if (sel.type === 'board' && sel.boardChoices) {\n        const boardChoices = sel.resolvedChoices as { choice: GameElement, error?: string, label?: string }[];\n        const boardMove = {...p, selections: [sel]}; // simple board move of single selection to attach to element\n        for (const { choice, error } of boardChoices) {\n          boardSelections[choice.branch()] ??= { clickMoves: [], dragMoves: [], error };\n          // note that multiple moves might select the same piece. error only set if only one choice and its invalid\n          if (!error) boardSelections[choice.branch()].clickMoves.push(boardMove);\n        }\n        let { dragInto, dragFrom } = sel.clientContext as { dragInto?: Selection | GameElement, dragFrom?: Selection | GameElement };\n        if (dragInto) {\n          if (dragInto instanceof GameElement) {\n            // convert to confirmation for a single drop target\n            dragInto = new Selection('__confirm__', { selectOnBoard: { chooseFrom: [dragInto] } });\n          }\n          for (const { choice, error } of boardChoices) {\n            if (!error) boardSelections[choice.branch()].dragMoves.push({ move: boardMove, drag: dragInto });\n          }\n        }\n        if (dragFrom) {\n          for (const el of dragFrom instanceof GameElement ? [{ choice: dragFrom }] : dragFrom.resolve(move?.args || {}).resolvedChoices || []) {\n            boardSelections[(el.choice as GameElement).branch()] ??= { clickMoves: [], dragMoves: [] };\n            boardSelections[(el.choice as GameElement).branch()].dragMoves.push({ move: boardMove, drag: sel });\n          }\n        }\n      }\n    }\n  }\n  return { boardSelections };\n}\n\nexport function updatePrompts(store: GameStore): Partial<GameStore> {\n  const { controls, prompt, actionDescription, gameManager, position, disambiguateElement } = store;\n  if (actionDescription && !gameManager.players.currentPosition.includes(position!)) return { boardPrompt: actionDescription };\n  if (!controls) return { boardPrompt: undefined };\n  const state: Partial<GameStore> = {};\n  const moves = [...controls.moves];\n\n  const boardMoves = moves.filter(m => m.selections.some(s => s.isBoardChoice()));\n  if (!boardMoves.length) return { boardPrompt: undefined };\n\n  state.boardPrompt = boardMoves.length > 1 ? prompt : undefined;\n\n  for (const move of boardMoves) {\n    // promote a board selection prompt to the move prompt\n    move.prompt = move.selections[0].prompt ?? move.prompt ?? prompt;\n    if (!move.prompt) {\n      move.prompt = move.name;\n      console.error(`No prompts defined for choosing \"${move.selections[0].name}\" in \"${move.name}\" action. Add either an action prompt or selection prompt.`);\n    }\n    move.selections[0].prompt = undefined;\n    if (state.boardPrompt && !disambiguateElement) {\n      move.prompt = undefined;\n    }\n  }\n\n  state.controls = {...controls, moves}\n  return state;\n}\n\nexport function removePlacementPiece(placement: NonNullable<GameStore['placement']>) {\n  const position = placement.into._t.children.indexOf(placement.piece);\n  placement.into._t.children.splice(position, 1);\n}\n\nexport function decorateUIMove(move: PendingMove | UIMove): UIMove {\n  const requireExplicitSubmit = ('requireExplicitSubmit' in move && move.requireExplicitSubmit) ||\n    move.selections.length !== 1 ||\n    ['number', 'text'].includes(move.selections[0].type) ||\n    !!move.selections[0].confirm ||\n    move.selections[0].isMulti();\n\n  return {\n    ...move,\n    requireExplicitSubmit,\n  };\n}\n\nexport function clearMove(): Partial<GameStore> {\n  return {\n    move: undefined,\n    cancellable: false,\n    error: undefined,\n    uncommittedArgs: {},\n    disambiguateElement: undefined,\n    selected: undefined,\n    dragElement: undefined,\n    currentDrop: undefined,\n    dropSelections: [],\n  }\n}\n"
  },
  {
    "path": "src/ui/queue.ts",
    "content": "class Queue {\n  updates: (() => any)[] = [];\n  justProcessed: boolean = false; // queue was just processed\n  timeout: number;\n  paused = false;\n\n  constructor(\n    public speed: number = 1\n  ) {\n  }\n\n  schedule(update: () => any, waitIfProcessing = false) {\n    this.updates.push(update);\n    if (this.updates.length === 1 && (!this.justProcessed || !waitIfProcessing)) {\n      this.pump();\n    }\n  }\n\n  pump() {\n    if (this.paused) return;\n    const update = this.updates.shift();\n    if (!update) {\n      this.justProcessed = false;\n      return;\n    }\n    this.justProcessed = true;\n    clearTimeout(this.timeout);\n    this.timeout = window.setTimeout(() => this.pump(), this.speed * 1000);\n    update();\n  }\n\n  pause() {\n    this.paused = true;\n  }\n\n  resume() {\n    if (!this.paused) return;\n    this.paused = false;\n    this.pump();\n  }\n}\n\nexport default Queue;\n"
  },
  {
    "path": "src/ui/render.ts",
    "content": "import GameElement from '../board/element.js';\nimport ElementCollection from '../board/element-collection.js';\nimport random from 'random-seed';\nimport { serialize } from '../action/utils.js'\nimport uuid from 'uuid-random';\nimport React from 'react';\n\nimport type { Game, Box, Vector } from \"../board/index.js\";\nimport type { ElementClass } from \"../board/element.js\";\n\nexport type UIRender = {\n  element: GameElement,\n  key?: string;\n  mutated?: boolean;\n  attributes?: Record<string, any>;\n  dataAttributes?: Record<string, any>;\n  previousAttributes?: Record<string, any>;\n  previousDataAttributes?: Record<string, any>;\n  relPos?: Box & { rotation?: number }; // raw pos data relative to parent\n  pos?: Box & { rotation?: number }; // raw pos data relative to a perfect square as high as the board\n  oldPos?: Box & { rotation?: number }; // old pos for transform relative to board\n  styles?: React.CSSProperties; // CSS, includes pos and transform from move\n  baseStyles?: React.CSSProperties;\n  classes?: string;\n  effectClasses?: string;\n  layouts: {\n    area: Box,\n    fixed?: Box, // if fixed independently and not el.pos\n    grid?: {\n      anchor: Vector,\n      origin: { column: number, row: number },\n      columns: number,\n      rows: number,\n      offsetColumn: Vector,\n      offsetRow: Vector,\n    },\n    showBoundingBox?: string | boolean,\n    children: UIRender[],\n    container?: {\n      type: 'drawer' | 'popout' | 'tabs',\n      attributes: Record<string, any>\n      id?: string,\n      key?: string,\n    },\n  }[],\n  parentRef?: number,\n  crossParent?: boolean,\n  proxy?: number // unrendered elements outside the limit are proxied to the closest element for animations\n};\n\nexport type UI = {\n  all: Record<string, UIRender>;\n  frame: Vector;\n  game: UIRender;\n  pile: number[];\n};\n\n/**\n * recalc all elements UI, base styles, wrapper styles, classes, attrs,\n * data-attrs, assign UUID DOM keys\n * @category UI\n * @internal\n */\nexport function applyLayouts(game: Game, base?: (b: Game) => void): UI {\n  if (!game._ui.boardSize) throw Error(\"Layout cannot be applied before setBoardSize\");\n  game.resetUI();\n  if (game._ui.setupLayout) {\n    game._ui.setupLayout(game, game._ctx.player!, game._ui.boardSize.name);\n  }\n  base?.(game);\n  const { frame } = game._ui.boardSize;\n\n  const ui: UI = {\n    all: {},\n    frame,\n    game: {\n      element: game,\n      pos: { left: 0, top: 0, width: frame.x, height: frame.y },\n      relPos: { left: 0, top: 0, width: 100, height: 100 },\n      styles: {\n        width: '100%',\n        height: '100%',\n        left: '0',\n        top: '0',\n        fontSize: (frame?.y ?? 100) * 0.04 + 'rem'\n      },\n      classes: `Space ${game._ui.appearance.className ?? ''} ${game.constructor.name}`,\n      layouts: []\n    },\n    pile: game.pile._t.children.map(e => e._t.ref)\n  };\n\n  ui.all[String(game._t.ref)] = ui.game;\n  ui.game.layouts = calcLayouts(game, ui);\n\n  return ui;\n}\n\n// compares render to oldRender and applies DOM keys only\nexport function applyDOMKeys(render: UIRender, ui: UI, oldUI: UI) {\n\n  const el = render.element;\n\n  const oldRender = oldUI.all[String(el._t.wasRef ?? el._t.ref)];\n\n  for (const layout of render.layouts) {\n    for (const child of layout.children) {\n      applyDOMKeys(child, ui, oldUI);\n    }\n  }\n\n  if (!('isSpace' in el) && el._t.parent?._t.ref === oldRender.parentRef) {\n    render.key = oldRender?.key ?? render.key;\n  }\n}\n\n// compares render to oldRender and applies transforms, effect classes, DOM key, old attrs\nexport function applyDiff(render: UIRender, ui: UI, oldUI: UI): boolean {\n\n  const proxy = render.proxy !== undefined ? ui.all[render.proxy] : undefined;\n  const el = render.element;\n\n  if ('pile' in el) {\n    // find offscreen moves\n    for (const off of (el as Game).pile._t.children) {\n      if (ui.all[off._t.ref]) continue;\n      const previous = oldUI.all[off._t.ref];\n      if (previous?.pos) {\n        const offRender = {\n          pos: {\n            left: 125,\n            top: -previous.pos.height,\n            width: previous.pos.width,\n            height: previous.pos.height,\n          },\n          relPos: {\n            left: 125,\n            top: -previous.pos.height,\n            width: previous.pos.width,\n            height: previous.pos.height,\n          },\n          element: off,\n          layouts: [],\n          key: previous.key,\n        };\n        applyBaseStyles(offRender, off);\n\n        render.layouts[0].children.push(offRender); // decks are single-layout\n        ui.all[off._t.ref] = offRender;\n      }\n    }\n  }\n\n  let oldRenderByWas = oldUI.all[String(el._t.wasRef ?? el._t.ref)];\n  let oldRender = oldRenderByWas?.proxy === undefined ? oldRenderByWas : oldUI.all[oldRenderByWas.proxy];\n  if (!oldRender?.pos || !oldRender?.relPos || (oldRender?.proxy && proxy)) { // do not animate from one proxy to another\n    if (oldUI.pile.includes(el._t.ref)) {\n      oldRender = {\n        pos: {\n          left: 125,\n          top: -render.pos!.height,\n          width: render.pos!.width,\n          height: render.pos!.height,\n        },\n        relPos: {\n          left: 125,\n          top: -render.pos!.height,\n          width: render.pos!.width,\n          height: render.pos!.height,\n        },\n        element: el,\n        layouts: [],\n      };\n    } else {\n      delete render.previousAttributes;\n      delete render.previousDataAttributes;\n      return true;\n    }\n  }\n  render.crossParent = el._t.parent?._t.ref !== oldRender.parentRef;\n\n  // depth first, bubble up mutations\n  let mutated = false\n\n  for (const layout of render.layouts) {\n    for (const child of layout.children) {\n      mutated = applyDiff(child, ui, oldUI) || mutated;\n    }\n  }\n\n  if (!('isSpace' in el) && !render.crossParent && !oldRenderByWas?.proxy) {\n    render.key = oldRender?.key ?? render.key;\n  }\n\n  const actual = proxy ?? render;\n  const relPos = actual.relPos;\n  if (\n    relPos && (\n      render.crossParent ||\n      oldRender.relPos!.left !== relPos.left ||\n      oldRender.relPos!.top !== relPos.top ||\n      oldRender.relPos!.width !== relPos.width ||\n      oldRender.relPos!.height !== relPos.height ||\n      (oldRender.relPos!.rotation ?? 0) !== (relPos.rotation ?? 0)\n    )\n  ) {\n    mutated = true;\n    const oldPos = render.crossParent ? oldRender.pos! : oldRender.relPos!;\n    const newPos = render.crossParent ? actual.pos! : actual.relPos!;\n    if (proxy !== undefined) {\n      render.classes = proxy.classes;\n      render.pos = proxy.pos;\n      render.relPos = proxy.relPos;\n      render.styles = {...proxy.styles};\n      render.baseStyles = {...proxy.baseStyles};\n    }\n\n    render.styles!.transform = `translate(${(oldPos.left + oldPos.width / 2 - newPos.left - newPos.width / 2) / newPos.width * 100}%, ` +\n      `${(oldPos.top + oldPos.height / 2 - newPos.top - newPos.height / 2) / newPos.height * 100}%) ` +\n      `scaleX(${oldPos.width / newPos.width}) ` +\n      `scaleY(${oldPos.height / newPos.height}) ` +\n      `rotate(${(oldPos.rotation ?? 0) - (newPos.rotation ?? 0)}deg)`;\n  } else if (proxy !== undefined) return false;\n\n  const changedAttrs = JSON.stringify(actual.dataAttributes) !== JSON.stringify(oldRender.dataAttributes);\n  mutated ||= changedAttrs;\n\n  if (changedAttrs) {\n    if (proxy !== undefined) {\n      render.attributes = proxy.attributes;\n      render.dataAttributes = proxy.dataAttributes;\n    }\n    render.previousAttributes = oldRender.attributes;\n    render.previousDataAttributes = oldRender.dataAttributes;\n\n    if (el._ui.appearance.effects) {\n      render.effectClasses = '';\n      for (const effect of el._ui.appearance.effects) {\n        if (effect.trigger(el, oldRender.attributes!)) render.effectClasses += ' ' + effect.name;\n      }\n    }\n  }\n\n  if (render.styles && (changedAttrs || render.styles.transform)) {\n    Object.assign(render.styles, {\n      // uuid so react re-applies if multiple\n      '--transformed-to-old': uuid(),\n      // supress normal transition style and re-add later. necessary to prevent\n      // transform transition from completing immediately\n      transition: 'none'\n    });\n  }\n\n  render.mutated = mutated;\n  return mutated;\n}\n\n/**\n * recalc one elements UI\n * @category UI\n * @internal\n */\nexport function calcLayouts(el: GameElement, ui: UI): UIRender['layouts'] {\n  if (el._ui.appearance.render === false) return [];\n\n  const layoutItems = getLayoutItems(el);\n  let absolutePosition = ui.all[String(el._t.ref)].pos! // or layout-pos\n  const layouts: UIRender['layouts'] = [];\n\n  for (let l = el._ui.layouts.length - 1; l >= 0; l--) {\n    const { attributes } = el._ui.layouts[l];\n    const allChildren = layoutItems[l];\n    let children = allChildren && attributes.limit !== undefined && allChildren.length > attributes.limit ?\n      el._t.order === 'stacking' ? allChildren?.slice(allChildren.length - attributes.limit) : allChildren?.slice(0, attributes.limit) :\n      allChildren;\n\n    const { slots, direction, gap, alignment, maxOverlap } = attributes;\n    let { size, scaling, aspectRatio, haphazardly, area, margin } = attributes;\n    if (!size && !scaling) scaling = 'fit';\n    let layoutPosition = absolutePosition;\n    if (attributes.__container__?.type === 'popout') {\n      const screen = el.game._ui.boardSize!.screen;\n      // calc the layout against the full viewport\n      const margin = typeof attributes.__container__.attributes.popoutMargin === 'number' ? {\n        top: attributes.__container__.attributes.popoutMargin,\n        bottom: attributes.__container__.attributes.popoutMargin,\n        left: attributes.__container__.attributes.popoutMargin,\n        right: attributes.__container__.attributes.popoutMargin,\n      } : attributes.__container__.attributes.popoutMargin ?? {\n        top: 4,\n        bottom: 4,\n        left: 4,\n        right: 4\n      };\n      let width = screen.x;\n      let height = screen.y;\n      layoutPosition = {\n        left: margin.left,\n        top: margin.top,\n        width: width - (margin.left + margin.right) * Math.min(width, height) / 100,\n        height: height - (margin.top + margin.bottom) * Math.min(width, height) / 100\n      };\n    }\n\n    area = getArea(layoutPosition, margin, area);\n\n    let cellBoxes = slots || [];\n    let sizes: number[] = []; // relative sizes of children so they retain scaling against each other\n    let maxSize: number = 0;\n\n    layouts[l] = {\n      area,\n      children: [],\n      showBoundingBox: attributes.showBoundingBox ?? el.game._ui.boundingBoxes,\n    };\n    const layout = layouts[l];\n\n    if (layoutPosition !== absolutePosition) {\n      // override to a fixed absolute position with area being the full region\n      console.log('layoutPosition', el.name, layoutPosition);\n      layout.fixed = layoutPosition;\n      area = {\n        left: 0,\n        top: 0,\n        width: 100,\n        height: 100\n      };\n    }\n\n    let minColumns = typeof attributes.columns === 'number' ? attributes.columns : attributes.columns?.min || 1;\n    let minRows = typeof attributes.rows === 'number' ? attributes.rows : attributes.rows?.min || 1;\n\n    if (!children?.length && minRows === 1 && minColumns === 1) continue;\n    children ??= [];\n\n    if (!slots) {\n      const cells: [number?, number?][] = [];\n      const min: {column?: number, row?: number} = {};\n      const max: {column?: number, row?: number} = {};\n\n      // find bounding box for any set positions\n      for (let c = 0; c != children.length; c++) {\n        const child = children[c];\n        const gridSize = el._sizeNeededFor(child);\n        if (child.column !== undefined && child.row !== undefined && !child._ui.ghost) {\n          cells[c] = [child.column, child.row];\n          if (min.column === undefined || child.column < min.column) min.column = child.column;\n          if (min.row === undefined || child.row < min.row) min.row = child.row;\n          if (max.column === undefined || child.column + gridSize.width - 1 > max.column) max.column = child.column + gridSize.width - 1;\n          if (max.row === undefined || child.row + gridSize.height - 1 > max.row) max.row = child.row + gridSize.height - 1;\n        }\n      }\n      min.column ??= 1;\n      min.row ??= 1;\n      max.column ??= 1;\n      max.row ??= 1;\n\n      // calculate # of rows/cols\n      minColumns = Math.max(minColumns, max.column - min.column + 1);\n      minRows = Math.max(minRows, max.row - min.row + 1);\n      let maxColumns = typeof attributes.columns === 'number' ? attributes.columns : attributes.columns?.max || Infinity;\n      let maxRows = typeof attributes.rows === 'number' ? attributes.rows : attributes.rows?.max || Infinity;\n\n      let columns = minColumns;\n      let rows = minRows;\n      let origin = {column: 1, row: 1};\n      const alignOffset = {\n        left: alignment.includes('left') ? 0 : (alignment.includes('right') ? 1 : 0.5),\n        top: alignment.includes('top') ? 0 : (alignment.includes('bottom') ? 1 : 0.5),\n      };\n\n      const ghostPiecesIgnoredForLayout = ('extendableGrid' in el && el.extendableGrid) ? children.filter(c => c._ui.ghost) : [];\n      const elements = children.length - ghostPiecesIgnoredForLayout.length;\n\n      // expand grid as needed for children in direction specified\n      if (children.length) {\n        if (direction === 'square') {\n          columns = Math.max(minColumns,\n            Math.min(\n              maxColumns,\n              Math.ceil(elements / minRows),\n              Math.max(Math.ceil(elements / maxRows), Math.ceil(Math.sqrt(elements)))\n            )\n          );\n          rows = Math.max(minRows,\n            Math.min(maxRows,\n              Math.ceil(elements / minColumns),\n              Math.ceil(elements / columns)\n            )\n          );\n        } else {\n          if (rows * columns < elements) {\n            if (['ltr', 'ltr-btt', 'rtl', 'rtl-btt'].includes(direction)) {\n              columns = Math.max(columns, Math.min(maxColumns, Math.ceil(elements / rows)));\n              rows = Math.max(rows, Math.min(maxRows, Math.ceil(elements / columns)));\n            }\n            if (['ttb', 'btt', 'ttb-rtl', 'btt-rtl'].includes(direction)) {\n              rows = Math.max(rows, Math.min(maxRows, Math.ceil(elements / columns)));\n              columns = Math.max(columns, Math.min(maxColumns, Math.ceil(elements / rows)));\n            }\n          }\n        }\n\n        // set origin if viewport should shift\n        origin = {\n          column: Math.min(min.column, max.column, Math.max(1, max.column - columns + 1)),\n          row: Math.min(min.row, max.row, Math.max(1, max.row - rows + 1))\n        }\n\n        if (ghostPiecesIgnoredForLayout.length) {\n          const extension = Math.max(...ghostPiecesIgnoredForLayout.map(p => Math.max(p._size?.width ?? 1, p._size?.height ?? 1)));\n          if (extension > 0) {\n            if (children.length === ghostPiecesIgnoredForLayout.length) {\n              columns = Math.max(columns, extension);\n              rows = Math.max(rows, extension);\n            } else {\n              if (min.column - extension < origin.column) {\n                columns += extension - min.column + origin.column;\n                origin.column = min.column - extension;\n              }\n              if (max.column + extension >= origin.column + columns) {\n                columns = max.column + extension - origin.column + 1;\n              }\n              if (min.row - extension < origin.row) {\n                rows += extension - min.row + origin.row;\n                origin.row = min.row - extension;\n              }\n              if (max.row + extension >= origin.row + rows) {\n                rows = max.row + extension - origin.row + 1;\n              }\n            }\n          }\n        }\n\n        let available: Vector;\n        let advance: Vector;\n        let carriageReturn: Vector;\n        let fillDirection = direction;\n        if (fillDirection === 'square') {\n          if (['left', 'top left', 'top', 'center'].includes(alignment)) {\n            fillDirection = 'ltr';\n          } else if (['right', 'top right'].includes(alignment)) {\n            fillDirection = 'rtl';\n          } else if (['bottom','bottom left'].includes(alignment)) {\n            fillDirection = 'ltr-btt';\n          } else {\n            fillDirection = 'rtl-btt';\n          }\n        }\n        switch (fillDirection) {\n          case 'ltr':\n            available = {x: 1, y: 1};\n            advance = {x: 1, y: 0};\n            carriageReturn = {x: -columns, y: 1};\n            break;\n          case 'rtl':\n            available = {x: columns, y: 1};\n            advance = {x: -1, y: 0};\n            carriageReturn = {x: columns, y: 1};\n            break;\n          case 'ttb':\n            available = {x: 1, y: 1};\n            advance = {x: 0, y: 1};\n            carriageReturn = {x: 1, y: -rows};\n            break;\n          case 'btt':\n            available = {x: 1, y: rows};\n            advance = {x: 0, y: -1};\n            carriageReturn = {x: 1, y: rows};\n            break;\n          case 'ltr-btt':\n            available = {x: 1, y: rows};\n            advance = {x: 1, y: 0};\n            carriageReturn = {x: -columns, y: -1};\n            break;\n          case 'rtl-btt':\n            available = {x: columns, y: rows};\n            advance = {x: -1, y: 0};\n            carriageReturn = {x: columns, y: -1};\n            break;\n          case 'ttb-rtl':\n            available = {x: columns, y: 1};\n            advance = {x: 0, y: 1};\n            carriageReturn = {x: -1, y: -rows};\n            break;\n          case 'btt-rtl':\n            available = {x: columns, y: rows};\n            advance = {x: 0, y: -1};\n            carriageReturn = {x: -1, y: rows};\n            break;\n        }\n\n        if (ghostPiecesIgnoredForLayout) {\n          for (let c = 0; c != children.length; c++) {\n            const child = children[c];\n            if (child.column !== undefined && child.row !== undefined && child._ui.ghost) cells[c] = [child.column, child.row];\n          }\n        }\n\n        // place unpositioned elements\n        let c = 0;\n        while (c != children.length) {\n          const child = children[c];\n          if (cells[c]) {\n            c++;\n            continue;\n          }\n          const cell: [number, number] = [available.x + origin.column! - 1, available.y + origin.row! - 1];\n          if (cells.every(([x, y]) => x !== cell[0] || y !== cell[1])) {\n            cells[c] = cell;\n            if (attributes.sticky) {\n              child.column = cell[0];\n              child.row = cell[1];\n            }\n            c++;\n          }\n          available.x += advance.x;\n          available.y += advance.y;\n          if (available.x > columns || available.x <= 0 || available.y > rows || available.y <= 0) {\n            available.x += carriageReturn.x;\n            available.y += carriageReturn.y;\n          }\n          if (available.x > columns || available.x <= 0 || available.y > rows || available.y <= 0) break;\n        }\n      }\n\n      // calculate offset or gap\n      let cellGap: Vector | undefined = undefined;\n      let offsetRow: Vector | undefined = undefined;\n      let offsetColumn: Vector | undefined = undefined;\n      let effecitveRowsWithOffsets = '_gridPositions' in el && 'rows' in el ? el.rows as number : rows;\n      let effecitveColumnsWithOffsets = '_gridPositions' in el && 'columns' in el ? el.columns as number : columns;\n      let rhomboid = !('_gridPositions' in el) || !('shape' in el) || el.shape === 'rhomboid';\n\n      if (attributes.offsetColumn || attributes.offsetRow) {\n        offsetColumn = typeof attributes.offsetColumn === 'number' ? {x: attributes.offsetColumn, y: 0} : attributes.offsetColumn;\n        offsetRow = typeof attributes.offsetRow === 'number' ? {x: 0, y: attributes.offsetRow} : attributes.offsetRow;\n        if (!offsetRow) offsetRow = { x: -offsetColumn!.y, y: offsetColumn!.x };\n        if (!offsetColumn) offsetColumn = { x: offsetRow!.y, y: -offsetRow!.x };\n      } else {\n        // gaps are absolute and convert by ratio\n        cellGap = {\n          x: (gap && (typeof gap === 'number' ? gap : gap.x) || 0) / layoutPosition.width * 100,\n          y: (gap && (typeof gap === 'number' ? gap : gap.y) || 0) / layoutPosition.height * 100,\n        };\n      }\n\n      if (!size) {\n        // start with largest size needed to accommodate\n        size = cellSizeForArea(\n          effecitveRowsWithOffsets, effecitveColumnsWithOffsets,\n          area, cellGap, offsetColumn, offsetRow, rhomboid\n        );\n\n        // find all aspect ratios and sizes of child elements and choose best fit\n        if (!aspectRatio) {\n          let minRatio = Infinity;\n          let maxRatio = 0;\n          for (const c of children) {\n            const r = c._ui.appearance.aspectRatio;\n            if (r !== undefined) {\n              if (r < minRatio) minRatio = r;\n              if (r > maxRatio) maxRatio = r;\n            }\n            const largestDimension = c._size ? Math.max(c._size.width, c._size.height) : 1;\n            sizes.push(largestDimension);\n            if (largestDimension > maxSize) maxSize = largestDimension;\n          }\n          if (minRatio < Infinity || maxRatio > 0) {\n            if (maxRatio > 1 && minRatio < 1) aspectRatio = 1;\n              else if (minRatio > 1) aspectRatio = minRatio;\n              else aspectRatio = maxRatio;\n          }\n        }\n\n        if (aspectRatio) {\n          aspectRatio *= layoutPosition.height / layoutPosition.width;\n          if (aspectRatio > size.width / size.height) {\n            size.height = size.width / aspectRatio;\n          } else {\n            size.width = aspectRatio * size.height;\n          }\n        }\n      }\n\n      if (!children.length) {\n        layout.grid = {\n          anchor: { x: 0, y: 0 },\n          origin,\n          rows,\n          columns,\n          offsetColumn: offsetColumn ?? { x: size.width + cellGap!.x, y: 0 },\n          offsetRow: offsetRow ?? { x: 0, y: size.height + cellGap!.y }\n        }\n        continue;\n      }\n\n      if (haphazardly) {\n        haphazardly *= .2 + Math.max(0, cellGap ?\n          cellGap.x / size.width + cellGap.y / size.height :\n          (Math.abs(offsetColumn!.x) + Math.abs(offsetColumn!.y) + Math.abs(offsetRow!.y) + Math.abs(offsetColumn!.y) - 200) / 100);\n      } else {\n        haphazardly = 0;\n      }\n      //console.log('haphazardly', haphazardly);\n\n      const startingOffset = {x: 0, y: 0};\n\n      const corners = '_cornerPositions' in el ? (el._cornerPositions as () => [number, number][])() : [\n        [1, 1],\n        [columns, 1],\n        [1, rows],\n        [columns, rows],\n      ] as [number, number][];\n\n      let totalAreaNeeded = getTotalArea(corners, area, size, columns, rows, startingOffset, cellGap, offsetColumn, offsetRow);\n\n      let scale: Vector = {x: 1, y: 1};\n\n      if (scaling) {\n        if (scaling === 'fill') {\n          // match the dimension furthest, spilling one dimesion out of bounds\n          const s = Math.max(area.width / totalAreaNeeded.width, area.height / totalAreaNeeded.height);\n          scale = {x: s, y: s};\n        } else if (scaling === 'fit' && attributes.size) { // if size was not given, size was already calculated as 'fit'\n          // match the closest dimension, pushing one dimesion inside\n          const s = Math.min(area.width / totalAreaNeeded.width, area.height / totalAreaNeeded.height);\n          scale = {x: s, y: s};\n        }\n\n        // reduce scale if necessary to keep size below amount needed for min rows/cols\n        const largestCellSize = cellSizeForArea(\n          Math.min(minRows, effecitveRowsWithOffsets), Math.min(minColumns, effecitveColumnsWithOffsets),\n          area, cellGap, offsetColumn, offsetRow, rhomboid\n        );\n        if (maxOverlap !== undefined) {\n          const largestCellSize2 = cellSizeForArea(rows, columns, area, undefined,\n            { x: Math.min(100 - maxOverlap, offsetColumn?.x ?? 100), y: Math.min(100 - maxOverlap, offsetColumn?.y ?? 0) },\n            { x: Math.min(100 - maxOverlap, offsetRow?.x ?? 0), y: Math.min(100 - maxOverlap, offsetRow?.y ?? 100) }\n          );\n          largestCellSize.width = Math.min(largestCellSize.width, largestCellSize2.width);\n          largestCellSize.height = Math.min(largestCellSize.height, largestCellSize2.height);\n        }\n\n        if (size.width * scale.x > largestCellSize.width) {\n          const reduction = largestCellSize.width / size.width / scale.x;\n          scale.x *= reduction;\n          scale.y *= reduction;\n        }\n        if (size.height * scale.y > largestCellSize.height) {\n          const reduction = largestCellSize.height / size.height / scale.y;\n          scale.x *= reduction;\n          scale.y *= reduction;\n        }\n\n        //console.log('pre-scale', largestCellSize, area, size, totalAreaNeeded, alignOffset, scale);\n\n        size.width *= scale.x;\n        size.height *= scale.y;\n      }\n\n      if (!cellGap) { // non-othogonal grid\n        if (scaling !== 'fit') {\n          // reduce offset along dimension needed to squish\n          if (area.width * scale.x / totalAreaNeeded.width > area.height * scale.y / totalAreaNeeded.height) {\n            const offsetScale = (area.height - size.height) / (totalAreaNeeded.height * scale.y - size.height);\n            if (offsetScale < 1) {\n              scale.y = scale.x = area.height / totalAreaNeeded.height;\n              offsetColumn!.y *= offsetScale;\n              offsetRow!.y *= offsetScale;\n            }\n          } else {\n            const offsetScale = (area.width - size.width) / (totalAreaNeeded.width * scale.x - size.width);\n            if (offsetScale < 1) {\n              scale.y = scale.x = area.width / totalAreaNeeded.width;\n              offsetColumn!.x *= offsetScale;\n              offsetRow!.x *= offsetScale;\n            }\n          }\n\n          totalAreaNeeded = getTotalArea(corners, area, size, columns, rows, startingOffset, cellGap, offsetColumn, offsetRow);\n        }\n        // align in reduced area\n        startingOffset.x += area.left - totalAreaNeeded.left * scale.x + alignOffset.left * (area.width - totalAreaNeeded.width * scale.x);\n        startingOffset.y += area.top - totalAreaNeeded.top * scale.y + alignOffset.top * (area.height - totalAreaNeeded.height * scale.y);\n        //console.log('align', area, size, totalAreaNeeded, alignOffset, startingOffset, scale);\n\n      } else { // orthogonal\n\n        if (scaling === 'fill') {\n          // reduce gap to squish it to fit, creating overlap\n          if (rows > 1) cellGap.y = Math.min(cellGap.y || 0, (area.height - rows * size.height) / (rows - 1));\n          if (columns > 1) cellGap.x = Math.min(cellGap.x || 0, (area.width - columns * size.width) / (columns - 1));\n        }\n\n        // align in reduced area\n        const newWidth = columns * (size.width + cellGap.x!) - cellGap.x!;\n        startingOffset.x += alignOffset.left * (area.width - newWidth);\n        const newHeight = rows * (size.height + cellGap.y!) - cellGap.y!;\n        startingOffset.y += alignOffset.top * (area.height - newHeight);\n      }\n\n      //console.log('size, area after fit/fill adj', size, area, scale, cellGap)\n      for (let c = 0; c < children.length && c < cells.length; c++) {\n        let [column, row] = cells[c];\n        if (column !== undefined && row !== undefined) {\n          column -= origin.column - 1;\n          row -= origin.row - 1;\n          const box = cellBoxRC(column, row, area, size!, columns, rows, startingOffset, cellGap, offsetColumn, offsetRow);\n          if (box) cellBoxes[c] = box;\n        }\n      }\n\n      layout.grid = {\n        anchor: startingOffset,\n        origin,\n        rows,\n        columns,\n        offsetColumn: offsetColumn ?? { x: size.width + cellGap!.x, y: 0 },\n        offsetRow: offsetRow ?? { x: 0, y: size.height + cellGap!.y }\n      }\n    }\n\n    // apply the final box to each child\n    const prandom = random.create('ge' + el.name).random;\n    for (let i = 0; i !== children.length; i++) {\n      const box = cellBoxes[i];\n      if (!box) continue;\n      const child = children[i];\n      const render: UIRender = ui.all[String(child._t.ref)] = {\n        element: child,\n        key: 'isSpace' in child ? String(child._t.ref) : uuid(),\n        styles: {},\n        layouts: [],\n        parentRef: el._t.ref\n      };\n      let { width, height, left, top } = box;\n      let transformOrigin: string | undefined = undefined;\n      const gridSize = el._sizeNeededFor(child);\n      if (gridSize.width !== 1 || gridSize.height !== 1) {\n        height *= (child._size!.height ?? 1);\n        width *= (child._size!.width ?? 1);\n        if (child.rotation === 90) {\n          transformOrigin = `${50 * child._size!.height / child._size!.width}% 50%`;\n        }\n        if (child.rotation === 270) {\n          transformOrigin = `50% ${50 * child._size!.width / child._size!.height}%`;\n        }\n      } else {\n        if (child._ui.appearance.aspectRatio || child._size) {\n          const aspectRatio = (child._ui.appearance.aspectRatio ?? 1) * (child._size?.width ?? 1) / (child._size?.height ?? 1) * layoutPosition.height / layoutPosition.width;\n\n          if (aspectRatio && aspectRatio !== width / height) {\n            if (aspectRatio > width / height) {\n              height = width / aspectRatio;\n            } else {\n              width = aspectRatio * height;\n            }\n          }\n          left = box.left + (box.width - width) / 2;\n          top = box.top + (box.height - height) / 2;\n        }\n        if (maxSize && maxSize > 0 && sizes[i] && sizes[i] !== maxSize) {\n          const scale = sizes[i]! / maxSize;\n          left += width * 0.5 * (1 - scale);\n          top += height * 0.5 * (1 - scale);\n          height *= scale;\n          width *= scale;\n        }\n      }\n\n      if (haphazardly) {\n        let wiggle = {x: 0, y: 0};\n        let overlap = Infinity;\n        for (let tries = 0; tries < 10; tries ++) {\n          const rx = prandom();\n          const ry = prandom();\n          const w = {\n            x: haphazardly ? Math.min(\n              area.left + area.width - left - width,\n              Math.max(area.left - left, (rx - ((left - area.left) / (area.width - width) - .5) / 2 - .5) * haphazardly * (size!.width + size!.height))\n            ): 0,\n            y: haphazardly ? Math.min(\n              area.top + area.height - top - height,\n              Math.max(area.top - top, (ry - ((top - area.top) / (area.height - height) - .5) / 2 - .5) * haphazardly * (size!.width + size!.height))\n            ): 0\n          }\n          let worstOverlapElTry = Infinity;\n          if (children.every(c => {\n            const render = ui.all[String(c._t.ref)]\n            if (!render?.relPos) return true;\n            const cbox = render.relPos;\n            const childOverlap = Math.min(\n              Math.max(0, cbox.left + cbox.width - left - w.x),\n              Math.max(0, cbox.top + cbox.height - top - w.y),\n              Math.max(0, left + width + w.x - cbox.left),\n              Math.max(0, top + height + w.y - cbox.top)\n            );\n            if (childOverlap === 0) return true;\n            worstOverlapElTry = Math.min(childOverlap, worstOverlapElTry);\n          })) {\n            wiggle = w;\n            break;\n          }\n          if (worstOverlapElTry < overlap) {\n            overlap = worstOverlapElTry;\n            wiggle = w;\n          }\n        }\n        left += wiggle.x\n        top += wiggle.y\n      }\n\n      render.relPos = { width, height, left, top };\n      render.pos = translate(render.relPos, layoutPosition);\n      if (child._rotation !== undefined) render.relPos.rotation = render.pos.rotation = child._rotation;\n\n      applyBaseStyles(render, child);\n      if (transformOrigin) render.baseStyles!.transformOrigin = transformOrigin;\n\n      render.layouts = calcLayouts(child, ui);\n      layout.children.push(render);\n    }\n\n    if (allChildren && allChildren.length > children.length) {\n      const unrendered = el._t.order === 'stacking' ? allChildren.slice(0, allChildren.length - children.length) : allChildren.slice(children.length);\n      // items beyond the layout limit inherit the appearance of the last item\n      for (const child of unrendered) {\n        const render = {element: child, layouts: [], proxy: children[el._t.order === 'stacking' ? 0 : children.length - 1]._t.ref, key: uuid()};\n        ui.all[child._t.ref] = render;\n        layout.children.unshift(render);\n      }\n    }\n\n    if (attributes.__container__) {\n      const { type, id, key, attributes: containerAttributes } = attributes.__container__;\n      layout.container = { type, id, key, attributes: containerAttributes };\n    }\n  }\n  return layouts;\n}\n\nfunction applyBaseStyles(render: UIRender, element: GameElement) {\n  render.styles = {\n    width: render.relPos!.width + '%',\n    height: render.relPos!.height + '%',\n    left: render.relPos!.left + '%',\n    top: render.relPos!.top + '%',\n    fontSize: render.pos!.height * 0.04 + 'rem',\n    backgroundSize: render.pos!.height\n  }\n\n  render.attributes = element.attributeList();\n  render.attributes.mine = element.mine;\n  render.dataAttributes = Object.assign(\n    {\n      'data-player': element.player?.position\n    },\n    Object.fromEntries(Object.entries(render.attributes).filter(([key, val]) => (\n      typeof val !== 'object' && (element.isVisible() || (element.constructor as typeof GameElement).visibleAttributes?.includes(key))\n    )).map(([key, val]) => (\n      [`data-${key.toLowerCase()}`, serialize(val)]\n    )))\n  );\n\n  const baseClass = 'isSpace' in element ? 'Space' : 'Piece';\n\n  render.classes = `${baseClass} ${element._ui.appearance.className ?? ''} ${baseClass !== element.constructor.name ? element.constructor.name : ''}`;\n\n  render.baseStyles = {};\n  if (element._rotation !== undefined) render.baseStyles.transform = `rotate(${element._rotation}deg)`;\n  if (element.player) Object.assign(render.baseStyles, {'--player-color': element.player.color});\n}\n\nfunction getLayoutItems(el: GameElement) {\n  const layoutItems: (GameElement[] | undefined)[] = [];\n\n  const layouts = [...el._ui.layouts].sort((a, b) => {\n    let aVal = 0, bVal = 0;\n    if (a.applyTo instanceof GameElement) aVal = 3\n    if (b.applyTo instanceof GameElement) bVal = 3\n    if (typeof a.applyTo === 'string') aVal = 2\n    if (typeof b.applyTo === 'string') bVal = 2\n    if (a.applyTo instanceof Array) aVal = 1\n    if (b.applyTo instanceof Array) bVal = 1\n    if (aVal !== 0 || bVal !== 0) return aVal - bVal;\n    const ac = a.applyTo as ElementClass;\n    const bc = b.applyTo as ElementClass;\n    return ac.prototype instanceof bc ? 1 : (bc.prototype instanceof ac ? -1 : 0);\n  }).reverse();\n\n  for (const child of el._t.children) {\n    if (child._ui.appearance.render === false) continue;\n    for (const layout of layouts) {\n      const { applyTo } = layout;\n      const l = el._ui.layouts.indexOf(layout);\n\n      if ((typeof applyTo === 'function' && child instanceof applyTo) ||\n        (typeof applyTo === 'string' && child.name === applyTo) ||\n        child === applyTo ||\n        (applyTo instanceof ElementCollection && applyTo.includes(child))\n      ) {\n        layoutItems[l] ??= [];\n        if (el._t.order === 'stacking') {\n          layoutItems[l]!.unshift(child);\n        } else {\n          layoutItems[l]!.push(child);\n        }\n        break;\n      }\n    }\n  }\n  return layoutItems;\n}\n\n/**\n * calculate working area\n * @internal\n */\nfunction getArea(absolutePosition: Box, margin?: number | { top: number, bottom: number, left: number, right: number }, area?: Box): Box {\n  if (area) return area;\n  if (!margin) return { left: 0, top: 0, width: 100, height: 100 };\n\n  // margins are absolute, so translate\n  const transform: Vector = {\n    x: absolutePosition.width / 100,\n    y: absolutePosition.height / 100\n  }\n\n  margin = (typeof margin === 'number') ? { left: margin, right: margin, top: margin, bottom: margin } : {...margin};\n  margin.left /= transform.x;\n  margin.right /= transform.x;\n  margin.top /= transform.y;\n  margin.bottom /= transform.y;\n\n  return {\n    left: margin.left,\n    top: margin.top,\n    width: 100 - margin.left - margin.right,\n    height: 100 - margin.top - margin.bottom\n  };\n}\n\nexport function translate(original: Box, transform: Box): Box {\n  return {\n    left: original.left * transform.width / 100 + transform.left,\n    top: original.top * transform.height / 100 + transform.top,\n    width: original.width * transform.width / 100,\n    height: original.height * transform.height / 100,\n  };\n}\n\nexport function cellBoxRC(\n  column: number,\n  row: number,\n  area: Box,\n  size: {width: number, height: number},\n  columns: number,\n  rows: number,\n  startingOffset: Vector,\n  cellGap?: Vector,\n  offsetColumn?: Vector,\n  offsetRow?: Vector,\n): Box | undefined {\n  if (column > columns || row > rows) return;\n  column -= 1;\n  row -= 1;\n\n  return {\n    left: area!.left + startingOffset.x + (\n      cellGap ?\n        column * (size.width + cellGap!.x) :\n        (size!.width * (column * offsetColumn!.x + row * offsetRow!.x)) / 100\n    ),\n    top: area!.top + startingOffset.y + (\n      cellGap ?\n        row * (size.height + cellGap!.y) :\n        (size!.height * (row * offsetRow!.y + column * offsetColumn!.y)) / 100\n    ),\n    width: size.width,\n    height: size.height,\n  }\n}\n\nexport function cellSizeForArea(\n  rows: number,\n  columns: number,\n  area: { width: number, height: number },\n  gap?: Vector,\n  offsetColumn?: Vector,\n  offsetRow?: Vector,\n  rhomboid?: boolean\n) {\n  let width: number;\n  let height: number;\n\n  if (offsetColumn === undefined) {\n    width = (area.width - (gap!.x || 0) * (columns - 1)) / columns;\n    height = (area.height - (gap!.y || 0) * (rows - 1)) / rows;\n  } else {\n    width = area.width / (\n      (rhomboid ? (rows - 1) * Math.abs(offsetRow!.x / 100) : 0) +\n        1 + (columns - 1) * Math.abs(offsetColumn.x / 100)\n    )\n    height = area.height / (\n      (rhomboid ? (columns - 1) * Math.abs(offsetColumn.y / 100) : 0) +\n        1 + (rows - 1) * Math.abs(offsetRow!.y / 100)\n    )\n  }\n\n  return { width, height };\n}\n\n// find the edge boxes and calculate the total size needed\n// @internal\nexport function getTotalArea(\n  corners: [number, number][],\n  area: Box,\n  size: {width: number, height: number},\n  columns: number,\n  rows: number,\n  startingOffset: Vector,\n  cellGap?: Vector,\n  offsetColumn?: Vector,\n  offsetRow?: Vector,\n): Box {\n  const boxes = corners.map(corner => (\n    cellBoxRC(corner[0], corner[1], area, size, columns, rows, startingOffset, cellGap, offsetColumn, offsetRow)\n  ));\n\n  const cellArea = {\n    top: Math.min(...boxes.map(b => b!.top)),\n    bottom: Math.max(...boxes.map(b => b!.top + b!.height)),\n    left: Math.min(...boxes.map(b => b!.left)),\n    right: Math.max(...boxes.map(b => b!.left + b!.width)),\n  };\n\n  return {\n    width: cellArea.right - cellArea.left,\n    height: cellArea.bottom - cellArea.top,\n    left: cellArea.left,\n    top: cellArea.top\n  }\n}\n"
  },
  {
    "path": "src/ui/setup/Setup.tsx",
    "content": "import React, { useCallback, useMemo } from 'react';\nimport Seating from './components/Seating.js';\nimport { gameStore } from '../store.js';\n\nimport type { SetupComponentProps } from './components/settingComponents.js';\nimport type { User, UpdatePlayersMessage, GameSettings } from '../Main.js';\n\nexport default ({ users, players, minPlayers, maxPlayers, setupComponents, settings, seatCount, onUpdatePlayers, onUpdateSettings }: {\n  users: User[],\n  players: User[],\n  minPlayers: number,\n  maxPlayers: number,\n  setupComponents: Record<string, (p: SetupComponentProps) => JSX.Element>\n  settings?: GameSettings,\n  seatCount: number,\n  onUpdatePlayers: (operations: UpdatePlayersMessage['operations']) => void,\n  onUpdateSettings: (update: {settings?: GameSettings, seatCount?: number}) => void,\n}) => {\n  const [userID, host] = gameStore(s => [s.userID, s.host]);\n\n  const self = useMemo(() => players.find(p => p.id === userID), [players, userID]);\n\n  const updateSettingsKey = useCallback((key: string, value: any) => {\n    onUpdateSettings({settings: { ...settings, [key]: value }});\n  }, [onUpdateSettings, settings])\n\n  const settingsComponents = setupComponents ?\n    Object.entries(setupComponents).map(([name, component]) => React.createElement(\n      component,\n      {\n        name,\n        key: name,\n        settings: settings || {},\n        players,\n        updateKey: updateSettingsKey\n      }\n    )) : [];\n\n  return (\n    <div id=\"setup\">\n      <div id=\"background\" className=\"full-page-cover\"/>\n      <div className={host ? '' : 'disabled'}>\n        <div className=\"heading\">\n          <h1>Game Setup</h1>\n          {host && <p>Use the invite link above to get other players to join.</p>}\n          {players.length < seatCount && <p>The game will start once <b>{seatCount}</b> players are seated and ready.</p>}\n          {players.length === seatCount && players.some(p => !p.playerDetails?.ready) && <p>Waiting for {players.filter(p => !p.playerDetails?.ready).map(p => p === self ? 'you' : p.name).reduce((s, p, i, t) => s + (s ? (i === t.length -1 ? ' and ' : ', ') : '') + p, '')} to start.</p>}\n        </div>\n        <Seating\n          users={users}\n          players={players}\n          minPlayers={minPlayers}\n          maxPlayers={maxPlayers}\n          seatCount={seatCount}\n          onUpdatePlayers={onUpdatePlayers}\n          onUpdateSettings={onUpdateSettings}\n        />\n        {settingsComponents.length > 0 && (\n          <div className=\"heading\">\n            <h2>Game Settings</h2>\n            <div id=\"settings\">\n              {settingsComponents}\n            </div>\n          </div>\n        )}\n        {self && (\n          <button\n            type=\"button\"\n            className=\"ready\"\n            onClick={() => onUpdatePlayers([{type: 'update', userID, ready: !self.playerDetails?.ready}])}\n          >\n            {self.playerDetails?.ready ? \"Wait, I'm not ready\" : (players.length === seatCount && players.filter(p => !p.playerDetails?.ready).length === 1 ? \"Start game\" : \"I'm ready\") }\n          </button>\n        )}\n      </div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "src/ui/setup/components/Seating.tsx",
    "content": "import React, { useCallback, useState } from 'react';\nimport { gameStore } from '../../store.js';\n\nimport { times } from '../../../utils.js';\nimport { colors } from '../../../interface.js';\nimport * as ReactColor from 'react-color';\nconst { GithubPicker } = ReactColor;\n\nimport type { User, UpdateOperation, UpdatePlayersMessage, GameSettings } from '../../Main.js';\n\nconst Seating = ({ users, players, minPlayers, maxPlayers, seatCount, onUpdatePlayers, onUpdateSettings }: {\n  users: User[],\n  players: User[],\n  minPlayers: number,\n  maxPlayers: number,\n  seatCount: number,\n  onUpdatePlayers: (operations: UpdatePlayersMessage['operations']) => void,\n  onUpdateSettings: (update: {settings?: GameSettings, seatCount?: number}) => void,\n}) => {\n  const [userID, host] = gameStore(s => [s.userID, s.host]);\n\n  const [pickingColor, setPickingColor] = useState<string>();\n\n  const rename = (id: string) => {\n    const user = users.find(u => u.id === id);\n    updateName(id, prompt(\"Please enter a name\", user?.name)!);\n  }\n\n  const seatPlayer = (position: number, id: string) => {\n    const user = users.find(u => u.id === id);\n    const unseats = players.filter(p => p.id === id && p.playerDetails?.position !== position || p.id !== id && p.playerDetails?.position === position);\n    const usedColors = players.filter(p => p.id !== id && p.playerDetails?.position !== position).map(p => p.playerDetails?.color);\n    const color = colors.find(c => !usedColors.includes(c))!;\n    if (!host && unseats.some(u => u.id !== userID)) return;\n\n    const operations: UpdatePlayersMessage['operations'] = unseats.map(u => (\n      {type: 'unseat', userID: u.id}\n    ));\n\n    // auto unready if changing seats around for more intuitive state game action\n    operations.push({ type: \"update\", userID, ready: false });\n\n    if (user && (host || id === userID)) {\n      operations.push({\n        type: \"seat\",\n        position,\n        userID: id,\n        color,\n        name: user.name,\n        settings: {}\n      });\n    }\n\n    onUpdatePlayers(operations);\n  }\n\n  const updateSeatCount = useCallback((count: number) => {\n    if (count < seatCount) {\n      // compress and unseat\n      const openSeats = [];\n      const operations: UpdatePlayersMessage['operations'] = [\n        // auto unready if reducing seats for more intuitive state game action\n        { type: \"update\", userID, ready: false }\n      ];\n\n      for (let i = 1; i <= maxPlayers; i++) {\n        const player = players.find(p => p.playerDetails?.position === i)\n        if (!player) {\n          openSeats.push(i)\n          continue;\n        }\n        if (player.playerDetails!.position > count) {\n          const openSeat = openSeats.shift();\n          operations.push({\n            type: \"unseat\",\n            userID: player.id,\n          });\n          if (openSeat) {\n            operations.push({\n              type: \"seat\",\n              position: openSeat,\n              userID: player.id,\n              color: player.playerDetails!.color,\n              name: player.name,\n              settings: player.playerDetails!.settings\n            });\n            operations.push({\n              type: \"update\",\n              userID: player.id,\n              ready: player.playerDetails?.ready\n            });\n          }\n        }\n      }\n      if (operations.length) onUpdatePlayers(operations);\n    }\n    onUpdateSettings({ seatCount: count });\n  }, [players, userID, seatCount, maxPlayers, onUpdatePlayers, onUpdateSettings]);\n\n  const updateColor = (id: string, color: string) => {\n    setPickingColor(undefined);\n    if (host || userID === userID) {\n      const operation: UpdateOperation = {\n        type: \"update\",\n        userID: id,\n        color,\n      };\n      onUpdatePlayers([operation]);\n    }\n  }\n\n  const updateName = (userID: string, name: string) => {\n    setPickingColor(undefined);\n    if (host || userID === userID) {\n      const operation: UpdateOperation = {\n        type: \"update\",\n        userID,\n        name,\n      };\n      onUpdatePlayers([operation]);\n    }\n  }\n\n  return (\n    <div id=\"seating\">\n      <div id=\"seats\">\n        {times(seatCount, position => {\n          const player = players.find(p => p.playerDetails?.position === position);\n          return (\n            <div className=\"seat\" key={position}>\n              <select\n                onDragOver={e => {e.preventDefault(); e.dataTransfer.dropEffect = \"move\";}}\n                onDrop={e => seatPlayer(position, e.dataTransfer.getData('user'))}\n                onMouseDown={e => {if (!host && !player) { seatPlayer(position, userID); e.preventDefault() }}}\n                value={player?.id || \"\"}\n                onChange={e => seatPlayer(position, e.target.value)}\n                disabled={!host && !!player?.id && player.id !== userID}\n                style={{backgroundColor: player?.playerDetails?.color ?? '#777' }}\n              >\n                {host ? (\n                  <>\n                    <option value=\"\">&lt; open seat &gt;</option>\n                    {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}\n                  </>\n                ) : (\n                  <>\n                    {player && <option value={userID}>{player.name}</option>}\n                    <option value={player ? \"\" : userID}>{player ? \"Leave\" : \"Take\"} seat</option>\n                  </>\n                )}\n              </select>\n              <img className=\"avatar\" draggable=\"false\" src={player?.avatar}/>\n              {player?.playerDetails?.ready && (\n                <div className=\"ready\">\n                  <svg\n                    style={{ width: \"1em\", height: \"1em\", verticalAlign: \"middle\" }}\n                    viewBox=\"25.762297 68.261274 213.23847 149.07793\"\n                    xmlns=\"http://www.w3.org/2000/svg\">\n                    <path\n                      fill=\"#21ff21\" stroke=\"black\" strokeWidth=\"30\" strokeLinecap=\"round\" strokeLinejoin=\"round\" paintOrder=\"stroke fill markers\"\n                      d=\"M 42.067911,162.20821 59.401006,144.01333 97.066979,181.31905 202.75316,75.448265 220.91697,93.183881 97.189426,217.33962 Z\" />\n                  </svg>\n                </div>\n              )}\n              {player && !player.playerDetails?.ready && (host || player.id === userID) && (\n                <>\n                  <div\n                    className=\"rename\"\n                    onClick={() => rename(player.id)}\n                  >\n                    <svg\n                      style={{ width: \"1em\", height: \"1em\", verticalAlign: \"middle\" }}\n                      viewBox=\"0 0 24 24\">\n                      <path d=\"M1 22C1 21.4477 1.44772 21 2 21H22C22.5523 21 23 21.4477 23 22C23 22.5523 22.5523 23 22 23H2C1.44772 23 1 22.5523 1 22Z\" fill=\"white\"/>\n                      <path fillRule=\"evenodd\" clipRule=\"evenodd\" d=\"M18.3056 1.87868C17.1341 0.707107 15.2346 0.707107 14.063 1.87868L3.38904 12.5526C2.9856 12.9561 2.70557 13.4662 2.5818 14.0232L2.04903 16.4206C1.73147 17.8496 3.00627 19.1244 4.43526 18.8069L6.83272 18.2741C7.38969 18.1503 7.89981 17.8703 8.30325 17.4669L18.9772 6.79289C20.1488 5.62132 20.1488 3.72183 18.9772 2.55025L18.3056 1.87868ZM15.4772 3.29289C15.8677 2.90237 16.5009 2.90237 16.8914 3.29289L17.563 3.96447C17.9535 4.35499 17.9535 4.98816 17.563 5.37868L15.6414 7.30026L13.5556 5.21448L15.4772 3.29289ZM12.1414 6.62869L4.80325 13.9669C4.66877 14.1013 4.57543 14.2714 4.53417 14.457L4.0014 16.8545L6.39886 16.3217C6.58452 16.2805 6.75456 16.1871 6.88904 16.0526L14.2272 8.71448L12.1414 6.62869Z\" fill=\"white\"/>\n                    </svg>\n                  </div>\n                  <div\n                    className=\"palette\"\n                    onClick={() => setPickingColor(picking => picking === player.id ? undefined : player.id)}\n                  >\n                    <svg\n                      style={{ width: \"1em\", height: \"1em\", verticalAlign: \"middle\" }}\n                      viewBox=\"0 0 316.249 288.333\"\n                    >\n                      <path\n                        fill=\"none\"\n                        stroke=\"white\"\n                        strokeLinecap=\"butt\"\n                        strokeWidth=\"20.315\"\n                        d=\"M242.888 162.508c-.23 34.436-17.432 73.325-39.074 94.779-25.529 25.308-59.475 39.242-95.596 39.242h-.038c-38.707-.011-96.13-26.903-96.141-64.034-.006-19.707 10.354-27.388 21.323-35.52 10.253-7.602 21.874-16.218 21.87-34.474-.006-18.253-11.63-26.874-21.886-34.479-10.974-8.139-21.34-15.826-21.346-35.535-.005-22.801 16.674-35.674 33.463-45.882 19.175-13.376 43.273-18.094 62.615-18.094h.021c29.491.008 57.517 9.254 81.048 26.736 21.702 16.125 44.463 42.573 47.947 75.486m-51.614 94.679c-6.358 25.196-22.356 37.968-47.594 37.967h-.006c-6.655 0-13.028-.908-18.386-2.04 6.4-6.527 8.399-16.349 10.13-24.858 3.297-16.208 6.415-31.547 31.923-35.191zm61.496-99.637c2.998-2.602 5.977-5.171 8.913-7.675 29.847-25.455 45.489-36.533 53.468-41.354-4.765 8.027-15.741 23.788-41.021 53.906-23.785 28.337-58.77 69.69-82.47 93.885l-25.1-23.827c21.488-21.39 60.491-52.614 86.21-74.935v0\"\n                      ></path>\n                      <circle\n                        cx=\"78.341\"\n                        cy=\"95.328\"\n                        r=\"22.398\"\n                        fill=\"none\"\n                        stroke=\"white\"\n                        strokeWidth=\"20.315\"\n                      ></circle>\n                      <circle\n                        cx=\"128.659\"\n                        cy=\"132.169\"\n                        r=\"22.398\"\n                        fill=\"none\"\n                        stroke=\"white\"\n                        strokeWidth=\"20.315\"\n                        transform=\"translate(24.304 -35.741)\"\n                      ></circle>\n                      <circle\n                        cx=\"79.964\"\n                        cy=\"223.845\"\n                        r=\"22.398\"\n                        fill=\"none\"\n                        stroke=\"white\"\n                        strokeWidth=\"20.315\"\n                      ></circle>\n                    </svg>\n                  </div>\n                  {pickingColor === player.id && (\n                    <GithubPicker\n                      color={player.playerDetails?.color}\n                      colors={colors.filter(c => c === player.playerDetails?.color || !players.map(p => p.playerDetails?.color).includes(c))}\n                      onChange={c => updateColor(player.id, c.hex)}\n                    />\n                  )}\n                </>\n              )}\n            </div>\n          );\n        })}\n        {host && seatCount < maxPlayers && (\n          <svg\n            className=\"addSeat\"\n            viewBox=\"-4.4276366 41.597518 239.72168 220.78024\"\n            xmlns=\"http://www.w3.org/2000/svg\"\n            onClick={() => updateSeatCount(seatCount + 1)}\n          >\n            <path\n              style={{fill: 'white', stroke: 'black', strokeWidth: 26.4583, strokeLinecap: 'round', strokeLinejoin: 'round', paintOrder: 'stroke markers fill'}}\n              d=\"m 105.68836,54.82669 20.19124,-5e-6 v 39.272268 l 39.32202,0.0606 -0.10104,20.077227 -39.22099,-0.0296 v 39.29772 l -20.19123,-1e-5 v -39.32986 l -39.17016,-0.0739 0.0094,-20.022317 39.16078,-0.1415 z\" />\n            <path\n              style={{fill: 'white', stroke: 'black', strokeWidth: 26.4583, strokeLinecap: 'round', strokeLinejoin: 'round', paintOrder: 'stroke markers fill'}}\n              d=\"M 115.43321,249.14914 8.8009906,142.51692 22.782624,128.29036 l 92.950586,91.87409 91.98988,-91.98987 14.34234,14.34234 z\" />\n          </svg>\n        )}\n        {host && seatCount > minPlayers && (\n          <svg\n            className=\"removeSeat\"\n            viewBox=\"-4.4276366 41.597518 239.72168 220.78024\"\n            xmlns=\"http://www.w3.org/2000/svg\"\n            onClick={() => updateSeatCount(seatCount - 1)}\n          >\n            <path\n              style={{fill: 'white', stroke: 'black', strokeWidth: 26.4583, strokeLinecap: 'round', strokeLinejoin: 'round', paintOrder: 'stroke markers fill'}}\n              d=\"m 65.664793,209.81572 0.10104,-20.07722 98.582377,0.13565 -0.009,20.02231 z\" />\n            <path\n              style={{fill: 'white', stroke: 'black', strokeWidth: 26.4583, strokeLinecap: 'round', strokeLinejoin: 'round', paintOrder: 'stroke markers fill'}}\n              d=\"M 115.4332,54.826137 222.06542,161.45836 208.08379,175.68492 115.1332,83.810827 23.143323,175.8007 8.8009825,161.45836 Z\" />\n          </svg>\n        )}\n      </div>\n      <div id=\"lobby\">\n        <div>Waiting in lobby</div>\n        <div id=\"users\">\n          {users.filter(u => !players.find(player => player.id === u.id)).map(\n            u => (\n              <div key={u.id} draggable={true} onDragStart={e => e.dataTransfer.setData('user', u.id)} className=\"user\">\n                <img draggable=\"false\" src={u.avatar}/>{u.name}\n              </div>\n            )\n          )}\n        </div>\n      </div>\n    </div>\n  );\n};\n\nexport default Seating;\n"
  },
  {
    "path": "src/ui/setup/components/settingComponents.tsx",
    "content": "import React, { useEffect } from 'react';\n\nimport type { User } from '../../Main.js'\n\nexport type SetupComponentProps = {\n  name: string,\n  settings: Record<string, any>,\n  players: User[],\n  updateKey: (key: string, value: any) => void,\n}\n\n/**\n * Provide a game setting that can be turned on or off.\n * @param label - Text label to appear next to the toggle\n * @param initial - The default toggle state\n * @category UI\n */\nexport const toggleSetting = (label: string, initial=false) => ({ name, settings, updateKey }: SetupComponentProps) => {\n  useEffect(() => {\n    if (settings[name] === undefined) updateKey(name, initial);\n  }, [name, settings, updateKey]);\n\n  return (\n    <div>\n      <input id={name} type=\"checkbox\" checked={settings?.[name] ?? false} onChange={e => updateKey(name, e.target.checked)}/>\n      <label htmlFor={name}>{label}</label>\n    </div>\n  );\n};\n\n/**\n * Provide a game setting that can be selected from a list of options.\n * @param label - Text label to appear next to the option list\n * @param choices - List of choices as key-value pairs, where the value will be\n * the text choice for the host and the key will the result of calling {@link\n * Game#setting}\n * @param initial - The key of preselected choice\n * @category UI\n */\nexport const choiceSetting = (label: string, choices: Record<string, string>, initial?: string) => ({ name, settings, updateKey }: SetupComponentProps) => {\n  useEffect(() => {\n    if (settings[name] === undefined) updateKey(name, initial ?? Object.keys(choices)[0]);\n  }, [name, settings, updateKey]);\n\n  return (\n    <div>\n      <label>{label}: </label>\n      <select value={settings?.[name]} onChange={e => updateKey(name, e.target.value)}>\n        {Object.entries(choices).map(([value, name]) => <option key={value} value={value}>{name}</option>)}\n      </select>\n    </div>\n  );\n};\n\n\n/**\n * Provide a game setting that can be entered as text.\n * @param label - Text label to appear next to the text box\n * @param initial - The initial text to appear by default\n * @category UI\n */\nexport const textSetting = (label: string, initial = \"\") => ({ name, settings, updateKey }: SetupComponentProps) => {\n  useEffect(() => {\n    if (settings[name] === undefined) updateKey(name, initial);\n  }, [name, settings, updateKey]);\n\n  return (\n    <div>\n      <label>{label}: </label>\n      <input value={settings?.[name] ?? \"\"} onChange={e => updateKey(name, e.target.value)}/>\n    </div>\n  );\n};\n\n/**\n * Provide a game setting that can be selected as a number.\n * @param label - Text label to appear next to the number select\n * @param min - The minimum number allowed\n * @param max - The maximum number allowed\n * @param initial - The starting value\n * @category UI\n */\nexport const numberSetting = (label: string, min: number, max: number, iniital?: number) => ({ name, settings, updateKey }: SetupComponentProps) => {\n  useEffect(() => {\n    if (settings[name] === undefined) updateKey(name, iniital ?? min);\n  }, [name, settings, updateKey]);\n\n  return (\n    <div>\n      <label>{label}: </label>\n      <input type=\"number\" min={min} max={max} value={settings?.[name] ?? String(min)} onChange={e => updateKey(name, parseInt(e.target.value))}/>\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/ui/store.ts",
    "content": "import React from 'react'\nimport { createWithEqualityFn } from \"zustand/traditional\";\nimport { shallow } from 'zustand/shallow';\nimport GameManager from '../game-manager.js'\nimport { Game } from '../board/index.js'\nimport Player from '../player/player.js';\nimport {\n  updateSelections,\n  UIMove,\n  removePlacementPiece,\n  decorateUIMove,\n  clearMove,\n  updateControls,\n  updatePrompts,\n} from './lib.js';\nimport {\n  applyLayouts,\n  applyDiff,\n  applyDOMKeys,\n} from './render.js';\n\nimport { ActionDebug } from '../game-manager.js'\nimport type { GameUpdateEvent, GameFinishedEvent, User } from './Main.js'\nimport type { BaseGame } from '../board/game.js'\nimport type { GameElement, Piece, PieceGrid } from '../board/index.js'\nimport type Selection from '../action/selection.js'\nimport type { Argument } from '../action/action.js'\nimport type { SetupFunction } from '../game-creator.js'\nimport type { GameState } from '../interface.js';\nimport type { ResolvedSelection } from '../action/selection.js';\nimport type { UI, UIRender } from './render.js';\n\nexport type GameStore = {\n  host: boolean;\n  setHost: (host: boolean) => void;\n  userID: string;\n  setUserID: (userID: string) => void;\n  dev?: boolean;\n  setDev: (dev?: boolean) => void;\n  setup?: SetupFunction;\n  setSetup: (s: SetupFunction) => void;\n  gameManager: GameManager;\n  isMobile: boolean;\n  updateState: (state: (GameUpdateEvent | GameFinishedEvent) & {state: GameState}, readOnly?: boolean) => void;\n  position?: number; // this player\n  move?: UIMove; // move in progress\n  cancellable: boolean;\n  selectMove: (move?: UIMove, args?: Record<string, Argument>) => void; // commit the choice and find new choices or process the choice\n  clearMove: () => void; // clear all move inputs\n  uncommittedArgs: Record<string, Argument>; // all current args that are submittable, including uncommitted board selections\n  controls?: {\n    style: React.CSSProperties;\n    name: string;\n    moves: UIMove[];\n  };\n  error?: string;\n  setError: (error: string) => void;\n  step?: string; // step from getPendingMoves\n  pendingMoves?: UIMove[]; // all pending moves from this point from getPendingMoves\n  prompt?: string; // prompt from getPendingMoves\n  boardPrompt?: string; // prompt for choosing board action\n  actionDescription?: string; // description of the current pending action\n  otherPlayerAction?: string;\n  actionDebug?: ActionDebug;\n  announcementIndex: number;\n  dismissAnnouncement: () => void;\n  boardSelections: Record<string, {\n    clickMoves: UIMove[];\n    dragMoves: {\n      move: UIMove;\n      drag: Selection | ResolvedSelection;\n    }[];\n    error?: string;\n  }>; // pending moves on board\n  disambiguateElement?: { element: GameElement, moves: UIMove[] };\n  selected?: GameElement[]; // selected elements on board. these are not committed, analagous to input state in a controlled form\n  selectElement: (moves: UIMove[], element: GameElement) => void;\n  automove?: number;\n  rendered?: UI;\n  renderedSequence: number;\n  setBoardSize: () => void;\n  aspectRatio?: number;\n  dragElement?: string;\n  setDragElement: (el?: string) => void;\n  dragOffset: {ref?: number, x?: number, y?: number}; // mutable non-reactive record of drag offset\n  dropSelections: UIMove[];\n  currentDrop?: GameElement;\n  setCurrentDrop: (el?: GameElement) => void;\n  placement?: { // placing a piece inside a grid as part of the current move\n    selected?: { row: number, column: number }; // player indicated choice, ready for validation/confirmation\n    piece: Piece<BaseGame> ; // temporary ghost piece\n    invalid?: boolean\n    into: PieceGrid<BaseGame>;\n    layout: UIRender['layouts'][number];\n    rotationChoices?: number[];\n  };\n  setPlacement: (placement: {column: number, row: number, rotation?: number}) => void; // select placement. not committed, analagous to input state in a controlled form\n  selectPlacement: (placement: {column: number, row: number, rotation?: number}) => void; // commit placement\n  infoElement?: {info: JSX.Element | boolean, element: GameElement };\n  setInfoElement: (el?: {info: JSX.Element | boolean, element: GameElement }) => void;\n  userOnline: Map<string, boolean>\n  setUserOnline: (id: string, online: boolean) => void\n}\n\nexport const createGameStore = () => createWithEqualityFn<GameStore>()((set, get) => ({\n  host: false,\n  setHost: host => set({ host }),\n  userID: '',\n  setUserID: userID => set({ userID }),\n  setDev: dev => set({ dev }),\n  setSetup: setup => set({ setup }),\n  gameManager: new GameManager(Player, Game),\n  isMobile: !!globalThis.navigator?.userAgent.match(/Mobi/),\n  updateState: (update, readOnly=false) => set(s => {\n    let { gameManager } = s;\n    const position = s.position || update.position;\n    window.clearTimeout(s.automove);\n\n    let state: GameStore = {\n      ...s,\n      position,\n      move: undefined,\n      prompt: undefined,\n      boardPrompt: undefined,\n      actionDescription: undefined,\n      otherPlayerAction: undefined,\n      renderedSequence: update.state.sequence,\n      announcementIndex: 0,\n      step: undefined,\n      boardSelections: {},\n      pendingMoves: undefined,\n      placement: undefined,\n    };\n\n    if (s.setup && (gameManager.phase === 'new' || update.state.sequence !== s.renderedSequence + 1)) {\n      gameManager = state.gameManager = s.setup(update.state);\n      // @ts-ignore;\n      window.game = gameManager.game;\n      // @ts-ignore;\n      for (const className of gameManager.game._ctx.classRegistry) window[className.name] = className;\n      const boardSize = gameManager.game.getBoardSize(window.innerWidth, window.innerHeight, !!globalThis.navigator?.userAgent.match(/Mobi/))\n      gameManager.game.setBoardSize(boardSize);\n    } else {\n      gameManager.players.fromJSON(update.state.players);\n      gameManager.game.fromJSON(update.state.board);\n      gameManager.players.assignAttributesFromJSON(update.state.players);\n      gameManager.setFlowFromJSON(update.state.position);\n    }\n    gameManager.contextualizeBoardToPlayer(gameManager.game.players.atPosition(position));\n    gameManager.phase = 'started';\n    gameManager.messages = update.state.messages;\n    gameManager.announcements = update.state.announcements;\n    gameManager.winner = [];\n\n    if (update.type === 'gameFinished') {\n      gameManager.players.setCurrent([]);\n      gameManager.phase = 'finished';\n      gameManager.winner = update.winners.map(p => gameManager.players.atPosition(p)!);\n    }\n    console.debug(`Game update for player #${position}. Current flow:\\n ${gameManager.flow().stacktrace()}`);\n    const rendered = applyLayouts(gameManager.game);\n    if (update.state.sequence === s.renderedSequence + 1 && state.rendered) applyDiff(rendered.game, rendered, state.rendered);\n    state.rendered = rendered;\n    gameManager.game.resetRefTracking();\n\n    if (!readOnly && update.type !== 'gameFinished') {\n      state = updateSelections(state)\n    }\n\n    s.gameManager.sequence = update.state.sequence;\n\n    return state;\n  }),\n\n  // pendingMove we're trying to complete, args are the ones we're committing to, pass no move/args for move cancellation\n  selectMove: (pendingMove?: UIMove, args?: Record<string, Argument>) => set(s => {\n    let state: GameStore = { ...s, cancellable: true };\n    if (pendingMove) {\n      args = { ...pendingMove.args, ...args };\n      state.move = { ...pendingMove, args };\n      state.uncommittedArgs = { ...args };\n      for (const sel of state.move.selections) {\n        // the current selection cannot be filled in unless explicity supplied. this could be a forced arg with a confirmation step\n        if (!args || !(sel.name in args)) delete state.move!.args[sel.name];\n      }\n      state.move = decorateUIMove(state.move);\n    } else {\n      get().clearMove();\n      state = get();\n      if (s.placement) {\n        // remove temporary placement piece\n        removePlacementPiece(s.placement);\n        state = {\n          ...state,\n          placement: undefined,\n          rendered: applyLayouts(s.gameManager.game)\n        };\n      }\n    }\n\n    return updateSelections(state);\n  }),\n\n  cancellable: false,\n  clearMove: () => set(clearMove()),\n  uncommittedArgs: {},\n  setError: error => set({ error }),\n  actions: [],\n  announcementIndex: 0,\n  dismissAnnouncement: () => set(s => ({ announcementIndex: s.announcementIndex + 1 })),\n  boardSelections: {},\n  pendingMoves: [],\n\n  selectElement: (moves: UIMove[], element: GameElement) => set(s => {\n    if (moves.length === 0) return {};\n    s.cancellable = true;\n    if (moves.length > 1) { // multiple moves are associated with this element (attached by getBoardSelections)\n      return updateSelections({\n        ...s,\n        selected: [element],\n        disambiguateElement: ({ element, moves })\n      });\n    }\n\n    const move = moves[0];\n    const selection = move.selections[0]; // simple one-selection UIMove created by getBoardSelections\n    if (!move.requireExplicitSubmit) {\n      // can be submitted\n      get().clearMove();\n      get().selectMove(move, {[selection.name]: element});\n      return {};\n    }\n\n    const selected = selection.isMulti() ? (\n      s.selected?.includes(element) ?\n        (s.selected ?? []).filter(s => s !== element) :\n        (s.selected ?? []).concat([element])\n    ) : (\n      s.selected?.[0] === element ? [] : [element]\n    );\n\n    const state: GameStore = {\n      ...s,\n      selected,\n      move,\n      pendingMoves: [move],\n      cancellable: true,\n      disambiguateElement: undefined,\n      uncommittedArgs: {\n        ...s.uncommittedArgs,\n        [selection.name]: selection.isMulti() ? selected : selected[0]\n      }\n    }\n    Object.assign(state, updateControls(state));\n    Object.assign(state, updatePrompts(state));\n    return state;\n  }),\n\n  setPlacement: ({ column, row, rotation }) => set(s => {\n    if (!s.placement || s.pendingMoves?.[0].selections[0]?.type !== 'place') return {};\n\n    const oldColumn = s.placement.piece.column;\n    const oldRow = s.placement.piece.row;\n    const oldRotation = s.placement.piece._rotation ?? 0;\n    const grid = s.placement.layout.grid!;\n    if (rotation !== undefined && oldRotation !== rotation) {\n      s.placement.piece._rotation = rotation;\n    }\n    const gridSize = s.placement.into._sizeNeededFor(s.placement.piece);\n    s.placement.piece.column = Math.max(grid.origin.column,\n      Math.min(grid.origin.column + grid.columns - gridSize.width,\n        Math.floor(column)\n      )\n    );\n    s.placement.piece.row = Math.max(grid.origin.row,\n      Math.min(grid.origin.row + grid.rows - gridSize.height,\n        Math.floor(row)\n      )\n    );\n    if (s.placement?.into.isOverlapping(s.placement.piece)) {\n      if ((rotation !== undefined && oldRotation !== rotation) || oldColumn === undefined || oldRow === undefined) {\n        // we have to try to fit\n        s.placement.into._fitPieceInFreePlace(s.placement.piece, grid.columns, grid.rows, grid.origin);\n        if (s.placement.piece.column === undefined) {\n          s.placement.piece.column = oldColumn;\n          s.placement.piece.row = oldRow;\n          s.placement.piece._rotation = oldRotation;\n          return {};\n        }\n      } else {\n        s.placement.piece.column = oldColumn;\n        s.placement.piece.row = oldRow;\n        s.placement.piece._rotation = oldRotation;\n        return {};\n      }\n    }\n    if (s.placement.piece.column === oldColumn && s.placement.piece.row === oldRow && s.placement.piece._rotation === oldRotation) return {};\n\n    s.placement.invalid = !!s.gameManager.getAction(s.pendingMoves?.[0].name, s.gameManager.players.atPosition(s.position!)!)._getError(\n      s.pendingMoves?.[0].selections[0],\n      {\n        ...s.move?.args,\n        '__placement__': [s.placement.piece.column ?? 1, s.placement.piece.row ?? 1, s.placement.piece.rotation]\n      }\n    );\n    const rendered = applyLayouts(s.gameManager.game);\n    applyDOMKeys(rendered.game, rendered, s.rendered!);\n\n    return {\n      cancellable: true,\n      rendered\n    };\n  }),\n\n  selectPlacement: ({ column, row, rotation }) => set(s => {\n    if (!s.pendingMoves) return { placement: undefined };\n    const error = s.gameManager.getAction(s.pendingMoves?.[0].name, s.gameManager.players.atPosition(s.position!)!)._getError(\n      s.pendingMoves?.[0].selections[0],\n      {\n        ...s.move?.args,\n        '__placement__': [column, row].concat(rotation ? [rotation] : [])\n      }\n    );\n    if (error) return { error };\n\n    // must be single move and single selection at this point\n    const state = {\n      placement: {\n        ...s.placement!,\n        selected: { row, column, rotation },\n      },\n    };\n\n    if (!s.pendingMoves[0].requireExplicitSubmit) {\n      get().clearMove()\n      get().selectMove(s.pendingMoves[0], { __placement__: [column, row].concat(rotation ? [rotation] : []) });\n      return state;\n    }\n\n    return updateSelections({\n      ...s,\n      ...state,\n      disambiguateElement: undefined,\n      uncommittedArgs: {\n        ...s.uncommittedArgs,\n        __placement__: [column, row].concat(rotation ? [rotation] : [])\n      }\n    });\n  }),\n\n  renderedSequence: -1,\n  setBoardSize: () => set(s => {\n    const boardSize = s.gameManager.game.getBoardSize(window.innerWidth, window.innerHeight, s.isMobile);\n    if ((boardSize.name !== s.gameManager.game._ui.boardSize?.name || boardSize.aspectRatio !== s.gameManager.game._ui.boardSize?.aspectRatio) && s.position) {\n      s.gameManager.game.setBoardSize(boardSize);\n      return {\n        aspectRatio: boardSize.aspectRatio,\n        rendered: applyLayouts(s.gameManager.game)\n      };\n    }\n    return {};\n  }),\n  setDragElement: dragElement => set(s => {\n    if (!dragElement) return { dragElement: undefined, dropSelections: [] };\n    const moves = s.boardSelections[dragElement].dragMoves;\n    let dropSelections: UIMove[] = [];\n    if (moves) for (let {move, drag} of moves) {\n      const elementChosen = {[move.selections[0].name]: s.gameManager!.game.atBranch(dragElement)};\n      const sel = drag.resolve({...(s.move?.args || {}), ...elementChosen});\n      // create new move with the dragElement included as an arg and the dropzone as the new selection\n      dropSelections.push(decorateUIMove({\n        name: move.name,\n        prompt: move.prompt,\n        args: { ...move.args, ...elementChosen },\n        selections: [sel]\n      }));\n    }\n    return { dragElement, dropSelections }\n  }),\n  dragOffset: {},\n  dropSelections: [],\n  setCurrentDrop: currentDrop => set(() => {\n    return { currentDrop };\n  }),\n  setInfoElement: infoElement => set({ infoElement }),\n  setUserOnline: (id: string, online: boolean) => {\n    set(s => {\n      const userOnline = new Map(s.userOnline)\n      userOnline.set(id, online)\n      return { userOnline }\n    })\n  },\n  userOnline: new Map(),\n}), shallow);\n\nexport const gameStore = createGameStore();\n\nexport type SetupComponentProps = {\n  name: string,\n  settings: Record<string, any>,\n  players: User[],\n  updateKey: (key: string, value: any) => void,\n}\n"
  },
  {
    "path": "src/utils.ts",
    "content": "import type { Argument } from './action/action.js';\nimport { escapeArgument } from './action/utils.js';\n\nexport const shuffleArray = (array: any[], random: () => number) => {\n  for (let i = array.length - 1; i > 0; i--) {\n    const j = Math.floor(random() * (i + 1));\n    [array[i], array[j]] = [array[j], array[i]];\n  }\n}\n\n// usage times(max, n => ...) from 1 to max\nexport const times = <T>(n: number, fn: (n: number) => T): T[] => Array.from(Array(n)).map((_, i) => fn(i + 1));\nexport const range = (min: number, max: number, step = 1) => times(Math.floor((max - min) / step) + 1, i => (i - 1) * step + min);\n\nexport const n = (message: string, args?: Record<string, Argument>, escaped: boolean = false) => {\n  Object.entries(args || {}).forEach(([k, v]) => {\n    message = message.replace(new RegExp(`\\\\{\\\\{\\\\s*${k}\\\\s*\\\\}\\\\}`), escaped ? escapeArgument(v) : v.toString());\n  })\n\n  const missingArgs = Array.from(message.matchAll(new RegExp(`\\\\{\\\\{\\\\s*(\\\\w+)\\\\s*\\\\}\\\\}`, 'g'))).map(([, arg]) => arg);\n  if (missingArgs.length) throw Error(`Missing strings in:\\n${message}\\nAll substitution strings must be specified in 2nd parameter. Missing: ${missingArgs.join('; ')}`);\n\n  return message;\n}\n\nexport const equals = (a: any, b: any) => {\n  if (a === b) return true;\n\n  if (a && b && typeof a == 'object' && typeof b == 'object') {\n    if (a.constructor !== b.constructor) return false;\n\n    let length, i, keys;\n    if (Array.isArray(a)) {\n      length = a.length;\n      if (length != b.length) return false;\n      for (i = length; i-- !== 0;)\n        if (!equals(a[i], b[i])) return false;\n      return true;\n    }\n\n    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n    keys = Object.keys(a);\n    length = keys.length;\n    if (length !== Object.keys(b).length) return false;\n\n    for (i = length; i-- !== 0;)\n      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n    for (i = length; i-- !== 0;) {\n      const key = keys[i];\n      if (!equals(a[key], b[key])) return false;\n    }\n\n    return true;\n  }\n\n  // true if both NaN, false otherwise\n  return a!==a && b!==b;\n};\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es2020\",\n    \"module\": \"nodenext\",\n    \"resolveJsonModule\": true,\n    \"outDir\": \"dist\",\n    \"esModuleInterop\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"sourceMap\": true,\n    \"noImplicitAny\": true,\n    \"strictNullChecks\": true,\n    \"jsx\": \"react\",\n    \"incremental\": true\n  },\n  \"include\": [\"decl.d.ts\", \"./src\"],\n  \"ts-node\": {\n    \"esm\": true,\n    \"experimentalSpecifierResolution\": true,\n    \"files\": true,\n    \"ignore\": [\n      \".*scss\",\n      \".*ogg\",\n    ],\n  }\n}\n"
  },
  {
    "path": "tsfmt.json",
    "content": "{\n  \"tabSize\": 2,\n  \"indentSize\": 2,\n  \"convertTabsToSpaces\": true\n}\n"
  }
]