Compare commits

...
Sign in to create a new pull request.

81 commits

Author SHA1 Message Date
Eldritch-Oliver
9955966375 Add required package for the linkFoundry to package.json 2025-09-28 00:49:47 -06:00
Eldritch-Oliver
e84e921bec Add scripts and infra required to get Foundry intellisense working 2025-09-28 00:45:48 -06:00
2cb4268400
Merge pull request #42 from Oliver-Akins/feature/chatMessageHook
Update parsing for the roll auto-tracking to provide a more robust privacy detection when roll mode isn't provided
2025-06-22 10:32:32 -06:00
Oliver-Akins
1a8fcf04ab Remove stray log 2025-06-22 10:30:23 -06:00
Oliver-Akins
8905cb05bc Update the message listening to use createChatMessage instead of preCreateChatMessage 2025-06-13 19:28:08 -06:00
Oliver-Akins
8c42f1b240 Add a utility to the API for inferring a chat message's roll mode (and update the docs) 2025-06-13 19:27:39 -06:00
Oliver-Akins
cbc2691a0e Update privacy detection to default to Self if it's not able to be otherwise determined 2025-06-12 22:04:01 -06:00
Oliver-Akins
a72c33b901 Rename files to better indicate that they're tests 2025-06-12 19:27:20 -06:00
Oliver-Akins
e4f37d56a6 Update the pre-filled draft release template to include the changes header and a download count badge 2025-06-11 01:01:14 -06:00
Oliver-Akins
d8121dbfaa Get GitHub to put both badges on the same row 2025-06-11 00:56:29 -06:00
Oliver-Akins
612f52bf51 Use URL-encoded URL for the badge 2025-06-11 00:52:56 -06:00
Oliver-Akins
7859d23d50 Add a couple of version badges because I want to 2025-06-11 00:51:14 -06:00
34975156c1
Merge pull request #37 from Oliver-Akins/feature/manifest-description
Add a description to the module manifest
2025-06-04 21:33:05 -06:00
Oliver-Akins
a773ce4688 Add description to manifest 2025-06-04 21:31:36 -06:00
c27c47661c
Merge pull request #36 from Oliver-Akins/fix/double-locked-buckets
Prevent the double-locked bucket configuration
2025-06-04 21:25:15 -06:00
c90ee7a6d3
Merge pull request #35 from Oliver-Akins/fix/bucket-type-list
Prevent erroneous range bucket types from existing
2025-06-04 21:21:20 -06:00
Oliver-Akins
00d63d42d1 Remove stray logs 2025-06-04 21:20:54 -06:00
Oliver-Akins
4b11d12f81 Undo code that got commented out 2025-06-04 21:18:10 -06:00
Oliver-Akins
4354a25866 Prevent the double-locked bucket configuration from being possible 2025-06-02 23:10:22 -06:00
Oliver-Akins
1423bf097a Version bump 2025-06-02 23:06:30 -06:00
Oliver-Akins
8f993adb47 Finish removing the Range bucket type that was accidentally still able to be created 2025-06-02 19:26:43 -06:00
Oliver-Akins
3fc8b654c7 Add images for the Foundry package listing 2025-06-01 16:08:34 -06:00
Oliver-Akins
ab3281b288 Update README 2025-06-01 15:47:39 -06:00
Oliver-Akins
cad04690ff Update the release creation to provide a direct manifest url in the description of the release 2025-06-01 15:00:23 -06:00
Oliver-Akins
8e83925abe Have the UserFlagDatabase validate the row's value according to the bucket schema during creation / updating 2025-06-01 14:59:06 -06:00
Oliver-Akins
fc3b041464 Expose the determinePrivacyFromRollMode within the API 2025-06-01 14:23:21 -06:00
Oliver-Akins
3d5e28189a Version bump 2025-06-01 14:23:18 -06:00
Oliver-Akins
bd4c32f65a Update documentation (closes #30) 2025-06-01 13:03:31 -06:00
Oliver-Akins
6ef20e1ec1 Remove action that I haven't implemented yet 2025-06-01 13:03:13 -06:00
Oliver-Akins
21b9cf5b2d Remove logs that aren't helpful for prod 2025-06-01 13:03:03 -06:00
Oliver-Akins
c6161dd312 Prevent errors when the flag is undefined on the user 2025-06-01 12:26:40 -06:00
Oliver-Akins
965cb26b51 Update the tests import not to be bundled for production 2025-06-01 11:25:10 -06:00
Oliver-Akins
c26b4318ee Finish writing the schema tests 2025-06-01 11:24:20 -06:00
Oliver-Akins
946a44edae Add missing import into the extraction script 2025-05-31 23:17:38 -06:00
Oliver-Akins
ac93a3342f Begin work on purging the range bucket type from the codebase 2025-05-31 23:16:13 -06:00
Oliver-Akins
5fe11fda0d Update db schemas 2025-05-31 23:15:42 -06:00
Oliver-Akins
22036c419d Begin writing tests 2025-05-31 23:15:24 -06:00
Oliver-Akins
d49998801f Remove TODO since it is handled by the watcher plugin 2025-05-31 17:28:23 -06:00
Oliver-Akins
60b01c55e1 Fix undefined reference error when updating a table (closes #27) 2025-05-31 15:33:40 -06:00
Oliver-Akins
d11262ad01 Make the bucket validator throw an error rather than returning a weird value 2025-05-31 15:32:22 -06:00
Oliver-Akins
af2dac394f Update the throw to not include the stack trace 2025-05-31 13:26:09 -06:00
Oliver-Akins
de69fdec0f Update vite to make dependabot happier 2025-05-31 11:04:43 -06:00
Oliver-Akins
d11b270019 Throw a more clear error when the compendia build fails 2025-05-31 11:03:55 -06:00
Oliver-Akins
0b89b0e54e Ensure that the manager doesn't error while prepping string buckets without a pre-existing choices config (closes #26) 2025-05-31 10:25:20 -06:00
Oliver-Akins
2c733385ef Close the TableCreator and dice namespace warning when the table is made successfully (closes #25) 2025-05-31 10:17:20 -06:00
Oliver-Akins
c7379a48f4 Increment version number 2025-05-31 10:05:08 -06:00
Oliver-Akins
79780e885b Only copy the licence and readme on production builds 2025-05-31 10:05:00 -06:00
Oliver-Akins
c23a656574 Make it so that I can test the prod build locally easier 2025-05-31 00:50:28 -06:00
Oliver-Akins
d888a0c9be Have the build delete all of the temp files 2025-05-31 00:28:12 -06:00
Oliver-Akins
033be40e80 Read the correct manifest file 2025-05-31 00:22:50 -06:00
Oliver-Akins
cf800f0a51 Update the github action to make it work with the prod.dist folder better 2025-05-31 00:17:45 -06:00
Oliver-Akins
d28f4af088 Add a build step to copy the license and readme into the build output. 2025-05-31 00:14:30 -06:00
Oliver-Akins
b70e4107b7 Add a license 2025-05-31 00:14:08 -06:00
Oliver-Akins
7b41343778 Improve logs in the compendia helpers 2025-05-30 23:59:14 -06:00
Oliver-Akins
777ea69b66 Update manifest version and bugs link 2025-05-30 23:58:50 -06:00
Oliver-Akins
1bcd01ed75 Rename github folder to .github 2025-05-30 23:55:13 -06:00
Oliver-Akins
8e667bf3ac Move the issue templates into the correct location so that they actually work 2025-05-30 23:53:00 -06:00
Oliver-Akins
9e037818a6 Finish creating the build step for prod to handle the compendia pack(s) 2025-05-30 23:50:59 -06:00
Oliver-Akins
66edecc217 Finish the majority of the docs that I feel are necessary for v1.0.0 2025-05-30 23:26:29 -06:00
Oliver-Akins
a7c11acc2f Add an action to delete a table (closes #21) 2025-05-30 23:25:34 -06:00
Oliver-Akins
b4b3becec0 Implement the deleteTable method on the MemoryDatabase 2025-05-30 23:24:51 -06:00
Oliver-Akins
de35935a2d Disable legend clicks in the graphs (closes #4) 2025-05-30 21:28:15 -06:00
Oliver-Akins
c7b9146e34 Remove logs that aren't required 2025-05-30 21:27:55 -06:00
Oliver-Akins
46400ca318 Make the migrationCheck methods synchronous 2025-05-30 21:27:23 -06:00
Oliver-Akins
5c1a332921 Keep writing initial documentation 2025-05-29 23:46:58 -06:00
Oliver-Akins
a13310aaad Allow each database to determine if a user is allowed to perform CRUD operations on tables 2025-05-29 23:42:14 -06:00
Oliver-Akins
2b782fd5ed Add issue templates for bug report and feature request 2025-05-29 23:35:04 -06:00
Oliver-Akins
cfc5b9e70a Add author info and links into the manifest file 2025-05-29 23:16:05 -06:00
Oliver-Akins
7c68dd0c31 Disable requiresReload on autoTrackRolls 2025-05-29 23:15:46 -06:00
Oliver-Akins
0a01528bd3 Set the correct setting name instead of trying to set a setting with the version name 2025-05-29 22:49:35 -06:00
Oliver-Akins
0af4be2cfb Update documentation Journal 2025-05-29 01:23:42 -06:00
Oliver-Akins
1e007af52a Add an API interface for performing DB migrations as required 2025-05-29 01:22:17 -06:00
Oliver-Akins
2567f5fb62 Add a build step in dev mode to create a symlink to the compendium packs on disk 2025-05-27 23:37:31 -06:00
Oliver-Akins
47deb24d67 Hard-override any configured database handler that is erroneous and freeze the config after ready. 2025-05-27 23:34:27 -06:00
Oliver-Akins
a354629839 Update the English documentation 2025-05-27 23:29:06 -06:00
Oliver-Akins
4b78ab4d01 Begin work on the English documentation in a compendium 2025-05-27 01:53:55 -06:00
Oliver-Akins
9b3751b281 Add a user setting to determine if the sidebar tab should be added 2025-05-25 18:21:29 -06:00
Oliver-Akins
12ac7edbc5 Add workflow to build the release 2025-05-25 18:08:18 -06:00
Oliver-Akins
52a64ca54b Make the schema a bit easier to read 2025-05-25 02:01:39 -06:00
Oliver-Akins
354b22da57 Add data validation and a world setting for enabling the Global API 2025-05-25 02:00:13 -06:00
Oliver-Akins
c3d632274a Ensure we conform to the API specification as closely as possible 2025-05-24 16:50:50 -06:00
54 changed files with 3249 additions and 281 deletions

2
.env.template Normal file
View file

@ -0,0 +1,2 @@
# The absolute path to the Foundry installation to create symlinks to
FOUNDRY_ROOT=""

53
.github/ISSUE_TEMPLATE/BugReport.yaml vendored Normal file
View file

@ -0,0 +1,53 @@
name: Bug Report
description: Have a bug to report, use this template!
labels:
- Bug
body:
- type: input
id: affected-version
attributes:
label: Affected Versions
description: >-
What version(s) of the stat-tracker module are you seeing this bug
happen on? If you put "latest" your bug report will be invalidated.
validations:
required: true
- type: input
id: system-id
attributes:
label: Game System
description: >-
What game system are you using the module with when you encounter the
bug?
placeholder: dnd5e
validations:
required: true
- type: textarea
id: description
attributes:
label: Bug Description
description: >-
Describe the bug you're encountering, the more detail you provide the
better.
validations:
required: true
- type: checkboxes
id: affected-environments
attributes:
label: Affected Environments
description: How are you accessing Foundry when you encounter this bug?
options:
- label: Desktop App
required: false
- label: Chrome
required: false
- label: Firefox
required: false
- type: textarea
id: support-summary
attributes:
label: Support Data
description: >-
Please open the settings tab in Foundry's sidebar, click "Support &
Issues", then press "Copy Report to Clipboard" and then paste that text
into the box below

View file

@ -0,0 +1,11 @@
name: Feature Request
description: Have a feature request? Use this template!
labels:
- Feature
body:
- type: textarea
attributes:
label: Description
description: A clear and concise description of the problem or missing capability
validations:
required: true

62
.github/workflows/draft-release.yaml vendored Normal file
View file

@ -0,0 +1,62 @@
name: Create Draft Release
on: [workflow_dispatch]
jobs:
everything:
runs-on: ubuntu-latest
steps:
# Checkout the repository
- uses: actions/checkout@v4
# Install node and NPM
- uses: actions/setup-node@v4
with:
node-version: "19"
# Install required packages
- run: npm install
- run: npm run build
- name: Reading the system.json for the version
id: "version"
run: cat prod.dist/module.json | echo version=`jq -r ".version"` >> "$GITHUB_OUTPUT"
# Check that tag doesn't exist
- uses: mukunku/tag-exists-action@v1.5.0
id: check-tag
with:
tag: "v${{ steps.version.outputs.version }}"
- name: "Ensure that the tag doesn't exist"
if: ${{ steps.check-tag.outputs.exists == 'true' }}
run: exit 1
- name: Move the manifest to a temp file
id: manifest-move
run: mv prod.dist/module.json prod.dist/module.temp.json
- name: Update the download property in the manifest
id: manifest-update
run: cat prod.dist/module.temp.json | jq -r --tab '.download = "https://github.com/${{ github.repository }}/releases/download/v${{ steps.version.outputs.version }}/release.zip"' > prod.dist/module.json
- name: Delete temp files from build
run: rm prod.dist/*.temp.*
- name: Create the zip
run: cd prod.dist; zip -r release.zip *
- name: Create the draft release
uses: ncipollo/release-action@v1
with:
tag: "v${{ steps.version.outputs.version }}"
commit: ${{ github.ref }}
draft: true
body: >
| <img aria-hidden="true" src="https://img.shields.io/github/downloads/Oliver-Akins/Foundry-Stat-Tracker/v${{ steps.version.outputs.version }}/release.zip?style=flat-square&color=%2300aa00">
|
| ### Changes:
| -
|
| This version can be installed using this manifest URL: https://github.com/Oliver-Akins/Foundry-Stat-Tracker/releases/download/v${{ steps.version.outputs.version }}/module.json
generateReleaseNotes: true
artifacts: "prod.dist/release.zip,prod.dist/module.json"
artifactsErrorsFailBuild: true

9
.gitignore vendored
View file

@ -1,3 +1,10 @@
# Ignore all of the binaries and stuff that gets built for Foundry from the raw
# JSON data because it's annoying seeing it in my git changes when it isn't actually
# needed.
/packs/**/*
!/packs/**/*/
!/packs/**/*.json
# Logs # Logs
logs logs
*.log *.log
@ -10,6 +17,8 @@ lerna-debug.log*
node_modules node_modules
/*.dist /*.dist
*.local *.local
.env
/foundry
# Editor directories and files # Editor directories and files
.vscode/* .vscode/*

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

373
LICENSE Normal file
View file

@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View file

@ -1,2 +1,30 @@
# Foundry-Stat-Tracker # Stats Tracker
A Foundry module that allows tracking arbitrary stats. This FoundryVTT module aims to provide a clean way of keeping track of any data
points you want within Foundry, whether that be dice rolls, or other things like
how many natural 1s to natural 20s you get.
I was inspired by the dicestats module, however it only allows tracking dice
statistics, which is something I found myself needing to work around and struggle
against, so I decided to make this module to fill that gap while improving upon
the graph rendering.
For more information on how to use this module, check out the "Documentation"
compendium within your world!
## Installation
<div style="display: flex; gap: 8px;">
<img aria-hidden="true" src="https://img.shields.io/github/v/release/Oliver-Akins/Foundry-Stat-Tracker?sort=semver&style=flat-square&label=Latest%20Stable%20Release&color=%23070">
<img aria-hidden="true" src="https://img.shields.io/github/v/release/Oliver-Akins/Foundry-Stat-Tracker?include_prereleases&sort=semver&style=flat-square&color=%23800&label=Latest%20Prerelease">
</div>
You can find a history of all releases on the [Foundry package listing](https://foundryvtt.com/packages/stat-tracker)
or in the [GitHub releases tab](https://github.com/Oliver-Akins/Foundry-Stat-Tracker/releases).
Prereleases will only be released to the GitHub page, so if you want to check
out those releases, you'll need to use those manifest links directly.
## Bugs or Feature Requests
Bugs and Feature Requests can be submitted via the [GitHub issues](https://github.com/Oliver-Akins/Foundry-Stat-Tracker/issues/new/choose).
Planned features can also be seen in the GitHub issues list.
## Contribution
Contribution guidelines / requirements coming soon.

14
augments.d.ts vendored Normal file
View file

@ -0,0 +1,14 @@
declare global {
class Hooks extends foundry.helpers.Hooks {};
const fromUuid = foundry.utils.fromUuid;
}
interface Actor {
/** The system-specific data */
system: any;
};
interface Item {
/** The system-specific data */
system: any;
};

View file

@ -45,6 +45,7 @@ export default [
}, },
languageOptions: { languageOptions: {
globals: { globals: {
__TITLE__: `readonly`,
__ID__: `readonly`, __ID__: `readonly`,
__VERSION__: `readonly`, __VERSION__: `readonly`,
}, },

View file

@ -1,10 +1,22 @@
{ {
"compilerOptions": { "compilerOptions": {
"module": "ES2020", "module": "ES2020",
"target": "ES2020" "target": "ES2020",
"types": [
"./augments.d.ts"
],
"paths": {
"@client/*": ["./foundry/client/*"],
"@common/*": ["./foundry/common/*"],
}
}, },
"exclude": ["node_modules", "**/node_modules/*"], "exclude": ["node_modules", "**/node_modules/*"],
"include": ["module/**/*"], "include": [
"module/**/*",
"foundry/client/client.mjs",
"foundry/client/global.d.mts",
"foundry/common/primitives/global.d.mts"
],
"typeAcquisition": { "typeAcquisition": {
"include": ["joi"] "include": ["joi"]
} }

View file

@ -44,8 +44,10 @@ export class StatSidebar extends HandlebarsApplicationMixin(AbstractSidebarTab)
// manageData: { label: `Manage Data`, action: `` }, // manageData: { label: `Manage Data`, action: `` },
}; };
if (!game.user.isGM) { if (!db.canCreateTables()) {
delete controls.createTable; delete controls.createTable;
};
if (!db.canEditTables()) {
delete controls.manageTables; delete controls.manageTables;
}; };
@ -55,7 +57,6 @@ export class StatSidebar extends HandlebarsApplicationMixin(AbstractSidebarTab)
// delete controls.manageData; // delete controls.manageData;
// }; // };
Hooks.callAll(`${__ID__}.getStatsSidebarControls`, controls);
ctx.controls = Object.values(controls); ctx.controls = Object.values(controls);
return ctx; return ctx;

View file

@ -21,10 +21,10 @@ export class StatsViewer extends HandlebarsApplicationMixin(ApplicationV2) {
resizable: true, resizable: true,
minimizable: true, minimizable: true,
controls: [ controls: [
{ // {
label: `Add All Users To Graph`, // label: `Add All Users To Graph`,
action: `addAllUsers`, // action: `addAllUsers`,
}, // },
], ],
}, },
position: { position: {
@ -84,11 +84,11 @@ export class StatsViewer extends HandlebarsApplicationMixin(ApplicationV2) {
// #endregion Instance Data // #endregion Instance Data
// #region Lifecycle // #region Lifecycle
async render({ userUpdated, ...opts } = {}) { async render({ userUpdated, ...opts } = {}, _options) {
if (userUpdated && !this._selectedUsers.includes(userUpdated)) { if (userUpdated && !this._selectedUsers.includes(userUpdated)) {
return; return;
} }
await super.render(opts); await super.render(opts, _options);
}; };
async _onFirstRender(context, options) { async _onFirstRender(context, options) {
@ -213,8 +213,6 @@ export class StatsViewer extends HandlebarsApplicationMixin(ApplicationV2) {
this._privacySetting, this._privacySetting,
); );
Logger.log(userData);
const data = {}; const data = {};
const allBuckets = new Set(); const allBuckets = new Set();
@ -266,6 +264,11 @@ export class StatsViewer extends HandlebarsApplicationMixin(ApplicationV2) {
stacked: table.graph?.stacked ?? false, stacked: table.graph?.stacked ?? false,
}, },
}, },
plugins: {
legend: {
onClick: null,
},
},
}, },
data: { data: {
labels: sortedBucketNames, labels: sortedBucketNames,
@ -281,7 +284,6 @@ export class StatsViewer extends HandlebarsApplicationMixin(ApplicationV2) {
}), }),
}, },
}; };
console.log(`graphData`, this._graphData);
}; };
// #endregion Data Prep // #endregion Data Prep

