From d926a14194db28bcefb22689a6c5ac12403de5d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Richard=20Sim=C3=B5es?= Date: Tue, 18 Apr 2023 00:08:34 -0500 Subject: [PATCH] Create global foundry module from single file --- .eslintrc.json | 11 +- src/module/rules/rule-element/base.ts | 2 +- types/foundry/.eslintrc.json | 11 + .../document-sheet/index.d.ts | 30 +- .../application/form-application/index.d.ts | 16 +- types/foundry/client/apps/sidebar/index.d.ts | 4 +- types/foundry/client/core/index.d.ts | 24 +- .../client/documents/active-effect.d.ts | 2 +- types/foundry/client/documents/actor.d.ts | 2 +- .../documents/ambient-light-document.d.ts | 2 +- .../documents/ambient-sound-document.d.ts | 2 +- types/foundry/client/documents/cards.d.ts | 2 +- .../client/documents/chat-message.d.ts | 2 +- .../client/documents/client-document.d.ts | 2 +- types/foundry/client/documents/combat.d.ts | 2 +- types/foundry/client/documents/combatant.d.ts | 2 +- .../client/documents/drawing-document.d.ts | 2 +- .../client/documents/fog-exploration.d.ts | 2 +- types/foundry/client/documents/folder.d.ts | 4 +- types/foundry/client/documents/index.d.ts | 56 +- types/foundry/client/documents/item.d.ts | 2 +- .../client/documents/journal-entry-page.d.ts | 2 +- .../client/documents/journal-entry.d.ts | 2 +- types/foundry/client/documents/macro.d.ts | 2 +- .../documents/measured-template-document.d.ts | 2 +- .../client/documents/note-document.d.ts | 2 +- .../client/documents/playlist-sound.d.ts | 2 +- types/foundry/client/documents/playlist.d.ts | 2 +- .../foundry/client/documents/roll-table.d.ts | 2 +- types/foundry/client/documents/scene.d.ts | 2 +- .../client/documents/table-result.d.ts | 2 +- .../client/documents/tile-document.d.ts | 2 +- .../client/documents/token-document.d.ts | 2 +- types/foundry/client/documents/user.d.ts | 2 +- .../client/documents/wall-document.d.ts | 2 +- types/foundry/client/index.d.ts | 14 + types/foundry/client/keyboard/index.d.ts | 4 +- types/foundry/client/pixi/core/index.d.ts | 4 +- .../client/pixi/core/interaction/index.d.ts | 2 +- .../client/pixi/core/shapes/index.d.ts | 4 +- types/foundry/client/pixi/grid/index.d.ts | 6 +- types/foundry/client/pixi/groups/index.d.ts | 6 +- types/foundry/client/pixi/helpers/index.d.ts | 18 +- .../pixi/helpers/point-source/index.d.ts | 8 +- .../client/pixi/helpers/ray/index.d.ts | 4 +- types/foundry/client/pixi/index.d.ts | 12 +- .../foundry/client/pixi/perception/index.d.ts | 10 +- .../client/pixi/placeable-object/index.d.ts | 18 +- .../client/pixi/placeables-layer/index.d.ts | 18 +- .../pixi/placeables-layer/lighting-layer.d.ts | 2 +- .../client/pixi/special-effect/index.d.ts | 2 +- .../client/pixi/webgl/filters/index.d.ts | 2 +- types/foundry/client/pixi/webgl/index.d.ts | 6 +- .../client/pixi/webgl/shaders/index.d.ts | 2 +- types/foundry/client/roll-term/index.d.ts | 22 +- types/foundry/client/ui/index.d.ts | 16 +- types/foundry/client/ui/tour.d.ts | 2 +- types/foundry/common/abstract/data.d.mts | 239 ---- types/foundry/common/abstract/data.d.ts | 241 +++- types/foundry/common/abstract/document.d.ts | 1205 ++++++++--------- .../common/abstract/embedded-collection.d.mts | 5 +- .../common/abstract/embedded-collection.d.ts | 46 +- types/foundry/common/abstract/index.d.ts | 2 - types/foundry/common/abstract/module.d.ts | 6 +- types/foundry/common/data/data.d.ts | 156 +++ .../common/data/data/animation-data.d.ts | 15 - .../common/data/data/darkness-activation.d.ts | 13 - types/foundry/common/data/data/index.d.ts | 7 - .../foundry/common/data/data/light-data.d.ts | 72 - .../data/data/prototype-token-data.d.ts | 28 - .../common/data/data/texture-data.d.ts | 20 - .../common/data/data/tile-occlusion.d.ts | 15 - .../foundry/common/data/data/video-data.d.ts | 15 - types/foundry/common/data/fields.d.ts | 20 +- types/foundry/common/data/index.d.ts | 9 - types/foundry/common/data/module.d.ts | 5 +- types/foundry/common/data/validators.d.ts | 116 +- .../common/documents/active-effect.d.ts | 173 ++- types/foundry/common/documents/actor.d.ts | 225 +-- types/foundry/common/documents/adventure.d.ts | 127 +- .../common/documents/ambient-light.d.ts | 85 +- .../common/documents/ambient-sound.d.ts | 89 +- types/foundry/common/documents/card.d.ts | 13 + types/foundry/common/documents/cards.d.ts | 117 +- .../common/documents/chat-message.d.ts | 182 +-- types/foundry/common/documents/combat.d.ts | 116 +- types/foundry/common/documents/combatant.d.ts | 95 +- types/foundry/common/documents/drawing.d.ts | 161 ++- .../common/documents/fog-exploration.d.ts | 89 +- types/foundry/common/documents/folder.d.ts | 98 +- types/foundry/common/documents/index.d.ts | 27 - types/foundry/common/documents/item.d.ts | 182 +-- .../common/documents/journal-entry-page.d.ts | 167 ++- .../common/documents/journal-entry.d.ts | 108 +- types/foundry/common/documents/macro.d.ts | 105 +- .../common/documents/measured-template.d.ts | 145 +- types/foundry/common/documents/module.d.ts | 29 + types/foundry/common/documents/note.d.ts | 115 +- .../common/documents/playlist-sound.d.ts | 93 +- types/foundry/common/documents/playlist.d.ts | 96 +- .../foundry/common/documents/roll-table.d.ts | 120 +- types/foundry/common/documents/scene.d.ts | 354 ++--- types/foundry/common/documents/setting.d.ts | 11 + .../common/documents/table-result.d.ts | 113 +- types/foundry/common/documents/tile.d.ts | 109 +- types/foundry/common/documents/token.d.ts | 348 ++--- types/foundry/common/documents/user.d.ts | 144 +- types/foundry/common/documents/wall.d.ts | 69 +- types/foundry/common/index.d.ts | 6 - types/foundry/common/module.d.ts | 23 + types/foundry/common/types.d.ts | 40 +- types/foundry/common/utils/collection.d.ts | 216 ++- types/foundry/common/utils/color.d.ts | 294 ++-- types/foundry/common/utils/geometry.d.ts | 208 ++- types/foundry/common/utils/helpers.d.ts | 514 ++++--- types/foundry/common/utils/index.d.ts | 5 - types/foundry/common/utils/module.d.ts | 6 + types/foundry/index.d.ts | 138 +- types/foundry/tsconfig.json | 3 +- types/foundry/util.d.ts | 6 +- 120 files changed, 3967 insertions(+), 4024 deletions(-) create mode 100644 types/foundry/.eslintrc.json create mode 100644 types/foundry/client/index.d.ts delete mode 100644 types/foundry/common/abstract/data.d.mts delete mode 100644 types/foundry/common/abstract/index.d.ts create mode 100644 types/foundry/common/data/data.d.ts delete mode 100644 types/foundry/common/data/data/animation-data.d.ts delete mode 100644 types/foundry/common/data/data/darkness-activation.d.ts delete mode 100644 types/foundry/common/data/data/index.d.ts delete mode 100644 types/foundry/common/data/data/light-data.d.ts delete mode 100644 types/foundry/common/data/data/prototype-token-data.d.ts delete mode 100644 types/foundry/common/data/data/texture-data.d.ts delete mode 100644 types/foundry/common/data/data/tile-occlusion.d.ts delete mode 100644 types/foundry/common/data/data/video-data.d.ts delete mode 100644 types/foundry/common/data/index.d.ts create mode 100644 types/foundry/common/documents/card.d.ts delete mode 100644 types/foundry/common/documents/index.d.ts create mode 100644 types/foundry/common/documents/module.d.ts create mode 100644 types/foundry/common/documents/setting.d.ts delete mode 100644 types/foundry/common/index.d.ts create mode 100644 types/foundry/common/module.d.ts delete mode 100644 types/foundry/common/utils/index.d.ts create mode 100644 types/foundry/common/utils/module.d.ts diff --git a/.eslintrc.json b/.eslintrc.json index ed873c87099..5c4f8f59570 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -5,11 +5,12 @@ "jest/globals": true }, "extends": [ - "prettier", - "plugin:import/errors", "eslint:recommended", "plugin:@typescript-eslint/recommended", - "plugin:json/recommended" + "plugin:import/errors", + "plugin:import/typescript", + "plugin:json/recommended", + "prettier" ], "parserOptions": { "ecmaVersion": 2018, @@ -84,9 +85,7 @@ ] }, "eslint-import-resolver-typescript": true, - "typescript": { - "alwaysTryTypes": true - } + "typescript": true }, "import/parsers": { "@typescript-eslint/parser": [ diff --git a/src/module/rules/rule-element/base.ts b/src/module/rules/rule-element/base.ts index 49d84a89a13..d40a5712590 100644 --- a/src/module/rules/rule-element/base.ts +++ b/src/module/rules/rule-element/base.ts @@ -7,7 +7,7 @@ import { TokenDocumentPF2e } from "@scene/index.ts"; import { CheckRoll } from "@system/check/index.ts"; import { LaxSchemaField, PredicateField, SlugField } from "@system/schema-data-fields.ts"; import { isObject, tupleHasValue } from "@util"; -import type { DataModelValidationOptions } from "types/foundry/common/abstract/data.d.mts"; +import type { DataModelValidationOptions } from "types/foundry/common/abstract/data.d.ts"; import { BracketedValue, RuleElementData, RuleElementSchema, RuleElementSource, RuleValue } from "./data.ts"; const { DataModel } = foundry.abstract; diff --git a/types/foundry/.eslintrc.json b/types/foundry/.eslintrc.json new file mode 100644 index 00000000000..b2a49ab4e89 --- /dev/null +++ b/types/foundry/.eslintrc.json @@ -0,0 +1,11 @@ +{ + "rules": { + // follow foundry convention in commons module + "import/no-default-export": "off", + // import plugin doesn't understand multiple exports in type declarations + "import/export": "off", + // import plugin isn't wise to node16 module resolution + "import/no-unresolved": "off", + "no-var": "off" + } +} diff --git a/types/foundry/client/application/form-application/document-sheet/index.d.ts b/types/foundry/client/application/form-application/document-sheet/index.d.ts index 72c50425574..5d15f3863e4 100644 --- a/types/foundry/client/application/form-application/document-sheet/index.d.ts +++ b/types/foundry/client/application/form-application/document-sheet/index.d.ts @@ -1,15 +1,15 @@ -import "./active-effect-config.js"; -import "./actor-sheet.js"; -import "./base.js"; -import "./combatant-config.js"; -import "./item-sheet.js"; -import "./journal-page-sheet.js"; -import "./journal-sheet.js"; -import "./macro-config.js"; -import "./note-config.js"; -import "./roll-table-config.js"; -import "./scene-config.js"; -import "./tile-config.js"; -import "./token-config.js"; -import "./user-config.js"; -import "./wall-config.js"; +import "./active-effect-config.d.ts"; +import "./actor-sheet.d.ts"; +import "./base.d.ts"; +import "./combatant-config.d.ts"; +import "./item-sheet.d.ts"; +import "./journal-page-sheet.d.ts"; +import "./journal-sheet.d.ts"; +import "./macro-config.d.ts"; +import "./note-config.d.ts"; +import "./roll-table-config.d.ts"; +import "./scene-config.d.ts"; +import "./tile-config.d.ts"; +import "./token-config.d.ts"; +import "./user-config.d.ts"; +import "./wall-config.d.ts"; diff --git a/types/foundry/client/application/form-application/index.d.ts b/types/foundry/client/application/form-application/index.d.ts index 4c79553de5f..c4375b30e3b 100644 --- a/types/foundry/client/application/form-application/index.d.ts +++ b/types/foundry/client/application/form-application/index.d.ts @@ -1,8 +1,8 @@ -import "./base.js"; -import "./client-settings.js"; -import "./document-sheet/index.js"; -import "./document-sheet-config.js"; -import "./image-popout.js"; -import "./other.js"; -import "./permission.js"; -import "./placeables-config.js"; +import "./base.d.ts"; +import "./client-settings.d.ts"; +import "./document-sheet/index.d.ts"; +import "./document-sheet-config.d.ts"; +import "./image-popout.d.ts"; +import "./other.d.ts"; +import "./permission.d.ts"; +import "./placeables-config.d.ts"; diff --git a/types/foundry/client/apps/sidebar/index.d.ts b/types/foundry/client/apps/sidebar/index.d.ts index 5a3260c37b4..e3e3cd92037 100644 --- a/types/foundry/client/apps/sidebar/index.d.ts +++ b/types/foundry/client/apps/sidebar/index.d.ts @@ -1,2 +1,2 @@ -import "./package-configuration.js"; -import "./apps/keybindings-config.js"; +import "./package-configuration.d.ts"; +import "./apps/keybindings-config.d.ts"; diff --git a/types/foundry/client/core/index.d.ts b/types/foundry/client/core/index.d.ts index 57fdcace070..e9a27ba5dbd 100644 --- a/types/foundry/client/core/index.d.ts +++ b/types/foundry/client/core/index.d.ts @@ -1,12 +1,12 @@ -import "./audio.js"; -import "./clipboard.js"; -import "./document-index.js"; -import "./fonts.js"; -import "./game-time.js"; -import "./hooks.js"; -import "./searchfilter.js"; -import "./settings.js"; -import "./socket.js"; -import "./sorting.js"; -import "./text-editor.js"; -import "./video.js"; +import "./audio.d.ts"; +import "./clipboard.d.ts"; +import "./document-index.d.ts"; +import "./fonts.d.ts"; +import "./game-time.d.ts"; +import "./hooks.d.ts"; +import "./searchfilter.d.ts"; +import "./settings.d.ts"; +import "./socket.d.ts"; +import "./sorting.d.ts"; +import "./text-editor.d.ts"; +import "./video.d.ts"; diff --git a/types/foundry/client/documents/active-effect.d.ts b/types/foundry/client/documents/active-effect.d.ts index 7ab512fa72c..07b9c2f271f 100644 --- a/types/foundry/client/documents/active-effect.d.ts +++ b/types/foundry/client/documents/active-effect.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseActiveEffect } from "./client-base-mixes.js"; +import type { ClientBaseActiveEffect } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/actor.d.ts b/types/foundry/client/documents/actor.d.ts index 398fd7aa58d..7a1082d6bd7 100644 --- a/types/foundry/client/documents/actor.d.ts +++ b/types/foundry/client/documents/actor.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseActor } from "./client-base-mixes.js"; +import type { ClientBaseActor } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/ambient-light-document.d.ts b/types/foundry/client/documents/ambient-light-document.d.ts index 2ca2505a898..bd8aeafdccb 100644 --- a/types/foundry/client/documents/ambient-light-document.d.ts +++ b/types/foundry/client/documents/ambient-light-document.d.ts @@ -1,4 +1,4 @@ -import { CanvasBaseAmbientLight } from "./client-base-mixes.js"; +import type { CanvasBaseAmbientLight } from "./client-base-mixes.d.ts"; declare global { class AmbientLightDocument extends CanvasBaseAmbientLight { diff --git a/types/foundry/client/documents/ambient-sound-document.d.ts b/types/foundry/client/documents/ambient-sound-document.d.ts index bf049ac05c8..5421c8d3316 100644 --- a/types/foundry/client/documents/ambient-sound-document.d.ts +++ b/types/foundry/client/documents/ambient-sound-document.d.ts @@ -1,4 +1,4 @@ -import { CanvasBaseAmbientSound } from "./client-base-mixes.js"; +import type { CanvasBaseAmbientSound } from "./client-base-mixes.d.ts"; declare global { class AmbientSoundDocument extends CanvasBaseAmbientSound {} diff --git a/types/foundry/client/documents/cards.d.ts b/types/foundry/client/documents/cards.d.ts index 296b8243be7..bcc5ce91ef1 100644 --- a/types/foundry/client/documents/cards.d.ts +++ b/types/foundry/client/documents/cards.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseCards } from "./client-base-mixes.js"; +import type { ClientBaseCards } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/chat-message.d.ts b/types/foundry/client/documents/chat-message.d.ts index 302f75eaf7f..85fc9e5016d 100644 --- a/types/foundry/client/documents/chat-message.d.ts +++ b/types/foundry/client/documents/chat-message.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseChatMessage } from "./client-base-mixes.js"; +import type { ClientBaseChatMessage } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/client-document.d.ts b/types/foundry/client/documents/client-document.d.ts index af2299e225e..cd273a5a4af 100644 --- a/types/foundry/client/documents/client-document.d.ts +++ b/types/foundry/client/documents/client-document.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseScene } from "./client-base-mixes.js"; +import type { ClientBaseScene } from "./client-base-mixes.d.ts"; declare global { // Interfaces for ClientDocuments, given there is no common base with the generated intermediate classes diff --git a/types/foundry/client/documents/combat.d.ts b/types/foundry/client/documents/combat.d.ts index 170933b6187..f653febb1a5 100644 --- a/types/foundry/client/documents/combat.d.ts +++ b/types/foundry/client/documents/combat.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseCombat } from "./client-base-mixes.js"; +import type { ClientBaseCombat } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/combatant.d.ts b/types/foundry/client/documents/combatant.d.ts index 36b39fe0985..13e1f4b146b 100644 --- a/types/foundry/client/documents/combatant.d.ts +++ b/types/foundry/client/documents/combatant.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseCombatant } from "./client-base-mixes.js"; +import type { ClientBaseCombatant } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/drawing-document.d.ts b/types/foundry/client/documents/drawing-document.d.ts index 01d25f5f9d2..1d1dc1f941d 100644 --- a/types/foundry/client/documents/drawing-document.d.ts +++ b/types/foundry/client/documents/drawing-document.d.ts @@ -1,4 +1,4 @@ -import { CanvasBaseDrawing } from "./client-base-mixes.js"; +import type { CanvasBaseDrawing } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/fog-exploration.d.ts b/types/foundry/client/documents/fog-exploration.d.ts index e6e4fec93a2..8e4132b25e6 100644 --- a/types/foundry/client/documents/fog-exploration.d.ts +++ b/types/foundry/client/documents/fog-exploration.d.ts @@ -1,5 +1,5 @@ import * as io from "socket.io"; -import { ClientBaseFogExploration } from "./client-base-mixes.js"; +import type { ClientBaseFogExploration } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/folder.d.ts b/types/foundry/client/documents/folder.d.ts index 2fec2b45742..5a94357818e 100644 --- a/types/foundry/client/documents/folder.d.ts +++ b/types/foundry/client/documents/folder.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseFolder } from "./client-base-mixes.js"; +import type { ClientBaseFolder } from "./client-base-mixes.d.ts"; declare global { /** @@ -33,7 +33,7 @@ declare global { get displayed(): boolean; /** Return a reference to the Document type which is contained within this Folder. */ - get documentClass(): Function; + get documentClass(): ConstructorOf; /** Return a reference to the WorldCollection instance which provides Documents to this Folder. */ get documentCollection(): WorldCollection; diff --git a/types/foundry/client/documents/index.d.ts b/types/foundry/client/documents/index.d.ts index 6a847501410..216feeed6dd 100644 --- a/types/foundry/client/documents/index.d.ts +++ b/types/foundry/client/documents/index.d.ts @@ -1,31 +1,31 @@ -import "./active-effect.js"; -import "./actor.js"; -import "./ambient-light-document.js"; -import "./ambient-sound-document.js"; -import "./cards.js"; -import "./chat-message.js"; -import "./client-base-mixes.js"; -import "./client-document.js"; -import "./combat.js"; -import "./combatant.js"; -import "./drawing-document.js"; -import "./fog-exploration.js"; -import "./folder.js"; -import "./item.js"; -import "./journal-entry.js"; -import "./journal-entry-page.js"; -import "./macro.js"; -import "./measured-template-document.js"; -import "./note-document.js"; -import "./playlist.js"; -import "./playlist-sound.js"; -import "./roll-table.js"; -import "./scene.js"; -import "./table-result.js"; -import "./tile-document.js"; -import "./token-document.js"; -import "./user.js"; -import "./wall-document.js"; +import "./active-effect.d.ts"; +import "./actor.d.ts"; +import "./ambient-light-document.d.ts"; +import "./ambient-sound-document.d.ts"; +import "./cards.d.ts"; +import "./chat-message.d.ts"; +import "./client-base-mixes.d.ts"; +import "./client-document.d.ts"; +import "./combat.d.ts"; +import "./combatant.d.ts"; +import "./drawing-document.d.ts"; +import "./fog-exploration.d.ts"; +import "./folder.d.ts"; +import "./item.d.ts"; +import "./journal-entry.d.ts"; +import "./journal-entry-page.d.ts"; +import "./macro.d.ts"; +import "./measured-template-document.d.ts"; +import "./note-document.d.ts"; +import "./playlist.d.ts"; +import "./playlist-sound.d.ts"; +import "./roll-table.d.ts"; +import "./scene.d.ts"; +import "./table-result.d.ts"; +import "./tile-document.d.ts"; +import "./token-document.d.ts"; +import "./user.d.ts"; +import "./wall-document.d.ts"; declare global { type WorldDocument = diff --git a/types/foundry/client/documents/item.d.ts b/types/foundry/client/documents/item.d.ts index fd3b0c27f69..16415b25f90 100644 --- a/types/foundry/client/documents/item.d.ts +++ b/types/foundry/client/documents/item.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseItem } from "./client-base-mixes.js"; +import type { ClientBaseItem } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/journal-entry-page.d.ts b/types/foundry/client/documents/journal-entry-page.d.ts index 9c52c6297dc..6daebf55576 100644 --- a/types/foundry/client/documents/journal-entry-page.d.ts +++ b/types/foundry/client/documents/journal-entry-page.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseJournalEntryPage } from "./client-base-mixes.js"; +import type { ClientBaseJournalEntryPage } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/journal-entry.d.ts b/types/foundry/client/documents/journal-entry.d.ts index 57a57eac0ae..554f1f0979a 100644 --- a/types/foundry/client/documents/journal-entry.d.ts +++ b/types/foundry/client/documents/journal-entry.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseJournalEntry } from "./client-base-mixes.js"; +import type { ClientBaseJournalEntry } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/macro.d.ts b/types/foundry/client/documents/macro.d.ts index d25491b20cb..eb81737dee8 100644 --- a/types/foundry/client/documents/macro.d.ts +++ b/types/foundry/client/documents/macro.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseMacro } from "./client-base-mixes.js"; +import type { ClientBaseMacro } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/measured-template-document.d.ts b/types/foundry/client/documents/measured-template-document.d.ts index 492e2a878b1..8d82d9ec5f3 100644 --- a/types/foundry/client/documents/measured-template-document.d.ts +++ b/types/foundry/client/documents/measured-template-document.d.ts @@ -1,4 +1,4 @@ -import { CanvasBaseMeasuredTemplate } from "./client-base-mixes.js"; +import type { CanvasBaseMeasuredTemplate } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/note-document.d.ts b/types/foundry/client/documents/note-document.d.ts index 8767607e1b5..5126c5f0f80 100644 --- a/types/foundry/client/documents/note-document.d.ts +++ b/types/foundry/client/documents/note-document.d.ts @@ -1,4 +1,4 @@ -import { CanvasBaseNote } from "./client-base-mixes.js"; +import type { CanvasBaseNote } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/playlist-sound.d.ts b/types/foundry/client/documents/playlist-sound.d.ts index a0878ced33b..24e61961499 100644 --- a/types/foundry/client/documents/playlist-sound.d.ts +++ b/types/foundry/client/documents/playlist-sound.d.ts @@ -1,4 +1,4 @@ -import { ClientBasePlaylistSound } from "./client-base-mixes.js"; +import type { ClientBasePlaylistSound } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/playlist.d.ts b/types/foundry/client/documents/playlist.d.ts index 958c806c3bd..002ece5c0e5 100644 --- a/types/foundry/client/documents/playlist.d.ts +++ b/types/foundry/client/documents/playlist.d.ts @@ -1,4 +1,4 @@ -import { ClientBasePlaylist } from "./client-base-mixes.js"; +import type { ClientBasePlaylist } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/roll-table.d.ts b/types/foundry/client/documents/roll-table.d.ts index 1220b16e5b4..d261d7c509d 100644 --- a/types/foundry/client/documents/roll-table.d.ts +++ b/types/foundry/client/documents/roll-table.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseRollTable } from "./client-base-mixes.js"; +import type { ClientBaseRollTable } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/scene.d.ts b/types/foundry/client/documents/scene.d.ts index 6b1906a2a62..f6b2135f830 100644 --- a/types/foundry/client/documents/scene.d.ts +++ b/types/foundry/client/documents/scene.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseScene } from "./client-base-mixes.js"; +import type { ClientBaseScene } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/table-result.d.ts b/types/foundry/client/documents/table-result.d.ts index 693d3b7b963..c4180d0e97e 100644 --- a/types/foundry/client/documents/table-result.d.ts +++ b/types/foundry/client/documents/table-result.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseTableResult } from "./client-base-mixes.js"; +import type { ClientBaseTableResult } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/tile-document.d.ts b/types/foundry/client/documents/tile-document.d.ts index df6f7fb0f53..abec9fc5426 100644 --- a/types/foundry/client/documents/tile-document.d.ts +++ b/types/foundry/client/documents/tile-document.d.ts @@ -1,4 +1,4 @@ -import { CanvasBaseTile } from "./client-base-mixes.js"; +import type { CanvasBaseTile } from "./client-base-mixes.d.ts"; declare global { class TileDocument extends CanvasBaseTile {} diff --git a/types/foundry/client/documents/token-document.d.ts b/types/foundry/client/documents/token-document.d.ts index fe196780188..7ccbe5a9b4b 100644 --- a/types/foundry/client/documents/token-document.d.ts +++ b/types/foundry/client/documents/token-document.d.ts @@ -1,4 +1,4 @@ -import { CanvasBaseToken } from "./client-base-mixes.js"; +import type { CanvasBaseToken } from "./client-base-mixes.d.ts"; declare global { class TokenDocument extends CanvasBaseToken { diff --git a/types/foundry/client/documents/user.d.ts b/types/foundry/client/documents/user.d.ts index a40a996bd44..5796665a67a 100644 --- a/types/foundry/client/documents/user.d.ts +++ b/types/foundry/client/documents/user.d.ts @@ -1,4 +1,4 @@ -import { ClientBaseUser } from "./client-base-mixes.js"; +import type { ClientBaseUser } from "./client-base-mixes.d.ts"; declare global { /** diff --git a/types/foundry/client/documents/wall-document.d.ts b/types/foundry/client/documents/wall-document.d.ts index a1dd81205aa..52479496c15 100644 --- a/types/foundry/client/documents/wall-document.d.ts +++ b/types/foundry/client/documents/wall-document.d.ts @@ -1,4 +1,4 @@ -import { CanvasBaseWall } from "./client-base-mixes.js"; +import type { CanvasBaseWall } from "./client-base-mixes.d.ts"; declare global { class WallDocument extends CanvasBaseWall {} diff --git a/types/foundry/client/index.d.ts b/types/foundry/client/index.d.ts new file mode 100644 index 00000000000..dac3ef2247b --- /dev/null +++ b/types/foundry/client/index.d.ts @@ -0,0 +1,14 @@ +declare global { + const CONST: typeof Constants; + namespace globalThis { + export import Color = Utils.Color; + + module foundry { + export import CONST = Constants; + export import abstract = Abstract; + export import data = Data; + export import documents = Documents; + export import utils = Utils; + } + } +} diff --git a/types/foundry/client/keyboard/index.d.ts b/types/foundry/client/keyboard/index.d.ts index 289f6a243bb..e95d6845ded 100644 --- a/types/foundry/client/keyboard/index.d.ts +++ b/types/foundry/client/keyboard/index.d.ts @@ -1,2 +1,2 @@ -import "./client-keybindings.js"; -import "./keyboard-manager.js"; +import "./client-keybindings.d.ts"; +import "./keyboard-manager.d.ts"; diff --git a/types/foundry/client/pixi/core/index.d.ts b/types/foundry/client/pixi/core/index.d.ts index b13b053876e..a3de581af3e 100644 --- a/types/foundry/client/pixi/core/index.d.ts +++ b/types/foundry/client/pixi/core/index.d.ts @@ -1,2 +1,2 @@ -import "./interaction/index.js"; -import "./shapes/index.js"; +import "./interaction/index.d.ts"; +import "./shapes/index.d.ts"; diff --git a/types/foundry/client/pixi/core/interaction/index.d.ts b/types/foundry/client/pixi/core/interaction/index.d.ts index 440b03f861d..3b104b41e52 100644 --- a/types/foundry/client/pixi/core/interaction/index.d.ts +++ b/types/foundry/client/pixi/core/interaction/index.d.ts @@ -1 +1 @@ -import "./canvas-animation.js"; +import "./canvas-animation.d.ts"; diff --git a/types/foundry/client/pixi/core/shapes/index.d.ts b/types/foundry/client/pixi/core/shapes/index.d.ts index 625f338ad11..2a131a1ab5e 100644 --- a/types/foundry/client/pixi/core/shapes/index.d.ts +++ b/types/foundry/client/pixi/core/shapes/index.d.ts @@ -1,2 +1,2 @@ -import "./polygon-helpers.js"; -import "./source-polygon.js"; +import "./polygon-helpers.d.ts"; +import "./source-polygon.d.ts"; diff --git a/types/foundry/client/pixi/grid/index.d.ts b/types/foundry/client/pixi/grid/index.d.ts index 57f84056de8..1aa7fc32fe4 100644 --- a/types/foundry/client/pixi/grid/index.d.ts +++ b/types/foundry/client/pixi/grid/index.d.ts @@ -1,3 +1,3 @@ -import "./base.js"; -import "./hexagonal-grid.js"; -import "./square-grid.js"; +import "./base.d.ts"; +import "./hexagonal-grid.d.ts"; +import "./square-grid.d.ts"; diff --git a/types/foundry/client/pixi/groups/index.d.ts b/types/foundry/client/pixi/groups/index.d.ts index 899d303cfac..19d066e34e3 100644 --- a/types/foundry/client/pixi/groups/index.d.ts +++ b/types/foundry/client/pixi/groups/index.d.ts @@ -1,3 +1,3 @@ -import "./effects.js"; -import "./interface.js"; -import "./primary.js"; +import "./effects.d.ts"; +import "./interface.d.ts"; +import "./primary.d.ts"; diff --git a/types/foundry/client/pixi/helpers/index.d.ts b/types/foundry/client/pixi/helpers/index.d.ts index d051b92c477..96a6c9a963f 100644 --- a/types/foundry/client/pixi/helpers/index.d.ts +++ b/types/foundry/client/pixi/helpers/index.d.ts @@ -1,9 +1,9 @@ -import "./cached-container.js"; -import "./control-icon.js"; -import "./door-control.js"; -import "./grid-highlight.js"; -import "./object-hud.js"; -import "./point-source/index.js"; -import "./precise-text.js"; -import "./ray/index.js"; -import "./resize-handle.js"; +import "./cached-container.d.ts"; +import "./control-icon.d.ts"; +import "./door-control.d.ts"; +import "./grid-highlight.d.ts"; +import "./object-hud.d.ts"; +import "./point-source/index.d.ts"; +import "./precise-text.d.ts"; +import "./ray/index.d.ts"; +import "./resize-handle.d.ts"; diff --git a/types/foundry/client/pixi/helpers/point-source/index.d.ts b/types/foundry/client/pixi/helpers/point-source/index.d.ts index acac6ae2ad7..afa94ade4b8 100644 --- a/types/foundry/client/pixi/helpers/point-source/index.d.ts +++ b/types/foundry/client/pixi/helpers/point-source/index.d.ts @@ -1,4 +1,4 @@ -import "./base.js"; -import "./light-source.js"; -import "./sound-source.js"; -import "./vision-source.js"; +import "./base.d.ts"; +import "./light-source.d.ts"; +import "./sound-source.d.ts"; +import "./vision-source.d.ts"; diff --git a/types/foundry/client/pixi/helpers/ray/index.d.ts b/types/foundry/client/pixi/helpers/ray/index.d.ts index 5f310615443..c59d61f578c 100644 --- a/types/foundry/client/pixi/helpers/ray/index.d.ts +++ b/types/foundry/client/pixi/helpers/ray/index.d.ts @@ -1,2 +1,2 @@ -import "./base.js"; -import "./sight-ray.js"; +import "./base.d.ts"; +import "./sight-ray.d.ts"; diff --git a/types/foundry/client/pixi/index.d.ts b/types/foundry/client/pixi/index.d.ts index 7121ead1804..e7ea9e451d3 100644 --- a/types/foundry/client/pixi/index.d.ts +++ b/types/foundry/client/pixi/index.d.ts @@ -42,12 +42,12 @@ import { UniformGroup, utils, } from "pixi.js"; -import "./core/index.js"; -import "./groups/index.js"; -import "./layers/effects/visibility.js"; -import "./perception/index.js"; -import "./webgl/index.js"; -import "./layers/controls/ruler.js"; +import "./core/index.d.ts"; +import "./groups/index.d.ts"; +import "./layers/effects/visibility.d.ts"; +import "./perception/index.d.ts"; +import "./webgl/index.d.ts"; +import "./layers/controls/ruler.d.ts"; declare global { module PIXI { diff --git a/types/foundry/client/pixi/perception/index.d.ts b/types/foundry/client/pixi/perception/index.d.ts index c86e159317c..c614b017b30 100644 --- a/types/foundry/client/pixi/perception/index.d.ts +++ b/types/foundry/client/pixi/perception/index.d.ts @@ -1,5 +1,5 @@ -import "./clockwise-sweep.js"; -import "./color-manager.js"; -import "./detection-mode.js"; -import "./perception-manager.js"; -import "./vision-mode.js"; +import "./clockwise-sweep.d.ts"; +import "./color-manager.d.ts"; +import "./detection-mode.d.ts"; +import "./perception-manager.d.ts"; +import "./vision-mode.d.ts"; diff --git a/types/foundry/client/pixi/placeable-object/index.d.ts b/types/foundry/client/pixi/placeable-object/index.d.ts index c87455b6417..344ae683db7 100644 --- a/types/foundry/client/pixi/placeable-object/index.d.ts +++ b/types/foundry/client/pixi/placeable-object/index.d.ts @@ -1,9 +1,9 @@ -import "./ambient-light.js"; -import "./ambient-sound.js"; -import "./base.js"; -import "./drawing.js"; -import "./measured-template.js"; -import "./note.js"; -import "./tile.js"; -import "./token.js"; -import "./wall.js"; +import "./ambient-light.d.ts"; +import "./ambient-sound.d.ts"; +import "./base.d.ts"; +import "./drawing.d.ts"; +import "./measured-template.d.ts"; +import "./note.d.ts"; +import "./tile.d.ts"; +import "./token.d.ts"; +import "./wall.d.ts"; diff --git a/types/foundry/client/pixi/placeables-layer/index.d.ts b/types/foundry/client/pixi/placeables-layer/index.d.ts index c1a6b583112..004054ed787 100644 --- a/types/foundry/client/pixi/placeables-layer/index.d.ts +++ b/types/foundry/client/pixi/placeables-layer/index.d.ts @@ -1,9 +1,9 @@ -import "./base.js"; -import "./drawings-layer.js"; -import "./lighting-layer.js"; -import "./notes-layer.js"; -import "./sounds-layer.js"; -import "./template-layer.js"; -import "./tiles-layer.js"; -import "./token-layer.js"; -import "./walls-layer.js"; +import "./base.d.ts"; +import "./drawings-layer.d.ts"; +import "./lighting-layer.d.ts"; +import "./notes-layer.d.ts"; +import "./sounds-layer.d.ts"; +import "./template-layer.d.ts"; +import "./tiles-layer.d.ts"; +import "./token-layer.d.ts"; +import "./walls-layer.d.ts"; diff --git a/types/foundry/client/pixi/placeables-layer/lighting-layer.d.ts b/types/foundry/client/pixi/placeables-layer/lighting-layer.d.ts index 2af873b2fbc..050dc98f157 100644 --- a/types/foundry/client/pixi/placeables-layer/lighting-layer.d.ts +++ b/types/foundry/client/pixi/placeables-layer/lighting-layer.d.ts @@ -19,7 +19,7 @@ declare global { constructor(); /** A mapping of light sources which are active within the rendered Scene */ - sources: foundry.utils.Collection>; + sources: Collection>; /** * Increment this whenever lighting channels are re-configured. diff --git a/types/foundry/client/pixi/special-effect/index.d.ts b/types/foundry/client/pixi/special-effect/index.d.ts index d69b2f7153a..6c356b46578 100644 --- a/types/foundry/client/pixi/special-effect/index.d.ts +++ b/types/foundry/client/pixi/special-effect/index.d.ts @@ -1 +1 @@ -import "./base.js"; +import "./base.d.ts"; diff --git a/types/foundry/client/pixi/webgl/filters/index.d.ts b/types/foundry/client/pixi/webgl/filters/index.d.ts index 7cd4e3aa755..742542a35cf 100644 --- a/types/foundry/client/pixi/webgl/filters/index.d.ts +++ b/types/foundry/client/pixi/webgl/filters/index.d.ts @@ -1 +1 @@ -import "./filters.js"; +import "./filters.d.ts"; diff --git a/types/foundry/client/pixi/webgl/index.d.ts b/types/foundry/client/pixi/webgl/index.d.ts index 5f33ee8233d..effb1d2066a 100644 --- a/types/foundry/client/pixi/webgl/index.d.ts +++ b/types/foundry/client/pixi/webgl/index.d.ts @@ -1,3 +1,3 @@ -import "./base.js"; -import "./filters/index.js"; -import "./shaders/index.js"; +import "./base.d.ts"; +import "./filters/index.d.ts"; +import "./shaders/index.d.ts"; diff --git a/types/foundry/client/pixi/webgl/shaders/index.d.ts b/types/foundry/client/pixi/webgl/shaders/index.d.ts index eba3622e3ab..d28b0374920 100644 --- a/types/foundry/client/pixi/webgl/shaders/index.d.ts +++ b/types/foundry/client/pixi/webgl/shaders/index.d.ts @@ -1 +1 @@ -import "./sampler.js"; +import "./sampler.d.ts"; diff --git a/types/foundry/client/roll-term/index.d.ts b/types/foundry/client/roll-term/index.d.ts index 84b16d0825b..29dc9e871e7 100644 --- a/types/foundry/client/roll-term/index.d.ts +++ b/types/foundry/client/roll-term/index.d.ts @@ -1,11 +1,11 @@ -import "./base.js"; -import "./dice-term/base.js"; -import "./dice-term/coin.js"; -import "./dice-term/die.js"; -import "./dice-term/fate-die.js"; -import "./math-term.js"; -import "./numeric-term.js"; -import "./operator-term.js"; -import "./parenthetical-term.js"; -import "./pool-term.js"; -import "./string-term.js"; +import "./base.d.ts"; +import "./dice-term/base.d.ts"; +import "./dice-term/coin.d.ts"; +import "./dice-term/die.d.ts"; +import "./dice-term/fate-die.d.ts"; +import "./math-term.d.ts"; +import "./numeric-term.d.ts"; +import "./operator-term.d.ts"; +import "./parenthetical-term.d.ts"; +import "./pool-term.d.ts"; +import "./string-term.d.ts"; diff --git a/types/foundry/client/ui/index.d.ts b/types/foundry/client/ui/index.d.ts index 2553076817e..8bd8483915d 100644 --- a/types/foundry/client/ui/index.d.ts +++ b/types/foundry/client/ui/index.d.ts @@ -1,11 +1,11 @@ -import "./context.js"; -import "./dialog.js"; -import "./drag-drop.js"; -import "./filepicker.js"; -import "./notifications.js"; -import "./tabs.js"; -import "./tooltip.js"; -import "./tour.js"; +import "./context.d.ts"; +import "./dialog.d.ts"; +import "./drag-drop.d.ts"; +import "./filepicker.d.ts"; +import "./notifications.d.ts"; +import "./tabs.d.ts"; +import "./tooltip.d.ts"; +import "./tour.d.ts"; declare global { interface FoundryUI< diff --git a/types/foundry/client/ui/tour.d.ts b/types/foundry/client/ui/tour.d.ts index 7010077da6a..0aa51a30bf5 100644 --- a/types/foundry/client/ui/tour.d.ts +++ b/types/foundry/client/ui/tour.d.ts @@ -155,7 +155,7 @@ declare global { } /** A singleton Tour Collection class responsible for registering and activating Tours, accessible as game.tours */ - class Tours extends foundry.utils.Collection { + class Tours extends Collection { /** * Register a new Tour * @param namespace The namespace of the Tour diff --git a/types/foundry/common/abstract/data.d.mts b/types/foundry/common/abstract/data.d.mts deleted file mode 100644 index 3a7f5ebacad..00000000000 --- a/types/foundry/common/abstract/data.d.mts +++ /dev/null @@ -1,239 +0,0 @@ -import * as fields from "../data/fields.js"; -import { EmbeddedCollection } from "./embedded-collection.mjs"; - -/** - * The abstract base class which defines the data schema contained within a Document. - * @param [data={}] Initial data used to construct the data object - * @param [options={}] Options which affect DataModel construction - */ -export abstract class DataModel< - TParent extends DataModel | null = _DataModel | null, - TSchema extends fields.DataSchema = fields.DataSchema -> { - constructor( - data?: DeepPartial>, - options?: DataModelConstructionOptions - ); - - /** - * The source data object for this DataModel instance. - * Once constructed, the source object is sealed such that no keys may be added nor removed. - */ - readonly _source: SourceFromSchema; - - /** An immutable reverse-reference to a parent DataModel to which this model belongs. */ - readonly parent: TParent; - - /** The defined and cached Data Schema for all instances of this DataModel. */ - protected static _schema: fields.SchemaField> | undefined; - - /** Configure the data model instance before validation and initialization workflows are performed. */ - protected _configure(): void; - - /* ---------------------------------------- */ - /* Data Schema */ - /* ---------------------------------------- */ - - /** - * Define the data schema for documents of this type. - * The schema is populated the first time it is accessed and cached for future reuse. - */ - static defineSchema(): fields.DataSchema; - - /** Define the data schema for documents of this type. */ - static get schema(): Required<(typeof this)["_schema"]>; - - /** Define the data schema for this document instance. */ - // PROJECT NOTE: this must be overloaded in an interface merge declaration - get schema(): fields.SchemaField; - - /** Is the current state of this DataModel invalid? */ - get invalid(): boolean; - - /* ---------------------------------------- */ - /* Data Cleaning Methods */ - /* ---------------------------------------- */ - - /** - * Initialize the source data for a new DataModel instance. - * One-time migrations and initial cleaning operations are applied to the source data. - * @param data The candidate source data from which the model will be constructed - * @param [options] Options provided to the model constructor - * @returns Migrated and cleaned source data which will be stored to the model instance - */ - protected _initializeSource(data: object, options?: DataModelConstructionOptions): this["_source"]; - - /** - * Clean a data source object to conform to a specific provided schema. - * @param [source] The source data object - * @param [options={}] Additional options which are passed to field cleaning methods - * @returns The cleaned source data - */ - static cleanData(source?: object, options?: Record): SourceFromSchema; - - /* ---------------------------------------- */ - /* Data Initialization */ - /* ---------------------------------------- */ - - /** - * Initialize the instance by copying data from the source object to instance attributes. - * This mirrors the workflow of SchemaField#initialize but with some added functionality. - * @param [options] Options provided to the model constructor - */ - protected _initialize(options?: Record): void; - - /** Reset the state of this data instance back to mirror the contained source data, erasing any changes. */ - reset(): void; - - /* ---------------------------------------- */ - /* Data Validation Methods */ - /* ---------------------------------------- */ - - /** - * Validate the data contained in the document to check for type and content - * This function throws an error if data within the document is not valid - * - * @param options Optional parameters which customize how validation occurs. - * @param [options.changes] A specific set of proposed changes to validate, rather than the full - * source data of the model. - * @param [options.clean=false] If changes are provided, attempt to clean the changes before validating - * them? - * @param [options.fallback=false] Allow replacement of invalid values with valid defaults? - * @param [options.strict=true] Throw if an invalid value is encountered, otherwise log a warning? - * @param [options.fields=true] Perform validation on individual fields? - * @param [options.joint] Perform joint validation on the full data model? - * Joint validation will be performed by default if no changes are passed. - * Joint validation will be disabled by default if changes are passed. - * Joint validation can be performed on a complete set of changes (for - * example testing a complete data model) by explicitly passing true. - * @return An indicator for whether the document contains valid data - */ - validate(options?: DataModelValidationOptions): boolean; - - /** - * Get an array of validation errors from the provided error structure - * @param errors - * @param [options={}] - * @param [options.label] A prefix label that should prepend any error messages - * @param [options.namespace] A field namespace that should prepend key names with dot-notation - */ - static formatValidationErrors( - errors: Record, - options?: { label?: string; namespace?: string } - ): string; - - /** - * Jointly validate the overall data model after each field has been individually validated. - * @param data The candidate data object to validate - * @throws An error if a validation failure is detected - */ - protected _validateModel(data: object): void; - - /* ---------------------------------------- */ - /* Data Management */ - /* ---------------------------------------- */ - - /** - * Update the DataModel locally by applying an object of changes to its source data. - * The provided changes are cleaned, validated, and stored to the source data object for this model. - * The source data is then re-initialized to apply those changes to the prepared data. - * The method returns an object of differential changes which modified the original data. - * - * @param changes New values which should be applied to the data model - * @param [options={}] Options which determine how the new data is merged - * @returns An object containing the changed keys and values - */ - updateSource( - changes?: DeepPartial | undefined, - options?: MergeObjectOptions - ): DeepPartial; - - /* ---------------------------------------- */ - /* Serialization and Storage */ - /* ---------------------------------------- */ - - /** - * Copy and transform the DataModel into a plain object. - * Draw the values of the extracted object from the data source (by default) otherwise from its transformed values. - * @param [source=true] Draw values from the underlying data source rather than transformed values - * @returns The extracted primitive object - */ - toObject(source?: true): this["_source"]; - toObject(source: false): RawObject; - toObject(source?: boolean): this["_source"] | RawObject; - - /** - * Extract the source data for the DataModel into a simple object format that can be serialized. - * @returns The document source data expressed as a plain object - */ - toJSON(): this["_source"]; - - /** - * Create a new instance of this DataModel from a source record. - * The source is presumed to be trustworthy and is not strictly validated. - * @param source Initial document data which comes from a trusted source. - * @param [context] Model construction context - * @param [context.strict=false] Models created from trusted source data are validated non-strictly - */ - static fromSource(source: object, context?: { strict?: boolean; [key: string]: unknown }): DataModel; - - /** - * Create a DataModel instance using a provided serialized JSON string. - * @param json Serialized document data in string format - * @returns A constructed data model instance - */ - static fromJSON(json: string): DataModel; - - /* -------------------------------------------- */ - /* Deprecations and Compatibility */ - /* -------------------------------------------- */ - - /** - * Migrate candidate source data for this DataModel which may require initial cleaning or transformations. - * @param source The candidate source data from which the model will be constructed - * @returns Migrated source data, if necessary - */ - static migrateData(source: TSource): TSource; - - /** - * Wrap data migration in a try/catch which attempts it safely - * @param source The candidate source data from which the model will be constructed - * @returns Migrated source data, if necessary - */ - static migrateDataSafe(source: object): object; -} - -export type RawObject> = { - [P in keyof TModel]: TModel[P] extends EmbeddedCollection - ? RawObject[] - : TModel[P] extends DataModel - ? RawObject - : TModel[P] extends DataModel[] - ? RawObject[] - : TModel[P]; -}; - -export interface DataModelValidationOptions { - changes?: object; - clean?: boolean; - fallback?: boolean; - strict?: boolean; - fields?: boolean; - joint?: boolean; -} - -declare global { - interface DataModelConstructionOptions { - /** @param [parent=null] A parent DataModel instance to which this DataModel belongs */ - parent?: TParent; - /** @param [strict=true] Control the strictness of validation for initially provided data */ - strict?: boolean; - /** @param [fallback=false] Attempt to replace invalid values with valid defaults? */ - fallback?: boolean; - /** @param [partial=false] Allow partial source data, ignoring absent fields? */ - partial?: boolean; - [key: string]: unknown; - } -} - -type _DataModel = DataModel; diff --git a/types/foundry/common/abstract/data.d.ts b/types/foundry/common/abstract/data.d.ts index d51faaf43eb..baef61e4317 100644 --- a/types/foundry/common/abstract/data.d.ts +++ b/types/foundry/common/abstract/data.d.ts @@ -1,10 +1,239 @@ -import * as AbstractDataModel from "./data.mjs"; +import type * as fields from "../data/fields.d.ts"; +import type { EmbeddedCollection } from "./embedded-collection.d.mts"; + +/** + * The abstract base class which defines the data schema contained within a Document. + * @param [data={}] Initial data used to construct the data object + * @param [options={}] Options which affect DataModel construction + */ +export default abstract class DataModel< + TParent extends DataModel | null = _DataModel | null, + TSchema extends fields.DataSchema = fields.DataSchema +> { + constructor( + data?: DeepPartial>, + options?: DataModelConstructionOptions + ); + + /** + * The source data object for this DataModel instance. + * Once constructed, the source object is sealed such that no keys may be added nor removed. + */ + readonly _source: SourceFromSchema; + + /** An immutable reverse-reference to a parent DataModel to which this model belongs. */ + readonly parent: TParent; + + /** The defined and cached Data Schema for all instances of this DataModel. */ + protected static _schema: fields.SchemaField | undefined; + + /** Configure the data model instance before validation and initialization workflows are performed. */ + protected _configure(): void; + + /* ---------------------------------------- */ + /* Data Schema */ + /* ---------------------------------------- */ + + /** + * Define the data schema for documents of this type. + * The schema is populated the first time it is accessed and cached for future reuse. + */ + static defineSchema(): fields.DataSchema; + + /** Define the data schema for documents of this type. */ + static get schema(): fields.SchemaField; + + /** Define the data schema for this document instance. */ + // PROJECT NOTE: this must be overloaded in an interface merge declaration + get schema(): fields.SchemaField; + + /** Is the current state of this DataModel invalid? */ + get invalid(): boolean; + + /* ---------------------------------------- */ + /* Data Cleaning Methods */ + /* ---------------------------------------- */ + + /** + * Initialize the source data for a new DataModel instance. + * One-time migrations and initial cleaning operations are applied to the source data. + * @param data The candidate source data from which the model will be constructed + * @param [options] Options provided to the model constructor + * @returns Migrated and cleaned source data which will be stored to the model instance + */ + protected _initializeSource(data: object, options?: DataModelConstructionOptions): this["_source"]; + + /** + * Clean a data source object to conform to a specific provided schema. + * @param [source] The source data object + * @param [options={}] Additional options which are passed to field cleaning methods + * @returns The cleaned source data + */ + static cleanData(source?: object, options?: Record): SourceFromSchema; + + /* ---------------------------------------- */ + /* Data Initialization */ + /* ---------------------------------------- */ + + /** + * Initialize the instance by copying data from the source object to instance attributes. + * This mirrors the workflow of SchemaField#initialize but with some added functionality. + * @param [options] Options provided to the model constructor + */ + protected _initialize(options?: Record): void; + + /** Reset the state of this data instance back to mirror the contained source data, erasing any changes. */ + reset(): void; + + /* ---------------------------------------- */ + /* Data Validation Methods */ + /* ---------------------------------------- */ + + /** + * Validate the data contained in the document to check for type and content + * This function throws an error if data within the document is not valid + * + * @param options Optional parameters which customize how validation occurs. + * @param [options.changes] A specific set of proposed changes to validate, rather than the full + * source data of the model. + * @param [options.clean=false] If changes are provided, attempt to clean the changes before validating + * them? + * @param [options.fallback=false] Allow replacement of invalid values with valid defaults? + * @param [options.strict=true] Throw if an invalid value is encountered, otherwise log a warning? + * @param [options.fields=true] Perform validation on individual fields? + * @param [options.joint] Perform joint validation on the full data model? + * Joint validation will be performed by default if no changes are passed. + * Joint validation will be disabled by default if changes are passed. + * Joint validation can be performed on a complete set of changes (for + * example testing a complete data model) by explicitly passing true. + * @return An indicator for whether the document contains valid data + */ + validate(options?: DataModelValidationOptions): boolean; + + /** + * Get an array of validation errors from the provided error structure + * @param errors + * @param [options={}] + * @param [options.label] A prefix label that should prepend any error messages + * @param [options.namespace] A field namespace that should prepend key names with dot-notation + */ + static formatValidationErrors( + errors: Record, + options?: { label?: string; namespace?: string } + ): string; + + /** + * Jointly validate the overall data model after each field has been individually validated. + * @param data The candidate data object to validate + * @throws An error if a validation failure is detected + */ + protected _validateModel(data: object): void; + + /* ---------------------------------------- */ + /* Data Management */ + /* ---------------------------------------- */ + + /** + * Update the DataModel locally by applying an object of changes to its source data. + * The provided changes are cleaned, validated, and stored to the source data object for this model. + * The source data is then re-initialized to apply those changes to the prepared data. + * The method returns an object of differential changes which modified the original data. + * + * @param changes New values which should be applied to the data model + * @param [options={}] Options which determine how the new data is merged + * @returns An object containing the changed keys and values + */ + updateSource( + changes?: DeepPartial | undefined, + options?: MergeObjectOptions + ): DeepPartial; + + /* ---------------------------------------- */ + /* Serialization and Storage */ + /* ---------------------------------------- */ + + /** + * Copy and transform the DataModel into a plain object. + * Draw the values of the extracted object from the data source (by default) otherwise from its transformed values. + * @param [source=true] Draw values from the underlying data source rather than transformed values + * @returns The extracted primitive object + */ + toObject(source?: true): this["_source"]; + toObject(source: false): RawObject; + toObject(source?: boolean): this["_source"] | RawObject; + + /** + * Extract the source data for the DataModel into a simple object format that can be serialized. + * @returns The document source data expressed as a plain object + */ + toJSON(): this["_source"]; + + /** + * Create a new instance of this DataModel from a source record. + * The source is presumed to be trustworthy and is not strictly validated. + * @param source Initial document data which comes from a trusted source. + * @param [context] Model construction context + * @param [context.strict=false] Models created from trusted source data are validated non-strictly + */ + static fromSource(source: object, context?: { strict?: boolean; [key: string]: unknown }): DataModel; + + /** + * Create a DataModel instance using a provided serialized JSON string. + * @param json Serialized document data in string format + * @returns A constructed data model instance + */ + static fromJSON(json: string): DataModel; + + /* -------------------------------------------- */ + /* Deprecations and Compatibility */ + /* -------------------------------------------- */ + + /** + * Migrate candidate source data for this DataModel which may require initial cleaning or transformations. + * @param source The candidate source data from which the model will be constructed + * @returns Migrated source data, if necessary + */ + static migrateData(source: TSource): TSource; + + /** + * Wrap data migration in a try/catch which attempts it safely + * @param source The candidate source data from which the model will be constructed + * @returns Migrated source data, if necessary + */ + static migrateDataSafe(source: object): object; +} + +export type RawObject> = { + [P in keyof TModel]: TModel[P] extends EmbeddedCollection + ? RawObject[] + : TModel[P] extends DataModel + ? RawObject + : TModel[P] extends DataModel[] + ? RawObject[] + : TModel[P]; +}; + +export interface DataModelValidationOptions { + changes?: object; + clean?: boolean; + fallback?: boolean; + strict?: boolean; + fields?: boolean; + joint?: boolean; +} declare global { - module foundry { - module abstract { - export import DataModel = AbstractDataModel.DataModel; - export import _DataModel = AbstractDataModel._DataModel; - } + interface DataModelConstructionOptions { + /** @param [parent=null] A parent DataModel instance to which this DataModel belongs */ + parent?: TParent; + /** @param [strict=true] Control the strictness of validation for initially provided data */ + strict?: boolean; + /** @param [fallback=false] Attempt to replace invalid values with valid defaults? */ + fallback?: boolean; + /** @param [partial=false] Allow partial source data, ignoring absent fields? */ + partial?: boolean; + [key: string]: unknown; } } + +type _DataModel = DataModel<_DataModel | null, fields.DataSchema>; diff --git a/types/foundry/common/abstract/document.d.ts b/types/foundry/common/abstract/document.d.ts index 0f757842d13..1321940b427 100644 --- a/types/foundry/common/abstract/document.d.ts +++ b/types/foundry/common/abstract/document.d.ts @@ -1,374 +1,359 @@ -export {}; - -declare global { - module foundry { - module abstract { - /** The abstract base interface for all Document types. */ - abstract class Document { - constructor(data: object, context?: DocumentConstructionContext); - - _id: string | null; - - /** An immutable reverse-reference to the parent Document to which this embedded Document belongs. */ - readonly parent: TParent; - - /** An immutable reference to a containing Compendium collection to which this Document belongs. */ - readonly pack: string | null; - - _source: object; - - /** Perform one-time initialization tasks which only occur when the Document is first constructed. */ - protected _initialize(): void; - - /** - * Initialize the source data for a new DataModel instance. - * One-time migrations and initial cleaning operations are applied to the source data. - * @param data The candidate source data from which the model will be constructed - * @param [options] Options provided to the model constructor - * @returns Migrated and cleaned source data which will be stored to the model instance - * System note: actually in `DataModel` - */ - protected _initializeSource( - data: Record, - options?: DocumentConstructionContext - ): this["_source"]; - - /** - * Reset the state of this data instance back to mirror the contained source data, erasing any changes. - */ - reset(): void; - - /* -------------------------------------------- */ - /* Configuration */ - /* -------------------------------------------- */ - - /** Default metadata which applies to each instance of this Document type. */ - static get metadata(): DocumentMetadata; - - /** - * The database backend used to execute operations and handle results - * @type {DatabaseBackend} - */ - static get database(): object; - - /** Return a reference to the implemented subclass of this base document type. */ - static get implementation(): typeof foundry.abstract.Document; - - /* -------------------------------------------- */ - /* Properties */ - /* -------------------------------------------- */ - - /** The named collection to which this Document belongs. */ - static get collectionName(): string; - - /** The canonical name of this Document type, for example "Actor". */ - get documentName(): string; - - /** The canonical name of this Document type, for example "Actor". */ - static get documentName(): string; - - /** The canonical identifier for this Document */ - get id(): string; - - /** Test whether this Document is embedded within a parent Document */ - get isEmbedded(): boolean; - - /** The name of this Document, if it has one assigned */ - name: string; - - /* ---------------------------------------- */ - /* Methods */ - /* ---------------------------------------- */ - - /** - * Test whether a given User has a sufficient role in order to create Documents of this type. - * @param user The User being tested - * @return Does the User have a sufficient role to create? - */ - static canUserCreate(user: documents.BaseUser): boolean; - - /** - * Migrate candidate source data for this DataModel which may require initial cleaning or transformations. - * @param source The candidate source data from which the model will be constructed - * @returns Migrated source data, if necessary - */ - static migrateData(source: TSource): TSource; - - /** - * Update the DataModel locally by applying an object of changes to its source data. - * The provided changes are cleaned, validated, and stored to the source data object for this model. - * The source data is then re-initialized to apply those changes to the prepared data. - * The method returns an object of differential changes which modified the original data. - * - * @param changes New values which should be applied to the data model - * @param [options={}] Options which determine how the new data is merged - * @returns An object containing the changed keys and values - */ - updateSource( - data?: DocumentUpdateData, - options?: DocumentSourceUpdateContext - ): DeepPartial; - - /** - * Clone a document, creating a new document by combining current data with provided overrides. - * The cloned document is ephemeral and not yet saved to the database. - * @param [data={}] Additional data which overrides current document data at the time of creation - * @param [options={}] Additional options which customize the creation workflow - * @param [options.save=false] Save the clone to the World database? - * @param [options.keepId=false] Keep the original Document ID? Otherwise the ID will become undefined - * @returns The cloned Document instance - */ - clone( - data: DocumentUpdateData | undefined, - options: DocumentCloneOptions & { save: true } - ): Promise; - clone(data?: DocumentUpdateData, options?: DocumentCloneOptions & { save?: false }): this; - clone(data?: DocumentUpdateData, options?: DocumentCloneOptions): this | Promise; - - /** - * Get the permission level that a specific User has over this Document, a value in CONST.ENTITY_PERMISSIONS. - * @param user The User being tested - * @returns A numeric permission level from CONST.ENTITY_PERMISSIONS or null - */ - getUserLevel(user: documents.BaseUser): DocumentOwnershipLevel | null; - - /** - * Test whether a certain User has a requested permission level (or greater) over the Document - * @param user The User being tested - * @param permission The permission level from DOCUMENT_PERMISSION_LEVELS to test - * @param options Additional options involved in the permission test - * @param [options.exact=false] Require the exact permission level requested? - * @return Does the user have this permission level over the Document? - */ - testUserPermission( - user: documents.BaseUser, - permission: DocumentOwnershipString | DocumentOwnershipLevel, - { exact }?: { exact?: boolean } - ): boolean; - - /** - * Test whether a given User has permission to perform some action on this Document - * @param user The User attempting modification - * @param action The attempted action - * @param [data] Data involved in the attempted action - * @return Does the User have permission? - */ - canUserModify(user: documents.BaseUser, action: UserAction, data?: Record): boolean; - - /* -------------------------------------------- */ - /* Database Operations */ - /* -------------------------------------------- */ - - /** - * Create multiple Documents using provided input data. - * Data is provided as an array of objects where each individual object becomes one new Document. - * - * @param data An array of data objects used to create multiple documents - * @param [context={}] Additional context which customizes the creation workflow - * @return An array of created Document instances - * - * @example Create a single Document - * const data = [{name: "New Actor", type: "character", img: "path/to/profile.jpg"}]; - * const created = await Actor.createDocuments(data); - * - * @example Create multiple Documents - * const data = [{name: "Tim", type: "npc"], [{name: "Tom", type: "npc"}]; - * const created = await Actor.createDocuments(data); - * - * @example Create multiple embedded Documents within a parent - * const actor = game.actors.getName("Tim"); - * const data = [{name: "Sword", type: "weapon"}, {name: "Breastplate", type: "equipment"}]; - * const created = await Item.createDocuments(data, {parent: actor}); - * - * @example Create a Document within a Compendium pack - * const data = [{name: "Compendium Actor", type: "character", img: "path/to/profile.jpg"}]; - * const created = await Actor.createDocuments(data, {pack: "mymodule.mypack"}); - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static createDocuments>( - this: ConstructorOf, - data?: (TDocument | PreCreate)[], - context?: DocumentModificationContext - ): Promise; - - /** - * Update multiple Document instances using provided differential data. - * Data is provided as an array of objects where each individual object updates one existing Document. - * - * @param updates An array of differential data objects, each used to update a single Document - * @param [context={}] Additional context which customizes the update workflow - * @return An array of updated Document instances - * - * @example Update a single Document - * const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}]; - * const updated = await Actor.updateDocuments(updates); - * - * @example Update multiple Documents - * const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}, {_id: "kj549dk48k34jk34", name: "Thomas"}]}; - * const updated = await Actor.updateDocuments(updates); - * - * @example Update multiple embedded Documents within a parent - * const actor = game.actors.getName("Timothy"); - * const updates = [{_id: sword.id, name: "Magic Sword"}, {_id: shield.id, name: "Magic Shield"}]; - * const updated = await Item.updateDocuments(updates, {parent: actor}); - * - * @example Update Documents within a Compendium pack - * const actor = await pack.getDocument(documentId); - * const updated = await Actor.updateDocuments([{_id: actor.id, name: "New Name"}], {pack: "mymodule.mypack"}); - */ - static updateDocuments( - this: ConstructorOf, - updates?: DocumentUpdateData[], - context?: DocumentModificationContext - ): Promise; - - /** - * Delete one or multiple existing Documents using an array of provided ids. - * Data is provided as an array of string ids for the documents to delete. - * - * @param ids An array of string ids for the documents to be deleted - * @param [context={}] Additional context which customizes the deletion workflow - * @return An array of deleted Document instances - * - * @example Delete a single Document - * const tim = game.actors.getName("Tim"); - * const deleted = await Actor.deleteDocuments([tim.id]); - * - * @example Delete multiple Documents - * const tim = game.actors.getName("Tim"); - * const tom = game.actors.getName("Tom"); - * const deleted = await Actor.deleteDocuments([tim.id, tom.id]); - * - * @example Delete multiple embedded Documents within a parent - * const tim = game.actors.getName("Tim"); - * const sword = tim.items.getName("Sword"); - * const shield = tim.items.getName("Shield"); - * const deleted = await Item.deleteDocuments([sword.id, shield.id], parent: actor}); - * - * @example Delete Documents within a Compendium pack - * const actor = await pack.getDocument(documentId); - * const deleted = await Actor.deleteDocuments([actor.id], {pack: "mymodule.mypack"}); - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static deleteDocuments>( - this: ConstructorOf, - ids?: string[], - context?: DocumentModificationContext - ): Promise; - - /** - * Create a new Document using provided input data, saving it to the database. - * @see {@link Document.createDocuments} - * @param [data={}] Initial data used to create this Document - * @param [context={}] Additional context which customizes the creation workflow - * @return The created Document instance - * - * @example Create a World-level Item - * const data = [{name: "Special Sword", type: "weapon"}]; - * const created = await Item.create(data); - * - * @example Create an Actor-owned Item - * const data = [{name: "Special Sword", type: "weapon"}]; - * const actor = game.actors.getName("My Hero"); - * const created = await Item.create(data, {parent: actor}); - * - * @example Create an Item in a Compendium pack - * const data = [{name: "Special Sword", type: "weapon"}]; - * const created = await Item.create(data, {pack: "mymodule.mypack"}); - */ - static create( - this: ConstructorOf, - data: PreCreate, - context?: DocumentModificationContext - ): Promise; - static create( - this: ConstructorOf, - data: PreCreate[], - context?: DocumentModificationContext - ): Promise; - static create( - this: ConstructorOf, - data: PreCreate | PreCreate[], - context?: DocumentModificationContext - ): Promise; - - /** - * Update one or multiple existing entities using provided input data. - * Data may be provided as a single object to update one Document, or as an Array of Objects. - * @static - * - * @param data A Data object or array of Data. Each element must contain the _id of an existing Document. - * @param options Additional options which customize the update workflow - * @param [options.diff] Difference the provided data against the current to eliminate unnecessary changes. - * @param [options.noHook] Block the dispatch of preUpdate hooks for this operation. - * - * @return The updated Document or array of Entities - * - * @example - * const data = {_id: "12ekjf43kj2312ds", name: "New Name"}}; - * const updated = await Document.update(data); // Updated entity saved to the database - * - * @example - * const data = [{_id: "12ekjf43kj2312ds", name: "New Name 1"}, {_id: "kj549dk48k34jk34", name: "New Name 2"}]}; - * const updated = await Document.update(data); // Returns an Array of Entities, updated in the database - */ - update(data: DocumentUpdateData, options?: DocumentModificationContext): Promise; - - /** +import type BaseUser from "../documents/user.d.ts"; +import type EmbeddedCollection from "./embedded-collection.d.ts"; +import type * as CONST from "../constants.d.ts"; + +/** The abstract base interface for all Document types. */ +export default abstract class Document { + constructor(data: object, context?: DocumentConstructionContext); + + _id: string | null; + + /** An immutable reverse-reference to the parent Document to which this embedded Document belongs. */ + readonly parent: TParent; + + /** An immutable reference to a containing Compendium collection to which this Document belongs. */ + readonly pack: string | null; + + _source: object; + + /** Perform one-time initialization tasks which only occur when the Document is first constructed. */ + protected _initialize(): void; + + /** + * Initialize the source data for a new DataModel instance. + * One-time migrations and initial cleaning operations are applied to the source data. + * @param data The candidate source data from which the model will be constructed + * @param [options] Options provided to the model constructor + * @returns Migrated and cleaned source data which will be stored to the model instance + * System note: actually in `DataModel` + */ + protected _initializeSource( + data: Record, + options?: DocumentConstructionContext + ): this["_source"]; + + /** + * Reset the state of this data instance back to mirror the contained source data, erasing any changes. + */ + reset(): void; + + /* -------------------------------------------- */ + /* Configuration */ + /* -------------------------------------------- */ + + /** Default metadata which applies to each instance of this Document type. */ + static get metadata(): DocumentMetadata; + + /** + * The database backend used to execute operations and handle results + * @type {DatabaseBackend} + */ + static get database(): object; + + /** Return a reference to the implemented subclass of this base document type. */ + static get implementation(): typeof Document; + + /* -------------------------------------------- */ + /* Properties */ + /* -------------------------------------------- */ + + /** The named collection to which this Document belongs. */ + static get collectionName(): string; + + /** The canonical name of this Document type, for example "Actor". */ + get documentName(): string; + + /** The canonical name of this Document type, for example "Actor". */ + static get documentName(): string; + + /** The canonical identifier for this Document */ + get id(): string; + + /** Test whether this Document is embedded within a parent Document */ + get isEmbedded(): boolean; + + /** The name of this Document, if it has one assigned */ + name: string; + + /* ---------------------------------------- */ + /* Methods */ + /* ---------------------------------------- */ + + /** + * Test whether a given User has a sufficient role in order to create Documents of this type. + * @param user The User being tested + * @return Does the User have a sufficient role to create? + */ + static canUserCreate(user: BaseUser): boolean; + + /** + * Migrate candidate source data for this DataModel which may require initial cleaning or transformations. + * @param source The candidate source data from which the model will be constructed + * @returns Migrated source data, if necessary + */ + static migrateData(source: TSource): TSource; + + /** + * Update the DataModel locally by applying an object of changes to its source data. + * The provided changes are cleaned, validated, and stored to the source data object for this model. + * The source data is then re-initialized to apply those changes to the prepared data. + * The method returns an object of differential changes which modified the original data. + * + * @param changes New values which should be applied to the data model + * @param [options={}] Options which determine how the new data is merged + * @returns An object containing the changed keys and values + */ + updateSource(data?: DocumentUpdateData, options?: DocumentSourceUpdateContext): DeepPartial; + + /** + * Clone a document, creating a new document by combining current data with provided overrides. + * The cloned document is ephemeral and not yet saved to the database. + * @param [data={}] Additional data which overrides current document data at the time of creation + * @param [options={}] Additional options which customize the creation workflow + * @param [options.save=false] Save the clone to the World database? + * @param [options.keepId=false] Keep the original Document ID? Otherwise the ID will become undefined + * @returns The cloned Document instance + */ + clone(data: DocumentUpdateData | undefined, options: DocumentCloneOptions & { save: true }): Promise; + clone(data?: DocumentUpdateData, options?: DocumentCloneOptions & { save?: false }): this; + clone(data?: DocumentUpdateData, options?: DocumentCloneOptions): this | Promise; + + /** + * Get the permission level that a specific User has over this Document, a value in CONST.ENTITY_PERMISSIONS. + * @param user The User being tested + * @returns A numeric permission level from CONST.ENTITY_PERMISSIONS or null + */ + getUserLevel(user: BaseUser): DocumentOwnershipLevel | null; + + /** + * Test whether a certain User has a requested permission level (or greater) over the Document + * @param user The User being tested + * @param permission The permission level from DOCUMENT_PERMISSION_LEVELS to test + * @param options Additional options involved in the permission test + * @param [options.exact=false] Require the exact permission level requested? + * @return Does the user have this permission level over the Document? + */ + testUserPermission( + user: BaseUser, + permission: DocumentOwnershipString | DocumentOwnershipLevel, + { exact }?: { exact?: boolean } + ): boolean; + + /** + * Test whether a given User has permission to perform some action on this Document + * @param user The User attempting modification + * @param action The attempted action + * @param [data] Data involved in the attempted action + * @return Does the User have permission? + */ + canUserModify(user: BaseUser, action: UserAction, data?: Record): boolean; + + /* -------------------------------------------- */ + /* Database Operations */ + /* -------------------------------------------- */ + + /** + * Create multiple Documents using provided input data. + * Data is provided as an array of objects where each individual object becomes one new Document. + * + * @param data An array of data objects used to create multiple documents + * @param [context={}] Additional context which customizes the creation workflow + * @return An array of created Document instances + * + * @example Create a single Document + * const data = [{name: "New Actor", type: "character", img: "path/to/profile.jpg"}]; + * const created = await Actor.createDocuments(data); + * + * @example Create multiple Documents + * const data = [{name: "Tim", type: "npc"], [{name: "Tom", type: "npc"}]; + * const created = await Actor.createDocuments(data); + * + * @example Create multiple embedded Documents within a parent + * const actor = game.actors.getName("Tim"); + * const data = [{name: "Sword", type: "weapon"}, {name: "Breastplate", type: "equipment"}]; + * const created = await Item.createDocuments(data, {parent: actor}); + * + * @example Create a Document within a Compendium pack + * const data = [{name: "Compendium Actor", type: "character", img: "path/to/profile.jpg"}]; + * const created = await Actor.createDocuments(data, {pack: "mymodule.mypack"}); + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createDocuments>( + this: ConstructorOf, + data?: (TDocument | PreCreate)[], + context?: DocumentModificationContext + ): Promise; + + /** + * Update multiple Document instances using provided differential data. + * Data is provided as an array of objects where each individual object updates one existing Document. + * + * @param updates An array of differential data objects, each used to update a single Document + * @param [context={}] Additional context which customizes the update workflow + * @return An array of updated Document instances + * + * @example Update a single Document + * const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}]; + * const updated = await Actor.updateDocuments(updates); + * + * @example Update multiple Documents + * const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}, {_id: "kj549dk48k34jk34", name: "Thomas"}]}; + * const updated = await Actor.updateDocuments(updates); + * + * @example Update multiple embedded Documents within a parent + * const actor = game.actors.getName("Timothy"); + * const updates = [{_id: sword.id, name: "Magic Sword"}, {_id: shield.id, name: "Magic Shield"}]; + * const updated = await Item.updateDocuments(updates, {parent: actor}); + * + * @example Update Documents within a Compendium pack + * const actor = await pack.getDocument(documentId); + * const updated = await Actor.updateDocuments([{_id: actor.id, name: "New Name"}], {pack: "mymodule.mypack"}); + */ + static updateDocuments( + this: ConstructorOf, + updates?: DocumentUpdateData[], + context?: DocumentModificationContext + ): Promise; + + /** + * Delete one or multiple existing Documents using an array of provided ids. + * Data is provided as an array of string ids for the documents to delete. + * + * @param ids An array of string ids for the documents to be deleted + * @param [context={}] Additional context which customizes the deletion workflow + * @return An array of deleted Document instances + * + * @example Delete a single Document + * const tim = game.actors.getName("Tim"); + * const deleted = await Actor.deleteDocuments([tim.id]); + * + * @example Delete multiple Documents + * const tim = game.actors.getName("Tim"); + * const tom = game.actors.getName("Tom"); + * const deleted = await Actor.deleteDocuments([tim.id, tom.id]); + * + * @example Delete multiple embedded Documents within a parent + * const tim = game.actors.getName("Tim"); + * const sword = tim.items.getName("Sword"); + * const shield = tim.items.getName("Shield"); + * const deleted = await Item.deleteDocuments([sword.id, shield.id], parent: actor}); + * + * @example Delete Documents within a Compendium pack + * const actor = await pack.getDocument(documentId); + * const deleted = await Actor.deleteDocuments([actor.id], {pack: "mymodule.mypack"}); + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static deleteDocuments>( + this: ConstructorOf, + ids?: string[], + context?: DocumentModificationContext + ): Promise; + + /** + * Create a new Document using provided input data, saving it to the database. + * @see {@link Document.createDocuments} + * @param [data={}] Initial data used to create this Document + * @param [context={}] Additional context which customizes the creation workflow + * @return The created Document instance + * + * @example Create a World-level Item + * const data = [{name: "Special Sword", type: "weapon"}]; + * const created = await Item.create(data); + * + * @example Create an Actor-owned Item + * const data = [{name: "Special Sword", type: "weapon"}]; + * const actor = game.actors.getName("My Hero"); + * const created = await Item.create(data, {parent: actor}); + * + * @example Create an Item in a Compendium pack + * const data = [{name: "Special Sword", type: "weapon"}]; + * const created = await Item.create(data, {pack: "mymodule.mypack"}); + */ + static create( + this: ConstructorOf, + data: PreCreate, + context?: DocumentModificationContext + ): Promise; + static create( + this: ConstructorOf, + data: PreCreate[], + context?: DocumentModificationContext + ): Promise; + static create( + this: ConstructorOf, + data: PreCreate | PreCreate[], + context?: DocumentModificationContext + ): Promise; + + /** + * Update one or multiple existing entities using provided input data. + * Data may be provided as a single object to update one Document, or as an Array of Objects. + * @static + * + * @param data A Data object or array of Data. Each element must contain the _id of an existing Document. + * @param options Additional options which customize the update workflow + * @param [options.diff] Difference the provided data against the current to eliminate unnecessary changes. + * @param [options.noHook] Block the dispatch of preUpdate hooks for this operation. + * + * @return The updated Document or array of Entities + * + * @example + * const data = {_id: "12ekjf43kj2312ds", name: "New Name"}}; + * const updated = await Document.update(data); // Updated entity saved to the database + * + * @example + * const data = [{_id: "12ekjf43kj2312ds", name: "New Name 1"}, {_id: "kj549dk48k34jk34", name: "New Name 2"}]}; + * const updated = await Document.update(data); // Returns an Array of Entities, updated in the database + */ + update(data: DocumentUpdateData, options?: DocumentModificationContext): Promise; + + /** * Delete the current Document. * @see {Document.delete} * @param context Options which customize the deletion workflow * @return The deleted Document */ - delete(context?: DocumentModificationContext): Promise; - - /* -------------------------------------------- */ - /* Embedded Operations */ - /* -------------------------------------------- */ - - /** - * Obtain a reference to the Array of source data within the data object for a certain embedded Document name - * @param embeddedName The name of the embedded Document type - * @return The Collection instance of embedded Documents of the requested type - */ - getEmbeddedCollection(embeddedName: string): abstract.EmbeddedCollection>; - - /** - * Get an embedded document by it's id from a named collection in the parent document. - * @param embeddedName The name of the embedded Document type - * @param id The id of the child document to retrieve - * @param [options] Additional options which modify how embedded documents are retrieved - * @param [options.strict=false] Throw an Error if the requested id does not exist. See Collection#get - * @return The retrieved embedded Document instance, or undefined - */ - getEmbeddedDocument(embeddedName: string, id: string, { strict }: { strict: true }): Document; - getEmbeddedDocument( - embeddedName: string, - id: string, - { strict }: { strict: false } - ): Document | undefined; - getEmbeddedDocument( - embeddedName: string, - id: string, - { strict }?: { strict?: boolean } - ): Document | undefined; - - /** - * Create multiple embedded Document instances within this parent Document using provided input data. - * @see {@link Document.createDocuments} - * @param embeddedName The name of the embedded Document type - * @param data An array of data objects used to create multiple documents - * @param [context={}] Additional context which customizes the creation workflow - * @return An array of created Document instances - */ - createEmbeddedDocuments( - embeddedName: string, - data: PreCreate[], - context?: DocumentModificationContext - ): Promise; - - /** + delete(context?: DocumentModificationContext): Promise; + + /* -------------------------------------------- */ + /* Embedded Operations */ + /* -------------------------------------------- */ + + /** + * Obtain a reference to the Array of source data within the data object for a certain embedded Document name + * @param embeddedName The name of the embedded Document type + * @return The Collection instance of embedded Documents of the requested type + */ + getEmbeddedCollection(embeddedName: string): EmbeddedCollection>; + + /** + * Get an embedded document by it's id from a named collection in the parent document. + * @param embeddedName The name of the embedded Document type + * @param id The id of the child document to retrieve + * @param [options] Additional options which modify how embedded documents are retrieved + * @param [options.strict=false] Throw an Error if the requested id does not exist. See Collection#get + * @return The retrieved embedded Document instance, or undefined + */ + getEmbeddedDocument(embeddedName: string, id: string, { strict }: { strict: true }): Document; + getEmbeddedDocument(embeddedName: string, id: string, { strict }: { strict: false }): Document | undefined; + getEmbeddedDocument(embeddedName: string, id: string, { strict }?: { strict?: boolean }): Document | undefined; + + /** + * Create multiple embedded Document instances within this parent Document using provided input data. + * @see {@link Document.createDocuments} + * @param embeddedName The name of the embedded Document type + * @param data An array of data objects used to create multiple documents + * @param [context={}] Additional context which customizes the creation workflow + * @return An array of created Document instances + */ + createEmbeddedDocuments( + embeddedName: string, + data: PreCreate[], + context?: DocumentModificationContext + ): Promise; + + /** * Update one or multiple existing entities using provided input data. * Data may be provided as a single object to update one Document, or as an Array of Objects. /** @@ -379,279 +364,226 @@ declare global { * @param [context={}] Additional context which customizes the update workflow * @return An array of updated Document instances */ - updateEmbeddedDocuments( - embeddedName: string, - updateData: EmbeddedDocumentUpdateData[], - context?: DocumentUpdateContext - ): Promise; - - /** - * Delete multiple embedded Document instances within a parent Document using provided string ids. - * @see {@link Document.deleteDocuments} - * @param embeddedName The name of the embedded Document type - * @param ids An array of string ids for each Document to be deleted - * @param [context={}] Additional context which customizes the deletion workflow - * @return An array of deleted Document instances - */ - deleteEmbeddedDocuments( - embeddedName: string, - dataId: string[], - context?: DocumentModificationContext - ): Promise; - - /* -------------------------------------------- */ - /* Flag Operations */ - /* -------------------------------------------- */ - - /** - * Get the value of a "flag" for this document - * See the setFlag method for more details on flags - * - * @param scope The flag scope which namespaces the key - * @param key The flag key - * @return The flag value - */ - getFlag(scope: string, key: string): unknown; - - /** - * Assign a "flag" to this document. - * Flags represent key-value type data which can be used to store flexible or arbitrary data required by either - * the core software, game systems, or user-created modules. - * - * Each flag should be set using a scope which provides a namespace for the flag to help prevent collisions. - * - * Flags set by the core software use the "core" scope. - * Flags set by game systems or modules should use the canonical name attribute for the module - * Flags set by an individual world should "world" as the scope. - * - * Flag values can assume almost any data type. Setting a flag value to null will delete that flag. - * - * @param scope The flag scope which namespaces the key - * @param key The flag key - * @param value The flag value - * @return A Promise resolving to the updated document - */ - setFlag(scope: string, key: string, value: unknown): Promise; - - /** - * Remove a flag assigned to the Document - * @param scope The flag scope which namespaces the key - * @param key The flag key - * @return A Promise resolving to the updated Document - */ - unsetFlag(scope: string, key: string): Promise; - - /* -------------------------------------------- */ - /* Event Handlers */ - /* -------------------------------------------- */ - - /** - * Perform preliminary operations before a Document of this type is created. - * Pre-creation operations only occur for the client which requested the operation. - * @param data The initial data object provided to the document creation request - * @param options Additional options which modify the creation request - * @param user The User requesting the document creation - */ - protected _preCreate( - data: PreDocumentId, - options: DocumentModificationContext, - user: documents.BaseUser - ): Promise; - - /** - * Perform preliminary operations before a Document of this type is updated. - * Pre-update operations only occur for the client which requested the operation. - * @param changed The differential data that is changed relative to the documents prior values - * @param options Additional options which modify the update request - * @param user The User requesting the document update - */ - protected _preUpdate( - changed: DeepPartial, - options: DocumentUpdateContext, - user: documents.BaseUser - ): Promise; - - /** - * Perform preliminary operations before a Document of this type is deleted. - * Pre-delete operations only occur for the client which requested the operation. - * @param options Additional options which modify the deletion request - * @param user The User requesting the document deletion - */ - protected _preDelete( - options: DocumentModificationContext, - user: documents.BaseUser - ): Promise; - - /** - * Perform follow-up operations after a Document of this type is created. - * Post-creation operations occur for all clients after the creation is broadcast. - * @param data The initial data object provided to the document creation request - * @param options Additional options which modify the creation request - */ - protected _onCreate( - data: this["_source"], - options: DocumentModificationContext, - userId: string - ): void; - - /** - * Perform follow-up operations after a Document of this type is updated. - * Post-update operations occur for all clients after the update is broadcast. - * @param changed The differential data that was changed relative to the documents prior values - * @param options Additional options which modify the update request - * @param userId The ID of the User requesting the document update - */ - protected _onUpdate( - changed: DeepPartial, - options: DocumentUpdateContext, - userId: string - ): void; - - /** - * Perform follow-up operations after a Document of this type is deleted. - * Post-deletion operations occur for all clients after the deletion is broadcast. - * @param options Additional options which modify the deletion request - * @param userId The ID of the User requesting the document deletion - */ - protected _onDelete(options: DocumentModificationContext, userId: string): void; - - /** - * Perform follow-up operations when a set of Documents of this type are created. - * This is where side effects of creation should be implemented. - * Post-creation side effects are performed only for the client which requested the operation. - * @param documents The Document instances which were created - * @param context The context for the modification operation - */ - protected static _onCreateDocuments( - documents: Document[], - context: DocumentModificationContext - ): void; - - /** - * Perform follow-up operations when a set of Documents of this type are updated. - * This is where side effects of updates should be implemented. - * Post-update side effects are performed only for the client which requested the operation. - * @param documents The Document instances which were updated - * @param context The context for the modification operation - */ - protected static _onUpdateDocuments( - documents: Document[], - context: DocumentModificationContext - ): void; - - /** - * Perform follow-up operations when a set of Documents of this type are deleted. - * This is where side effects of deletion should be implemented. - * Post-deletion side effects are performed only for the client which requested the operation. - * @param documents The Document instances which were deleted - * @param context The context for the modification operation - */ - protected static _onDeleteDocuments( - documents: Document[], - context: DocumentModificationContext - ): void; - - /* ---------------------------------------- */ - /* Serialization and Storage */ - /* ---------------------------------------- */ - - /** - * Transform the Document instance into a plain object. - * The created object is an independent copy of the original data. - * See DocumentData#toObject - * @param [source=true] Draw values from the underlying data source rather than transformed values - * @returns The extracted primitive object - */ - toObject(source?: true): this["_source"]; - toObject(source: false): RawObject; - toObject(source?: boolean): this["_source"] | RawObject; - - /** - * Serializing an Document should simply serialize its inner data, not the entire instance - */ - toJSON(): RawObject; - } - - type MetadataPermission = - | keyof typeof CONST.USER_ROLES - | keyof typeof CONST.USER_PERMISSIONS - // eslint-disable-next-line @typescript-eslint/no-explicit-any - | ((...args: any[]) => boolean); - - interface DocumentMetadata { - collection: string; - embedded: Record>; - hasSystemData: boolean; - isEmbedded?: boolean; - isPrimary?: boolean; - name: string; - pack: null; - permissions: { - create: MetadataPermission; - update: MetadataPermission; - delete: MetadataPermission; - }; - types: string[] | Record; - } - } - } - - interface DocumentConstructionContext { - parent?: TParent; - pack?: string; - [key: string]: unknown; - } - - type DocumentSourceUpdateContext = Omit, "parent">; - - interface DocumentCloneOptions extends Omit, "parent"> { - save?: boolean; - keepId?: boolean; - } + updateEmbeddedDocuments( + embeddedName: string, + updateData: EmbeddedDocumentUpdateData[], + context?: DocumentUpdateContext + ): Promise; + + /** + * Delete multiple embedded Document instances within a parent Document using provided string ids. + * @see {@link Document.deleteDocuments} + * @param embeddedName The name of the embedded Document type + * @param ids An array of string ids for each Document to be deleted + * @param [context={}] Additional context which customizes the deletion workflow + * @return An array of deleted Document instances + */ + deleteEmbeddedDocuments( + embeddedName: string, + dataId: string[], + context?: DocumentModificationContext + ): Promise; + + /* -------------------------------------------- */ + /* Flag Operations */ + /* -------------------------------------------- */ + + /** + * Get the value of a "flag" for this document + * See the setFlag method for more details on flags + * + * @param scope The flag scope which namespaces the key + * @param key The flag key + * @return The flag value + */ + getFlag(scope: string, key: string): unknown; + + /** + * Assign a "flag" to this document. + * Flags represent key-value type data which can be used to store flexible or arbitrary data required by either + * the core software, game systems, or user-created modules. + * + * Each flag should be set using a scope which provides a namespace for the flag to help prevent collisions. + * + * Flags set by the core software use the "core" scope. + * Flags set by game systems or modules should use the canonical name attribute for the module + * Flags set by an individual world should "world" as the scope. + * + * Flag values can assume almost any data type. Setting a flag value to null will delete that flag. + * + * @param scope The flag scope which namespaces the key + * @param key The flag key + * @param value The flag value + * @return A Promise resolving to the updated document + */ + setFlag(scope: string, key: string, value: unknown): Promise; + + /** + * Remove a flag assigned to the Document + * @param scope The flag scope which namespaces the key + * @param key The flag key + * @return A Promise resolving to the updated Document + */ + unsetFlag(scope: string, key: string): Promise; + + /* -------------------------------------------- */ + /* Event Handlers */ + /* -------------------------------------------- */ + + /** + * Perform preliminary operations before a Document of this type is created. + * Pre-creation operations only occur for the client which requested the operation. + * @param data The initial data object provided to the document creation request + * @param options Additional options which modify the creation request + * @param user The User requesting the document creation + */ + protected _preCreate( + data: PreDocumentId, + options: DocumentModificationContext, + user: BaseUser + ): Promise; + + /** + * Perform preliminary operations before a Document of this type is updated. + * Pre-update operations only occur for the client which requested the operation. + * @param changed The differential data that is changed relative to the documents prior values + * @param options Additional options which modify the update request + * @param user The User requesting the document update + */ + protected _preUpdate( + changed: DeepPartial, + options: DocumentUpdateContext, + user: BaseUser + ): Promise; + + /** + * Perform preliminary operations before a Document of this type is deleted. + * Pre-delete operations only occur for the client which requested the operation. + * @param options Additional options which modify the deletion request + * @param user The User requesting the document deletion + */ + protected _preDelete(options: DocumentModificationContext, user: BaseUser): Promise; + + /** + * Perform follow-up operations after a Document of this type is created. + * Post-creation operations occur for all clients after the creation is broadcast. + * @param data The initial data object provided to the document creation request + * @param options Additional options which modify the creation request + */ + protected _onCreate(data: this["_source"], options: DocumentModificationContext, userId: string): void; + + /** + * Perform follow-up operations after a Document of this type is updated. + * Post-update operations occur for all clients after the update is broadcast. + * @param changed The differential data that was changed relative to the documents prior values + * @param options Additional options which modify the update request + * @param userId The ID of the User requesting the document update + */ + protected _onUpdate( + changed: DeepPartial, + options: DocumentUpdateContext, + userId: string + ): void; + + /** + * Perform follow-up operations after a Document of this type is deleted. + * Post-deletion operations occur for all clients after the deletion is broadcast. + * @param options Additional options which modify the deletion request + * @param userId The ID of the User requesting the document deletion + */ + protected _onDelete(options: DocumentModificationContext, userId: string): void; + + /** + * Perform follow-up operations when a set of Documents of this type are created. + * This is where side effects of creation should be implemented. + * Post-creation side effects are performed only for the client which requested the operation. + * @param documents The Document instances which were created + * @param context The context for the modification operation + */ + protected static _onCreateDocuments( + documents: Document[], + context: DocumentModificationContext + ): void; + + /** + * Perform follow-up operations when a set of Documents of this type are updated. + * This is where side effects of updates should be implemented. + * Post-update side effects are performed only for the client which requested the operation. + * @param documents The Document instances which were updated + * @param context The context for the modification operation + */ + protected static _onUpdateDocuments( + documents: Document[], + context: DocumentModificationContext + ): void; + + /** + * Perform follow-up operations when a set of Documents of this type are deleted. + * This is where side effects of deletion should be implemented. + * Post-deletion side effects are performed only for the client which requested the operation. + * @param documents The Document instances which were deleted + * @param context The context for the modification operation + */ + protected static _onDeleteDocuments( + documents: Document[], + context: DocumentModificationContext + ): void; + + /* ---------------------------------------- */ + /* Serialization and Storage */ + /* ---------------------------------------- */ + + /** + * Transform the Document instance into a plain object. + * The created object is an independent copy of the original data. + * See DocumentData#toObject + * @param [source=true] Draw values from the underlying data source rather than transformed values + * @returns The extracted primitive object + */ + toObject(source?: true): this["_source"]; + toObject(source: false): RawObject; + toObject(source?: boolean): this["_source"] | RawObject; + + /** + * Serializing an Document should simply serialize its inner data, not the entire instance + */ + toJSON(): RawObject; +} - interface DocumentModificationContext { - /** A parent Document within which these Documents should be embedded */ - parent?: TParent; - /** Block the dispatch of preCreate hooks for this operation */ - noHook?: boolean; - /** A Compendium pack identifier within which the Documents should be modified */ - pack?: string | null; - /** Return an index of the Document collection, used only during a get operation. */ - index?: boolean; - /** When performing a creation operation, keep the provided _id instead of clearing it. */ - keepId?: boolean; - /** When performing a creation operation, keep existing _id values of documents embedded within the one being created instead of generating new ones. */ - keepEmbeddedIds?: boolean; - /** Create a temporary document which is not saved to the database. Only used during creation. */ - temporary?: boolean; - /** Automatically re-render existing applications associated with the document. */ - render?: boolean; - /** Automatically create and render the Document sheet when the Document is first created. */ - renderSheet?: boolean; - /** Difference each update object against current Document data to reduce the size of the transferred data. Only used during update. */ - diff?: boolean; - /** Merge objects recursively. If false, inner objects will be replaced explicitly. Use with caution! */ - recursive?: boolean; - /** Whether to delete all documents of a given type, regardless of the array of ids provided. Only used during a delete operation. */ - deleteAll?: boolean; - } +type MetadataPermission = + | keyof typeof CONST.USER_ROLES + | keyof typeof CONST.USER_PERMISSIONS + // eslint-disable-next-line @typescript-eslint/no-explicit-any + | ((...args: any[]) => boolean); + +export interface DocumentMetadata { + collection: string; + embedded: Record>; + hasSystemData: boolean; + isEmbedded?: boolean; + isPrimary?: boolean; + name: string; + pack: null; + permissions: { + create: MetadataPermission; + update: MetadataPermission; + delete: MetadataPermission; + }; + types: string[] | Record; +} - type DocumentUpdateContext = Omit< - DocumentModificationContext, - "deleteAll" | "index" | "keepId" | "keepEmbeddedIds" | "temporary" - >; +type _Document = Document<_Document | null>; +declare global { type PreCreate = T extends { name: string; type: string } ? Omit, "name" | "type"> & { name: string; type: T["type"] } : DeepPartial; type PreDocumentId = Omit & { _id: null }; - type DocumentUpdateData = - | Partial - | Record; + type DocumentUpdateData = Partial | Record; - type EmbeddedDocumentUpdateData = DocumentUpdateData & { _id: string }; + type EmbeddedDocumentUpdateData = DocumentUpdateData & { _id: string }; interface DocumentRenderOptions extends RenderOptions { data?: { @@ -661,15 +593,20 @@ declare global { type DocumentFlags = Record | undefined>; - type RawObject = { - [P in keyof T["_source"]]: T[P] extends foundry.abstract.EmbeddedCollection + type RawObject = { + [P in keyof T["_source"]]: T[P] extends EmbeddedCollection ? RawObject[] - : T[P] extends foundry.abstract.Document + : T[P] extends Document ? RawObject - : T[P] extends foundry.abstract.Document[] + : T[P] extends Document[] ? RawObject[] : T[P]; }; -} -type _Document = foundry.abstract.Document<_Document | null>; + interface DocumentCloneOptions extends Omit, "parent"> { + save?: boolean; + keepId?: boolean; + } + + type DocumentSourceUpdateContext = Omit, "parent">; +} diff --git a/types/foundry/common/abstract/embedded-collection.d.mts b/types/foundry/common/abstract/embedded-collection.d.mts index 1a6be8795ca..f811cbc3bcb 100644 --- a/types/foundry/common/abstract/embedded-collection.d.mts +++ b/types/foundry/common/abstract/embedded-collection.d.mts @@ -1,4 +1,5 @@ -import { DataModel, RawObject } from "./data.mjs"; +import type DataModel from "./data.d.ts"; +import type { RawObject } from "./data.d.ts"; /** * An extension of the Collection. @@ -9,7 +10,7 @@ export class EmbeddedCollection extends Collection>): TModel; + new (data: TModel["_source"], context?: DataModelConstructionOptions): TModel; } ); diff --git a/types/foundry/common/abstract/embedded-collection.d.ts b/types/foundry/common/abstract/embedded-collection.d.ts index 64f060de6ff..f4421fb14af 100644 --- a/types/foundry/common/abstract/embedded-collection.d.ts +++ b/types/foundry/common/abstract/embedded-collection.d.ts @@ -1,31 +1,23 @@ -export {}; -declare global { - module foundry { - module abstract { - /** - * An extension of the Collection. - * Used for the specific task of containing embedded Document instances within a parent Document. - * @param sourceArray The source data array for the collection in the parent Document data - */ - class EmbeddedCollection> extends utils.Collection { - constructor( - sourceArray: TDocument["_source"][], - documentClass: { - new ( - data: TDocument["_source"], - context?: DocumentConstructionContext - ): TDocument; - } - ); +import type Document from "./document.d.ts"; - override set(key: string, value: TDocument, { modifySource }?: { modifySource?: boolean }): this; +/** + * An extension of the Collection. + * Used for the specific task of containing embedded Document instances within a parent Document. + * @param sourceArray The source data array for the collection in the parent Document data + */ +export default class EmbeddedCollection> extends Collection { + constructor( + sourceArray: TDocument["_source"][], + documentClass: { + new (data: TDocument["_source"], context?: DocumentConstructionContext): TDocument; + } + ); - override delete(key: string, { modifySource }?: { modifySource?: boolean }): boolean; + override set(key: string, value: TDocument, { modifySource }?: { modifySource?: boolean }): this; - toObject(source?: T): TDocument["_source"][]; - toObject(source: T): RawObject[]; - toObject(source?: T): TDocument["_source"][] | RawObject[]; - } - } - } + override delete(key: string, { modifySource }?: { modifySource?: boolean }): boolean; + + toObject(source?: T): TDocument["_source"][]; + toObject(source: T): RawObject[]; + toObject(source?: T): TDocument["_source"][] | RawObject[]; } diff --git a/types/foundry/common/abstract/index.d.ts b/types/foundry/common/abstract/index.d.ts deleted file mode 100644 index d1825b161bf..00000000000 --- a/types/foundry/common/abstract/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import "./document.js"; -import "./embedded-collection.js"; diff --git a/types/foundry/common/abstract/module.d.ts b/types/foundry/common/abstract/module.d.ts index 28bec827431..0b9211cfff1 100644 --- a/types/foundry/common/abstract/module.d.ts +++ b/types/foundry/common/abstract/module.d.ts @@ -1,2 +1,4 @@ -export * from "./data.mjs"; -export * from "./embedded-collection.mjs"; +export { default as DataModel } from "./data.ts"; +export { default as Document } from "./document.ts"; +export { default as EmbeddedCollection } from "./embedded-collection.ts"; +export type * from "./document.d.ts"; diff --git a/types/foundry/common/data/data.d.ts b/types/foundry/common/data/data.d.ts new file mode 100644 index 00000000000..1945194fc4c --- /dev/null +++ b/types/foundry/common/data/data.d.ts @@ -0,0 +1,156 @@ +import type { Document, DataModel } from "../abstract/module.d.ts"; +import type { BaseActor } from "../documents/module.d.ts"; +import type { TokenBarData, TokenSource } from "../documents/token.d.ts"; +import type { + AlphaField, + AngleField, + BooleanField, + ColorField, + ModelPropsFromSchema, + NumberField, + SchemaField, + StringField, +} from "./fields.d.ts"; + +/** + * An embedded data object which defines the properties of a light source animation + * @property type The animation type which is applied + * @property speed The speed of the animation, a number between 1 and 10 + * @property intensity The intensity of the animation, a number between 1 and 10 + */ +export interface AnimationData { + type: string; + speed: number; + intensity: number; +} + +/** + * An embedded data object which defines the darkness range during which some attribute is active + * @property [min=0] The minimum darkness level for which activation occurs + * @property [max=1] The maximum darkness level for which activation occurs + */ +export interface DarknessActivation { + min: number; + max: number; +} + +/** + * A reusable document structure for the internal data used to render the appearance of a light source. + * This is re-used by both the AmbientLightData and TokenData classes. + * + * @property alpha An opacity for the emitted light, if any + * @property animation An animation configuration for the source + * @property angle The angle of emission for this point source + * @property bright The allowed radius of bright vision or illumination + * @property color A tint color for the emitted light, if any + * @property coloration The coloration technique applied in the shader + * @property contrast The amount of contrast this light applies to the background texture + * @property darkness A darkness range (min and max) for which the source should be active + * @property dim The allowed radius of dim vision or illumination + * @property invertColor Does this source invert the color of the background texture? + * @property gradual Fade the difference between bright, dim, and dark gradually? + * @property luminosity The luminosity applied in the shader + * @property saturation The amount of color saturation this light applies to the background texture + * @property shadows The depth of shadows this light applies to the background texture + */ +export class LightData extends DataModel { + static override defineSchema(): LightDataSchema; + + static override migrateData(source: TSource): TSource; +} + +export interface LightData + extends DataModel, + ModelPropsFromSchema {} + +export type LightSource = SourceFromSchema; + +type LightDataSchema = { + alpha: AlphaField; + angle: AngleField; + bright: NumberField; + color: ColorField; + coloration: NumberField; + dim: NumberField; + attenuation: NumberField; + luminosity: NumberField; + saturation: NumberField; + constrast: NumberField; + shadows: NumberField; + animation: SchemaField<{ + type: StringField; + speed: NumberField; + intensity: NumberField; + reverse: BooleanField; + }>; + darkness: SchemaField<{ + min: AlphaField; + speed: AlphaField; + }>; +}; + +export interface PrototypeTokenSource + extends Omit< + TokenSource, + "_id" | "actorId" | "actorData" | "x" | "y" | "elevation" | "effects" | "overlayEffect" | "hidden" + > { + name: string; + randomImg: boolean; +} + +export class PrototypeToken extends Document { + protected override _initialize(): void; + + override toJSON(): RawObject; + + lightAnimation: AnimationData; + + bar1: TokenBarData; + + bar2: TokenBarData; +} + +export interface PrototypeToken extends Omit { + readonly _source: PrototypeTokenSource; +} + +export interface TextureData { + /** The URL of the texture source. */ + src: string | null; + /** The scale of the texture in the X dimension. */ + scaleX: number; + /** The scale of the texture in the Y dimension. */ + scaleY: number; + /** The X offset of the texture with (0,0) in the top left. */ + offsetX: number; + /** The Y offset of the texture with (0,0) in the top left. */ + offsetY: number; + /** An angle of rotation by which this texture is rotated around its center. */ + rotation: number; + /** An optional color string used to tint the texture. */ + tint: number | null; +} + +/** + * An embedded data object which defines the properties of a light source animation + * @property mode The occlusion mode from CONST.TILE_OCCLUSION_MODES + * @property alpha The occlusion alpha between 0 and 1 + * @property [radius] An optional radius of occlusion used for RADIAL mode + */ +export interface TileOcclusion { + mode: TileOcclusionMode; + alpha: number; + radius?: number; +} + +/** + * An inner-object which defines the schema for how Tile video backgrounds are managed + * @property loop Automatically loop the video? + * @property autoplay Should the video play automatically? + * @property volume The volume level of any audio that the video file contains + */ +export interface VideoData { + loop: boolean; + autoplay: boolean; + volume: boolean; +} diff --git a/types/foundry/common/data/data/animation-data.d.ts b/types/foundry/common/data/data/animation-data.d.ts deleted file mode 100644 index 6d464be3a1f..00000000000 --- a/types/foundry/common/data/data/animation-data.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -declare module foundry { - module data { - /** - * An embedded data object which defines the properties of a light source animation - * @property type The animation type which is applied - * @property speed The speed of the animation, a number between 1 and 10 - * @property intensity The intensity of the animation, a number between 1 and 10 - */ - interface AnimationData { - type: string; - speed: number; - intensity: number; - } - } -} diff --git a/types/foundry/common/data/data/darkness-activation.d.ts b/types/foundry/common/data/data/darkness-activation.d.ts deleted file mode 100644 index 4e0a900e31e..00000000000 --- a/types/foundry/common/data/data/darkness-activation.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -declare module foundry { - module data { - /** - * An embedded data object which defines the darkness range during which some attribute is active - * @property [min=0] The minimum darkness level for which activation occurs - * @property [max=1] The maximum darkness level for which activation occurs - */ - interface DarknessActivation { - min: number; - max: number; - } - } -} diff --git a/types/foundry/common/data/data/index.d.ts b/types/foundry/common/data/data/index.d.ts deleted file mode 100644 index 8894287e028..00000000000 --- a/types/foundry/common/data/data/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import "./animation-data.js"; -import "./darkness-activation.js"; -import "./light-data.js"; -import "./prototype-token-data.js"; -import "./texture-data.js"; -import "./tile-occlusion.js"; -import "./video-data.js"; diff --git a/types/foundry/common/data/data/light-data.d.ts b/types/foundry/common/data/data/light-data.d.ts deleted file mode 100644 index 2729c0e6b6c..00000000000 --- a/types/foundry/common/data/data/light-data.d.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { DataModel } from "../../abstract/data.mjs"; -import { - AlphaField, - AngleField, - BooleanField, - ColorField, - ModelPropsFromSchema, - NumberField, - SchemaField, - StringField, -} from "../fields.js"; - -declare global { - module foundry { - module data { - /** - * A reusable document structure for the internal data used to render the appearance of a light source. - * This is re-used by both the AmbientLightData and TokenData classes. - * - * @property alpha An opacity for the emitted light, if any - * @property animation An animation configuration for the source - * @property angle The angle of emission for this point source - * @property bright The allowed radius of bright vision or illumination - * @property color A tint color for the emitted light, if any - * @property coloration The coloration technique applied in the shader - * @property contrast The amount of contrast this light applies to the background texture - * @property darkness A darkness range (min and max) for which the source should be active - * @property dim The allowed radius of dim vision or illumination - * @property invertColor Does this source invert the color of the background texture? - * @property gradual Fade the difference between bright, dim, and dark gradually? - * @property luminosity The luminosity applied in the shader - * @property saturation The amount of color saturation this light applies to the background texture - * @property shadows The depth of shadows this light applies to the background texture - */ - class LightData extends DataModel { - static override defineSchema(): LightDataSchema; - - static override migrateData(source: TSource): TSource; - } - - interface LightData - extends DataModel, - ModelPropsFromSchema {} - - type LightSource = SourceFromSchema; - } - } -} - -type LightDataSchema = { - alpha: AlphaField; - angle: AngleField; - bright: NumberField; - color: ColorField; - coloration: NumberField; - dim: NumberField; - attenuation: NumberField; - luminosity: NumberField; - saturation: NumberField; - constrast: NumberField; - shadows: NumberField; - animation: SchemaField<{ - type: StringField; - speed: NumberField; - intensity: NumberField; - reverse: BooleanField; - }>; - darkness: SchemaField<{ - min: AlphaField; - speed: AlphaField; - }>; -}; diff --git a/types/foundry/common/data/data/prototype-token-data.d.ts b/types/foundry/common/data/data/prototype-token-data.d.ts deleted file mode 100644 index 4daf91d8b29..00000000000 --- a/types/foundry/common/data/data/prototype-token-data.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -declare namespace foundry { - module data { - interface PrototypeTokenSource - extends Omit< - documents.TokenSource, - "_id" | "actorId" | "actorData" | "x" | "y" | "elevation" | "effects" | "overlayEffect" | "hidden" - > { - name: string; - randomImg: boolean; - } - - class PrototypeToken extends abstract.Document { - protected override _initialize(): void; - - override toJSON(): RawObject; - - lightAnimation: AnimationData; - - bar1: documents.TokenBarData; - - bar2: documents.TokenBarData; - } - - interface PrototypeToken extends Omit { - readonly _source: PrototypeTokenSource; - } - } -} diff --git a/types/foundry/common/data/data/texture-data.d.ts b/types/foundry/common/data/data/texture-data.d.ts deleted file mode 100644 index a686381b2e3..00000000000 --- a/types/foundry/common/data/data/texture-data.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -declare module foundry { - module data { - interface TextureData { - /** The URL of the texture source. */ - src: string | null; - /** The scale of the texture in the X dimension. */ - scaleX: number; - /** The scale of the texture in the Y dimension. */ - scaleY: number; - /** The X offset of the texture with (0,0) in the top left. */ - offsetX: number; - /** The Y offset of the texture with (0,0) in the top left. */ - offsetY: number; - /** An angle of rotation by which this texture is rotated around its center. */ - rotation: number; - /** An optional color string used to tint the texture. */ - tint: number | null; - } - } -} diff --git a/types/foundry/common/data/data/tile-occlusion.d.ts b/types/foundry/common/data/data/tile-occlusion.d.ts deleted file mode 100644 index 9e049903560..00000000000 --- a/types/foundry/common/data/data/tile-occlusion.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -declare module foundry { - module data { - /** - * An embedded data object which defines the properties of a light source animation - * @property mode The occlusion mode from CONST.TILE_OCCLUSION_MODES - * @property alpha The occlusion alpha between 0 and 1 - * @property [radius] An optional radius of occlusion used for RADIAL mode - */ - interface TileOcclusion { - mode: TileOcclusionMode; - alpha: number; - radius?: number; - } - } -} diff --git a/types/foundry/common/data/data/video-data.d.ts b/types/foundry/common/data/data/video-data.d.ts deleted file mode 100644 index ff355433404..00000000000 --- a/types/foundry/common/data/data/video-data.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -declare module foundry { - module data { - /** - * An inner-object which defines the schema for how Tile video backgrounds are managed - * @property loop Automatically loop the video? - * @property autoplay Should the video play automatically? - * @property volume The volume level of any audio that the video file contains - */ - interface VideoData { - loop: boolean; - autoplay: boolean; - volume: boolean; - } - } -} diff --git a/types/foundry/common/data/fields.d.ts b/types/foundry/common/data/fields.d.ts index 2606094da9e..aa7ea14627c 100644 --- a/types/foundry/common/data/fields.d.ts +++ b/types/foundry/common/data/fields.d.ts @@ -1,4 +1,5 @@ -import { DataModel, EmbeddedCollection } from "../abstract/module.js"; +import type DataModel from "../abstract/data.d.ts"; +import type { EmbeddedCollection } from "../abstract/embedded-collection.d.mts"; /* ---------------------------------------- */ /* Abstract Data Field */ @@ -11,7 +12,7 @@ import { DataModel, EmbeddedCollection } from "../abstract/module.js"; * @property [initial] The initial value of a field, or a function which assigns that initial value. * @property [validate] A data validation function which accepts one argument with the current value. * @property [choices] An array of values or an object of values/labels which represent allowed choices for the - field. A function may be provided which dynamically returns the array of choices. + * field. A function may be provided which dynamically returns the array of choices. * @property [label] A localizable label displayed on forms which render this field. * @property [hint] Localizable help text displayed on forms which render this field. * @property [validationError] A custom validation error string. When displayed will be prepended with the @@ -37,6 +38,21 @@ export interface DataFieldOptions< validationError?: string; } +/** + * An abstract class that defines the base pattern for a data field within a data schema. + * + * @property name The name of this data field within the schema that contains it + * @property [required=false] Is this field required to be populated? + * @property [nullable=false] Can this field have null values? + * @property initial The initial value of a field, or a function which assigns that initial value. + * @property validate A data validation function which accepts one argument with the current value. + * @property [readonly=false] Should the prepared value of the field be read-only, preventing it from being + * changed unless a change to the _source data is applied. + * @property {string} label A localizable label displayed on forms which render this field. + * @property {string} hint Localizable help text displayed on forms which render this field. + * @property {string} validationError A custom validation error string. When displayed will be prepended with the + * document name, field name, and candidate value. + */ export abstract class DataField< TSourceProp = unknown, TModelProp = TSourceProp, diff --git a/types/foundry/common/data/index.d.ts b/types/foundry/common/data/index.d.ts deleted file mode 100644 index 6442c0d9929..00000000000 --- a/types/foundry/common/data/index.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import * as Fields from "./fields.js"; - -declare global { - module foundry { - module data { - export import fields = Fields; - } - } -} diff --git a/types/foundry/common/data/module.d.ts b/types/foundry/common/data/module.d.ts index 9cfb5047384..efa98d17626 100644 --- a/types/foundry/common/data/module.d.ts +++ b/types/foundry/common/data/module.d.ts @@ -1,2 +1,3 @@ -export * as fields from "./fields.js"; -export * from "./validators.js"; +export * as fields from "./fields.ts"; +export * as validators from "./validators.ts"; +export * from "./data.ts"; diff --git a/types/foundry/common/data/validators.d.ts b/types/foundry/common/data/validators.d.ts index adfd5d5b84f..3db8958cd4a 100644 --- a/types/foundry/common/data/validators.d.ts +++ b/types/foundry/common/data/validators.d.ts @@ -1,61 +1,55 @@ -declare module foundry { - module data { - module validators { - /** Test whether a string is a valid 16 character UID */ - function isValidId(id: string): boolean; - - /** Test whether a file path has an extension in a list of provided extensions */ - function _hasFileExtension(path: string, extensions: string[]): path is `${string}.${string}`; - - /** - * Test whether a file path has a valid image file extension or is base64 PNG data - * @param path The image path to test - * @return Is the path valid? - */ - function hasImageExtension(path: string): path is ImageFilePath; - - /** - * Test whether a data blob represents a base64 image - * @param data A base64 data string - * @return Is it a base64 image? - */ - function isBase64Image(data: string): data is `data:image/${string}`; - - /** - * Test whether an input represents a valid 6-character color string - * @param color The input string to test - * @return Is the string a valid color? - */ - function isColorString(color: string): color is HexColorString; - - /** - * Test whether a file path has a valid audio file extension - * @param path The image path to test - * @return Is the path valid? - */ - function hasVideoExtension(path: string): path is VideoFilePath; - - /** - * Test whether a file path has a valid video file extension - * @param path The image path to test - * @return Is the path valid? - */ - function hasAudioExtension(path: string): path is AudioFilePath; - - /** - * Assert that the given value is in an array of allowed options - * @param val The value to test - * @param array The set of allowed options - * @return Is the valid included? - */ - function valueInArray(val: unknown, array: T): val is T[number]; - - /** - * Assert that the given value parses as a valid JSON string - * @param val The value to test - * @return Is the String valid JSON? - */ - function isJSON(val: string): boolean; - } - } -} +/** Test whether a string is a valid 16 character UID */ +export function isValidId(id: string): boolean; + +/** Test whether a file path has an extension in a list of provided extensions */ +export function _hasFileExtension(path: string, extensions: string[]): path is `${string}.${string}`; + +/** + * Test whether a file path has a valid image file extension or is base64 PNG data + * @param path The image path to test + * @return Is the path valid? + */ +export function hasImageExtension(path: string): path is ImageFilePath; + +/** + * Test whether a data blob represents a base64 image + * @param data A base64 data string + * @return Is it a base64 image? + */ +export function isBase64Image(data: string): data is `data:image/${string}`; + +/** + * Test whether an input represents a valid 6-character color string + * @param color The input string to test + * @return Is the string a valid color? + */ +export function isColorString(color: string): color is HexColorString; + +/** + * Test whether a file path has a valid audio file extension + * @param path The image path to test + * @return Is the path valid? + */ +export function hasVideoExtension(path: string): path is VideoFilePath; + +/** + * Test whether a file path has a valid video file extension + * @param path The image path to test + * @return Is the path valid? + */ +export function hasAudioExtension(path: string): path is AudioFilePath; + +/** + * Assert that the given value is in an array of allowed options + * @param val The value to test + * @param array The set of allowed options + * @return Is the valid included? + */ +export function valueInArray(val: unknown, array: T): val is T[number]; + +/** + * Assert that the given value parses as a valid JSON string + * @param val The value to test + * @return Is the String valid JSON? + */ +export function isJSON(val: string): boolean; diff --git a/types/foundry/common/documents/active-effect.d.ts b/types/foundry/common/documents/active-effect.d.ts index b58001bead3..bc870f84fb8 100644 --- a/types/foundry/common/documents/active-effect.d.ts +++ b/types/foundry/common/documents/active-effect.d.ts @@ -1,95 +1,94 @@ -declare module foundry { - module documents { - /** - * The ActiveEffect document model. - * @param data Initial data from which to construct the document. - * @property data The constructed data object for the document. - */ - class BaseActiveEffect< - TParent extends BaseActor | BaseItem | null - > extends abstract.Document { - static override get metadata(): ActiveEffectMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseActor, BaseItem, BaseUser } from "./module.d.ts"; - protected override _preCreate( - data: PreDocumentId, - options: DocumentModificationContext, - user: BaseUser - ): Promise; +/** + * The ActiveEffect document model. + * @param data Initial data from which to construct the document. + * @property data The constructed data object for the document. + */ +export default class BaseActiveEffect< + TParent extends BaseActor | BaseItem | null +> extends Document { + static override get metadata(): ActiveEffectMetadata; - override testUserPermission( - user: BaseUser, - permission: DocumentOwnershipString | DocumentOwnershipLevel, - { exact }?: { exact?: boolean } - ): boolean; - } + protected override _preCreate( + data: PreDocumentId, + options: DocumentModificationContext, + user: BaseUser + ): Promise; - interface BaseActiveEffect | null> - extends abstract.Document { - readonly _source: ActiveEffectSource; - } + override testUserPermission( + user: BaseUser, + permission: DocumentOwnershipString | DocumentOwnershipLevel, + { exact }?: { exact?: boolean } + ): boolean; +} + +export default interface BaseActiveEffect | null> + extends Document { + readonly _source: ActiveEffectSource; +} - /** - * @property _id The EmbeddedEntity id of the Active Effect - * @property label The label which describes this effect - * @property [disabled] Is this effect currently disabled? - * @property [icon] An image icon path for this effect - * @property [tint] A hex color string to tint the effect icon - * @property [origin] The UUID of an Entity or EmbeddedEntity which was the source of this effect - * @property [transfer] Should this effect transfer automatically to an Actor when its Item becomes owned? - * @property flags Additional key/value flags - */ - interface ActiveEffectSource { - _id: string; - label: string; - duration: EffectDurationSource; - changes: EffectChangeSource[]; - disabled: boolean; - icon: ImageFilePath; - tint: string; - origin: string | undefined; - transfer: boolean; - flags: Record; - } +/** + * @property _id The EmbeddedEntity id of the Active Effect + * @property label The label which describes this effect + * @property [disabled] Is this effect currently disabled? + * @property [icon] An image icon path for this effect + * @property [tint] A hex color string to tint the effect icon + * @property [origin] The UUID of an Entity or EmbeddedEntity which was the source of this effect + * @property [transfer] Should this effect transfer automatically to an Actor when its Item becomes owned? + * @property flags Additional key/value flags + */ +export interface ActiveEffectSource { + _id: string; + label: string; + duration: EffectDurationSource; + changes: EffectChangeSource[]; + disabled: boolean; + icon: ImageFilePath; + tint: string; + origin: string | undefined; + transfer: boolean; + flags: Record; +} - /** - * An embedded data structure which tracks the duration of an ActiveEffect. - * @property startTime The world time when the active effect first started - * @property [seconds] The maximum duration of the effect, in seconds - * @property [combat] The _id of the CombatEncounter in which the effect first started - * @property [rounds] The maximum duration of the effect, in combat rounds - * @property [turns] The maximum duration of the effect, in combat turns - * @property [startRound] The round of the CombatEncounter in which the effect first started - * @property [startTurn] The turn of the CombatEncounter in which the effect first started - */ - interface EffectDurationSource { - startTime: number; - seconds: number | undefined; - combat?: string; - rounds: number | undefined; - turns: number | undefined; - startRound: number | null; - startTurn: number | null; - } +/** + * An embedded data structure which tracks the duration of an ActiveEffect. + * @property startTime The world time when the active effect first started + * @property [seconds] The maximum duration of the effect, in seconds + * @property [combat] The _id of the CombatEncounter in which the effect first started + * @property [rounds] The maximum duration of the effect, in combat rounds + * @property [turns] The maximum duration of the effect, in combat turns + * @property [startRound] The round of the CombatEncounter in which the effect first started + * @property [startTurn] The turn of the CombatEncounter in which the effect first started + */ +export interface EffectDurationSource { + startTime: number; + seconds: number | undefined; + combat?: string; + rounds: number | undefined; + turns: number | undefined; + startRound: number | null; + startTurn: number | null; +} - /** - * An embedded data structure which defines the structure of a change applied by an ActiveEffect. - * @property key The attribute path in the Actor or Item data which the change modifies - * @property value The value of the change effect - * @property mode The modification mode with which the change is applied - * @property priority The priority level with which this change is applied - */ - interface EffectChangeSource { - key: string; - value: string; - mode: ActiveEffectChangeMode; - priority: number; - } +/** + * An embedded data structure which defines the structure of a change applied by an ActiveEffect. + * @property key The attribute path in the Actor or Item data which the change modifies + * @property value The value of the change effect + * @property mode The modification mode with which the change is applied + * @property priority The priority level with which this change is applied + */ +export interface EffectChangeSource { + key: string; + value: string; + mode: ActiveEffectChangeMode; + priority: number; +} - interface ActiveEffectMetadata extends abstract.DocumentMetadata { - name: "ActiveEffect"; - collection: "effects"; - label: "DOCUMENT.ActiveEffect"; - isEmbedded: true; - } - } +export interface ActiveEffectMetadata extends DocumentMetadata { + name: "ActiveEffect"; + collection: "effects"; + label: "DOCUMENT.ActiveEffect"; + isEmbedded: true; } diff --git a/types/foundry/common/documents/actor.d.ts b/types/foundry/common/documents/actor.d.ts index 9798fa7ab47..f9d71c3c64f 100644 --- a/types/foundry/common/documents/actor.d.ts +++ b/types/foundry/common/documents/actor.d.ts @@ -1,125 +1,126 @@ -declare module foundry { - module documents { - /** - * The Actor document model. - * @param data Initial data from which to construct the document. - * @property data The constructed data object for the document. - */ - class BaseActor extends abstract.Document { - prototypeToken: data.PrototypeToken; +import type { Document, DocumentMetadata, EmbeddedCollection } from "../abstract/module.d.ts"; +import type { ActiveEffectSource } from "./active-effect.d.ts"; +import type { ItemSource } from "./item.d.ts"; +import type { BaseActiveEffect, BaseItem, BaseToken, BaseUser } from "./module.d.ts"; - /** The default icon used for newly created Actor documents */ - static DEFAULT_ICON: ImageFilePath; +/** + * The Actor document model. + * @param data Initial data from which to construct the document. + * @property data The constructed data object for the document. + */ +export default class BaseActor extends Document { + prototypeToken: foundry.data.PrototypeToken; - static override get metadata(): ActorMetadata; + /** The default icon used for newly created Actor documents */ + static DEFAULT_ICON: ImageFilePath; - /** A Collection of Item embedded Documents */ - readonly items: abstract.EmbeddedCollection>; + static override get metadata(): ActorMetadata; - /** A Collection of ActiveEffect embedded Documents */ - readonly effects: abstract.EmbeddedCollection>; + /** A Collection of Item embedded Documents */ + readonly items: EmbeddedCollection>; - /** - * Migrate the system data object to conform to data model defined by the current system version. - * @see mergeObject - * @param options Options which customize how the system data is migrated. - * @param options.insertKeys Retain keys which exist in the current data, but not the model - * @param options.insertValues Retain inner-object values which exist in the current data, but not the model - * @param options.enforceTypes Require that data types match the model exactly to be retained - * @return The migrated system data object, not yet saved to the database - */ - migrateSystemData({ - insertKeys, - insertValues, - enforceTypes, - }?: { - insertKeys?: boolean; - insertValues?: boolean; - enforceTypes?: boolean; - }): this["system"]; + /** A Collection of ActiveEffect embedded Documents */ + readonly effects: EmbeddedCollection>; - protected override _preCreate( - data: PreDocumentId, - options: DocumentModificationContext, - user: BaseUser - ): Promise; + /** + * Migrate the system data object to conform to data model defined by the current system version. + * @see mergeObject + * @param options Options which customize how the system data is migrated. + * @param options.insertKeys Retain keys which exist in the current data, but not the model + * @param options.insertValues Retain inner-object values which exist in the current data, but not the model + * @param options.enforceTypes Require that data types match the model exactly to be retained + * @return The migrated system data object, not yet saved to the database + */ + migrateSystemData({ + insertKeys, + insertValues, + enforceTypes, + }?: { + insertKeys?: boolean; + insertValues?: boolean; + enforceTypes?: boolean; + }): this["system"]; - protected override _preUpdate( - changed: DocumentUpdateData, - options: DocumentModificationContext, - user: BaseUser - ): Promise; - } + protected override _preCreate( + data: PreDocumentId, + options: DocumentModificationContext, + user: BaseUser + ): Promise; - interface BaseActor extends abstract.Document { - flags: ActorFlags; - readonly _source: ActorSource; - system: object; + protected override _preUpdate( + changed: DocumentUpdateData, + options: DocumentModificationContext, + user: BaseUser + ): Promise; +} - get documentName(): (typeof BaseActor)["metadata"]["name"]; - } +export default interface BaseActor extends Document { + flags: ActorFlags; + readonly _source: ActorSource; + system: object; - /** - * The data schema for a Actor document. - * @see BaseActor - * - * @param data Initial data used to construct the data object - * @param [document] The document to which this data object belongs - * - * @property _id The _id which uniquely identifies this Actor document - * @property name The name of this Actor - * @property type An Actor subtype which configures the system data model applied - * @property [img] An image file path which provides the artwork for this Actor - * @property [data] The system data object which is defined by the system template.json model - * @property [token] Default Token settings which are used for Tokens created from this Actor - * @property items A Collection of Item embedded Documents - * @property effects A Collection of ActiveEffect embedded Documents - * @property folder The _id of a Folder which contains this Actor - * @property [sort] The numeric sort value which orders this Actor relative to its siblings - * @property [ownership] An object which configures user permissions to this Actor - * @property [flags={}] An object of optional key/value flags - */ - interface ActorSource< - TType extends string = string, - TSystemSource extends object = object, - TItemSource extends ItemSource = ItemSource - > { - _id: string; - name: string; - type: TType; - img: ImageFilePath; - system: TSystemSource; - prototypeToken: data.PrototypeTokenSource; - items: TItemSource[]; - effects: ActiveEffectSource[]; - folder: string | null; - sort: number; - ownership: Record; - flags: ActorFlags; - } + get documentName(): (typeof BaseActor)["metadata"]["name"]; +} - interface ActorFlags extends DocumentFlags { - core?: { - sourceId?: ActorUUID; - }; - } +/** + * The data schema for a Actor document. + * @see BaseActor + * + * @param data Initial data used to construct the data object + * @param [document] The document to which this data object belongs + * + * @property _id The _id which uniquely identifies this Actor document + * @property name The name of this Actor + * @property type An Actor subtype which configures the system data model applied + * @property [img] An image file path which provides the artwork for this Actor + * @property [data] The system data object which is defined by the system template.json model + * @property [token] Default Token settings which are used for Tokens created from this Actor + * @property items A Collection of Item embedded Documents + * @property effects A Collection of ActiveEffect embedded Documents + * @property folder The _id of a Folder which contains this Actor + * @property [sort] The numeric sort value which orders this Actor relative to its siblings + * @property [ownership] An object which configures user permissions to this Actor + * @property [flags={}] An object of optional key/value flags + */ +export interface ActorSource< + TType extends string = string, + TSystemSource extends object = object, + TItemSource extends ItemSource = ItemSource +> { + _id: string; + name: string; + type: TType; + img: ImageFilePath; + system: TSystemSource; + prototypeToken: foundry.data.PrototypeTokenSource; + items: TItemSource[]; + effects: ActiveEffectSource[]; + folder: string | null; + sort: number; + ownership: Record; + flags: ActorFlags; +} + +export interface ActorFlags extends DocumentFlags { + core?: { + sourceId?: ActorUUID; + }; +} - interface ActorMetadata extends abstract.DocumentMetadata { - name: "Actor"; - collection: "actors"; - label: "DOCUMENT.Actor"; - embedded: { - ActiveEffect: typeof BaseActiveEffect; - Item: typeof BaseItem; - }; - isPrimary: true; - hasSystemData: true; - permissions: { - create: "ACTOR_CREATE"; - update: "ASSISTANT"; - delete: "ASSISTANT"; - }; - types: string[]; - } - } +export interface ActorMetadata extends DocumentMetadata { + name: "Actor"; + collection: "actors"; + label: "DOCUMENT.Actor"; + embedded: { + ActiveEffect: typeof BaseActiveEffect; + Item: typeof BaseItem; + }; + isPrimary: true; + hasSystemData: true; + permissions: { + create: "ACTOR_CREATE"; + update: "ASSISTANT"; + delete: "ASSISTANT"; + }; + types: string[]; } diff --git a/types/foundry/common/documents/adventure.d.ts b/types/foundry/common/documents/adventure.d.ts index 2ea3282af6f..796d179798f 100644 --- a/types/foundry/common/documents/adventure.d.ts +++ b/types/foundry/common/documents/adventure.d.ts @@ -1,75 +1,74 @@ -declare module foundry { - module documents { - /** - * The base User document, which is extended by both the server and client. - * This base User provides shared functionality which is consistent for both sides of the application. - * Each client who connects to a Foundry Virtual Tabletop session assumes the identity of one (and only one) User. - * - * @param data Initial data from which to construct the document. - * @property data The constructed data object for the document. - */ - class BaseAdventure extends abstract.Document { - static override get metadata(): AdventureMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseUser } from "./module.d.ts"; - /* ---------------------------------------- */ - /* Permissions */ - /* ---------------------------------------- */ +/** + * The base User document, which is extended by both the server and client. + * This base User provides shared functionality which is consistent for both sides of the application. + * Each client who connects to a Foundry Virtual Tabletop session assumes the identity of one (and only one) User. + * + * @param data Initial data from which to construct the document. + * @property data The constructed data object for the document. + */ +export default class BaseAdventure extends Document { + static override get metadata(): AdventureMetadata; - /** Test whether the User has a GAMEMASTER or ASSISTANT role in this World? */ - get isGM(): boolean; + /* ---------------------------------------- */ + /* Permissions */ + /* ---------------------------------------- */ - /** - * Test whether the User is able to perform a certain permission action. - * The provided permission string may pertain to an explicit permission setting or a named user role. - * Alternatively, Gamemaster users are assumed to be allowed to take all actions. - * - * @param action The action to test - * @return Does the user have the ability to perform this action? - */ - can(action: UserAction): boolean; + /** Test whether the User has a GAMEMASTER or ASSISTANT role in this World? */ + get isGM(): boolean; - getUserLevel(user: BaseUser): DocumentOwnershipLevel; + /** + * Test whether the User is able to perform a certain permission action. + * The provided permission string may pertain to an explicit permission setting or a named user role. + * Alternatively, Gamemaster users are assumed to be allowed to take all actions. + * + * @param action The action to test + * @return Does the user have the ability to perform this action? + */ + can(action: UserAction): boolean; - /** - * Test whether the User has at least a specific permission - * @param permission The permission name from USER_PERMISSIONS to test - * @return Does the user have at least this permission - */ - hasPermission(permission: UserPermission): boolean; + getUserLevel(user: BaseUser): DocumentOwnershipLevel; - /** - * Test whether the User has at least the permission level of a certain role - * @param role The role name from USER_ROLES to test - * @param [exact] Require the role match to be exact - * @return Does the user have at this role level (or greater)? - */ - hasRole(role: UserRole | UserRoleName, { exact }?: { exact: boolean }): boolean; - } + /** + * Test whether the User has at least a specific permission + * @param permission The permission name from USER_PERMISSIONS to test + * @return Does the user have at least this permission + */ + hasPermission(permission: UserPermission): boolean; - interface BaseAdventure extends abstract.Document { - readonly _source: AdventureSource; + /** + * Test whether the User has at least the permission level of a certain role + * @param role The role name from USER_ROLES to test + * @param [exact] Require the role match to be exact + * @return Does the user have at this role level (or greater)? + */ + hasRole(role: UserRole | UserRoleName, { exact }?: { exact: boolean }): boolean; +} + +export default interface BaseAdventure extends Document { + readonly _source: AdventureSource; - get documentName(): "Adventure"; - } + get documentName(): "Adventure"; +} - interface AdventureMetadata extends abstract.DocumentMetadata { - name: "Adventure"; - collection: "Adventures"; - label: "DOCUMENT.Adventure"; - isPrimary: true; - } +interface AdventureMetadata extends DocumentMetadata { + name: "Adventure"; + collection: "Adventures"; + label: "DOCUMENT.Adventure"; + isPrimary: true; +} - interface AdventureSource { - _id: string; - avatar: ImageFilePath; - img: ImageFilePath; - character: string | null; - color: HexColorString; - hotbar: Record; - name: string; - password: string; - role: UserRole; - flags: DocumentFlags; - } - } +interface AdventureSource { + _id: string; + avatar: ImageFilePath; + img: ImageFilePath; + character: string | null; + color: HexColorString; + hotbar: Record; + name: string; + password: string; + role: UserRole; + flags: DocumentFlags; } diff --git a/types/foundry/common/documents/ambient-light.d.ts b/types/foundry/common/documents/ambient-light.d.ts index aa04778f7a7..42ef6565030 100644 --- a/types/foundry/common/documents/ambient-light.d.ts +++ b/types/foundry/common/documents/ambient-light.d.ts @@ -1,49 +1,48 @@ -declare module foundry { - module documents { - /** The AmbientLight embedded document model. */ - class BaseAmbientLight extends abstract.Document { - static override get metadata(): AmbientLightMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseScene } from "./module.d.ts"; - config: data.LightSource; +/** The AmbientLight embedded document model. */ +export default class BaseAmbientLight extends Document { + static override get metadata(): AmbientLightMetadata; - protected override _initialize(): void; - } + config: foundry.data.LightData; - interface BaseAmbientLight extends abstract.Document { - readonly _source: AmbientLightSource; - } + protected override _initialize(): void; +} + +export default interface BaseAmbientLight extends Document { + readonly _source: AmbientLightSource; +} - /** - * The data schema for a AmbientLight embedded document. - * - * @property _id The _id which uniquely identifies this BaseAmbientLight embedded document - * @property [x=0] The x-coordinate position of the origin of the light - * @property [y=0] The y-coordinate position of the origin of the light - * @property [rotation=0] The angle of rotation for the tile between 0 and 360 - * @property [walls=true] Whether or not this light source is constrained by Walls - * @property [vision=false] Whether or not this light source provides a source of vision - * @property config Light configuration data - * @property [hidden=false] Is the light source currently hidden? - * @property [flags={}] An object of optional key/value flags - */ - interface AmbientLightSource { - _id: string; - t: string; - x: number; - y: number; - rotation: number; - walls: boolean; - vision: boolean; - config: data.LightSource; - hidden: boolean; - flags: Record; - } +/** + * The data schema for a AmbientLight embedded document. + * + * @property _id The _id which uniquely identifies this BaseAmbientLight embedded document + * @property [x=0] The x-coordinate position of the origin of the light + * @property [y=0] The y-coordinate position of the origin of the light + * @property [rotation=0] The angle of rotation for the tile between 0 and 360 + * @property [walls=true] Whether or not this light source is constrained by Walls + * @property [vision=false] Whether or not this light source provides a source of vision + * @property config Light configuration data + * @property [hidden=false] Is the light source currently hidden? + * @property [flags={}] An object of optional key/value flags + */ +interface AmbientLightSource { + _id: string; + t: string; + x: number; + y: number; + rotation: number; + walls: boolean; + vision: boolean; + config: foundry.data.LightSource; + hidden: boolean; + flags: Record; +} - interface AmbientLightMetadata extends abstract.DocumentMetadata { - name: "AmbientLight"; - collection: "lights"; - label: "DOCUMENT.AmbientLight"; - isEmbedded: true; - } - } +interface AmbientLightMetadata extends DocumentMetadata { + name: "AmbientLight"; + collection: "lights"; + label: "DOCUMENT.AmbientLight"; + isEmbedded: true; } diff --git a/types/foundry/common/documents/ambient-sound.d.ts b/types/foundry/common/documents/ambient-sound.d.ts index 7e5085a8ec4..1818382f727 100644 --- a/types/foundry/common/documents/ambient-sound.d.ts +++ b/types/foundry/common/documents/ambient-sound.d.ts @@ -1,49 +1,48 @@ -declare module foundry { - module documents { - /** The AmbientSound embedded document model. */ - class BaseAmbientSound extends abstract.Document { - static override get metadata(): AmbientSoundMetadata; - } +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseScene } from "./module.d.ts"; - interface BaseAmbientSound extends abstract.Document { - readonly _source: AmbientSoundSource; - } +/** The AmbientSound embedded document model. */ +export default class BaseAmbientSound extends Document { + static override get metadata(): AmbientSoundMetadata; +} + +export default interface BaseAmbientSound extends Document { + readonly _source: AmbientSoundSource; +} - interface AmbientSoundMetadata extends abstract.DocumentMetadata { - name: "AmbientSound"; - collection: "sounds"; - label: "DOCUMENT.AmbientSound"; - isEmbedded: true; - types: ["l", "g"]; - } +interface AmbientSoundMetadata extends DocumentMetadata { + name: "AmbientSound"; + collection: "sounds"; + label: "DOCUMENT.AmbientSound"; + isEmbedded: true; + types: ["l", "g"]; +} - /** - * The data schema for a AmbientSound embedded document. - * @see BaseAmbientSound - * - * @param data Initial data used to construct the data object - * @param [document] The document to which this data object belongs - * - * @property _id The _id which uniquely identifies this AmbientSound document - * @property path The audio file path that is played by this sound - * @property [playing=false] Is this sound currently playing? - * @property [repeat=false] Does this sound loop? - * @property [volume=0.5] The audio volume of the sound, from 0 to 1 - * @property [flags={}] An object of optional key/value flags - */ - interface AmbientSoundSource { - _id: string; - type: string; - x: number; - y: number; - radius: number; - path: AudioFilePath; - repeat: boolean; - volume: number; - easing: boolean; - hidden: boolean; - darkness: data.DarknessActivation; - flags: DocumentFlags; - } - } +/** + * The data schema for a AmbientSound embedded document. + * @see BaseAmbientSound + * + * @param data Initial data used to construct the data object + * @param [document] The document to which this data object belongs + * + * @property _id The _id which uniquely identifies this AmbientSound document + * @property path The audio file path that is played by this sound + * @property [playing=false] Is this sound currently playing? + * @property [repeat=false] Does this sound loop? + * @property [volume=0.5] The audio volume of the sound, from 0 to 1 + * @property [flags={}] An object of optional key/value flags + */ +export interface AmbientSoundSource { + _id: string; + type: string; + x: number; + y: number; + radius: number; + path: AudioFilePath; + repeat: boolean; + volume: number; + easing: boolean; + hidden: boolean; + darkness: foundry.data.DarknessActivation; + flags: DocumentFlags; } diff --git a/types/foundry/common/documents/card.d.ts b/types/foundry/common/documents/card.d.ts new file mode 100644 index 00000000000..de8677abdcd --- /dev/null +++ b/types/foundry/common/documents/card.d.ts @@ -0,0 +1,13 @@ +import type { Document } from "../abstract/module.d.ts"; +import type { BaseCards } from "./module.d.ts"; + +/** + * The Document definition for a Card. + * Defines the DataSchema and common behaviors for a Card which are shared between both client and server. + * @memberof documents + * + * @param data Initial data from which to construct the Card + * @param context Construction context options + * @todo Fill in + */ +export default class BaseCard extends Document {} diff --git a/types/foundry/common/documents/cards.d.ts b/types/foundry/common/documents/cards.d.ts index 76a52a08b73..8776041a6bd 100644 --- a/types/foundry/common/documents/cards.d.ts +++ b/types/foundry/common/documents/cards.d.ts @@ -1,66 +1,67 @@ -declare module foundry { - module documents { - /** The base Cards definition which defines common behavior of an Cards document shared by both client and server. */ - class BaseCards extends abstract.Document { - static override get metadata(): abstract.DocumentMetadata; +import type { Document, DocumentMetadata, EmbeddedCollection } from "../abstract/module.d.ts"; +import type { BaseCard, BaseUser } from "./module.d.ts"; - /** The sub-type of Card. */ - readonly type: string; +/** The base Cards definition which defines common behavior of an Cards document shared by both client and server. */ +export default class BaseCards extends Document { + static override get metadata(): DocumentMetadata; - /** Is a User able to create a new embedded Card document within this parent? */ - protected static _canCreate(user: BaseUser, doc: BaseCards, data: object): boolean; + /** The sub-type of Card. */ + readonly type: string; - /** Is a user able to update an existing Card? */ - protected static _canUpdate(user: BaseUser, doc: BaseCards, data: object): boolean; + /** Is a User able to create a new embedded Card document within this parent? */ + protected static _canCreate(user: BaseUser, doc: BaseCards, data: object): boolean; - override testUserPermission( - user: BaseUser, - permission: DocumentOwnershipString | DocumentOwnershipLevel, - { exact }?: { exact?: boolean } - ): boolean; - } + /** Is a user able to update an existing Card? */ + protected static _canUpdate(user: BaseUser, doc: BaseCards, data: object): boolean; - interface BaseCards extends abstract.Document { - readonly _source: CardsSource; + readonly cards: EmbeddedCollection>; - get documentName(): "Cards"; - } + override testUserPermission( + user: BaseUser, + permission: DocumentOwnershipString | DocumentOwnershipLevel, + { exact }?: { exact?: boolean } + ): boolean; +} + +export default interface BaseCards extends Document { + readonly _source: CardsSource; + + get documentName(): "Cards"; +} - /** - * The data schema of a stack of multiple Cards. - * Each stack can represent a Deck, a Hand, or a Pile. - */ - interface CardsSource<> { - /** The _id which uniquely identifies this stack of Cards document */ - _id: string; - /** The text name of this stack */ - name: string; - /** The type of this stack, in BaseCards.metadata.types */ - type: string; - /** A text description of this stack */ - description: string; - /** An image or video which is used to represent the stack of cards */ - img: VideoFilePath; - /** Game system data which is defined by the system template.json model */ - data: object; - /** A collection of Card documents which currently belong to this stack */ - cards: object; - /** The visible width of this stack */ - width: number; - /** The visible height of this stack */ - height: number; - /** The angle of rotation of this stack */ - rotation: string; - /** Whether or not to publicly display the number of cards in this stack */ - displayCount?: boolean; - /** The _id of a Folder which contains this document */ - folder?: string | null; - /** The sort order of this stack relative to others in its parent collection */ - sort: number; - /** An object which configures user permissions to this stack */ - ownership: Record; - /** An object of optional key/value flags */ - flags: Record>; - } - } +/** + * The data schema of a stack of multiple Cards. + * Each stack can represent a Deck, a Hand, or a Pile. + */ +interface CardsSource { + /** The _id which uniquely identifies this stack of Cards document */ + _id: string; + /** The text name of this stack */ + name: string; + /** The type of this stack, in BaseCards.metadata.types */ + type: string; + /** A text description of this stack */ + description: string; + /** An image or video which is used to represent the stack of cards */ + img: VideoFilePath; + /** Game system data which is defined by the system template.json model */ + data: object; + /** A collection of Card documents which currently belong to this stack */ + cards: object; + /** The visible width of this stack */ + width: number; + /** The visible height of this stack */ + height: number; + /** The angle of rotation of this stack */ + rotation: string; + /** Whether or not to publicly display the number of cards in this stack */ + displayCount?: boolean; + /** The _id of a Folder which contains this document */ + folder?: string | null; + /** The sort order of this stack relative to others in its parent collection */ + sort: number; + /** An object which configures user permissions to this stack */ + ownership: Record; + /** An object of optional key/value flags */ + flags: Record>; } diff --git a/types/foundry/common/documents/chat-message.d.ts b/types/foundry/common/documents/chat-message.d.ts index 4e36e63683d..b2eb89d4773 100644 --- a/types/foundry/common/documents/chat-message.d.ts +++ b/types/foundry/common/documents/chat-message.d.ts @@ -1,105 +1,105 @@ -declare module foundry { - module documents { - /** - * The ChatMessage document model. - * @extends Document - * @memberof documents - * - * @param data Initial data from which to construct the document. - * @property data The constructed data object for the document. - */ - class BaseChatMessage extends abstract.Document { - blind: boolean; - content: string; - flags: ChatMessageFlags; - rolls: Rolled[]; - speaker: ChatSpeakerData; - type: ChatMessageType; - whisper: string[]; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseUser } from "./module.d.ts"; - static override get metadata(): ChatMessageMetadata; +/** + * The ChatMessage document model. + * @memberof documents + * + * @param data Initial data from which to construct the document. + * @property data The constructed data object for the document. + */ +export default class BaseChatMessage extends Document { + blind: boolean; + content: string; + flags: ChatMessageFlags; + rolls: Rolled[]; + speaker: ChatSpeakerData; + type: ChatMessageType; + whisper: string[]; - /** Is a user able to create a new chat message? */ - protected static _canCreate(user: BaseUser, doc: BaseChatMessage): boolean; + static override get metadata(): ChatMessageMetadata; - /** Is a user able to update an existing chat message? */ - protected static _canUpdate(user: BaseUser, doc: BaseChatMessage, data: ChatMessageSource): boolean; + /** Is a user able to create a new chat message? */ + protected static _canCreate(user: BaseUser, doc: BaseChatMessage): boolean; - /** Is a user able to delete an existing chat message? */ - protected static _canDelete(user: BaseUser, doc: BaseChatMessage): boolean; + /** Is a user able to update an existing chat message? */ + protected static _canUpdate(user: BaseUser, doc: BaseChatMessage, data: ChatMessageSource): boolean; - static override createDocuments>( - this: ConstructorOf, - data?: (TDocument | PreCreate)[], - context?: ChatMessageModificationContext - ): Promise; - } + /** Is a user able to delete an existing chat message? */ + protected static _canDelete(user: BaseUser, doc: BaseChatMessage): boolean; - interface BaseChatMessage extends abstract.Document { - readonly _source: ChatMessageSource; + static override createDocuments>( + this: ConstructorOf, + data?: (TDocument | PreCreate)[], + context?: ChatMessageModificationContext + ): Promise; +} + +export default interface BaseChatMessage extends Document { + readonly _source: ChatMessageSource; - get documentName(): "ChatMessage"; - } + get documentName(): "ChatMessage"; +} - interface ChatMessageSource { - _id: string; - type: ChatMessageType; - user: string; - timestamp: string; - flavor?: string; - content: string; - speaker: ChatSpeakerData; - whisper: string[]; - blind: boolean; - rolls: (string | RollJSON)[]; - sound: AudioFilePath; - emote?: boolean; - flags: ChatMessageFlags; - } +export interface ChatMessageSource { + _id: string; + type: ChatMessageType; + user: string; + timestamp: string; + flavor?: string; + content: string; + speaker: ChatSpeakerData; + whisper: string[]; + blind: boolean; + rolls: (string | RollJSON)[]; + sound: AudioFilePath; + emote?: boolean; + flags: ChatMessageFlags; +} - interface ChatMessageFlags extends DocumentFlags { - core?: { - canPopout?: boolean; - initiativeRoll?: boolean; - RollTable?: string; - }; - } +export interface ChatMessageFlags extends DocumentFlags { + core?: { + canPopout?: boolean; + initiativeRoll?: boolean; + RollTable?: string; + }; +} - /** - * The data schema for an embedded Chat Speaker object. - * @extends DocumentData - * @memberof data - * @see ChatMessageData - * - * @param data Initial data used to construct the data object - * @param [document] The document to which this data object belongs - * - * @property [scene] The _id of the Scene where this message was created - * @property [actor] The _id of the Actor who generated this message - * @property [token] The _id of the Token who generated this message - * @property [alias] An overridden alias name used instead of the Actor or Token name - */ - interface ChatSpeakerData { - scene?: string | null; - actor?: string | null; - token?: string | null; - alias: string; - } +/** + * The data schema for an embedded Chat Speaker object. + * @extends DocumentData + * @memberof data + * @see ChatMessageData + * + * @param data Initial data used to construct the data object + * @param [document] The document to which this data object belongs + * + * @property [scene] The _id of the Scene where this message was created + * @property [actor] The _id of the Actor who generated this message + * @property [token] The _id of the Token who generated this message + * @property [alias] An overridden alias name used instead of the Actor or Token name + */ +export interface ChatSpeakerData { + scene?: string | null; + actor?: string | null; + token?: string | null; + alias: string; +} - interface ChatMessageMetadata extends abstract.DocumentMetadata { - name: "ChatMessage"; - collection: "messages"; - label: "DOCUMENT.ChatMessage"; - isPrimary: true; - permissions: { - create: (typeof BaseChatMessage)["_canCreate"]; - update: (typeof BaseChatMessage)["_canUpdate"]; - delete: (typeof BaseChatMessage)["_canDelete"]; - }; - } - } +interface ChatMessageMetadata extends DocumentMetadata { + name: "ChatMessage"; + collection: "messages"; + label: "DOCUMENT.ChatMessage"; + isPrimary: true; + permissions: { + create: (typeof BaseChatMessage)["_canCreate"]; + update: (typeof BaseChatMessage)["_canUpdate"]; + delete: (typeof BaseChatMessage)["_canDelete"]; + }; } -declare interface ChatMessageModificationContext extends DocumentModificationContext { - rollMode?: RollMode | "roll"; +declare global { + interface ChatMessageModificationContext extends DocumentModificationContext { + rollMode?: RollMode | "roll"; + } } diff --git a/types/foundry/common/documents/combat.d.ts b/types/foundry/common/documents/combat.d.ts index 3cc4c1ba3a4..f84289a6d84 100644 --- a/types/foundry/common/documents/combat.d.ts +++ b/types/foundry/common/documents/combat.d.ts @@ -1,59 +1,59 @@ -declare module foundry { - module documents { - /** The Combat document model. */ - class BaseCombat extends abstract.Document { - static override get metadata(): CombatMetadata; - - flags: DocumentFlags; - - /** A reference to the Collection of Combatant instances in the Combat document, indexed by id. */ - readonly combatants: abstract.EmbeddedCollection>; - - /** Is a user able to update an existing Combat? */ - protected static _canUpdate(user: documents.BaseUser, doc: BaseCombat, data: CombatSource): boolean; - } - - interface BaseCombat extends abstract.Document { - readonly _source: CombatSource; - - get documentName(): "Combat"; - } - - interface CombatMetadata extends abstract.DocumentMetadata { - name: "Combat"; - collection: "combats"; - label: "DOCUMENT.Combat"; - embedded: { - Combatant: typeof BaseCombatant; - }; - isPrimary: true; - permissions: { - create: "ASSISTANT"; - update: (typeof BaseCombat)["_canUpdate"]; - delete: "ASSISTANT"; - }; - } - - /** - * The data schema for a Combat document. - * @property _id The _id which uniquely identifies this Combat document - * @property scene The _id of a Scene within which this Combat occurs - * @property combatants A Collection of Combatant embedded Documents - * @property [active=false] Is the Combat encounter currently active? - * @property [round=0] The current round of the Combat encounter - * @property [turn=0] The current turn in the Combat round - * @property [sort=0] The current sort order of this Combat relative to others in the same Scene - * @property [flags={}] An object of optional key/value flags - */ - interface CombatSource { - _id: string; - scene: string; - combatants: CombatantSource[]; - active: boolean; - round: number; - turn: number; - sort: number; - flags: DocumentFlags; - } - } +import type { Document, DocumentMetadata, EmbeddedCollection } from "../abstract/module.d.ts"; +import type { CombatantSource } from "./combatant.d.ts"; +import type { BaseCombatant, BaseUser } from "./module.d.ts"; + +/** The Combat document model. */ +export default class BaseCombat extends Document { + static override get metadata(): CombatMetadata; + + flags: DocumentFlags; + + /** A reference to the Collection of Combatant instances in the Combat document, indexed by id. */ + readonly combatants: EmbeddedCollection>; + + /** Is a user able to update an existing Combat? */ + protected static _canUpdate(user: BaseUser, doc: BaseCombat, data: CombatSource): boolean; +} + +export default interface BaseCombat extends Document { + readonly _source: CombatSource; + + get documentName(): "Combat"; +} + +interface CombatMetadata extends DocumentMetadata { + name: "Combat"; + collection: "combats"; + label: "DOCUMENT.Combat"; + embedded: { + Combatant: typeof BaseCombatant; + }; + isPrimary: true; + permissions: { + create: "ASSISTANT"; + update: (typeof BaseCombat)["_canUpdate"]; + delete: "ASSISTANT"; + }; +} + +/** + * The data schema for a Combat document. + * @property _id The _id which uniquely identifies this Combat document + * @property scene The _id of a Scene within which this Combat occurs + * @property combatants A Collection of Combatant embedded Documents + * @property [active=false] Is the Combat encounter currently active? + * @property [round=0] The current round of the Combat encounter + * @property [turn=0] The current turn in the Combat round + * @property [sort=0] The current sort order of this Combat relative to others in the same Scene + * @property [flags={}] An object of optional key/value flags + */ +interface CombatSource { + _id: string; + scene: string; + combatants: CombatantSource[]; + active: boolean; + round: number; + turn: number; + sort: number; + flags: DocumentFlags; } diff --git a/types/foundry/common/documents/combatant.d.ts b/types/foundry/common/documents/combatant.d.ts index 630c0aa5c02..bd56c3553c7 100644 --- a/types/foundry/common/documents/combatant.d.ts +++ b/types/foundry/common/documents/combatant.d.ts @@ -1,56 +1,51 @@ -declare module foundry { - module documents { - /** The Combat document model. */ - class BaseCombatant extends abstract.Document { - static override get metadata(): CombatantMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseCombat, BaseUser } from "./module.d.ts"; - flags: DocumentFlags; +/** The Combat document model. */ +export default class BaseCombatant extends Document { + static override get metadata(): CombatantMetadata; - /** Is a user able to update an existing Combatant? */ - protected static _canUpdate( - user: documents.BaseUser, - doc: BaseCombatant, - data: CombatantSource - ): boolean; - } + flags: DocumentFlags; - interface BaseCombatant extends CombatantSource, abstract.Document { - readonly _source: CombatantSource; - } + /** Is a user able to update an existing Combatant? */ + protected static _canUpdate(user: BaseUser, doc: BaseCombatant, data: CombatantSource): boolean; +} + +export default interface BaseCombatant extends CombatantSource, Document { + readonly _source: CombatantSource; +} - interface CombatantMetadata extends abstract.DocumentMetadata { - name: "Combatant"; - collection: "combatants"; - label: "DOCUMENT.Combatant"; - isPrimary: true; - permissions: { - create: "PLAYER"; - update: (typeof BaseCombatant)["_canUpdate"]; - delete: "ASSISTANT"; - }; - } +interface CombatantMetadata extends DocumentMetadata { + name: "Combatant"; + collection: "combatants"; + label: "DOCUMENT.Combatant"; + isPrimary: true; + permissions: { + create: "PLAYER"; + update: (typeof BaseCombatant)["_canUpdate"]; + delete: "ASSISTANT"; + }; +} - /** - * The data schema for a Combat document. - * @property _id The _id which uniquely identifies this Combatant embedded document - * @property [tokenId] The _id of a Token associated with this Combatant - * @property [name] A customized name which replaces the name of the Token in the tracker - * @property [img] A customized image which replaces the Token image in the tracker - * @property [initiative] The initiative score for the Combatant which determines its turn order - * @property [hidden=false] Is this Combatant currently hidden? - * @property [defeated=false] Has this Combatant been defeated? - * @property [flags={}] An object of optional key/value flags - */ - interface CombatantSource { - _id: string | null; - actorId: string; - sceneId: string; - tokenId: string; - img: VideoFilePath; - initiative: number | null; - hidden: boolean; - defeated: boolean; - flags: DocumentFlags; - } - } +/** + * The data schema for a Combat document. + * @property _id The _id which uniquely identifies this Combatant embedded document + * @property [tokenId] The _id of a Token associated with this Combatant + * @property [name] A customized name which replaces the name of the Token in the tracker + * @property [img] A customized image which replaces the Token image in the tracker + * @property [initiative] The initiative score for the Combatant which determines its turn order + * @property [hidden=false] Is this Combatant currently hidden? + * @property [defeated=false] Has this Combatant been defeated? + * @property [flags={}] An object of optional key/value flags + */ +export interface CombatantSource { + _id: string | null; + actorId: string; + sceneId: string; + tokenId: string; + img: VideoFilePath; + initiative: number | null; + hidden: boolean; + defeated: boolean; + flags: DocumentFlags; } diff --git a/types/foundry/common/documents/drawing.d.ts b/types/foundry/common/documents/drawing.d.ts index 5e7386b0afd..62bea08fe2f 100644 --- a/types/foundry/common/documents/drawing.d.ts +++ b/types/foundry/common/documents/drawing.d.ts @@ -1,88 +1,83 @@ -declare module foundry { - module documents { - /** The Drawing embedded document model. */ - class BaseDrawing extends abstract.Document { - static override get metadata(): DrawingMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseScene, BaseUser } from "./module.d.ts"; - /** Is a user able to update or delete an existing Drawing document? */ - protected static _canModify( - user: BaseUser, - doc: BaseDrawing, - data: DrawingSource - ): boolean; - } +/** The Drawing embedded document model. */ +export default class BaseDrawing extends Document { + static override get metadata(): DrawingMetadata; - interface BaseDrawing extends abstract.Document { - readonly _source: DrawingSource; - } + /** Is a user able to update or delete an existing Drawing document? */ + protected static _canModify(user: BaseUser, doc: BaseDrawing, data: DrawingSource): boolean; +} + +export default interface BaseDrawing extends Document { + readonly _source: DrawingSource; +} - /** - * The data schema for a Drawing embedded document. - * @see BaseDrawing - * - * @param data Initial data used to construct the data object - * @param [document] The embedded document to which this data object belongs - * - * @property t The value in CONST.DRAWING_TYPES which defines the geometry type of this drawing - * @property x The x-coordinate position of the top-left corner of the drawn shape - * @property y The y-coordinate position of the top-left corner of the drawn shape - * @property width The pixel width of the drawing figure - * @property height The pixel height of the drawing figure - * @property [rotation=0] The angle of rotation for the drawing figure - * @property [z=0] The z-index of this drawing relative to other siblings - * @property [points] An array of points [x,y] which define polygon vertices - * @property [bezierFactor=0] An amount of bezier smoothing applied, between 0 and 1 - * @property [fillType=0] The fill type of the drawing shape, a value from CONST.DRAWING_FILL_TYPES - * @property [fillColor] An optional color string with which to fill the drawing geometry - * @property [fillAlpha=0.5] The opacity of the fill applied to the drawing geometry - * @property [strokeWidth=8] The width in pixels of the boundary lines of the drawing geometry - * @property [strokeColor] The color of the boundary lines of the drawing geometry - * @property [strokeAlpha=1] The opacity of the boundary lines of the drawing geometry - * @property [texture] The path to a tiling image texture used to fill the drawing geometry - * @property [text] Optional text which is displayed overtop of the drawing - * @property [fontFamily=Signika] The font family used to display text within this drawing - * @property [fontSize=48] The font size used to display text within this drawing - * @property [textColor=#FFFFFF] The color of text displayed within this drawing - * @property [textAlpha=1] The opacity of text displayed within this drawing - * @property [hidden=false] Is the drawing currently hidden? - * @property [locked=false] Is the drawing currently locked? - */ - interface DrawingSource { - t: DrawingShapeType; - x: number; - y: number; - width: number; - height: number; - rotation?: number; - z?: number; - points?: [number, number][]; - bezierFactor?: number; - fillType?: number; - fillColor?: string; - fillAlpha?: number; - strokeWidth?: number; - strokeColor?: number; - strokeAlpha?: number; - texture?: string; - text?: string; - fontFamily?: string; - fontSize?: number; - textColor?: string; - textAlpha?: number; - hidden?: boolean; - locked?: boolean; - } +/** + * The data schema for a Drawing embedded document. + * @see BaseDrawing + * + * @param data Initial data used to construct the data object + * @param [document] The embedded document to which this data object belongs + * + * @property t The value in CONST.DRAWING_TYPES which defines the geometry type of this drawing + * @property x The x-coordinate position of the top-left corner of the drawn shape + * @property y The y-coordinate position of the top-left corner of the drawn shape + * @property width The pixel width of the drawing figure + * @property height The pixel height of the drawing figure + * @property [rotation=0] The angle of rotation for the drawing figure + * @property [z=0] The z-index of this drawing relative to other siblings + * @property [points] An array of points [x,y] which define polygon vertices + * @property [bezierFactor=0] An amount of bezier smoothing applied, between 0 and 1 + * @property [fillType=0] The fill type of the drawing shape, a value from CONST.DRAWING_FILL_TYPES + * @property [fillColor] An optional color string with which to fill the drawing geometry + * @property [fillAlpha=0.5] The opacity of the fill applied to the drawing geometry + * @property [strokeWidth=8] The width in pixels of the boundary lines of the drawing geometry + * @property [strokeColor] The color of the boundary lines of the drawing geometry + * @property [strokeAlpha=1] The opacity of the boundary lines of the drawing geometry + * @property [texture] The path to a tiling image texture used to fill the drawing geometry + * @property [text] Optional text which is displayed overtop of the drawing + * @property [fontFamily=Signika] The font family used to display text within this drawing + * @property [fontSize=48] The font size used to display text within this drawing + * @property [textColor=#FFFFFF] The color of text displayed within this drawing + * @property [textAlpha=1] The opacity of text displayed within this drawing + * @property [hidden=false] Is the drawing currently hidden? + * @property [locked=false] Is the drawing currently locked? + */ +export interface DrawingSource { + t: DrawingShapeType; + x: number; + y: number; + width: number; + height: number; + rotation?: number; + z?: number; + points?: [number, number][]; + bezierFactor?: number; + fillType?: number; + fillColor?: string; + fillAlpha?: number; + strokeWidth?: number; + strokeColor?: number; + strokeAlpha?: number; + texture?: string; + text?: string; + fontFamily?: string; + fontSize?: number; + textColor?: string; + textAlpha?: number; + hidden?: boolean; + locked?: boolean; +} - interface DrawingMetadata extends abstract.DocumentMetadata { - name: "Drawing"; - collection: "drawings"; - label: "DOCUMENT.Drawing"; - isEmbedded: true; - permissions: { - create: "TEMPLATE_CREATE"; - update: (typeof BaseDrawing)["_canModify"]; - delete: (typeof BaseDrawing)["_canModify"]; - }; - } - } +interface DrawingMetadata extends DocumentMetadata { + name: "Drawing"; + collection: "drawings"; + label: "DOCUMENT.Drawing"; + isEmbedded: true; + permissions: { + create: "TEMPLATE_CREATE"; + update: (typeof BaseDrawing)["_canModify"]; + delete: (typeof BaseDrawing)["_canModify"]; + }; } diff --git a/types/foundry/common/documents/fog-exploration.d.ts b/types/foundry/common/documents/fog-exploration.d.ts index 38f6419dbc5..1431e3e7756 100644 --- a/types/foundry/common/documents/fog-exploration.d.ts +++ b/types/foundry/common/documents/fog-exploration.d.ts @@ -1,51 +1,50 @@ -declare module foundry { - module documents { - /** The FogExploration Document model. */ - class BaseFogExploration extends abstract.Document { - static override get metadata(): FogExplorationMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseUser } from "./module.d.ts"; - protected override _preUpdate( - changed: DocumentUpdateData, - options: DocumentModificationContext, - user: BaseUser - ): Promise; +/** The FogExploration Document model. */ +export default class BaseFogExploration extends Document { + static override get metadata(): FogExplorationMetadata; - /** Test whether a User can modify a FogExploration document. */ - protected static _canUserModify(user: BaseUser, doc: T): boolean; - } + protected override _preUpdate( + changed: DocumentUpdateData, + options: DocumentModificationContext, + user: BaseUser + ): Promise; - interface BaseFogExploration extends abstract.Document { - readonly _source: FogExplorationSource; - } + /** Test whether a User can modify a FogExploration document. */ + protected static _canUserModify(user: BaseUser, doc: T): boolean; +} + +export default interface BaseFogExploration extends Document { + readonly _source: FogExplorationSource; +} - interface FogExplorationMetadata extends abstract.DocumentMetadata { - name: "DogExploration"; - collection: "fog"; - label: "DOCUMENT.FogExploration"; - isPrimary: true; - permissions: { - create: "PLAYER"; - update: (typeof BaseFogExploration)["_canUserModify"]; - delete: (typeof BaseFogExploration)["_canUserModify"]; - }; - } +interface FogExplorationMetadata extends DocumentMetadata { + name: "DogExploration"; + collection: "fog"; + label: "DOCUMENT.FogExploration"; + isPrimary: true; + permissions: { + create: "PLAYER"; + update: (typeof BaseFogExploration)["_canUserModify"]; + delete: (typeof BaseFogExploration)["_canUserModify"]; + }; +} - /** - * The data schema for a FogExploration document. - * @property _id The _id which uniquely identifies this FogExploration document - * @property scene The _id of the Scene document to which this fog applies - * @property user The _id of the User document to which this fog applies - * @property explored The base64 png image of the explored fog polygon - * @property positions The object of scene positions which have been explored at a certain vision radius - * @property timestamp The timestamp at which this fog exploration was last updated - */ - interface FogExplorationSource { - _id: string; - scene: string; - user: string; - explored: string; - position: unknown; - timestamp: number; - } - } +/** + * The data schema for a FogExploration document. + * @property _id The _id which uniquely identifies this FogExploration document + * @property scene The _id of the Scene document to which this fog applies + * @property user The _id of the User document to which this fog applies + * @property explored The base64 png image of the explored fog polygon + * @property positions The object of scene positions which have been explored at a certain vision radius + * @property timestamp The timestamp at which this fog exploration was last updated + */ +interface FogExplorationSource { + _id: string; + scene: string; + user: string; + explored: string; + position: unknown; + timestamp: number; } diff --git a/types/foundry/common/documents/folder.d.ts b/types/foundry/common/documents/folder.d.ts index d8cc35a572f..84c5c5e38e0 100644 --- a/types/foundry/common/documents/folder.d.ts +++ b/types/foundry/common/documents/folder.d.ts @@ -1,55 +1,53 @@ -declare module foundry { - module documents { - /** - * The Folder Document model. - * - * @param data Initial data from which to construct the document. - * @property data The constructed data object for the document. - */ - class BaseFolder extends abstract.Document { - static override get metadata(): FolderMetadata; - } +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; - interface BaseFolder extends abstract.Document { - readonly _source: FolderSource; +/** + * The Folder Document model. + * + * @param data Initial data from which to construct the document. + * @property data The constructed data object for the document. + */ +export default class BaseFolder extends Document { + static override get metadata(): FolderMetadata; +} + +export default interface BaseFolder extends Document { + readonly _source: FolderSource; - get documentName(): (typeof BaseFolder)["metadata"]["name"]; - } + get documentName(): (typeof BaseFolder)["metadata"]["name"]; +} - /** - * The data schema for a Folder document. - * - * @param data Initial data used to construct the data object - * @param [document] The document to which this data object belongs - * - * @property _id The _id which uniquely identifies this Folder document - * @property name The name of this Folder - * @property type The document type which this Folder contains, from CONST.FOLDER_DOCUMENT_TYPES - * @property [description] An HTML description of the contents of this folder - * @property [parent] The _id of a parent Folder which contains this Folder - * @property [sorting=a] The sorting mode used to organize documents within this Folder, in ["a", "m"] - * @property [sort] The numeric sort value which orders this Folder relative to its siblings - * @property [color] A color string used for the background color of this Folder - * @property [flags={}] An object of optional key/value flags - */ - interface FolderSource { - _id: string; - name: string; - type: FolderDocumentType; - description: string; - parent: string | null; - sorting: "a" | "m"; - sort: number; - color: HexColorString; - flags: DocumentFlags; - } +/** + * The data schema for a Folder document. + * + * @param data Initial data used to construct the data object + * @param [document] The document to which this data object belongs + * + * @property _id The _id which uniquely identifies this Folder document + * @property name The name of this Folder + * @property type The document type which this Folder contains, from CONST.FOLDER_DOCUMENT_TYPES + * @property [description] An HTML description of the contents of this folder + * @property [parent] The _id of a parent Folder which contains this Folder + * @property [sorting=a] The sorting mode used to organize documents within this Folder, in ["a", "m"] + * @property [sort] The numeric sort value which orders this Folder relative to its siblings + * @property [color] A color string used for the background color of this Folder + * @property [flags={}] An object of optional key/value flags + */ +interface FolderSource { + _id: string; + name: string; + type: FolderDocumentType; + description: string; + parent: string | null; + sorting: "a" | "m"; + sort: number; + color: HexColorString; + flags: DocumentFlags; +} - interface FolderMetadata extends abstract.DocumentMetadata { - name: "Folder"; - collection: "folders"; - label: "DOCUMENT.Folder"; - isPrimary: true; - types: typeof CONST.FOLDER_DOCUMENT_TYPES; - } - } +interface FolderMetadata extends DocumentMetadata { + name: "Folder"; + collection: "folders"; + label: "DOCUMENT.Folder"; + isPrimary: true; + types: typeof CONST.FOLDER_DOCUMENT_TYPES; } diff --git a/types/foundry/common/documents/index.d.ts b/types/foundry/common/documents/index.d.ts deleted file mode 100644 index 426c11f6d93..00000000000 --- a/types/foundry/common/documents/index.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -import "./active-effect.js"; -import "./actor.js"; -import "./adventure.js"; -import "./ambient-light.js"; -import "./ambient-sound.js"; -import "./cards.js"; -import "./chat-message.js"; -import "./combat.js"; -import "./combatant.js"; -import "./drawing.js"; -import "./fog-exploration.js"; -import "./folder.js"; -import "./item.js"; -import "./journal-entry.js"; -import "./journal-entry-page.js"; -import "./macro.js"; -import "./measured-template.js"; -import "./note.js"; -import "./playlist.js"; -import "./playlist-sound.js"; -import "./roll-table.js"; -import "./scene.js"; -import "./table-result.js"; -import "./tile.js"; -import "./token.js"; -import "./user.js"; -import "./wall.js"; diff --git a/types/foundry/common/documents/item.d.ts b/types/foundry/common/documents/item.d.ts index 6c237a86e2b..f47eef77ec0 100644 --- a/types/foundry/common/documents/item.d.ts +++ b/types/foundry/common/documents/item.d.ts @@ -1,103 +1,103 @@ -declare module foundry { - module documents { - /** The Item document model. */ - class BaseItem extends abstract.Document { - sort: number; +import type { Document, DocumentMetadata, EmbeddedCollection } from "../abstract/module.d.ts"; +import type { ActiveEffectSource } from "./active-effect.d.ts"; +import type { BaseActiveEffect, BaseActor, BaseUser } from "./module.d.ts"; - /** The default icon used for newly created Item documents */ - static DEFAULT_ICON: ImageFilePath; +/** The Item document model. */ +export default class BaseItem extends Document { + sort: number; - static override get metadata(): ItemMetadata; + /** The default icon used for newly created Item documents */ + static DEFAULT_ICON: ImageFilePath; - /** A Collection of ActiveEffect embedded Documents */ - readonly effects: abstract.EmbeddedCollection>; + static override get metadata(): ItemMetadata; - override canUserModify(user: BaseUser, action: UserAction, data?: DocumentUpdateData): boolean; + /** A Collection of ActiveEffect embedded Documents */ + readonly effects: EmbeddedCollection>; - override testUserPermission( - user: BaseUser, - permission: DocumentOwnershipString | DocumentOwnershipLevel, - { exact }?: { exact?: boolean } - ): boolean; + override canUserModify(user: BaseUser, action: UserAction, data?: DocumentUpdateData): boolean; - /** - * Migrate the system data object to conform to data model defined by the current system version. - * @see mergeObject - * @param options Options which customize how the system data is migrated. - * @param options.insertKeys Retain keys which exist in the current data, but not the model - * @param options.insertValues Retain inner-object values which exist in the current data, but not the model - * @param options.enforceTypes Require that data types match the model exactly to be retained - * @return The migrated system data object, not yet saved to the database - */ - migrateSystemData({ - insertKeys, - insertValues, - enforceTypes, - }?: { - insertKeys?: boolean; - insertValues?: boolean; - enforceTypes?: boolean; - }): this["system"]; - } + override testUserPermission( + user: BaseUser, + permission: DocumentOwnershipString | DocumentOwnershipLevel, + { exact }?: { exact?: boolean } + ): boolean; - interface BaseItem extends abstract.Document { - flags: ItemFlags; - readonly _source: ItemSource; - system: object; + /** + * Migrate the system data object to conform to data model defined by the current system version. + * @see mergeObject + * @param options Options which customize how the system data is migrated. + * @param options.insertKeys Retain keys which exist in the current data, but not the model + * @param options.insertValues Retain inner-object values which exist in the current data, but not the model + * @param options.enforceTypes Require that data types match the model exactly to be retained + * @return The migrated system data object, not yet saved to the database + */ + migrateSystemData({ + insertKeys, + insertValues, + enforceTypes, + }?: { + insertKeys?: boolean; + insertValues?: boolean; + enforceTypes?: boolean; + }): this["system"]; +} - get documentName(): (typeof BaseItem)["metadata"]["name"]; - } +export default interface BaseItem extends Document { + flags: ItemFlags; + readonly _source: ItemSource; + system: object; - /** - * The data schema for a Item document. - * @see BaseItem - * - * @param data Initial data used to construct the data object - * @param [document] The document to which this data object belongs - * - * @property _id The _id which uniquely identifies this Item document - * @property name The name of this Item - * @property type An Item subtype which configures the system data model applied - * @property [img] An image file path which provides the artwork for this Item - * @property [data] The system data object which is defined by the system template.json model - * @property folder The _id of a Folder which contains this Item - * @property [sort] The numeric sort value which orders this Item relative to its siblings - * @property [ownership] An object which configures user permissions to this Item - * @property [flags={}] An object of optional key/value flags - */ - interface ItemSource { - _id: string; - name: string; - type: TType; - img: ImageFilePath; - system: TSystemSource; - effects: ActiveEffectSource[]; - folder?: string | null; - sort: number; - ownership: Record; - flags: ItemFlags; - } + get documentName(): (typeof BaseItem)["metadata"]["name"]; +} - interface ItemFlags extends DocumentFlags { - core?: { - sourceId?: ItemUUID; - }; - [key: string]: Record | undefined; - } +/** + * The data schema for a Item document. + * @see BaseItem + * + * @param data Initial data used to construct the data object + * @param [document] The document to which this data object belongs + * + * @property _id The _id which uniquely identifies this Item document + * @property name The name of this Item + * @property type An Item subtype which configures the system data model applied + * @property [img] An image file path which provides the artwork for this Item + * @property [data] The system data object which is defined by the system template.json model + * @property folder The _id of a Folder which contains this Item + * @property [sort] The numeric sort value which orders this Item relative to its siblings + * @property [ownership] An object which configures user permissions to this Item + * @property [flags={}] An object of optional key/value flags + */ +interface ItemSource { + _id: string; + name: string; + type: TType; + img: ImageFilePath; + system: TSystemSource; + effects: ActiveEffectSource[]; + folder?: string | null; + sort: number; + ownership: Record; + flags: ItemFlags; +} + +interface ItemFlags extends DocumentFlags { + core?: { + sourceId?: ItemUUID; + }; + [key: string]: Record | undefined; +} - interface ItemMetadata extends abstract.DocumentMetadata { - name: "Item"; - collection: "items"; - label: "DOCUMENT.Item"; - embedded: { - ActiveEffect: typeof BaseActiveEffect; - }; - isPrimary: true; - hasSystemData: true; - types: string[]; - permissions: Omit & { - create: "ITEM_CREATE"; - }; - } - } +interface ItemMetadata extends DocumentMetadata { + name: "Item"; + collection: "items"; + label: "DOCUMENT.Item"; + embedded: { + ActiveEffect: typeof BaseActiveEffect; + }; + isPrimary: true; + hasSystemData: true; + types: string[]; + permissions: Omit & { + create: "ITEM_CREATE"; + }; } diff --git a/types/foundry/common/documents/journal-entry-page.d.ts b/types/foundry/common/documents/journal-entry-page.d.ts index cfc0ce46a17..0d2d9bc85f5 100644 --- a/types/foundry/common/documents/journal-entry-page.d.ts +++ b/types/foundry/common/documents/journal-entry-page.d.ts @@ -1,94 +1,93 @@ -declare module foundry { - module documents { - /** The JournalEntryPage document model. */ - class BaseJournalEntryPage extends abstract.Document { - static override get metadata(): JournalEntryPageMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseJournalEntry } from "./module.d.ts"; - readonly type: string; - } +/** The JournalEntryPage document model. */ +export default class BaseJournalEntryPage extends Document { + static override get metadata(): JournalEntryPageMetadata; - interface BaseJournalEntryPage { - readonly _source: JournalEntryPageSource; - readonly parent: TParent; + readonly type: string; +} + +export default interface BaseJournalEntryPage extends Document { + readonly _source: JournalEntryPageSource; + readonly parent: TParent; - get documentName(): (typeof BaseJournalEntryPage)["metadata"]["name"]; - } + get documentName(): (typeof BaseJournalEntryPage)["metadata"]["name"]; +} - /** - * The data schema for a JournalEntryPage document. - * @property _id - * @property name The text name of this page. - * @property type The type of this page, in {@link BaseJournalEntryPage.TYPES}. - * @property title Data that control's the display of this page's title. - * @property image Data particular to image journal entry pages. - * @property text Data particular to text journal entry pages. - * @property video Data particular to video journal entry pages. - * @property [src] The URI of the image or other external media to be used for this page. - * @property system System-specific data. - * @property sort The numeric sort value which orders this page relative to its siblings. - * @property [ownership] An object which configures the ownership of this page. - * @property [flags] An object of optional key/value flags. - */ - interface JournalEntryPageSource { - _id: string; - name: string; - title: JournalEntryPageTitleData; - image: JournalEntryPageImageData; - text: JournalEntryPageTextData; - video: JournalEntryPageVideoData; - src?: string | null; - system: object; // will be filled out later - sort: number; - ownership?: Record; - flags: object; // will be filled out later - } - } +/** + * The data schema for a JournalEntryPage document. + * @property _id + * @property name The text name of this page. + * @property type The type of this page, in {@link BaseJournalEntryPage.TYPES}. + * @property title Data that control's the display of this page's title. + * @property image Data particular to image journal entry pages. + * @property text Data particular to text journal entry pages. + * @property video Data particular to video journal entry pages. + * @property [src] The URI of the image or other external media to be used for this page. + * @property system System-specific data. + * @property sort The numeric sort value which orders this page relative to its siblings. + * @property [ownership] An object which configures the ownership of this page. + * @property [flags] An object of optional key/value flags. + */ +export interface JournalEntryPageSource { + _id: string; + name: string; + title: JournalEntryPageTitleData; + image: JournalEntryPageImageData; + text: JournalEntryPageTextData; + video: JournalEntryPageVideoData; + src?: string | null; + system: object; // will be filled out later + sort: number; + ownership?: Record; + flags: object; // will be filled out later +} - interface JournalEntryPageImageData { - /** A caption for the image. */ - caption?: string; - } +interface JournalEntryPageImageData { + /** A caption for the image. */ + caption?: string; +} - interface JournalEntryPageTextData { - /** The content of the JournalEntryPage in a format appropriate for its type. */ - content?: string; - /** The original markdown source, if applicable. */ - markdown?: string; - /** The format of the page's content, in {@link CONST.JOURNAL_ENTRY_PAGE_FORMATS}. */ - format: JournalEntryPageFormat; - } +interface JournalEntryPageTextData { + /** The content of the JournalEntryPage in a format appropriate for its type. */ + content?: string; + /** The original markdown source, if applicable. */ + markdown?: string; + /** The format of the page's content, in {@link CONST.JOURNAL_ENTRY_PAGE_FORMATS}. */ + format: JournalEntryPageFormat; +} - interface JournalEntryPageVideoData { - /** Automatically loop the video? */ - loop?: boolean; - /** Should the video play automatically? */ - autoplay?: boolean; - /** The volume level of any audio that the video file contains. */ - volume?: number; - /** The starting point of the video, in seconds. */ - timestamp?: number; - /** The width of the video, otherwise it will fill the available container width. */ - width?: number; - /** - * The height of the video, otherwise it will use the aspect ratio of the source video, - * or 16:9 if that aspect ratio is not available. - */ - height?: number; - } +interface JournalEntryPageVideoData { + /** Automatically loop the video? */ + loop?: boolean; + /** Should the video play automatically? */ + autoplay?: boolean; + /** The volume level of any audio that the video file contains. */ + volume?: number; + /** The starting point of the video, in seconds. */ + timestamp?: number; + /** The width of the video, otherwise it will fill the available container width. */ + width?: number; + /** + * The height of the video, otherwise it will use the aspect ratio of the source video, + * or 16:9 if that aspect ratio is not available. + */ + height?: number; +} - interface JournalEntryPageTitleData { - /** Whether to render the page's title in the overall journal view. */ - show: boolean; - /** The heading level to render this page's title at in the overall journal view. */ - level: number; - } +interface JournalEntryPageTitleData { + /** Whether to render the page's title in the overall journal view. */ + show: boolean; + /** The heading level to render this page's title at in the overall journal view. */ + level: number; +} - interface JournalEntryPageMetadata extends abstract.DocumentMetadata { - name: "JournalEntryPage"; - collection: "pages"; - indexed: true; - label: "DOCUMENT.JournalEntryPage"; - labelPlural: "DOCUMENT.JournalEntryPages"; - coreTypes: ["image", "pdf", "text", "video"]; - } +interface JournalEntryPageMetadata extends DocumentMetadata { + name: "JournalEntryPage"; + collection: "pages"; + indexed: true; + label: "DOCUMENT.JournalEntryPage"; + labelPlural: "DOCUMENT.JournalEntryPages"; + coreTypes: ["image", "pdf", "text", "video"]; } diff --git a/types/foundry/common/documents/journal-entry.d.ts b/types/foundry/common/documents/journal-entry.d.ts index 4b7292b0a4d..01ce323aa73 100644 --- a/types/foundry/common/documents/journal-entry.d.ts +++ b/types/foundry/common/documents/journal-entry.d.ts @@ -1,60 +1,60 @@ -declare module foundry { - module documents { - /** The JournalEntry document model. */ - class BaseJournalEntry extends abstract.Document { - static override get metadata(): JournalEntryMetadata; +import type { Document, DocumentMetadata, EmbeddedCollection } from "../abstract/module.d.ts"; +import type { JournalEntryPageSource } from "./journal-entry-page.d.ts"; +import type { BaseJournalEntryPage } from "./module.d.ts"; - readonly pages: abstract.EmbeddedCollection>; - } +/** The JournalEntry document model. */ +export default class BaseJournalEntry extends Document { + static override get metadata(): JournalEntryMetadata; - interface BaseJournalEntry extends abstract.Document { - readonly _source: JournalEntrySource; + readonly pages: EmbeddedCollection>; +} + +export default interface BaseJournalEntry extends Document { + readonly _source: JournalEntrySource; - get documentName(): (typeof BaseJournalEntry)["metadata"]["name"]; - } + get documentName(): (typeof BaseJournalEntry)["metadata"]["name"]; +} - /** - * The data schema for a JournalEntry document. - * @see BaseJournalEntry - * - * @param data Initial data used to construct the data object - * @param [document] The document to which this data object belongs - * - * @property _id The _id which uniquely identifies this JournalEntry document - * @property name The name of this JournalEntry - * @property pages The pages contained within this JournalEntry document - * @property [img] An image file path which provides the artwork for this JournalEntry - * @property folder The _id of a Folder which contains this JournalEntry - * @property [sort] The numeric sort value which orders this JournalEntry relative to its siblings - * @property [permission] An object which configures user permissions to this JournalEntry - * @property [flags={}] An object of optional key/value flags - */ - interface JournalEntrySource { - _id: string; - name: string; - pages: JournalEntryPageSource[]; - content: string; - img: ImageFilePath; - folder: string | null; - sort: number; - ownership: Record; - flags: Record>; - } - } +/** + * The data schema for a JournalEntry document. + * @see BaseJournalEntry + * + * @param data Initial data used to construct the data object + * @param [document] The document to which this data object belongs + * + * @property _id The _id which uniquely identifies this JournalEntry document + * @property name The name of this JournalEntry + * @property pages The pages contained within this JournalEntry document + * @property [img] An image file path which provides the artwork for this JournalEntry + * @property folder The _id of a Folder which contains this JournalEntry + * @property [sort] The numeric sort value which orders this JournalEntry relative to its siblings + * @property [permission] An object which configures user permissions to this JournalEntry + * @property [flags={}] An object of optional key/value flags + */ +interface JournalEntrySource { + _id: string; + name: string; + pages: JournalEntryPageSource[]; + content: string; + img: ImageFilePath; + folder: string | null; + sort: number; + ownership: Record; + flags: Record>; +} - interface JournalEntryMetadata extends abstract.DocumentMetadata { - name: "JournalEntry"; - collection: "journal"; - indexed: true; - compendiumIndexFields: ["_id", "name", "sort"]; - embedded: { - JournalEntryPage: typeof documents.BaseJournalEntryPage; - }; - label: "DOCUMENT.JournalEntry"; - labelPlural: "DOCUMENT.JournalEntries"; - isPrimary: true; - permissions: Omit & { - create: "JOURNAL_CREATE"; - }; - } +interface JournalEntryMetadata extends DocumentMetadata { + name: "JournalEntry"; + collection: "journal"; + indexed: true; + compendiumIndexFields: ["_id", "name", "sort"]; + embedded: { + JournalEntryPage: typeof BaseJournalEntryPage; + }; + label: "DOCUMENT.JournalEntry"; + labelPlural: "DOCUMENT.JournalEntries"; + isPrimary: true; + permissions: Omit & { + create: "JOURNAL_CREATE"; + }; } diff --git a/types/foundry/common/documents/macro.d.ts b/types/foundry/common/documents/macro.d.ts index c7b3b483cd6..f7934f3c786 100644 --- a/types/foundry/common/documents/macro.d.ts +++ b/types/foundry/common/documents/macro.d.ts @@ -1,54 +1,53 @@ -declare module foundry { - module documents { - /** The Macro document model. */ - class BaseMacro extends abstract.Document { - static override get metadata(): MacroMetadata; - - protected override _preCreate( - data: PreDocumentId, - options: DocumentModificationContext, - user: BaseUser - ): Promise; - - /** Is a user able to update an existing Macro document? */ - protected static _canUpdate(user: BaseUser, doc: BaseMacro, data: MacroSource): boolean; - - /** Is a user able to delete an existing Macro document? */ - protected static _canDelete(user: BaseUser, doc: BaseMacro): boolean; - } - - interface BaseMacro extends abstract.Document { - readonly _source: MacroSource; - - get documentName(): (typeof BaseMacro)["metadata"]["name"]; - } - - interface MacroSource { - _id: string; - name: string; - type: "chat" | "script"; - img: ImageFilePath; - actorIds: string[]; - author: string; - command: string; - scope: string; - folder?: string | null; - sort: number; - ownership: Record; - flags: DocumentFlags; - } - - interface MacroMetadata extends abstract.DocumentMetadata { - name: "Macro"; - collection: "macros"; - label: "DOCUMENT.Macro"; - isPrimary: true; - types: ["script", "chat"]; - permissions: { - create: "PLAYER"; - update: (typeof BaseMacro)["_canUpdate"]; - delete: (typeof BaseMacro)["_canDelete"]; - }; - } - } +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseUser } from "./module.d.ts"; + +/** The Macro document model. */ +export default class BaseMacro extends Document { + static override get metadata(): MacroMetadata; + + protected override _preCreate( + data: PreDocumentId, + options: DocumentModificationContext, + user: BaseUser + ): Promise; + + /** Is a user able to update an existing Macro document? */ + protected static _canUpdate(user: BaseUser, doc: BaseMacro, data: MacroSource): boolean; + + /** Is a user able to delete an existing Macro document? */ + protected static _canDelete(user: BaseUser, doc: BaseMacro): boolean; +} + +export default interface BaseMacro extends Document { + readonly _source: MacroSource; + + get documentName(): (typeof BaseMacro)["metadata"]["name"]; +} + +export interface MacroSource { + _id: string; + name: string; + type: "chat" | "script"; + img: ImageFilePath; + actorIds: string[]; + author: string; + command: string; + scope: string; + folder?: string | null; + sort: number; + ownership: Record; + flags: DocumentFlags; +} + +interface MacroMetadata extends DocumentMetadata { + name: "Macro"; + collection: "macros"; + label: "DOCUMENT.Macro"; + isPrimary: true; + types: ["script", "chat"]; + permissions: { + create: "PLAYER"; + update: (typeof BaseMacro)["_canUpdate"]; + delete: (typeof BaseMacro)["_canDelete"]; + }; } diff --git a/types/foundry/common/documents/measured-template.d.ts b/types/foundry/common/documents/measured-template.d.ts index ea7aab03720..bf62fffcf84 100644 --- a/types/foundry/common/documents/measured-template.d.ts +++ b/types/foundry/common/documents/measured-template.d.ts @@ -1,80 +1,79 @@ -declare module foundry { - module documents { - /** The MeasuredTemplate embedded document model. */ - class BaseMeasuredTemplate extends abstract.Document { - static override get metadata(): MeasuredTemplateMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseScene, BaseUser } from "./module.d.ts"; - readonly t: MeasuredTemplateType; - width: number; - distance: number; - direction: number; +/** The MeasuredTemplate embedded document model. */ +export default class BaseMeasuredTemplate extends Document { + static override get metadata(): MeasuredTemplateMetadata; - override testUserPermission( - user: documents.BaseUser, - permission: DocumentOwnershipString | DocumentOwnershipLevel, - { exact }?: { exact?: boolean } - ): boolean; + readonly t: MeasuredTemplateType; + width: number; + distance: number; + direction: number; - /** Is a user able to update or delete an existing MeasuredTemplate? */ - protected static _canModify( - user: BaseUser, - doc: BaseMeasuredTemplate, - data: MeasuredTemplateSource - ): boolean; - } + override testUserPermission( + user: BaseUser, + permission: DocumentOwnershipString | DocumentOwnershipLevel, + { exact }?: { exact?: boolean } + ): boolean; - interface BaseMeasuredTemplate - extends abstract.Document, - MeasuredTemplateSource { - readonly _source: MeasuredTemplateSource; - } + /** Is a user able to update or delete an existing MeasuredTemplate? */ + protected static _canModify( + user: BaseUser, + doc: BaseMeasuredTemplate, + data: MeasuredTemplateSource + ): boolean; +} + +export default interface BaseMeasuredTemplate + extends Document, + MeasuredTemplateSource { + readonly _source: MeasuredTemplateSource; +} - /** - * The data schema for a MeasuredTemplate embedded document. - * @see BaseMeasuredTemplate - * - * @param data Initial data used to construct the data object - * @param [document] The embedded document to which this data object belongs - * - * @property _id The _id which uniquely identifies this BaseMeasuredTemplate embedded document - * @property [t=circle] The value in CONST.MEASURED_TEMPLATE_TYPES which defines the geometry type of this template - * @property [x=0] The x-coordinate position of the origin of the template effect - * @property [y=0] The y-coordinate position of the origin of the template effect - * @property [distance] The distance of the template effect - * @property [direction=0] The angle of rotation for the measured template - * @property [angle=360] The angle of effect of the measured template, applies to cone types - * @property [width] The width of the measured template, applies to ray types - * @property [borderColor=#000000] A color string used to tint the border of the template shape - * @property [fillColor=#FF0000] A color string used to tint the fill of the template shape - * @property [texture] A repeatable tiling texture used to add a texture fill to the template shape - * @property [flags={}] An object of optional key/value flags - */ - interface MeasuredTemplateSource { - _id: string | null; - user: string; - t: MeasuredTemplateType; - x: number; - y: number; - distance: number; - direction: number; - angle: number; - width: number; - borderColor: HexColorString; - fillColor: HexColorString; - texture: ImageFilePath; - flags: DocumentFlags; - } +/** + * The data schema for a MeasuredTemplate embedded document. + * @see BaseMeasuredTemplate + * + * @param data Initial data used to construct the data object + * @param [document] The embedded document to which this data object belongs + * + * @property _id The _id which uniquely identifies this BaseMeasuredTemplate embedded document + * @property [t=circle] The value in CONST.MEASURED_TEMPLATE_TYPES which defines the geometry type of this template + * @property [x=0] The x-coordinate position of the origin of the template effect + * @property [y=0] The y-coordinate position of the origin of the template effect + * @property [distance] The distance of the template effect + * @property [direction=0] The angle of rotation for the measured template + * @property [angle=360] The angle of effect of the measured template, applies to cone types + * @property [width] The width of the measured template, applies to ray types + * @property [borderColor=#000000] A color string used to tint the border of the template shape + * @property [fillColor=#FF0000] A color string used to tint the fill of the template shape + * @property [texture] A repeatable tiling texture used to add a texture fill to the template shape + * @property [flags={}] An object of optional key/value flags + */ +export interface MeasuredTemplateSource { + _id: string | null; + user: string; + t: MeasuredTemplateType; + x: number; + y: number; + distance: number; + direction: number; + angle: number; + width: number; + borderColor: HexColorString; + fillColor: HexColorString; + texture: ImageFilePath; + flags: DocumentFlags; +} - interface MeasuredTemplateMetadata extends abstract.DocumentMetadata { - name: "MeasuredTemplate"; - collection: "templates"; - label: "DOCUMENT.MeasuredTemplate"; - isEmbedded: true; - permissions: { - create: "TEMPLATE_CREATE"; - update: (typeof BaseMeasuredTemplate)["_canModify"]; - delete: (typeof BaseMeasuredTemplate)["_canModify"]; - }; - } - } +interface MeasuredTemplateMetadata extends DocumentMetadata { + name: "MeasuredTemplate"; + collection: "templates"; + label: "DOCUMENT.MeasuredTemplate"; + isEmbedded: true; + permissions: { + create: "TEMPLATE_CREATE"; + update: (typeof BaseMeasuredTemplate)["_canModify"]; + delete: (typeof BaseMeasuredTemplate)["_canModify"]; + }; } diff --git a/types/foundry/common/documents/module.d.ts b/types/foundry/common/documents/module.d.ts new file mode 100644 index 00000000000..9040186463f --- /dev/null +++ b/types/foundry/common/documents/module.d.ts @@ -0,0 +1,29 @@ +export { default as BaseActiveEffect, ActiveEffectSource, EffectChangeSource } from "./active-effect.ts"; +export { default as BaseActor, ActorFlags, ActorSource } from "./actor.ts"; +export { default as BaseAdventure, AdventureSource } from "./adventure.ts"; +export { default as BaseAmbientLight, AmbientLightSource } from "./ambient-light.ts"; +export { default as BaseAmbientSound, AmbientSoundSource } from "./ambient-sound.ts"; +export { default as BaseCard } from "./card.ts"; +export { default as BaseCards, CardsSource } from "./cards.ts"; +export { default as BaseChatMessage, ChatMessageFlags, ChatMessageSource, ChatSpeakerData } from "./chat-message.ts"; +export { default as BaseCombat, CombatSource } from "./combat.ts"; +export { default as BaseCombatant, CombatantSource } from "./combatant.ts"; +export { default as BaseDrawing, DrawingSource } from "./drawing.ts"; +export { default as BaseFogExploration, FogExplorationSource } from "./fog-exploration.ts"; +export { default as BaseFolder, FolderSource } from "./folder.ts"; +export { default as BaseItem, ItemFlags, ItemSource } from "./item.ts"; +export { default as BaseJournalEntry, JournalEntrySource } from "./journal-entry.ts"; +export { default as BaseJournalEntryPage, JournalEntryPageSource } from "./journal-entry-page.ts"; +export { default as BaseMacro, MacroSource } from "./macro.ts"; +export { default as BaseMeasuredTemplate, MeasuredTemplateSource } from "./measured-template.ts"; +export { default as BaseNote, NoteSource } from "./note.ts"; +export { default as BasePlaylist, PlaylistSource } from "./playlist.ts"; +export { default as BasePlaylistSound, PlaylistSoundSource } from "./playlist-sound.ts"; +export { default as BaseRollTable, RollTableSource } from "./roll-table.ts"; +export { default as BaseScene, SceneSource } from "./scene.ts"; +export { default as BaseSetting } from "./setting.ts"; +export { default as BaseTableResult, TableResultSource } from "./table-result.ts"; +export { default as BaseTile, TileSource } from "./tile.ts"; +export { default as BaseToken, TokenSource } from "./token.ts"; +export { default as BaseUser, UserSource } from "./user.ts"; +export { default as BaseWall, WallSource } from "./wall.ts"; diff --git a/types/foundry/common/documents/note.d.ts b/types/foundry/common/documents/note.d.ts index 7d6a59544de..e2cf4384f38 100644 --- a/types/foundry/common/documents/note.d.ts +++ b/types/foundry/common/documents/note.d.ts @@ -1,63 +1,62 @@ -declare module foundry { - module documents { - /** The Note embedded document model. */ - class BaseNote extends abstract.Document { - static override get metadata(): NoteMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseScene, BaseUser } from "./module.d.ts"; - /** Is a user able to update an existing Note? */ - protected static _canUpdate(user: BaseUser, doc: BaseNote, data: NoteSource): boolean; - } +/** The Note embedded document model. */ +export default class BaseNote extends Document { + static override get metadata(): NoteMetadata; - interface BaseNote extends abstract.Document { - readonly _source: NoteSource; - } + /** Is a user able to update an existing Note? */ + protected static _canUpdate(user: BaseUser, doc: BaseNote, data: NoteSource): boolean; +} + +export default interface BaseNote extends Document { + readonly _source: NoteSource; +} - /** - * The data schema for a Note embedded document. - * @see BaseNote - * - * @param data Initial data used to construct the data object - * @param [document] The embedded document to which this data object belongs - * - * @property _id The _id which uniquely identifies this BaseNote embedded document - * @property [entryId=null] The _id of a JournalEntry document which this Note represents - * @property [x=0] The x-coordinate position of the center of the note icon - * @property [y=0] The y-coordinate position of the center of the note icon - * @property [icon] An image icon path used to represent this note - * @property [iconSize=40] The pixel size of the map note icon - * @property [iconTint] An optional color string used to tint the map note icon - * @property [text] Optional text which overrides the title of the linked Journal Entry - * @property [fontFamily=Signika] The font family used to display the text label on this note - * @property [fontSize=36] The font size used to display the text label on this note - * @property [textAnchor=1] A value in CONST.TEXT_ANCHOR_POINTS which defines where the text label anchors - * to the note icon. - * @property [textColor=#FFFFFF] The string that defines the color with which the note text is rendered - * @property [flags={}] An object of optional key/value flags - */ - interface NoteSource { - _id: string; - entryId: string | null; - x: number; - y: number; - icon: ImageFilePath; - iconSize: number; - iconTint: HexColorString; - text: string; - fontFamily: string; - fontSize: number; - textAnchor: number; - textColor: HexColorString; - flags: Record; - } +/** + * The data schema for a Note embedded document. + * @see BaseNote + * + * @param data Initial data used to construct the data object + * @param [document] The embedded document to which this data object belongs + * + * @property _id The _id which uniquely identifies this BaseNote embedded document + * @property [entryId=null] The _id of a JournalEntry document which this Note represents + * @property [x=0] The x-coordinate position of the center of the note icon + * @property [y=0] The y-coordinate position of the center of the note icon + * @property [icon] An image icon path used to represent this note + * @property [iconSize=40] The pixel size of the map note icon + * @property [iconTint] An optional color string used to tint the map note icon + * @property [text] Optional text which overrides the title of the linked Journal Entry + * @property [fontFamily=Signika] The font family used to display the text label on this note + * @property [fontSize=36] The font size used to display the text label on this note + * @property [textAnchor=1] A value in CONST.TEXT_ANCHOR_POINTS which defines where the text label anchors + * to the note icon. + * @property [textColor=#FFFFFF] The string that defines the color with which the note text is rendered + * @property [flags={}] An object of optional key/value flags + */ +export interface NoteSource { + _id: string; + entryId: string | null; + x: number; + y: number; + icon: ImageFilePath; + iconSize: number; + iconTint: HexColorString; + text: string; + fontFamily: string; + fontSize: number; + textAnchor: number; + textColor: HexColorString; + flags: Record; +} - interface NoteMetadata extends abstract.DocumentMetadata { - name: "Note"; - collection: "notess"; - label: "DOCUMENT.Note"; - isEmbedded: true; - permissions: Omit & { - update: (typeof foundry.documents.BaseNote)["_canUpdate"]; - }; - } - } +interface NoteMetadata extends DocumentMetadata { + name: "Note"; + collection: "notess"; + label: "DOCUMENT.Note"; + isEmbedded: true; + permissions: Omit & { + update: (typeof BaseNote)["_canUpdate"]; + }; } diff --git a/types/foundry/common/documents/playlist-sound.d.ts b/types/foundry/common/documents/playlist-sound.d.ts index 5838263bc18..f3bae0d1979 100644 --- a/types/foundry/common/documents/playlist-sound.d.ts +++ b/types/foundry/common/documents/playlist-sound.d.ts @@ -1,52 +1,51 @@ -declare module foundry { - module documents { - /** The PlaylistSound document model. */ - class BasePlaylistSound extends abstract.Document { - static override get metadata(): PlaylistSoundMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BasePlaylist, BaseUser } from "./module.d.ts"; - testUserPermission( - user: BaseUser, - permission: DocumentOwnershipString | DocumentOwnershipLevel, - { exact }?: { exact?: boolean } - ): boolean; - } +/** The PlaylistSound document model. */ +export default class BasePlaylistSound extends Document { + static override get metadata(): PlaylistSoundMetadata; - interface BasePlaylistSound extends abstract.Document { - readonly _source: PlaylistSoundSource; - } + testUserPermission( + user: BaseUser, + permission: DocumentOwnershipString | DocumentOwnershipLevel, + { exact }?: { exact?: boolean } + ): boolean; +} + +export default interface BasePlaylistSound extends Document { + readonly _source: PlaylistSoundSource; +} - /** - * The data schema for a PlaylistSound embedded document. - * @see BasePlaylistSound - * - * @param data Initial data used to construct the data object - * @param [document] The document to which this data object belongs - * - * @property _id The _id which uniquely identifies this PlaylistSound document - * @property name The name of this sound track - * @property path The audio file path that is played by this sound - * @property [playing=false] Is this sound currently playing? - * @property [repeat=false] Does this sound loop? - * @property [volume=0.5] The audio volume of the sound, from 0 to 1 - * @property [streaming=false] Does this audio file use the "large file streaming" mode? - * @property [flags={}] An object of optional key/value flags - */ - interface PlaylistSoundSource { - _id: string; - name: string; - path: string; - playing: boolean; - repeat: boolean; - volumn: number; - streaming: boolean; - flags: Record; - } +/** + * The data schema for a PlaylistSound embedded document. + * @see BasePlaylistSound + * + * @param data Initial data used to construct the data object + * @param [document] The document to which this data object belongs + * + * @property _id The _id which uniquely identifies this PlaylistSound document + * @property name The name of this sound track + * @property path The audio file path that is played by this sound + * @property [playing=false] Is this sound currently playing? + * @property [repeat=false] Does this sound loop? + * @property [volume=0.5] The audio volume of the sound, from 0 to 1 + * @property [streaming=false] Does this audio file use the "large file streaming" mode? + * @property [flags={}] An object of optional key/value flags + */ +interface PlaylistSoundSource { + _id: string; + name: string; + path: string; + playing: boolean; + repeat: boolean; + volumn: number; + streaming: boolean; + flags: Record; +} - interface PlaylistSoundMetadata extends abstract.DocumentMetadata { - name: "PlaylistSound"; - collection: "sounds"; - label: "DOCUMENT.PlaylistSound"; - isEmbedded: true; - } - } +interface PlaylistSoundMetadata extends DocumentMetadata { + name: "PlaylistSound"; + collection: "sounds"; + label: "DOCUMENT.PlaylistSound"; + isEmbedded: true; } diff --git a/types/foundry/common/documents/playlist.d.ts b/types/foundry/common/documents/playlist.d.ts index 13a8698b080..dd912f06227 100644 --- a/types/foundry/common/documents/playlist.d.ts +++ b/types/foundry/common/documents/playlist.d.ts @@ -1,54 +1,54 @@ -declare module foundry { - module documents { - /** The Playlist document model. */ - class BasePlaylist extends abstract.Document { - static override get metadata(): PlaylistMetadata; +import type { Document, DocumentMetadata, EmbeddedCollection } from "../abstract/module.d.ts"; +import type { BasePlaylistSound } from "./module.d.ts"; +import type { PlaylistSoundSource } from "./playlist-sound.d.ts"; - /** A reference to the Collection of PlaylistSound instances in the Playlist document, indexed by _id. */ - readonly sounds: abstract.EmbeddedCollection>; - } +/** The Playlist document model. */ +export default class BasePlaylist extends Document { + static override get metadata(): PlaylistMetadata; - interface BasePlaylist extends abstract.Document { - readonly _source: PlaylistSource; + /** A reference to the Collection of PlaylistSound instances in the Playlist document, indexed by _id. */ + readonly sounds: EmbeddedCollection>; +} + +export default interface BasePlaylist extends Document { + readonly _source: PlaylistSource; - get documentName(): (typeof BasePlaylist)["metadata"]["name"]; - } + get documentName(): (typeof BasePlaylist)["metadata"]["name"]; +} - /** - * The data schema for a Playlist document. - * @see BasePlaylist - * @property _id The _id which uniquely identifies this Playlist document - * @property name The name of this playlist - * @property sounds A Collection of PlaylistSounds embedded documents which belong to this playlist - * @property [mode=0] The playback mode for sounds in this playlist - * @property [playing=false] Is this playlist currently playing? - * @property folder The _id of a Folder which contains this playlist - * @property [sort] The numeric sort value which orders this playlist relative to its siblings - * @property [permission] An object which configures user permissions to this playlist - * @property [flags={}] An object of optional key/value flags - */ - interface PlaylistSource { - _id: string; - name: string; - sounds: PlaylistSoundSource[]; - mode: PlaylistMode; - playing: boolean; - fade: number; - folder: string; - sort: number; - seed: number; - permission: Record; - flags: Record; - } +/** + * The data schema for a Playlist document. + * @see BasePlaylist + * @property _id The _id which uniquely identifies this Playlist document + * @property name The name of this playlist + * @property sounds A Collection of PlaylistSounds embedded documents which belong to this playlist + * @property [mode=0] The playback mode for sounds in this playlist + * @property [playing=false] Is this playlist currently playing? + * @property folder The _id of a Folder which contains this playlist + * @property [sort] The numeric sort value which orders this playlist relative to its siblings + * @property [permission] An object which configures user permissions to this playlist + * @property [flags={}] An object of optional key/value flags + */ +interface PlaylistSource { + _id: string; + name: string; + sounds: PlaylistSoundSource[]; + mode: PlaylistMode; + playing: boolean; + fade: number; + folder: string; + sort: number; + seed: number; + permission: Record; + flags: Record; +} - interface PlaylistMetadata extends abstract.DocumentMetadata { - name: "Playlist"; - collection: "playlists"; - label: "DOCUMENT.Playlist"; - embedded: { - PlaylistSound: typeof BasePlaylistSound; - }; - isPrimary: true; - } - } +interface PlaylistMetadata extends DocumentMetadata { + name: "Playlist"; + collection: "playlists"; + label: "DOCUMENT.Playlist"; + embedded: { + PlaylistSound: typeof BasePlaylistSound; + }; + isPrimary: true; } diff --git a/types/foundry/common/documents/roll-table.d.ts b/types/foundry/common/documents/roll-table.d.ts index 5e915b4c6ca..5f21e119260 100644 --- a/types/foundry/common/documents/roll-table.d.ts +++ b/types/foundry/common/documents/roll-table.d.ts @@ -1,66 +1,66 @@ -declare module foundry { - module documents { - /** - * The RollTable document model. - * @param data Initial data from which to construct the document. - * @property data The constructed data object for the document. - */ - class BaseRollTable extends abstract.Document { - static override get metadata(): RollTableMetadata; +import type { Document, DocumentMetadata, EmbeddedCollection } from "../abstract/module.d.ts"; +import type { BaseTableResult } from "./module.d.ts"; +import type { TableResultSource } from "./table-result.d.ts"; - /** A reference to the Collection of TableResult instances in this document, indexed by _id. */ - readonly results: abstract.EmbeddedCollection>; - } +/** + * The RollTable document model. + * @param data Initial data from which to construct the document. + * @property data The constructed data object for the document. + */ +export default class BaseRollTable extends Document { + static override get metadata(): RollTableMetadata; - interface BaseRollTable extends abstract.Document { - readonly _source: RollTableSource; + /** A reference to the Collection of TableResult instances in this document, indexed by _id. */ + readonly results: EmbeddedCollection>; +} + +export default interface BaseRollTable extends Document { + readonly _source: RollTableSource; - get documentName(): (typeof BaseRollTable)["metadata"]["name"]; - } + get documentName(): (typeof BaseRollTable)["metadata"]["name"]; +} - /** - * The data schema for a RollTable document. - * @see BaseRollTable - * - * @param data Initial data used to construct the data object - * @param [document] The document to which this data object belongs - * - * @property _id The _id which uniquely identifies this RollTable document - * @property name The name of this RollTable - * @property [img] An image file path which provides the thumbnail artwork for this RollTable - * @property [description] The HTML text description for this RollTable document - * @property [results=[]] A Collection of TableResult embedded documents which belong to this RollTable - * @property formula The Roll formula which determines the results chosen from the table - * @property [replacement=true] Are results from this table drawn with replacement? - * @property [displayRoll=true] Is the Roll result used to draw from this RollTable displayed in chat? - * @property folder The _id of a Folder which contains this RollTable - * @property [sort] The numeric sort value which orders this RollTable relative to its siblings - * @property [permission] An object which configures user permissions to this RollTable - * @property [flags={}] An object of optional key/value flags - */ - interface RollTableSource { - _id: string; - name: string; - img?: ImageFilePath; - description: string; - results: TableResultSource[]; - formula: string; - replacement: boolean; - displayRoll: boolean; - folder?: string | null; - sort: number; - ownership: Record; - flags: Record>; - } +/** + * The data schema for a RollTable document. + * @see BaseRollTable + * + * @param data Initial data used to construct the data object + * @param [document] The document to which this data object belongs + * + * @property _id The _id which uniquely identifies this RollTable document + * @property name The name of this RollTable + * @property [img] An image file path which provides the thumbnail artwork for this RollTable + * @property [description] The HTML text description for this RollTable document + * @property [results=[]] A Collection of TableResult embedded documents which belong to this RollTable + * @property formula The Roll formula which determines the results chosen from the table + * @property [replacement=true] Are results from this table drawn with replacement? + * @property [displayRoll=true] Is the Roll result used to draw from this RollTable displayed in chat? + * @property folder The _id of a Folder which contains this RollTable + * @property [sort] The numeric sort value which orders this RollTable relative to its siblings + * @property [permission] An object which configures user permissions to this RollTable + * @property [flags={}] An object of optional key/value flags + */ +interface RollTableSource { + _id: string; + name: string; + img?: ImageFilePath; + description: string; + results: TableResultSource[]; + formula: string; + replacement: boolean; + displayRoll: boolean; + folder?: string | null; + sort: number; + ownership: Record; + flags: Record>; +} - interface RollTableMetadata extends abstract.DocumentMetadata { - name: "RollTable"; - collection: "tables"; - label: "DOCUMENT.RollTable"; - embedded: { - TableResult: typeof documents.BaseTableResult; - }; - isPrimary: true; - } - } +interface RollTableMetadata extends DocumentMetadata { + name: "RollTable"; + collection: "tables"; + label: "DOCUMENT.RollTable"; + embedded: { + TableResult: typeof BaseTableResult; + }; + isPrimary: true; } diff --git a/types/foundry/common/documents/scene.d.ts b/types/foundry/common/documents/scene.d.ts index b5d8c90573b..c6ca1ff5fb7 100644 --- a/types/foundry/common/documents/scene.d.ts +++ b/types/foundry/common/documents/scene.d.ts @@ -1,180 +1,196 @@ -export {}; +import type { Document, DocumentMetadata, EmbeddedCollection } from "../abstract/module.d.ts"; +import type { AmbientLightSource } from "./ambient-light.d.ts"; +import type { AmbientSoundSource } from "./ambient-sound.d.ts"; +import type { DrawingSource } from "./drawing.d.ts"; +import type { MeasuredTemplateSource } from "./measured-template.d.ts"; +import type { + BaseAmbientLight, + BaseAmbientSound, + BaseDrawing, + BaseJournalEntry, + BaseMeasuredTemplate, + BaseNote, + BasePlaylist, + BaseTile, + BaseToken, + BaseWall, +} from "./module.d.ts"; +import type { NoteSource } from "./note.d.ts"; +import type { TileSource } from "./tile.d.ts"; +import type { TokenSource } from "./token.d.ts"; +import type { WallSource } from "./wall.d.ts"; + +/** + * The Scene document model. + * @param data Initial data from which to construct the document. + * @property data The constructed data object for the document. + */ +export default class BaseScene extends Document { + active: boolean; + background: foundry.data.TextureData; + grid: GridData; + darkness: number; + tokenVision: boolean; + globalLight: boolean; + hasGlobalThreshold: boolean; + globalLightThreshold: number; + flags: DocumentFlags; + playlist: BasePlaylist | null; + playlistSound: string | null; + journal: BaseJournalEntry | null; + journalEntryPage: string | null; + + /** A reference to the Collection of Drawing instances in the Scene document, indexed by _id. */ + readonly drawings: EmbeddedCollection>; + + /** A reference to the Collection of AmbientLight instances in the Scene document, indexed by _id. */ + readonly lights: EmbeddedCollection>; + + /** A reference to the Collection of Note instances in the Scene document, indexed by _id. */ + readonly notes: EmbeddedCollection>; + + /** A reference to the Collection of AmbientSound instances in the Scene document, indexed by _id. */ + readonly sounds: EmbeddedCollection>; + + /** A reference to the Collection of MeasuredTemplate instances in the Scene document, indexed by _id. */ + readonly templates: EmbeddedCollection>; + + /** A reference to the Collection of Token instances in the Scene document, indexed by _id. */ + readonly tokens: EmbeddedCollection>; + + /** A reference to the Collection of Tile instances in the Scene document, indexed by _id. */ + readonly tiles: EmbeddedCollection>; + + /** A reference to the Collection of Wall instances in the Scene document, indexed by _id. */ + readonly walls: EmbeddedCollection>; + + static override get metadata(): SceneMetadata; -declare global { - module foundry { - module documents { - /** - * The Scene document model. - * @param data Initial data from which to construct the document. - * @property data The constructed data object for the document. - */ - class BaseScene extends abstract.Document { - active: boolean; - background: data.TextureData; - grid: GridData; - darkness: number; - tokenVision: boolean; - globalLight: boolean; - hasGlobalThreshold: boolean; - globalLightThreshold: number; - flags: DocumentFlags; - playlist: BasePlaylist | null; - playlistSound: string | null; - journal: BaseJournalEntry | null; - journalEntryPage: string | null; - - /** A reference to the Collection of Drawing instances in the Scene document, indexed by _id. */ - readonly drawings: abstract.EmbeddedCollection>; - - /** A reference to the Collection of AmbientLight instances in the Scene document, indexed by _id. */ - readonly lights: abstract.EmbeddedCollection>; - - /** A reference to the Collection of Note instances in the Scene document, indexed by _id. */ - readonly notes: abstract.EmbeddedCollection>; - - /** A reference to the Collection of AmbientSound instances in the Scene document, indexed by _id. */ - readonly sounds: abstract.EmbeddedCollection>; - - /** A reference to the Collection of MeasuredTemplate instances in the Scene document, indexed by _id. */ - readonly templates: abstract.EmbeddedCollection>; - - /** A reference to the Collection of Token instances in the Scene document, indexed by _id. */ - readonly tokens: abstract.EmbeddedCollection>; - - /** A reference to the Collection of Tile instances in the Scene document, indexed by _id. */ - readonly tiles: abstract.EmbeddedCollection>; - - /** A reference to the Collection of Wall instances in the Scene document, indexed by _id. */ - readonly walls: abstract.EmbeddedCollection>; - - static override get metadata(): SceneMetadata; - - /** - * Get the Canvas dimensions which would be used to display this Scene. - * Apply padding to enlarge the playable space and round to the nearest 2x grid size to ensure symmetry. - * @returns An object describing the configured dimensions - */ - static getDimensions({ - width, - height, - size, - gridDistance, - padding, - shiftX, - shiftY, - }: GetDimensionsParams): SceneDimensions; - } - - interface BaseScene extends foundry.abstract.Document { - readonly _source: SceneSource; - get documentName(): (typeof BaseScene)["metadata"]["name"]; - } - - interface SceneSource { - _id: string; - name: string; - - // Navigation - active: boolean; - navigation: boolean; - navOrder: number; - navName: string; - - // Canvas Dimensions - img: VideoFilePath; - foreground: VideoFilePath; - thumb: ImageFilePath; - width: number; - height: number; - padding: number; - initial: { - x: number; - y: number; - scale: number; - }; - - backgroundColor: HexColorString; - - grid: GridData; - - shiftX: number; - shiftY: number; - - // Vision and Lighting Configuration - tokenVision: boolean; - fogExploration: boolean; - fogReset: string; - globalLight: boolean; - globalLightThreshold: number; - hasGlobalThreshold: boolean; - darkness: number; - - // Embedded Collections - drawings: DrawingSource[]; - tokens: TokenSource[]; - lights: AmbientLightSource[]; - notes: NoteSource[]; - sounds: AmbientSoundSource[]; - templates: MeasuredTemplateSource[]; - tiles: TileSource[]; - walls: WallSource[]; - - // Linked Documents - playlist: PlaylistSource | null; - playlistSound: PlaylistSoundSource | null; - journal: JournalEntrySource | null; - weather: string; - - // Permissions - folder: string | null; - sort: number; - ownership: Record; - flags: Record>; - } - - interface GridData { - /** The type of grid, a number from CONST.GRID_TYPES. */ - type: GridType; - /** The grid size which represents the width (or height) of a single grid space. */ - size: number; - /** A string representing the color used to render the grid lines. */ - color: HexColorString; - /** A number between 0 and 1 for the opacity of the grid lines. */ - alpha: number; - /** The number of distance units which are represented by a single grid space. */ - distance: number; - /** A label for the units of measure which are used for grid distance. */ - units: string; - } - - interface SceneMetadata extends abstract.DocumentMetadata { - name: "Scene"; - collection: "scenes"; - label: "DOCUMENT.Scene"; - isPrimary: true; - embedded: { - AmbientLight: typeof documents.BaseAmbientLight; - AmbientSound: typeof documents.BaseAmbientSound; - Drawing: typeof documents.BaseDrawing; - MeasuredTemplate: typeof documents.BaseMeasuredTemplate; - Note: typeof documents.BaseNote; - Tile: typeof documents.BaseTile; - Token: typeof documents.BaseToken; - Wall: typeof documents.BaseWall; - }; - } - } - } + /** + * Get the Canvas dimensions which would be used to display this Scene. + * Apply padding to enlarge the playable space and round to the nearest 2x grid size to ensure symmetry. + * @returns An object describing the configured dimensions + */ + static getDimensions({ + width, + height, + size, + gridDistance, + padding, + shiftX, + shiftY, + }: GetDimensionsParams): SceneDimensions; +} + +export default interface BaseScene extends Document { + readonly _source: SceneSource; + get documentName(): (typeof BaseScene)["metadata"]["name"]; +} +export interface SceneSource { + _id: string; + name: string; + + // Navigation + active: boolean; + navigation: boolean; + navOrder: number; + navName: string; + + // Canvas Dimensions + img: VideoFilePath; + foreground: VideoFilePath; + thumb: ImageFilePath; + width: number; + height: number; + padding: number; + initial: { + x: number; + y: number; + scale: number; + }; + + backgroundColor: HexColorString; + + grid: GridData; + + shiftX: number; + shiftY: number; + + // Vision and Lighting Configuration + tokenVision: boolean; + fogExploration: boolean; + fogReset: string; + globalLight: boolean; + globalLightThreshold: number; + hasGlobalThreshold: boolean; + darkness: number; + + // Embedded Collections + drawings: DrawingSource[]; + tokens: TokenSource[]; + lights: AmbientLightSource[]; + notes: NoteSource[]; + sounds: AmbientSoundSource[]; + templates: MeasuredTemplateSource[]; + tiles: TileSource[]; + walls: WallSource[]; + + // Linked Documents + playlist: string | null; + playlistSound: string | null; + journal: string | null; + weather: string; + + // Permissions + folder: string | null; + sort: number; + ownership: Record; + flags: Record>; +} + +export interface GridData { + /** The type of grid, a number from CONST.GRID_TYPES. */ + type: GridType; + /** The grid size which represents the width (or height) of a single grid space. */ + size: number; + /** A string representing the color used to render the grid lines. */ + color: HexColorString; + /** A number between 0 and 1 for the opacity of the grid lines. */ + alpha: number; + /** The number of distance units which are represented by a single grid space. */ + distance: number; + /** A label for the units of measure which are used for grid distance. */ + units: string; +} + +export interface SceneMetadata extends DocumentMetadata { + name: "Scene"; + collection: "scenes"; + label: "DOCUMENT.Scene"; + isPrimary: true; + embedded: { + AmbientLight: typeof BaseAmbientLight; + AmbientSound: typeof BaseAmbientSound; + Drawing: typeof BaseDrawing; + MeasuredTemplate: typeof BaseMeasuredTemplate; + Note: typeof BaseNote; + Tile: typeof BaseTile; + Token: typeof BaseToken; + Wall: typeof BaseWall; + }; +} + +declare global { /** * @property [isUndo] Is the operation undoing a previous operation, only used by embedded Documents within a Scene */ - interface SceneEmbeddedModificationContext + export interface SceneEmbeddedModificationContext extends DocumentModificationContext { isUndo?: boolean; } - interface GetDimensionsParams { + export interface GetDimensionsParams { gridDistance: number; height: number; padding: number; @@ -184,7 +200,7 @@ declare global { width: number; } - interface SceneDimensions { + export interface SceneDimensions { distance: number; height: number; paddingX: number; diff --git a/types/foundry/common/documents/setting.d.ts b/types/foundry/common/documents/setting.d.ts new file mode 100644 index 00000000000..bcc92d93580 --- /dev/null +++ b/types/foundry/common/documents/setting.d.ts @@ -0,0 +1,11 @@ +import type { Document } from "../abstract/module.d.ts"; + +/** + * The Document definition for a Setting. + * Defines the DataSchema and common behaviors for a Setting which are shared between both client and server. + * @memberof documents + * + * @param data Initial data from which to construct the Setting + * @param context Construction context options + */ +export default class BaseSetting extends Document {} diff --git a/types/foundry/common/documents/table-result.d.ts b/types/foundry/common/documents/table-result.d.ts index 69ea92c02e0..1005d4f2e03 100644 --- a/types/foundry/common/documents/table-result.d.ts +++ b/types/foundry/common/documents/table-result.d.ts @@ -1,63 +1,62 @@ -declare module foundry { - module documents { - /** The TableResult document model. */ - class BaseTableResult extends abstract.Document { - static override get metadata(): TableResultMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseRollTable, BaseUser } from "./module.d.ts"; - /** Is a user able to update an existing TableResult? */ - protected static _canUpdate( - user: BaseUser, - doc: BaseTableResult, - data: TableResultSource - ): boolean; +/** The TableResult document model. */ +export default class BaseTableResult extends Document { + static override get metadata(): TableResultMetadata; - override testUserPermission( - user: BaseUser, - permission: DocumentOwnershipString | DocumentOwnershipLevel, - { exact }?: { exact?: boolean } - ): boolean; - } + /** Is a user able to update an existing TableResult? */ + protected static _canUpdate( + user: BaseUser, + doc: BaseTableResult, + data: TableResultSource + ): boolean; - interface BaseTableResult extends abstract.Document { - readonly _source: TableResultSource; - } + override testUserPermission( + user: BaseUser, + permission: DocumentOwnershipString | DocumentOwnershipLevel, + { exact }?: { exact?: boolean } + ): boolean; +} + +export default interface BaseTableResult extends Document { + readonly _source: TableResultSource; +} - /** - * The data schema for a TableResult embedded document within a Roll Table. - * @see BaseTableResult - * - * @param data Initial data used to construct the data object - * @param [document] The document to which this data object belongs - * - * @property [type=p] A result sub-type from CONST.TABLE_RESULT_TYPES - * @property [text] The text which describes the table result - * @property [img] An image file url that represents the table result - * @property [collection] A named collection from which this result is drawn - * @property [resultId] The _id of a Document within the collection this result references - * @property [weight=1] The probabilistic weight of this result relative to other results - * @property [range] A length 2 array of ascending integers which defines the range of dice roll - * totals which produce this drawn result - * @property [drawn=false] Has this result already been drawn (without replacement) - */ - interface TableResultSource { - type: TableResultType; - text: string; - img: ImageFilePath; - collection: string; - resultId: string; - weight: number; - range: [number, number]; - drawn: boolean; - } +/** + * The data schema for a TableResult embedded document within a Roll Table. + * @see BaseTableResult + * + * @param data Initial data used to construct the data object + * @param [document] The document to which this data object belongs + * + * @property [type=p] A result sub-type from CONST.TABLE_RESULT_TYPES + * @property [text] The text which describes the table result + * @property [img] An image file url that represents the table result + * @property [collection] A named collection from which this result is drawn + * @property [resultId] The _id of a Document within the collection this result references + * @property [weight=1] The probabilistic weight of this result relative to other results + * @property [range] A length 2 array of ascending integers which defines the range of dice roll + * totals which produce this drawn result + * @property [drawn=false] Has this result already been drawn (without replacement) + */ +interface TableResultSource { + type: TableResultType; + text: string; + img: ImageFilePath; + collection: string; + resultId: string; + weight: number; + range: [number, number]; + drawn: boolean; +} - interface TableResultMetadata extends abstract.DocumentMetadata { - name: "TableResult"; - collection: "results"; - label: "DOCUMENT.TableResult"; - types: typeof CONST.TABLE_RESULT_TYPES; - permissions: Omit & { - update: (typeof BaseTableResult)["_canUpdate"]; - }; - } - } +interface TableResultMetadata extends DocumentMetadata { + name: "TableResult"; + collection: "results"; + label: "DOCUMENT.TableResult"; + types: typeof CONST.TABLE_RESULT_TYPES; + permissions: Omit & { + update: (typeof BaseTableResult)["_canUpdate"]; + }; } diff --git a/types/foundry/common/documents/tile.d.ts b/types/foundry/common/documents/tile.d.ts index 9fd92f03150..da7b885635b 100644 --- a/types/foundry/common/documents/tile.d.ts +++ b/types/foundry/common/documents/tile.d.ts @@ -1,59 +1,58 @@ -declare module foundry { - module documents { - /** The Tile embedded document model. */ - class BaseTile extends abstract.Document { - static override get metadata(): TileMetadata; - } +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseScene } from "./module.d.ts"; - interface BaseTile extends abstract.Document { - readonly _source: TileSource; - } +/** The Tile embedded document model. */ +export default class BaseTile extends Document { + static override get metadata(): TileMetadata; +} + +export default interface BaseTile extends Document { + readonly _source: TileSource; +} - /** - * The data schema for a Tile embedded document. - * @see BaseTile - * - * @property _id The _id which uniquely identifies this Tile embedded document - * @property [img] An image or video file path which this tile displays - * @property [width=0] The pixel width of the tile - * @property [height=0] The pixel height of the tile - * @property [x=0] The x-coordinate position of the top-left corner of the tile - * @property [y=0] The y-coordinate position of the top-left corner of the tile - * @property [z=100] The z-index ordering of this tile relative to its siblings - * @property [rotation=0] The angle of rotation for the tile between 0 and 360 - * @property [alpha=1] The tile opacity - * @property [tint] A color to tint the tile - * @property [hidden=false] Is the tile currently hidden? - * @property [locked=false] Is the tile currently locked? - * @property [overhead=false] Is the tile an overhead tile? - * @property [occlusion] The tile's occlusion settings - * @property [video] The tile's video settings - * @property [flags={}] An object of optional key/value flags - */ - interface TileSource { - _id: string; - img: ImageFilePath | null; - width: number; - height: number; - x: number; - y: number; - z: number; - rotation: number; - alpha: number; - tint: HexColorString | null; - hidden: boolean; - locked: boolean; - overhead: boolean; - video: data.VideoData; - occlusion: data.TileOcclusion; - flags: DocumentFlags; - } +/** + * The data schema for a Tile embedded document. + * @see BaseTile + * + * @property _id The _id which uniquely identifies this Tile embedded document + * @property [img] An image or video file path which this tile displays + * @property [width=0] The pixel width of the tile + * @property [height=0] The pixel height of the tile + * @property [x=0] The x-coordinate position of the top-left corner of the tile + * @property [y=0] The y-coordinate position of the top-left corner of the tile + * @property [z=100] The z-index ordering of this tile relative to its siblings + * @property [rotation=0] The angle of rotation for the tile between 0 and 360 + * @property [alpha=1] The tile opacity + * @property [tint] A color to tint the tile + * @property [hidden=false] Is the tile currently hidden? + * @property [locked=false] Is the tile currently locked? + * @property [overhead=false] Is the tile an overhead tile? + * @property [occlusion] The tile's occlusion settings + * @property [video] The tile's video settings + * @property [flags={}] An object of optional key/value flags + */ +export interface TileSource { + _id: string; + img: ImageFilePath | null; + width: number; + height: number; + x: number; + y: number; + z: number; + rotation: number; + alpha: number; + tint: HexColorString | null; + hidden: boolean; + locked: boolean; + overhead: boolean; + video: foundry.data.VideoData; + occlusion: foundry.data.TileOcclusion; + flags: DocumentFlags; +} - interface TileMetadata extends abstract.DocumentMetadata { - name: "Tile"; - collection: "tiles"; - label: "DOCUMENT.Tile"; - isEmbedded: true; - } - } +interface TileMetadata extends DocumentMetadata { + name: "Tile"; + collection: "tiles"; + label: "DOCUMENT.Tile"; + isEmbedded: true; } diff --git a/types/foundry/common/documents/token.d.ts b/types/foundry/common/documents/token.d.ts index c1d51f0c246..a46684382a5 100644 --- a/types/foundry/common/documents/token.d.ts +++ b/types/foundry/common/documents/token.d.ts @@ -1,175 +1,175 @@ -declare module foundry { - module documents { - /** - * The Token document model. - * @param data Initial data from which to construct the document. - * @property data The constructed data object for the document. - */ - class BaseToken extends abstract.Document { - readonly actorLink: boolean; - - displayName: TokenDisplayMode; - - disposition: TokenDisposition; - - width: number; - - height: number; - - texture: { - src: VideoFilePath; - scaleX: number; - scaleY: number; - offsetX: number; - offsetY: number; - rotation: number | null; - tint: HexColorString; - }; - - light: foundry.data.LightData; - - sight: { - enabled: boolean; - range: number | null; - angle: number; - color: HexColorString; - attenuation: number; - brightness: number; - saturation: number; - contrast: number; - visionMode: string; - }; - - elevation: number; - - effects: VideoFilePath[]; - - flags: DocumentFlags; - - static override get metadata(): TokenMetadata; - - /** Is a user able to update an existing Token? */ - protected static _canUpdate(user: BaseUser, doc: BaseToken, data: TokenSource): boolean; - } - - interface BaseToken extends abstract.Document { - readonly _source: TokenSource; - } - - /** - * The data schema for a Token document. - * - * @property _id The Token _id which uniquely identifies it within its parent Scene - * @property name The name used to describe the Token - * @property [displayName=0] The display mode of the Token nameplate, from CONST.TOKEN_DISPLAY_MODES - * @property actorId The _id of an Actor document which this Token represents - * @property [actorLink=false] Does this Token uniquely represent a singular Actor, or is it one of many? - * @property [actorData] Token-level data which overrides the base data of the associated Actor - * @property [width=1] The width of the Token in grid units - * @property [height=1] The height of the Token in grid units - * @property [scale=1] A scale factor applied to the Token image, between 0.25 and 3 - * @property [mirrorX=false] Flip the Token image horizontally? - * @property [mirrorY=false] Flip the Token image vertically? - * @property [x=0] The x-coordinate of the top-left corner of the Token - * @property [y=0] The y-coordinate of the top-left corner of the Token - * @property [elevation=0] The vertical elevation of the Token, in distance units - * @property [lockRotation=false] Prevent the Token image from visually rotating? - * @property [rotation=0] The rotation of the Token in degrees, from 0 to 360. A value of 0 represents a southward-facing Token. - * @property [effects] An array of effect icon paths which are displayed on the Token - * @property [overlayEffect] A single icon path which is displayed as an overlay on the Token - * @property [hidden=false] Is the Token currently hidden from player view? - * @property [vision] Is this Token a source of vision? - * @property [dimSight=0] How far in distance units the Token can naturally see as if in dim light - * @property [brightSight=0] How far in distance units the Token can naturally see as if in bright light - * @property [sightAngle=360] The angle at which this Token is able to see, if it has vision - * @property [light] The angle at which this Token is able to see, if it has vision - * @property [dimLight=0] How far in distance units this Token emits dim light - * @property [brightLight=0] How far in distance units this Token emits bright light - * @property [lightAngle=360] The angle at which this Token is able to emit light - * @property [lightAnimation] A data object which configures token light animation settings - * @property [disposition=-1] A displayed Token disposition from CONST.TOKEN_DISPOSITIONS - * @property [displayBars=0] The display mode of Token resource bars, from CONST.TOKEN_DISPLAY_MODES - * @property [bar1] The configuration of the Token's primary resource bar - * @property [bar2] The configuration of the Token's secondary resource bar - * @property [flags={}] An object of optional key/value flags - */ - interface TokenSource extends TokenLightData { - _id: string; - name: string; - - // Navigation - active: boolean; - navigation: boolean; - navOrder: number; - navName: string; - - actorId: string | null; - actorLink: boolean; - actorData: DeepPartial; - mirrorX: boolean; - mirrorY: boolean; - height: number; - width: number; - x: number; - y: number; - elevation: number; - lockRotation: boolean; - effects: VideoFilePath[]; - overlayEffect: string | null; - vision: boolean; - dimSight: number; - brightSight: number; - sightAngle: number; - light: data.LightSource; - hidden: boolean; - texture: { - src: VideoFilePath; - scaleX: number; - scaleY: number; - offsetX: number; - offsetY: number; - rotation: number | null; - tint: `#${string}`; - }; - - lightAnimation: data.AnimationData; - disposition: TokenDisposition; - displayName: TokenDisplayMode; - displayBars: TokenDisplayMode; - bar1: TokenBarData; - bar2: TokenBarData; - flags: DocumentFlags; - } - - interface TokenLightData { - brightLight: number; - dimLight: number; - lightAlpha: number; - lightAngle: number; - lightAnimation: { - type: string; - speed: number; - intensity: number; - }; - lightColor: string; - } - - interface TokenMetadata extends abstract.DocumentMetadata { - name: "Token"; - collection: "tokens"; - label: "DOCUMENT.Token"; - isEmbedded: true; - permissions: Omit & { - create: "TOKEN_CREATE"; - }; - } - - /** - * An embedded data structure for the contents of a Token attribute bar. - * @property [attribute] The attribute path within the Token's Actor data which should be displayed - */ - interface TokenBarData { - attribute: string | null; - } - } +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { ActorSource } from "./actor.d.ts"; +import type { BaseScene, BaseUser } from "./module.d.ts"; + +/** + * The Token document model. + * @param data Initial data from which to construct the document. + * @property data The constructed data object for the document. + */ +export default class BaseToken extends Document { + readonly actorLink: boolean; + + displayName: TokenDisplayMode; + + disposition: TokenDisposition; + + width: number; + + height: number; + + texture: { + src: VideoFilePath; + scaleX: number; + scaleY: number; + offsetX: number; + offsetY: number; + rotation: number | null; + tint: HexColorString; + }; + + light: foundry.data.LightData; + + sight: { + enabled: boolean; + range: number | null; + angle: number; + color: HexColorString; + attenuation: number; + brightness: number; + saturation: number; + contrast: number; + visionMode: string; + }; + + elevation: number; + + effects: VideoFilePath[]; + + flags: DocumentFlags; + + static override get metadata(): TokenMetadata; + + /** Is a user able to update an existing Token? */ + protected static _canUpdate(user: BaseUser, doc: BaseToken, data: TokenSource): boolean; +} + +export default interface BaseToken extends Document { + readonly _source: TokenSource; +} + +/** + * The data schema for a Token document. + * + * @property _id The Token _id which uniquely identifies it within its parent Scene + * @property name The name used to describe the Token + * @property [displayName=0] The display mode of the Token nameplate, from CONST.TOKEN_DISPLAY_MODES + * @property actorId The _id of an Actor document which this Token represents + * @property [actorLink=false] Does this Token uniquely represent a singular Actor, or is it one of many? + * @property [actorData] Token-level data which overrides the base data of the associated Actor + * @property [width=1] The width of the Token in grid units + * @property [height=1] The height of the Token in grid units + * @property [scale=1] A scale factor applied to the Token image, between 0.25 and 3 + * @property [mirrorX=false] Flip the Token image horizontally? + * @property [mirrorY=false] Flip the Token image vertically? + * @property [x=0] The x-coordinate of the top-left corner of the Token + * @property [y=0] The y-coordinate of the top-left corner of the Token + * @property [elevation=0] The vertical elevation of the Token, in distance units + * @property [lockRotation=false] Prevent the Token image from visually rotating? + * @property [rotation=0] The rotation of the Token in degrees, from 0 to 360. A value of 0 represents a southward-facing Token. + * @property [effects] An array of effect icon paths which are displayed on the Token + * @property [overlayEffect] A single icon path which is displayed as an overlay on the Token + * @property [hidden=false] Is the Token currently hidden from player view? + * @property [vision] Is this Token a source of vision? + * @property [dimSight=0] How far in distance units the Token can naturally see as if in dim light + * @property [brightSight=0] How far in distance units the Token can naturally see as if in bright light + * @property [sightAngle=360] The angle at which this Token is able to see, if it has vision + * @property [light] The angle at which this Token is able to see, if it has vision + * @property [dimLight=0] How far in distance units this Token emits dim light + * @property [brightLight=0] How far in distance units this Token emits bright light + * @property [lightAngle=360] The angle at which this Token is able to emit light + * @property [lightAnimation] A data object which configures token light animation settings + * @property [disposition=-1] A displayed Token disposition from CONST.TOKEN_DISPOSITIONS + * @property [displayBars=0] The display mode of Token resource bars, from CONST.TOKEN_DISPLAY_MODES + * @property [bar1] The configuration of the Token's primary resource bar + * @property [bar2] The configuration of the Token's secondary resource bar + * @property [flags={}] An object of optional key/value flags + */ +export interface TokenSource extends TokenLightData { + _id: string; + name: string; + + // Navigation + active: boolean; + navigation: boolean; + navOrder: number; + navName: string; + + actorId: string | null; + actorLink: boolean; + actorData: DeepPartial; + mirrorX: boolean; + mirrorY: boolean; + height: number; + width: number; + x: number; + y: number; + elevation: number; + lockRotation: boolean; + effects: VideoFilePath[]; + overlayEffect: string | null; + vision: boolean; + dimSight: number; + brightSight: number; + sightAngle: number; + light: foundry.data.LightSource; + hidden: boolean; + texture: { + src: VideoFilePath; + scaleX: number; + scaleY: number; + offsetX: number; + offsetY: number; + rotation: number | null; + tint: `#${string}`; + }; + + lightAnimation: foundry.data.AnimationData; + disposition: TokenDisposition; + displayName: TokenDisplayMode; + displayBars: TokenDisplayMode; + bar1: TokenBarData; + bar2: TokenBarData; + flags: DocumentFlags; +} + +interface TokenLightData { + brightLight: number; + dimLight: number; + lightAlpha: number; + lightAngle: number; + lightAnimation: { + type: string; + speed: number; + intensity: number; + }; + lightColor: string; +} + +interface TokenMetadata extends DocumentMetadata { + name: "Token"; + collection: "tokens"; + label: "DOCUMENT.Token"; + isEmbedded: true; + permissions: Omit & { + create: "TOKEN_CREATE"; + }; +} + +/** + * An embedded data structure for the contents of a Token attribute bar. + * @property [attribute] The attribute path within the Token's Actor data which should be displayed + */ +interface TokenBarData { + attribute: string | null; } diff --git a/types/foundry/common/documents/user.d.ts b/types/foundry/common/documents/user.d.ts index 2999d85bb73..d32003b3118 100644 --- a/types/foundry/common/documents/user.d.ts +++ b/types/foundry/common/documents/user.d.ts @@ -1,84 +1,84 @@ -declare module foundry { - module documents { - /** - * The base User document, which is extended by both the server and client. - * This base User provides shared functionality which is consistent for both sides of the application. - * Each client who connects to a Foundry Virtual Tabletop session assumes the identity of one (and only one) User. - * - * @param data Initial data from which to construct the document. - * @property data The constructed data object for the document. - */ - class BaseUser extends abstract.Document { - avatar: ImageFilePath; - border: HexColorString; - character: BaseActor | null | undefined; - charname: string; - color: HexColorString; - flags: DocumentFlags; - name: string; - readonly role: UserRole; +import type Document from "../abstract/document.d.ts"; +import type { DocumentMetadata } from "../abstract/document.d.ts"; +import type { BaseActor } from "./module.d.ts"; - static override get metadata(): UserMetadata; +/** + * The base User document, which is extended by both the server and client. + * This base User provides shared functionality which is consistent for both sides of the application. + * Each client who connects to a Foundry Virtual Tabletop session assumes the identity of one (and only one) User. + * + * @param data Initial data from which to construct the document. + * @property data The constructed data object for the document. + */ +export default class BaseUser extends Document { + avatar: ImageFilePath; + border: HexColorString; + character: BaseActor | null | undefined; + charname: string; + color: HexColorString; + flags: DocumentFlags; + name: string; + readonly role: UserRole; - /* ---------------------------------------- */ - /* Permissions */ - /* ---------------------------------------- */ + static override get metadata(): UserMetadata; - /** Test whether the User has a GAMEMASTER or ASSISTANT role in this World? */ - get isGM(): boolean; + /* ---------------------------------------- */ + /* Permissions */ + /* ---------------------------------------- */ - /** - * Test whether the User is able to perform a certain permission action. - * The provided permission string may pertain to an explicit permission setting or a named user role. - * Alternatively, Gamemaster users are assumed to be allowed to take all actions. - * - * @param action The action to test - * @return Does the user have the ability to perform this action? - */ - can(action: UserAction): boolean; + /** Test whether the User has a GAMEMASTER or ASSISTANT role in this World? */ + get isGM(): boolean; - getUserLevel(user: this): DocumentOwnershipLevel; + /** + * Test whether the User is able to perform a certain permission action. + * The provided permission string may pertain to an explicit permission setting or a named user role. + * Alternatively, Gamemaster users are assumed to be allowed to take all actions. + * + * @param action The action to test + * @return Does the user have the ability to perform this action? + */ + can(action: UserAction): boolean; - /** - * Test whether the User has at least a specific permission - * @param permission The permission name from USER_PERMISSIONS to test - * @return Does the user have at least this permission - */ - hasPermission(permission: UserPermission): boolean; + getUserLevel(user: this): DocumentOwnershipLevel; - /** - * Test whether the User has at least the permission level of a certain role - * @param role The role name from USER_ROLES to test - * @param [exact] Require the role match to be exact - * @return Does the user have at this role level (or greater)? - */ - hasRole(role: UserRole | UserRoleName, { exact }?: { exact: boolean }): boolean; - } + /** + * Test whether the User has at least a specific permission + * @param permission The permission name from USER_PERMISSIONS to test + * @return Does the user have at least this permission + */ + hasPermission(permission: UserPermission): boolean; - interface BaseUser extends abstract.Document { - readonly _source: UserSource; + /** + * Test whether the User has at least the permission level of a certain role + * @param role The role name from USER_ROLES to test + * @param [exact] Require the role match to be exact + * @return Does the user have at this role level (or greater)? + */ + hasRole(role: UserRole | UserRoleName, { exact }?: { exact: boolean }): boolean; +} + +export default interface BaseUser extends Document { + readonly _source: UserSource; - get documentName(): "User"; - } + get documentName(): "User"; +} - interface UserMetadata extends abstract.DocumentMetadata { - name: "User"; - collection: "users"; - label: "DOCUMENT.User"; - isPrimary: true; - } +interface UserMetadata extends DocumentMetadata { + name: "User"; + collection: "users"; + label: "DOCUMENT.User"; + isPrimary: true; +} - interface UserSource { - _id: string; - avatar: ImageFilePath; - img: ImageFilePath; - character: string | null; - color: HexColorString; - hotbar: Record; - name: string; - password: string; - role: UserRole; - flags: DocumentFlags; - } - } +interface UserSource { + _id: string; + avatar: ImageFilePath; + img: ImageFilePath; + character: string | null; + color: HexColorString; + hotbar: Record; + name: string; + password: string; + role: UserRole; + flags: DocumentFlags; } diff --git a/types/foundry/common/documents/wall.d.ts b/types/foundry/common/documents/wall.d.ts index 7f48756560c..68853b33369 100644 --- a/types/foundry/common/documents/wall.d.ts +++ b/types/foundry/common/documents/wall.d.ts @@ -1,41 +1,40 @@ -declare module foundry { - module documents { - /** The Wall embedded document model. */ - class BaseWall extends abstract.Document { - static override get metadata(): WallMetadata; +import type { Document, DocumentMetadata } from "../abstract/module.d.ts"; +import type { BaseScene, BaseUser } from "./module.d.ts"; - /** Is a user able to update an existing Wall? */ - protected static _canUpdate(user: BaseUser, doc: BaseWall, data: WallSource): boolean; +/** The Wall embedded document model. */ +export default class BaseWall extends Document { + static override get metadata(): WallMetadata; - light: WallSenseType; - move: WallSenseType; - sight: WallSenseType; - sound: WallSenseType; - } + /** Is a user able to update an existing Wall? */ + protected static _canUpdate(user: BaseUser, doc: BaseWall, data: WallSource): boolean; - interface BaseWall extends abstract.Document { - readonly _source: WallSource; - } + light: WallSenseType; + move: WallSenseType; + sight: WallSenseType; + sound: WallSenseType; +} + +export default interface BaseWall extends Document { + readonly _source: WallSource; +} - interface WallSource { - c: number[]; - move?: number; - sense?: number; - dir?: number; - door?: number; - ds?: number; - } +interface WallSource { + c: number[]; + move?: number; + sense?: number; + dir?: number; + door?: number; + ds?: number; +} - interface WallMetadata extends abstract.DocumentMetadata { - name: "Wall"; - collection: "walls"; - label: "DOCUMENT.Wall"; - isEmbedded: true; - permissions: { - create: "ASSISTANT"; - update: (typeof documents.BaseWall)["_canUpdate"]; - delete: "ASSISTANT"; - }; - } - } +interface WallMetadata extends DocumentMetadata { + name: "Wall"; + collection: "walls"; + label: "DOCUMENT.Wall"; + isEmbedded: true; + permissions: { + create: "ASSISTANT"; + update: (typeof BaseWall)["_canUpdate"]; + delete: "ASSISTANT"; + }; } diff --git a/types/foundry/common/index.d.ts b/types/foundry/common/index.d.ts deleted file mode 100644 index 3fcab29dfe6..00000000000 --- a/types/foundry/common/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as Constants from "./constants.js"; -import "./data/index.js"; - -declare global { - const CONST: typeof Constants; -} diff --git a/types/foundry/common/module.d.ts b/types/foundry/common/module.d.ts new file mode 100644 index 00000000000..698003e1e0a --- /dev/null +++ b/types/foundry/common/module.d.ts @@ -0,0 +1,23 @@ +import * as Abstract from "./abstract/module.ts"; +import * as Constants from "./constants.ts"; +import * as Data from "./data/module.ts"; +import * as Documents from "./documents/module.ts"; +import * as Utils from "./utils/module.ts"; + +// global-modifying module +import "./types.ts"; + +declare global { + const CONST: typeof Constants; + namespace globalThis { + export import Color = Utils.Color; + + module foundry { + export import CONST = Constants; + export import abstract = Abstract; + export import data = Data; + export import documents = Documents; + export import utils = Utils; + } + } +} diff --git a/types/foundry/common/types.d.ts b/types/foundry/common/types.d.ts index 8cfd9a97a52..7e5c4431b3e 100644 --- a/types/foundry/common/types.d.ts +++ b/types/foundry/common/types.d.ts @@ -1,6 +1,44 @@ -export {}; +import type { Document, EmbeddedCollection } from "./abstract/module.d.ts"; declare global { + interface DocumentConstructionContext { + parent?: TParent; + pack?: string; + [key: string]: unknown; + } + + interface DocumentModificationContext { + /** A parent Document within which these Documents should be embedded */ + parent?: TParent; + /** Block the dispatch of preCreate hooks for this operation */ + noHook?: boolean; + /** A Compendium pack identifier within which the Documents should be modified */ + pack?: string | null; + /** Return an index of the Document collection, used only during a get operation. */ + index?: boolean; + /** When performing a creation operation, keep the provided _id instead of clearing it. */ + keepId?: boolean; + /** When performing a creation operation, keep existing _id values of documents embedded within the one being created instead of generating new ones. */ + keepEmbeddedIds?: boolean; + /** Create a temporary document which is not saved to the database. Only used during creation. */ + temporary?: boolean; + /** Automatically re-render existing applications associated with the document. */ + render?: boolean; + /** Automatically create and render the Document sheet when the Document is first created. */ + renderSheet?: boolean; + /** Difference each update object against current Document data to reduce the size of the transferred data. Only used during update. */ + diff?: boolean; + /** Merge objects recursively. If false, inner objects will be replaced explicitly. Use with caution! */ + recursive?: boolean; + /** Whether to delete all documents of a given type, regardless of the array of ids provided. Only used during a delete operation. */ + deleteAll?: boolean; + } + + type DocumentUpdateContext = Omit< + DocumentModificationContext, + "deleteAll" | "index" | "keepId" | "keepEmbeddedIds" | "temporary" + >; + /* ----------------------------------------- */ /* Reusable Type Definitions */ /* ----------------------------------------- */ diff --git a/types/foundry/common/utils/collection.d.ts b/types/foundry/common/utils/collection.d.ts index 30802900be8..18fa561f163 100644 --- a/types/foundry/common/utils/collection.d.ts +++ b/types/foundry/common/utils/collection.d.ts @@ -1,127 +1,121 @@ -declare module foundry { - module utils { - /** - * A reusable storage concept which blends the functionality of an Array with the efficient key-based lookup of a Map. - * This concept is reused throughout Foundry VTT where a collection of uniquely identified elements is required. - */ - interface Collection - extends Omit, "forEach" | "delete" | "set" | SymbolConstructor["iterator"]> { - set(key: string, value: V): this; +/** + * A reusable storage concept which blends the functionality of an Array with the efficient key-based lookup of a Map. + * This concept is reused throughout Foundry VTT where a collection of uniquely identified elements is required. + */ +declare interface Collection + extends Omit, "forEach" | "delete" | "set" | SymbolConstructor["iterator"]> { + set(key: string, value: V): this; - delete(key: string): boolean; + delete(key: string): boolean; - /** When iterating over a Collection, we should iterate over its values instead of over its entries */ - [Symbol.iterator](): IterableIterator; + /** When iterating over a Collection, we should iterate over its values instead of over its entries */ + [Symbol.iterator](): IterableIterator; - /** Return an Array of all the entry values in the Collection */ - get contents(): V[]; + /** Return an Array of all the entry values in the Collection */ + get contents(): V[]; - /** - * Find an entry in the Map using an functional condition. - * @see {Array#find} - * - * @param condition The functional condition to test - * @return The value, if found, otherwise null - * - * @example - * let c = new Collection([["a", "A"], ["b", "B"], ["c", "C"]]); - * let a = c.find(entry => entry === "A"); - */ - find(condition: (value: V) => boolean): T | undefined; + /** + * Find an entry in the Map using an functional condition. + * @see {Array#find} + * + * @param condition The functional condition to test + * @return The value, if found, otherwise null + * + * @example + * let c = new Collection([["a", "A"], ["b", "B"], ["c", "C"]]); + * let a = c.find(entry => entry === "A"); + */ + find(condition: (value: V) => boolean): T | undefined; - /** - * Filter the Collection, returning an Array of entries which match a functional condition. - * @see {Array#filter} - * @param condition The functional condition to test - * @return An Array of matched values - * - * @example - * let c = new Collection([["a", "AA"], ["b", "AB"], ["c", "CC"]]); - * let hasA = c.filters(entry => entry.slice(0) === "A"); - */ - filter(condition: (value: V) => value is T): T[]; - filter(condition: (value: V) => boolean): T[]; + /** + * Filter the Collection, returning an Array of entries which match a functional condition. + * @see {Array#filter} + * @param condition The functional condition to test + * @return An Array of matched values + * + * @example + * let c = new Collection([["a", "AA"], ["b", "AB"], ["c", "CC"]]); + * let hasA = c.filters(entry => entry.slice(0) === "A"); + */ + filter(condition: (value: V) => value is T): T[]; + filter(condition: (value: V) => boolean): T[]; - /** - * Apply a function to each element of the collection - * @see Array#forEach - * @param fn The function to apply - * - * @example - * let c = new Collection([["a", {active: false}], ["b", {active: false}], ["c", {active: false}]]); - * c.forEach(e => e.active = true); - */ - forEach(fn: (value: V) => void): void; + /** + * Apply a function to each element of the collection + * @see Array#forEach + * @param fn The function to apply + * + * @example + * let c = new Collection([["a", {active: false}], ["b", {active: false}], ["c", {active: false}]]); + * c.forEach(e => e.active = true); + */ + forEach(fn: (value: V) => void): void; - /** - * Get an element from the Collection by its key. - * @param key The key of the entry to retrieve - * @param strict Throw an Error if the requested id does not exist, otherwise return null. Default false - * @return The retrieved entry value, if the key exists, otherwise null - * - * @example - * let c = new Collection([["a", "A"], ["b", "B"], ["c", "C"]]); - * c.get("a"); // "A" - * c.get("d"); // null - * c.get("d", {strict: true}); // throws Error - */ - get(key: Maybe, { strict }: { strict: true }): T; - get(key: string, { strict }?: CollectionGetOptions): T | undefined; + /** + * Get an element from the Collection by its key. + * @param key The key of the entry to retrieve + * @param strict Throw an Error if the requested id does not exist, otherwise return null. Default false + * @return The retrieved entry value, if the key exists, otherwise null + * + * @example + * let c = new Collection([["a", "A"], ["b", "B"], ["c", "C"]]); + * c.get("a"); // "A" + * c.get("d"); // null + * c.get("d", {strict: true}); // throws Error + */ + get(key: Maybe, { strict }: { strict: true }): T; + get(key: string, { strict }?: CollectionGetOptions): T | undefined; - /** - * Get an entry from the Collection by name. - * Use of this method assumes that the objects stored in the collection have a "name" attribute. - * @param name The name of the entry to retrieve - * @param strict Throw an Error if the requested id does not exist, otherwise return null. Default false. - * @return The retrieved Entity, if one was found, otherwise null; - */ - getName(name: string, { strict }?: { strict?: boolean }): V | undefined; + /** + * Get an entry from the Collection by name. + * Use of this method assumes that the objects stored in the collection have a "name" attribute. + * @param name The name of the entry to retrieve + * @param strict Throw an Error if the requested id does not exist, otherwise return null. Default false. + * @return The retrieved Entity, if one was found, otherwise null; + */ + getName(name: string, { strict }?: { strict?: boolean }): V | undefined; - /** - * Transform each element of the Collection into a new form, returning an Array of transformed values - * @param transformer The transformation function to apply to each entry value - * @return An Array of transformed values - */ - map(transformer: (value: V) => T): T[]; + /** + * Transform each element of the Collection into a new form, returning an Array of transformed values + * @param transformer The transformation function to apply to each entry value + * @return An Array of transformed values + */ + map(transformer: (value: V) => T): T[]; - /** - * Reduce the Collection by applying an evaluator function and accumulating entries - * @see {Array#reduce} - * @param evaluator A function which mutates the accumulator each iteration - * @param initial An initial value which accumulates with each iteration - * @return The accumulated result - * - * @example - * let c = new Collection([["a", "A"], ["b", "B"], ["c", "C"]]); - * let letters = c.reduce((s, l) => { - * return s + l; - * }, ""); // "ABC" - */ - reduce(evaluator: (accumlator: T, value: V) => T, initial: T): T; + /** + * Reduce the Collection by applying an evaluator function and accumulating entries + * @see {Array#reduce} + * @param evaluator A function which mutates the accumulator each iteration + * @param initial An initial value which accumulates with each iteration + * @return The accumulated result + * + * @example + * let c = new Collection([["a", "A"], ["b", "B"], ["c", "C"]]); + * let letters = c.reduce((s, l) => { + * return s + l; + * }, ""); // "ABC" + */ + reduce(evaluator: (accumlator: T, value: V) => T, initial: T): T; - /** - * Test whether a condition is met by some entry in the Collection - * @see {Array#some} - * @param condition A test condition to apply to each entry - * @return Was the test condition passed by at least one entry? - */ - some(condition: (value: V) => boolean): boolean; - } - - interface CollectionConstructor { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - new (): Collection; - new (entries?: readonly (readonly [string, V])[] | null): Collection; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - readonly prototype: Collection; - } + /** + * Test whether a condition is met by some entry in the Collection + * @see {Array#some} + * @param condition A test condition to apply to each entry + * @return Was the test condition passed by at least one entry? + */ + some(condition: (value: V) => boolean): boolean; +} - const Collection: CollectionConstructor; - } +declare interface CollectionConstructor { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + new (): Collection; + new (entries?: readonly (readonly [string, V])[] | null): Collection; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + readonly prototype: Collection; } -declare type Collection = foundry.utils.Collection; -declare const Collection: typeof foundry.utils.Collection; -declare interface CollectionGetOptions { +declare var Collection: CollectionConstructor; + +interface CollectionGetOptions { strict?: boolean; } diff --git a/types/foundry/common/utils/color.d.ts b/types/foundry/common/utils/color.d.ts index 81875ef88bd..723b2c7a376 100644 --- a/types/foundry/common/utils/color.d.ts +++ b/types/foundry/common/utils/color.d.ts @@ -1,153 +1,143 @@ -export {}; - -declare global { - module foundry { - module utils { - /** - * A representation of a color in hexadecimal format. - * This class provides methods for transformations and manipulations of colors. - */ - class Color extends Number { - /** - * A CSS-compatible color string. - * An alias for Color#toString. - */ - get css(): string; - - /** The color represented as an RGB array. */ - get rgb(): [number, number, number]; - - /** The numeric value of the red channel between [0, 1]. */ - get r(): number; - - /** The numeric value of the green channel between [0, 1]. */ - get g(): number; - - /** The numeric value of the blue channel between [0, 1]. */ - get b(): number; - - /** The maximum value of all channels. */ - get maximum(): number; - - /** The minimum value of all channels. */ - get minimum(): number; - - /** Get the value of this color in little endian format. */ - get littleEndian(): number; - - /** - * The color represented as an HSV array. - * Conversion formula adapted from http://en.wikipedia.org/wiki/HSV_color_space. - * Assumes r, g, and b are contained in the set [0, 1] and returns h, s, and v in the set [0, 1]. - */ - get hsv(): [number, number, number]; - - /* ------------------------------------------ */ - /* Color Manipulation Methods */ - /* ------------------------------------------ */ - - override toString(radix?: number): string; - - /** - * Test whether this color equals some other color - * @param other Some other color or hex number - * @returns Are the colors equal? - */ - equals(other: Color | number): boolean; - - /** - * Get a CSS-compatible RGBA color string. - * @param alpha The desired alpha in the range [0, 1] - * @returns A CSS-compatible RGBA string - */ - toRGBA(alpha: number): string; - - /** - * Mix this Color with some other Color using a provided interpolation weight. - * @param other Some other Color to mix with - * @param weight The mixing weight placed on this color where weight is placed on the other color - * @returns The resulting mixed Color - */ - mix(other: Color, weight: number): Color; - - /** - * Multiply this Color by another Color or a static scalar. - * @param other Some other Color or a static scalar. - * @returns The resulting Color. - */ - multiply(other: Color | number): Color; - - /** - * Add this Color by another Color or a static scalar. - * @param other Some other Color or a static scalar. - * @returns The resulting Color. - */ - add(other: Color | number): Color; - - /** - * Subtract this Color by another Color or a static scalar. - * @param other Some other Color or a static scalar. - * @returns The resulting Color. - */ - subtract(other: Color | number): Color; - - /** - * Max this color by another Color or a static scalar. - * @param other Some other Color or a static scalar. - * @returns The resulting Color. - */ - maximize(other: Color | number): Color; - - /** - * Min this color by another Color or a static scalar. - * @param other Some other Color or a static scalar. - * @returns The resulting Color. - */ - minimize(other: Color | number): Color; - - /* ------------------------------------------ */ - /* Iterator */ - /* ------------------------------------------ */ - - /** Iterating over a Color is equivalent to iterating over its [r,g,b] color channels. */ - [Symbol.iterator](): Generator; - - /* ------------------------------------------ */ - /* Factory Methods */ - /* ------------------------------------------ */ - - /** - * Create a Color instance from an RGB array. - * @param color A color input - * @returns The hex color instance or NaN - */ - static from(color: null | string | number | [number, number, number]): Color | number; - - /** - * Create a Color instance from a color string which either includes or does not include a leading #. - * @param color A color string - * @returns The hex color instance - */ - static fromString(color: string): Color; - - /** - * Create a Color instance from an RGB array. - * @param rgb An RGB tuple - * @returns The hex color instance - */ - static fromRGB(rgb: [number, number, number]): Color; - - /** - * Create a Color instance from an HSV array. - * Conversion formula adapted from http://en.wikipedia.org/wiki/HSV_color_space. - * Assumes h, s, and v are contained in the set [0, 1]. - * @param hsv An HSV tuple - * @returns The hex color instance - */ - static fromHSV(hsv: [number, number, number]): Color; - } - } - } - - type Color = foundry.utils.Color; +/** + * A representation of a color in hexadecimal format. + * This class provides methods for transformations and manipulations of colors. + */ +export default class Color extends Number { + /** + * A CSS-compatible color string. + * An alias for Color#toString. + */ + get css(): string; + + /** The color represented as an RGB array. */ + get rgb(): [number, number, number]; + + /** The numeric value of the red channel between [0, 1]. */ + get r(): number; + + /** The numeric value of the green channel between [0, 1]. */ + get g(): number; + + /** The numeric value of the blue channel between [0, 1]. */ + get b(): number; + + /** The maximum value of all channels. */ + get maximum(): number; + + /** The minimum value of all channels. */ + get minimum(): number; + + /** Get the value of this color in little endian format. */ + get littleEndian(): number; + + /** + * The color represented as an HSV array. + * Conversion formula adapted from http://en.wikipedia.org/wiki/HSV_color_space. + * Assumes r, g, and b are contained in the set [0, 1] and returns h, s, and v in the set [0, 1]. + */ + get hsv(): [number, number, number]; + + /* ------------------------------------------ */ + /* Color Manipulation Methods */ + /* ------------------------------------------ */ + + override toString(radix?: number): string; + + /** + * Test whether this color equals some other color + * @param other Some other color or hex number + * @returns Are the colors equal? + */ + equals(other: Color | number): boolean; + + /** + * Get a CSS-compatible RGBA color string. + * @param alpha The desired alpha in the range [0, 1] + * @returns A CSS-compatible RGBA string + */ + toRGBA(alpha: number): string; + + /** + * Mix this Color with some other Color using a provided interpolation weight. + * @param other Some other Color to mix with + * @param weight The mixing weight placed on this color where weight is placed on the other color + * @returns The resulting mixed Color + */ + mix(other: Color, weight: number): Color; + + /** + * Multiply this Color by another Color or a static scalar. + * @param other Some other Color or a static scalar. + * @returns The resulting Color. + */ + multiply(other: Color | number): Color; + + /** + * Add this Color by another Color or a static scalar. + * @param other Some other Color or a static scalar. + * @returns The resulting Color. + */ + add(other: Color | number): Color; + + /** + * Subtract this Color by another Color or a static scalar. + * @param other Some other Color or a static scalar. + * @returns The resulting Color. + */ + subtract(other: Color | number): Color; + + /** + * Max this color by another Color or a static scalar. + * @param other Some other Color or a static scalar. + * @returns The resulting Color. + */ + maximize(other: Color | number): Color; + + /** + * Min this color by another Color or a static scalar. + * @param other Some other Color or a static scalar. + * @returns The resulting Color. + */ + minimize(other: Color | number): Color; + + /* ------------------------------------------ */ + /* Iterator */ + /* ------------------------------------------ */ + + /** Iterating over a Color is equivalent to iterating over its [r,g,b] color channels. */ + [Symbol.iterator](): Generator; + + /* ------------------------------------------ */ + /* Factory Methods */ + /* ------------------------------------------ */ + + /** + * Create a Color instance from an RGB array. + * @param color A color input + * @returns The hex color instance or NaN + */ + static from(color: null | string | number | [number, number, number]): Color | number; + + /** + * Create a Color instance from a color string which either includes or does not include a leading #. + * @param color A color string + * @returns The hex color instance + */ + static fromString(color: string): Color; + + /** + * Create a Color instance from an RGB array. + * @param rgb An RGB tuple + * @returns The hex color instance + */ + static fromRGB(rgb: [number, number, number]): Color; + + /** + * Create a Color instance from an HSV array. + * Conversion formula adapted from http://en.wikipedia.org/wiki/HSV_color_space. + * Assumes h, s, and v are contained in the set [0, 1]. + * @param hsv An HSV tuple + * @returns The hex color instance + */ + static fromHSV(hsv: [number, number, number]): Color; } diff --git a/types/foundry/common/utils/geometry.d.ts b/types/foundry/common/utils/geometry.d.ts index 0c78ec75e65..63f3d6c9432 100644 --- a/types/foundry/common/utils/geometry.d.ts +++ b/types/foundry/common/utils/geometry.d.ts @@ -1,120 +1,108 @@ -export {}; +/** + * Determine the relative orientation of three points in two-dimensional space. + * The result is also an approximation of twice the signed area of the triangle defined by the three points. + * This method is fast - but not robust against issues of floating point precision. Best used with integer coordinates. + * Adapted from https://github.com/mourner/robust-predicates + * + * @param a An endpoint of segment AB, relative to which point C is tested + * @param b An endpoint of segment AB, relative to which point C is tested + * @param c A point that is tested relative to segment AB + * + * @returns The relative orientation of points A, B, and C + * A positive value if the points are in counter-clockwise order (C lies to the left of AB) + * A negative value if the points are in clockwise order (C lies to the right of AB) + * Zero if the points A, B, and C are collinear. + */ +export function orient2dFast(a: Point, b: Point, c: Point): number; -declare global { - module foundry { - module utils { - /** - * Determine the relative orientation of three points in two-dimensional space. - * The result is also an approximation of twice the signed area of the triangle defined by the three points. - * This method is fast - but not robust against issues of floating point precision. Best used with integer coordinates. - * Adapted from https://github.com/mourner/robust-predicates - * - * @param a An endpoint of segment AB, relative to which point C is tested - * @param b An endpoint of segment AB, relative to which point C is tested - * @param c A point that is tested relative to segment AB - * - * @returns The relative orientation of points A, B, and C - * A positive value if the points are in counter-clockwise order (C lies to the left of AB) - * A negative value if the points are in clockwise order (C lies to the right of AB) - * Zero if the points A, B, and C are collinear. - */ - function orient2dFast(a: Point, b: Point, c: Point): number; - - /** - * Quickly test whether the line segment AB intersects with the line segment CD. - * This method does not determine the point of intersection, for that use lineLineIntersection - * - * @param a The first endpoint of segment AB - * @param b The second endpoint of segment AB - * @param c The first endpoint of segment CD - * @param d The second endpoint of segment CD - * - * @returns Do the line segments intersect? - */ - function lineSegmentIntersects(a: Point, b: Point, c: Point, d: Point): boolean; +/** + * Quickly test whether the line segment AB intersects with the line segment CD. + * This method does not determine the point of intersection, for that use lineLineIntersection + * + * @param a The first endpoint of segment AB + * @param b The second endpoint of segment AB + * @param c The first endpoint of segment CD + * @param d The second endpoint of segment CD + * + * @returns Do the line segments intersect? + */ +export function lineSegmentIntersects(a: Point, b: Point, c: Point, d: Point): boolean; - /** - * An internal helper method for computing the intersection between two infinite-length lines. - * Adapted from http://paulbourke.net/geometry/pointlineplane/ - * - * @param a The first endpoint of segment AB - * @param b The second endpoint of segment AB - * @param c The first endpoint of segment CD - * @param d The second endpoint of segment CD - * - * @returns An intersection point, or null if no intersection occurred - */ - function lineLineIntersection(a: Point, b: Point, c: Point, d: Point): LineIntersection | null; +/** + * An internal helper method for computing the intersection between two infinite-length lines. + * Adapted from http://paulbourke.net/geometry/pointlineplane/ + * + * @param a The first endpoint of segment AB + * @param b The second endpoint of segment AB + * @param c The first endpoint of segment CD + * @param d The second endpoint of segment CD + * + * @returns An intersection point, or null if no intersection occurred + */ +export function lineLineIntersection(a: Point, b: Point, c: Point, d: Point): LineIntersection | null; - /** - * An internal helper method for computing the intersection between two finite line segments. - * Adapted from http://paulbourke.net/geometry/pointlineplane/ - * - * @param a The first endpoint of segment AB - * @param b The second endpoint of segment AB - * @param c The first endpoint of segment CD - * @param d The second endpoint of segment CD - * @param [epsilon] A small epsilon which defines a tolerance for near-equality - * - * @returns An intersection point, or null if no intersection occurred - */ - function lineSegmentIntersection( - a: Point, - b: Point, - c: Point, - d: Point, - epsilon?: number - ): LineIntersection | null; +/** + * An internal helper method for computing the intersection between two finite line segments. + * Adapted from http://paulbourke.net/geometry/pointlineplane/ + * + * @param a The first endpoint of segment AB + * @param b The second endpoint of segment AB + * @param c The first endpoint of segment CD + * @param d The second endpoint of segment CD + * @param [epsilon] A small epsilon which defines a tolerance for near-equality + * + * @returns An intersection point, or null if no intersection occurred + */ +export function lineSegmentIntersection( + a: Point, + b: Point, + c: Point, + d: Point, + epsilon?: number +): LineIntersection | null; - /** - * Determine the intersection between a candidate wall and the circular radius of the polygon. - * @param a The initial vertex of the candidate edge - * @param b The second vertex of the candidate edge - * @param center The center of the bounding circle - * @param radius The radius of the bounding circle - * @param epsilon A small tolerance for floating point precision - * - * @returns The intersection of the segment AB with the circle - */ - export function lineCircleIntersection( - a: Point, - b: Point, - center: Point, - radius: number, - epsilon?: number - ): LineCircleIntersection; +/** + * Determine the intersection between a candidate wall and the circular radius of the polygon. + * @param a The initial vertex of the candidate edge + * @param b The second vertex of the candidate edge + * @param center The center of the bounding circle + * @param radius The radius of the bounding circle + * @param epsilon A small tolerance for floating point precision + * + * @returns The intersection of the segment AB with the circle + */ +export function lineCircleIntersection( + a: Point, + b: Point, + center: Point, + radius: number, + epsilon?: number +): LineCircleIntersection; - /** - * Identify the point closest to C on segment AB - * @param c The reference point C - * @param a Point A on segment AB - * @param b Point B on segment AB - * - * @returns The closest point to C on segment AB - */ - export function closestPointToSegment(c: Point, a: Point, b: Point): Point; +/** + * Identify the point closest to C on segment AB + * @param c The reference point C + * @param a Point A on segment AB + * @param b Point B on segment AB + * + * @returns The closest point to C on segment AB + */ +export function closestPointToSegment(c: Point, a: Point, b: Point): Point; - /** - * Determine the points of intersection between a line segment (p0,p1) and a circle. - * There will be zero, one, or two intersections - * See https://math.stackexchange.com/a/311956 - * - * @param p0 The initial point of the line segment - * @param p1 The terminal point of the line segment - * @param center The center of the circle - * @param radius The radius of the circle - * @param [epsilon=0] A small tolerance for floating point precision - */ - function quadraticIntersection( - p0: Point, - p1: Point, - center: Point, - radius: number, - epsilon?: number - ): Point[]; - } - } +/** + * Determine the points of intersection between a line segment (p0,p1) and a circle. + * There will be zero, one, or two intersections + * See https://math.stackexchange.com/a/311956 + * + * @param p0 The initial point of the line segment + * @param p1 The terminal point of the line segment + * @param center The center of the circle + * @param radius The radius of the circle + * @param [epsilon=0] A small tolerance for floating point precision + */ +export function quadraticIntersection(p0: Point, p1: Point, center: Point, radius: number, epsilon?: number): Point[]; +declare global { /** * @property x The x-coordinate of intersection * @property y The y-coordinate of intersection diff --git a/types/foundry/common/utils/helpers.d.ts b/types/foundry/common/utils/helpers.d.ts index 40b2b3c6874..e0525d0e3b5 100644 --- a/types/foundry/common/utils/helpers.d.ts +++ b/types/foundry/common/utils/helpers.d.ts @@ -1,293 +1,279 @@ -export {}; +/** + * Wrap a callback in a debounced timeout. + * Delay execution of the callback function until the function has not been called for delay milliseconds + * @param callback A function to execute once the debounced threshold has been passed + * @param delay An amount of time in milliseconds to delay + * @return A wrapped function which can be called to debounce execution + */ +export function debounce(callback: (...args: T) => unknown, delay: number): (...args: T) => void; -declare global { - module foundry { - module utils { - /** - * Wrap a callback in a debounced timeout. - * Delay execution of the callback function until the function has not been called for delay milliseconds - * @param callback A function to execute once the debounced threshold has been passed - * @param delay An amount of time in milliseconds to delay - * @return A wrapped function which can be called to debounce execution - */ - function debounce( - callback: (...args: T) => unknown, - delay: number - ): (...args: T) => void; - - /** - * Quickly clone a simple piece of data, returning a copy which can be mutated safely. - * This method DOES support recursive data structures containing inner objects or arrays. - * This method DOES NOT support advanced object types like Set, Map, or other specialized classes. - * @param original Some sort of data - * @return The clone of that data - */ - function deepClone(original: T): T; +/** + * Quickly clone a simple piece of data, returning a copy which can be mutated safely. + * This method DOES support recursive data structures containing inner objects or arrays. + * This method DOES NOT support advanced object types like Set, Map, or other specialized classes. + * @param original Some sort of data + * @return The clone of that data + */ +export function deepClone(original: T): T; - /** - * A cheap data duplication trick which is relatively robust. - * For a subset of cases the deepClone function will offer better performance. - * @param original Some sort of data - */ - function duplicate(original: T): T; +/** + * A cheap data duplication trick which is relatively robust. + * For a subset of cases the deepClone function will offer better performance. + * @param original Some sort of data + */ +export function duplicate(original: T): T; - /** - * Update a source object by replacing its keys and values with those from a target object. - * - * @param original The initial object which should be updated with values from the target - * @param [other={}] A new object whose values should replace those in the source - * @param [options={}] Additional options which configure the merge - * @param [options.insertKeys=true] Control whether to insert new top-level objects into the resulting structure which do not previously exist in the original object. - * @param [options.insertValues=true] Control whether to insert new nested values into child objects in the resulting structure which did not previously exist in the original object. - * @param [options.overwrite=true] Control whether to replace existing values in the source, or only merge values which do not already exist in the original object. - * @param [options.recursive=true] Control whether to merge inner-objects recursively (if true), or whether to simply replace inner objects with a provided new value. - * @param [options.inplace=true] Control whether to apply updates to the original object in-place (if true), otherwise the original object is duplicated and the copy is merged. - * @param [options.enforceTypes=false] Control whether strict type checking requires that the value of a key in the other object must match the data type in the original data to be merged. - * @param [options.performDeletions=false] Control whether to perform deletions on the original object if deletion keys are present in the other object. - * @param [_d=0] A privately used parameter to track recursion depth. - * @returns The original source object including updated, inserted, or overwritten records. - * - * @example Control how new keys and values are added - * mergeObject({k1: "v1"}, {k2: "v2"}, {insertKeys: false}); // {k1: "v1"} - * mergeObject({k1: "v1"}, {k2: "v2"}, {insertKeys: true}); // {k1: "v1", k2: "v2"} - * mergeObject({k1: {i1: "v1"}}, {k1: {i2: "v2"}}, {insertValues: false}); // {k1: {i1: "v1"}} - * mergeObject({k1: {i1: "v1"}}, {k1: {i2: "v2"}}, {insertValues: true}); // {k1: {i1: "v1", i2: "v2"}} - * - * @example Control how existing data is overwritten - * mergeObject({k1: "v1"}, {k1: "v2"}, {overwrite: true}); // {k1: "v2"} - * mergeObject({k1: "v1"}, {k1: "v2"}, {overwrite: false}); // {k1: "v1"} - * - * @example Control whether merges are performed recursively - * mergeObject({k1: {i1: "v1"}}, {k1: {i2: "v2"}}, {recursive: false}); // {k1: {i1: "v2"}} - * mergeObject({k1: {i1: "v1"}}, {k1: {i2: "v2"}}, {recursive: true}); // {k1: {i1: "v1", i2: "v2"}} - * - * @example Deleting an existing object key - * mergeObject({k1: "v1", k2: "v2"}, {"-=k1": null}); // {k2: "v2"} - */ - function mergeObject( - original: T, - other: U, - { insertKeys, insertValues, overwrite, inplace, enforceTypes, performDeletions }?: MergeObjectOptions, - _d?: number - ): T & U; +/** + * Update a source object by replacing its keys and values with those from a target object. + * + * @param original The initial object which should be updated with values from the target + * @param [other={}] A new object whose values should replace those in the source + * @param [options={}] Additional options which configure the merge + * @param [options.insertKeys=true] Control whether to insert new top-level objects into the resulting structure which do not previously exist in the original object. + * @param [options.insertValues=true] Control whether to insert new nested values into child objects in the resulting structure which did not previously exist in the original object. + * @param [options.overwrite=true] Control whether to replace existing values in the source, or only merge values which do not already exist in the original object. + * @param [options.recursive=true] Control whether to merge inner-objects recursively (if true), or whether to simply replace inner objects with a provided new value. + * @param [options.inplace=true] Control whether to apply updates to the original object in-place (if true), otherwise the original object is duplicated and the copy is merged. + * @param [options.enforceTypes=false] Control whether strict type checking requires that the value of a key in the other object must match the data type in the original data to be merged. + * @param [options.performDeletions=false] Control whether to perform deletions on the original object if deletion keys are present in the other object. + * @param [_d=0] A privately used parameter to track recursion depth. + * @returns The original source object including updated, inserted, or overwritten records. + * + * @example Control how new keys and values are added + * mergeObject({k1: "v1"}, {k2: "v2"}, {insertKeys: false}); // {k1: "v1"} + * mergeObject({k1: "v1"}, {k2: "v2"}, {insertKeys: true}); // {k1: "v1", k2: "v2"} + * mergeObject({k1: {i1: "v1"}}, {k1: {i2: "v2"}}, {insertValues: false}); // {k1: {i1: "v1"}} + * mergeObject({k1: {i1: "v1"}}, {k1: {i2: "v2"}}, {insertValues: true}); // {k1: {i1: "v1", i2: "v2"}} + * + * @example Control how existing data is overwritten + * mergeObject({k1: "v1"}, {k1: "v2"}, {overwrite: true}); // {k1: "v2"} + * mergeObject({k1: "v1"}, {k1: "v2"}, {overwrite: false}); // {k1: "v1"} + * + * @example Control whether merges are performed recursively + * mergeObject({k1: {i1: "v1"}}, {k1: {i2: "v2"}}, {recursive: false}); // {k1: {i1: "v2"}} + * mergeObject({k1: {i1: "v1"}}, {k1: {i2: "v2"}}, {recursive: true}); // {k1: {i1: "v1", i2: "v2"}} + * + * @example Deleting an existing object key + * mergeObject({k1: "v1", k2: "v2"}, {"-=k1": null}); // {k2: "v2"} + */ +export function mergeObject( + original: T, + other: U, + { insertKeys, insertValues, overwrite, inplace, enforceTypes, performDeletions }?: MergeObjectOptions, + _d?: number +): T & U; - /** - * Learn the named type of a token - extending the functionality of typeof to recognize some core Object types - * @param token Some passed token - * @return The named type of the token - */ - function getType(token: unknown): string; +/** + * Learn the named type of a token - extending the functionality of typeof to recognize some core Object types + * @param token Some passed token + * @return The named type of the token + */ +export function getType(token: unknown): string; - /** - * A temporary shim to invert an object, flipping keys and values - * @param obj Some object where the values are unique - * @return An inverted object where the values of the original object are the keys of the new object - */ - function invertObject(obj: object): object; +/** + * A temporary shim to invert an object, flipping keys and values + * @param obj Some object where the values are unique + * @return An inverted object where the values of the original object are the keys of the new object + */ +export function invertObject(obj: object): object; - /** - * Filter the contents of some source object using the structure of a template object. - * Only keys which exist in the template are preserved in the source object. - * - * @param source An object which contains the data you wish to filter - * @param template An object which contains the structure you wish to preserve - * @param keepSpecial Whether to keep special tokens like deletion keys - * @param templateValues Instead of keeping values from the source, instead draw values from the template - * - * @example - * const source = {foo: {number: 1, name: "Tim", topping: "olives"}, bar: "baz"}; - * const template = {foo: {number: 0, name: "Mit", style: "bold"}, other: 72}; - * filterObject(source, template); // {foo: {number: 1, name: "Tim"}}; - * filterObject(source, template, {templateValues: true}); // {foo: {number: 0, name: "Mit"}}; - */ - function filterObject( - source: object, - template: object, - keepSpecial?: boolean, - templateValues?: boolean - ): object; +/** + * Filter the contents of some source object using the structure of a template object. + * Only keys which exist in the template are preserved in the source object. + * + * @param source An object which contains the data you wish to filter + * @param template An object which contains the structure you wish to preserve + * @param keepSpecial Whether to keep special tokens like deletion keys + * @param templateValues Instead of keeping values from the source, instead draw values from the template + * + * @example + * const source = {foo: {number: 1, name: "Tim", topping: "olives"}, bar: "baz"}; + * const template = {foo: {number: 0, name: "Mit", style: "bold"}, other: 72}; + * filterObject(source, template); // {foo: {number: 1, name: "Tim"}}; + * filterObject(source, template, {templateValues: true}); // {foo: {number: 0, name: "Mit"}}; + */ +export function filterObject(source: object, template: object, keepSpecial?: boolean, templateValues?: boolean): object; - /** - * Flatten a possibly multi-dimensional object to a one-dimensional one by converting all nested keys to dot notation - * @param obj The object to flatten - * @param _d Recursion depth, to prevent overflow - * @return A flattened object - */ - function flattenObject(obj: object, _d?: number): Record; +/** + * Flatten a possibly multi-dimensional object to a one-dimensional one by converting all nested keys to dot notation + * @param obj The object to flatten + * @param _d Recursion depth, to prevent overflow + * @return A flattened object + */ +export function flattenObject(obj: object, _d?: number): Record; - /** - * Expand a flattened object to be a standard multi-dimensional nested Object by converting all dot-notation keys to - * inner objects. - * - * @param obj The object to expand - * @param _d Recursion depth, to prevent overflow - * @return An expanded object - */ - function expandObject(obj: object, _d?: number): T; +/** + * Expand a flattened object to be a standard multi-dimensional nested Object by converting all dot-notation keys to + * inner objects. + * + * @param obj The object to expand + * @param _d Recursion depth, to prevent overflow + * @return An expanded object + */ +export function expandObject(obj: object, _d?: number): T; - /** - * A simple function to test whether or not an Object is empty - * @param obj The object to test - * @return Is the object empty? - */ - function isObjectEmpty(obj: object): boolean; +/** + * A simple function to test whether or not an Object is empty + * @param obj The object to test + * @return Is the object empty? + */ +export function isObjectEmpty(obj: object): boolean; - /** - * Deeply difference an object against some other, returning the update keys and values - * @param original - * @param other - * @return - */ - function diffObject = Record>( - original: object, - other: object - ): T; +/** + * Deeply difference an object against some other, returning the update keys and values + * @param original + * @param other + * @return + */ +export function diffObject = Record>( + original: object, + other: object +): T; - /** - * A helper function which tests whether an object has a property or nested property given a string key. - * The string key supports the notation a.b.c which would return true if object[a][b][c] exists - * @param object The object to traverse - * @param key An object property with notation a.b.c - * - * @return An indicator for whether the property exists - */ - function hasProperty(object: object, key: string): boolean; +/** + * A helper function which tests whether an object has a property or nested property given a string key. + * The string key supports the notation a.b.c which would return true if object[a][b][c] exists + * @param object The object to traverse + * @param key An object property with notation a.b.c + * + * @return An indicator for whether the property exists + */ +export function hasProperty(object: object, key: string): boolean; - /** - * A helper function which searches through an object to retrieve a value by a string key. - * The string key supports the notation a.b.c which would return object[a][b][c] - * @param object The object to traverse - * @param key An object property with notation a.b.c - * - * @return The value of the found property - */ - function getProperty(object: object, key: string): unknown; +/** + * A helper function which searches through an object to retrieve a value by a string key. + * The string key supports the notation a.b.c which would return object[a][b][c] + * @param object The object to traverse + * @param key An object property with notation a.b.c + * + * @return The value of the found property + */ +export function getProperty(object: object, key: string): unknown; - /** - * A helper function which searches through an object to assign a value using a string key - * This string key supports the notation a.b.c which would target object[a][b][c] - * - * @param object The object to update - * @param key The string key - * @param value The value to be assigned - * - * @return A flag for whether or not the object was updated - */ - function setProperty(object: object, key: string, value: unknown): boolean; +/** + * A helper function which searches through an object to assign a value using a string key + * This string key supports the notation a.b.c which would target object[a][b][c] + * + * @param object The object to update + * @param key The string key + * @param value The value to be assigned + * + * @return A flag for whether or not the object was updated + */ +export function setProperty(object: object, key: string, value: unknown): boolean; - /** - * Encode a url-like string by replacing any characters which need encoding - * @param path A fully-qualified URL or url component (like a relative path) - * @return An encoded URL string - */ - function encodeURL(path: string): string; +/** + * Encode a url-like string by replacing any characters which need encoding + * @param path A fully-qualified URL or url component (like a relative path) + * @return An encoded URL string + */ +export function encodeURL(path: string): string; - /** - * Express a timestamp as a relative string - * @param timeStamp - * @return - */ - function timeSince(timeStamp: Date): string; +/** + * Express a timestamp as a relative string + * @param timeStamp + * @return + */ +export function timeSince(timeStamp: Date): string; - /** - * Converts an RGB color value to HSV. Conversion formula - * adapted from http://en.wikipedia.org/wiki/HSV_color_space. - * Assumes r, g, and b are contained in the set [0, 1] and - * returns h, s, and v in the set [0, 1]. - * - * @param r The red color value - * @param g The green color value - * @param b The blue color value - * @return The HSV representation - */ - function rgbToHsv(r: number, g: number, b: number): number[]; +/** + * Converts an RGB color value to HSV. Conversion formula + * adapted from http://en.wikipedia.org/wiki/HSV_color_space. + * Assumes r, g, and b are contained in the set [0, 1] and + * returns h, s, and v in the set [0, 1]. + * + * @param r The red color value + * @param g The green color value + * @param b The blue color value + * @return The HSV representation + */ +export function rgbToHsv(r: number, g: number, b: number): number[]; - /** - * Converts an HSV color value to RGB. Conversion formula - * adapted from http://en.wikipedia.org/wiki/HSV_color_space. - * Assumes h, s, and v are contained in the set [0, 1] and - * returns r, g, and b in the set [0, 1]. - * - * @param h The hue - * @param s The saturation - * @param v The value - * @return The RGB representation - */ - function hsvToRgb(h: number, s: number, v: number): [number, number, number]; +/** + * Converts an HSV color value to RGB. Conversion formula + * adapted from http://en.wikipedia.org/wiki/HSV_color_space. + * Assumes h, s, and v are contained in the set [0, 1] and + * returns r, g, and b in the set [0, 1]. + * + * @param h The hue + * @param s The saturation + * @param v The value + * @return The RGB representation + */ +export function hsvToRgb(h: number, s: number, v: number): [number, number, number]; - /** - * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. - * @param rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. - * @return Number in hexadecimal. - */ - function rgbToHex(rgb: [number, number, number]): number; +/** + * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. + * @param rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. + * @return Number in hexadecimal. + */ +export function rgbToHex(rgb: [number, number, number]): number; - /** - * Convert a hex color code to an RGB array - * @param hex A hex color number - * @return An array of [r,g,b] colors normalized on the range of [0,1] - */ - function hexToRGB(hex: number): [number, number, number]; +/** + * Convert a hex color code to an RGB array + * @param hex A hex color number + * @return An array of [r,g,b] colors normalized on the range of [0,1] + */ +export function hexToRGB(hex: number): [number, number, number]; - /** - * Convert a hex color code to an RGBA color string which can be used for CSS styling - * @param hex A hex color number - * @param alpha A level of transparency - * @return An rgba style string - */ - function hexToRGBAString(hex: number, alpha?: number): string; +/** + * Convert a hex color code to an RGBA color string which can be used for CSS styling + * @param hex A hex color number + * @param alpha A level of transparency + * @return An rgba style string + */ +export function hexToRGBAString(hex: number, alpha?: number): string; - /** - * Convert a string color to a hex integer - * @param color The string color - * @return The hexidecimal color code - */ - function colorStringToHex(color: string): number; +/** + * Convert a string color to a hex integer + * @param color The string color + * @return The hexidecimal color code + */ +export function colorStringToHex(color: string): number; - /** - * Return whether or not a version (v1) is more advanced than some other version (v0) - * Supports numeric or string version numbers - * @param v0 - * @param v1 - * @return - */ - function isNewerVersion(v1: number | string | null, v0: number | string): boolean; +/** + * Return whether or not a version (v1) is more advanced than some other version (v0) + * Supports numeric or string version numbers + * @param v0 + * @param v1 + * @return + */ +export function isNewerVersion(v1: number | string | null, v0: number | string): boolean; - /** - * Generate a random ID - * Generate random number and convert it to base 36 and remove the '0.' at the beginning - * As long as the string is not long enough, generate more random data into it - * Use substring in case we generated a string with a length higher than the requested length - * - * @param length The length of the random ID to generate - * @return Return a string containing random letters and numbers - */ - function randomID(length?: number): string; +/** + * Generate a random ID + * Generate random number and convert it to base 36 and remove the '0.' at the beginning + * As long as the string is not long enough, generate more random data into it + * Use substring in case we generated a string with a length higher than the requested length + * + * @param length The length of the random ID to generate + * @return Return a string containing random letters and numbers + */ +export function randomID(length?: number): string; - /** - * Log a compatibility warning which is filtered based on the client's defined compatibility settings. - * @param message The original warning or error message - * @param [options={}] Additional options which customize logging - * @param [options.mode] A logging level in COMPATIBILITY_MODES which overrides the configured default - * @param [options.since] A version identifier since which a change was made - * @param [options.until] A version identifier until which a change remains supported - * @param [options.details] Additional details to append to the logged message - * @param [options.stack=true] Include the message stack trace - * @throws An Error if the mode is ERROR - */ - function logCompatibilityWarning( - message: string, - options?: { - mode?: CompatibilityMode; - since?: number | string; - until?: number | string; - details?: string; - stack?: boolean; - } - ): void; - } +/** + * Log a compatibility warning which is filtered based on the client's defined compatibility settings. + * @param message The original warning or error message + * @param [options={}] Additional options which customize logging + * @param [options.mode] A logging level in COMPATIBILITY_MODES which overrides the configured default + * @param [options.since] A version identifier since which a change was made + * @param [options.until] A version identifier until which a change remains supported + * @param [options.details] Additional details to append to the logged message + * @param [options.stack=true] Include the message stack trace + * @throws An Error if the mode is ERROR + */ +export function logCompatibilityWarning( + message: string, + options?: { + mode?: CompatibilityMode; + since?: number | string; + until?: number | string; + details?: string; + stack?: boolean; } +): void; +declare global { interface MergeObjectOptions { insertKeys?: boolean; insertValues?: boolean; diff --git a/types/foundry/common/utils/index.d.ts b/types/foundry/common/utils/index.d.ts deleted file mode 100644 index dc8ef1efc91..00000000000 --- a/types/foundry/common/utils/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import "./collection.js"; -import "./color.js"; -import "./geometry.js"; -import "./helpers.js"; -import "./primitives.js"; diff --git a/types/foundry/common/utils/module.d.ts b/types/foundry/common/utils/module.d.ts new file mode 100644 index 00000000000..fff51c40831 --- /dev/null +++ b/types/foundry/common/utils/module.d.ts @@ -0,0 +1,6 @@ +import "./collection.d.ts"; +export * from "./geometry.ts"; +export * from "./helpers.ts"; +// export * from "./http.mjs"; +// export * from "./logging.mjs"; +export { default as Color } from "./color.ts"; diff --git a/types/foundry/index.d.ts b/types/foundry/index.d.ts index 131310cb2bd..5e91fd41603 100644 --- a/types/foundry/index.d.ts +++ b/types/foundry/index.d.ts @@ -1,73 +1,65 @@ -import "./client/application/base.js"; -import "./client/application/chat-popout.js"; -import "./client/application/compendium.js"; -import "./client/application/form-application/index.js"; -import "./client/application/hotbar.js"; -import "./client/application/hud/chat-bubbles.js"; -import "./client/application/hud/container.js"; -import "./client/application/hud/controls.js"; -import "./client/application/hud/hud.js"; -import "./client/application/hud/menu.js"; -import "./client/application/hud/navigation.js"; -import "./client/application/hud/pause.js"; -import "./client/application/hud/players.js"; -import "./client/application/i18n.js"; -import "./client/application/placeables/placeables-hud.js"; -import "./client/application/sidebar/sidebar.js"; -import "./client/application/sidebar/sidebar-tab/base.js"; -import "./client/application/sidebar/sidebar-tab/chat-log.js"; -import "./client/application/sidebar/sidebar-tab/combat-tracker.js"; -import "./client/application/sidebar/sidebar-tab/compendium-directory.js"; -import "./client/application/sidebar/sidebar-tab/settings.js"; -import "./client/application/sidebar/sidebar-tab/sidebar-directory/actor-directory.js"; -import "./client/application/sidebar/sidebar-tab/sidebar-directory/base.js"; -import "./client/application/sidebar/sidebar-tab/sidebar-directory/item-directory.js"; -import "./client/application/sidebar/sidebar-tab/sidebar-directory/roll-table-directory.js"; -import "./client/application/templates.js"; -import "./client/apps/forms/fonts.js"; -import "./client/apps/sidebar/index.js"; -import "./client/collections/compendium-collection.js"; -import "./client/collections/document-collection.js"; -import "./client/collections/world-collection/actors.js"; -import "./client/collections/world-collection/base.js"; -import "./client/collections/world-collection/combat-encounters.js"; -import "./client/collections/world-collection/folders.js"; -import "./client/collections/world-collection/items.js"; -import "./client/collections/world-collection/journal.js"; -import "./client/collections/world-collection/macros.js"; -import "./client/collections/world-collection/messages.js"; -import "./client/collections/world-collection/playlists.js"; -import "./client/collections/world-collection/roll-tables.js"; -import "./client/collections/world-collection/scenes.js"; -import "./client/collections/world-collection/users.js"; -import "./client/config.js"; -import "./client/core/index.js"; -import "./client/documents/index.js"; -import "./client/game.js"; -import "./client/keyboard/index.js"; -import "./client/misc.js"; -import "./client/pixi/index.js"; -import "./client/pixi/canvas.js"; -import "./client/pixi/canvas-layer/base.js"; -import "./client/pixi/canvas-layer/controls-layer.js"; -import "./client/pixi/canvas-layer/grid-layer.js"; -import "./client/pixi/grid/index.js"; -import "./client/pixi/helpers/index.js"; -import "./client/pixi/helpers/point-source/index.js"; -import "./client/pixi/mouse-interaction-manager.js"; -import "./client/pixi/placeable-object/index.js"; -import "./client/pixi/placeables-layer/index.js"; -import "./client/pixi/special-effect/index.js"; -import "./client/roll.js"; -import "./client/roll-term/index.js"; -import "./client/ui/index.js"; -import "./common/index.js"; -import "./common/abstract/index.js"; -import "./common/constants.js"; -import "./common/data/index.js"; -import "./common/data/data/index.js"; -import "./common/data/validators"; -import "./common/documents/index.js"; -import "./common/types.js"; -import "./common/utils/index.js"; -import "./util.js"; +import "./client/application/base.d.ts"; +import "./client/application/chat-popout.d.ts"; +import "./client/application/compendium.d.ts"; +import "./client/application/form-application/index.d.ts"; +import "./client/application/hotbar.d.ts"; +import "./client/application/hud/chat-bubbles.d.ts"; +import "./client/application/hud/container.d.ts"; +import "./client/application/hud/controls.d.ts"; +import "./client/application/hud/hud.d.ts"; +import "./client/application/hud/menu.d.ts"; +import "./client/application/hud/navigation.d.ts"; +import "./client/application/hud/pause.d.ts"; +import "./client/application/hud/players.d.ts"; +import "./client/application/i18n.d.ts"; +import "./client/application/placeables/placeables-hud.d.ts"; +import "./client/application/sidebar/sidebar.d.ts"; +import "./client/application/sidebar/sidebar-tab/base.d.ts"; +import "./client/application/sidebar/sidebar-tab/chat-log.d.ts"; +import "./client/application/sidebar/sidebar-tab/combat-tracker.d.ts"; +import "./client/application/sidebar/sidebar-tab/compendium-directory.d.ts"; +import "./client/application/sidebar/sidebar-tab/settings.d.ts"; +import "./client/application/sidebar/sidebar-tab/sidebar-directory/actor-directory.d.ts"; +import "./client/application/sidebar/sidebar-tab/sidebar-directory/base.d.ts"; +import "./client/application/sidebar/sidebar-tab/sidebar-directory/item-directory.d.ts"; +import "./client/application/sidebar/sidebar-tab/sidebar-directory/roll-table-directory.d.ts"; +import "./client/application/templates.d.ts"; +import "./client/apps/forms/fonts.d.ts"; +import "./client/apps/sidebar/index.d.ts"; +import "./client/collections/compendium-collection.d.ts"; +import "./client/collections/document-collection.d.ts"; +import "./client/collections/world-collection/actors.d.ts"; +import "./client/collections/world-collection/base.d.ts"; +import "./client/collections/world-collection/combat-encounters.d.ts"; +import "./client/collections/world-collection/folders.d.ts"; +import "./client/collections/world-collection/items.d.ts"; +import "./client/collections/world-collection/journal.d.ts"; +import "./client/collections/world-collection/macros.d.ts"; +import "./client/collections/world-collection/messages.d.ts"; +import "./client/collections/world-collection/playlists.d.ts"; +import "./client/collections/world-collection/roll-tables.d.ts"; +import "./client/collections/world-collection/scenes.d.ts"; +import "./client/collections/world-collection/users.d.ts"; +import "./client/config.d.ts"; +import "./client/core/index.d.ts"; +import "./client/documents/index.d.ts"; +import "./client/game.d.ts"; +import "./client/keyboard/index.d.ts"; +import "./client/misc.d.ts"; +import "./client/pixi/index.d.ts"; +import "./client/pixi/canvas.d.ts"; +import "./client/pixi/canvas-layer/base.d.ts"; +import "./client/pixi/canvas-layer/controls-layer.d.ts"; +import "./client/pixi/canvas-layer/grid-layer.d.ts"; +import "./client/pixi/grid/index.d.ts"; +import "./client/pixi/helpers/index.d.ts"; +import "./client/pixi/helpers/point-source/index.d.ts"; +import "./client/pixi/mouse-interaction-manager.d.ts"; +import "./client/pixi/placeable-object/index.d.ts"; +import "./client/pixi/placeables-layer/index.d.ts"; +import "./client/pixi/special-effect/index.d.ts"; +import "./client/roll.d.ts"; +import "./client/roll-term/index.d.ts"; +import "./client/ui/index.d.ts"; +import "./common/module.d.ts"; +import "./util.d.ts"; diff --git a/types/foundry/tsconfig.json b/types/foundry/tsconfig.json index ca6da400d81..baf49684560 100644 --- a/types/foundry/tsconfig.json +++ b/types/foundry/tsconfig.json @@ -10,7 +10,8 @@ "strict": true, "noImplicitOverride": true, "noEmit": true, - "esModuleInterop": true + "esModuleInterop": true, + "allowImportingTsExtensions": true }, "files": [ "index.d.ts", diff --git a/types/foundry/util.d.ts b/types/foundry/util.d.ts index 359ab821ce8..c7cc796b8c1 100644 --- a/types/foundry/util.d.ts +++ b/types/foundry/util.d.ts @@ -1,5 +1,5 @@ -import { DataModel } from "./common/abstract/data.mjs"; -import { DataSchema } from "./common/data/fields.js"; +import type DataModel from "./common/abstract/data.d.ts"; +import type { DataSchema } from "./common/data/fields.d.ts"; declare global { interface ElementDragEvent extends DragEvent { @@ -14,7 +14,7 @@ declare global { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P]; }; - type CollectionValue = T extends foundry.utils.Collection ? U : never; + type CollectionValue = T extends Collection ? U : never; // eslint-disable-next-line @typescript-eslint/no-explicit-any type AbstractConstructorOf = abstract new (...args: any[]) => T;