Merge branch 'develop' into pr/Jonpot/301

This commit is contained in:
Thaum Rystra
2024-11-05 12:22:09 +02:00
1001 changed files with 55739 additions and 27230 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "app/packages/redis-oplog"]
path = app/packages/redis-oplog
url = https://github.com/ramezrafla/redis-oplog.git

33
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,33 @@
{
"cSpell.words": [
"alea",
"armor",
"autorun",
"blackbox",
"cantrip",
"Cantrips",
"Crit",
"Crits",
"cyrb",
"denormalize",
"denormalized",
"EJSON",
"healthbar",
"healthbars",
"jank",
"meteortesting",
"nearley",
"ngraph",
"ostrio",
"Ruleset",
"snackbars",
"Spellcasting",
"Subheaders",
"thumbhash",
"uncomputed",
"untarget",
"vuetify",
"Vuex",
"walkdown"
]
}

View File

@@ -1,14 +1,27 @@
FROM ubuntu:latest FROM ubuntu:jammy
RUN apt-get update --quiet \
&& apt-get install --quiet --yes \ USER root
bsdtar \ RUN adduser --system mt
curl \
git RUN apt-get update
RUN ln --symbolic --force $(which bsdtar) $(which tar) RUN apt-get install --quiet --yes curl
RUN useradd --create-home --shell /bin/bash dicecloud RUN curl -fsSL https://deb.nodesource.com/setup_14.x | bash -
USER dicecloud RUN apt-get update
WORKDIR /home/dicecloud RUN apt-get install --quiet --yes nodejs git
RUN curl https://install.meteor.com/?release=1.8.0.2 | sh
ENV PATH="${PATH}:/home/dicecloud/.meteor" USER mt
COPY dev.sh ./dev.sh
ENTRYPOINT ./dev.sh RUN curl https://install.meteor.com/ | sh
WORKDIR /home/mt
RUN git clone https://github.com/ThaumRystra/DiceCloud dicecloud
WORKDIR /home/mt/dicecloud/app
RUN npm install --production
ENV PATH=$PATH:/home/mt/.meteor
RUN meteor build --directory ~/dc/ --architecture os.linux.x86_64
WORKDIR /home/mt/dc/bundle/programs/server
RUN npm install
WORKDIR /home/mt/dc/bundle
RUN rm -r /home/mt/dicecloud
ENTRYPOINT node main.js

View File