View file

@ -75,7 +75,7 @@ export class TableCreator extends HandlebarsApplicationMixin(ApplicationV2) {
if (this._name.startsWith(`Dice`)) { if (this._name.startsWith(`Dice`)) {
ctx.createButtonDisabled = !this._name.match(diceNamespacePattern); ctx.createButtonDisabled = !this._name.match(diceNamespacePattern);
ctx.typeDisabled = true; ctx.typeDisabled = true;
ctx.type = BucketTypes.RANGE; ctx.type = BucketTypes.NUMBER;
this.#diceNamespaceAlert ??= ui.notifications.info( this.#diceNamespaceAlert ??= ui.notifications.info(
`Tables in the "Dice" namespace must be formatted as "Dice/dX" where X is the number of sides on the die and are restricted to be ranges 1 to X.`, `Tables in the "Dice" namespace must be formatted as "Dice/dX" where X is the number of sides on the die and are restricted to be ranges 1 to X.`,
{ permanent: true }, { permanent: true },
@ -104,11 +104,11 @@ export class TableCreator extends HandlebarsApplicationMixin(ApplicationV2) {
return; return;
}; };
Logger.log(`updating ${binding} value to ${target.value}`);
this[binding] = target.value; this[binding] = target.value;
this.render(); this.render();
}; };
/** @this {TableCreator} */
static async #createTable() { static async #createTable() {
/** @type {string} */ /** @type {string} */
const name = this._name; const name = this._name;
@ -122,25 +122,38 @@ export class TableCreator extends HandlebarsApplicationMixin(ApplicationV2) {
return; return;
}; };
let created = false;
if (name.startsWith(`Dice`)) { if (name.startsWith(`Dice`)) {
if (!name.match(diceNamespacePattern)) { if (!name.match(diceNamespacePattern)) {
ui.notifications.error(`Table name doesn't conform to the "Dice/dX" format required by the Dice namespace.`); ui.notifications.error(`Table name doesn't conform to the "Dice/dX" format required by the Dice namespace.`);
return; return;
}; };
const size = Number(name.replace(`Dice/d`, ``)); const size = Number(name.replace(`Dice/d`, ``));
await CONFIG.stats.db.createTable(createDiceTable(size)); created = await CONFIG.stats.db.createTable(createDiceTable(size));
return; if (created) {
}; this.close();
ui.notifications.remove(this.#diceNamespaceAlert);
this.#diceNamespaceAlert = null;
};
} else {
created = await CONFIG.stats.db.createTable({
name,
buckets: {
type: this._type,
},
graph: {
type: `bar`,
stacked: true,
},
});
}
await CONFIG.stats.db.createTable({ if (created) {
name, this.close();
buckets: { if (this.#diceNamespaceAlert) {
type: this._type, ui.notifications.remove(this.#diceNamespaceAlert);
}, this.#diceNamespaceAlert = null;
graph: { };
type: `bar`, };
stacked: true,
},
});
}; };
}; };

View file

@ -4,7 +4,7 @@ import { filePath } from "../consts.mjs";
import { Logger } from "../utils/Logger.mjs"; import { Logger } from "../utils/Logger.mjs";
import { smallToLarge } from "../utils/sorters/smallToLarge.mjs"; import { smallToLarge } from "../utils/sorters/smallToLarge.mjs";
const { HandlebarsApplicationMixin, ApplicationV2 } = foundry.applications.api; const { HandlebarsApplicationMixin, ApplicationV2, DialogV2 } = foundry.applications.api;
const { isEmpty } = foundry.utils; const { isEmpty } = foundry.utils;
export class TableManager extends HandlebarsApplicationMixin(ApplicationV2) { export class TableManager extends HandlebarsApplicationMixin(ApplicationV2) {
@ -24,6 +24,12 @@ export class TableManager extends HandlebarsApplicationMixin(ApplicationV2) {
contentClasses: [`st-scrollable`], contentClasses: [`st-scrollable`],
controls: [ controls: [
// Add action for deleting the table // Add action for deleting the table
{
icon: `fa-solid fa-trash`,
label: `Delete Selected Table`,
action: `deleteTable`,
visible: () => CONFIG.stats.db.canDeleteTables(),
},
], ],
}, },
position: { position: {
@ -35,7 +41,9 @@ export class TableManager extends HandlebarsApplicationMixin(ApplicationV2) {
closeOnSubmit: false, closeOnSubmit: false,
handler: this.#submit, handler: this.#submit,
}, },
actions: {}, actions: {
deleteTable: this.#deleteTable,
},
}; };
static PARTS = { static PARTS = {
@ -202,7 +210,7 @@ export class TableManager extends HandlebarsApplicationMixin(ApplicationV2) {
}; };
async _prepareStringContext(ctx, table) { async _prepareStringContext(ctx, table) {
ctx.buckets.choices = [...table.buckets.choices]; ctx.buckets.choices = [...(table.buckets.choices ?? [])];
}; };
// #endregion Data Prep // #endregion Data Prep
@ -239,5 +247,31 @@ export class TableManager extends HandlebarsApplicationMixin(ApplicationV2) {
} }
await CONFIG.stats.db.updateTable(this.activeTableID, formData.object); await CONFIG.stats.db.updateTable(this.activeTableID, formData.object);
}; };
/**
* @this {TableManager}
*/
static async #deleteTable() {
const table = await CONFIG.stats.db.getTable(this.activeTableID);
if (!table) {
ui.notifications.error(
`You must select a table before you can delete it`,
{ console: false },
);
return;
};
const confirmed = await DialogV2.confirm({
window: {
title: `Confirm Deletion`,
},
content: `<p>Are you sure you want to delete the table: <code>${this.activeTableID}</code></p>`,
});
if (!confirmed) { return };
CONFIG.stats.db.deleteTable(this.activeTableID);
this._selectedTable = null;
this.render();
};
// #endregion Actions // #endregion Actions
}; };

View file

@ -0,0 +1,5 @@
## Testing
The stat-tracker module utilizes [quench](https://foundryvtt.com/packages/quench)
for it's end-to-end tests and unit tests, enabling us to be sure that the module
is as stable as possible and detect when there are breaking changes.

View file

@ -0,0 +1,13 @@
import { barGraphTests } from "./schemas/barGraph.test.mjs";
import { numberBucketTests } from "./schemas/numberBucket.test.mjs";
import { rowTests } from "./schemas/row.test.mjs";
import { stringBucketTests } from "./schemas/stringBucket.test.mjs";
import { tableTests } from "./schemas/table.test.mjs";
Hooks.on(`quenchReady`, (quench) => {
numberBucketTests(quench);
stringBucketTests(quench);
barGraphTests(quench);
tableTests(quench);
rowTests(quench);
});

View file

@ -0,0 +1,51 @@
import { api } from "../../api.mjs";
export function barGraphTests(quench) {
quench.registerBatch(
`${__ID__}.barGraphSchema`,
(ctx) => {
const { describe, it, expect } = ctx;
describe(`the bar graph schema`, () => {
it(`should default any additional properties left out`, () => {
const { value, error } = api.schemas.graphs.bar.validate(
{ type: `bar` },
);
expect(value).to.have.keys(`type`, `stacked`, `showEmptyBuckets`);
expect(error).to.be.undefined;
});
it(`should allow stacked to be provided specifically`, () => {
const { value, error } = api.schemas.graphs.bar.validate(
{ type: `bar`, stacked: true },
);
expect(value).to.have.keys(`type`, `stacked`, `showEmptyBuckets`);
expect(error).to.be.undefined;
});
it(`should allow showEmptyBuckets to be provided specifically`, () => {
const { value, error } = api.schemas.graphs.bar.validate(
{ type: `bar`, showEmptyBuckets: true },
);
expect(value).to.have.keys(`type`, `stacked`, `showEmptyBuckets`);
expect(error).to.be.undefined;
});
it(`should only allow showEmptyBuckets to be a boolean`, () => {
const { value, error } = api.schemas.graphs.bar.validate(
{ type: `bar`, showEmptyBuckets: `a potato` },
);
expect(value).to.have.keys(`type`, `stacked`, `showEmptyBuckets`);
expect(error).not.to.be.undefined;
});
it(`should only allow stacked to be a boolean`, () => {
const { error } = api.schemas.graphs.bar.validate(
{ type: `bar`, stacked: `a potato` },
);
expect(error).not.to.be.undefined;
});
});
},
);
};

View file

@ -0,0 +1,61 @@
import { api } from "../../api.mjs";
export function numberBucketTests(quench) {
quench.registerBatch(
`${__ID__}.numberBucketSchema`,
(ctx) => {
const { describe, it, expect } = ctx;
describe(`the number bucket schema`, () => {
it(`should allow all additional properties to be left out`, () => {
const { error } = api.schemas.buckets.number.validate(
{ type: `number` },
);
expect(error).to.be.undefined;
});
it(`should allow the min additional property if only it is provided with the type`, () => {
const { error } = api.schemas.buckets.number.validate(
{ type: `number`, min: 0 },
);
expect(error).to.be.undefined;
});
it(`should allow the max additional property if only it is provided with the type`, () => {
const { error } = api.schemas.buckets.number.validate(
{ type: `number`, max: 10 },
);
expect(error).to.be.undefined;
});
it(`should not allow the step additional property if only it is provided with the type`, () => {
const { error } = api.schemas.buckets.number.validate(
{ type: `number`, step: 1 },
);
expect(error).not.to.be.undefined;
});
it(`should not allow max to be less than min`, () => {
const { error } = api.schemas.buckets.number.validate(
{ type: `number`, min: 10, max: 5 },
);
expect(error).not.to.be.undefined;
});
it(`should not allow max to be less than min`, () => {
const { error } = api.schemas.buckets.number.validate(
{ type: `number`, min: 10, max: 15 },
);
expect(error).to.be.undefined;
});
it(`should allow step when min is also provided`, () => {
const { error } = api.schemas.buckets.number.validate(
{ type: `number`, min: 10, step: 5 },
);
expect(error).to.be.undefined;
});
});
},
);
};

View file

@ -0,0 +1,96 @@
import { api } from "../../api.mjs";
import { PrivacyMode } from "../../utils/privacy.mjs";
export function rowTests(quench) {
quench.registerBatch(
`${__ID__}.rowSchema`,
(ctx) => {
const { describe, it, expect } = ctx;
describe(`the row schema`, () => {
it(`should allow number-based values`, () => {
const { error } = api.schemas.row.validate(
{
_id: `1`,
timestamp: (new Date()).toISOString(),
value: 1,
privacy: PrivacyMode.PUBLIC,
},
);
expect(error).to.be.undefined;
});
it(`should allow string-based values`, () => {
const { error } = api.schemas.row.validate(
{
_id: `1`,
timestamp: (new Date()).toISOString(),
value: `apple`,
privacy: PrivacyMode.PUBLIC,
},
);
expect(error).to.be.undefined;
});
it(`shouldn't allow invalid privacy modes`, () => {
const { error } = api.schemas.row.validate(
{
_id: `1`,
timestamp: (new Date()).toISOString(),
value: 1,
privacy: `yahaha`,
},
);
expect(error).not.to.be.undefined;
});
it(`shouldn't allow invalid value modes`, () => {
const { error } = api.schemas.row.validate(
{
_id: `1`,
timestamp: (new Date()).toISOString(),
value: true,
privacy: PrivacyMode.PUBLIC,
},
);
expect(error).not.to.be.undefined;
});
it(`shouldn't allow non-ISO date formats`, () => {
const { error } = api.schemas.row.validate(
{
_id: `1`,
timestamp: (new Date()).toDateString(),
value: 1,
privacy: PrivacyMode.PUBLIC,
},
);
expect(error).not.to.be.undefined;
});
it(`should require an ID to be present`, () => {
const { error } = api.schemas.row.validate(
{
timestamp: (new Date()).toISOString(),
value: true,
privacy: PrivacyMode.PUBLIC,
},
);
expect(error).not.to.be.undefined;
});
it(`shouldn't allow empty string as a value`, () => {
const { error } = api.schemas.row.validate(
{
_id: `1`,
timestamp: (new Date()).toISOString(),
value: ``,
privacy: PrivacyMode.PUBLIC,
},
);
expect(error).not.to.be.undefined;
});
});
},
);
};

View file

@ -0,0 +1,40 @@
import { api } from "../../api.mjs";
export function stringBucketTests(quench) {
quench.registerBatch(
`${__ID__}.stringBucketSchema`,
(ctx) => {
const { describe, it, expect } = ctx;
describe(`the string bucket schema`, () => {
it(`should allow all additional properties to be left out`, () => {
const { error } = api.schemas.buckets.string.validate(
{ type: `string` },
);
expect(error).to.be.undefined;
});
it(`should allow specific choices to be provided`, () => {
const { error } = api.schemas.buckets.string.validate(
{ type: `string`, choices: [`choice 1`, `choice 2`] },
);
expect(error).to.be.undefined;
});
it(`shouldn't allow specific choices to be empty`, () => {
const { error } = api.schemas.buckets.string.validate(
{ type: `string`, choices: [] },
);
expect(error).not.to.be.undefined;
});
it(`should only allow specific choices to be strings`, () => {
const { error } = api.schemas.buckets.string.validate(
{ type: `string`, choices: [`choice 1`, 5] },
);
expect(error).not.to.be.undefined;
});
});
},
);
};

View file

@ -0,0 +1,43 @@
import { api } from "../../api.mjs";
const graph = { type: `bar` };
const buckets = { type: `string` };
export function tableTests(quench) {
quench.registerBatch(
`${__ID__}.tableSchema`,
(ctx) => {
const { describe, it, expect } = ctx;
describe(`the table schema`, () => {
it(`should require that name be a non-empty string`, () => {
const { error } = api.schemas.table.validate(
{ name: ``, graph, buckets },
);
expect(error).not.to.be.undefined;
});
it(`should require that name only contain alphanumeric characters`, () => {
const { error } = api.schemas.table.validate(
{ name: `:(`, graph, buckets },
);
expect(error).not.to.be.undefined;
});
it(`should allow the name to contain spaces`, () => {
const { error } = api.schemas.table.validate(
{ name: `a name with spaces`, graph, buckets },
);
expect(error).to.be.undefined;
});
it(`should allow a single forward slash for subtables`, () => {
const { error } = api.schemas.table.validate(
{ name: `Table/subtable`, graph, buckets },
);
expect(error).to.be.undefined;
});
});
},
);
};

View file

@ -10,36 +10,44 @@ import { MemoryDatabase } from "./utils/databases/Memory.mjs";
import { UserFlagDatabase } from "./utils/databases/UserFlag.mjs"; import { UserFlagDatabase } from "./utils/databases/UserFlag.mjs";
// Utils // Utils
import { filterPrivateRows, PrivacyMode } from "./utils/privacy.mjs"; import { barGraphSchema, numberBucketSchema, rowSchema, stringBucketSchema, tableSchema } from "./utils/databases/model.mjs";
import { determinePrivacyFromRollMode, filterPrivateRows, PrivacyMode } from "./utils/privacy.mjs";
import { validateBucketConfig, validateValue } from "./utils/buckets.mjs"; import { validateBucketConfig, validateValue } from "./utils/buckets.mjs";
import { inferRollMode } from "./utils/inferRollMode.mjs";
const { deepFreeze } = foundry.utils; const { deepFreeze } = foundry.utils;
Object.defineProperty( export const api = deepFreeze({
globalThis, Apps: {
`stats`, TestApp,
{ StatsViewer,
value: deepFreeze({ TableCreator,
Apps: { TableManager,
TestApp,
StatsViewer,
TableCreator,
TableManager,
},
utils: {
filterPrivateRows,
validateValue,
validateBucketConfig,
},
enums: {
PrivacyMode,
},
databases: {
Database,
MemoryDatabase,
UserFlagDatabase,
},
}),
writable: false,
}, },
); utils: {
determinePrivacyFromRollMode,
inferRollMode,
filterPrivateRows,
validateValue,
validateBucketConfig,
},
enums: {
PrivacyMode,
},
databases: {
Database,
MemoryDatabase,
UserFlagDatabase,
},
schemas: {
buckets: {
number: numberBucketSchema,
string: stringBucketSchema,
},
graphs: {
bar: barGraphSchema,
},
table: tableSchema,
row: rowSchema,
},
});

View file

@ -0,0 +1,40 @@
import { determinePrivacyFromRollMode } from "../utils/privacy.mjs";
import { inferRollMode } from "../utils/inferRollMode.mjs";
Hooks.on(`createChatMessage`, (message, options, author) => {
const isSelf = author === game.user.id;
const isNew = options.action === `create`;
const hasRolls = message.rolls?.length > 0;
const autoTracking = game.settings.get(__ID__, `autoTrackRolls`);
if (!isSelf || !isNew || !hasRolls || !autoTracking) { return };
/** An object of dice denomination to database rows */
const rows = {};
const privacy = determinePrivacyFromRollMode(options.rollMode ?? inferRollMode(message));
/*
Goes through all of the dice within the message and grabs their result in order
to batch-save them all to the database handler.
*/
for (const roll of message.rolls) {
for (const die of roll.dice) {
const size = die.denomination;
rows[size] ??= [];
for (const result of die.results) {
rows[size].push({ privacy, value: result.result });
};
};
};
// save all the rows, then rerender once we're properly done
for (const denomination in rows) {
CONFIG.stats.db.createRows(
`Dice/${denomination}`,
author,
rows[denomination],
{ rerender: false },
);
};
CONFIG.stats.db.render({ userUpdated: author });
});

View file

@ -9,30 +9,36 @@ import { TableCreator } from "../Apps/TableCreator.mjs";
import { TableManager } from "../Apps/TableManager.mjs"; import { TableManager } from "../Apps/TableManager.mjs";
// Misc Imports // Misc Imports
import { api } from "../api.mjs";
import helpers from "../handlebarsHelpers/_index.mjs"; import helpers from "../handlebarsHelpers/_index.mjs";
import { Logger } from "../utils/Logger.mjs"; import { Logger } from "../utils/Logger.mjs";
import { registerCustomComponents } from "../Apps/elements/_index.mjs"; import { registerCustomComponents } from "../Apps/elements/_index.mjs";
import { registerMetaSettings } from "../settings/meta.mjs"; import { registerMetaSettings } from "../settings/meta.mjs";
import { registerUserSettings } from "../settings/user.mjs";
import { registerWorldSettings } from "../settings/world.mjs"; import { registerWorldSettings } from "../settings/world.mjs";
Hooks.on(`init`, () => { Hooks.on(`init`, () => {
Logger.debug(`Initializing`); Logger.debug(`Initializing`);
// Add a custom sidebar tab for the module
CONFIG.ui.sidebar.TABS.stats = {
active: false,
icon: `fa-solid fa-chart-line`,
tooltip: `Stats!`,
};
CONFIG.ui.stats = StatSidebar;
// Inject the tab right before settings;
const temp = CONFIG.ui.sidebar.TABS.settings;
delete CONFIG.ui.sidebar.TABS.settings;
CONFIG.ui.sidebar.TABS.settings = temp;
registerMetaSettings(); registerMetaSettings();
registerWorldSettings(); registerWorldSettings();
registerUserSettings();
// Add a custom sidebar tab for the module
if (game.settings.get(__ID__, `statsSidebarTab`)) {
CONFIG.ui.sidebar.TABS.stats = {
active: false,
icon: `fa-solid fa-chart-line`,
tooltip: `Stats!`,
};
CONFIG.ui.stats = StatSidebar;
// Inject the custom tab right before settings
const temp = CONFIG.ui.sidebar.TABS.settings;
delete CONFIG.ui.sidebar.TABS.settings;
CONFIG.ui.sidebar.TABS.settings = temp;
};
CONFIG.stats = { CONFIG.stats = {
db: UserFlagDatabase, db: UserFlagDatabase,
@ -45,6 +51,18 @@ Hooks.on(`init`, () => {
CONFIG.stats.db = MemoryDatabase; CONFIG.stats.db = MemoryDatabase;
}; };
game.modules.get(__ID__).api = api;
if (game.settings.get(__ID__, `globalAPI`)) {
Object.defineProperty(
globalThis,
`stats`,
{
value: api,
writable: false,
},
);
};
Handlebars.registerHelper(helpers); Handlebars.registerHelper(helpers);
registerCustomComponents(); registerCustomComponents();
}); });

View file

@ -1,30 +0,0 @@
import { determinePrivacyFromRollMode } from "../utils/privacy.mjs";
Hooks.on(`preCreateChatMessage`, (_message, context, options, author) => {
const isNew = options.action === `create`;
const hasRolls = context.rolls?.length > 0;
const autoTracking = game.settings.get(__ID__, `autoTrackRolls`);
if (!isNew || !hasRolls || !autoTracking) { return };
/** An object of dice denomination to rows to add */
const rows = {};
const privacy = determinePrivacyFromRollMode(options.rollMode);
for (const roll of context.rolls) {
for (const die of roll.dice) {
const size = die.denomination;
rows[size] ??= [];
for (const result of die.results) {
rows[size].push({ privacy, value: result.result });
};
};
};
for (const denomination in rows) {
CONFIG.stats.db.createRows(
`Dice/${denomination}`,
author,
rows[denomination],
);
};
});

View file

@ -1,12 +1,55 @@
import { Database } from "../utils/databases/Database.mjs"; import { Database } from "../utils/databases/Database.mjs";
import { Logger } from "../utils/Logger.mjs"; import { Logger } from "../utils/Logger.mjs";
import { NilDatabase } from "../utils/databases/NilDatabase.mjs";
Hooks.on(`ready`, () => { Hooks.on(`ready`, () => {
Logger.log(`Version: ${__VERSION__}`); Logger.log(`Version: ${__VERSION__}`);
// Alert GMs when the configured DB is invalid // Alert GMs when the configured DB is invalid
if (!(CONFIG.stats.db.prototype instanceof Database) && game.user.isGM) { if (!(CONFIG.stats.db.prototype instanceof Database) && game.user.isGM) {
ui.notifications.error(`The database handler does not conform to the required heirarchy, the stats tracker module will almost certainly not work correctly.`, { permanent: true }); ui.notifications.error(`The database adapter does not conform to the required specification, the stats tracker module overrode the configured database adapter with a stub to protect data that exists already.`, { permanent: true });
CONFIG.stats.db = NilDatabase;
}; };
/*
Perform any required data migration if any is required for the version
jump that the user may have caused. This only migrates the data iff the
currently authenticated user is able to perform the full migration of
data.
*/
const db = CONFIG.stats.db;
const lastVersion = game.settings.get(__ID__, `lastVersion`);
const canDoMigration = db.canPerformMigration();
const requiresMigration = db.requiresMigrationFrom(lastVersion);
if (requiresMigration) {
if (canDoMigration) {
const notif = ui.notifications.info(
`${__TITLE__} | Performing data migration, please do not close the window`,
{ progress: true, permanent: true },
);
// Fire and forget
CONFIG.stats.db.migrateData(lastVersion, notif)
.then(() => {
game.settings.set(__ID__, `lastVersion`, __VERSION__);
setTimeout(() => ui.notifications.remove(notif), 5_000);
});
} else {
ui.notifications.error(
`The stat-tracker database is out of date, temporarily disabling the stat-tracker module's functionality until the migration can be performed by a GM user logging into the world.`,
{ console: false, permanent: true },
);
CONFIG.stats.db = NilDatabase;
};
};
/*
Prevent any run-time modifications to the CONFIG API so that users can't wreck
themselves nor their data by fooling around with the values.
*/
if (import.meta.env.PROD) {
Object.freeze(CONFIG.stats);
};
CONFIG.stats.db.registerListeners(); CONFIG.stats.db.registerListeners();
}); });

View file

@ -5,4 +5,9 @@ import "./hooks/init.mjs";
import "./hooks/ready.mjs"; import "./hooks/ready.mjs";
// Document Hooks // Document Hooks
import "./hooks/preCreateChatMessage.mjs"; import "./hooks/createChatMessage.mjs";
// Dev Only imports
if (import.meta.env.DEV) {
import(`./__tests__/registration.mjs`);
};

View file

@ -23,4 +23,11 @@ export function registerMetaSettings() {
config: false, config: false,
requiresReload: false, requiresReload: false,
}); });
game.settings.register(__ID__, `lastVersion`, {
scope: `world`,
type: String,
config: false,
requiresReload: false,
});
}; };