@@ -1,7 +1,7 @@
DiceCloud DiceCloud
======== ========
This is the repo for [DiceCloud](dicecloud.com). This is the repo for [DiceCloud](https://dicecloud.com).
DiceCloud is a free, auditable, real-time character sheet for D&D 5e. DiceCloud is a free, auditable, real-time character sheet for D&D 5e.

4
app/.gitignore vendored
View File

@@ -3,6 +3,10 @@
.demeteorized .demeteorized
.cache .cache
.vscode .vscode
.coverage
.nyc_output
.DS_Store
fileStorage
settings.json settings.json
public/components public/components
public/_imports.html public/_imports.html

View File

@@ -3,29 +3,27 @@
# 'meteor add' and 'meteor remove' will edit this file for you, # 'meteor add' and 'meteor remove' will edit this file for you,
# but you can also edit it by hand. # but you can also edit it by hand.
accounts-password@2.3.1 accounts-password@2.4.0
random@1.2.0 random@1.2.1
underscore@1.0.10 underscore@1.6.1
dburles:mongo-collection-instances dburles:mongo-collection-instances
accounts-google@1.4.0 accounts-google@1.4.0
email@2.2.1 email@2.2.6
meteor-base@1.5.1 meteor-base@1.5.1
mobile-experience@1.1.0 mobile-experience@1.1.1
mongo@1.16.0 mongo@1.16.10
session@1.2.0 session@1.2.1
tracker@1.2.0 tracker@1.3.3
logging@1.3.1 logging@1.3.4
reload@1.3.1 reload@1.3.1
ejson@1.1.2 ejson@1.1.3
check@1.3.1 check@1.4.1
standard-minifier-js@2.8.1 standard-minifier-js@2.8.1
shell-server@0.5.0 shell-server@0.5.0
ecmascript@0.16.2 service-configuration@1.3.4
es5-shim@4.8.0 dynamic-import@0.7.3
service-configuration@1.3.0 ddp-rate-limiter@1.2.1
dynamic-import@0.7.2 rate-limit@1.1.1
ddp-rate-limiter@1.1.0
rate-limit@1.0.9
mdg:validated-method mdg:validated-method
static-html@1.3.2 static-html@1.3.2
aldeed:collection2 aldeed:collection2
@@ -37,9 +35,8 @@ simple:rest
simple:rest-method-mixin simple:rest-method-mixin
mikowals:batch-insert mikowals:batch-insert
peerlibrary:subscription-data peerlibrary:subscription-data
seba:minifiers-autoprefixer
zer0th:meteor-vuetify-loader zer0th:meteor-vuetify-loader
akryum:vue-component akryum:vue-component@0.15.2
akryum:vue-router2 akryum:vue-router2
percolate:migrations percolate:migrations
meteortesting:mocha meteortesting:mocha
@@ -47,5 +44,12 @@ ostrio:files
simple:rest-bearer-token-parser simple:rest-bearer-token-parser
simple:rest-json-error-handler simple:rest-json-error-handler
littledata:synced-cron littledata:synced-cron
mdg:meteor-apm-agent #mdg:meteor-apm-agent
typescript@4.5.4 seba:minifiers-autoprefixer
#mixmax:smart-disconnect
zodern:types
zodern:fix-async-stubs
typescript@4.9.5
ecmascript@0.16.8
lmieulet:meteor-legacy-coverage
lmieulet:meteor-coverage

View File

@@ -1 +1 @@
METEOR@2.8.0 METEOR@2.16

View File

@@ -1,87 +1,86 @@
accounts-base@2.2.4 accounts-base@2.2.11
accounts-google@1.4.0 accounts-google@1.4.0
accounts-oauth@1.4.1 accounts-oauth@1.4.4
accounts-password@2.3.1 accounts-password@2.4.0
accounts-patreon@0.1.0 accounts-patreon@0.1.0
akryum:npm-check@0.1.2 akryum:npm-check@0.1.2
akryum:vue-component@0.15.2 akryum:vue-component@0.16.0
akryum:vue-component-dev-client@0.4.7 akryum:vue-component-dev-client@0.4.7
akryum:vue-component-dev-server@0.1.4 akryum:vue-component-dev-server@0.1.4
akryum:vue-router2@0.2.3 akryum:vue-router2@0.2.3
aldeed:collection2@3.5.0 aldeed:collection2@3.5.0
aldeed:schema-index@3.0.0 aldeed:schema-index@3.1.0
allow-deny@1.1.1 allow-deny@1.1.1
autoupdate@1.8.0 autoupdate@1.8.0
babel-compiler@7.9.2 babel-compiler@7.10.5
babel-runtime@1.5.1 babel-runtime@1.5.1
base64@1.0.12 base64@1.0.12
binary-heap@1.0.11 binary-heap@1.0.11
blaze-tools@1.1.3 blaze-tools@1.1.4
boilerplate-generator@1.7.1 boilerplate-generator@1.7.2
bozhao:link-accounts@2.6.1 bozhao:link-accounts@2.8.0
caching-compiler@1.2.2 caching-compiler@1.2.2
caching-html-compiler@1.2.1 caching-html-compiler@1.2.2
callback-hook@1.4.0 callback-hook@1.5.1
check@1.3.1 check@1.4.1
coffeescript@2.4.1 coffeescript@2.7.0
coffeescript-compiler@2.4.1 coffeescript-compiler@2.4.1
dburles:mongo-collection-instances@0.3.6 dburles:mongo-collection-instances@0.4.0
ddp@1.4.0 ddp@1.4.1
ddp-client@2.6.0 ddp-client@2.6.2
ddp-common@1.4.0 ddp-common@1.4.1
ddp-rate-limiter@1.1.0 ddp-rate-limiter@1.2.1
ddp-server@2.6.0 ddp-server@2.7.1
diff-sequence@1.1.1 diff-sequence@1.1.2
dynamic-import@0.7.2 dynamic-import@0.7.3
ecmascript@0.16.2 ecmascript@0.16.8
ecmascript-runtime@0.8.0 ecmascript-runtime@0.8.1
ecmascript-runtime-client@0.12.1 ecmascript-runtime-client@0.12.1
ecmascript-runtime-server@0.11.0 ecmascript-runtime-server@0.11.0
ejson@1.1.2 ejson@1.1.3
email@2.2.1 email@2.2.6
es5-shim@4.8.0 es5-shim@4.8.0
fetch@0.1.1 fetch@0.1.4
geojson-utils@1.0.10 geojson-utils@1.0.11
google-oauth@1.4.2 google-oauth@1.4.4
hot-code-push@1.0.4 hot-code-push@1.0.4
html-tools@1.1.3 html-tools@1.1.4
htmljs@1.1.1 htmljs@1.2.1
http@2.0.0 http@2.0.0
id-map@1.1.1 id-map@1.1.1
inter-process-messaging@0.1.1 inter-process-messaging@0.1.1
lai:collection-extensions@0.3.0 lai:collection-extensions@0.4.0
launch-screen@1.3.0 launch-screen@2.0.0
littledata:synced-cron@1.5.1 littledata:synced-cron@1.5.1
livedata@1.0.18 lmieulet:meteor-coverage@4.1.0
lmieulet:meteor-legacy-coverage@0.2.0
localstorage@1.2.0 localstorage@1.2.0
logging@1.3.1 logging@1.3.4
mdg:meteor-apm-agent@3.5.1 mdg:validated-method@1.3.0
mdg:validated-method@1.2.0 meteor@1.11.5
meteor@1.10.1
meteor-base@1.5.1 meteor-base@1.5.1
meteortesting:browser-tests@1.3.5 meteortesting:browser-tests@1.5.3
meteortesting:mocha@2.0.3 meteortesting:mocha@2.1.0
meteortesting:mocha-core@8.1.2 meteortesting:mocha-core@8.1.2
mikowals:batch-insert@1.3.0 mikowals:batch-insert@1.3.0
minifier-css@1.6.1 minifier-css@1.6.4
minifier-js@2.7.5 minifier-js@2.8.0
minimongo@1.9.0 minimongo@1.9.4
mobile-experience@1.1.0 mobile-experience@1.1.1
mobile-status-bar@1.1.0 mobile-status-bar@1.1.0
modern-browsers@0.1.8 modern-browsers@0.1.10
modules@0.19.0 modules@0.20.0
modules-runtime@0.13.0 modules-runtime@0.13.1
mongo@1.16.0 mongo@1.16.10
mongo-decimal@0.1.3 mongo-decimal@0.1.3
mongo-dev-server@1.1.0 mongo-dev-server@1.1.0
mongo-id@1.0.8 mongo-id@1.0.8
mongo-livedata@1.0.12 npm-mongo@4.17.2
npm-mongo@4.9.0 oauth@2.2.1
oauth@2.1.2 oauth2@1.3.2
oauth2@1.3.1
ordered-dict@1.1.0 ordered-dict@1.1.0
ostrio:cookies@2.7.2 ostrio:cookies@2.8.1
ostrio:files@2.3.0 ostrio:files@2.3.3
patreon-oauth@0.1.0 patreon-oauth@0.1.0
peerlibrary:assert@0.3.0 peerlibrary:assert@0.3.0
peerlibrary:check-extension@0.7.0 peerlibrary:check-extension@0.7.0
@@ -93,37 +92,39 @@ peerlibrary:reactive-mongo@0.4.1
peerlibrary:reactive-publish@0.10.0 peerlibrary:reactive-publish@0.10.0
peerlibrary:server-autorun@0.8.0 peerlibrary:server-autorun@0.8.0
peerlibrary:subscription-data@0.8.0 peerlibrary:subscription-data@0.8.0
percolate:migrations@1.0.3 percolate:migrations@1.1.1
promise@0.12.0 promise@0.12.2
raix:eventemitter@1.0.0 raix:eventemitter@1.0.0
random@1.2.0 random@1.2.1
rate-limit@1.0.9 rate-limit@1.1.1
react-fast-refresh@0.2.3 react-fast-refresh@0.2.8
reactive-dict@1.3.0 reactive-dict@1.3.1
reactive-var@1.0.11 reactive-var@1.0.12
reload@1.3.1 reload@1.3.1
retry@1.1.0 retry@1.1.0
routepolicy@1.1.1 routepolicy@1.1.1
seba:minifiers-autoprefixer@2.0.1 seba:minifiers-autoprefixer@2.0.1
service-configuration@1.3.0 service-configuration@1.3.4
session@1.2.0 session@1.2.1
sha@1.0.9 sha@1.0.9
shell-server@0.5.0 shell-server@0.5.0
simple:json-routes@2.3.1 simple:json-routes@2.3.1
simple:rest@1.2.1 simple:rest@1.2.1
simple:rest-bearer-token-parser@1.1.1 simple:rest-bearer-token-parser@1.1.1
simple:rest-json-error-handler@1.1.1 simple:rest-json-error-handler@1.1.3
simple:rest-method-mixin@1.1.0 simple:rest-method-mixin@1.1.0
socket-stream-client@0.5.0 socket-stream-client@0.5.2
spacebars-compiler@1.3.1 spacebars-compiler@1.3.2
standard-minifier-js@2.8.1 standard-minifier-js@2.8.1
static-html@1.3.2 static-html@1.3.2
templating-tools@1.2.2 templating-tools@1.2.3
tmeasday:check-npm-versions@1.0.2 tmeasday:check-npm-versions@1.0.2
tracker@1.2.0 tracker@1.3.3
typescript@4.5.4 typescript@4.9.5
underscore@1.0.10 underscore@1.6.1
url@1.3.2 url@1.3.2
webapp@1.13.1 webapp@1.13.8
webapp-hashing@1.1.0 webapp-hashing@1.1.1
zer0th:meteor-vuetify-loader@0.1.41 zer0th:meteor-vuetify-loader@0.1.41
zodern:fix-async-stubs@1.0.2
zodern:types@1.0.13

12328
app/client/game-icons.css Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
import '/imports/api/simpleSchemaConfig.js'; import '/imports/api/simpleSchemaConfig';
import '/imports/ui/vueSetup.js'; import '/imports/client/ui/vueSetup';
import '/imports/ui/styles/stylesIndex.js'; import '/imports/client/ui/styles/stylesIndex';
import '/imports/client/config.js'; import '/imports/client/config';
import '/imports/client/serviceWorker.js'; import '/imports/client/serviceWorker';
import 'ngraph.graph'; import 'ngraph.graph';

View File

@@ -1,6 +1,7 @@
{ {
"public": { "public": {
"environment": "production", "environment": "production",
"disablePatreon": true "disablePatreon": true,
"disallowCreatureApiImport": false
} }
} }

3
app/imports/@types/ddp.d.ts vendored Normal file
View File

@@ -0,0 +1,3 @@
declare namespace DDP {
function randomStream(seed: string): typeof Random;
}

View File

@@ -0,0 +1,244 @@
declare module 'meteor/ostrio:files' {
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { ReactiveVar } from 'meteor/reactive-var';
import { SimpleSchemaDefinition } from 'simpl-schema';
import * as http from 'http';
import { IncomingMessage } from 'connect';
interface Params {
_id: string;
query: { [key: string]: string };
name: string;
version: string;
}
interface ContextHTTP {
request: IncomingMessage;
response: http.ServerResponse;
params: Params;
}
interface ContextUser {
userId: string;
user: () => Meteor.User;
}
interface ContextUpload {
file: object;
/** On server only. */
chunkId?: number;
/** On server only. */
eof?: boolean;
}
interface Version<MetadataType> {
extension: string;
meta: MetadataType;
path: string;
size: number;
type: string;
}
class FileObj<MetadataType> {
_id: string;
size: number;
name: string;
type: string;
path: string;
isVideo: boolean;
isAudio: boolean;
isImage: boolean;
isText: boolean;
isJSON: boolean;
isPDF: boolean;
ext?: string;
extension?: string;
extensionWithDot: string;
_storagePath: string;
_downloadRoute: string;
_collectionName: string;
public?: boolean;
meta?: MetadataType;
userId?: string;
updatedAt?: Date;
versions: {
[propName: string]: Version<MetadataType>;
};
mime: string;
'mime-type': string;
}
class FileRef<MetadataType> extends FileObj<MetadataType> {
remove: (callback?: (error: Meteor.Error) => void) => void;
link: (version?: string, location?: string) => string;
get: (property?: string) => any;
fetch: () => Array<FileObj<MetadataType>>;
with: () => FileCursor<MetadataType>;
}
interface FileData<MetadataType> {
size: number;
type: string;
mime: string;
'mime-type': string;
ext: string;
extension: string;
name: string;
meta: MetadataType;
}
interface FilesCollectionConfig<MetadataType> {
storagePath?: string | ((fileObj: FileObj<MetadataType>) => string);
collection?: Mongo.Collection<FileObj<MetadataType>>;
collectionName?: string;
continueUploadTTL?: string;
ddp?: object;
cacheControl?: string;
responseHeaders?: { [x: string]: string } | ((responseCode?: string, fileRef?: FileRef<MetadataType>, versionRef?: Version<MetadataType>, version?: string) => { [x: string]: string });
throttle?: number | boolean;
downloadRoute?: string;
schema?: SimpleSchemaDefinition;
chunkSize?: number;
namingFunction?: (fileObj: FileObj<MetadataType>) => string;
permissions?: number;
parentDirPermissions?: number;
integrityCheck?: boolean;
strict?: boolean;
downloadCallback?: (this: ContextHTTP & ContextUser, fileObj: FileObj<MetadataType>) => boolean;
protected?: boolean | ((this: ContextHTTP & ContextUser, fileObj: FileObj<MetadataType>) => boolean | number);
public?: boolean;
onBeforeUpload?: (this: ContextUpload & ContextUser, fileData: FileData<MetadataType>) => boolean | string;
onBeforeRemove?: (this: ContextUser, cursor: Mongo.Cursor<FileObj<MetadataType>>) => boolean;
onInitiateUpload?: (this: ContextUpload & ContextUser, fileData: FileData<MetadataType>) => void;
onAfterUpload?: (fileRef: FileRef<MetadataType>) => any;
onAfterRemove?: (files: ReadonlyArray<FileObj<MetadataType>>) => any;
onbeforeunloadMessage?: string | (() => string);
allowClientCode?: boolean;
debug?: boolean;
interceptDownload?: (http: object, fileRef: FileRef<MetadataType>, version: string) => boolean;
}
interface SearchOptions<MetadataType, TransformAdditions> {
sort?: Mongo.SortSpecifier;
skip?: number;
limit?: number;
fields?: Mongo.FieldSpecifier;
reactive?: boolean;
transform?: (fileObj: FileObj<MetadataType>) => FileObj<MetadataType> & TransformAdditions;
}
interface InsertOptions<MetadataType> {
file: File | object | string;
fileId?: string;
fileName?: string;
isBase64?: boolean;
meta?: MetadataType;
transport?: 'ddp' | 'http';
ddp?: object;
onStart?: (error: Meteor.Error, fileData: FileData<MetadataType>) => any;
onUploaded?: (error: Meteor.Error, fileRef: FileRef<MetadataType>) => any;
onAbort?: (fileData: FileData<MetadataType>) => any;
onError?: (error: Meteor.Error, fileData: FileData<MetadataType>) => any;
onProgress?: (progress: number, fileData: FileData<MetadataType>) => any;
onBeforeUpload?: (fileData: FileData<MetadataType>) => any;
chunkSize?: number | 'dynamic';
allowWebWorkers?: boolean;
type?: string;
}
interface LoadOptions<MetadataType> {
fileName: string;
meta?: MetadataType;
type?: string;
size?: number;
userId?: string;
fileId?: string;
}
class FileUpload {
file: File;
onPause: ReactiveVar<boolean>;
progress: ReactiveVar<number>;
estimateTime: ReactiveVar<number>;
estimateSpeed: ReactiveVar<number>;
state: ReactiveVar<'active' | 'paused' | 'aborted' | 'completed'>;
pause(): void;
continue(): void;
toggle(): void;
pipe(): void;
start(): void;
on(event: string, callback: () => void): void;
}
class FileCursor<MetadataType> extends FileRef<MetadataType> { }
class FilesCursor<MetadataType, TransformAdditions> extends Mongo.Cursor<FileObj<MetadataType>> {
cursor: Mongo.Cursor<FileObj<MetadataType>>; // Refers to base cursor? Why is this existing?
get(): Array<FileCursor<MetadataType> & TransformAdditions>;
hasNext(): boolean;
next(): FileCursor<MetadataType> & TransformAdditions;
hasPrevious(): boolean;
previous(): FileCursor<MetadataType> & TransformAdditions;
first(): FileCursor<MetadataType> & TransformAdditions;
last(): FileCursor<MetadataType> & TransformAdditions;
remove(callback?: (err: object) => void): void;
each(callback: (cursor: FileCursor<MetadataType> & TransformAdditions) => void): void;
current(): object | undefined;
}
class FilesCollection<MetadataType = { [x: string]: any }> {
collection: Mongo.Collection<FileObj<MetadataType>>;
schema: SimpleSchemaDefinition;
constructor(config: FilesCollectionConfig<MetadataType>)
/**
* Find and return Cursor for matching documents.
*
* @param selector [[http://docs.meteor.com/api/collections.html#selectors | Mongo-Style selector]]
* @param options [[http://docs.meteor.com/api/collections.html#sortspecifiers | Mongo-Style selector Options]]
*
* @template TransformAdditions Additional properties provided by transforming a document with options.tranform().
* Note that removing fields with a transform function is not currently supported as this may break
* functions defined on a FileRef or FileCursor.
*/
find<TransformAdditions = {}>(
selector?: Mongo.Selector<Partial<FileObj<MetadataType>>>,
options?: SearchOptions<MetadataType, TransformAdditions>
): FilesCursor<MetadataType, TransformAdditions>;
/**
* Finds the first document that matches the selector, as ordered by sort and skip options.
*
* @param selector [[http://docs.meteor.com/api/collections.html#selectors | Mongo-Style selector]]
* @param options [[http://docs.meteor.com/api/collections.html#sortspecifiers | Mongo-Style selector Options]]
*
* @template TransformAdditions Additional properties provided by transforming a document with options.tranform().
* Note that removing fields with a transform function is not currently supported as this may break
* functions defined on a FileRef or FileCursor.
*/
findOne<TransformAdditions = {}>(
selector?: Mongo.Selector<Partial<FileObj<MetadataType>>> | string,
options?: SearchOptions<MetadataType, TransformAdditions>
): FileCursor<MetadataType> & TransformAdditions;
insert(settings: InsertOptions<MetadataType>, autoStart?: boolean): FileUpload;
remove(select: Mongo.Selector<FileObj<MetadataType>> | string, callback?: (error: Meteor.Error) => void): FilesCollection<MetadataType>;
update(select: Mongo.Selector<FileObj<MetadataType>> | string, modifier: Mongo.Modifier<FileObj<MetadataType>>, options?: {
multi?: boolean;
upsert?: boolean;
arrayFilters?: Array<{ [identifier: string]: any }>;
}, callback?: (error: Meteor.Error, insertedCount: number) => void): FilesCollection<MetadataType>;
link(fileRef: FileRef<MetadataType>, version?: string): string;
allow(options: Mongo.AllowDenyOptions): void;
deny(options: Mongo.AllowDenyOptions): void;
denyClient(): void;
on(event: string, callback: (fileRef: FileRef<MetadataType>) => void): void;
unlink(fileRef: FileRef<MetadataType>, version?: string): FilesCollection<MetadataType>;
addFile(path: string, opts: LoadOptions<MetadataType>, callback?: (err: any, fileRef: FileRef<MetadataType>) => any, proceedAfterUpload?: boolean): FilesCollection<MetadataType>;
load(url: string, opts: LoadOptions<MetadataType>, callback?: (err: object, fileRef: FileRef<MetadataType>) => any, proceedAfterUpload?: boolean): FilesCollection<MetadataType>;
write(buffer: Buffer, opts: LoadOptions<MetadataType>, callback?: (err: object, fileRef: FileRef<MetadataType>) => any, proceedAfterUpload?: boolean): FilesCollection<MetadataType>;
}
}

7
app/imports/@types/meteor.d.ts vendored Normal file
View File

@@ -0,0 +1,7 @@
declare module 'meteor/meteor' {
namespace Meteor {
interface User {
roles?: string[];
}
}
}

7
app/imports/@types/mongo.d.ts vendored Normal file
View File

@@ -0,0 +1,7 @@
declare namespace Mongo {
interface CollectionStatic {
get: <T>(
collectionName: string, options?: { connection: Meteor.Connection }
) => Mongo.Collection<T>;
}
}

View File

@@ -0,0 +1,27 @@
declare module 'meteor/mdg:validated-method' {
interface ValidatedMethodOptionsMixinFields<TRunArg, TRunReturn> {
rateLimit: {
numRequests: number,
timeInterval: number,
};
}
type Return<TFunc> = TFunc extends (...args: any[]) => infer TReturn ? TReturn : never;
type Argument<TFunc> = TFunc extends (...args: infer TArgs) => any ? TArgs extends [infer TArg] ? TArg
: NoArguments
: never;
interface ValidatedMethod<TName extends string, TRun extends (...args: any[]) => any> {
callAsync: Argument<TRun> extends NoArguments
// methods with no argument can be called with () or just a callback
?
& ((unusedArg: any, callback: (error: Meteor.Error, result: Return<TRun>) => void) => void)
& ((callback: (error: Meteor.Error | undefined, result: Return<TRun>) => void) => void)
& (() => Return<TRun>)
// methods with arguments require those arguments to be called
:
& ((
arg: Argument<TRun>,
callback: (error: Meteor.Error | undefined, result: Return<TRun>) => void,
) => void)
& ((arg: Argument<TRun>) => Return<TRun>);
}
}

15
app/imports/@types/vue-meteor.d.ts vendored Normal file
View File

@@ -0,0 +1,15 @@
import Vue from 'vue';
declare module 'vue/types/options' {
interface ComponentOptions<V extends Vue> {
meteor?: any;
}
}
declare module 'vue/types/vue' {
interface Vue {
$subscribe: (name: string, params: any[]) => void;
$autorun: (fn: () => void) => number;
$subReady: Record<string, boolean>;
}
}

View File

@@ -1,18 +1,28 @@
import { createS3FilesCollection } from '/imports/api/files/s3FileStorage.js';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { incrementFileStorageUsed } from '/imports/api/users/methods/updateFileStorageUsed.js'; import { incrementFileStorageUsed } from '/imports/api/users/methods/updateFileStorageUsed';
import { CreaturePropertySchema } from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import { CreaturePropertySchema } from '/imports/api/creature/creatureProperties/CreatureProperties';
import { CreatureSchema } from '/imports/api/creature/creatures/Creatures.js'; import { CreatureSchema } from '/imports/api/creature/creatures/Creatures';
import assertUserHasFileSpace from '/imports/api/files/assertUserHasFileSpace';
let createS3FilesCollection;
if (Meteor.isServer) {
createS3FilesCollection = require('/imports/api/files/server/s3FileStorage').createS3FilesCollection
} else {
createS3FilesCollection = require('/imports/api/files/client/s3FileStorage').createS3FilesCollection
}
const ArchiveCreatureFiles = createS3FilesCollection({ const ArchiveCreatureFiles = createS3FilesCollection({
collectionName: 'archiveCreatureFiles', collectionName: 'archiveCreatureFiles',
storagePath: Meteor.isDevelopment ? '/DiceCloud/archiveCreatures/' : 'assets/app/archiveCreatures', storagePath: Meteor.isDevelopment ? '../../../../../fileStorage/archiveCreatures' : 'assets/app/archiveCreatures',
onBeforeUpload(file) { onBeforeUpload(file) {
// Allow upload files under 10MB, and only in json format // Allow upload files under 10MB, and only in json format
if (file.size > 10485760) { if (file.size > 10485760) {
return 'Please upload with size equal or less than 10MB'; return 'Please upload with size equal or less than 10MB';
} }
if (!/json/i.test(file.extension)){ // Make sure the user has enough space
assertUserHasFileSpace(Meteor.userId(), file.size);
// Only accept JSON
if (!/json/i.test(file.extension)) {
return 'Please upload only a JSON file'; return 'Please upload only a JSON file';
} }
return true; return true;

View File

@@ -1,21 +1,24 @@
import SCHEMA_VERSION from '/imports/constants/SCHEMA_VERSION.js'; import { Meteor } from 'meteor/meteor';
import SCHEMA_VERSION from '/imports/constants/SCHEMA_VERSION';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import { assertOwnership } from '/imports/api/creature/creatures/creaturePermissions.js'; import { assertOwnership } from '/imports/api/creature/creatures/creaturePermissions';
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import Creatures from '/imports/api/creature/creatures/Creatures';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import CreatureLogs from '/imports/api/creature/log/CreatureLogs.js'; import CreatureLogs from '/imports/api/creature/log/CreatureLogs';
import Experiences from '/imports/api/creature/experience/Experiences.js'; import Experiences from '/imports/api/creature/experience/Experiences';
import { removeCreatureWork } from '/imports/api/creature/creatures/methods/removeCreature.js'; import { removeCreatureWork } from '/imports/api/creature/creatures/methods/removeCreature';
import ArchiveCreatureFiles from '/imports/api/creature/archive/ArchiveCreatureFiles.js'; import ArchiveCreatureFiles from '/imports/api/creature/archive/ArchiveCreatureFiles';
import { getFilter } from '/imports/api/parenting/parentingFunctions';
export function getArchiveObj(creatureId){ export function getArchiveObj(creatureId) {
// Build the archive document // Build the archive document
const creature = Creatures.findOne(creatureId); const creature = Creatures.findOne(creatureId);
const properties = CreatureProperties.find({'ancestors.id': creatureId}).fetch(); if (!creature) throw new Meteor.Error('creature-not-found', 'Creature not found');
const experiences = Experiences.find({creatureId}).fetch(); const properties = CreatureProperties.find({ ...getFilter.descendantsOfRoot(creatureId) }).fetch();
const logs = CreatureLogs.find({creatureId}).fetch(); const experiences = Experiences.find({ creatureId }).fetch();
const logs = CreatureLogs.find({ creatureId }).fetch();
let archiveCreature = { let archiveCreature = {
meta: { meta: {
type: 'DiceCloud V2 Creature Archive', type: 'DiceCloud V2 Creature Archive',
@@ -31,7 +34,7 @@ export function getArchiveObj(creatureId){
return archiveCreature; return archiveCreature;
} }
export function archiveCreature(creatureId){ export const archiveCreature = Meteor.wrapAsync(function archiveCreatureFn(creatureId, callback) {
const archive = getArchiveObj(creatureId); const archive = getArchiveObj(creatureId);
const buffer = Buffer.from(JSON.stringify(archive, null, 2)); const buffer = Buffer.from(JSON.stringify(archive, null, 2));
ArchiveCreatureFiles.write(buffer, { ArchiveCreatureFiles.write(buffer, {
@@ -43,14 +46,33 @@ export function archiveCreature(creatureId){
creatureId: archive.creature._id, creatureId: archive.creature._id,
creatureName: archive.creature.name, creatureName: archive.creature.name,
}, },
}, (error) => { }, (error, fileRef) => {
if (error){ if (error) {
throw error; // If there is an error already, just call the callback
} else { callback(error);
} else if (!Meteor.settings.useS3) {
// If we aren't using s3, remove the creature and call the callback
removeCreatureWork(creatureId); removeCreatureWork(creatureId);
callback();
} else {
// Wait for s3Result event that occurs when the s3 attempt to write ends.
// If it's successful, remove the creature, otherwise callback with error
const resultHandler = (s3Error, resultRef) => {
// This event is for a different file, ignore it
if (resultRef._id !== fileRef._id) return;
// Remove this handler, we are only running it once for this fileId
ArchiveCreatureFiles.off('s3Result', resultHandler);
// Remove the creature if there was no error
if (!s3Error) {
removeCreatureWork(creatureId);
}
// Alert the callback that we're done
callback(s3Error);
}
ArchiveCreatureFiles.on('s3Result', resultHandler);
} }
}, true); }, true);
} });
const archiveCreatureToFile = new ValidatedMethod({ const archiveCreatureToFile = new ValidatedMethod({
name: 'Creatures.methods.archiveCreatureToFile', name: 'Creatures.methods.archiveCreatureToFile',
@@ -65,10 +87,10 @@ const archiveCreatureToFile = new ValidatedMethod({
numRequests: 10, numRequests: 10,
timeInterval: 5000, timeInterval: 5000,
}, },
async run({creatureId}) { async run({ creatureId }) {
assertOwnership(creatureId, this.userId); assertOwnership(creatureId, this.userId);
if (Meteor.isServer){ if (Meteor.isServer) {
archiveCreature(creatureId, this.userId); archiveCreature(creatureId);
} else { } else {
removeCreatureWork(creatureId); removeCreatureWork(creatureId);
} }

View File

@@ -1,3 +1,3 @@
import '/imports/api/creature/archive/methods/archiveCreatureToFile.js'; import '/imports/api/creature/archive/methods/archiveCreatureToFile';
import '/imports/api/creature/archive/methods/restoreCreatureFromFile.js'; import '/imports/api/creature/archive/methods/restoreCreatureFromFile';
import '/imports/api/creature/archive/methods/removeArchiveCreature.js'; import '/imports/api/creature/archive/methods/removeArchiveCreature';

View File

@@ -1,8 +1,8 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import ArchiveCreatureFiles from '/imports/api/creature/archive/ArchiveCreatureFiles.js'; import ArchiveCreatureFiles from '/imports/api/creature/archive/ArchiveCreatureFiles';
import { incrementFileStorageUsed } from '/imports/api/users/methods/updateFileStorageUsed.js'; import { incrementFileStorageUsed } from '/imports/api/users/methods/updateFileStorageUsed';
const removeArchiveCreature = new ValidatedMethod({ const removeArchiveCreature = new ValidatedMethod({
name: 'ArchiveCreatureFiles.methods.removeArchiveCreature', name: 'ArchiveCreatureFiles.methods.removeArchiveCreature',

View File

@@ -1,24 +1,24 @@
import SCHEMA_VERSION from '/imports/constants/SCHEMA_VERSION.js'; import SCHEMA_VERSION from '/imports/constants/SCHEMA_VERSION';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import Creatures from '/imports/api/creature/creatures/Creatures';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import CreatureLogs from '/imports/api/creature/log/CreatureLogs.js'; import CreatureLogs from '/imports/api/creature/log/CreatureLogs';
import Experiences from '/imports/api/creature/experience/Experiences.js'; import Experiences from '/imports/api/creature/experience/Experiences';
import { removeCreatureWork } from '/imports/api/creature/creatures/methods/removeCreature.js'; import { removeCreatureWork } from '/imports/api/creature/creatures/methods/removeCreature';
import ArchiveCreatureFiles from '/imports/api/creature/archive/ArchiveCreatureFiles.js'; import ArchiveCreatureFiles from '/imports/api/creature/archive/ArchiveCreatureFiles';
import assertHasCharactersSlots from '/imports/api/creature/creatures/methods/assertHasCharacterSlots.js'; import assertHasCharactersSlots from '/imports/api/creature/creatures/methods/assertHasCharacterSlots';
import { incrementFileStorageUsed } from '/imports/api/users/methods/updateFileStorageUsed.js'; import { incrementFileStorageUsed } from '/imports/api/users/methods/updateFileStorageUsed';
import verifyArchiveSafety from '/imports/api/creature/archive/methods/verifyArchiveSafety.js'; import verifyArchiveSafety from '/imports/api/creature/archive/methods/verifyArchiveSafety';
let migrateArchive; let migrateArchive;
if (Meteor.isServer){ if (Meteor.isServer) {
migrateArchive = require('/imports/migrations/server/migrateArchive.js').default; migrateArchive = require('/imports/migrations/archive/migrateArchive').default;
} }
function restoreCreature(archive, userId){ function restoreCreature(archive, userId) {
if (SCHEMA_VERSION < archive.meta.schemaVersion){ if (SCHEMA_VERSION < archive.meta.schemaVersion) {
throw new Meteor.Error('Incompatible', throw new Meteor.Error('Incompatible',
'The archive file is from a newer version. Update required to read.') 'The archive file is from a newer version. Update required to read.')
} }
@@ -35,7 +35,7 @@ function restoreCreature(archive, userId){
}); });
if (existingCreature) throw new Meteor.Error('Already exists', if (existingCreature) throw new Meteor.Error('Already exists',
'The creature you are trying to restore already exists.') 'The creature you are trying to restore already exists.')
// Ensure the user owns the restored creature // Ensure the user owns the restored creature
archive.creature.owner = userId; archive.creature.owner = userId;
@@ -44,13 +44,13 @@ function restoreCreature(archive, userId){
Creatures.insert(archive.creature); Creatures.insert(archive.creature);
try { try {
// Add all the properties // Add all the properties
if (archive.properties && archive.properties.length){ if (archive.properties && archive.properties.length) {
CreatureProperties.batchInsert(archive.properties); CreatureProperties.batchInsert(archive.properties);
} }
if (archive.experiences && archive.experiences.length){ if (archive.experiences && archive.experiences.length) {
Experiences.batchInsert(archive.experiences); Experiences.batchInsert(archive.experiences);
} }
if (archive.logs && archive.logs.length){ if (archive.logs && archive.logs.length) {
CreatureLogs.batchInsert(archive.logs); CreatureLogs.batchInsert(archive.logs);
} }
} catch (e) { } catch (e) {
@@ -73,23 +73,23 @@ const restoreCreaturefromFile = new ValidatedMethod({
numRequests: 10, numRequests: 10,
timeInterval: 5000, timeInterval: 5000,
}, },
async run({fileId}) { async run({ fileId }) {
// fetch the file // fetch the file
const file = ArchiveCreatureFiles.findOne({_id: fileId}).get(); const file = ArchiveCreatureFiles.findOne({ _id: fileId }).get();
if (!file){ if (!file) {
throw new Meteor.Error('File not found', throw new Meteor.Error('File not found',
'The requested creature archive does not exist'); 'The requested creature archive does not exist');
} }
// Assert ownership // Assert ownership
const userId = file?.userId; const userId = file?.userId;
if (!userId || userId !== this.userId){ if (!userId || userId !== this.userId) {
throw new Meteor.Error('Permission denied', throw new Meteor.Error('Permission denied',
'You can only restore creatures you own'); 'You can only restore creatures you own');
} }
assertHasCharactersSlots(this.userId); assertHasCharactersSlots(this.userId);
if (Meteor.isServer){ if (Meteor.isServer) {
// Read the file data // Read the file data
const archive = await ArchiveCreatureFiles.readJSONFile(file); const archive = await ArchiveCreatureFiles.readJSONFile(file);
restoreCreature(archive, this.userId); restoreCreature(archive, this.userId);

View File

@@ -1,7 +1,7 @@
import { slice } from 'lodash'; import { slice } from 'lodash';
import PER_CREATURE_LOG_LIMIT from '/imports/api/creature/log/CreatureLogs.js'; import { PER_CREATURE_LOG_LIMIT } from '/imports/api/creature/log/CreatureLogs';
export default function verifyArchiveSafety({ meta, creature, properties, experiences, logs }){ export default function verifyArchiveSafety({ creature, properties, experiences, logs }) {
const creatureId = creature._id; const creatureId = creature._id;
// Check lengths of arrays // Check lengths of arrays
@@ -21,7 +21,7 @@ export default function verifyArchiveSafety({ meta, creature, properties, experi
} }
}); });
properties.forEach(prop => { properties.forEach(prop => {
if (prop.ancestors[0].id !== creatureId) { if (prop.root?.id !== creatureId) {
throw new Meteor.Error('Malicious prop', 'Properties contains an entry for the wrong creature'); throw new Meteor.Error('Malicious prop', 'Properties contains an entry for the wrong creature');
} }
}); });

View File

@@ -1,5 +1,5 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS.js'; import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS';
let CreatureFolders = new Mongo.Collection('creatureFolders'); let CreatureFolders = new Mongo.Collection('creatureFolders');
@@ -35,5 +35,5 @@ let creatureFolderSchema = new SimpleSchema({
CreatureFolders.attachSchema(creatureFolderSchema); CreatureFolders.attachSchema(creatureFolderSchema);
import '/imports/api/creature/creatureFolders/methods.js/index.js'; import '/imports/api/creature/creatureFolders/methods.js/index';
export default CreatureFolders; export default CreatureFolders;

View File

@@ -1,4 +1,4 @@
import '/imports/api/creature/creatureFolders/methods.js/insertCreatureFolder.js'; import '/imports/api/creature/creatureFolders/methods.js/insertCreatureFolder';
import '/imports/api/creature/creatureFolders/methods.js/updateCreatureFolderName.js'; import '/imports/api/creature/creatureFolders/methods.js/updateCreatureFolderName';
import '/imports/api/creature/creatureFolders/methods.js/removeCreatureFolder.js'; import '/imports/api/creature/creatureFolders/methods.js/removeCreatureFolder';
import '/imports/api/creature/creatureFolders/methods.js/moveCreatureToFolder.js'; import '/imports/api/creature/creatureFolders/methods.js/moveCreatureToFolder';

View File

@@ -1,4 +1,4 @@
import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders.js'; import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
@@ -15,23 +15,23 @@ const insertCreatureFolder = new ValidatedMethod({
let userId = this.userId; let userId = this.userId;
if (!userId) { if (!userId) {
throw new Meteor.Error('creatureFolders.methods.insert.denied', throw new Meteor.Error('creatureFolders.methods.insert.denied',
'You need to be logged in to insert a folder'); 'You need to be logged in to insert a folder');
} }
// Limit folders to 50 per user // Limit folders to 50 per user
let existingFolders = CreatureFolders.find({ let existingFolders = CreatureFolders.find({
owner: userId owner: userId
}, { }, {
fields: {order: 1}, fields: { order: 1 },
sort: {order :-1} sort: { left: -1 }
}); });
if (existingFolders.count() >= 50){ if (existingFolders.count() >= 50) {
throw new Meteor.Error('creatureFolders.methods.insert.denied', throw new Meteor.Error('creatureFolders.methods.insert.denied',
'You can not have more than 50 folders'); 'You can not have more than 50 folders');
} }
// Make the new folder the last in the order // Make the new folder the last in the order
let order = 0; let order = 0;
let lastFolder = existingFolders.fetch()[0]; let lastFolder = existingFolders.fetch()[0];
if (lastFolder){ if (lastFolder) {
order = (lastFolder.order || 0) + 1; order = (lastFolder.order || 0) + 1;
} }
// Insert // Insert

View File

@@ -1,4 +1,4 @@
import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders.js'; import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
@@ -10,33 +10,33 @@ const moveCreatureToFolder = new ValidatedMethod({
numRequests: 5, numRequests: 5,
timeInterval: 5000, timeInterval: 5000,
}, },
run({creatureId, folderId}) { run({ creatureId, folderId }) {
// Ensure logged in // Ensure logged in
let userId = this.userId; let userId = this.userId;
if (!userId) { if (!userId) {
throw new Meteor.Error('creatureFolders.methods.updateName.denied', throw new Meteor.Error('creatureFolders.methods.updateName.denied',
'You need to be logged in to remove a folder'); 'You need to be logged in to remove a folder');
} }
// Check that this folder is owned by the user // Check that this folder is owned by the user
if (folderId){ if (folderId) {
let existingFolder = CreatureFolders.findOne(folderId); let existingFolder = CreatureFolders.findOne(folderId);
if (existingFolder.owner !== userId){ if (existingFolder.owner !== userId) {
throw new Meteor.Error('creatureFolders.methods.updateName.denied', throw new Meteor.Error('creatureFolders.methods.updateName.denied',
'This folder does not belong to you'); 'This folder does not belong to you');
} }
} }
// Remove from other folders // Remove from other folders
CreatureFolders.update({ CreatureFolders.update({
owner: userId owner: userId
}, { }, {
$pull: {creatures: creatureId}, $pull: { creatures: creatureId },
}, { }, {
multi: true, multi: true,
}); });
if (folderId){ if (folderId) {
// Add to this folder // Add to this folder
CreatureFolders.update(folderId, { CreatureFolders.update(folderId, {
$addToSet: {creatures: creatureId}, $addToSet: { creatures: creatureId },
}); });
} }
}, },

View File

@@ -1,4 +1,4 @@
import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders.js'; import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
@@ -10,18 +10,18 @@ const removeCreatureFolder = new ValidatedMethod({
numRequests: 5, numRequests: 5,
timeInterval: 5000, timeInterval: 5000,
}, },
run({_id}) { run({ _id }) {
// Ensure logged in // Ensure logged in
let userId = this.userId; let userId = this.userId;
if (!userId) { if (!userId) {
throw new Meteor.Error('creatureFolders.methods.updateName.denied', throw new Meteor.Error('creatureFolders.methods.updateName.denied',
'You need to be logged in to remove a folder'); 'You need to be logged in to remove a folder');
} }
// Check that this folder is owned by the user // Check that this folder is owned by the user
let existingFolder = CreatureFolders.findOne(_id); let existingFolder = CreatureFolders.findOne(_id);
if (existingFolder.owner !== userId){ if (existingFolder.owner !== userId) {
throw new Meteor.Error('creatureFolders.methods.updateName.denied', throw new Meteor.Error('creatureFolders.methods.updateName.denied',
'This folder does not belong to you'); 'This folder does not belong to you');
} }
// Remove // Remove
return CreatureFolders.remove(_id); return CreatureFolders.remove(_id);

View File

@@ -1,4 +1,4 @@
import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders.js'; import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
@@ -10,31 +10,31 @@ const reorderCreatureFolder = new ValidatedMethod({
numRequests: 5, numRequests: 5,
timeInterval: 5000, timeInterval: 5000,
}, },
run({_id, order}) { run({ _id, order }) {
// Ensure logged in // Ensure logged in
let userId = this.userId; let userId = this.userId;
if (!userId) { if (!userId) {
throw new Meteor.Error('creatureFolders.methods.reorder.denied', throw new Meteor.Error('creatureFolders.methods.reorder.denied',
'You need to be logged in to reorder a folder'); 'You need to be logged in to reorder a folder');
} }
// Check that this folder is owned by the user // Check that this folder is owned by the user
let existingFolder = CreatureFolders.findOne(_id); let existingFolder = CreatureFolders.findOne(_id);
if (existingFolder.owner !== userId){ if (existingFolder.owner !== userId) {
throw new Meteor.Error('creatureFolders.methods.reorder.denied', throw new Meteor.Error('creatureFolders.methods.reorder.denied',
'This folder does not belong to you'); 'This folder does not belong to you');
} }
// First give it the new order, it should end in 0.5 putting it between two other docs // First give it the new order, it should end in 0.5 putting it between two other docs
CreatureFolders.update(_id, {$set: {order}}); CreatureFolders.update(_id, { $set: { order } });
this.unblock(); this.unblock();
// Reorder all the folders with integer numbers in this new order // Reorder all the folders with integer numbers in this new order
CreatureFolders.find({ CreatureFolders.find({
owner: userId owner: userId
}, { }, {
fields: {order: 1,}, fields: { order: 1, },
sort: {order: -1} sort: { order: 1 }
}).forEach((folder, index) => { }).forEach((folder, index) => {
if (folder.order !== index){ if (folder.order !== index) {
CreatureFolders.update(_id, {$set: {order: index}}) CreatureFolders.update(_id, { $set: { order: index } })
} }
}); });
}, },

View File

@@ -1,4 +1,4 @@
import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders.js'; import CreatureFolders from '/imports/api/creature/creatureFolders/CreatureFolders';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
@@ -10,21 +10,21 @@ const updateCreatureFolderName = new ValidatedMethod({
numRequests: 5, numRequests: 5,
timeInterval: 5000, timeInterval: 5000,
}, },
run({_id, name}) { run({ _id, name }) {
// Ensure logged in // Ensure logged in
let userId = this.userId; let userId = this.userId;
if (!userId) { if (!userId) {
throw new Meteor.Error('creatureFolders.methods.updateName.denied', throw new Meteor.Error('creatureFolders.methods.updateName.denied',
'You need to be logged in to update a folder'); 'You need to be logged in to update a folder');
} }
// Check that this folder is owned by the user // Check that this folder is owned by the user
let existingFolder = CreatureFolders.findOne(_id); let existingFolder = CreatureFolders.findOne(_id);
if (existingFolder.owner !== userId){ if (existingFolder.owner !== userId) {
throw new Meteor.Error('creatureFolders.methods.updateName.denied', throw new Meteor.Error('creatureFolders.methods.updateName.denied',
'This folder does not belong to you'); 'This folder does not belong to you');
} }
// Update // Update
return CreatureFolders.update(_id, {$set: {name}}); return CreatureFolders.update(_id, { $set: { name } });
}, },
}); });

View File

@@ -1,15 +1,36 @@
import { Mongo } from 'meteor/mongo'; import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js'; import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema';
import ChildSchema from '/imports/api/parenting/ChildSchema.js'; import ChildSchema, { TreeDoc } from '/imports/api/parenting/ChildSchema';
import SoftRemovableSchema from '/imports/api/parenting/SoftRemovableSchema.js'; import SoftRemovableSchema from '/imports/api/parenting/SoftRemovableSchema';
import propertySchemasIndex from '/imports/api/properties/computedPropertySchemasIndex.js'; import propertySchemasIndex from '/imports/api/properties/computedPropertySchemasIndex';
import { storedIconsSchema } from '/imports/api/icons/Icons.js'; import { storedIconsSchema } from '/imports/api/icons/Icons';
import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS.js'; import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS';
let CreatureProperties = new Mongo.Collection('creatureProperties'); // TODO make this a union type of all CreatureProperty types
const CreatureProperties: Mongo.Collection<any> = new Mongo.Collection('creatureProperties');
let CreaturePropertySchema = new SimpleSchema({ export interface CreatureProperty extends TreeDoc {
_id: string
_migrationError?: string
tags: string[]
type: string
disabled?: boolean
icon?: {
name: string
shape: string
},
libraryNodeId?: string
slotQuantityFilled?: number
inactive?: boolean
deactivatedByAncestor?: boolean
deactivatedBySelf?: boolean
deactivatedByToggle?: boolean
deactivatingToggleId?: boolean
dirty?: boolean
}
const CreaturePropertySchema = new SimpleSchema({
_id: { _id: {
type: String, type: String,
regEx: SimpleSchema.RegEx.Id, regEx: SimpleSchema.RegEx.Id,
@@ -46,11 +67,17 @@ let CreaturePropertySchema = new SimpleSchema({
regEx: SimpleSchema.RegEx.Id, regEx: SimpleSchema.RegEx.Id,
optional: true, optional: true,
}, },
// Fill more than one quantity in a slot, like feats and ability score
// improvements, filtered out of UI if there isn't space in quantityExpected
slotQuantityFilled: {
type: SimpleSchema.Integer,
optional: true, // Undefined implies 1
},
}); });
const DenormalisedOnlyCreaturePropertySchema = new SimpleSchema({ const DenormalisedOnlyCreaturePropertySchema = new SimpleSchema({
// Denormalised flag if this property is inactive on the sheet for any reason // Denormalised flag if this property is inactive on the sheet for any reason
// Including being disabled, or a decendent of a disabled property // Including being disabled, or a descendant of a disabled property
inactive: { inactive: {
type: Boolean, type: Boolean,
optional: true, optional: true,
@@ -82,6 +109,42 @@ const DenormalisedOnlyCreaturePropertySchema = new SimpleSchema({
index: 1, index: 1,
removeBeforeCompute: true, removeBeforeCompute: true,
}, },
deactivatingToggleId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
optional: true,
removeBeforeCompute: true,
},
// Triggers that fire when this property is applied
'triggerIds': {
type: Object,
optional: true,
removeBeforeCompute: true,
},
'triggerIds.before': {
type: Array,
optional: true,
},
'triggerIds.before.$': {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
'triggerIds.after': {
type: Array,
optional: true,
},
'triggerIds.after.$': {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
'triggerIds.afterChildren': {
type: Array,
optional: true,
},
'triggerIds.afterChildren.$': {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
// When this is true on any property, the creature needs to be recomputed // When this is true on any property, the creature needs to be recomputed
dirty: { dirty: {
type: Boolean, type: Boolean,
@@ -93,13 +156,20 @@ const DenormalisedOnlyCreaturePropertySchema = new SimpleSchema({
CreaturePropertySchema.extend(DenormalisedOnlyCreaturePropertySchema); CreaturePropertySchema.extend(DenormalisedOnlyCreaturePropertySchema);
for (let key in propertySchemasIndex) { for (const key in propertySchemasIndex) {
let schema = new SimpleSchema({}); const schema = new SimpleSchema({});
schema.extend(propertySchemasIndex[key]); schema.extend(propertySchemasIndex[key]);
schema.extend(CreaturePropertySchema); schema.extend(CreaturePropertySchema);
schema.extend(ColorSchema); schema.extend(ColorSchema);
schema.extend(ChildSchema); schema.extend(ChildSchema);
schema.extend(SoftRemovableSchema); schema.extend(SoftRemovableSchema);
// Use the any schema as a default schema for the collection
if (key === 'any') {
// @ts-expect-error don't have types for .attachSchema
CreatureProperties.attachSchema(schema);
}
// TODO make this an else branch and remove all {selector: {type: any}} options
// @ts-expect-error don't have types for .attachSchema
CreatureProperties.attachSchema(schema, { CreatureProperties.attachSchema(schema, {
selector: { type: key } selector: { type: key }
}); });

View File

@@ -1,5 +1,5 @@
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import { getCreature } from '/imports/api/engine/loadCreatures';
export default function getRootCreatureAncestor(property){ export default function getRootCreatureAncestor(property) {
return Creatures.findOne(property.ancestors[0].id); return getCreature(property.root.id);
} }

View File

@@ -1,9 +1,9 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
const adjustQuantity = new ValidatedMethod({ const adjustQuantity = new ValidatedMethod({
name: 'creatureProperties.adjustQuantity', name: 'creatureProperties.adjustQuantity',

View File

@@ -0,0 +1,182 @@
import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import LibraryNodes from '/imports/api/library/LibraryNodes';
import { RefSchema } from '/imports/api/parenting/ChildSchema';
import {
assertEditPermission,
assertDocEditPermission,
assertCopyPermission
} from '/imports/api/sharing/sharingPermissions';
import {
fetchDocByRef,
getFilter,
renewDocIds
} from '/imports/api/parenting/parentingFunctions';
import { rebuildNestedSets } from '/imports/api/parenting/parentingFunctions';
import Libraries from '/imports/api/library/Libraries';
const DUPLICATE_CHILDREN_LIMIT = 500;
const copyPropertyToLibrary = new ValidatedMethod({
name: 'creatureProperties.copyPropertyToLibrary',
validate: new SimpleSchema({
propId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
parentRef: {
type: RefSchema,
},
order: {
type: Number,
optional: true,
},
}).validator(),
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 1,
timeInterval: 5000,
},
run({ propId, parentRef, order }) {
// get the new ancestry for the properties
const parentDoc = fetchDocByRef(parentRef);
// Check permission to edit the destination
let rootLibrary;
if (parentRef.collection === 'libraries') {
rootLibrary = parentDoc;
} else if (parentRef.collection === 'libraryNodes') {
rootLibrary = Libraries.findOne(parentDoc.root.id)
} else {
throw `${parentRef.collection} is not a valid parent collection`
}
assertEditPermission(rootLibrary, this.userId);
const insertedRootNode = insertNodeFromProperty(propId, order, this);
// Tree structure changed by inserts, reorder the tree
rebuildNestedSets(LibraryNodes, rootLibrary._id);
// Return the docId of the inserted root property
return insertedRootNode?._id;
},
});
function insertNodeFromProperty(propId, order, method) {
// Fetch the property and its descendants, provided they have not been
// removed
let prop = CreatureProperties.findOne({
_id: propId,
removed: { $ne: true },
});
if (!prop) {
if (Meteor.isClient) return;
else {
throw new Meteor.Error(
'Insert property from library failed',
`No property with id '${propId}' was found`
);
}
}
// Make sure we can edit this property
assertDocEditPermission(prop, method.userId);
let oldParentId = prop.parentId;
const propCursor = CreatureProperties.find({
...getFilter.descendants(prop),
removed: { $ne: true },
});
// Make sure there aren't too many descendants
if (propCursor.count() > DUPLICATE_CHILDREN_LIMIT) {
throw new Meteor.Error('Copy children limit',
`The property has over ${DUPLICATE_CHILDREN_LIMIT} descendants and cannot be copied`);
}
let props = propCursor.fetch();
// The root prop is first in the array of props
// It must get the first generated ID to prevent flickering
props = [prop, ...props];
// If the docs came from a library, that library must consent to this user copying their
// properties
assertSourceLibraryCopyPermission(props, method);
// Give the docs new IDs without breaking internal references
renewDocIds({
docArray: props,
collectionMap: { 'creatureProperties': 'libraryNodes' }
});
// Order the root node
prop.left = Number.MAX_SAFE_INTEGER - 1;
prop.right = Number.MAX_SAFE_INTEGER;
// Clean the props
props = cleanProps(props);
// Insert the props as library nodes
LibraryNodes.batchInsert(props);
return prop;
}
/**
*
* @param props The properties to check
* @param userId The userId trying to copy these properties to a library
* Checks that every property can be copied out of the library that originated it by this user
*/
function assertSourceLibraryCopyPermission(props, method) {
// Skip on the client
if (method.isSimulation) return;
// Get all the library node ids that are sources for these properties
const libraryNodeIds = [];
props.forEach(prop => {
if (prop.libraryNodeId) libraryNodeIds.push(prop.libraryNodeId);
});
if (!libraryNodeIds.length) return;
// Get the actual library Ids that each of these source nodes came from
const sourceLibIds = new Set();
LibraryNodes.find({
_id: { $in: libraryNodeIds }
}, {
fields: { root: 1 }
}).forEach(node => {
sourceLibIds.add(node.root.id);
});
// Assert copy permission on each of those libraries
Libraries.find({
_id: { $in: Array.from(sourceLibIds) }
}, {
fields: {
name: 1,
owner: 1,
readers: 1,
writers: 1,
public: 1,
readersCanCopy: 1,
}
}).forEach(lib => {
try {
assertCopyPermission(lib, method.userId);
} catch (e) {
throw new Meteor.Error('Copy permission denied',
`One of the properties you are copying comes from ${lib.name}, which you do not have permission to copy from`);
}
});
}
export function cleanProps(props) {
return props.map(prop => {
let schema = LibraryNodes.simpleSchema(prop);
return schema.clean(prop);
});
}
export default copyPropertyToLibrary;

View File

@@ -1,139 +0,0 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import SimpleSchema from 'simpl-schema';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js';
import { applyTriggers } from '/imports/api/engine/actions/applyTriggers.js';
import ActionContext from '/imports/api/engine/actions/ActionContext.js';
const damageProperty = new ValidatedMethod({
name: 'creatureProperties.damage',
validate: new SimpleSchema({
_id: SimpleSchema.RegEx.Id,
operation: {
type: String,
allowedValues: ['set', 'increment']
},
value: Number,
}).validator(),
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 20,
timeInterval: 5000,
},
run({ _id, operation, value }) {
// Get action context
let prop = CreatureProperties.findOne(_id);
if (!prop) throw new Meteor.Error(
'Damage property failed', 'Property doesn\'t exist'
);
const creatureId = prop.ancestors[0].id;
const actionContext = new ActionContext(creatureId, [creatureId], this);
// Check permissions
assertEditPermission(actionContext.creature, this.userId);
// Check if property can take damage
let schema = CreatureProperties.simpleSchema(prop);
if (!schema.allowsKey('damage')) {
throw new Meteor.Error(
'Damage property failed',
`Property of type "${prop.type}" can't be damaged`
);
}
// Replace the prop by its actionContext counterpart if possible
if (prop.variableName) {
const actionContextProp = actionContext.scope[prop.variableName];
if (actionContextProp?._id === prop._id) {
prop = actionContextProp;
}
}
const result = damagePropertyWork({ prop, operation, value, actionContext });
// Insert the log
actionContext.writeLog();
return result;
},
});
export function damagePropertyWork({ prop, operation, value, actionContext }) {
// Save the value to the scope before applying the before triggers
if (operation === 'increment') {
if (value >= 0) {
actionContext.scope['$damage'] = value;
} else {
actionContext.scope['$healing'] = -value;
}
} else {
actionContext.scope['$set'] = value;
}
applyTriggers(actionContext.triggers?.damageProperty?.before, prop, actionContext);
// fetch the value from the scope after the before triggers, in case they changed them
if (operation === 'increment') {
if (value >= 0) {
value = actionContext.scope['$damage'];
} else {
value = -actionContext.scope['$healing'];
}
} else {
value = actionContext.scope['$set'];
}
let damage, newValue, increment;
if (operation === 'set') {
const total = prop.total || 0;
// Set represents what we want the value to be after damage
// So we need the actual damage to get to that value
damage = total - value;
// Damage can't exceed total value
if (damage > total && !prop.ignoreLowerLimit) damage = total;
// Damage must be positive
if (damage < 0 && !prop.ignoreUpperLimit) damage = 0;
newValue = prop.total - damage;
// Write the results
CreatureProperties.update(prop._id, {
$set: { damage, value: newValue, dirty: true }
}, {
selector: prop
});
// Also write it straight to the prop so that it is updated in the actionContext
prop.damage = damage;
prop.value = newValue;
} else if (operation === 'increment') {
let currentValue = prop.value || 0;
let currentDamage = prop.damage || 0;
increment = value;
// Can't increase damage above the remaining value
if (increment > currentValue && !prop.ignoreLowerLimit) increment = currentValue;
// Can't decrease damage below zero
if (-increment > currentDamage && !prop.ignoreUpperLimit) increment = -currentDamage;
damage = currentDamage + increment;
newValue = prop.total - damage;
// Write the results
CreatureProperties.update(prop._id, {
$inc: { damage: increment, value: -increment },
$set: { dirty: true },
}, {
selector: prop
});
// Also write it straight to the prop so that it is updated in the actionContext
prop.damage += increment;
prop.value -= increment;
}
applyTriggers(actionContext.triggers?.damageProperty?.after, prop, actionContext);
if (operation === 'set') {
return damage;
} else if (operation === 'increment') {
return increment;
}
}
export default damageProperty;

View File

@@ -1,18 +1,18 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
import { import {
setLineageOfDocs, getFilter,
renewDocIds renewDocIds
} from '/imports/api/parenting/parenting.js'; } from '/imports/api/parenting/parentingFunctions';
import { reorderDocs } from '/imports/api/parenting/order.js'; import { rebuildNestedSets } from '/imports/api/parenting/parentingFunctions';
var snackbar; var snackbar;
if (Meteor.isClient) { if (Meteor.isClient) {
snackbar = require( snackbar = require(
'/imports/ui/components/snackbars/SnackbarQueue.js' '/imports/client/ui/components/snackbars/SnackbarQueue'
).snackbar ).snackbar
} }
@@ -33,22 +33,29 @@ const duplicateProperty = new ValidatedMethod({
}, },
run({ _id }) { run({ _id }) {
let property = CreatureProperties.findOne(_id); let property = CreatureProperties.findOne(_id);
let creature = getRootCreatureAncestor(property); if (!property) throw new Meteor.Error('not-found', 'The source property was not found');
const creature = getRootCreatureAncestor(property);
assertEditPermission(creature, this.userId); assertEditPermission(creature, this.userId);
// Renew the doc ID // Renew the doc ID
let randomSrc = DDP.randomStream('duplicateProperty'); const randomSrc = DDP.randomStream('duplicateProperty');
let propertyId = randomSrc.id(); const propertyId = randomSrc.id();
property._id = propertyId; property._id = propertyId;
// Change the variableName so it isn't immediately overridden
if (property.variableName) {
property.variableName += 'Copy'
}
// Get all the descendants // Get all the descendants
let nodes = CreatureProperties.find({ const nodes = CreatureProperties.find({
'ancestors.id': _id, ...getFilter.descendants(property),
removed: { $ne: true }, removed: { $ne: true },
}, { }, {
limit: DUPLICATE_CHILDREN_LIMIT + 1, limit: DUPLICATE_CHILDREN_LIMIT + 1,
sort: { order: 1 }, sort: { left: 1 },
}).fetch(); }).fetch();
// Alert the user if the limit was hit // Alert the user if the limit was hit
@@ -61,33 +68,28 @@ const duplicateProperty = new ValidatedMethod({
} }
} }
// re-map all the ancestors // Give the docs new IDs without breaking internal references
setLineageOfDocs({ const allNodes = [property, ...nodes];
docArray: nodes, renewDocIds({
newAncestry: [ docArray: allNodes,
...property.ancestors, idMap: {
{ id: propertyId, collection: 'creatureProperties' } [_id]: propertyId,
], [propertyId]: propertyId,
oldParent: { id: _id, collection: 'creatureProperties' }, },
}); });
// Give the docs new IDs without breaking internal references
renewDocIds({ docArray: nodes });
// Order the root node // Order the root node
property.order += 0.5; property.left = Number.MAX_SAFE_INTEGER - 1;
property.right = Number.MAX_SAFE_INTEGER;
// Mark the sheet as needing recompute // Mark the sheet as needing recompute
property.dirty = true; property.dirty = true;
// Insert the properties // Insert the properties
CreatureProperties.batchInsert([property, ...nodes]); CreatureProperties.batchInsert(allNodes);
// Tree structure changed by inserts, reorder the tree // Tree structure changed by inserts, reorder the tree
reorderDocs({ rebuildNestedSets(CreatureProperties, property.root.id);
collection: CreatureProperties,
ancestorId: property.ancestors[0].id,
});
return propertyId; return propertyId;
}, },

View File

@@ -1,11 +1,11 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import { organizeDoc } from '/imports/api/parenting/organizeMethods.js'; import { organizeDoc } from '/imports/api/parenting/organizeMethods';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
import BUILT_IN_TAGS from '/imports/constants/BUILT_IN_TAGS.js'; import BUILT_IN_TAGS from '/imports/constants/BUILT_IN_TAGS';
import getParentRefByTag from '/imports/api/creature/creatureProperties/methods/getParentRefByTag.js'; import getParentRefByTag from '/imports/api/creature/creatureProperties/methods/getParentRefByTag';
// Equipping or unequipping an item will also change its parent // Equipping or unequipping an item will also change its parent
const equipItem = new ValidatedMethod({ const equipItem = new ValidatedMethod({
@@ -36,7 +36,7 @@ const equipItem = new ValidatedMethod({
let parentRef = getParentRefByTag(creature._id, tag); let parentRef = getParentRefByTag(creature._id, tag);
if (!parentRef) parentRef = { id: creature._id, collection: 'creatures' }; if (!parentRef) parentRef = { id: creature._id, collection: 'creatures' };
organizeDoc.call({ organizeDoc.callAsync({
docRef: { docRef: {
id: _id, id: _id,
collection: 'creatureProperties', collection: 'creatureProperties',

View File

@@ -1,8 +1,8 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
const flipToggle = new ValidatedMethod({ const flipToggle = new ValidatedMethod({
name: 'creatureProperties.flipToggle', name: 'creatureProperties.flipToggle',
@@ -17,7 +17,7 @@ const flipToggle = new ValidatedMethod({
run({ _id }) { run({ _id }) {
// Permission // Permission
let property = CreatureProperties.findOne(_id, { let property = CreatureProperties.findOne(_id, {
fields: { type: 1, ancestors: 1, enabled: 1, disabled: 1 } fields: { type: 1, root: 1, enabled: 1, disabled: 1 }
}); });
if (property.type !== 'toggle') { if (property.type !== 'toggle') {
throw new Meteor.Error('wrong property', throw new Meteor.Error('wrong property',

View File

@@ -1,13 +1,14 @@
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { getFilter } from '/imports/api/parenting/parentingFunctions';
export default function getParentRefByTag(creatureId, tag){ export default function getParentRefByTag(creatureId, tag) {
let prop = CreatureProperties.findOne({ let prop = CreatureProperties.findOne({
'ancestors.id': creatureId, ...getFilter.descendantsOfRoot(creatureId),
removed: {$ne: true}, removed: { $ne: true },
inactive: {$ne: true}, inactive: { $ne: true },
tags: tag, tags: tag,
}, { }, {
sort: {order: 1}, sort: { left: 1 },
}); });
return prop && {id: prop._id, collection: 'creatureProperties'}; return prop && { id: prop._id, collection: 'creatureProperties' };
} }

View File

@@ -1,62 +1,78 @@
export default function getSlotFillFilter({slot, libraryIds}){ import { getFilter } from '/imports/api/parenting/parentingFunctions';
export default function getSlotFillFilter({ slot, libraryIds }) {
if (!slot) throw 'Slot is required for getSlotFillFilter';
if (!libraryIds) throw 'LibraryIds is required for getSlotFillFilter';
let filter = { let filter = {
removed: {$ne: true}, fillSlots: true,
$and: [] removed: { $ne: true },
$and: [],
}; };
if (libraryIds){ if (libraryIds.length) {
filter['ancestors.id'] = {$in: libraryIds}; Object.assign(
filter,
getFilter.descendantsOfAllRoots(libraryIds)
);
} }
if (slot.slotType){ if (slot.slotType) {
filter.$and.push({ filter.$and.push({
$or: [{ $or: [{
type: slot.slotType type: slot.slotType
},{ }, {
type: 'slotFiller',
slotFillerType: slot.slotType, slotFillerType: slot.slotType,
}] }]
}); });
} else if (slot.type === 'class') { } else if (slot.type === 'class') {
filter.$and.push({ const classLevelFilter = {
$or: [{ type: 'classLevel',
type: 'classLevel', };
},{ const slotFillerFilter = {
type: 'slotFiller', slotFillerType: 'classLevel',
slotFillerType: 'classLevel', };
}]
}); // Match variable name or tags
if (slot.variableName) { if (slot.variableName) {
filter.variableName = slot.variableName; classLevelFilter.variableName = slot.variableName;
slotFillerFilter.libraryTags = slot.variableName;
} }
// Only search for levels the class needs // Only search for levels the class needs
if (slot.missingLevels && slot.missingLevels.length) { if (slot.missingLevels && slot.missingLevels.length) {
filter.level = {$in: slot.missingLevels}; classLevelFilter.level = { $in: slot.missingLevels };
slotFillerFilter['cache.node.level'] = { $in: slot.missingLevels };
} else { } else {
filter.level = (slot.level || 0) + 1; classLevelFilter.level = { $gt: slot.level || 0 };
slotFillerFilter['cache.node.level'] = { $gt: slot.level || 0 };
} }
filter.$and.push({
$or: [classLevelFilter, slotFillerFilter]
});
} }
let tagsOr = []; let tagsOr = [];
let tagsNin = []; let tagsNin = [];
if (slot.slotTags && slot.slotTags.length){ if (slot.slotTags && slot.slotTags.length) {
tagsOr.push({tags: {$all: slot.slotTags}}); tagsOr.push({ libraryTags: { $all: slot.slotTags } });
} }
if (slot.extraTags && slot.extraTags.length){ if (slot.extraTags && slot.extraTags.length) {
slot.extraTags.forEach(extra => { slot.extraTags.forEach(extra => {
if (!extra.tags || !extra.tags.length) return; if (!extra.tags || !extra.tags.length) return;
if (extra.operation === 'OR'){ if (extra.operation === 'OR') {
tagsOr.push({tags: {$all: extra.tags}}); tagsOr.push({ libraryTags: { $all: extra.tags } });
} else if (extra.operation === 'NOT'){ } else if (extra.operation === 'NOT') {
tagsNin.push(...extra.tags); tagsNin.push(...extra.tags);
} }
}); });
} }
if (tagsOr.length){ if (tagsOr.length) {
filter.$or = tagsOr; filter.$or = tagsOr;
} }
if (tagsNin.length){ if (tagsNin.length) {
filter.$and.push({tags: {$nin: tagsNin}}); filter.$and.push({ libraryTags: { $nin: tagsNin } });
} }
if (!filter.$and.length){ if (!filter.$and.length) {
delete filter.$and; delete filter.$and;
} }
return filter; return filter;

View File

@@ -0,0 +1,85 @@
import { assert } from 'chai';
import getSlotFillFilter from '/imports/api/creature/creatureProperties/methods/getSlotFillFilter';
describe('Slot fill filter', function () {
it('Gives error if arguments aren\'t provided', function () {
assert.throws(
() => getSlotFillFilter(undefined),
null, null, 'Passing undefined should give an error'
);
assert.throws(
() => getSlotFillFilter({
slot: { slotTags: ['tag1'] },
}),
null, null, 'Passing no libraryIds should give an error'
);
assert.throws(
() => getSlotFillFilter({
libraryIds: ['libraryId1'],
}),
null, null, 'Passing no slot should give an error'
);
});
it('filters using basic slot tags', function () {
const filter = getSlotFillFilter({
slot: {
slotTags: ['tag1', 'tag2']
},
libraryIds: ['libraryId1', 'libraryId2'],
});
assert.deepStrictEqual(filter, {
$or: [{
libraryTags: { $all: ['tag1', 'tag2'] }
}],
'root.id': { $in: ['libraryId1', 'libraryId2'] },
removed: { $ne: true },
fillSlots: true,
});
});
it('filters using slot type', function () {
const filter = getSlotFillFilter({
slot: {
slotTags: ['tag1', 'tag2'],
slotType: 'feature',
},
libraryIds: ['libraryId1', 'libraryId2']
});
assert.deepStrictEqual(filter.$and, [{
$or: [{
type: 'feature'
}, {
slotFillerType: 'feature',
}],
}]);
});
it('filters using extra tags', function () {
const filter = getSlotFillFilter({
slot: {
slotTags: ['tag1', 'tag2'],
extraTags: [
{ operation: 'OR', tags: ['tag3', 'tag4'] },
{ operation: 'NOT', tags: ['tag5', 'tag6'] },
{ operation: 'NOT', tags: ['tag7', 'tag8'] },
],
},
libraryIds: ['libraryId1', 'libraryId2'],
});
assert.deepStrictEqual(filter, {
$or: [
{ libraryTags: { $all: ['tag1', 'tag2'] } },
{ libraryTags: { $all: ['tag3', 'tag4'] } },
],
$and: [
{ libraryTags: { $nin: ['tag5', 'tag6', 'tag7', 'tag8'] } },
],
'root.id': { $in: ['libraryId1', 'libraryId2'] },
removed: { $ne: true },
fillSlots: true,
});
});
});

View File

@@ -1,13 +1,13 @@
import '/imports/api/creature/creatureProperties/methods/adjustQuantity.js'; import '/imports/api/creature/creatureProperties/methods/adjustQuantity';
import '/imports/api/creature/creatureProperties/methods/damageProperty.js'; import '/imports/api/creature/creatureProperties/methods/copyPropertyToLibrary';
import '/imports/api/creature/creatureProperties/methods/duplicateProperty.js'; import '/imports/api/creature/creatureProperties/methods/duplicateProperty';
import '/imports/api/creature/creatureProperties/methods/equipItem.js'; import '/imports/api/creature/creatureProperties/methods/equipItem';
import '/imports/api/creature/creatureProperties/methods/insertProperty.js'; import '/imports/api/creature/creatureProperties/methods/insertProperty';
import '/imports/api/creature/creatureProperties/methods/insertPropertyFromLibraryNode.js'; import '/imports/api/creature/creatureProperties/methods/insertPropertyFromLibraryNode';
import '/imports/api/creature/creatureProperties/methods/pullFromProperty.js'; import '/imports/api/creature/creatureProperties/methods/pullFromProperty';
import '/imports/api/creature/creatureProperties/methods/pushToProperty.js'; import '/imports/api/creature/creatureProperties/methods/pushToProperty';
import '/imports/api/creature/creatureProperties/methods/restoreProperty.js'; import '/imports/api/creature/creatureProperties/methods/restoreProperty';
import '/imports/api/creature/creatureProperties/methods/selectAmmoItem.js'; import '/imports/api/creature/creatureProperties/methods/selectAmmoItem';
import '/imports/api/creature/creatureProperties/methods/softRemoveProperty.js'; import '/imports/api/creature/creatureProperties/methods/softRemoveProperty';
import '/imports/api/creature/creatureProperties/methods/updateCreatureProperty.js'; import '/imports/api/creature/creatureProperties/methods/updateCreatureProperty';
import '/imports/api/creature/creatureProperties/methods/flipToggle.js'; import '/imports/api/creature/creatureProperties/methods/flipToggle';

View File

@@ -1,14 +1,12 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import { reorderDocs } from '/imports/api/parenting/order.js'; import { fetchDocByRef, rebuildNestedSets } from '/imports/api/parenting/parentingFunctions';
import { getAncestry } from '/imports/api/parenting/parenting.js'; import getParentRefByTag from '/imports/api/creature/creatureProperties/methods/getParentRefByTag';
import getParentRefByTag from '/imports/api/creature/creatureProperties/methods/getParentRefByTag.js'; import { RefSchema } from '/imports/api/parenting/ChildSchema';
import { RefSchema } from '/imports/api/parenting/ChildSchema.js';
import { getHighestOrder } from '/imports/api/parenting/order.js';
const insertProperty = new ValidatedMethod({ const insertProperty = new ValidatedMethod({
name: 'creatureProperties.insert', name: 'creatureProperties.insert',
@@ -25,27 +23,23 @@ const insertProperty = new ValidatedMethod({
timeInterval: 5000, timeInterval: 5000,
}, },
run({ creatureProperty, parentRef }) { run({ creatureProperty, parentRef }) {
// get the new ancestry for the properties let rootCreature;
let { parentDoc, ancestors } = getAncestry({ parentRef }); const parentDoc = fetchDocByRef(parentRef);
// Check permission to edit // Check permission to edit
let rootCreature;
if (parentRef.collection === 'creatures') { if (parentRef.collection === 'creatures') {
rootCreature = parentDoc; rootCreature = parentDoc;
} else if (parentRef.collection === 'creatureProperties') { } else if (parentRef.collection === 'creatureProperties') {
rootCreature = getRootCreatureAncestor(parentDoc); rootCreature = getRootCreatureAncestor(parentDoc);
creatureProperty.parentId = parentDoc._id;
} else { } else {
throw `${parentRef.collection} is not a valid parent collection` throw `${parentRef.collection} is not a valid parent collection`
} }
assertEditPermission(rootCreature, this.userId); assertEditPermission(rootCreature, this.userId);
creatureProperty.parent = parentRef; creatureProperty.root = { collection: 'creatures', id: rootCreature._id };
creatureProperty.ancestors = ancestors;
return insertPropertyWork({ return insertPropertyWork(creatureProperty);
property: creatureProperty,
creature: rootCreature,
});
}, },
}); });
@@ -77,18 +71,17 @@ const insertPropertyAsChildOfTag = new ValidatedMethod({
}, },
run({ creatureProperty, creatureId, tag, tagDefaultName }) { run({ creatureProperty, creatureId, tag, tagDefaultName }) {
let parentRef = getParentRefByTag(creatureId, tag); let parentRef = getParentRefByTag(creatureId, tag);
let insertFolderFirst = false;
if (!parentRef) { if (!parentRef) {
// Use the creature as the parent and mark that we need to insert the folder first later // Use the creature as the parent and mark that we need to insert the folder first later
var insertFolderFirst = true; insertFolderFirst = true;
parentRef = { id: creatureId, collection: 'creatures' }; parentRef = { id: creatureId, collection: 'creatures' };
} }
// get the new ancestry for the properties
let { parentDoc, ancestors } = getAncestry({ parentRef });
// Check permission to edit // Check permission to edit
let rootCreature; let rootCreature;
const parentDoc = fetchDocByRef(parentRef);
if (parentRef.collection === 'creatures') { if (parentRef.collection === 'creatures') {
rootCreature = parentDoc; rootCreature = parentDoc;
} else if (parentRef.collection === 'creatureProperties') { } else if (parentRef.collection === 'creatureProperties') {
@@ -98,46 +91,34 @@ const insertPropertyAsChildOfTag = new ValidatedMethod({
} }
assertEditPermission(rootCreature, this.userId); assertEditPermission(rootCreature, this.userId);
const root = { collection: 'creatures', id: rootCreature._id };
// Add the folder first if we need to // Add the folder first if we need to
if (insertFolderFirst) { if (insertFolderFirst) {
let order = getHighestOrder({
collection: CreatureProperties,
ancestorId: parentRef.id,
}) + 1;
let id = CreatureProperties.insert({ let id = CreatureProperties.insert({
type: 'folder', type: 'folder',
name: tagDefaultName || (tag.charAt(0).toUpperCase() + tag.slice(1)), name: tagDefaultName || (tag.charAt(0).toUpperCase() + tag.slice(1)),
tags: [tag], tags: [tag],
parent: parentRef, // parentId: undefined,
ancestors: [parentRef], root,
order,
}); });
// Make the folder our new parent // Make the folder our new parent
let newParentRef = { id, collection: 'creatureProperties' }; parentRef = { id, collection: 'creatureProperties' };
ancestors = [parentRef, newParentRef];
parentRef = newParentRef;
creatureProperty.order = order + 1;
} }
creatureProperty.parent = parentRef; creatureProperty.root = root;
creatureProperty.ancestors = ancestors; creatureProperty.parentId = parentRef.id;
return insertPropertyWork({ return insertPropertyWork(creatureProperty);
property: creatureProperty,
creature: rootCreature,
});
}, },
}); });
export function insertPropertyWork({ property, creature }) { export function insertPropertyWork(property) {
delete property._id; delete property._id;
property.dirty = true; property.dirty = true;
let _id = CreatureProperties.insert(property); let _id = CreatureProperties.insert(property);
// Tree structure changed by insert, reorder the tree // Tree structure changed by insert, reorder the tree
reorderDocs({ rebuildNestedSets(CreatureProperties, property.root.id);
collection: CreatureProperties,
ancestorId: creature._id,
});
return _id; return _id;
} }

View File

@@ -1,19 +1,18 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import LibraryNodes from '/imports/api/library/LibraryNodes.js'; import LibraryNodes from '/imports/api/library/LibraryNodes';
import { RefSchema } from '/imports/api/parenting/ChildSchema.js'; import { RefSchema } from '/imports/api/parenting/ChildSchema';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import { import {
setLineageOfDocs, renewDocIds,
getAncestry, fetchDocByRef,
renewDocIds rebuildNestedSets,
} from '/imports/api/parenting/parenting.js'; getFilter
import { reorderDocs } from '/imports/api/parenting/order.js'; } from '/imports/api/parenting/parentingFunctions';
import { setDocToLastOrder } from '/imports/api/parenting/order.js'; import { union } from 'lodash';
import fetchDocByRef from '/imports/api/parenting/fetchDocByRef.js';
const insertPropertyFromLibraryNode = new ValidatedMethod({ const insertPropertyFromLibraryNode = new ValidatedMethod({
name: 'creatureProperties.insertPropertyFromLibraryNode', name: 'creatureProperties.insertPropertyFromLibraryNode',
@@ -29,19 +28,15 @@ const insertPropertyFromLibraryNode = new ValidatedMethod({
parentRef: { parentRef: {
type: RefSchema, type: RefSchema,
}, },
order: {
type: Number,
optional: true,
},
}).validator(), }).validator(),
mixins: [RateLimiterMixin], mixins: [RateLimiterMixin],
rateLimit: { rateLimit: {
numRequests: 5, numRequests: 5,
timeInterval: 5000, timeInterval: 5000,
}, },
run({ nodeIds, parentRef, order }) { run({ nodeIds, parentRef }) {
// get the new ancestry for the properties // get the new ancestry for the properties
let { parentDoc, ancestors } = getAncestry({ parentRef }); const parentDoc = fetchDocByRef(parentRef);
// Check permission to edit // Check permission to edit
let rootCreature; let rootCreature;
@@ -54,37 +49,32 @@ const insertPropertyFromLibraryNode = new ValidatedMethod({
} }
assertEditPermission(rootCreature, this.userId); assertEditPermission(rootCreature, this.userId);
// {libraryId: hasViewPermission} const root = { collection: 'creatures', id: rootCreature._id };
//let libraryPermissionMemoir = {}; const parentId = parentRef.id;
let node; let node;
nodeIds.forEach(nodeId => { nodeIds.forEach(nodeId => {
// TODO: Check library view permission for each node before starting node = insertPropertyFromNode(nodeId, root, parentId);
node = insertPropertyFromNode(nodeId, ancestors, order);
}); });
// get one of the root inserted docs
let rootId = node._id;
// Tree structure changed by inserts, reorder the tree // Tree structure changed by inserts, reorder the tree
reorderDocs({ rebuildNestedSets(CreatureProperties, rootCreature._id);
collection: CreatureProperties,
ancestorId: rootCreature._id, // get one of the root inserted docs
}); const lastInsertedId = node?._id;
// Return the docId of the last property, the inserted root property return lastInsertedId;
return rootId;
}, },
}); });
function insertPropertyFromNode(nodeId, ancestors, order) { function insertPropertyFromNode(nodeId, root, parentId) {
// Fetch the library node and its decendents, provided they have not been // Fetch the library node and its descendants, provided they have not been
// removed // removed
// TODO: Check permission to read the library this node is in
let node = LibraryNodes.findOne({ let node = LibraryNodes.findOne({
_id: nodeId, _id: nodeId,
removed: { $ne: true }, removed: { $ne: true },
}); });
if (!node) { if (!node) {
if (Meteor.isClient) return; if (Meteor.isClient) return {};
else { else {
throw new Meteor.Error( throw new Meteor.Error(
'Insert property from library failed', 'Insert property from library failed',
@@ -92,69 +82,51 @@ function insertPropertyFromNode(nodeId, ancestors, order) {
); );
} }
} }
let oldParent = node.parent;
let nodes = LibraryNodes.find({ let nodes = LibraryNodes.find({
'ancestors.id': nodeId, ...getFilter.descendants(node),
removed: { $ne: true }, removed: { $ne: true },
}).fetch(); }).fetch();
// Convert all references into actual nodes
nodes = reifyNodeReferences(nodes);
// The root node is first in the array of nodes // The root node is first in the array of nodes
// It must get the first generated ID to prevent flickering // It must get the first generated ID to prevent flickering
nodes = [node, ...nodes]; nodes = [node, ...nodes];
// Convert all references into actual nodes
nodes = reifyNodeReferences(nodes);
// Refetch the root node, it might have been reified
node = nodes[0] || node;
// set libraryNodeIds // set libraryNodeIds
storeLibraryNodeReferences(nodes); storeLibraryNodeReferences(nodes);
// re-map all the ancestors
setLineageOfDocs({
docArray: nodes,
newAncestry: ancestors,
oldParent,
});
// Give the docs new IDs without breaking internal references // Give the docs new IDs without breaking internal references
renewDocIds({ renewDocIds({
docArray: nodes, docArray: nodes,
collectionMap: { 'libraryNodes': 'creatureProperties' } collectionMap: { 'libraryNodes': 'creatureProperties' }
}); });
// Order the root node // Mark root node as dirty
if (order === undefined) { node.dirty = true;
setDocToLastOrder({
collection: CreatureProperties,
doc: node,
});
} else {
node.order = order;
}
// Mark all nodes as dirty // Move the root node to the end of the order
dirtyNodes(nodes); node.left = Number.MAX_SAFE_INTEGER;
// Insert the creature properties // Insert the creature properties
CreatureProperties.batchInsert(nodes); CreatureProperties.batchInsert(nodes);
return node; return node;
} }
function storeLibraryNodeReferences(nodes) { export function storeLibraryNodeReferences(nodes) {
nodes.forEach(node => { nodes.forEach(node => {
if (node.libraryNodeId) return; if (node.libraryNodeId) return;
node.libraryNodeId = node._id; node.libraryNodeId = node._id;
}); });
} }
function dirtyNodes(nodes) {
nodes.forEach(node => {
node.dirty = true;
});
}
// Covert node references into actual nodes // Covert node references into actual nodes
// TODO: check permissions for each library a reference node references // TODO: check permissions for each library a reference node references
function reifyNodeReferences(nodes, visitedRefs = new Set(), depth = 0) { export function reifyNodeReferences(nodes, visitedRefs = new Set(), depth = 0) {
depth += 1; depth += 1;
// New nodes added this function // New nodes added this function
let newNodes = []; let newNodes = [];
@@ -174,7 +146,7 @@ function reifyNodeReferences(nodes, visitedRefs = new Set(), depth = 0) {
let referencedNode let referencedNode
try { try {
referencedNode = fetchDocByRef(node.ref); referencedNode = fetchDocByRef(node.ref);
referencedNode.order = node.order; referencedNode.tags = union(node.tags, referencedNode.tags);
// We are definitely replacing this node, so add it to the list // We are definitely replacing this node, so add it to the list
visitedRefs.add(node._id); visitedRefs.add(node._id);
} catch (e) { } catch (e) {
@@ -183,23 +155,15 @@ function reifyNodeReferences(nodes, visitedRefs = new Set(), depth = 0) {
} }
// Get all the descendants of the referenced node // Get all the descendants of the referenced node
let descendents = LibraryNodes.find({ let descendants = LibraryNodes.find({
'ancestors.id': referencedNode._id, ...getFilter.descendants(referencedNode),
removed: { $ne: true }, removed: { $ne: true },
}, { }, {
sort: { order: 1 }, sort: { left: 1 },
}).fetch(); }).fetch();
// We are adding the referenced node and its descendants // We are adding the referenced node and its descendants
let addedNodes = [referencedNode, ...descendents]; let addedNodes = [referencedNode, ...descendants];
// re-map all the ancestors to parent the new sub-tree into our existing
// node tree
setLineageOfDocs({
docArray: addedNodes,
newAncestry: node.ancestors,
oldParent: referencedNode.parent,
});
// Filter all the looped references // Filter all the looped references
addedNodes = addedNodes.filter(addedNode => { addedNodes = addedNodes.filter(addedNode => {

View File

@@ -1,8 +1,8 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
const pullFromProperty = new ValidatedMethod({ const pullFromProperty = new ValidatedMethod({
name: 'creatureProperties.pull', name: 'creatureProperties.pull',

View File

@@ -1,8 +1,8 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
import { get } from 'lodash'; import { get } from 'lodash';
const pushToProperty = new ValidatedMethod({ const pushToProperty = new ValidatedMethod({

View File

@@ -1,10 +1,10 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import { restore } from '/imports/api/parenting/softRemove.js'; import { restore } from '/imports/api/parenting/softRemove';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
const restoreProperty = new ValidatedMethod({ const restoreProperty = new ValidatedMethod({
name: 'creatureProperties.restore', name: 'creatureProperties.restore',
@@ -23,13 +23,7 @@ const restoreProperty = new ValidatedMethod({
assertEditPermission(rootCreature, this.userId); assertEditPermission(rootCreature, this.userId);
// Do work // Do work
restore({ restore(CreatureProperties, property, { $set: { dirty: true } });
_id,
collection: CreatureProperties,
extraUpdates: {
$set: { dirty: true }
},
});
} }
}); });

View File

@@ -1,9 +1,9 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
const selectAmmoItem = new ValidatedMethod({ const selectAmmoItem = new ValidatedMethod({
name: 'creatureProperties.selectAmmoItem', name: 'creatureProperties.selectAmmoItem',

View File

@@ -1,10 +1,10 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import { softRemove } from '/imports/api/parenting/softRemove.js'; import { softRemove } from '/imports/api/parenting/softRemove';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
const softRemoveProperty = new ValidatedMethod({ const softRemoveProperty = new ValidatedMethod({
name: 'creatureProperties.softRemove', name: 'creatureProperties.softRemove',
@@ -23,7 +23,7 @@ const softRemoveProperty = new ValidatedMethod({
assertEditPermission(rootCreature, this.userId); assertEditPermission(rootCreature, this.userId);
// Do work // Do work
softRemove({ _id, collection: CreatureProperties }); softRemove(CreatureProperties, property);
} }
}); });

View File

@@ -1,8 +1,8 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor.js'; import getRootCreatureAncestor from '/imports/api/creature/creatureProperties/getRootCreatureAncestor';
const updateCreatureProperty = new ValidatedMethod({ const updateCreatureProperty = new ValidatedMethod({
name: 'creatureProperties.update', name: 'creatureProperties.update',
@@ -14,6 +14,10 @@ const updateCreatureProperty = new ValidatedMethod({
case 'order': case 'order':
case 'parent': case 'parent':
case 'ancestors': case 'ancestors':
case 'root':
case 'left':
case 'right':
case 'parentId':
case 'damage': case 'damage':
throw new Meteor.Error('Permission denied', throw new Meteor.Error('Permission denied',
'This property can\'t be updated directly'); 'This property can\'t be updated directly');
@@ -21,13 +25,13 @@ const updateCreatureProperty = new ValidatedMethod({
}, },
mixins: [RateLimiterMixin], mixins: [RateLimiterMixin],
rateLimit: { rateLimit: {
numRequests: 5, numRequests: 12,
timeInterval: 5000, timeInterval: 5000,
}, },
run({ _id, path, value }) { run({ _id, path, value }) {
// Permission // Permission
let property = CreatureProperties.findOne(_id, { let property = CreatureProperties.findOne(_id, {
fields: { type: 1, ancestors: 1 } fields: { type: 1, root: 1 }
}); });
let rootCreature = getRootCreatureAncestor(property); let rootCreature = getRootCreatureAncestor(property);
assertEditPermission(rootCreature, this.userId); assertEditPermission(rootCreature, this.userId);

View File

@@ -1,12 +1,9 @@
import computeCreature from '/imports/api/engine/computeCreature.js'; import computeCreature from '/imports/api/engine/computeCreature';
/** /**
* Recomputes all ancestor creatures of this property * Recomputes all ancestor creatures of this property
* @deprecated
*/ */
export default function recomputeCreaturesByProperty(property){ export default function recomputeCreaturesByProperty(property) {
for (let ref of property.ancestors){ computeCreature.call(property.root.id);
if (ref.collection === 'creatures') {
computeCreature.call(ref.id);
}
}
} }

View File

@@ -1,21 +0,0 @@
//set up the collection for creature variables
let CreatureVariables = new Mongo.Collection('creatureVariables');
// Unique index on _creatureId
if (Meteor.isServer) {
CreatureVariables._ensureIndex({ _creatureId: 1 }, { unique: true })
}
/** No schema because the structure isn't known until compute time
* Expect documents to looke like:
* {
* _id: "nE8Ngd6K4L4jSxLY2",
* _creatureId: "nE8Ngd6K4L4jSxLY2", // indexed reference to the creature
* explicitlyDefinedVariableName: {...some creatureProperty}
* implicitVariableName: {value: 10},
* undefinedVariableName: {},
* }
* Where top level fields that don't start with `_` are variables on the sheet
**/
export default CreatureVariables;

View File

@@ -0,0 +1,103 @@
import { getSingleProperty } from '/imports/api/engine/loadCreatures';
import ParseNode from '/imports/parser/parseTree/ParseNode';
import array from '/imports/parser/parseTree/array';
import constant, { isFiniteNode } from '/imports/parser/parseTree/constant';
//set up the collection for creature variables
const CreatureVariables = new Mongo.Collection('creatureVariables');
// Unique index on _creatureId
if (Meteor.isServer) {
CreatureVariables._ensureIndex({ _creatureId: 1 }, { unique: true })
}
/** No schema because the structure isn't known until compute time
* Expect documents to look like:
* {
* _id: "nE8Ngd6K4L4jSxLY2",
* _creatureId: "nE8Ngd6K4L4jSxLY2", // indexed reference to the creature
* explicitlyDefinedVariableName: {...some creatureProperty},
* // Must be found in CreatureProperties before using:
* linkedProperty: { _propId: "nE8Ngd6K1234SxLY2" }
* implicitVariableName: {value: 10},
* undefinedVariableName: {},
* }
* Where top level fields that don't start with `_` are variables on the sheet
**/
/**
* Get the property from the given scope, respecting properties that are just a link to the actual
* property document
*/
export function getFromScope(name: string, scope) {
let value = scope?.[name];
if (value?._propId) {
const [propId, rowIdentifier, rowNumber] = value._propId.split('_');
value = getSingleProperty(scope._creatureId, propId);
if (rowIdentifier === 'row' && value?.type === 'pointBuy') {
value = value.values[rowNumber];
}
}
return value;
}
export function getNumberFromScope(name, scope) {
const parseNode = getParseNodeFromScope(name, scope);
if (!parseNode || !isFiniteNode(parseNode)) {
return undefined;
}
return parseNode.value;
}
export async function getConstantValueFromScope(
name, scope
) {
const parseNode = getParseNodeFromScope(name, scope);
if (!parseNode) return;
if (parseNode.parseType !== 'constant') return;
return parseNode.value;
}
export function getParseNodeFromScope(name, scope): ParseNode | undefined {
let value = getFromScope(name, scope);
if (!value) return;
let valueType = getType(value);
// Iterate into object.values
while (valueType === 'object') {
// Prefer the valueNode over the value
if (value.valueNode) {
value = value.valueNode;
} else {
value = value.value;
}
valueType = getType(value);
}
// Return a discovered parse node
if (valueType === 'parseNode') {
return value;
}
// Return a parse node based on the constant type returned
if (valueType === 'string' || valueType === 'number' || valueType === 'boolean') {
return constant.create({ value });
}
// Return a parser array
if (valueType === 'array') {
// If the first value is a parse node, assume all the values are
if (getType(value[0]) === 'parseNode') {
return array.create({
values: value,
});
}
// Create the array from js primitives instead
return array.fromConstantArray(value);
}
}
function getType(val) {
if (!val) return typeof val;
if (Array.isArray(val)) return 'array';
if (val.parseType) return 'parseNode';
return typeof val;
}
export default CreatureVariables;

View File

@@ -1,13 +1,59 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import deathSaveSchema from '/imports/api/properties/subSchemas/DeathSavesSchema.js' import ColorSchema, { Colored } from '/imports/api/properties/subSchemas/ColorSchema';
import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js'; import SharingSchema, { Shared } from '/imports/api/sharing/SharingSchema';
import SharingSchema from '/imports/api/sharing/SharingSchema.js'; import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS';
import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS.js';
export type Creature = Colored & Shared & {
// Strings
_id: string,
name?: string,
alignment?: string,
gender?: string,
picture?: string,
avatarPicture?: string,
// Libraries
allowedLibraries?: string[],
allowedLibraryCollections?: string[],
// Stats that are computed and denormalized outside of recomputation
denormalizedStats?: {
xp: number,
milestoneLevels: number,
},
propCount?: number,
// Does the character need a recompute?
dirty?: boolean,
// Version of computation engine that was last used to compute this creature
computeVersion?: string,
type: 'pc' | 'npc' | 'monster',
computeErrors?: {
type: string,
details?: any,
}[],
// Tabletop
tabletopId?: string,
initiativeRoll?: number,
settings: {
useVariantEncumbrance?: true,
hideSpellcasting?: true,
hideRestButtons?: true,
swapStatAndModifier?: true,
hideUnusedStats?: true,
showTreeTab?: true,
hideSpellsTab?: true,
hideCalculationErrors?: true,
hitDiceResetMultiplier?: number,
discordWebhook?: string,
},
};
//set up the collection for creatures //set up the collection for creatures
let Creatures = new Mongo.Collection('creatures'); const Creatures = new Mongo.Collection<Creature>('creatures');
let CreatureSettingsSchema = new SimpleSchema({ const CreatureSettingsSchema = new SimpleSchema({
//slowed down by carrying too much? //slowed down by carrying too much?
useVariantEncumbrance: { useVariantEncumbrance: {
type: Boolean, type: Boolean,
@@ -62,7 +108,24 @@ let CreatureSettingsSchema = new SimpleSchema({
}, },
}); });
let CreatureSchema = new SimpleSchema({ const IconGroupSchema = new SimpleSchema({
name: {
type: String,
max: STORAGE_LIMITS.name,
optional: true,
},
iconIds: {
type: Array,
max: 4,
defaultValue: [],
},
'iconIds.$': {
type: String,
max: STORAGE_LIMITS.variableName,
},
});
const CreatureSchema = new SimpleSchema({
// Strings // Strings
name: { name: {
type: String, type: String,
@@ -111,11 +174,6 @@ let CreatureSchema = new SimpleSchema({
regEx: SimpleSchema.RegEx.Id, regEx: SimpleSchema.RegEx.Id,
}, },
// Mechanics
deathSave: {
type: deathSaveSchema,
defaultValue: {},
},
// Stats that are computed and denormalised outside of recomputation // Stats that are computed and denormalised outside of recomputation
denormalizedStats: { denormalizedStats: {
type: Object, type: Object,
@@ -131,6 +189,10 @@ let CreatureSchema = new SimpleSchema({
type: SimpleSchema.Integer, type: SimpleSchema.Integer,
defaultValue: 0, defaultValue: 0,
}, },
propCount: {
type: SimpleSchema.Integer,
defaultValue: 0,
},
// Does the character need a recompute? // Does the character need a recompute?
dirty: { dirty: {
type: Boolean, type: Boolean,
@@ -146,16 +208,6 @@ let CreatureSchema = new SimpleSchema({
defaultValue: 'pc', defaultValue: 'pc',
allowedValues: ['pc', 'npc', 'monster'], allowedValues: ['pc', 'npc', 'monster'],
}, },
damageMultipliers: {
type: Object,
blackbox: true,
defaultValue: {}
},
variables: {
type: Object,
blackbox: true,
defaultValue: {}
},
computeErrors: { computeErrors: {
type: Array, type: Array,
optional: true, optional: true,
@@ -173,9 +225,10 @@ let CreatureSchema = new SimpleSchema({
}, },
// Tabletop // Tabletop
tabletop: { tabletopId: {
index: 1,
type: String, type: String,
regEx: SimpleSchema.RegEx.id, regEx: SimpleSchema.RegEx.Id,
optional: true, optional: true,
}, },
initiativeRoll: { initiativeRoll: {
@@ -193,11 +246,10 @@ let CreatureSchema = new SimpleSchema({
CreatureSchema.extend(ColorSchema); CreatureSchema.extend(ColorSchema);
CreatureSchema.extend(SharingSchema); CreatureSchema.extend(SharingSchema);
//@ts-expect-error attachSchema not defined
Creatures.attachSchema(CreatureSchema); Creatures.attachSchema(CreatureSchema);
export default Creatures; export default Creatures;
export { CreatureSchema }; export { CreatureSchema };
import '/imports/api/engine/actions/doAction.js';

View File

@@ -1,29 +1,29 @@
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import Creatures from '/imports/api/creature/creatures/Creatures';
import { import {
assertEditPermission as editPermission, assertEditPermission as editPermission,
assertViewPermission as viewPermission, assertViewPermission as viewPermission,
assertOwnership as ownership assertOwnership as ownership
} from '/imports/api/sharing/sharingPermissions.js'; } from '/imports/api/sharing/sharingPermissions';
function getCreature(creature, fields){ function getCreature(creature, fields) {
if (typeof creature === 'string'){ if (typeof creature === 'string') {
return Creatures.findOne(creature, {fields}); return Creatures.findOne(creature, { fields });
} else { } else {
return creature; return creature;
} }
} }
export function assertOwnership(creature, userId){ export function assertOwnership(creature, userId) {
creature = getCreature(creature, {owner: 1}); creature = getCreature(creature, { owner: 1 });
ownership(creature, userId); ownership(creature, userId);
} }
export function assertEditPermission(creature, userId) { export function assertEditPermission(creature, userId) {
creature = getCreature(creature, {owner: 1, writers: 1}); creature = getCreature(creature, { owner: 1, writers: 1 });
editPermission(creature, userId); editPermission(creature, userId);
} }
export function assertViewPermission(creature, userId) { export function assertViewPermission(creature, userId) {
creature = getCreature(creature, {owner: 1, readers:1, writers: 1, public: 1}); creature = getCreature(creature, { owner: 1, readers: 1, writers: 1, public: 1 });
viewPermission(creature, userId); viewPermission(creature, userId);
} }

View File

@@ -1,47 +1,50 @@
import BUILT_IN_TAGS from '/imports/constants/BUILT_IN_TAGS.js'; import BUILT_IN_TAGS from '/imports/constants/BUILT_IN_TAGS';
export default function defaultCharacterProperties(creatureId){ export default function defaultCharacterProperties(creatureId) {
if (!creatureId) throw 'creatureId is required'; if (!creatureId) throw 'creatureId is required';
const creatureRef = {collection: 'creatures', id: creatureId}; const creatureRef = { collection: 'creatures', id: creatureId };
let randomSrc = DDP.randomStream('defaultProperties'); let randomSrc = DDP.randomStream('defaultProperties');
const inventoryId = randomSrc.id(); const inventoryId = randomSrc.id();
const inventoryRef = {collection: 'creatureProperties', id: inventoryId};
return [ return [
{ {
type: 'propertySlot', type: 'propertySlot',
name: 'Ruleset', name: 'Ruleset',
description: {text: 'Choose a starting point for your character, this will define the basic setup of your character sheet. Without a base ruleset, your sheet will be empty.'}, description: { text: 'Choose a starting point for your character, this will define the basic setup of your character sheet. Without a base ruleset, your sheet will be empty.' },
slotTags: ['base'], slotTags: ['base'],
tags: [], tags: [],
quantityExpected: {calculation: '1'}, quantityExpected: { calculation: '1' },
hideWhenFull: true, hideWhenFull: true,
spaceLeft: 1, spaceLeft: 1,
totalFilled: 0, totalFilled: 0,
order: 0, left: 1,
parent: creatureRef, right: 2,
ancestors: [creatureRef], parentId: creatureId,
root: creatureRef,
}, { }, {
_id: inventoryId, _id: inventoryId,
type: 'folder', type: 'folder',
name: 'Inventory', name: 'Inventory',
tags: [BUILT_IN_TAGS.inventory], tags: [BUILT_IN_TAGS.inventory],
order: 1, left: 3,
parent: creatureRef, right: 8,
ancestors: [creatureRef], parentId: creatureId,
root: creatureRef,
}, { }, {
type: 'folder', type: 'folder',
name: 'Equipment', name: 'Equipment',
tags: [BUILT_IN_TAGS.equipment], tags: [BUILT_IN_TAGS.equipment],
order: 2, left: 4,
parent: inventoryRef, right: 5,
ancestors: [creatureRef, inventoryRef], parentId: inventoryId,
root: creatureRef,
}, { }, {
type: 'folder', type: 'folder',
name: 'Carried', name: 'Carried',
tags: [BUILT_IN_TAGS.carried], tags: [BUILT_IN_TAGS.carried],
order: 3, left: 6,
parent: inventoryRef, right: 7,
ancestors: [creatureRef, inventoryRef], parent: inventoryId,
root: creatureRef,
}, },
]; ];
} }

View File

@@ -1,5 +1,5 @@
import { getUserTier } from '/imports/api/users/patreon/tiers.js'; import { getUserTier } from '/imports/api/users/patreon/tiers';
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import Creatures from '/imports/api/creature/creatures/Creatures';
export default function assertHasCharactersSlots(userId) { export default function assertHasCharactersSlots(userId) {
if (characterSlotsRemaining(userId) <= 0) { if (characterSlotsRemaining(userId) <= 0) {

View File

@@ -1,9 +1,9 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import Creatures from '/imports/api/creature/creatures/Creatures';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import simpleSchemaMixin from '/imports/api/creature/mixins/simpleSchemaMixin.js'; import simpleSchemaMixin from '/imports/api/creature/mixins/simpleSchemaMixin';
const changeAllowedLibraries = new ValidatedMethod({ const changeAllowedLibraries = new ValidatedMethod({
name: 'creatures.changeAllowedLibraries', name: 'creatures.changeAllowedLibraries',

View File

@@ -0,0 +1,99 @@
import SCHEMA_VERSION from '/imports/constants/SCHEMA_VERSION';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import Creatures from '/imports/api/creature/creatures/Creatures';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import CreatureLogs from '/imports/api/creature/log/CreatureLogs';
import Experiences from '/imports/api/creature/experience/Experiences';
import { removeCreatureWork } from '/imports/api/creature/creatures/methods/removeCreature';
import assertHasCharactersSlots from '/imports/api/creature/creatures/methods/assertHasCharacterSlots';
import verifyArchiveSafety from '/imports/api/creature/archive/methods/verifyArchiveSafety';
let migrateApiCreature;
if (Meteor.isServer) {
migrateApiCreature = require('/imports/migrations/apiCreature/migrateApiCreature.js').default;
}
function importApiCreature(apiCreature, userId) {
const apiVersion = apiCreature.meta?.schemaVersion ?? 2;
const creatureId = apiCreature.creatures[0]._id;
if (SCHEMA_VERSION < apiVersion) {
throw new Meteor.Error('Incompatible',
'The creature on the remote server is from a newer version of DiceCloud')
}
// Migrate and verify the archive meets the current schema
migrateApiCreature(apiCreature);
// Asset that the api creature is (mildly) safe
verifyArchiveSafety({
creature: apiCreature.creatures[0],
properties: apiCreature.creatureProperties ?? [],
experiences: apiCreature.experiences ?? [],
logs: apiCreature.logs ?? [],
});
// Don't upload creatures twice
const existingCreature = Creatures.findOne(apiCreature.creatures[0]._id, {
fields: { _id: 1 }
});
if (existingCreature) throw new Meteor.Error('Already exists',
'The creature you are trying to import already exists in this database.')
// Ensure the user owns the restored creature
apiCreature.creatures[0].owner = userId;
// Ensure there is only 1 creature being imported
if (apiCreature.creatures.length !== 1) {
throw new Meteor.Error('invalid-import',
'One and only one creature must be imported at a time'
)
}
// Insert the creature sub documents
// They still have their original _id's
Creatures.insert(apiCreature.creatures[0]);
try {
// Add all the properties
if (apiCreature.creatureProperties && apiCreature.creatureProperties.length) {
CreatureProperties.batchInsert(apiCreature.creatureProperties);
}
if (apiCreature.experiences && apiCreature.experiences.length) {
Experiences.batchInsert(apiCreature.experiences);
}
if (apiCreature.logs && apiCreature.logs.length) {
CreatureLogs.batchInsert(apiCreature.logs);
}
} catch (e) {
// If the above fails, delete the inserted creature
removeCreatureWork(creatureId);
throw e;
}
return creatureId;
}
const importCharacterFromDiceCloudInstance = new ValidatedMethod({
name: 'Creatures.methods.importFromInstance',
validate: null,
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 10,
timeInterval: 5000,
},
async run({ characterData }) {
if (Meteor.settings.public.disallowCreatureApiImport) throw new Meteor.Error('not-allowed',
'This instance of DiceCloud has disallowed creature imports')
// fetch the file
if (!characterData) {
throw new Meteor.Error('no-input',
'No character data was provided');
}
assertHasCharactersSlots(this.userId);
if (Meteor.isServer) {
return importApiCreature(characterData, this.userId)
}
},
});
export default importCharacterFromDiceCloudInstance;

View File

@@ -1,5 +1,5 @@
import '/imports/api/creature/creatures/methods/insertCreature.js'; import '/imports/api/creature/creatures/methods/changeAllowedLibraries';
import '/imports/api/creature/creatures/methods/removeCreature.js'; import '/imports/api/creature/creatures/methods/importCharacterFromDiceCloudInstance.js';
import '/imports/api/creature/creatures/methods/restCreature.js'; import '/imports/api/creature/creatures/methods/insertCreature';
import '/imports/api/creature/creatures/methods/updateCreature.js'; import '/imports/api/creature/creatures/methods/removeCreature';
import '/imports/api/creature/creatures/methods/changeAllowedLibraries.js'; import '/imports/api/creature/creatures/methods/updateCreature';

View File

@@ -1,21 +1,21 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import simpleSchemaMixin from '/imports/api/creature/mixins/simpleSchemaMixin.js'; import simpleSchemaMixin from '/imports/api/creature/mixins/simpleSchemaMixin';
import Creatures, { CreatureSchema } from '/imports/api/creature/creatures/Creatures.js'; import Creatures, { CreatureSchema } from '/imports/api/creature/creatures/Creatures';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import defaultCharacterProperties from '/imports/api/creature/creatures/defaultCharacterProperties.js'; import defaultCharacterProperties from '/imports/api/creature/creatures/defaultCharacterProperties';
import insertPropertyFromLibraryNode from '/imports/api/creature/creatureProperties/methods/insertPropertyFromLibraryNode.js'; import insertPropertyFromLibraryNode from '/imports/api/creature/creatureProperties/methods/insertPropertyFromLibraryNode';
import assertHasCharactersSlots from '/imports/api/creature/creatures/methods/assertHasCharacterSlots.js'; import assertHasCharactersSlots from '/imports/api/creature/creatures/methods/assertHasCharacterSlots';
import getSlotFillFilter from '/imports/api/creature/creatureProperties/methods/getSlotFillFilter.js'; import getSlotFillFilter from '/imports/api/creature/creatureProperties/methods/getSlotFillFilter';
import getCreatureLibraryIds from '/imports/api/library/getCreatureLibraryIds.js'; import getCreatureLibraryIds from '/imports/api/library/getCreatureLibraryIds';
import LibraryNodes from '/imports/api/library/LibraryNodes.js'; import LibraryNodes from '/imports/api/library/LibraryNodes';
import { insertExperienceForCreature } from '/imports/api/creature/experience/Experiences.js'; import { insertExperienceForCreature } from '/imports/api/creature/experience/Experiences';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
const insertCreature = new ValidatedMethod({ const insertCreature = new ValidatedMethod({
name: 'creatures.insertCreature', name: 'creatures.insertCreature',
mixins: [RateLimiterMixin, simpleSchemaMixin], mixins: [RateLimiterMixin, simpleSchemaMixin],
schema: CreatureSchema.pick( validate: CreatureSchema.pick(
'name', 'name',
'gender', 'gender',
'alignment', 'alignment',
@@ -26,7 +26,7 @@ const insertCreature = new ValidatedMethod({
type: SimpleSchema.Integer, type: SimpleSchema.Integer,
min: 0, min: 0,
}, },
}), }).validator(),
rateLimit: { rateLimit: {
numRequests: 5, numRequests: 5,
timeInterval: 5000, timeInterval: 5000,
@@ -48,8 +48,13 @@ const insertCreature = new ValidatedMethod({
name, name,
gender, gender,
alignment, alignment,
type: 'pc',
allowedLibraries, allowedLibraries,
allowedLibraryCollections, allowedLibraryCollections,
settings: {},
readers: [],
writers: [],
public: false,
}); });
// Insert experience to get character to starting level // Insert experience to get character to starting level
@@ -61,7 +66,6 @@ const insertCreature = new ValidatedMethod({
creatureId creatureId
}, },
creatureId, creatureId,
userId,
}); });
} }
@@ -96,7 +100,6 @@ function insertDefaultRuleset(creatureId, baseId, userId, slot) {
insertPropertyFromLibraryNode.call({ insertPropertyFromLibraryNode.call({
nodeIds: [ruleset._id], nodeIds: [ruleset._id],
parentRef: { id: baseId, collection: 'creatureProperties' }, parentRef: { id: baseId, collection: 'creatureProperties' },
order: 0.5,
}); });
} }
} }

View File

@@ -1,18 +1,19 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import { assertOwnership } from '/imports/api/creature/creatures/creaturePermissions.js'; import { assertOwnership } from '/imports/api/creature/creatures/creaturePermissions';
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import Creatures from '/imports/api/creature/creatures/Creatures';
import CreatureVariables from '/imports/api/creature/creatures/CreatureVariables.js'; import CreatureVariables from '/imports/api/creature/creatures/CreatureVariables';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import CreatureLogs from '/imports/api/creature/log/CreatureLogs.js'; import CreatureLogs from '/imports/api/creature/log/CreatureLogs';
import Experiences from '/imports/api/creature/experience/Experiences.js'; import Experiences from '/imports/api/creature/experience/Experiences';
import { getFilter } from '/imports/api/parenting/parentingFunctions';
function removeRelatedDocuments(creatureId){ function removeRelatedDocuments(creatureId) {
CreatureVariables.remove({_creatureId: creatureId}); CreatureVariables.remove({ _creatureId: creatureId });
CreatureProperties.remove({'ancestors.id': creatureId}); CreatureProperties.remove(getFilter.descendantsOfRoot(creatureId));
CreatureLogs.remove({creatureId}); CreatureLogs.remove({ creatureId });
Experiences.remove({creatureId}); Experiences.remove({ creatureId });
} }
const removeCreature = new ValidatedMethod({ const removeCreature = new ValidatedMethod({
@@ -28,14 +29,14 @@ const removeCreature = new ValidatedMethod({
numRequests: 5, numRequests: 5,
timeInterval: 5000, timeInterval: 5000,
}, },
run({charId}) { run({ charId }) {
assertOwnership(charId, this.userId) assertOwnership(charId, this.userId)
this.unblock(); this.unblock();
removeCreatureWork(charId) removeCreatureWork(charId)
}, },
}); });
export function removeCreatureWork(creatureId){ export function removeCreatureWork(creatureId) {
Creatures.remove(creatureId); Creatures.remove(creatureId);
removeRelatedDocuments(creatureId); removeRelatedDocuments(creatureId);
} }

View File

@@ -1,180 +0,0 @@
import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties.js';
import { assertEditPermission } from '/imports/api/creature/creatures/creaturePermissions.js';
import { union } from 'lodash';
import ActionContext from '/imports/api/engine/actions/ActionContext.js';
import { applyTriggers } from '/imports/api/engine/actions/applyTriggers.js';
const restCreature = new ValidatedMethod({
name: 'creature.methods.rest',
validate: new SimpleSchema({
creatureId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
restType: {
type: String,
allowedValues: ['shortRest', 'longRest'],
},
}).validator(),
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 5,
timeInterval: 5000,
},
run({ creatureId, restType }) {
// Get action context
const actionContext = new ActionContext(creatureId, [creatureId], this);
// Check permissions
assertEditPermission(actionContext.creature, this.userId);
// Join, sort, and apply before triggers
const beforeTriggers = union(
actionContext.triggers.anyRest?.before, actionContext.triggers[restType]?.before
).sort((a, b) => a.order - b.order);
applyTriggers(beforeTriggers, null, actionContext);
// Rest
actionContext.addLog({
name: restType === 'shortRest' ? 'Short rest' : 'Long rest',
});
doRestWork(restType, actionContext);
// Join, sort, and apply after triggers
const afterTriggers = union(
actionContext.triggers.anyRest?.after, actionContext.triggers[restType]?.after
).sort((a, b) => a.order - b.order);
applyTriggers(afterTriggers, null, actionContext);
// Insert log
actionContext.writeLog();
},
});
function doRestWork(restType, actionContext) {
const creatureId = actionContext.creature._id;
// Long rests reset short rest properties as well
let resetFilter;
if (restType === 'shortRest') {
resetFilter = 'shortRest'
} else {
resetFilter = { $in: ['shortRest', 'longRest'] }
}
resetProperties(creatureId, resetFilter, actionContext);
// Reset half hit dice on a long rest, starting with the highest dice
if (restType === 'longRest') {
resetHitDice(creatureId, actionContext);
}
}
export function resetProperties(creatureId, resetFilter, actionContext) {
// Only apply to active properties
const filter = {
'ancestors.id': creatureId,
reset: resetFilter,
removed: { $ne: true },
inactive: { $ne: true },
};
// update all attribute's damage
const attributeFilter = {
...filter,
type: 'attribute',
damage: { $ne: 0 },
}
CreatureProperties.find(attributeFilter, {
fields: { name: 1, damage: 1 }
}).forEach(prop => {
actionContext.addLog({
name: prop.name,
value: prop.damage >= 0 ? `Restored ${prop.damage}` : `Removed ${-prop.damage}`
});
});
CreatureProperties.update(attributeFilter, {
$set: {
damage: 0,
dirty: true,
}
}, {
selector: { type: 'attribute' },
multi: true,
});
// Update all action-like properties' usesUsed
const actionFilter = {
...filter,
type: {
$in: ['action', 'spell']
},
usesUsed: { $ne: 0 },
};
CreatureProperties.find(actionFilter, {
fields: { name: 1, usesUsed: 1 }
}).forEach(prop => {
actionContext.addLog({
name: prop.name,
value: prop.usesUsed >= 0 ? `Restored ${prop.usesUsed} uses` : `Removed ${-prop.usesUsed} uses`
});
});
CreatureProperties.update(actionFilter, {
$set: {
usesUsed: 0,
dirty: true,
}
}, {
selector: { type: 'action' },
multi: true,
});
}
function resetHitDice(creatureId, actionContext) {
let hitDice = CreatureProperties.find({
'ancestors.id': creatureId,
type: 'attribute',
attributeType: 'hitDice',
removed: { $ne: true },
inactive: { $ne: true },
}, {
fields: {
name: 1,
hitDiceSize: 1,
damage: 1,
total: 1,
}
}).fetch();
// Use a collator to do sorting in natural order
let collator = new Intl.Collator('en', {
numeric: true, sensitivity: 'base'
});
// Get the hit dice in decending order of hitDiceSize
let compare = (a, b) => collator.compare(b.hitDiceSize, a.hitDiceSize)
hitDice.sort(compare);
// Get the total number of hit dice that can be recovered this rest
let totalHd = hitDice.reduce((sum, hd) => sum + (hd.total || 0), 0);
let resetMultiplier = actionContext.creature.settings.hitDiceResetMultiplier || 0.5;
let recoverableHd = Math.max(Math.floor(totalHd * resetMultiplier), 1);
// recover each hit dice in turn until the recoverable amount is used up
let amountToRecover, resultingDamage;
hitDice.forEach(hd => {
if (!recoverableHd) return;
amountToRecover = Math.min(recoverableHd, hd.damage || 0);
if (!amountToRecover) return;
recoverableHd -= amountToRecover;
resultingDamage = hd.damage - amountToRecover;
actionContext.addLog({
name: hd.name,
value: amountToRecover >= 0 ? `Restored ${amountToRecover} hit dice` : `Removed ${-amountToRecover} hit dice`
});
CreatureProperties.update(hd._id, {
$set: {
damage: resultingDamage,
dirty: true,
}
}, {
selector: { type: 'attribute' },
});
});
}
export default restCreature;

View File

@@ -1,7 +1,7 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import Creatures from '/imports/api/creature/creatures/Creatures';
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertEditPermission } from '/imports/api/sharing/sharingPermissions';
const updateCreature = new ValidatedMethod({ const updateCreature = new ValidatedMethod({
name: 'creatures.update', name: 'creatures.update',

View File

@@ -1,9 +1,9 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import { assertEditPermission } from '/imports/api/creature/creatures/creaturePermissions.js'; import { assertEditPermission } from '/imports/api/creature/creatures/creaturePermissions';
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import Creatures from '/imports/api/creature/creatures/Creatures';
import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS.js'; import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS';
let Experiences = new Mongo.Collection('experiences'); let Experiences = new Mongo.Collection('experiences');
@@ -26,7 +26,7 @@ let ExperienceSchema = new SimpleSchema({
min: 0, min: 0,
index: 1, index: 1,
}, },
// The real-world date that it occured, usually sorted by date // The real-world date that it occurred, usually sorted by date
date: { date: {
type: Date, type: Date,
autoValue: function () { autoValue: function () {
@@ -93,7 +93,7 @@ const insertExperience = new ValidatedMethod({
let insertedIds = []; let insertedIds = [];
creatureIds.forEach(creatureId => { creatureIds.forEach(creatureId => {
assertEditPermission(creatureId, userId); assertEditPermission(creatureId, userId);
let id = insertExperienceForCreature({ experience, creatureId, userId }); let id = insertExperienceForCreature({ experience, creatureId });
insertedIds.push(id); insertedIds.push(id);
}); });
return insertedIds; return insertedIds;

View File

@@ -1,5 +1,5 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS.js'; import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS';
let ExperienceSchema = new SimpleSchema({ let ExperienceSchema = new SimpleSchema({
title: { title: {

View File

@@ -1,17 +1,19 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import Creatures from '/imports/api/creature/creatures/Creatures.js'; import Creatures from '/imports/api/creature/creatures/Creatures';
import CreatureVariables from '/imports/api/creature/creatures/CreatureVariables.js'; import CreatureVariables from '/imports/api/creature/creatures/CreatureVariables';
import LogContentSchema from '/imports/api/creature/log/LogContentSchema.js'; import LogContentSchema from '/imports/api/creature/log/LogContentSchema';
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin'; import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import { assertEditPermission } from '/imports/api/creature/creatures/creaturePermissions.js'; import { assertEditPermission } from '/imports/api/creature/creatures/creaturePermissions';
import { parse, prettifyParseError } from '/imports/parser/parser.js'; import { parse, prettifyParseError } from '/imports/parser/parser';
import resolve, { toString } from '/imports/parser/resolve.js'; import resolve from '/imports/parser/resolve';
import toString from '/imports/parser/toString';
import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS';
const PER_CREATURE_LOG_LIMIT = 100; const PER_CREATURE_LOG_LIMIT = 100;
import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS.js';
if (Meteor.isServer) { if (Meteor.isServer) {
var sendWebhookAsCreature = require('/imports/server/discord/sendWebhook.js').sendWebhookAsCreature; var sendWebhookAsCreature = require('/imports/server/discord/sendWebhook').sendWebhookAsCreature;
} }
let CreatureLogs = new Mongo.Collection('creatureLogs'); let CreatureLogs = new Mongo.Collection('creatureLogs');
@@ -36,9 +38,15 @@ let CreatureLogSchema = new SimpleSchema({
}, },
index: 1, index: 1,
}, },
// The acting creature initiating the logged events
creatureId: { creatureId: {
type: String, type: String,
regEx: SimpleSchema.RegEx.Id, index: 1,
},
// The tabletops this log is associated with
tabletopId: {
type: String,
optional: true,
index: 1, index: 1,
}, },
creatureName: { creatureName: {
@@ -50,11 +58,17 @@ let CreatureLogSchema = new SimpleSchema({
CreatureLogs.attachSchema(CreatureLogSchema); CreatureLogs.attachSchema(CreatureLogSchema);
function removeOldLogs(creatureId) { function removeOldLogs({ creatureId, tabletopId }) {
let filter;
if (creatureId && tabletopId || (!creatureId && !tabletopId)) {
throw Error('Provide either creatureId or tabletopId')
} else if (creatureId) {
filter = { creatureId };
} else if (tabletopId) {
filter = { tabletopId }
}
// Find the first log that is over the limit // Find the first log that is over the limit
let firstExpiredLog = CreatureLogs.find({ let firstExpiredLog = CreatureLogs.find(filter, {
creatureId
}, {
sort: { date: -1 }, sort: { date: -1 },
skip: PER_CREATURE_LOG_LIMIT, skip: PER_CREATURE_LOG_LIMIT,
}); });
@@ -70,10 +84,21 @@ function logToMessageData(log) {
let embed = { let embed = {
fields: [], fields: [],
}; };
log.content.forEach(field => { log.content.forEach((field, index) => {
// Empty character for blank names
if (!field.name) field.name = '\u200b'; if (!field.name) field.name = '\u200b';
if (!field.value) field.value = '\u200b'; if (!field.value) field.value = '\u200b';
embed.fields.push(field); // Enforce Discord field character limits
if (field.name?.length > 256) {
field.name = field.name.substring(0, 255);
}
if (field.value?.length > 1024) {
field.value = field.value.substring(0, 1024 - 3) + '...';
}
// Enforce Discord 25 field limit
if (index < 25) {
embed.fields.push(field);
}
}); });
return { embeds: [embed] }; return { embeds: [embed] };
} }
@@ -107,6 +132,7 @@ const insertCreatureLog = new ValidatedMethod({
'settings.discordWebhook': 1, 'settings.discordWebhook': 1,
name: 1, name: 1,
avatarPicture: 1, avatarPicture: 1,
tabletop: 1,
} }
}); });
assertEditPermission(creature, this.userId); assertEditPermission(creature, this.userId);
@@ -122,13 +148,27 @@ export function insertCreatureLogWork({ log, creature, method }) {
log = { content: [{ value: log }] }; log = { content: [{ value: log }] };
} }
if (!log.content?.length) return; if (!log.content?.length) return;
// Truncate the string lengths to fit the log content schema
log.content.forEach((logItem) => {
if (logItem.value?.length > STORAGE_LIMITS.summary) {
logItem.value = logItem.value.substring(0, STORAGE_LIMITS.summary - 3) + '...';
}
});
log.date = new Date(); log.date = new Date();
if (creature && creature.tabletop) log.tabletopId = creature.tabletop;
// Insert it // Insert it
let id = CreatureLogs.insert(log); let id = CreatureLogs.insert(log);
if (Meteor.isServer) { if (Meteor.isServer) {
method?.unblock(); method?.unblock();
removeOldLogs(creature._id); if (creature) {
logWebhook({ log, creature }); logWebhook({ log, creature });
}
if (log.tabletopId) {
removeOldLogs({ tabletopId: log.tabletopId });
} else {
removeOldLogs({ creatureId: creature._id });
}
} }
return id; return id;
} }
@@ -153,21 +193,28 @@ const logRoll = new ValidatedMethod({
creatureId: { creatureId: {
type: String, type: String,
regEx: SimpleSchema.RegEx.Id, regEx: SimpleSchema.RegEx.Id,
optional: true,
}, },
}).validator(), }).validator(),
run({ roll, creatureId }) { async run({ roll, creatureId }) {
const creature = Creatures.findOne(creatureId, { if (!creatureId) throw new Meteor.Error('no-id',
fields: { 'A creature id must be given'
readers: 1, );
writers: 1, let creature;
owner: 1, if (creatureId) {
'settings.discordWebhook': 1, creature = Creatures.findOne(creatureId, {
name: 1, fields: {
avatarPicture: 1, readers: 1,
} writers: 1,
}); owner: 1,
assertEditPermission(creature, this.userId); 'settings.discordWebhook': 1,
const variables = CreatureVariables.findOne({ _creatureId: creatureId }); name: 1,
avatarPicture: 1,
}
});
assertEditPermission(creature, this.userId);
}
const variables = CreatureVariables.findOne({ _creatureId: creatureId }) || {};
let logContent = [] let logContent = []
let parsedResult = undefined; let parsedResult = undefined;
try { try {
@@ -180,7 +227,7 @@ const logRoll = new ValidatedMethod({
let { let {
result: compiled, result: compiled,
context context
} = resolve('compile', parsedResult, variables); } = await resolve('compile', parsedResult, variables);
const compiledString = toString(compiled); const compiledString = toString(compiled);
if (!equalIgnoringWhitespace(compiledString, roll)) logContent.push({ if (!equalIgnoringWhitespace(compiledString, roll)) logContent.push({
value: roll value: roll
@@ -188,12 +235,12 @@ const logRoll = new ValidatedMethod({
logContent.push({ logContent.push({
value: compiledString value: compiledString
}); });
let { result: rolled } = resolve('roll', compiled, variables, context); let { result: rolled } = await resolve('roll', compiled, variables, context);
let rolledString = toString(rolled); let rolledString = toString(rolled);
if (rolledString !== compiledString) logContent.push({ if (rolledString !== compiledString) logContent.push({
value: rolledString value: rolledString
}); });
let { result } = resolve('reduce', rolled, variables, context); let { result } = await resolve('reduce', rolled, variables, context);
let resultString = toString(result); let resultString = toString(result);
if (resultString !== rolledString) logContent.push({ if (resultString !== rolledString) logContent.push({
value: resultString value: resultString

View File

@@ -1,7 +1,18 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js'; import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema';
import RollDetailsSchema from '/imports/api/properties/subSchemas/RollDetailsSchema.js'; import RollDetailsSchema from '/imports/api/properties/subSchemas/RollDetailsSchema';
import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS.js'; import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS';
export interface LogContent {
name?: string
value?: string
inline?: boolean
context?: {
errors: any[]
rolls: any[]
doubleRolls?: boolean
}
}
let LogContentSchema = new SimpleSchema({ let LogContentSchema = new SimpleSchema({
// The name of the field, included in discord webhook message // The name of the field, included in discord webhook message
@@ -22,11 +33,16 @@ let LogContentSchema = new SimpleSchema({
type: Boolean, type: Boolean,
optional: true, optional: true,
}, },
// This log entry was silenced
silenced: {
type: Boolean,
optional: true,
},
context: { context: {
type: Object, type: Object,
optional: true, optional: true,
}, },
'context.errors':{ 'context.errors': {
type: Array, type: Array,
defaultValue: [], defaultValue: [],
maxCount: STORAGE_LIMITS.errorCount, maxCount: STORAGE_LIMITS.errorCount,
@@ -46,6 +62,13 @@ let LogContentSchema = new SimpleSchema({
type: Boolean, type: Boolean,
optional: true, optional: true,
}, },
targetIds: {
type: Array,
optional: true,
},
'targetIds.$': {
type: String,
}
}); });
export default LogContentSchema; export default LogContentSchema;

View File

@@ -2,7 +2,7 @@ import {
assertEditPermission, assertEditPermission,
assertViewPermission, assertViewPermission,
assertOwnership, assertOwnership,
} from '/imports/api/creature/creatures/creaturePermissions.js'; } from '/imports/api/creature/creatures/creaturePermissions';
// Checks if the method has permission to run on the document. If the document // Checks if the method has permission to run on the document. If the document
// has a charId, that creature is checked, otherwise if it has an _id and the // has a charId, that creature is checked, otherwise if it has an _id and the
@@ -13,36 +13,36 @@ import {
// Because this mixin injects the charId into argument objects that don't // Because this mixin injects the charId into argument objects that don't
// already contain it, it should always come last in the mixin list, so that it // already contain it, it should always come last in the mixin list, so that it
// the outermost wrapper of the run function // the outermost wrapper of the run function
export default function creaturePermissionMixin(methodOptions){ export default function creaturePermissionMixin(methodOptions) {
let assertPermission; let assertPermission;
if (methodOptions.permission === 'owner'){ if (methodOptions.permission === 'owner') {
assertPermission = assertOwnership; assertPermission = assertOwnership;
} else if (methodOptions.permission === 'edit'){ } else if (methodOptions.permission === 'edit') {
assertPermission = assertEditPermission; assertPermission = assertEditPermission;
} else if (methodOptions.permission === 'view'){ } else if (methodOptions.permission === 'view') {
assertPermission = assertViewPermission; assertPermission = assertViewPermission;
} else { } else {
throw "`permission` missing in method options"; throw "`permission` missing in method options";
} }
let getCharId; let getCharId;
if (methodOptions.getCharId){ if (methodOptions.getCharId) {
getCharId = methodOptions.getCharId; getCharId = methodOptions.getCharId;
} else if (methodOptions.collection) { } else if (methodOptions.collection) {
getCharId = function({_id}){ getCharId = function ({ _id }) {
return methodOptions.collection.findOne(_id, { return methodOptions.collection.findOne(_id, {
fields: {charId: 1} fields: { charId: 1 }
}).charId; }).charId;
}; };
} else { } else {
getCharId = function(){ getCharId = function () {
throw "`getCharId` or `collection` missing in method options," + throw "`getCharId` or `collection` missing in method options," +
" or {charId} missing in call"; " or {charId} missing in call";
}; };
} }
let runFunc = methodOptions.run; let runFunc = methodOptions.run;
methodOptions.run = function(doc, ...rest){ methodOptions.run = function (doc, ...rest) {
// Store the charId on the doc for other mixins if it had to be fetched // Store the charId on the doc for other mixins if it had to be fetched
doc.charId = doc.charId || getCharId.apply(this, arguments); doc.charId = doc.charId || getCharId.apply(this, arguments);
assertPermission(doc.charId, this.userId); assertPermission(doc.charId, this.userId);

View File

@@ -1,59 +0,0 @@
import {
updateChildren,
updateDescendants,
} from '/imports/api/parenting/parenting.js';
import { inheritedFields } from '/imports/api/parenting/ChildSchema.js';
import MONGO_OPERATORS from '/imports/constants/MONGO_OPERATORS.js';
// This mixin can be safely applied to all update methods which are validated
// with the updateSchemaMixin. It will propagate updates to fields which
// are inherited and normalised on the parent or ancestor docs
// It should have neglible performance impact for updates that aren't inherited
function propagateInheritanceUpdate({_id, update}){
let childModifier = {};
let descendantModifier = {};
// For each operator
for (let operator of MONGO_OPERATORS){
// If the operator is in the update, for each field
if (update[operator]) for (let field in update[operator]){
// Get the top level field that was actually modified
const indexOfDot = field.indexOf('.');
let modifiedField;
if (indexOfDot !== -1) {
modifiedField = field.substring(0, indexOfDot);
} else {
modifiedField = field;
}
// If that field is updated and inherited
if (inheritedFields.has(modifiedField)){
// Perform the same update on the descendants
if (!childModifier[operator]) childModifier[operator] = {};
if (!descendantModifier[operator]) descendantModifier[operator] = {};
childModifier[operator][`parent.${field}`] = update[operator][field];
descendantModifier[operator][`ancestors.$.${field}`] = update[operator][field];
}
}
}
// Update the parent object of its children
updateChildren({
parentId: _id,
modifier: childModifier,
});
// Update the ancestors object of its descendants
updateDescendants({
ancestorId: _id,
modifier: descendantModifier,
});
}
export default function propagateInheritanceUpdateMixin(methodOptions){
let runFunc = methodOptions.run;
methodOptions.run = function({_id, update}){
const result = runFunc.apply(this, arguments);
propagateInheritanceUpdate({_id, update});
return result;
};
return methodOptions;
}

View File

@@ -1,8 +1,8 @@
import computeCreature from '/imports/api/engine/computeCreature.js'; import computeCreature from '/imports/api/engine/computeCreature';
export default function recomputeCreatureMixin(methodOptions){ export default function recomputeCreatureMixin(methodOptions) {
let runFunc = methodOptions.run; let runFunc = methodOptions.run;
methodOptions.run = function({charId}){ methodOptions.run = function ({ charId }) {
const result = runFunc.apply(this, arguments); const result = runFunc.apply(this, arguments);
if ( if (
methodOptions.skipRecompute && methodOptions.skipRecompute &&

View File

@@ -1,27 +0,0 @@
import SimpleSchema from 'simpl-schema';
import { setDocToLastOrder } from '/imports/api/parenting/order.js';
export function setDocToLastMixin(methodOptions){
// Make sure the doc has a charId
// This mixin should come before simpleSchemaMixin so that it can extend the
// schema before it is turned into a validate function
if (methodOptions.validate){
throw new Meteor.Error(`setDocToLastMixin should come before simpleSchemaMixin`);
}
methodOptions.schema = new SimpleSchema({
charId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
}).extend(methodOptions.schema);
let collection = methodOptions.collection;
if (!collection){
throw new Meteor.Error("`collection` required in method options for setDocToLastMixin");
}
let runFunc = methodOptions.run;
methodOptions.run = function(doc){
setDocToLastOrder({collection, doc});
return runFunc.apply(this, arguments);
};
return methodOptions;
}

View File

@@ -1,3 +0,0 @@
if (Meteor.isServer) throw 'Client side only collection, don\'t import on server';
const Docs = new Mongo.Collection('docs');
export default Docs;

View File

@@ -0,0 +1,287 @@
import { Meteor } from 'meteor/meteor';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
import SimpleSchema from 'simpl-schema';
import { softRemove } from '/imports/api/parenting/softRemove';
import SoftRemovableSchema from '/imports/api/parenting/SoftRemovableSchema';
import { storedIconsSchema } from '/imports/api/icons/Icons';
import '/imports/api/library/methods/index';
import STORAGE_LIMITS from '/imports/constants/STORAGE_LIMITS';
import { restore } from '/imports/api/parenting/softRemove';
import { getFilter, rebuildNestedSets, moveDocWithinRoot } from '/imports/api/parenting/parentingFunctions';
import ChildSchema, { TreeDoc } from '/imports/api/parenting/ChildSchema';
// Give the docs a common root, so they can share parenting logic
export const DOC_ROOT_ID = 'DDDDDDDDDDDDDDDDD'
type Doc = {
_id: string,
name: string,
urlName: string,
href: string,
description?: string,
published?: true,
icon?: {
name: string,
shape: string,
},
} & TreeDoc;
const Docs: Mongo.Collection<Doc> & {
getJsonDocs?: () => string
} = new Mongo.Collection<Doc>('docs');
const DocSchema = new SimpleSchema({
_id: {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
name: {
type: String,
max: STORAGE_LIMITS.description,
},
urlName: {
type: String,
regEx: /[a-z]+(?:[a-z]|-)+/,
min: 2,
max: STORAGE_LIMITS.variableName,
},
href: {
type: String,
},
description: {
type: String,
optional: true,
},
published: {
type: Boolean,
optional: true,
},
icon: {
type: storedIconsSchema,
optional: true,
max: STORAGE_LIMITS.icon,
},
});
const schema = new SimpleSchema({});
schema.extend(DocSchema);
schema.extend(ChildSchema);
schema.extend(SoftRemovableSchema);
// @ts-expect-error No attach schema in types
Docs.attachSchema(schema);
function assertDocsEditPermission(userId) {
if (!userId || typeof userId !== 'string') throw new Meteor.Error('No user id provided');
const user = Meteor.users.findOne(userId);
if (!user) throw new Meteor.Error('User does not exist');
if (!user?.roles?.includes?.('docsWriter')) throw ('Permission denied')
}
function getDocLink(doc: Doc, urlName?: string) {
if (!urlName) urlName = doc.urlName;
const address = ['/docs'];
const ancestorDocs = Docs.find(getFilter.ancestors(doc));
ancestorDocs?.forEach(a => {
address.push(a.urlName);
});
address.push(urlName);
return address.join('/');
}
// Add a means of seeding new servers with documentation
if (Meteor.isClient) {
Docs.getJsonDocs = function () {
return JSON.stringify(Docs.find({}).fetch(), null, 2);
}
} else if (Meteor.isServer) {
Meteor.startup(() => {
if (!Docs.findOne()) {
console.log('No docs found, filling documentation with defaults');
Assets.getText('docs/defaultDocs.json', (error, string) => {
const docs = JSON.parse(string)
docs.forEach(doc => Docs.insert(doc));
rebuildNestedSets(Docs, DOC_ROOT_ID);
});
}
});
}
const insertDoc = new ValidatedMethod({
name: 'docs.insert',
validate: null,
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 5,
timeInterval: 5000,
},
run({ doc, parentId }) {
delete doc._id;
assertDocsEditPermission(this.userId);
doc.parentId = parentId;
doc.root = {
collection: 'docs',
id: DOC_ROOT_ID,
};
const lastOrder = Docs.find({}, { sort: { left: -1 }, limit: 1 }).fetch()[0]?.left || 0;
doc.urlName = 'new-doc-' + (lastOrder + 1);
doc.href = getDocLink(doc);
if (Docs.findOne({ href: doc.href })) {
throw new Meteor.Error('Link collision', 'A document with the same URL already exists');
}
const docId = Docs.insert(doc);
rebuildNestedSets(Docs, DOC_ROOT_ID);
return docId;
},
});
const updateDoc = new ValidatedMethod({
name: 'docs.update',
validate({ _id, path }) {
if (!_id) return false;
// We cannot change these fields with a simple update
switch (path[0]) {
case '_is':
return false;
}
},
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 5,
timeInterval: 5000,
},
run({ _id, path, value }) {
assertDocsEditPermission(this.userId);
const pathString = path.join('.');
let modifier;
// unset empty values
if (value === null || value === undefined) {
modifier = { $unset: { [pathString]: 1 } };
} else {
modifier = { $set: { [pathString]: value } };
}
if (pathString === 'urlName') {
const doc = Docs.findOne(_id);
if (!doc) throw new Meteor.Error('Not Found', 'The document you are trying to edit was not found');
const newLink = getDocLink(doc, value);
if (Docs.findOne({ href: newLink })) {
throw new Meteor.Error('Link collision', 'A document with the same URL already exists');
}
modifier.$set = modifier.$set || {};
modifier.$set.href = newLink;
}
const updates = Docs.update(_id, modifier);
rebuildNestedSets(Docs, DOC_ROOT_ID);
return updates;
},
});
const pushToDoc = new ValidatedMethod({
name: 'docs.push',
validate: null,
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 5,
timeInterval: 5000,
},
run({ _id, path, value }) {
assertDocsEditPermission(this.userId);
return Docs.update(_id, {
$push: { [path.join('.')]: value },
});
}
});
const pullFromDoc = new ValidatedMethod({
name: 'docs.pull',
validate: null,
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 5,
timeInterval: 5000,
},
run({ _id, path, itemId }) {
assertDocsEditPermission(this.userId);
return Docs.update(_id, {
$pull: { [path.join('.')]: { _id: itemId } },
});
}
});
const softRemoveDoc = new ValidatedMethod({
name: 'docs.softRemove',
validate: new SimpleSchema({
_id: SimpleSchema.RegEx.Id
}).validator(),
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 5,
timeInterval: 5000,
},
run({ _id }) {
assertDocsEditPermission(this.userId);
softRemove(Docs, _id);
rebuildNestedSets(Docs, DOC_ROOT_ID);
}
});
const restoreDoc = new ValidatedMethod({
name: 'docs.restore',
validate: new SimpleSchema({
_id: SimpleSchema.RegEx.Id
}).validator(),
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 5,
timeInterval: 5000,
},
run({ _id }) {
assertDocsEditPermission(this.userId);
restore('docs', _id);
rebuildNestedSets(Docs, DOC_ROOT_ID);
}
});
const organizeDoc = new ValidatedMethod({
name: 'docs.organizeDoc',
validate: new SimpleSchema({
docId: String,
newPosition: Number,
skipClient: {
type: Boolean,
optional: true,
}
}).validator(),
mixins: [RateLimiterMixin],
rateLimit: {
numRequests: 5,
timeInterval: 5000,
},
async run({ docId, newPosition, skipClient }: { docId: string, newPosition: number, skipClient?: boolean }) {
if (skipClient && this.isSimulation) {
return;
}
assertDocsEditPermission(this.userId);
const doc = Docs.findOne(docId);
if (!doc) throw new Meteor.Error('not found', 'The doc you are moving was not found');
// Move the doc
await moveDocWithinRoot(doc, Docs, newPosition);
},
});
export {
DocSchema,
insertDoc,
updateDoc,
pushToDoc,
pullFromDoc,
softRemoveDoc,
restoreDoc,
organizeDoc,
};
export default Docs;

View File

@@ -0,0 +1,448 @@
import { assert } from 'chai';
import '/imports/api/simpleSchemaConfig.js';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { propsFromForest } from '/imports/api/properties/tests/propTestBuilder.testFn';
import Creatures from '/imports/api/creature/creatures/Creatures';
import computeCreature from '/imports/api/engine/computeCreature';
import { loadCreature } from '/imports/api/engine/loadCreatures';
import EngineActions, { EngineAction } from '/imports/api/engine/action/EngineActions';
import applyAction from '/imports/api/engine/action/functions/applyAction';
import { LogContent, Removal, Update } from '/imports/api/engine/action/tasks/TaskResult';
import inputProvider from './functions/userInput/inputProviderForTests.testFn';
import { removeAllCreaturesAndProps } from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const creatureId = Random.id();
const targetId = Random.id();
describe('Interrupt action system', function () {
const dummySubscription = Tracker.autorun(() => undefined)
this.timeout(8000);
before(async function () {
// Remove old data
await removeAllCreaturesAndProps();
// Add creatures
await Promise.all([
Creatures.insertAsync({
_id: creatureId,
name: 'action test creature',
owner: Random.id(),
dirty: true,
type: 'pc',
readers: [],
writers: [],
public: false,
settings: {},
}),
Creatures.insertAsync({
_id: targetId,
name: 'action test creature',
owner: Random.id(),
dirty: true,
type: 'pc',
readers: [],
writers: [],
public: false,
settings: {},
})
]);
// Add test props
await insertActionTestProps();
// Compute before load or we might run tests before the computation changes reflect in the cache
computeCreature(creatureId);
computeCreature(targetId);
loadCreature(creatureId, dummySubscription);
});
after(function () {
dummySubscription.stop();
});
it('writes notes to the log', async function () {
const action = await runActionById(note1Id);
assert.deepEqual(
allLogContent(action),
[{ value: 'Note 1 summary. 1 + 1 = 2' }]
);
});
it('Applies children of folders', async function () {
const action = await runActionById(folderId);
assert.deepEqual(
allLogContent(action),
[{ value: 'child of folder' }]
);
});
it('Applies the children of if branches', async function () {
let action = await runActionById(ifTruthyBranchId);
assert.deepEqual(
allLogContent(action),
[{ value: 'child of if branch' }]
);
action = await runActionById(ifFalsyBranchId);
assert.deepEqual(
allLogContent(action),
[]
);
});
it('Applies the children of index branches', async function () {
const action = await runActionById(indexBranchId);
assert.deepEqual(
allLogContent(action),
[{ value: 'child 2 of index branch' }]
);
});
it('Gets choices from choice branches', async function () {
const action = await runActionById(choiceBranchId);
assert.deepEqual(
allLogContent(action),
[{ value: 'child 1 of choice branch' }]
);
});
it('Applies adjustments', async function () {
let action = await runActionById(adjustmentSetId);
assert.deepEqual(
allUpdates(action),
[{
propId: adjustedStatId,
type: 'attribute',
set: { damage: 5, value: 3 },
}],
'Applying set adjustments should return the correct updates'
);
action = await runActionById(adjustmentIncrementId)
assert.deepEqual(
allUpdates(action),
[{
propId: adjustedStatId,
type: 'attribute',
inc: { damage: 2, value: -2 }, // damage goes up by 2, value down by 2
}],
'Applying increment adjustments should return the correct updates'
);
});
it('Applies rolls', async function () {
const action = await runActionById(rollId);
assert.deepEqual(allLogContent(action), [
{
name: 'New Roll',
value: '7d1 [1, 1, 1, 1, 1, 1, 1] + 9\n**16**',
inline: true,
}, {
value: 'rollVar: 16'
}
]);
});
it('Applies buffs', async function () {
const action = await runActionById(buffId);
const inserts = allInserts(action);
const newIds = inserts.map(p => p._id);
assert.notEqual(buffId, newIds[0]);
assert.deepEqual(inserts, [
{
_id: newIds[0],
left: 43,
parentId: null,
right: 48,
root: {
collection: 'creatures',
id: creatureId,
},
tags: [],
target: 'self',
type: 'buff',
}, {
_id: newIds[1],
attributeType: 'stat',
baseValue: {
calculation: '13 + buffSourceStat + 7',
},
left: 44,
parentId: newIds[0],
right: 45,
root: {
collection: 'creatures',
id: creatureId,
},
tags: [],
type: 'attribute',
variableName: 'buffStat',
}, {
_id: newIds[2],
left: 46,
parentId: newIds[0],
removeAll: true,
right: 47,
root: {
collection: 'creatures',
id: creatureId,
},
tags: [],
target: 'self',
targetParentBuff: true,
type: 'buffRemover',
}
]);
});
it('Removes parent buffs', async function () {
const action = await runActionById(removeParentBuffId);
assert.deepEqual(allRemovals(action), [
{ propId: buffId }
]);
});
it('Removes all buffs by tag', async function () {
const action = await runActionById(removeTaggedBuffsId);
assert.deepEqual(allRemovals(action), [
{ propId: taggedBuffId },
{ propId: secondTaggedBuffId },
]);
});
it('Removes a single buff by tag', async function () {
const action = await runActionById(removeOneTaggedBuffId);
assert.deepEqual(allRemovals(action), [
{ propId: taggedBuffId },
]);
});
});
function createAction(prop, targetIds?) {
const action: EngineAction = {
creatureId: prop.root.id,
results: [],
taskCount: 0,
task: {
prop,
targetIds,
}
};
return EngineActions.insertAsync(action);
}
async function runActionById(propId) {
const prop = await CreatureProperties.findOneAsync(propId);
const actionId = await createAction(prop);
const action = await EngineActions.findOneAsync(actionId);
if (!action) throw 'Action is expected to exist';
await applyAction(action, inputProvider, { simulate: true });
return action;
}
function allUpdates(action: EngineAction) {
const updates: Update[] = [];
action.results.forEach(result => {
result.mutations.forEach(mutation => {
mutation.updates?.forEach(update => {
updates.push(update);
});
});
});
return updates;
}
function allInserts(action: EngineAction) {
const inserts: any[] = [];
action.results.forEach(result => {
result.mutations.forEach(mutation => {
mutation.inserts?.forEach(update => {
inserts.push(update);
});
});
});
return inserts;
}
function allRemovals(action: EngineAction) {
const removals: Removal[] = [];
action.results.forEach(result => {
result.mutations.forEach(mutation => {
mutation.removals?.forEach(update => {
removals.push(update);
});
});
});
return removals
}
function allLogContent(action: EngineAction) {
const contents: LogContent[] = [];
action.results.forEach(result => {
result.mutations.forEach(mutation => {
mutation.contents?.forEach(logContent => {
contents.push(logContent);
});
});
});
return contents;
}
let note1Id, folderId, ifTruthyBranchId, ifFalsyBranchId, indexBranchId, choiceBranchId,
adjustedStatId, adjustmentIncrementId, adjustmentSetId, rollId, buffId,
removeParentBuffId, removeTaggedBuffsId, removeOneTaggedBuffId, taggedBuffId, secondTaggedBuffId;
const propForest = [
// Apply a simple note
{
_id: note1Id = Random.id(),
type: 'note',
summary: {
text: 'Note 1 summary. 1 + 1 = {1 + 1}'
},
},
// Apply a folder with a note inside
{
_id: folderId = Random.id(),
type: 'folder',
children: [{ type: 'note', summary: { text: 'child of folder' } }],
},
// Apply an if branch with a truthy condition
{
_id: ifTruthyBranchId = Random.id(),
type: 'branch',
branchType: 'if',
condition: { calculation: '1 + 1' },
children: [{ type: 'note', summary: { text: 'child of if branch' } }],
},
// Apply an if branch with a falsy condition
{
_id: ifFalsyBranchId = Random.id(),
type: 'branch',
branchType: 'if',
condition: { calculation: '1 - 1' },
children: [{ type: 'note', summary: { text: 'child of if branch' } }],
},
// Apply an index branch
{
_id: indexBranchId = Random.id(),
type: 'branch',
branchType: 'index',
condition: { calculation: '1 + 1' },
children: [
{ type: 'note', summary: { text: 'child 1 of index branch' } },
{ type: 'note', summary: { text: 'child 2 of index branch' } },
{ type: 'note', summary: { text: 'child 3 of index branch' } },
],
},
// Apply a choice branch
{
_id: choiceBranchId = Random.id(),
type: 'branch',
branchType: 'choice',
children: [
{ type: 'note', summary: { text: 'child 1 of choice branch' } },
{ type: 'note', summary: { text: 'child 2 of choice branch' } },
{ type: 'note', summary: { text: 'child 3 of choice branch' } },
],
},
// Apply adjustments
{
_id: adjustedStatId = Random.id(),
type: 'attribute',
attributeType: 'stat',
variableName: 'adjustedStat',
baseValue: { calculation: '8' },
}, {
_id: adjustmentSetId = Random.id(),
type: 'adjustment',
stat: 'adjustedStat',
operation: 'set',
amount: { calculation: '3' },
target: 'self',
children: [
{ type: 'note', summary: { text: 'adjustment set applied' } },
],
}, {
_id: adjustmentIncrementId = Random.id(),
type: 'adjustment',
stat: 'adjustedStat',
operation: 'increment',
amount: { calculation: '2' },
target: 'self',
children: [
{ type: 'note', summary: { text: 'adjustment increment applied' } },
],
},
// Apply buffs
{
_id: Random.id(),
type: 'attribute',
attributeType: 'stat',
variableName: 'buffSourceStat',
baseValue: { calculation: '13' },
}, {
_id: buffId = Random.id(),
type: 'buff',
target: 'self',
children: [
{
_id: Random.id(),
type: 'attribute',
attributeType: 'stat',
variableName: 'buffStat',
baseValue: { calculation: 'buffSourceStat + ~target.buffSourceStat + 7' },
}, {
_id: removeParentBuffId = Random.id(),
type: 'buffRemover',
target: 'self',
targetParentBuff: true,
},
],
},
// Extra buffs with and without tags
{
_id: taggedBuffId = Random.id(),
name: 'Tagged Buff',
type: 'buff',
tags: ['buff tag', 'other tag']
}, {
_id: secondTaggedBuffId = Random.id(),
name: 'Tagged buff 2',
type: 'buff',
tags: ['buff tag', 'yet another tag']
}, {
_id: Random.id(),
name: 'Untagged buff',
type: 'buff',
tags: ['other tag']
},
// Remove buffs by tag
{
_id: removeTaggedBuffsId = Random.id(),
type: 'buffRemover',
target: 'self',
removeAll: true,
targetTags: 'buff tag',
}, {
_id: removeOneTaggedBuffId = Random.id(),
type: 'buffRemover',
target: 'self',
removeAll: false,
targetTags: 'buff tag',
},
// Apply rolls
{
_id: rollId = Random.id(),
type: 'roll',
// Roll d1's because it's a pain to test random numbers
roll: { calculation: '1 + 3 + 7d1 + 5' },
variableName: 'rollVar',
children: [
{ type: 'note', summary: { text: 'rollVar: {rollVar}' } }
]
}
];
const targetPropForest = [
{
type: 'attribute',
attributeType: 'stat',
variableName: 'armor',
baseValue: { calculation: '10' },
}
];
function insertActionTestProps() {
const promises = propsFromForest(propForest, creatureId).map(prop => {
return CreatureProperties.insertAsync(prop);
});
propsFromForest(targetPropForest, targetId).forEach(prop => {
promises.push(CreatureProperties.insertAsync(prop));
});
return Promise.all(promises);
}

View File

@@ -0,0 +1,137 @@
import SimpleSchema from 'simpl-schema';
import TaskResult from './tasks/TaskResult';
import LogContentSchema from '/imports/api/creature/log/LogContentSchema';
import Task from './tasks/Task';
const EngineActions = new Mongo.Collection<EngineAction>('actions');
export interface EngineAction {
_id?: string;
_isSimulation?: boolean;
_stepThrough?: boolean;
_decisions?: any[],
task: Task;
creatureId: string;
tabletopId?: string;
results: TaskResult[];
taskCount: number;
}
const ActionSchema = new SimpleSchema({
creatureId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
// @ts-expect-error index not defined
index: 1,
},
rootPropId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
optional: true,
},
tabletopId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
optional: true,
// @ts-expect-error index not defined
index: 1,
},
task: {
type: Object,
blackbox: true,
},
// Applied properties
results: {
type: Array,
defaultValue: [],
},
'results.$': {
type: Object,
},
// The property and target ids popped off the task stack
// Pushing these to the top of the stack and deleting the results from this point onwards
// Should re-run the action identically from this point
'results.$.propId': {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
'results.$.targetIds': {
type: Array,
defaultValue: [],
},
'results.$.targetIds.$': {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
// Changes that override the local scope
'results.$.scope': {
type: Object,
optional: true,
blackbox: true,
},
// Changes that consume pushed values from the local scope
'results.$.popScope': {
type: Object,
optional: true,
blackbox: true,
},
// Changes that push values to the local scope
'results.$.pushScope': {
type: Object,
optional: true,
blackbox: true,
},
// database changes
'results.$.mutations': {
type: Array,
optional: true,
},
'results.$.mutations.$': {
type: Object,
},
'results.$.mutations.$.targetIds': {
type: Array,
},
'results.$.mutations.$.targetIds.$': {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
'results.$.mutations.$.updates': {
type: Array,
optional: true,
},
'results.$.mutations.$.updates.$': {
type: Object,
},
'results.$.mutations.$.updates.$.propId': {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
// Required, because CreatureProperties.update requires a selector of { type }
'results.$.mutations.$.updates.$.type': {
type: String,
},
'results.$.mutations.$.updates.$.set': {
type: Object,
optional: true,
blackbox: true,
},
'results.$.mutations.$.updates.$.inc': {
type: Object,
optional: true,
blackbox: true,
},
'results.$.mutations.$.contents': {
type: Array,
optional: true,
},
'results.$.mutations.$.contents.$': {
type: LogContentSchema,
},
});
// @ts-expect-error Collections2 lacks TypeScript support
EngineActions.attachSchema(ActionSchema);
export default EngineActions;
export { ActionSchema }

View File

@@ -0,0 +1,458 @@
import { assert } from 'chai';
import {
allLogContent,
allMutations,
allUpdates,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
import { LogContent, Mutation, Update } from '/imports/api/engine/action/tasks/TaskResult';
import Alea from 'alea';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
const [
creatureId, targetCreatureId, targetCreature2Id, emptyActionId, selfActionId, attackActionId,
usesActionId, attackMissId, attackNoTargetId, usesResourcesActionId, ammoId, resourceAttId,
consumeAmmoId, consumeResourceId, noUsesActionId, insufficientResourcesActionId,
attributeResetByEventId, eventActionId, advantageAttackId, advantageEffectId, disadvantageAttackId, disadvantageEffectId,
] = getRandomIds(100);
const actionTestCreature = {
_id: creatureId,
props: [
// Empty
{
_id: emptyActionId,
type: 'action',
summary: { text: 'Summary text 1 + 1 = {1 + 1}' }
},
// Attack that targets self
{
_id: selfActionId,
type: 'action',
target: 'self',
},
// Attack that hits
{
_id: attackActionId,
type: 'action',
attackRoll: { calculation: '10' },
},
// Attack that misses
{
_id: attackMissId,
type: 'action',
attackRoll: { calculation: '-5' },
},
// Attack that has Advantage
{
_id: advantageAttackId,
type: 'action',
attackRoll: { calculation: '0' },
tags: ['hasAdvantage'],
},
{
_id: advantageEffectId,
type: 'effect',
operation: 'advantage',
targetByTags: true,
targetTags: ['hasAdvantage'],
},
// Attack that has Disadvantage
{
_id: disadvantageAttackId,
type: 'action',
attackRoll: { calculation: '0' },
tags: ['hasDisadvantage'],
},
{
_id: disadvantageEffectId,
type: 'effect',
operation: 'disadvantage',
targetByTags: true,
targetTags: ['hasDisadvantage'],
},
// Attack that has no target
{
_id: attackNoTargetId,
type: 'action',
attackRoll: { calculation: '1' },
},
// Disable crits
{
type: 'attribute',
attributeType: 'stat',
variableName: '~criticalHitTarget',
baseValue: { calculation: '21' },
},
{
type: 'attribute',
attributeType: 'stat',
variableName: '~criticalMissTarget',
baseValue: { calculation: '0' },
},
// Has uses
{
_id: usesActionId,
type: 'action',
uses: { calculation: '3' },
usesUsed: 1,
reset: 'longRest',
},
// Not enough uses
{
_id: noUsesActionId,
type: 'action',
uses: { calculation: '5' },
usesUsed: 5,
reset: 'longRest',
},
// Uses Resources
{
_id: ammoId,
type: 'item',
quantity: 12,
tags: ['ammo']
},
{
_id: resourceAttId,
type: 'attribute',
name: 'Resource Name',
attributeType: 'stat',
baseValue: { calculation: '7' },
variableName: 'resourceVar',
},
{
_id: usesResourcesActionId,
type: 'action',
resources: {
itemsConsumed: [{
_id: consumeAmmoId,
tag: 'ammo',
quantity: { calculation: '3' },
itemId: ammoId,
}],
attributesConsumed: [{
_id: consumeResourceId,
variableName: 'resourceVar',
quantity: { calculation: '2' },
}]
}
},
{
_id: insufficientResourcesActionId,
type: 'action',
resources: {
attributesConsumed: [{
_id: consumeResourceId,
variableName: 'resourceVar',
quantity: { calculation: '9001' },
}]
}
},
// Events and resetting attributes
{
_id: attributeResetByEventId,
type: 'attribute',
name: 'Attribute Reset By testEvent Event',
attributeType: 'stat',
baseValue: { calculation: '27' },
damage: 13,
variableName: 'resetByEventAtt',
reset: 'testEvent'
},
{
_id: eventActionId,
type: 'action',
actionType: 'event',
variableName: 'testEvent',
},
],
}
const actionTargetCreature = {
_id: targetCreatureId,
props: [
{
type: 'attribute',
attributeType: 'stat',
variableName: 'armor',
baseValue: { calculation: '10' },
}
]
}
const actionTargetCreature2 = {
_id: targetCreature2Id,
props: [
{
type: 'attribute',
attributeType: 'stat',
variableName: 'armor',
baseValue: { calculation: '10' },
}
]
}
describe('Apply Action Properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
await createTestCreature(actionTargetCreature);
await createTestCreature(actionTargetCreature2);
});
it('should generate random numbers reliably given consistent seeds', function () {
const aleaFraction = Alea('test', 'seeds');
const randomNumbers = [aleaFraction(), aleaFraction(), aleaFraction()];
assert.deepEqual(randomNumbers, [
0.19889510236680508, 0.9176857066340744, 0.042551583144813776
]);
});
it('should run empty actions', async function () {
const action = await runActionById(emptyActionId);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [{
name: 'Action',
value: 'Summary text 1 + 1 = 2',
}],
targetIds: [],
}]);
});
it('should target self when set', async function () {
const action = await runActionById(selfActionId);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [{
name: 'Action',
}],
targetIds: [creatureId],
}]);
});
it('should make attack rolls against no targets', async function () {
const action = await runActionById(attackNoTargetId, []);
const expectedMutations: Mutation[] = [
{
contents: [{ name: 'Action' }],
targetIds: [],
}, {
contents: [{
name: 'To Hit',
value: '1d20 [10] + 1\n**11**',
inline: true,
}],
targetIds: [],
}
];
assert.deepEqual(allMutations(action), expectedMutations);
})
it('should make attack rolls against multiple creatures', async function () {
const action = await runActionById(attackActionId, [
targetCreatureId,
targetCreature2Id,
]);
const expectedMutations: Mutation[] = [
{
contents: [{ name: 'Action' }],
targetIds: [targetCreatureId, targetCreature2Id]
}, {
contents: [{
inline: true,
name: 'Hit!',
value: '1d20 [10] + 10\n**20**',
}],
targetIds: [targetCreatureId],
}, {
contents: [{
inline: true,
name: 'Hit!',
value: '1d20 [10] + 10\n**20**',
}],
targetIds: [targetCreature2Id],
},
];
assert.deepEqual(allMutations(action), expectedMutations);
});
it('should make attack rolls that use uses', async function () {
const action = await runActionById(usesActionId, [targetCreatureId]);
const expectedUpdates: Update[] = [
{
propId: usesActionId,
type: 'action',
inc: { usesUsed: 1, usesLeft: -1 },
}
]
assert.deepEqual(allUpdates(action), expectedUpdates);
});
it('should fail to make attacks that have no uses left', async function () {
const action = await runActionById(noUsesActionId, [targetCreatureId]);
const expectedContent: LogContent[] = [
{
name: 'Action'
}, {
name: 'Error',
value: 'Action does not have enough uses left'
}
]
assert.deepEqual(allLogContent(action), expectedContent);
});
it('should make attack rolls that miss', async function () {
const action = await runActionById(attackMissId, [targetCreatureId]);
const expectedMutations: Mutation[] = [
{
contents: [{ name: 'Action' }],
targetIds: [targetCreatureId],
}, {
contents: [{
inline: true,
name: 'Miss!',
value: '1d20 [10] 5\n**5**', // DiceCloud uses unicode minus
}],
targetIds: [targetCreatureId],
}
];
assert.deepEqual(allMutations(action), expectedMutations);
});
it('should make attack rolls that roll with advantage', async function () {
const prop = await CreatureProperties.findOneAsync(advantageAttackId);
assert.equal(prop.attackRoll.advantage, 1, 'The attack roll should have advantage');
const action = await runActionById(advantageAttackId, [targetCreatureId]);
const expectedMutations: Mutation[] = [
{
contents: [{ name: 'Action' }],
targetIds: [targetCreatureId],
}, {
contents: [{
inline: true,
name: 'Hit! (Advantage)',
value: '1d20 [ ~~10~~, 11 ] + 0\n**11**',
}],
targetIds: [targetCreatureId],
}
];
assert.deepEqual(allMutations(action), expectedMutations);
});
it('should make attack rolls that roll with disadvantage', async function () {
const prop = await CreatureProperties.findOneAsync(disadvantageAttackId);
assert.equal(prop.attackRoll.disadvantage, 1, 'The attack roll should have disadvantage');
const action = await runActionById(disadvantageAttackId, [targetCreatureId]);
const expectedMutations: Mutation[] = [
{
contents: [{ name: 'Action' }],
targetIds: [targetCreatureId],
}, {
contents: [{
inline: true,
name: 'Hit! (Disadvantage)',
value: '1d20 [ 10, ~~11~~ ] + 0\n**10**',
}],
targetIds: [targetCreatureId],
}
];
assert.deepEqual(allMutations(action), expectedMutations);
});
it('actions should consume resources', async function () {
const action = await runActionById(usesResourcesActionId, []);
const expectedMutations: Mutation[] = [
{
contents: [{ name: 'Action' }],
targetIds: []
},
{
contents: [{
inline: true,
name: 'Attribute damaged',
value: '2 Resource Name',
}],
targetIds: [creatureId],
updates: [{
inc: {
damage: 2,
value: -2
},
propId: resourceAttId,
type: 'attribute'
}],
},
{
targetIds: [],
updates: [
{
inc: {
quantity: -3
},
propId: ammoId,
type: 'item',
}
]
}
];
assert.deepEqual(allMutations(action), expectedMutations);
});
it('should handle insufficient resources', async function () {
const action = await runActionById(insufficientResourcesActionId, []);
const expectedMutations: Mutation[] = [
{
contents: [{
name: 'Action'
}, {
name: 'Error',
value: 'This creature doesn\'t have sufficient resources to perform this action',
}],
targetIds: [],
},
];
assert.deepEqual(allMutations(action), expectedMutations);
});
it('should reset attributes when events happen', async function () {
const action = await runActionById(eventActionId, []);
const expectedMutations: Mutation[] = [
{
contents: [{
name: 'Action'
}],
targetIds: [],
},
{
contents: [
{
inline: true,
name: 'Attribute restored',
value: '+13 Attribute Reset By testEvent Event',
},
],
targetIds: [creatureId],
updates: [
{
inc: {
damage: -13,
value: 13,
},
propId: attributeResetByEventId,
type: 'attribute',
},
],
}
];
assert.deepEqual(allMutations(action), expectedMutations);
});
});

View File

@@ -0,0 +1,251 @@
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import { PropTask } from '../tasks/Task';
import TaskResult, { LogContent } from '../tasks/TaskResult';
import { getVariables } from '/imports/api/engine/loadCreatures';
import getPropertyTitle from '/imports/api/utility/getPropertyTitle';
import recalculateInlineCalculations from '/imports/api/engine/action/functions/recalculateInlineCalculations';
import spendResources from '/imports/api/engine/action/functions/spendResources';
import { applyAfterChildrenTriggers, applyAfterTriggers, applyChildren } from '/imports/api/engine/action/functions/applyTaskGroups';
import recalculateCalculation from '/imports/api/engine/action/functions/recalculateCalculation';
import { getEffectiveActionScope } from '/imports/api/engine/action/functions/getEffectiveActionScope';
import numberToSignedString from '/imports/api/utility/numberToSignedString';
import { getNumberFromScope } from '/imports/api/creature/creatures/CreatureVariables';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
import { CalculatedField } from '/imports/api/properties/subSchemas/computedField';
import applyResetTask from '/imports/api/engine/action/tasks/applyResetTask';
export default async function applyActionProperty(
task: PropTask, action: EngineAction, result: TaskResult, userInput: InputProvider
): Promise<void> {
const prop = task.prop;
const targetIds = prop.target === 'self' ? [action.creatureId] : task.targetIds;
//Log the name and summary, check that the property has enough resources to fire
if (prop.summary?.text) {
await recalculateInlineCalculations(prop.summary, action, 'reduce', userInput);
}
result.appendLog({
name: getPropertyTitle(prop),
...prop.summary && { value: prop.summary.value },
silenced: prop.silent,
}, targetIds);
// Check Uses
if (prop.usesLeft <= 0) {
result.appendLog({
name: 'Error',
value: `${getPropertyTitle(prop)} does not have enough uses left`,
silenced: prop.silent,
}, targetIds);
return;
}
// Check Resources
if (prop.insufficientResources) {
result.appendLog({
name: 'Error',
value: 'This creature doesn\'t have sufficient resources to perform this action',
silenced: prop.silent,
}, targetIds);
return;
}
await spendResources(action, prop, targetIds, result, userInput);
const attack: CalculatedField = prop.attackRoll || prop.attackRollBonus;
// Attack if there is an attack roll
if (attack && attack.calculation) {
if (targetIds.length) {
for (const targetId of targetIds) {
await applyAttackToTarget(task, action, attack, targetId, result, userInput);
await applyAfterTriggers(action, prop, [targetId], userInput);
await applyChildren(action, prop, [targetId], userInput);
}
} else {
await applyAttackWithoutTarget(action, prop, attack, result, userInput);
await applyAfterTriggers(action, prop, targetIds, userInput);
await applyChildren(action, prop, targetIds, userInput);
}
} else {
await applyAfterTriggers(action, prop, targetIds, userInput);
await applyChildren(action, prop, targetIds, userInput);
}
if (prop.actionType === 'event' && prop.variableName) {
await applyResetTask({
subtaskFn: 'reset',
eventName: prop.variableName,
targetIds: [action.creatureId],
}, action, result, userInput);
}
// Finish
return await applyAfterChildrenTriggers(action, prop, targetIds, userInput);
}
async function applyAttackToTarget(
task: PropTask, action: EngineAction, attack: CalculatedField, targetId: string,
taskResult: TaskResult, userInput: InputProvider
) {
taskResult.pushScope = {
'~attackHit': {},
'~attackMiss': {},
'~criticalHit': {},
'~criticalMiss': {},
'~attackRoll': {},
}
await recalculateCalculation(attack, action, 'reduce', userInput);
const scope = await getEffectiveActionScope(action);
const contents: LogContent[] = [];
const {
resultPrefix,
result,
criticalHit,
criticalMiss,
advantage
} = await rollAttack(attack, scope, taskResult.pushScope, userInput);
const targetScope = getVariables(targetId);
const targetArmor = getNumberFromScope('armor', targetScope)
if (targetArmor !== undefined) {
let name = criticalHit ? 'Critical Hit!' :
criticalMiss ? 'Critical Miss!' :
result >= targetArmor ? 'Hit!' : 'Miss!';
if (advantage === 1) {
name += ' (Advantage)';
} else if (advantage === -1) {
name += ' (Disadvantage)';
}
contents.push({
name,
value: `${resultPrefix}\n**${result}**`,
inline: true,
...task.prop.silent && { silenced: true },
});
if (criticalMiss || result < targetArmor) {
taskResult.pushScope['~attackMiss'] = { value: true };
} else {
taskResult.pushScope['~attackHit'] = { value: true };
}
} else {
contents.push({
name: 'Error',
value: 'Target has no `armor`',
inline: true,
...task.prop.silent && { silenced: true },
}, {
name: criticalHit ? 'Critical Hit!' : criticalMiss ? 'Critical Miss!' : 'To Hit',
value: `${resultPrefix}\n**${result}**`,
inline: true,
...task.prop.silent && { silenced: true },
});
}
if (contents.length) {
taskResult.mutations.push({
contents,
targetIds: [targetId],
});
}
}
async function applyAttackWithoutTarget(action, prop, attack, taskResult: TaskResult, userInput: InputProvider) {
taskResult.pushScope = {
'~attackHit': {},
'~attackMiss': {},
'~criticalHit': {},
'~criticalMiss': {},
'~attackRoll': {},
}
await recalculateCalculation(attack, action, 'reduce', userInput);
const scope = await getEffectiveActionScope(action);
const {
resultPrefix,
result,
criticalHit,
criticalMiss,
advantage,
} = await rollAttack(attack, scope, taskResult.pushScope, userInput);
let name = criticalHit ? 'Critical Hit!' : criticalMiss ? 'Critical Miss!' : 'To Hit';
if (advantage === 1) {
name += ' (Advantage)';
} else if (advantage === -1) {
name += ' (Disadvantage)';
}
if (!criticalMiss) {
taskResult.pushScope['~attackHit'] = { value: true }
}
if (!criticalHit) {
taskResult.pushScope['~attackMiss'] = { value: true };
}
taskResult.mutations.push({
contents: [{
name,
value: `${resultPrefix}\n**${result}**`,
inline: true,
...prop.silent && { silenced: true },
}],
targetIds: [],
});
}
async function rollAttack(attack, scope: any, resultPushScope, userInput: InputProvider) {
const advantage: 0 | 1 | -1 = await userInput.advantage(
(!!attack.advantage && !attack.disadvantage) ? 1 :
(!attack.advantage && !!attack.disadvantage) ? -1 :
0
);
const rollModifierText = numberToSignedString(attack.value, true);
let value, resultPrefix;
if (advantage === 1) {
const [[a, b]] = await userInput.rollDice([{ number: 2, diceSize: 20 }]);
if (a >= b) {
value = a;
resultPrefix = `1d20 [ ${a}, ~~${b}~~ ] ${rollModifierText}`;
} else {
value = b;
resultPrefix = `1d20 [ ~~${a}~~, ${b} ] ${rollModifierText}`;
}
} else if (advantage === -1) {
const [[a, b]] = await userInput.rollDice([{ number: 2, diceSize: 20 }]);
if (a <= b) {
value = a;
resultPrefix = `1d20 [ ${a}, ~~${b}~~ ] ${rollModifierText}`;
} else {
value = b;
resultPrefix = `1d20 [ ~~${a}~~, ${b} ] ${rollModifierText}`;
}
} else {
[[value]] = await userInput.rollDice([{ number: 1, diceSize: 20 }]);
resultPrefix = `1d20 [${value}] ${rollModifierText}`
}
resultPushScope['~attackDiceRoll'] = { value };
const result = value + attack.value;
resultPushScope['~attackRoll'] = { value: result };
const { criticalHit, criticalMiss } = applyCrits(value, scope, resultPushScope);
return { resultPrefix, result, value, criticalHit, criticalMiss, advantage };
}
function applyCrits(value, scope, resultPushScope) {
const scopeCritTarget = getNumberFromScope('~criticalHitTarget', scope);
const criticalHitTarget = scopeCritTarget !== undefined &&
Number.isFinite(scopeCritTarget) ? scopeCritTarget : 20;
const scopeCritMissTarget = getNumberFromScope('~criticalMissTarget', scope);
const criticalMissTarget = scopeCritMissTarget !== undefined &&
Number.isFinite(scopeCritMissTarget) ? scopeCritMissTarget : 1;
const criticalHit = value >= criticalHitTarget;
const criticalMiss = value <= criticalMissTarget;
if (criticalHit) {
resultPushScope['~criticalHit'] = { value: true };
} else if (criticalMiss) {
resultPushScope['~criticalMiss'] = { value: true };
}
return { criticalHit, criticalMiss };
}

View File

@@ -0,0 +1,164 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, targetCreatureId, targetCreature2Id, adjustmentToTargetId, adjustmentToSelfId, targetCreatureStrengthId, targetCreature2StrengthId, selfDexterityId
] = getRandomIds(100);
const actionTestCreature = {
_id: creatureId,
props: [
{
_id: adjustmentToTargetId,
type: 'adjustment',
target: 'target',
stat: 'strength',
operation: 'increment',
amount: { calculation: '2' }
},
{
_id: adjustmentToSelfId,
type: 'adjustment',
target: 'self',
stat: 'dexterity',
operation: 'set',
amount: { calculation: '11' }
},
{
_id: selfDexterityId,
type: 'attribute',
name: 'Dexterity',
attributeType: 'ability',
variableName: 'dexterity',
baseValue: { calculation: '13' },
},
],
}
const actionTargetCreature = {
_id: targetCreatureId,
props: [
{
_id: targetCreatureStrengthId,
type: 'attribute',
attributeType: 'ability',
variableName: 'strength',
baseValue: { calculation: '12' },
}
]
}
const actionTargetCreature2 = {
_id: targetCreature2Id,
props: [
{
_id: targetCreature2StrengthId,
type: 'attribute',
attributeType: 'ability',
variableName: 'strength',
baseValue: { calculation: '18' },
}
]
}
describe('Apply Adjustment Properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
await createTestCreature(actionTargetCreature);
await createTestCreature(actionTargetCreature2);
});
it('Adjusts the attributes of self', async function () {
const action = await runActionById(adjustmentToSelfId);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [
{
inline: true,
name: 'Attribute damage',
value: 'Dexterity set from 13 to 11',
}
],
targetIds: [creatureId],
updates: [
{
propId: selfDexterityId,
type: 'attribute',
set: { damage: 2, value: 11 },
},
],
}]);
});
it('Adjusts the attributes of a single target', async function () {
const action = await runActionById(adjustmentToTargetId, [targetCreatureId]);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [
{
inline: true,
name: 'Attribute damaged',
value: '2 Attribute',
}
],
targetIds: [targetCreatureId],
updates: [
{
propId: targetCreatureStrengthId,
type: 'attribute',
inc: { damage: 2, value: -2 },
},
],
}]);
});
it('Adjusts the attributes of multiple targets', async function () {
const action = await runActionById(adjustmentToTargetId, [
targetCreatureId, targetCreature2Id
]);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [
{
inline: true,
name: 'Attribute damaged',
value: '2 Attribute',
}
],
targetIds: [targetCreatureId],
updates: [
{
propId: targetCreatureStrengthId,
type: 'attribute',
inc: { damage: 2, value: -2 },
},
],
}, {
contents: [
{
inline: true,
name: 'Attribute damaged',
value: '2 Attribute',
}
],
targetIds: [targetCreature2Id],
updates: [
{
propId: targetCreature2StrengthId,
type: 'attribute',
inc: { damage: 2, value: -2 },
},
],
}]);
});
});

View File

@@ -0,0 +1,62 @@
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
import { applyDefaultAfterPropTasks, applyTaskToEachTarget } from '/imports/api/engine/action/functions/applyTaskGroups';
import recalculateCalculation from '/imports/api/engine/action/functions/recalculateCalculation';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import TaskResult from '/imports/api/engine/action/tasks/TaskResult';
import applyTask from '/imports/api/engine/action/tasks/applyTask';
import { getSingleProperty, getVariables } from '/imports/api/engine/loadCreatures';
import getPropertyTitle from '/imports/api/utility/getPropertyTitle';
export default async function applyAdjustmentProperty(
task: PropTask, action: EngineAction, result: TaskResult, userInput: InputProvider
): Promise<void> {
const prop = task.prop;
const damageTargetIds = prop.target === 'self' ? [action.creatureId] : task.targetIds;
if (damageTargetIds.length > 1) {
return applyTaskToEachTarget(action, task, damageTargetIds, userInput);
}
// Get the operation and value and push the damage hooks to the queue
if (!prop.amount) {
return;
}
// Evaluate the amount
await recalculateCalculation(prop.amount, action, 'reduce', userInput);
const value = +prop.amount.value;
if (!isFinite(value)) {
return;
}
if (!damageTargetIds?.length) {
return;
}
if (damageTargetIds.length !== 1) {
throw 'At this step, only a single target is supported'
}
const targetId = damageTargetIds[0];
const statId = getVariables(targetId)?.[prop.stat]?._propId;
const stat = statId && getSingleProperty(targetId, statId);
if (!stat?.type) {
result.appendLog({
name: 'Error',
value: `Could not apply attribute damage, creature does not have \`${prop.stat}\` set`,
silenced: prop.silent,
}, damageTargetIds);
return;
}
await applyTask(action, {
targetIds: damageTargetIds,
subtaskFn: 'damageProp',
params: {
title: getPropertyTitle(prop),
operation: prop.operation,
value,
targetProp: stat,
},
}, userInput);
return applyDefaultAfterPropTasks(action, prop, damageTargetIds, userInput);
}

View File

@@ -0,0 +1,376 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, targetCreatureId, ifTrueBranchId, ifFalseBranchId, indexBranchId, attackHitId, attackMissId, saveSucceedId, saveFailId, randomBranchId, targetCreature2Id, eachTargetBranchId, choiceBranchId,
] = getRandomIds(100);
const actionTestCreature = {
_id: creatureId,
props: [
// If branch
{
_id: ifTrueBranchId,
type: 'branch',
branchType: 'if',
condition: { calculation: 'true' },
children: [
{
type: 'note',
summary: { text: 'this should run' },
},
],
},
{
_id: ifFalseBranchId,
type: 'branch',
branchType: 'if',
condition: { calculation: 'false' },
children: [
{
type: 'note',
summary: { text: 'this should not run' },
},
],
},
// index branch
{
_id: indexBranchId,
type: 'branch',
branchType: 'index',
condition: { calculation: '1 + 1' },
children: [
{
type: 'note',
summary: { text: 'FAIL: index child 1 should not run' },
},
{
type: 'note',
summary: { text: 'Child 2 should run' },
},
{
type: 'note',
summary: { text: 'FAIL: index child 3 should not run' },
},
],
},
// Hit and miss branches
{
_id: attackHitId,
type: 'action',
attackRoll: { calculation: '1' },
children: [
{
type: 'branch',
branchType: 'hit',
children: [{
type: 'note',
summary: { text: 'attack hit branch' }
}],
},
{
type: 'branch',
branchType: 'miss',
children: [{
type: 'note',
summary: { text: 'attack miss branch' }
}],
},
]
},
{
_id: attackMissId,
type: 'action',
attackRoll: { calculation: '-1' },
children: [
{
type: 'branch',
branchType: 'hit',
children: [{
type: 'note',
summary: { text: 'attack hit branch' }
}],
},
{
type: 'branch',
branchType: 'miss',
children: [{
type: 'note',
summary: { text: 'attack miss branch' }
}],
},
]
},
// Save and fail save branch
{
_id: saveSucceedId,
type: 'savingThrow',
dc: { calculation: '10' },
target: 'target',
stat: 'strengthSave',
children: [
{
type: 'branch',
branchType: 'successfulSave',
children: [{
type: 'note',
summary: { text: 'made save branch' }
}],
},
{
type: 'branch',
branchType: 'failedSave',
children: [{
type: 'note',
summary: { text: 'failed save branch' }
}],
},
]
},
{
_id: saveFailId,
type: 'savingThrow',
dc: { calculation: '15' },
target: 'target',
stat: 'strengthSave',
children: [
{
type: 'branch',
branchType: 'successfulSave',
children: [{
type: 'note',
summary: { text: 'made save branch' }
}],
},
{
type: 'branch',
branchType: 'failedSave',
children: [{
type: 'note',
summary: { text: 'failed save branch' }
}],
},
]
},
// Random branch
{
_id: randomBranchId,
type: 'branch',
branchType: 'random',
children: [
{
type: 'note',
summary: { text: 'FAIL: random child 1 should not run' },
},
{
type: 'note',
summary: { text: 'Random child 2 should run' },
},
{
type: 'note',
summary: { text: 'FAIL: random child 3 should not run' },
},
],
},
// Each target branch
{
_id: eachTargetBranchId,
type: 'branch',
branchType: 'eachTarget',
children: [
{
type: 'note',
summary: { text: 'some note' }
}
]
},
// Choice branch
{
_id: choiceBranchId,
type: 'branch',
branchType: 'choice',
children: [
{
type: 'note',
summary: { text: 'Choice child 1 should run' },
},
{
type: 'note',
summary: { text: 'Fail: choice child 2 should not run' },
},
{
type: 'note',
summary: { text: 'Fail: choice child 3 should not run' },
},
],
},
],
}
const actionTargetCreature = {
_id: targetCreatureId,
props: [
{
type: 'attribute',
attributeType: 'stat',
variableName: 'armor',
baseValue: { calculation: '10' },
},
{
type: 'skill',
skillType: 'save',
variableName: 'strengthSave',
baseValue: { calculation: '3' },
},
]
}
const actionTargetCreature2 = {
_id: targetCreature2Id,
props: [
{
type: 'attribute',
attributeType: 'stat',
variableName: 'armor',
baseValue: { calculation: '15' },
},
]
}
describe('Apply Branch Properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
await createTestCreature(actionTargetCreature);
await createTestCreature(actionTargetCreature2);
});
// If branch
it('Runs an if branch with a true condition', async function () {
const action = await runActionById(ifTrueBranchId);
assert.deepEqual(allMutations(action), [{
contents: [{ value: 'this should run' }],
targetIds: [],
}]);
});
it('runs an if branch with a false condition', async function () {
const action = await runActionById(ifFalseBranchId);
assert.deepEqual(allMutations(action), []);
});
it('runs an if branch and chooses the correct child', async function () {
const action = await runActionById(indexBranchId);
assert.deepEqual(allMutations(action), [{
contents: [{ value: 'Child 2 should run' }],
targetIds: [],
}]);
});
// Hit and miss branch
it('Runs only hit branches on an attack that hits', async function () {
const action = await runActionById(attackHitId, [targetCreatureId]);
assert.deepEqual(allMutations(action), [{
contents: [{ name: 'Action' }],
targetIds: [targetCreatureId],
}, {
contents: [{ inline: true, name: 'Hit!', value: '1d20 [10] + 1\n**11**' }],
targetIds: [targetCreatureId],
}, {
contents: [{ value: 'attack hit branch' }],
targetIds: [targetCreatureId],
}]);
});
it('Runs only miss branches on an attack that misses', async function () {
const action = await runActionById(attackMissId, [targetCreatureId]);
assert.deepEqual(allMutations(action), [{
contents: [{ name: 'Action' }],
targetIds: [targetCreatureId],
}, {
contents: [{ inline: true, name: 'Miss!', value: '1d20 [10] 1\n**9**' }],
targetIds: [targetCreatureId],
}, {
contents: [{ value: 'attack miss branch' }],
targetIds: [targetCreatureId],
}]);
});
// Save succeed and fail branches
it('Runs only miss branches on an attack that misses', async function () {
const action = await runActionById(saveSucceedId, [targetCreatureId]);
assert.deepEqual(allMutations(action), [{
contents: [{
name: 'Saving throw',
value: 'DC **10**',
inline: true
}, {
name: 'Successful save',
value: '1d20 [ 10 ] + 3\n**13**',
inline: true
}],
targetIds: [targetCreatureId],
}, {
contents: [{ value: 'made save branch' }],
targetIds: [targetCreatureId],
}]);
});
it('Runs only miss branches on an attack that misses', async function () {
const action = await runActionById(saveFailId, [targetCreatureId]);
assert.deepEqual(allMutations(action), [{
contents: [{
name: 'Saving throw',
value: 'DC **15**',
inline: true
}, {
name: 'Failed save',
value: '1d20 [ 10 ] + 3\n**13**',
inline: true
}],
targetIds: [targetCreatureId],
}, {
contents: [{ value: 'failed save branch' }],
targetIds: [targetCreatureId],
}]);
});
// Random branches, RNG is fixed at average for testing, so child 2 should run
it('runs a random branch and chooses the correct child', async function () {
const action = await runActionById(randomBranchId);
assert.deepEqual(allMutations(action), [{
contents: [{ value: 'Random child 2 should run' }],
targetIds: [],
}]);
});
// Branches can split actions across targets
it('Can split actions to targets using a branch', async function () {
const action = await runActionById(eachTargetBranchId, [targetCreatureId, targetCreature2Id]);
assert.deepEqual(allMutations(action), [{
contents: [{ value: 'some note' }],
targetIds: [targetCreatureId],
}, {
contents: [{ value: 'some note' }],
targetIds: [targetCreature2Id],
}]);
});
// Choice branches, choices are fixed to first option for testing
it('runs a choice branch and chooses the correct child', async function () {
const action = await runActionById(choiceBranchId);
assert.deepEqual(allMutations(action), [{
contents: [{ value: 'Choice child 1 should run' }],
targetIds: [],
}]);
});
});

View File

@@ -0,0 +1,131 @@
import { filter } from 'lodash';
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
import { applyAfterPropTasksForSingleChild, applyAfterPropTasksForSomeChildren, applyAfterTasksSkipChildren, applyDefaultAfterPropTasks, applyTaskToEachTarget } from '/imports/api/engine/action/functions/applyTaskGroups';
import { getEffectiveActionScope } from '/imports/api/engine/action/functions/getEffectiveActionScope';
import recalculateCalculation from '/imports/api/engine/action/functions/recalculateCalculation';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import TaskResult from '/imports/api/engine/action/tasks/TaskResult';
import { getPropertyChildren } from '/imports/api/engine/loadCreatures';
export default async function applyBranchProperty(
task: PropTask, action: EngineAction, result: TaskResult, userInput: InputProvider
): Promise<void> {
const prop = task.prop;
const targets = task.targetIds;
switch (prop.branchType) {
case 'if': {
await recalculateCalculation(prop.condition, action, 'reduce', userInput);
if (prop.condition?.value) {
return applyDefaultAfterPropTasks(action, prop, targets, userInput);
} else {
return applyAfterTasksSkipChildren(action, prop, targets, userInput);
}
}
case 'index': {
const children = await getPropertyChildren(action.creatureId, prop);
if (!children.length) {
return applyAfterTasksSkipChildren(action, prop, targets, userInput);
}
await recalculateCalculation(prop.condition, action, 'reduce', userInput);
if (!isFinite(prop.condition?.value)) {
result.appendLog({
name: 'Branch Error',
value: `Index did not resolve into a valid number, got \`${prop.condition?.value}\` instead`,
silenced: prop.silent,
}, targets);
return applyAfterTasksSkipChildren(action, prop, targets, userInput);
}
let index = Math.floor(prop.condition?.value);
if (index < 1) index = 1;
if (index > children.length) index = children.length;
const child = children[index - 1];
return applyAfterPropTasksForSingleChild(action, prop, child, targets, userInput);
}
case 'hit': {
const scope = await getEffectiveActionScope(action);
if (scope['~attackHit']?.value) {
if (!targets.length && !prop.silent) {
result.appendLog({
value: '**On hit**',
silenced: prop.silent,
}, targets);
}
return applyDefaultAfterPropTasks(action, prop, targets, userInput);
} else {
return applyAfterTasksSkipChildren(action, prop, targets, userInput);
}
}
case 'miss': {
const scope = await getEffectiveActionScope(action);
if (scope['~attackMiss']?.value) {
if (!targets.length && !prop.silent) {
result.appendLog({
value: '**On miss**',
silenced: prop.silent,
}, targets);
}
return applyDefaultAfterPropTasks(action, prop, targets, userInput);
} else {
return applyAfterTasksSkipChildren(action, prop, targets, userInput);
}
}
case 'failedSave': {
const scope = await getEffectiveActionScope(action);
if (scope['~saveFailed']?.value) {
if (!targets.length && !prop.silent) {
result.appendLog({
value: '**On failed save**',
silenced: prop.silent,
}, targets);
}
return applyDefaultAfterPropTasks(action, prop, targets, userInput);
} else {
return applyAfterTasksSkipChildren(action, prop, targets, userInput);
}
}
case 'successfulSave': {
const scope = await getEffectiveActionScope(action);
if (scope['~saveSucceeded']?.value) {
if (!targets.length && !prop.silent) {
result.appendLog({
value: '**On save**',
silenced: prop.silent,
}, targets);
}
return applyDefaultAfterPropTasks(action, prop, targets, userInput);
} else {
return applyAfterTasksSkipChildren(action, prop, targets, userInput);
}
}
case 'random': {
const children = await getPropertyChildren(action.creatureId, prop);
if (children.length) {
const index = (await userInput.rollDice([{ number: 1, diceSize: children.length }]))[0][0];
const child = children[index - 1];
return applyAfterPropTasksForSingleChild(action, prop, child, targets, userInput);
} else {
return applyAfterTasksSkipChildren(action, prop, targets, userInput);
}
}
case 'eachTarget':
if (targets.length > 1) {
return applyTaskToEachTarget(action, task, targets, userInput);
}
return applyDefaultAfterPropTasks(action, prop, targets, userInput);
case 'choice': {
const children = await getPropertyChildren(action.creatureId, prop);
let choices: string[];
let chosenChildren: typeof children = [];
if (children.length) {
choices = await userInput.choose(children);
chosenChildren = filter(children, child => choices.includes(child._id));
}
if (!children.length || !chosenChildren.length) {
return applyAfterTasksSkipChildren(action, prop, targets, userInput);
}
return applyAfterPropTasksForSomeChildren(action, prop, chosenChildren, targets, userInput);
}
}
}

View File

@@ -0,0 +1,115 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, targetCreatureId, buffId
] = getRandomIds(100);
const actionTestCreature = {
_id: creatureId,
props: [
{
_id: buffId,
type: 'buff',
description: { text: 'This buff reduces AC of target by difference between the strength of caster {strength} and the target {~target.strength}' },
children: [
{
type: 'effect',
stats: ['armor'],
operation: 'add',
amount: { calculation: '~target.strength - strength' },
},
],
},
{
type: 'attribute',
attributeType: 'stat',
variableName: 'strength',
baseValue: { calculation: '18' },
},
],
};
const actionTargetCreature = {
_id: targetCreatureId,
props: [
{
type: 'attribute',
attributeType: 'stat',
variableName: 'armor',
baseValue: { calculation: '10' },
},
{
type: 'attribute',
attributeType: 'ability',
variableName: 'strength',
baseValue: { calculation: '12' },
},
],
};
describe('Apply Buff Properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
await createTestCreature(actionTargetCreature);
});
it('Applies a buff and freezes some variables', async function () {
const action = await runActionById(buffId, [targetCreatureId]);
const mutations = allMutations(action);
// Get random Ids of inserted props
const insertedBuffId = mutations?.[1]?.inserts?.[0]?._id;
const insertedEffectId = mutations?.[1]?.inserts?.[1]?._id;
assert.deepEqual(mutations, [{
contents: [{
name: 'Buff',
// TODO Make target strength available in action scope to fix: 'target 0' -> 'target 12'
value: 'This buff reduces AC of target by difference between the strength of caster 18 and the target 0',
}],
targetIds: [targetCreatureId],
}, {
contents: [],
inserts: [{
_id: insertedBuffId,
type: 'buff',
description: {
text: 'This buff reduces AC of target by difference between the strength of caster {18} and the target {strength}'
},
left: 1,
right: 4,
parentId: null,
root: {
collection: 'creatures',
id: targetCreatureId,
},
tags: [],
target: 'target',
}, {
_id: insertedEffectId,
type: 'effect',
stats: ['armor'],
operation: 'add',
amount: { calculation: 'strength - 18' },
left: 2,
right: 3,
parentId: insertedBuffId,
root: {
collection: 'creatures',
id: targetCreatureId,
},
tags: [],
}],
targetIds: [targetCreatureId],
}]);
});
});

View File

@@ -0,0 +1,165 @@
import { get } from 'lodash';
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import { getPropertyDescendants } from '/imports/api/engine/loadCreatures';
import resolve from '/imports/parser/resolve';
import map from '/imports/parser/map';
import toString from '/imports/parser/toString';
import computedSchemas from '/imports/api/properties/computedOnlyPropertySchemasIndex.js';
import applyFnToKey, { applyFnToKeyAsync } from '/imports/api/engine/computation/utility/applyFnToKey';
import accessor from '/imports/parser/parseTree/accessor';
import TaskResult, { Mutation } from '/imports/api/engine/action/tasks/TaskResult';
import { getEffectiveActionScope } from '/imports/api/engine/action/functions/getEffectiveActionScope';
import cyrb53 from '/imports/api/engine/computation/utility/cyrb53';
import { renewDocIds } from '/imports/api/parenting/parentingFunctions';
import { cleanProps } from '/imports/api/creature/creatureProperties/methods/copyPropertyToLibrary';
import recalculateInlineCalculations from '/imports/api/engine/action/functions/recalculateInlineCalculations';
import getPropertyTitle from '/imports/api/utility/getPropertyTitle';
import INLINE_CALCULATION_REGEX from '/imports/constants/INLINE_CALCULATION_REGEX';
import { applyAfterTasksSkipChildren } from '/imports/api/engine/action/functions/applyTaskGroups';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
export default async function applyBuffProperty(
task: PropTask, action: EngineAction, result: TaskResult, userInput: InputProvider
) {
const prop = EJSON.clone(task.prop);
const targetIds = prop.target === 'self' ? [action.creatureId] : task.targetIds;
// Get the buff and its descendants
const propList = [
EJSON.clone(prop),
...getPropertyDescendants(action.creatureId, prop._id),
];
// Crystalize the variables
if (!prop.skipCrystalization) {
await crystalizeVariables(action, propList, task, result);
}
targetIds.forEach(target => {
// Create a per-target mutation
const mutation: Mutation = { targetIds: [target], contents: [] };
// Create a per-target copy of the propList
let targetPropList = EJSON.clone(propList);
// Give the properties new IDs as descendants of the target
renewDocIds({
docArray: targetPropList,
idMap: {
[prop.parentId]: null,
[prop.root.id]: target,
},
collectionMap: { [prop.root.collection]: 'creatures' }
});
//Log the buff
let logValue = prop.description?.value
if (prop.description?.text) {
recalculateInlineCalculations(prop.description, action, 'reduce', userInput);
logValue = prop.description?.value;
}
result.appendLog({
name: getPropertyTitle(prop),
value: logValue,
silenced: prop.silent,
}, [target]);
// remove all the computed fields
targetPropList = cleanProps(targetPropList);
// Insert the props in the mutation
mutation.inserts = targetPropList;
// Add the mutation to the results
result.mutations.push(mutation);
});
applyAfterTasksSkipChildren(action, prop, targetIds, userInput);
}
/**
* Replaces all variables with their resolved values
* except variables of the form `~target.thing.total` become `thing.total`
*/
async function crystalizeVariables(
action: EngineAction, propList: any[], task: PropTask, result: TaskResult
) {
const scope = await getEffectiveActionScope(action);
for (const prop of propList) {
if (prop._skipCrystalize) {
delete prop._skipCrystalize;
return;
}
// Iterate through all the calculations and crystalize them
for (const calcKey of computedSchemas[prop.type].computedFields()) {
await applyFnToKeyAsync(prop, calcKey, async (prop, key) => {
const calcObj = get(prop, key);
if (!calcObj?.parseNode) return;
calcObj.parseNode = await map(calcObj.parseNode, async node => {
// Skip nodes that aren't symbols or accessors
if (
node.parseType !== 'accessor'
) return node;
// Handle variables
if (node.parseType === 'accessor' && node.name === '~target') {
// strip ~target
if (node.path?.length > 0) {
const name = node.path.shift();
return accessor.create({
name,
path: node.path?.length ? node.path : undefined,
});
} else {
// Can't strip if there isn't anything in the path after ~target
result.appendLog({
name: 'Error',
value: 'Variable `~target` should not be used without a property: ~target.property',
silenced: prop.silent,
}, task.targetIds);
}
return node;
} else {
// Resolve all other variables
const { result: nodeResult, context } = await resolve('reduce', node, scope);
result.appendParserContextErrors(context, task.targetIds);
return nodeResult;
}
});
calcObj.calculation = toString(calcObj.parseNode);
calcObj.hash = cyrb53(calcObj.calculation);
});
}
// For each key in the schema
for (const calcKey of computedSchemas[prop.type].inlineCalculationFields()) {
// That ends in .inlineCalculations
applyFnToKey(prop, calcKey, (prop, key) => {
const inlineCalcObj = get(prop, key);
if (!inlineCalcObj) return;
// If there is no text, skip
if (!inlineCalcObj.text) {
return;
}
// Replace all the existing calculations
let index = -1;
inlineCalcObj.text = inlineCalcObj.text.replace(INLINE_CALCULATION_REGEX, () => {
index += 1;
return `{${inlineCalcObj.inlineCalculations[index].calculation}}`;
});
// Set the value to the uncomputed string
inlineCalcObj.value = inlineCalcObj.text;
// Write a new hash
const inlineCalcHash = cyrb53(inlineCalcObj.text);
if (inlineCalcHash === inlineCalcObj.hash) {
// Skip if nothing changed
return;
}
inlineCalcObj.hash = inlineCalcHash;
});
}
}
}

View File

@@ -0,0 +1,97 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, otherCreatureId, buffId, removeParentBuffId, removeTargetBuffsId,
] = getRandomIds(100);
const actionTestCreature = {
_id: creatureId,
props: [
{
_id: buffId,
type: 'buff',
description: { text: 'This buff reduces AC of target by difference between the strength of caster {strength} and the target {~target.strength}' },
tags: ['some buff'],
children: [
{
type: 'effect',
stats: ['armor'],
operation: 'add',
amount: { calculation: '~target.strength - strength' },
},
{
_id: removeParentBuffId,
type: 'buffRemover',
targetParentBuff: true,
target: 'self',
},
],
},
{
type: 'attribute',
attributeType: 'stat',
variableName: 'strength',
baseValue: { calculation: '18' },
},
],
};
const actionOtherCreature = {
_id: otherCreatureId,
props: [
{
_id: removeTargetBuffsId,
type: 'buffRemover',
target: 'target',
targetTags: ['some buff']
},
],
};
describe('Apply Buff Remover Properties', function () {
// Increase timeout
this.timeout(8000);
beforeEach(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
await createTestCreature(actionOtherCreature);
});
it('removes a parent buff', async function () {
const action = await runActionById(removeParentBuffId);
const mutations = allMutations(action);
assert.deepEqual(mutations, [{
contents: [{
name: 'Removed',
value: 'Buff',
}],
removals: [{
propId: buffId,
}],
targetIds: []
}]);
});
it('removes a tag targeted buff', async function () {
const action = await runActionById(removeTargetBuffsId, [creatureId]);
const mutations = allMutations(action);
assert.deepEqual(mutations, [{
contents: [{
name: 'Removed',
value: 'Buff',
}],
removals: [{
propId: buffId,
}],
targetIds: [creatureId]
}]);
});
});

View File

@@ -0,0 +1,117 @@
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import TaskResult from 'imports/api/engine/action/tasks/TaskResult';
import getPropertyTitle from '/imports/api/utility/getPropertyTitle';
import { findLast, filter, difference, intersection } from 'lodash';
import { getPropertiesOfType, getPropertyAncestors } from '/imports/api/engine/loadCreatures';
import getEffectivePropTags from '/imports/api/engine/computation/utility/getEffectivePropTags';
import { applyDefaultAfterPropTasks, applyTaskToEachTarget } from '/imports/api/engine/action/functions/applyTaskGroups';
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
export default async function applyBuffRemoverProperty(
task: PropTask, action: EngineAction, result: TaskResult, userInput: InputProvider
) {
const prop = task.prop;
const targetIds = prop.target === 'self' ? [action.creatureId] : task.targetIds;
if (prop.name) {
// Log Name
result.appendLog({
name: getPropertyTitle(prop),
silenced: prop.silent,
}, task.targetIds)
}
if (targetIds.length > 1) {
return applyTaskToEachTarget(action, task, targetIds, userInput);
}
if (targetIds.length !== 1) {
throw 'At this step, only a single target is supported'
}
const targetId = targetIds[0];
// Remove buffs
if (prop.targetParentBuff) {
// Remove nearest ancestor buff
const ancestors = getPropertyAncestors(action.creatureId, prop._id);
const nearestBuff = findLast(ancestors, ancestor => ancestor.type === 'buff');
if (!nearestBuff) {
result.appendLog({
name: 'Error',
value: 'Buff remover does not have a parent buff to remove',
silenced: prop.silent,
}, [targetId]);
return;
}
removeBuff(nearestBuff, prop, result);
} else {
// Get all the buffs targeted by tags
const allBuffs = getPropertiesOfType(targetId, 'buff');
const targetedBuffs = filter(allBuffs, buff => {
if (buff.inactive) return false;
if (buffRemoverMatchTags(prop, buff)) return true;
});
// Remove the buffs
if (prop.removeAll) {
// Remove all matching buffs
targetedBuffs.forEach(buff => {
removeBuff(buff, prop, result);
});
} else {
// Sort in reverse order
targetedBuffs.sort((a, b) => b.order - a.order);
// Remove the one with the highest order
const buff = targetedBuffs[0];
if (buff) {
removeBuff(buff, prop, result);
}
}
}
return applyDefaultAfterPropTasks(action, prop, task.targetIds, userInput);
}
function removeBuff(buff: any, prop, result: TaskResult) {
result.mutations.push({
targetIds: result.targetIds,
removals: [{ propId: buff._id }],
contents: [{
name: 'Removed',
value: `${buff.name || 'Buff'}`,
...prop.silent && { silenced: true },
}],
});
}
function buffRemoverMatchTags(buffRemover, prop) {
let matched = false;
const propTags = getEffectivePropTags(prop);
// Check the target tags
if (
!buffRemover.targetTags?.length ||
difference(buffRemover.targetTags, propTags).length === 0
) {
matched = true;
}
// Check the extra tags
buffRemover.extraTags?.forEach(extra => {
if (extra.operation === 'OR') {
if (matched) return;
if (
!extra.tags.length ||
difference(extra.tags, propTags).length === 0
) {
matched = true;
}
} else if (extra.operation === 'NOT') {
if (
extra.tags.length &&
intersection(extra.tags, propTags)
) {
return false;
}
}
});
return matched;
}

View File

@@ -0,0 +1,31 @@
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import recalculateInlineCalculations from '/imports/api/engine/action/functions/recalculateInlineCalculations';
import getPropertyTitle from '/imports/api/utility/getPropertyTitle';
export default async function applyCreatureTemplateProperty(
task: PropTask, action: EngineAction, result, userInput
): Promise<void> {
const prop = task.prop;
//Log the Creature that is about to be summoned
let logValue = prop.description?.value
if (prop.description?.text) {
recalculateInlineCalculations(prop.description, action, 'reduce', userInput);
logValue = prop.description?.value;
}
// There are no targets for creature templates
// Creatures are always summoned as children of the action's creature
result.appendLog({
name: getPropertyTitle(prop),
value: logValue,
silenced: prop.silent,
}, []);
result.appendLog({
name: 'Warning',
value: 'Creature summoning is not yet implemented...',
silenced: prop.silent,
}, []);
return;
}

View File

@@ -0,0 +1,244 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, targetCreatureId, targetCreature2Id, damageTargetId, damageSelfId, targetCreatureHitPointsId, targetCreature2HitPointsId, selfHitPointsId, damageWithEffectsId, effectId, effect2Id,
] = getRandomIds(20);
const actionTestCreature = {
_id: creatureId,
props: [
{
_id: damageTargetId,
type: 'damage',
target: 'target',
amount: { calculation: '2d6 + 7' }
},
{
_id: damageSelfId,
type: 'damage',
target: 'self',
amount: { calculation: '1d12 + 7' }
},
{
_id: selfHitPointsId,
type: 'attribute',
name: 'Hit Points',
attributeType: 'healthBar',
variableName: 'hitPoints',
baseValue: { calculation: '20' },
},
{
_id: damageWithEffectsId,
type: 'damage',
target: 'target',
amount: { calculation: '1d13 + 3' },
tags: ['tag']
},
{
_id: effectId,
type: 'effect',
operation: 'add',
amount: { calculation: '1' },
targetByTags: true,
targetTags: ['tag'],
},
{
_id: effect2Id,
type: 'effect',
operation: 'mul',
amount: { calculation: '2' },
targetByTags: true,
targetTags: ['tag'],
},
],
}
const actionTargetCreature = {
_id: targetCreatureId,
props: [
{
_id: targetCreatureHitPointsId,
type: 'attribute',
name: 'Hit Points',
attributeType: 'healthBar',
variableName: 'hitPoints',
baseValue: { calculation: '33' },
}
]
}
const actionTargetCreature2 = {
_id: targetCreature2Id,
props: [
{
_id: targetCreature2HitPointsId,
type: 'attribute',
name: 'Hit Points',
attributeType: 'healthBar',
variableName: 'hitPoints',
baseValue: { calculation: '47' },
}
]
}
describe('Apply Damage Properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
await createTestCreature(actionTargetCreature);
await createTestCreature(actionTargetCreature2);
});
it('Damages self', async function () {
const action = await runActionById(damageSelfId);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [
{
inline: true,
name: 'Damage',
value: '1d12 [6] + 7',
}
],
targetIds: [creatureId],
}, {
contents: [{
inline: true,
name: 'Attribute damaged',
value: '13 Hit Points',
}],
updates: [
{
propId: selfHitPointsId,
type: 'attribute',
inc: { damage: 13, value: -13 },
},
],
targetIds: [creatureId],
}]);
});
it('Damages a single target', async function () {
const action = await runActionById(damageTargetId, [targetCreatureId]);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [
{
inline: true,
name: 'Damage',
value: '2d6 [3, 4] + 7',
}
],
targetIds: [targetCreatureId],
}, {
contents: [
{
inline: true,
name: 'Attribute damaged',
value: '14 Hit Points',
}
],
targetIds: [targetCreatureId],
updates: [
{
propId: targetCreatureHitPointsId,
type: 'attribute',
inc: { damage: 14, value: -14 },
},
],
}]);
});
it('Damages multiple targets', async function () {
const action = await runActionById(damageTargetId, [
targetCreatureId, targetCreature2Id
]);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [
{
inline: true,
name: 'Damage',
value: '2d6 [3, 4] + 7',
}
],
targetIds: [
targetCreatureId,
targetCreature2Id,
],
}, {
contents: [
{
inline: true,
name: 'Attribute damaged',
value: '14 Hit Points',
}
],
targetIds: [targetCreatureId],
updates: [
{
propId: targetCreatureHitPointsId,
type: 'attribute',
inc: { damage: 14, value: -14 },
},
],
}, {
contents: [
{
inline: true,
name: 'Attribute damaged',
value: '14 Hit Points',
}
],
targetIds: [targetCreature2Id],
updates: [
{
propId: targetCreature2HitPointsId,
type: 'attribute',
inc: { damage: 14, value: -14 },
},
],
}]);
});
it('Applies effects when doing damage', async function () {
const action = await runActionById(damageWithEffectsId, [targetCreatureId]);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [
{
inline: true,
name: 'Damage',
value: '(1d13 [7] + 4) * 2',
}
],
targetIds: [targetCreatureId],
}, {
contents: [
{
inline: true,
name: 'Attribute damaged',
value: '22 Hit Points',
}
],
targetIds: [targetCreatureId],
updates: [
{
propId: targetCreatureHitPointsId,
type: 'attribute',
inc: { damage: 22, value: -22 },
},
],
}]);
});
});

View File

@@ -0,0 +1,322 @@
import { some, includes, difference, intersection } from 'lodash';
import { getConstantValueFromScope } from '/imports/api/creature/creatures/CreatureVariables';
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import { applyDefaultAfterPropTasks } from '/imports/api/engine/action/functions/applyTaskGroups';
import { getEffectiveActionScope } from '/imports/api/engine/action/functions/getEffectiveActionScope';
import recalculateCalculation from '/imports/api/engine/action/functions/recalculateCalculation';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import TaskResult from '/imports/api/engine/action/tasks/TaskResult';
import { isFiniteNode } from '/imports/parser/parseTree/constant';
import resolve from '/imports/parser/resolve';
import toString from '/imports/parser/toString';
import { getPropertiesOfType } from '/imports/api/engine/loadCreatures';
import applyTask from '/imports/api/engine/action/tasks/applyTask';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
import getEffectivePropTags from '/imports/api/engine/computation/utility/getEffectivePropTags';
import Context from '/imports/parser/types/Context';
import applySavingThrowProperty from '/imports/api/engine/action/applyProperties/applySavingThrowProperty';
export default async function applyDamageProperty(
task: PropTask, action: EngineAction, result: TaskResult, inputProvider: InputProvider
) {
const prop = task.prop;
const scope = getEffectiveActionScope(action);
// Skip if there is no parse node to work with
if (!prop.amount?.parseNode) return;
// Choose target
const damageTargets = prop.target === 'self' ? [action.creatureId] : task.targetIds;
// Determine if the hit is critical
const criticalHit = await getConstantValueFromScope('~criticalHit', scope)
&& prop.damageType !== 'healing'; // Can't critically heal
// Double the damage rolls if the hit is critical
const context = new Context({
options: { doubleRolls: criticalHit },
});
// Gather all the lines we need to log into an array
const logValue: string[] = [];
const logName = prop.damageType === 'healing' ? 'Healing' : 'Damage';
// roll the dice only and store that string
await recalculateCalculation(prop.amount, action, 'compile', inputProvider);
const { result: rolled } = await resolve('roll', prop.amount.valueNode, scope, context, inputProvider);
if (rolled.parseType !== 'constant') {
logValue.push(toString(rolled));
}
result.appendParserContextErrors(context, damageTargets);
// Reset the errors so we don't log the same errors twice
context.errors = [];
// Resolve the roll to a final value
const { result: reduced } = await resolve('reduce', rolled, scope, context, inputProvider);
result.appendParserContextErrors(context, damageTargets);
// Store the result
let damage: number | undefined = undefined;
if (reduced.parseType === 'constant') {
prop.amount.value = reduced.value;
if (typeof reduced.value === 'number') {
damage = reduced.value;
}
} else if (reduced.parseType === 'error') {
prop.amount.value = null;
} else {
prop.amount.value = toString(reduced);
}
// If we didn't end up with damage of finite amount, give up
if (
typeof damage !== 'number'
|| !isFinite(damage)
) {
return applyDefaultAfterPropTasks(action, prop, damageTargets, inputProvider);
}
// Round the damage to a whole number
damage = Math.floor(damage);
scope['~damage'] = { value: damage };
// Convert extra damage into the stored type
const lastDamageType = await getConstantValueFromScope('~lastDamageType', scope);
if (prop.damageType === 'extra' && typeof lastDamageType === 'string') {
prop.damageType = lastDamageType;
}
// Store current damage type
if (prop.damageType !== 'healing') {
scope['~lastDamageType'] = { value: prop.damageType };
}
// Memoise the damage suffix for the log
const suffix = (criticalHit ? ' critical ' : ' ') +
prop.damageType +
(prop.damageType !== 'healing' ? ' damage ' : '');
// If there is a save, calculate the save damage
let damageOnSave, saveProp, saveRoll;
if (prop.save) {
if (prop.save.damageFunction?.calculation) {
await recalculateCalculation(prop.save.damageFunction, action, 'compile', inputProvider);
context.errors = [];
const { result: saveDamageRolled } = await resolve(
'roll', prop.save.damageFunction.valueNode, scope, context, inputProvider
);
saveRoll = toString(saveDamageRolled);
const { result: saveDamageResult } = await resolve(
'reduce', saveDamageRolled, scope, context, inputProvider
);
result.appendParserContextErrors(context, damageTargets);
// If we didn't end up with a constant of finite amount, give up
if (
!isFiniteNode(saveDamageResult)
) {
return applyDefaultAfterPropTasks(action, prop, damageTargets, inputProvider);
}
// Round the damage to a whole number
damageOnSave = Math.floor(saveDamageResult.value);
} else {
damageOnSave = Math.floor(damage / 2);
}
saveProp = {
node: {
...prop.save,
name: prop.save.stat,
silent: prop.silent,
},
children: [],
}
}
if (damageTargets && damageTargets.length) {
// Iterate through all the targets
for (const target of damageTargets) {
let damageToApply = damage || 0;
// If there is a saving throw, apply that first
if (prop.save) {
await applySavingThrowProperty({
prop: saveProp,
targetIds: task.targetIds,
}, action, result, inputProvider);
if (await getConstantValueFromScope('~saveSucceeded', scope)) {
// Log the total damage
logValue.push(toString(reduced));
// Log the save damage
const damageText = damageFunctionText(prop.save);
if (damageText) {
logValue.push(damageText);
} else {
logValue.push(
'**Damage on successful save**',
prop.save.damageFunction.calculation,
saveRoll
);
}
damageToApply = damageOnSave;
}
}
// Apply weaknesses/resistances/immunities
damageToApply = applyDamageMultipliers({
target,
damage: damageToApply,
damageProp: prop,
logValue
});
// Deal the damage to the target
await dealDamage(
action, prop, result, inputProvider, target, prop.damageType, damageToApply
);
}
} else {
// There are no targets, just log the result
logValue.push(`**${damage}** ${suffix}`);
if (prop.save) {
await applySavingThrowProperty(saveProp, action, result, inputProvider);
await applySavingThrowProperty({
prop: saveProp,
targetIds: task.targetIds,
}, action, result, inputProvider);
logValue.push(`**${damageOnSave}** ${suffix} on a successful save`);
}
}
if (logValue.length) result.appendLog({
name: logName,
value: logValue.join('\n'),
inline: true,
silenced: prop.silent,
}, damageTargets);
return applyDefaultAfterPropTasks(action, prop, damageTargets, inputProvider);
}
function damageFunctionText(save) {
if (!save) return;
if (!save.damageFunction) {
return '**Half damage on successful save**';
}
if (save.damageFunction.calculation == '0' || save.damageFunction.value === 0) {
return '**No damage on successful save**'
}
}
function applyDamageMultipliers({ target, damage, damageProp, logValue }) {
const damageType = damageProp?.damageType;
if (!damageType) return damage;
const multiplier = target?.variables?.[damageType];
if (!multiplier) return damage;
const damageTypeText = damageType == 'healing' ? 'healing' : `${damageType} damage`;
if (
multiplier.immunity &&
some(multiplier.immunities, multiplierAppliesTo(damageProp, 'immunity'))
) {
logValue.push(`Immune to ${damageTypeText}`);
return 0;
} else {
if (
multiplier.resistance &&
some(multiplier.resistances, multiplierAppliesTo(damageProp, 'resistance'))
) {
logValue.push(`Resistant to ${damageTypeText}`);
damage = Math.floor(damage / 2);
}
if (
multiplier.vulnerability &&
some(multiplier.vulnerabilities, multiplierAppliesTo(damageProp, 'vulnerability'))
) {
logValue.push(`Vulnerable to ${damageTypeText}`);
damage = Math.floor(damage * 2);
}
}
return damage;
}
function multiplierAppliesTo(damageProp, multiplierType) {
return multiplier => {
// Apply the default 'ignore x' tags
const effectiveTags = getEffectivePropTags(damageProp);
if (includes(effectiveTags, `ignore ${multiplierType}`)) return false;
const hasRequiredTags = difference(
multiplier.includeTags, effectiveTags
).length === 0;
const hasNoExcludedTags = intersection(
multiplier.excludeTags, effectiveTags
).length === 0;
return hasRequiredTags && hasNoExcludedTags;
}
}
async function dealDamage(
action: EngineAction, prop: any, result: TaskResult, userInput: InputProvider,
targetId: string, damageType: string, amount: number
) {
// Get all the health bars and do damage to them
let healthBars = getPropertiesOfType(targetId, 'attribute');
// Keep only the healthbars that can take damage/healing
healthBars = healthBars.filter((bar) => {
if (bar.attributeType !== 'healthBar' || bar.inactive || bar.removed || bar.overridden) {
return false;
}
if (damageType === 'healing' && bar.healthBarNoHealing) {
return false;
}
if (damageType !== 'healing' && amount >= 0 && bar.healthBarNoDamage) {
return false;
}
return true;
});
// Sort healthbars by damage/healing order or tree order as a fallback
healthBars.sort((a, b) => {
let diff;
if (amount >= 0) {
diff = a.healthBarDamageOrder - b.healthBarDamageOrder;
} else {
diff = a.healthBarHealingOrder - b.healthBarHealingOrder;
}
if (Number.isFinite(diff)) {
return diff;
} else {
return a.order - b.order;
}
});
// Deal the damage to each healthbar in order until all damage is done
const totalDamage = amount;
let damageLeft = totalDamage;
if (damageType === 'healing') damageLeft = -totalDamage;
for (const healthBar of healthBars) {
if (damageLeft === 0) return;
// Do the damage
const damageAdded = await applyTask(action, {
targetIds: [targetId],
subtaskFn: 'damageProp',
params: {
operation: 'increment',
value: +damageLeft || 0,
targetProp: healthBar,
},
}, userInput);
damageLeft -= damageAdded;
// Prevent overflow
if (
damageType === 'healing' ?
healthBar.healthBarNoHealingOverflow :
healthBar.healthBarNoDamageOverflow
) {
damageLeft = 0;
}
}
return totalDamage;
}

View File

@@ -0,0 +1,49 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, folderId
] = getRandomIds(100);
const actionTestCreature = {
_id: creatureId,
props: [
{
_id: folderId,
type: 'folder',
children: [{
type: 'note',
summary: { text: 'this should run' },
}],
},
],
}
describe('Apply folder properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
});
it('Applies the children of the folder', async function () {
const action = await runActionById(folderId);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [
{
value: 'this should run'
}
],
targetIds: [],
}]);
});
});

View File

@@ -0,0 +1,11 @@
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import { applyDefaultAfterPropTasks } from '/imports/api/engine/action/functions/applyTaskGroups';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
export default async function applyFolderProperty(
task: PropTask, action: EngineAction, result, userInput
): Promise<void> {
const prop = task.prop;
return applyDefaultAfterPropTasks(action, prop, task.targetIds, userInput);
}

View File

@@ -0,0 +1,48 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, noteId
] = getRandomIds(2);
const actionTestCreature = {
_id: creatureId,
props: [
{
_id: noteId,
type: 'note',
name: 'Note Name',
summary: { text: 'Note summary {1 + 2}' }
},
],
}
describe('Apply note properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
});
it('Applies the note text', async function () {
const action = await runActionById(noteId);
assert.exists(action);
assert.deepEqual(allMutations(action), [{
contents: [
{
name: 'Note Name',
value: 'Note summary 3'
}
],
targetIds: [],
}]);
});
});

View File

@@ -0,0 +1,33 @@
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
import { applyDefaultAfterPropTasks } from '/imports/api/engine/action/functions/applyTaskGroups';
import recalculateInlineCalculations from '/imports/api/engine/action/functions/recalculateInlineCalculations';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import TaskResult, { LogContent } from '/imports/api/engine/action/tasks/TaskResult';
export default async function applyNoteProperty(
task: PropTask, action: EngineAction, result: TaskResult, inputProvider: InputProvider
): Promise<void> {
const prop = task.prop;
const logContent: LogContent & { silenced: boolean } = {
silenced: prop.silent,
};
if (prop.name) logContent.name = prop.name;
if (prop.summary?.text) {
await recalculateInlineCalculations(prop.summary, action, 'reduce', inputProvider);
logContent.value = prop.summary.value;
}
if (logContent.name || logContent.value) {
result.appendLog(logContent, task.targetIds);
}
// Log description
if (prop.description?.text) {
await recalculateInlineCalculations(prop.description, action, 'reduce', inputProvider);
result.appendLog({
value: prop.description.value,
silenced: prop.silent,
}, task.targetIds);
}
return applyDefaultAfterPropTasks(action, prop, task.targetIds, inputProvider);
}

View File

@@ -0,0 +1,53 @@
import { assert } from 'chai';
import {
allLogContent,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, rollId,
] = getRandomIds(2);
const actionTestCreature = {
_id: creatureId,
props: [
{
_id: rollId,
type: 'roll',
name: 'Roll Name',
variableName: 'roll1',
roll: { calculation: '7 + 15' },
children: [
{
type: 'note',
summary: { text: 'roll: {roll1}' },
},
],
},
],
};
describe('Apply roll properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
});
it('Saves the value of the roll into the variable name', async function () {
const action = await runActionById(rollId);
assert.exists(action);
assert.deepEqual(allLogContent(action), [{
inline: true,
name: 'Roll Name',
value: '**22**',
}, {
value: 'roll: 22',
}]);
});
});

View File

@@ -0,0 +1,64 @@
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
import { applyDefaultAfterPropTasks } from '/imports/api/engine/action/functions/applyTaskGroups';
import { rollAndReduceCalculation } from '/imports/api/engine/action/functions/recalculateCalculation';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import TaskResult from '/imports/api/engine/action/tasks/TaskResult';
import { isFiniteNode } from '/imports/parser/parseTree/constant';
import toString from '/imports/parser/toString';
export default async function applyRollProperty(
task: PropTask, action: EngineAction, result: TaskResult, inputProvider: InputProvider
): Promise<void> {
const prop = task.prop;
// If there isn't a calculation, just apply the children instead
if (!prop.roll?.calculation) {
return applyDefaultAfterPropTasks(action, prop, task.targetIds, inputProvider);
}
const logValue: string[] = [];
// roll the dice only and store that string
const {
rolled, reduced, errors
} = await rollAndReduceCalculation(prop.roll, action, inputProvider);
if (rolled.parseType !== 'constant') {
logValue.push(toString(rolled));
}
errors?.forEach(error => {
result.appendLog({
name: 'Error',
value: error.message,
silenced: prop.silent,
}, task.targetIds);
});
// Store the result
if (reduced.parseType === 'constant') {
prop.roll.value = reduced.value;
} else if (reduced.parseType === 'error') {
prop.roll.value = null;
} else {
prop.roll.value = toString(reduced);
}
// If we didn't end up with a constant or a number of finite value, give up
if (reduced?.parseType !== 'constant' || !isFiniteNode(reduced)) {
return applyDefaultAfterPropTasks(action, prop, task.targetIds, inputProvider);
}
const value = reduced.value;
result.scope[prop.variableName] = { value };
logValue.push(`**${value}**`);
result.appendLog({
name: prop.name,
value: logValue.join('\n'),
inline: true,
silenced: prop.silent,
}, task.targetIds);
// Apply children
return applyDefaultAfterPropTasks(action, prop, task.targetIds, inputProvider);
}

View File

@@ -0,0 +1,114 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, savingThrowId, targetCreatureId, targetCreature2Id
] = getRandomIds(4);
const actionTestCreature = {
_id: creatureId,
props: [
{
_id: savingThrowId,
type: 'savingThrow',
name: 'Strength Save',
dc: { calculation: '10 + 3' },
stat: 'strengthSave',
children: [{
type: 'branch',
branchType: 'successfulSave',
children: [{
type: 'note',
summary: { text: 'note to apply on save' },
}],
}, {
type: 'branch',
branchType: 'failedSave',
children: [{
type: 'note',
summary: { text: 'note to apply on failed save' },
}],
}],
},
],
}
const actionTargetCreature = {
_id: targetCreatureId,
props: [
{
type: 'skill',
variableName: 'strengthSave',
baseValue: { calculation: '3' },
},
],
}
const actionTargetCreature2 = {
_id: targetCreature2Id,
props: [
{
type: 'skill',
variableName: 'strengthSave',
baseValue: { calculation: '2' },
},
],
}
describe('Apply saving throw properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
await createTestCreature(actionTargetCreature);
await createTestCreature(actionTargetCreature2);
});
it('Makes multiple creatures make saves', async function () {
const action = await runActionById(savingThrowId, [targetCreatureId, targetCreature2Id]);
assert.exists(action);
assert.deepEqual(allMutations(action), [
{
'contents': [{
'inline': true,
'name': 'Strength Save',
'value': 'DC **13**',
}, {
'inline': true,
'name': 'Successful save',
'value': '1d20 [ 10 ] + 3\n**13**',
}],
'targetIds': [targetCreatureId],
}, {
'contents': [{
'value': 'note to apply on save',
}],
'targetIds': [targetCreatureId],
}, {
'contents': [{
'inline': true,
'name': 'Strength Save',
'value': 'DC **13**',
}, {
'inline': true,
'name': 'Failed save',
'value': '1d20 [ 10 ] + 2\n**12**',
}],
'targetIds': [targetCreature2Id],
}, {
'contents': [{
'value': 'note to apply on failed save',
}],
'targetIds': [targetCreature2Id],
},
],
);
});
});

View File

@@ -0,0 +1,115 @@
import { getFromScope } from '/imports/api/creature/creatures/CreatureVariables';
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
import { applyDefaultAfterPropTasks, applyTaskToEachTarget } from '/imports/api/engine/action/functions/applyTaskGroups';
import getPropertyTitle from '/imports/api/utility/getPropertyTitle';
import recalculateCalculation from '/imports/api/engine/action/functions/recalculateCalculation';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import TaskResult from '/imports/api/engine/action/tasks/TaskResult';
import { getVariables } from '/imports/api/engine/loadCreatures';
import numberToSignedString from '/imports/api/utility/numberToSignedString';
import { isFiniteNode } from '/imports/parser/parseTree/constant';
export default async function applySavingThrowProperty(
task: PropTask, action: EngineAction, result: TaskResult, inputProvider: InputProvider
): Promise<void> {
const prop = task.prop;
const saveTargetIds = prop.target === 'self' ? [action.creatureId] : task.targetIds;
if (saveTargetIds.length > 1) {
return applyTaskToEachTarget(action, task, saveTargetIds, inputProvider);
}
recalculateCalculation(prop.dc, action, 'reduce', inputProvider);
if (!isFiniteNode(prop.dc?.valueNode)) {
result.appendLog({
name: 'Error',
value: 'Saving throw requires a DC',
silenced: prop.silent,
}, saveTargetIds);
return applyDefaultAfterPropTasks(action, prop, saveTargetIds, inputProvider);
}
const dc = (prop.dc?.value);
result.appendLog({
name: getPropertyTitle(prop),
value: `DC **${dc}**`,
inline: true,
silenced: prop.silent,
}, saveTargetIds);
const targetId = saveTargetIds[0];
// If there are no save targets, apply all children as if the save both
// succeeded and failed
if (!targetId) {
console.warn('no target, returning early');
result.pushScope = {
['~saveFailed']: { value: true },
['~saveSucceeded']: { value: true },
}
return applyDefaultAfterPropTasks(action, prop, saveTargetIds, inputProvider);
}
// Each target makes the saving throw
const save = getFromScope(prop.stat, getVariables(targetId));
if (!save) {
result.appendLog({
name: 'Saving throw error',
value: 'No saving throw found: ' + prop.stat,
silenced: prop.silent,
}, [targetId]);
return applyDefaultAfterPropTasks(action, prop, [targetId], inputProvider);
}
const rollModifierText = numberToSignedString(save.value, true);
const rollModifier = save.value;
let value, resultPrefix;
if (save.advantage === 1) {
const [[a, b]] = await inputProvider.rollDice([{ number: 2, diceSize: 20 }]);
if (a >= b) {
value = a;
resultPrefix = `Advantage\n1d20 [ ${a}, ~~${b}~~ ] ${rollModifierText}`;
} else {
value = b;
resultPrefix = `Advantage\n1d20 [ ~~${a}~~, ${b} ] ${rollModifierText}`;
}
} else if (save.advantage === -1) {
const [[a, b]] = await inputProvider.rollDice([{ number: 2, diceSize: 20 }]);
if (a <= b) {
value = a;
resultPrefix = `Disadvantage\n1d20 [ ${a}, ~~${b}~~ ] ${rollModifierText}`;
} else {
value = b;
resultPrefix = `Disadvantage\n1d20 [ ~~${a}~~, ${b} ] ${rollModifierText}`;
}
} else {
const [[rolledValue]] = await inputProvider.rollDice([{ number: 1, diceSize: 20 }]);
value = rolledValue;
resultPrefix = `1d20 [ ${value} ] ${rollModifierText}`
}
result.pushScope = {};
result.pushScope['~saveDiceRoll'] = { value };
const resultValue = value + rollModifier || 0;
result.pushScope['~saveRoll'] = { value: resultValue };
const saveSuccess = resultValue >= dc;
if (saveSuccess) {
result.pushScope['~saveSucceeded'] = { value: true };
result.pushScope['~saveFailed'] = { value: false };
} else {
result.pushScope['~saveFailed'] = { value: true };
result.pushScope['~saveSucceeded'] = { value: false };
}
result.appendLog({
name: saveSuccess ? 'Successful save' : 'Failed save',
value: resultPrefix + '\n**' + resultValue + '**',
inline: true,
silenced: prop.silent,
}, [targetId]);
return applyDefaultAfterPropTasks(action, prop, [targetId], inputProvider);
}

View File

@@ -0,0 +1,63 @@
import { assert } from 'chai';
import {
allMutations,
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, trueToggleId, falseToggleId,
] = getRandomIds(3);
const actionTestCreature = {
_id: creatureId,
props: [
{
_id: trueToggleId,
type: 'toggle',
condition: { calculation: 'true' },
children: [
{
type: 'note',
summary: { text: 'this should run' },
},
],
},
{
_id: falseToggleId,
type: 'toggle',
condition: { calculation: 'false' },
children: [
{
type: 'note',
summary: { text: 'this should not run' },
},
],
},
],
}
describe('Apply Toggle Properties', function () {
// Increase timeout
this.timeout(8000);
before(async function () {
await removeAllCreaturesAndProps();
await createTestCreature(actionTestCreature);
});
// If branch
it('Runs a toggle with a true condition', async function () {
const action = await runActionById(trueToggleId);
assert.deepEqual(allMutations(action), [{
contents: [{ value: 'this should run' }],
targetIds: [],
}]);
});
it('runs a toggle with a false condition', async function () {
const action = await runActionById(falseToggleId);
assert.deepEqual(allMutations(action), []);
});
});

View File

@@ -0,0 +1,19 @@
import { EngineAction } from '/imports/api/engine/action/EngineActions';
import InputProvider from '/imports/api/engine/action/functions/userInput/InputProvider';
import { applyAfterTasksSkipChildren, applyDefaultAfterPropTasks } from '/imports/api/engine/action/functions/applyTaskGroups';
import recalculateCalculation from '/imports/api/engine/action/functions/recalculateCalculation';
import { PropTask } from '/imports/api/engine/action/tasks/Task';
import TaskResult from '/imports/api/engine/action/tasks/TaskResult';
export default async function applyToggle(
task: PropTask, action: EngineAction, result: TaskResult, inputProvider: InputProvider
): Promise<void> {
const prop = task.prop;
await recalculateCalculation(prop.condition, action, 'reduce', inputProvider);
if (prop.condition?.value) {
return applyDefaultAfterPropTasks(action, prop, task.targetIds, inputProvider);
} else {
return applyAfterTasksSkipChildren(action, prop, task.targetIds, inputProvider);
}
}

Some files were not shown because too many files have changed in this diff Show More