11
module/settings/user.mjs Normal file
View file

@ -0,0 +1,11 @@
export function registerUserSettings() {
game.settings.register(__ID__, `statsSidebarTab`, {
name: `STAT_TRACKER.settings.statsSidebarTab.name`,
hint: `STAT_TRACKER.settings.statsSidebarTab.hint`,
scope: `user`,
type: Boolean,
config: true,
default: true,
requiresReload: true,
});
};

View file

@ -1,18 +1,26 @@
/* /*
World Settings: World Settings:
- Track rolls automatically
- Track inactive rolls (e.g. the "lower" in a "kh" roll) - Track inactive rolls (e.g. the "lower" in a "kh" roll)
- Track self rolls (defaulta false)
*/ */
export function registerWorldSettings() { export function registerWorldSettings() {
game.settings.register(__ID__, `autoTrackRolls`, { game.settings.register(__ID__, `autoTrackRolls`, {
name: `Roll Auto-Tracking`, name: `STAT_TRACKER.settings.autoTrackRolls.name`,
hint: `Whether or not the module should automatically add rolls made in the chat to the database. This is useful if the system you're using has implemented an integration with the module, or if you only want macros to handle the database additions.`, hint: `STAT_TRACKER.settings.autoTrackRolls.hint`,
scope: `world`, scope: `world`,
type: Boolean, type: Boolean,
config: true, config: true,
default: true, default: true,
requiresReload: false,
});
game.settings.register(__ID__, `globalAPI`, {
name: `STAT_TRACKER.settings.globalAPI.name`,
hint: `STAT_TRACKER.settings.globalAPI.hint`,
scope: `world`,
type: Boolean,
config: true,
default: import.meta.env.DEV,
requiresReload: true, requiresReload: true,
}); });
}; };

View file

@ -6,7 +6,6 @@ const { StringField, NumberField } = foundry.data.fields;
export const BucketTypes = { export const BucketTypes = {
STRING: `string`, STRING: `string`,
NUMBER: `number`, NUMBER: `number`,
RANGE: `range`,
}; };
/** /**
@ -52,8 +51,7 @@ export function validateBucketConfig(config) {
const validator = validators[conf.type]; const validator = validators[conf.type];
if (validator == null) { if (validator == null) {
Logger.error(`Failed to find type validator for: ${conf.type}`); throw new Error(`Failed to find type validator for: ${conf.type}`);
return false;
}; };
// Disallow function choices if present // Disallow function choices if present
@ -62,7 +60,7 @@ export function validateBucketConfig(config) {
delete conf.choices; delete conf.choices;
}; };
validator.validateConfig(conf); validator.validateConfig?.(conf);
return conf; return conf;
}; };
@ -75,7 +73,7 @@ const validators = {
opts.trim = true; opts.trim = true;
opts.blank = false; opts.blank = false;
}, },
validateConfig: (config) => { transformConfig: (config) => {
if (config.choices.length === 0) { if (config.choices.length === 0) {
delete config.choices; delete config.choices;
config[`-=choices`] = null; config[`-=choices`] = null;
@ -85,35 +83,6 @@ const validators = {
[BucketTypes.NUMBER]: { [BucketTypes.NUMBER]: {
field: NumberField, field: NumberField,
transformOptions: transformNumberFieldOptions, transformOptions: transformNumberFieldOptions,
validateConfig: (config) => {
if (config.step != null && config.min == null) {
delete config.step;
config[`-=step`] = null;
};
if (
config.min != null
&& config.max != null
&& config.min > config.max
) {
throw new Error(`"min" must be less than "max"`);
}
},
},
[BucketTypes.RANGE]: {
field: NumberField,
transformOptions: transformNumberFieldOptions,
validateConfig: (config) => {
if (config.min == null) {
throw new Error(`"min" must be defined for range buckets`);
};
if (config.max == null) {
throw new Error(`"max" must be defined for range buckets`);
};
if (config.min > config.max) {
throw new Error(`"min" must be less than "max"`);
}
config.step ??= 1;
},
}, },
}; };

View file

@ -1,6 +1,8 @@
/* eslint-disable no-unused-vars */ /* eslint-disable no-unused-vars */
import { BucketTypes, validateBucketConfig } from "../buckets.mjs";
import { Logger } from "../Logger.mjs";
import { PrivacyMode } from "../privacy.mjs"; import { PrivacyMode } from "../privacy.mjs";
import { validateBucketConfig } from "../buckets.mjs"; import { tableSchema } from "./model.mjs";
/* /*
NOTE: NOTE:
@ -26,35 +28,86 @@ Default Subtables:
tables that are parents to other tables. tables that are parents to other tables.
*/ */
const { deleteProperty, diffObject, expandObject, mergeObject } = foundry.utils; const { deleteProperty, diffObject, expandObject, isNewerVersion, mergeObject } = foundry.utils;
/**
* The generic Database implementation, any subclasses should implement all of
* the required methods, optionally overriding the methods provided by this class,
* data validation should be used on any and all of the create* methods to ensure
* consistency across databases.
*/
export class Database { export class Database {
// MARK: Permissions
/**
* Indicates whether the authenticated user has permission and is able to
* create tables with the specific database implementation. (because tables
* are stored as world settings by default, this checks if the user is a GM)
*/
static canCreateTables() {
return game.user.isGM;
};
/**
* Indicates whether the authenticated user has permission and is able to
* edit tables with the specific database implementation. (because tables
* are stored as world settings by default, this checks if the user is a GM)
*/
static canEditTables() {
return game.user.isGM;
};
/**
* Indicates whether the authenticated user has permission and is able to
* delete tables with the specific database implementation. (because tables
* are stored as world settings by default, this checks if the user is a GM)
*/
static canDeleteTables() {
return game.user.isGM;
};
// MARK: Table Ops // MARK: Table Ops
static async createTable(tableConfig) { static async createTable(tableConfig) {
if (!game.user.isGM) { if (!this.canCreateTables()) {
ui.notifications.error(`You do not have the required permission to create a new table`); ui.notifications.error(`You do not have the required permission to create a new table`);
return false; return false;
}; };
const name = tableConfig.name; const { error, value: corrected } = tableSchema.validate(
if (name.split(`/`).length > 2) { tableConfig,
ui.notifications.error(`Subtables are not able to have subtables`); { abortEarly: false, convert: true, dateFormat: `iso`, render: false },
);
if (error) {
ui.notifications.error(`Table being created did not conform to required schema, see console for more information.`, { console: false });
Logger.error(error);
return false; return false;
}; };
const tables = game.settings.get(__ID__, `tables`); const name = tableConfig.name;
const [ table, subtable ] = name.split(`/`); const [ table, subtable ] = name.split(`/`);
const tables = game.settings.get(__ID__, `tables`);
if (subtable && tables[table]) { if (subtable && tables[table]) {
ui.notifications.error(`Cannot add subtable for a table that already exists`); ui.notifications.error(`Cannot add subtable for a table that already exists`);
return false; return false;
}; };
if (table === `Dice`) {
if (!subtable.match(/^d[0-9]+$/)) {
ui.notifications.error(`Cannot create a Dice subtable that doesn't use "dX" as it's subtable name.`);
return false;
};
if (tableConfig.buckets.type === BucketTypes.RANGE) {
ui.notifications.error(`Cannot create a Dice subtable with a non-range bucket type`);
return false;
};
};
if (tables[name]) { if (tables[name]) {
ui.notifications.error(`Cannot create table that already exists`); ui.notifications.error(`Cannot create table that already exists`);
return false; return false;
}; };
tables[name] = tableConfig; tables[name] = corrected;
game.settings.set(__ID__, `tables`, tables); game.settings.set(__ID__, `tables`, tables);
this.render({ tags: [`table`] }); this.render({ tags: [`table`] });
return true; return true;
@ -73,8 +126,13 @@ export class Database {
}; };
static async updateTable(tableID, changes) { static async updateTable(tableID, changes) {
const table = this.getTable(tableID); if (!this.canEditTables()) {
if (!tables[tableID]) { ui.notifications.error(`You don't have the required permission to edit tables`);
return false;
};
const table = await this.getTable(tableID);
if (!table) {
ui.notifications.error(`Cannot update table that doesn't exist`); ui.notifications.error(`Cannot update table that doesn't exist`);
return false; return false;
}; };
@ -86,7 +144,7 @@ export class Database {
const diff = diffObject( const diff = diffObject(
table, table,
expandObject(changes), expandObject(changes),
{ inner: true, deletionKeys: true }, { deletionKeys: true },
); );
if (Object.keys(diff).length === 0) { return false }; if (Object.keys(diff).length === 0) { return false };
@ -99,7 +157,7 @@ export class Database {
try { try {
updated.buckets = validateBucketConfig(updated.buckets); updated.buckets = validateBucketConfig(updated.buckets);
} catch (e) { } catch (e) {
ui.notifications.error(e); Logger.error(e);
return false; return false;
}; };
@ -111,7 +169,7 @@ export class Database {
}; };
static async deleteTable(tableID) { static async deleteTable(tableID) {
if (!game.user.isGM) { if (!this.canDeleteTables()) {
ui.notifications.error(`You do not have the required permission to delete a table`); ui.notifications.error(`You do not have the required permission to delete a table`);
return false; return false;
}; };
@ -195,6 +253,63 @@ export class Database {
static async triggerListeners() {}; static async triggerListeners() {};
static async unregisterListeners() {}; static async unregisterListeners() {};
// MARK: Migrations
/**
* Determines if the currently authenticated user is capable of running
* the full migration on their own.
*
* @returns {boolean}
*/
static canPerformMigration() {
// TODO: this *must* account for isActiveGM, because otherwise the
// world setting cannot be updated after the migration finishes.
return game.user.isActiveGM;
};
/**
* Determines if the previous version of the plugin that was active
* needs to be migrated in order to work with the new version.
*
* @param {string} lastVersion The version that was last active
* @returns {boolean}
*/
static requiresMigrationFrom(lastVersion) {
return isNewerVersion(__VERSION__, lastVersion);
};
/**
* This method migrates ALL of the database data from one version of
* the module to the currently installed module. This is not guaranteed
* to run only on one client, so it should be made to be either
* idempotent, or have an operation locking mechanism that can prevent
* other clients from executing it if there's a migration in-progress.
*
* @param {string} lastVersion The last version that the user had active
* @param {Notification} notif The progress bar notification used for
* user feedback while performing migrations.
*/
static async migrateData(lastVersion, notif) {
const totalSteps = 1;
/*
This migration is for going up to 1.0.3, getting rid of any tables that have
a bucket type of range, since those were not supported within the initial
release, but could still accidentally be created by users.
*/
if (isNewerVersion(`1.0.3`, lastVersion)) {
Logger.log(`Migrating up to the v1.0.3 data structure`);
const tables = game.settings.get(__ID__, `tables`);
for (const table of Object.values(tables)) {
if (table.buckets.type !== `range`) { continue };
table.buckets.type = BucketTypes.NUMBER;
table.buckets.showEmptyBuckets = true;
};
await game.settings.set(__ID__, `tables`, tables);
notif.update({ pct: notif.pct + (1 / totalSteps) });
};
};
}; };
/* eslint-enable no-unused-vars */ /* eslint-enable no-unused-vars */

View file

@ -1,7 +1,6 @@
import { filterPrivateRows, PrivacyMode } from "../privacy.mjs"; import { filterPrivateRows, PrivacyMode } from "../privacy.mjs";
import { createDiceTable } from "./utils.mjs"; import { createDiceTable } from "./utils.mjs";
import { Database } from "./Database.mjs"; import { Database } from "./Database.mjs";
import { Logger } from "../Logger.mjs";
import { validateBucketConfig } from "../buckets.mjs"; import { validateBucketConfig } from "../buckets.mjs";
const { deleteProperty, diffObject, expandObject, mergeObject, randomID } = foundry.utils; const { deleteProperty, diffObject, expandObject, mergeObject, randomID } = foundry.utils;
@ -117,6 +116,10 @@ export class MemoryDatabase extends Database {
return true; return true;
}; };
static async deleteTable(tableID) {
return delete this.#tables[tableID];
};
static async createRow(table, userID, row, { rerender = true } = {}) { static async createRow(table, userID, row, { rerender = true } = {}) {
if (!this.#tables[table]) { return }; if (!this.#tables[table]) { return };
this.#rows[userID] ??= {}; this.#rows[userID] ??= {};
@ -126,7 +129,6 @@ export class MemoryDatabase extends Database {
row._id ||= randomID(); row._id ||= randomID();
row.timestamp = new Date().toISOString(); row.timestamp = new Date().toISOString();
Logger.debug(`Adding row:`, row);
this.#rows[userID][table].push(row); this.#rows[userID][table].push(row);
if (rerender) { if (rerender) {
this.render({ userUpdated: userID }); this.render({ userUpdated: userID });

View file

@ -0,0 +1,39 @@
import { Database } from "./Database.mjs";
/**
* This database implemention is not recommended for any actual usage,
* it is intended for overriding the current database implementation
* when a non-conforming Database is provided as the CONFIG.stats.db
* value in order to maintain the API interface for dependant modules
* and systems.
*/
export class NilDatabase extends Database {
// MARK: Table Ops
static async createTable() {};
static async getTables() {};
static async getTable() {};
static async updateTable() {};
static async deleteTable() {};
// MARK: Row Ops
static async createRow() {};
static async createRows() {};
static async getRows() {};
static async updateRow() {};
static async deleteRow() {};
// MARK: Applications
static addApp() {};
static removeApp() {};
static async render() {};
// MARK: Listeners
static async registerListeners() {};
static async triggerListeners() {};
static async unregisterListeners() {};
// MARK: Migrations
static async canPerformMigration() { return true };
static async requiresMigrationFrom() { return false };
static async migrateData() {};
};

View file

@ -1,6 +1,8 @@
import { filterPrivateRows, PrivacyMode } from "../privacy.mjs"; import { filterPrivateRows, PrivacyMode } from "../privacy.mjs";
import { Database } from "./Database.mjs"; import { Database } from "./Database.mjs";
import { Logger } from "../Logger.mjs"; import { Logger } from "../Logger.mjs";
import { rowSchema } from "./model.mjs";
import { validateValue } from "../buckets.mjs";
const { hasProperty, mergeObject, randomID } = foundry.utils; const { hasProperty, mergeObject, randomID } = foundry.utils;
@ -13,12 +15,22 @@ export class UserFlagDatabase extends Database {
let user = game.users.get(userID); let user = game.users.get(userID);
if (!table || !user) { return }; if (!table || !user) { return };
row._id ||= randomID(); row._id = randomID();
row.timestamp = new Date().toISOString(); row.timestamp = new Date().toISOString();
const userData = user.getFlag(__ID__, dataFlag); const { error, value: corrected } = rowSchema.validate(
row,
{ abortEarly: false, convert: true, dateFormat: `iso`, render: false },
);
if (error) {
ui.notifications.error(`Row being created did not conform to required schema, see console for more information.`, { console: false });
Logger.error(error);
return false;
};
const userData = user.getFlag(__ID__, dataFlag) ?? {};
userData[tableID] ??= []; userData[tableID] ??= [];
userData[tableID].push(row); userData[tableID].push(corrected);
await user.setFlag(__ID__, dataFlag, userData); await user.setFlag(__ID__, dataFlag, userData);
if (rerender) { if (rerender) {
@ -35,10 +47,44 @@ export class UserFlagDatabase extends Database {
const userData = user.getFlag(__ID__, dataFlag) ?? {}; const userData = user.getFlag(__ID__, dataFlag) ?? {};
userData[tableID] ??= []; userData[tableID] ??= [];
let valueErrorPosted = false;
let validationErrorPosted = false;
for (const row of rows) { for (const row of rows) {
row._id ||= randomID(); row._id = randomID();
row.timestamp = new Date().toISOString(); row.timestamp = new Date().toISOString();
userData[tableID].push(row);
const { error, value: corrected } = rowSchema.validate(
row,
{ abortEarly: false, convert: true, dateFormat: `iso`, render: false },
);
if (error) {
if (!validationErrorPosted) {
ui.notifications.error(
`One or more rows being created did not conform to required schema, skipping row and see console for more information.`,
{ console: false },
);
validationErrorPosted = true;
};
Logger.error(`Failing row:`, row);
Logger.error(error);
continue;
};
const validValue = validateValue(corrected.value, table.buckets);
if (!validValue) {
if (!valueErrorPosted) {
ui.notifications.warn(
`One or more rows being created did not contain a valid value, skipping row and see console for more information.`,
{ console: false },
);
valueErrorPosted = true;
};
Logger.warn(`Row with invalid value:`, row);
continue;
};
userData[tableID].push(corrected);
}; };
await user.setFlag(__ID__, dataFlag, userData); await user.setFlag(__ID__, dataFlag, userData);
@ -77,22 +123,36 @@ export class UserFlagDatabase extends Database {
const table = await this.getTable(tableID); const table = await this.getTable(tableID);
if (!table) { if (!table) {
Logger.error(`Cannot find the table with ID "${tableID}"`); Logger.error(`Cannot find the table with ID "${tableID}"`);
return; return false;
}; };
const user = game.users.get(userID); const user = game.users.get(userID);
if (!user) { if (!user) {
Logger.error(`Can't find the user with ID "${tableID}"`); Logger.error(`Can't find the user with ID "${tableID}"`);
return; return false;
}; };
const userData = user.getFlag(__ID__, dataFlag) ?? {}; const userData = user.getFlag(__ID__, dataFlag) ?? {};
let row = userData[tableID]?.find(row => row._id === rowID); let row = userData[tableID]?.find(row => row._id === rowID);
if (!row) { return }; if (!row) { return false };
if (hasProperty(changes, `value`)) {
const validValue = validateValue(changes.value, table.buckets);
if (!validValue) {
ui.notifications.warn(
`One or more rows being created did not contain a valid value, skipping row and see console for more information.`,
{ console: false },
);
Logger.warn(`Row with invalid value:`, row);
return false;
};
};
mergeObject(row, changes); mergeObject(row, changes);
await user.setFlag(__ID__, dataFlag, userData); await user.setFlag(__ID__, dataFlag, userData);
this.render({ userUpdated: userID }); this.render({ userUpdated: userID });
this.triggerListeners(); this.triggerListeners();
return true;
}; };
static async deleteRow(tableID, userID, rowID) { static async deleteRow(tableID, userID, rowID) {
@ -123,7 +183,6 @@ export class UserFlagDatabase extends Database {
if (this.#listener !== null) { return }; if (this.#listener !== null) { return };
this.#listener = Hooks.on(`updateUser`, (doc, diff, options, userID) => { this.#listener = Hooks.on(`updateUser`, (doc, diff, options, userID) => {
Logger.debug({ diff, userID, doc });
// Shortcircuit when on the client that triggered the update // Shortcircuit when on the client that triggered the update
if (userID === game.user.id) { return }; if (userID === game.user.id) { return };
if (!hasProperty(diff, `flags.${__ID__}.${dataFlag}`)) { return }; if (!hasProperty(diff, `flags.${__ID__}.${dataFlag}`)) { return };

View file

@ -1,43 +1,45 @@
import * as Joi from "joi"; import * as Joi from "joi";
import { PrivacyMode } from "../privacy.mjs";
// MARK: Buckets // MARK: Buckets
const numberBucketSchema = Joi.object({ export const numberBucketSchema = Joi.object({
type: Joi.string().valid(`number`, `range`).required(), type: Joi.string().valid(`number`).required(),
min: Joi min: Joi
.number() .number()
.integer() .integer()
.when(`type`, { .when(`step`, {
is: Joi.string().valid(`range`), is: Joi.exist(),
then: Joi.required(), then: Joi.required(),
otherwise: Joi.optional(),
}), }),
max: Joi max: Joi
.number() .number()
.integer() .integer()
.when(`type`, { .when(`min`, {
is: Joi.string().valid(`range`), is: Joi.exist(),
then: Joi.required(), then: Joi.number().greater(Joi.ref(`min`)),
otherwise: Joi.optional(),
}), }),
step: Joi step: Joi
.number() .number()
.integer() .integer()
.when(`type`, { .min(1),
is: Joi.string().valid(`range`),
then: Joi.required(),
otherwise: Joi.optional(),
}),
}); });
const stringBucketSchema = Joi.object({ export const stringBucketSchema = Joi.object({
type: Joi.string().valid(`string`).required(), type: Joi.string().valid(`string`).required(),
choices: Joi.array(Joi.string()).optional(), choices: Joi
.array()
.items(
Joi.string().trim().invalid(``),
)
.min(1)
.optional(),
}); });
// MARK: Graphs // MARK: Graphs
const barGraphSchema = Joi.object({ export const barGraphSchema = Joi.object({
type: Joi.string().valid(`bar`).required(), type: Joi.string().valid(`bar`).required(),
stacked: Joi.boolean().required(), stacked: Joi.boolean().optional().default(true),
showEmptyBuckets: Joi.boolean().optional().default(false),
}); });
// MARK: Table // MARK: Table
@ -45,16 +47,67 @@ export const tableSchema = Joi.object({
name: Joi name: Joi
.string() .string()
.trim() .trim()
.invalid(``)
.required() .required()
.pattern(/^[a-z \-_]+(\/[a-z \-_]+)?$/i), .pattern(/^[0-9a-z \-_]+(\/[0-9a-z \-_]+)?$/i),
buckets: Joi.alternatives([ buckets: Joi
numberBucketSchema, .alternatives()
stringBucketSchema, .conditional(
]).match(`one`), `/buckets.type`,
graph: Joi.alternatives([ {
barGraphSchema, switch: [
]).match(`one`), {
is: `number`,
then: numberBucketSchema,
},
{
is: `string`,
then: stringBucketSchema,
},
],
otherwise: Joi.forbidden(),
},
)
.required(),
graph: Joi
.alternatives()
.conditional(
`/graph.type`,
{
switch: [
{ is: `bar`, then: barGraphSchema },
],
otherwise: Joi.forbidden(),
},
)
.required(),
}); });
// MARK: Row // MARK: Row
export const rowSchema = Joi.object({}); /**
* The schema for the row objects, this does not validate that the
* value of the row conforms to the bucket configurations, however
* it does validate that the value is at least one of the accepted
* types. For validation of the value itself check "validateValue"
* in `utils/buckets.mjs`
*/
export const rowSchema = Joi.object({
_id: Joi
.string()
.alphanum()
.required(),
timestamp: Joi
.string()
.isoDate()
.required(),
value: Joi
.alternatives([
Joi.string().trim().invalid(``),
Joi.number(),
])
.required(),
privacy: Joi
.string()
.valid(...Object.values(PrivacyMode))
.required(),
});

View file

@ -2,7 +2,7 @@ export function createDiceTable(size) {
return { return {
name: `Dice/d${size}`, name: `Dice/d${size}`,
buckets: { buckets: {
type: `range`, type: `number`,
min: 1, min: 1,
max: size, max: size,
step: 1, step: 1,
@ -10,6 +10,7 @@ export function createDiceTable(size) {
graph: { graph: {
type: `bar`, type: `bar`,
stacked: true, stacked: true,
showEmptyBuckets: true,
}, },
}; };
}; };

View file

@ -0,0 +1,36 @@
/**
* A helper function to try and infer what roll mode was used when creating a
* chat message in case the roll mode was not provided during the createChatMessage
* hook for whatever reason.
*
* **Disclaimer**: This inference is not totally correct. Particularly when inferring
* a GM's message, as it won't be able to distinguish between a self-roll and a
* private GM roll when it's
*
* @param {ChatMessage} message The ChatMessage document to infer from
* @returns The Foundry-specified roll mode
*/
export function inferRollMode(message) {
const whisperCount = message.whisper.length;
if (whisperCount === 0) {
return CONST.DICE_ROLL_MODES.PUBLIC;
};
if (whisperCount === 1 && message.whisper[0] === game.user.id) {
return CONST.DICE_ROLL_MODES.SELF;
};
let allGMs = true;
for (const userID of message.whisper) {
const user = game.users.get(userID);
if (!user) { continue };
allGMs &&= user.isGM;
};
if (!allGMs) {
return CONST.DICE_ROLL_MODES.PUBLIC;
};
return message.blind
? CONST.DICE_ROLL_MODES.BLIND
: CONST.DICE_ROLL_MODES.PRIVATE;
};

View file

@ -11,6 +11,8 @@ export const PrivacyMode = Object.freeze({
export function determinePrivacyFromRollMode(rollMode) { export function determinePrivacyFromRollMode(rollMode) {
switch (rollMode) { switch (rollMode) {
case CONST.DICE_ROLL_MODES.PUBLIC:
return PrivacyMode.PUBLIC;
case CONST.DICE_ROLL_MODES.BLIND: case CONST.DICE_ROLL_MODES.BLIND:
return PrivacyMode.GM; return PrivacyMode.GM;
case CONST.DICE_ROLL_MODES.PRIVATE: case CONST.DICE_ROLL_MODES.PRIVATE:
@ -18,7 +20,7 @@ export function determinePrivacyFromRollMode(rollMode) {
case CONST.DICE_ROLL_MODES.SELF: case CONST.DICE_ROLL_MODES.SELF:
return PrivacyMode.SELF; return PrivacyMode.SELF;
} }
return PrivacyMode.PUBLIC; return PrivacyMode.SELF;
}; };
/** /**
@ -31,7 +33,6 @@ export function determinePrivacyFromRollMode(rollMode) {
* @returns The filtered rows * @returns The filtered rows
*/ */
export function filterPrivateRows(rows, userID, privacies) { export function filterPrivateRows(rows, userID, privacies) {
console.log({rows, userID, privacies});
const filtered = []; const filtered = [];
const isMe = userID === game.user.id; const isMe = userID === game.user.id;

938
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -7,16 +7,17 @@
"lint:nofix": "eslint", "lint:nofix": "eslint",
"dev": "NODE_ENV=development vite build --mode dev --watch", "dev": "NODE_ENV=development vite build --mode dev --watch",
"dev:once": "NODE_ENV=development vite build --mode dev", "dev:once": "NODE_ENV=development vite build --mode dev",
"staging": "NODE_ENV=staging vite build --mode dev --watch", "staging": "NODE_ENV=staging vite build --mode staging",
"staging:once": "NODE_ENV=staging vite build --mode dev",
"build": "NODE_ENV=production vite build --mode prod" "build": "NODE_ENV=production vite build --mode prod"
}, },
"devDependencies": { "devDependencies": {
"@foundryvtt/foundryvtt-cli": "^1.1.0",
"@stylistic/eslint-plugin": "^4.2.0", "@stylistic/eslint-plugin": "^4.2.0",
"dotenv": "^17.2.2",
"eslint": "^9.25.0", "eslint": "^9.25.0",
"glob": "^11.0.1", "glob": "^11.0.1",
"terser": "^5.39.0", "terser": "^5.39.0",
"vite": "^6.3.1" "vite": "^6.3.4"
}, },
"dependencies": { "dependencies": {
"chart.js": "^4.4.9", "chart.js": "^4.4.9",

View file

@ -0,0 +1,592 @@
{
"name": "English",
"_id": "pBOyeBDuTeowuDOE",
"pages": [
{
"sort": 100000,
"name": "Getting Started",
"type": "text",
"category": "mrZHFR2i0MYp7aaY",
"_id": "xcR48pakEm49hbc2",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>Thank you for installing Stat Tracker!</p><p>This module aims to provide a clean way of keeping track of any data points you want within Foundry, whether that be dice rolls, or other things like how many natural 1s to natural 20s you get.</p><p>I was inspired by the <a href=\"https://foundryvtt.com/packages/dicestats\" title=\"dicestats\">dicestats</a> module, however it only allows tracking dice statistics, which is something I found myself needing to work around and struggle against, so I decided to make this module to fill that gap while improving upon the graph rendering.</p><p>You've already done the hardest part of set up for this module to work on the basic level, installing it! However if you want a more advanced set up for the module, this Journal is your go-to for information.</p><p>This module makes use of multiple key terms which are important for your understanding, the main terms you need to understand are:</p><ul><li><p>@UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.S7Z6mZ0JablJVQJu]{Row}</p></li><li><p>@UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.ugzCCxQskUSYMZR4]{Table}</p></li><li><p>and, @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.e9FYKidbfFnnTspO]{Bucket}</p></li></ul><p>You can find information about what each of those terms mean within the \"Key Concepts\" section of the documentation or by clicking the above links.</p><p></p><h2>Dice Stats</h2><p>If you just want the module to track dice stats, then it's probably already done for you! All you need to do is start playing your game.</p><p>The only situation in which you <em>need </em>to do additional configuration for your game is if you are playing a game which doesn't use the standard dice sizes (d4, d6, d8, d10, d12, d20, d100), however you can add any dice size you want by creating a new table named <code>Dice/dX</code> where <code>X</code> is the number of sides the dice should have (e.g. for a 3-sided dice you would make the table name be <code>Dice/d3</code>). By adding a table in this way, it's configuration will be locked for editing and the only way to change it will be to delete the table entirely.</p><p></p><h2>System Support</h2><p>Currently this module does not support system-specific implementations, however in the future I am planning on adding support for systems as desired by users (the dnd5e system will be the first one supported once I can).</p><p></p><h2>Feature Requests and Bugs</h2><p>All feature requests and bug reports can go the module's GitHub page : <a href=\"https://github.com/Oliver-Akins/Foundry-Stat-Tracker/issues/new/choose\">https://github.com/Oliver-Akins/Foundry-Stat-Tracker/issues/new/choose</a></p>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748328891633,
"modifiedTime": 1748583825340,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.xcR48pakEm49hbc2"
},
{
"sort": 300000,
"name": "Table",
"type": "text",
"category": "ZPAbuPbVOLWh75hL",
"_id": "ugzCCxQskUSYMZR4",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>Tables are quite close to being a \"container\" for every piece of data within the module, every @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.S7Z6mZ0JablJVQJu]{row} within the module must be associated with a particular table. The table is responsible for maintaining all of the @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.e9FYKidbfFnnTspO]{bucket} and @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.IXZpEBEJsvOpY3OL]{graph} configurations, controlling what data is allowed to be saved and how to represent that data.</p><p></p><h2>Subtables</h2><p>Subtables are a concept used to group multiple tables together in a logical way, taking the <code>Dice/d10</code> table as an example, the \"table ID\" is the full <code>\"Dice/d10\"</code>, while the table name is <code>\"Dice\"</code> and the subtable name is <code>\"d10\"</code>. This allows the module to group all of the \"Dice\" tables together in the user interfaces.</p><p></p><h2>Limitations</h2><ul><li><p>Subtables can only go one level deep (e.g. <code>Table/SubTable/SubSubTable</code> is an invalid table ID and the module will reject it)</p></li><li><p>Subtables within the \"Dice\" table cannot be edited, they are required to use a @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.e9FYKidbfFnnTspO#range-buckets]{Range Bucket} and the settings are locked. This is because the module makes certain assumptions about the subtables within that space adhering to those requirements and making changes to them causes some issues. If you want to make a table that doesn't conform to those requirements, you can make a new table for your own purposes though!</p></li></ul>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748329356680,
"modifiedTime": 1748658060472,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.ugzCCxQskUSYMZR4"
},
{
"sort": 200000,
"name": "Row",
"type": "text",
"category": "ZPAbuPbVOLWh75hL",
"_id": "S7Z6mZ0JablJVQJu",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>Rows make up the vast majority of data that the stat tracker stores. Every dice roll, or custom entry, is saved as a single row.</p><p>Each row consists of the following data:</p><ul><li><p>The value (e.g. the result of a single dice roll)</p></li><li><p>A timestamp of when it was added to the database</p></li><li><p>A privacy mode (one for each of the Foundry-provided roll modes, see @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.WYaZPgSRDx8L7Zmq#privacy-modes]{Privacy Modes})</p></li><li><p>An identifier</p></li></ul><blockquote><p>This combination of data can end up becoming a lot of data to load when opening Foundry, if you don't think you'll be resetting the data very often, please consider checking out the different @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.PcdmuLgNM15h0in1]{Database Adapters} and picking one of them that is more suitable for your campaign.</p></blockquote>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748329454864,
"modifiedTime": 1748497975724,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.S7Z6mZ0JablJVQJu"
},
{
"sort": 400000,
"name": "Bucket",
"type": "text",
"category": "ZPAbuPbVOLWh75hL",
"_id": "e9FYKidbfFnnTspO",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>A bucket is the term used to identify a group of allowed values within a @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.ugzCCxQskUSYMZR4]{table}, each bucket must have a type, and a number of additional settings depending on what type it is.</p><p></p><h2>String Buckets</h2><p>This is the most simple type of bucket, it allows a string to be added as the row's value. The only additional configuration for this type of bucket is restricting what strings can be added be added.</p><p>e.g. you can limit each row to only have a value of <code>\"Critical Success\"</code>, or <code>\"Critical Failure\"</code> and if someone tries to add <code>\"Apple Sauce\"</code> into the table, it will reject that row.</p><p></p><h2>Number Buckets</h2><p>This type of bucket is likely the one you will utilize the most, it allows storing any number. It accepts an set of additional options described below, all of which are optional.</p><table><tbody><tr><td data-colwidth=\"128\"><p>Setting</p></td><td><p>Description</p></td></tr><tr><td data-colwidth=\"128\"><p>Minimum</p></td><td><p>The minimum allowed value.</p><p>Required when Step is provided.</p></td></tr><tr><td data-colwidth=\"128\"><p>Maximum</p></td><td><p>The maximum allowed value, must be greater than Minimum</p></td></tr><tr><td data-colwidth=\"128\"><p>Step</p></td><td><p>When a step is set it requires each number to be a \"step\" away from the lower one. So if you have a minimum of 2 and a step of 4, the allowed values are: 2, 6, 10, 14, 18, etc.</p></td></tr></tbody></table>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748329573212,
"modifiedTime": 1748803873692,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.e9FYKidbfFnnTspO"
},
{
"sort": 500000,
"name": "The Sidebar Tab",
"type": "text",
"category": "mrZHFR2i0MYp7aaY",
"_id": "ZI6rVlgXYnZGZ3MS",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>This stat tracker comes with a custom sidebar tab that provides a general overview of the module's state as well as short-cuts for opening and controlling settings of the module.</p><p>The primary actions within the sidebar are:</p><ul><li><p>Viewing the data in graphs</p></li><li><p>Creating a new @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.ugzCCxQskUSYMZR4]{table} (Gamemasters only)</p></li><li><p>Managing existing @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.ugzCCxQskUSYMZR4]{tables} (Gamemasters only)</p></li></ul>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748329854358,
"modifiedTime": 1748394635911,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.ZI6rVlgXYnZGZ3MS"
},
{
"sort": 600000,
"name": "Configuration",
"type": "text",
"category": "mrZHFR2i0MYp7aaY",
"_id": "UuAWTQtd3QMKOWvU",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>The module provides a bunch of settings to be able to control how it interacts with Foundry in various ways. Each setting has a description provided in the settings configuration window, but these descriptions will go more in depth than the ones in there. This will not include all settings, just the ones that would be more beneficial to have additional clarification for.</p><p></p><h2>Roll Auto-Tracking</h2><p>This tells the module to automatically track rolls that are sent to the chat, this includes systems, modules, and other rolls like RollTables. As long as it gets sent to the chat, this will allow that roll to automatically be tracked.</p><p>By default, this only tracks the standard dice sizes (d4, d6, d8, d10, d12, d20, d100), however you can add any dice size you want by creating a new table named <code>Dice/dX</code> where <code>X</code> is the number of sides the dice should have (e.g. for a 3-sided dice you would make the table name be <code>Dice/d3</code>). By adding a table in this way, it's configuration will be locked for editing and the only way to change it will be to delete the table entirely.</p><p>For most systems you will want to leave this setting enabled, because otherwise there is a chance that no dice rolls will be tracked at all unless the system has specifically implemented an integration with the module.</p><p></p><h2>Global API</h2><p>This setting is primarily targeted at users who would like to integrate stats tracking into macros, as it exposes a globally available <code>stats</code> variable with references to all of the exposed methods and utility helpers of the module. This can sometimes cause conflicts with systems or other modules, so make sure that there isn't already another a global variable named stats before enabling this setting.</p><p>Below is an example of how to retrieve the module's API both with and without this setting enabled:</p><pre><code>// with it enabled:\nconst statViewer = new stats.Apps.StatsViewer;\nstatViewer.render({ force: true });\n\n// with it disabled\nconst api = game.modules.get(`stat-tracker`)?.api;\nconst statViewer = new api.Apps.StatsViewer;\nstatViewer?.render({ force: true });</code></pre>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": 0,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748330762378,
"modifiedTime": 1748658920308,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.UuAWTQtd3QMKOWvU"
},
{
"sort": 900000,
"name": "Utilities",
"type": "text",
"category": "KGdeJUfatQ9v0raI",
"_id": "TQzWrVTEz4oQhLPD",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>The module provides a multitude of utility functions through it's API for usage however desired. This will go over them and describe their purpose.</p><p></p><h2>filterPrivateRows</h2><p>This method is intended to take @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.S7Z6mZ0JablJVQJu]{rows} provided by the database and filter out any that the user would not be able to see normally. This is usually called by the database adapters so there's unlikely to be any reason to use it externally.</p><p>Available under <code>&lt;api&gt;.utils.filterPrivateRows</code>.</p><p></p><h2>inferRollMode</h2><p>This utility is intended to try and determine what roll mode was used to create a chat message. The inference is not entirely accurate because it struggles to differentiate between a GM rolling with a Private GM Roll and a Self Roll when there is only one GM present in the world.</p><p>Available under <code>&lt;api&gt;.utils.inferRollMode</code></p><p></p><h2>validateValue</h2><p>Available under <code>&lt;api&gt;.utils.validateValue</code>.</p><p></p><h2>validateBucketConfig</h2><p>Available under <code>&lt;api&gt;.utils.validateBucketConfig</code>.</p>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.345",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748330904988,
"modifiedTime": 1749864406851,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.TQzWrVTEz4oQhLPD"
},
{
"sort": 800000,
"name": "Database Adapters",
"type": "text",
"category": "KGdeJUfatQ9v0raI",
"_id": "PcdmuLgNM15h0in1",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>This is a list of all available database adapters and how they're configured.</p><p></p><h2>Database</h2><p>This database adapter isn't a full adapter, this is an abstract class that is used by the other database adapters to enforce a consistent method / interface specification. The general interface includes implementation details for storing the table data in a world setting as well as adding/removing any applications that are rendered as part of the module's operations.</p><p>Available under <code>&lt;api&gt;.databases.Database</code>.</p><p></p><h2>User Flag Database</h2><p>This database adapter uses Foundry's flag system in order to store the row data in the User document, leveraging Foundry's automatic database update propagation to other clients. The application handling and table storage utilizes the abstract implementations.</p><p>Available under <code>&lt;api&gt;.databases.UserFlagDatabase</code>.</p><p></p><h2>Condensed User Flag Database</h2><p>This is unimplemented at the moment. But it will be a database that makes long-term campaign storage more viable, at the tradeoff of not being able to filter data as granularly.</p><p></p><h2>Memory Database</h2><p>This database adapter should <strong>not</strong> be used in any actual games, it is intended for development only.</p><p>Available under <code>&lt;api&gt;.databases.MemoryDatabase</code>.</p>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748331161024,
"modifiedTime": 1748409643379,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.PcdmuLgNM15h0in1"
},
{
"sort": 1000000,
"name": "Graph",
"type": "text",
"category": "ZPAbuPbVOLWh75hL",
"_id": "IXZpEBEJsvOpY3OL",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>Right now all graphs are bar graphs and non-configurable. This is coming in a later update.</p>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748393806045,
"modifiedTime": 1748803890586,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.IXZpEBEJsvOpY3OL"
},
{
"sort": 1100000,
"name": "Table Manager",
"type": "text",
"category": "mrZHFR2i0MYp7aaY",
"_id": "Z31C8BPl4ZXDn3R6",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>Documentation Coming Soon</p>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748393919924,
"modifiedTime": 1748583846540,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.Z31C8BPl4ZXDn3R6"
},
{
"sort": 850000,
"name": "Enums",
"type": "text",
"category": "KGdeJUfatQ9v0raI",
"_id": "WYaZPgSRDx8L7Zmq",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>All of these enums are available within <code>&lt;api&gt;.enums</code>, they are read-only and cannot be modified by other plugins.</p><p></p><h2>Privacy Modes</h2><p>This enum is used by the module to specify all of the privacy levels that it uses.</p><p>The valid values are:</p><ul><li><p><code>GM</code> - Representing that only gamemasters and assistant gamemasters will be able to see this data entry. This mode is similar to the \"Blind GM Roll\" roll mode.</p></li><li><p><code>PRIVATE</code> - Indicating that this is a piece of private data, that only gamemasters, assistant gamemasters, and the user who owns the piece of data will be able to see it.</p></li><li><p><code>SELF</code> - Similar to the \"GM\" level, but instead of gamemasters, it's only the user who owns the piece of data that's able to see it.</p></li><li><p><code>PUBLIC</code> - Everyone can see it.</p></li></ul>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748394110971,
"modifiedTime": 1748803937108,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.WYaZPgSRDx8L7Zmq"
},
{
"sort": 1000000,
"name": "Usage Within Macros",
"type": "text",
"category": "mrZHFR2i0MYp7aaY",
"_id": "cpix3FpMmI1U1xXa",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>This module was designed from the ground up with the desire to be able to be used within macros, because of this it has first-class Macro support through the entire API.</p><p></p><h2>Getting the API</h2><p>The primary API that you will interact with inside of macros is held within <code>CONFIG.stats</code>, this is the core API which allows interacting with the stored data however the user wants it to be stored, it allows accessing the apps to view stats, manage the tables, and create new tables.</p><p></p><h2>The API Methods</h2><p>Each of the items within <code>CONFIG.stats</code> has a different purpose, but most of the programmatic interactions for the module are most likely to be interested in the <code>CONFIG.stats.db</code> part of the API, which handles all of the data within the module in your configured preference.</p>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748408620967,
"modifiedTime": 1748409821925,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.cpix3FpMmI1U1xXa"
},
{
"sort": 700000,
"name": "Database Interface",
"type": "text",
"category": "KGdeJUfatQ9v0raI",
"_id": "PlKHrrb61Uc1sGbN",
"system": {},
"title": {
"show": true,
"level": 1
},
"image": {},
"text": {
"format": 1,
"content": "<p>This is the interface which all @UUID[Compendium.stat-tracker.docs.JournalEntry.pBOyeBDuTeowuDOE.JournalEntryPage.PcdmuLgNM15h0in1]{Database Adapters} <strong>must</strong> conform to in order for the module to function. If they do not conform to this a warning will be thrown and the module will override the provided database with a database adapter which does nothing, so that the existing data will be protected from errors.</p><p>The best way to learn about the required database interface is to read the <a href=\"https://github.com/Oliver-Akins/Foundry-Stat-Tracker/blob/main/module/utils/databases/Database.mjs\">implementation of the interface</a> that all database adapters are required to extend.</p>"
},
"video": {
"controls": true,
"volume": 0.5
},
"src": null,
"ownership": {
"default": -1,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748408916163,
"modifiedTime": 1748656904440,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.pages!pBOyeBDuTeowuDOE.PlKHrrb61Uc1sGbN"
}
],
"folder": null,
"categories": [
{
"name": "Overview",
"sort": 100000,
"_id": "mrZHFR2i0MYp7aaY",
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748328842906,
"modifiedTime": 1748328842906,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.categories!pBOyeBDuTeowuDOE.mrZHFR2i0MYp7aaY"
},
{
"name": "API",
"sort": 300000,
"_id": "KGdeJUfatQ9v0raI",
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748328851997,
"modifiedTime": 1748328851997,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.categories!pBOyeBDuTeowuDOE.KGdeJUfatQ9v0raI"
},
{
"name": "Key Concepts",
"sort": 200000,
"_id": "ZPAbuPbVOLWh75hL",
"flags": {},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748329482648,
"modifiedTime": 1748329482648,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal.categories!pBOyeBDuTeowuDOE.ZPAbuPbVOLWh75hL"
}
],
"sort": 0,
"ownership": {
"default": 0,
"t2sWGWEYSMFrfBu3": 3
},
"flags": {
"core": {
"locked": false
}
},
"_stats": {
"compendiumSource": null,
"duplicateSource": null,
"exportSource": null,
"coreVersion": "13.344",
"systemId": "empty-system",
"systemVersion": "0.0.0",
"createdTime": 1748328832096,
"modifiedTime": 1748393668194,
"lastModifiedBy": "t2sWGWEYSMFrfBu3"
},
"_key": "!journal!pBOyeBDuTeowuDOE"
}

View file

@ -5,6 +5,20 @@
"Subtable": "Subtable", "Subtable": "Subtable",
"Users": "Users", "Users": "Users",
"DataVisibility": "Data Visibility" "DataVisibility": "Data Visibility"
},
"settings": {
"autoTrackRolls": {
"name": "Roll Auto-Tracking",
"hint": "Whether or not the module should automatically add rolls made in the chat to the database. This is useful if the system you're using has implemented an integration with the module, or if you only want macros to handle the database additions."
},
"globalAPI": {
"name": "Global API",
"hint": "Whether or not the module provides a global interface for interacting with the module's backend. This is convenient for macros and using the dev console."
},
"statsSidebarTab": {
"name": "Stats Sidebar Tab",
"hint": "Adds a custom sidebar tab to view and control the module with ease. With the sidebar tab disabled the only way to control the module is via the public API."
}
} }
} }
} }

View file

@ -1,12 +1,23 @@
{ {
"id": "stat-tracker", "id": "stat-tracker",
"title": "Stats Tracker", "title": "Stats Tracker",
"version": "0.0.1", "description": "<p>A user-first approach to stat tracking. Designed from the ground up with the intent of being able to track whatever statistics you want.</p>",
"version": "1.0.3",
"compatibility": { "compatibility": {
"maximum": 13, "maximum": 13,
"verified": 13, "verified": 13,
"minimum": 13 "minimum": 13
}, },
"authors": [
{
"name": "Oliver Akins",
"url": "https://github.com/Oliver-Akins"
}
],
"url": "https://github.com/Oliver-Akins/Foundry-Stat-Tracker",
"manifest": "https://github.com/Oliver-Akins/Foundry-Stat-Tracker/releases/latest/download/module.json",
"download": "https://github.com/Oliver-Akins/Foundry-Stat-Tracker/releases/latest/download/release.zip",
"bugs": "https://github.com/Oliver-Akins/Foundry-Stat-Tracker/issues/new/choose",
"esmodules": [ "esmodules": [
"./module.mjs" "./module.mjs"
], ],
@ -22,5 +33,14 @@
"name": "English (Canadian)", "name": "English (Canadian)",
"path": "langs/en-ca.json" "path": "langs/en-ca.json"
} }
],
"packs": [
{
"name": "docs",
"label": "Documentation",
"module": "stat-tracker",
"type": "JournalEntry",
"path": "packs/docs"
}
] ]
} }

View file

@ -1,13 +1,4 @@
<div <div data-bucket-type="number">
class="{{#if buckets.locked}}alert-box locked{{/if}}"
data-bucket-type="number"
>
{{#if buckets.locked}}
<p class="center">
This bucket configuration has been locked, preventing editing
of the settings.
</p>
{{/if}}
<div class="input-group"> <div class="input-group">
<label for="{{meta.idp}}-min"> <label for="{{meta.idp}}-min">
Minimum Minimum

View file

@ -1,42 +0,0 @@
<div class="input-group">
<label for="{{meta.idp}}-min">
Minimum
</label>
<input
id="{{meta.idp}}-min"
type="number"
name="buckets.min"
value="{{ buckets.min }}"
required
{{disabled buckets.locked}}
>
</div>
<div class="input-group">
<label for="{{meta.idp}}-max">
Maximum
</label>
<input
id="{{meta.idp}}-max"
type="number"
name="buckets.max"
value="{{ buckets.max }}"
required
{{disabled buckets.locked}}
>
</div>
<div class="input-group">
<label for="{{meta.idp}}-step">
Step
</label>
<input
id="{{meta.idp}}-step"
type="number"
name="buckets.step"
value="{{ buckets.step }}"
required
{{disabled buckets.locked}}
>
<p class="hint">
The size of the step between values within the range.
</p>
</div>

View file

@ -1,7 +1,4 @@
<div <div data-bucket-type="string">
class="{{#if buckets.locked}}alert-box locked{{/if}}"
data-bucket-type="string"
>
<div class="input-group"> <div class="input-group">
<label for=""> <label for="">
Valid Options Valid Options

View file

@ -0,0 +1,36 @@
import { existsSync } from "fs";
import { readFile } from "fs/promises";
import { join } from "path";
import { compilePack } from "@foundryvtt/foundryvtt-cli";
import { pathToFileURL } from "url";
export async function buildCompendia() {
const manifest = JSON.parse(await readFile(`./public/module.json`, `utf-8`));
if (!manifest.packs || manifest.packs.length === 0) {
console.log(`No compendium packs defined`);
process.exit(0);
};
console.log(`Packing compendia`);
for (const compendium of manifest.packs) {
console.debug(`Packing ${compendium.label} (${compendium.name})`);
let src = join(process.cwd(), compendium.path, `_source`);
if (!existsSync(src)) {
console.warn(`${compendium.path} doesn't exist, skipping.`)
continue;
};
await compilePack(
src,
join(process.cwd(), compendium.path),
{ recursive: true },
);
console.debug(`Finished packing compendium: ${compendium.name}`);
};
console.log(`Finished packing all compendia`)
};
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
buildCompendia();
};

View file

@ -0,0 +1,31 @@
import { readFile } from "fs/promises";
import { join } from "path";
import { extractPack } from "@foundryvtt/foundryvtt-cli";
import { pathToFileURL } from "url";
export async function extractCompendia() {
const manifest = JSON.parse(await readFile(`./public/module.json`, `utf-8`));
if (!manifest.packs || manifest.packs.length === 0) {
console.log(`No compendium packs defined`);
process.exit(0);
};
console.log(`Extracting compendia`);
for (const compendium of manifest.packs) {
console.debug(`Unpacking ${compendium.label} (${compendium.name})`);
let src = join(process.cwd(), compendium.path, `_source`);
await extractPack(
join(process.cwd(), compendium.path),
src,
{ recursive: true },
);
console.debug(`Finished unpacking compendium: ${compendium.name}`);
};
console.log(`Finished unpacking all compendia`);
};
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
extractCompendia();
};

47
scripts/linkFoundry.mjs Normal file
View file

@ -0,0 +1,47 @@
import { existsSync } from "fs";
import { symlink, unlink } from "fs/promises";
import { join } from "path";
import { config } from "dotenv";
config({ quiet: true });
const root = process.env.FOUNDRY_ROOT;
// Early exit
if (!root) {
console.error(`Must provide a FOUNDRY_ROOT environment variable`);
process.exit(1);
};
// Assert Foundry exists
if (!existsSync(root)) {
console.error(`Foundry root not found.`);
process.exit(1);
};
// Removing existing symlink
if (existsSync(`foundry`)) {
console.log(`Attempting to unlink foundry instance`);
try {
await unlink(`foundry`);
} catch {
console.error(`Failed to unlink foundry folder.`);
process.exit(1);
};
};
// Account for if the root is pointing at an Electron install
let targetRoot = root;
if (existsSync(join(root, `resources`, `app`))) {
console.log(`Switching to use the "${root}/resources/app" directory`);
targetRoot = join(root, `resources`, `app`);
};
// Create symlink
console.log(`Linking foundry source into folder`)
try {
await symlink(targetRoot, `foundry`);
} catch (e) {
console.error(e);
process.exit(1);
};

View file

@ -1,9 +1,11 @@
/* eslint-disable no-undef */ /* eslint-disable no-undef */
import { cp, rm } from "fs/promises";
import { readFileSync, symlinkSync } from "fs";
import { buildCompendia } from "./scripts/buildCompendia.mjs";
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import { glob } from "glob"; import { glob } from "glob";
import path from "path"; import path from "path";
import { readFileSync } from "fs";
// MARK: custom plugins // MARK: custom plugins
function fileMarkerPlugin() { function fileMarkerPlugin() {
@ -41,14 +43,78 @@ function watcher(...globs) {
}; };
}; };
/*
The intent of this plugin is to handle the symlinking of the compendium packs
so that they can modified during dev without needing to worry about the rebuild
destroying the in-progress compendia data.
*/
function symlinkPacks() {
return {
writeBundle(options) {
symlinkSync(
path.resolve(__dirname, `packs`),
`${options.dir}/packs`,
`dir`,
);
},
};
};
/*
The intent of this plugin is to handle the copying, cleaning and compiling of
compendia packs for production
*/
function buildPacks() {
return {
async writeBundle(options) {
const buildDir = options.dir;
try {
await buildCompendia();
} catch {
const err = new Error(`Compendium building failed, make sure Foundry isn't running`);
err.stack = ``;
throw err;
};
await cp(`${__dirname}/packs`, `${buildDir}/packs`, { recursive: true, force: true });
for (const file of glob.sync(`${buildDir}/packs/**/_source/`)) {
await rm(file, { recursive: true, force: true });
};
},
};
};
/*
Allows copying a file from somewhere into the build directory once the build has
completed.
*/
function copyFile(filepath, targetPath) {
return {
async writeBundle(options) {
const buildDir = options.dir;
await cp(filepath, `${buildDir}/${targetPath}`);
},
};
};
// MARK: config // MARK: config
export default defineConfig(({ mode }) => { export default defineConfig(({ mode }) => {
const isProd = mode === `prod`; const isProd = [`prod`, `staging`].includes(mode);
let outMode = mode;
if (mode === `staging`) {
outMode = `dev`;
};
const plugins = []; const plugins = [];
if (!isProd) { if (isProd) {
plugins.push( plugins.push(
copyFile(`LICENSE`, `LICENSE`),
copyFile(`README.md`, `README.md`),
buildPacks(),
);
} else {
plugins.push(
symlinkPacks(),
watcher( watcher(
`./public`, `./public`,
), ),
@ -61,24 +127,28 @@ export default defineConfig(({ mode }) => {
return { return {
plugins, plugins,
define: { define: {
__TITLE__: JSON.stringify(manifest.title),
__ID__: JSON.stringify(manifest.id), __ID__: JSON.stringify(manifest.id),
__VERSION__: JSON.stringify(manifest.version), __VERSION__: JSON.stringify(manifest.version),
}, },
mode: isProd ? `production` : `development`, mode: isProd ? `production` : `development`,
build: { build: {
minify: isProd ? `terser` : false, minify: isProd ? `terser` : false,
terserOptions: {
keep_classnames: true,
keep_fnames: true,
},
sourcemap: true, sourcemap: true,
rollupOptions: { rollupOptions: {
input: { input: {
module: `./module/main.mjs`, module: `./module/main.mjs`,
// TODO: Figure out how to get handlebars files being used here
}, },
output: { output: {
entryFileNames: `[name].mjs`, entryFileNames: `[name].mjs`,
format: `esm`, format: `esm`,
}, },
}, },
outDir: `${mode}.dist`, outDir: `${outMode}.dist`,
emptyOutDir: true, emptyOutDir: true,
}, },
}; };