All user data for FoundryVTT. Includes worlds, systems, modules, and any asset in the "foundryuserdata" directory. Does NOT include the FoundryVTT installation itself.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

748 lines
38 KiB

1 year ago
1 year ago
1 year ago
1 year ago
  1. # 1. FVTT libWrapper
  2. Library for [Foundry VTT](https://foundryvtt.com/) which provides package developers with a simple way to modify core Foundry VTT code, while reducing the likelihood of conflict with other packages and making troubleshooting easier.
  3. [![License](https://img.shields.io/github/license/ruipin/fvtt-lib-wrapper)](LICENSE)
  4. [![Build Release](https://github.com/ruipin/fvtt-lib-wrapper/workflows/Build%20Release/badge.svg)](https://github.com/ruipin/fvtt-lib-wrapper/releases/latest)
  5. [![Version (latest)](https://img.shields.io/github/v/release/ruipin/fvtt-lib-wrapper)](https://github.com/ruipin/fvtt-lib-wrapper/releases/latest)
  6. [![Foundry Version](https://img.shields.io/badge/dynamic/json.svg?url=https://github.com/ruipin/fvtt-lib-wrapper/releases/latest/download/module.json&label=Foundry%20Version&query=$.compatibleCoreVersion&colorB=blueviolet)](https://github.com/ruipin/fvtt-lib-wrapper/releases/latest)
  7. [![GitHub downloads (latest)](https://img.shields.io/badge/dynamic/json?label=Downloads@latest&query=assets[?(@.name.includes('zip'))].download_count&url=https://api.github.com/repos/ruipin/fvtt-lib-wrapper/releases/latest&color=green)](https://github.com/ruipin/fvtt-lib-wrapper/releases/latest)
  8. [![Forge Install Base](https://img.shields.io/badge/dynamic/json?label=Forge%20Install%20Base&query=package.installs&suffix=%&url=https://forge-vtt.com/api/bazaar/package/lib-wrapper&colorB=brightgreen)](https://forge-vtt.com/)
  9. [![GitHub issues](https://img.shields.io/github/issues-raw/ruipin/fvtt-lib-wrapper)](https://github.com/ruipin/fvtt-lib-wrapper/issues)
  10. [![Ko-fi](https://img.shields.io/badge/-buy%20me%20a%20coffee-%23FF5E5B?logo=Ko-fi&logoColor=white)](https://ko-fi.com/ruipin)
  11. - [1. FVTT libWrapper](#1-fvtt-libwrapper)
  12. - [1.1. Why?](#11-why)
  13. - [1.2. Installation](#12-installation)
  14. - [1.2.1. As a Module](#121-as-a-module)
  15. - [1.2.2. As a Library](#122-as-a-library)
  16. - [1.2.3. As a Contributor](#123-as-a-contributor)
  17. - [1.3. Usage](#13-usage)
  18. - [1.3.1. Summary](#131-summary)
  19. - [1.3.2. Common Issues and Pitfalls](#132-common-issues-and-pitfalls)
  20. - [1.3.2.1. Not allowed to register wrappers before the `init` hook.](#1321-not-allowed-to-register-wrappers-before-the-init-hook)
  21. - [1.3.2.2. OVERRIDE wrappers have a different call signature](#1322-override-wrappers-have-a-different-call-signature)
  22. - [1.3.2.3. Arrow Functions do not support `this`](#1323-arrow-functions-do-not-support-this)
  23. - [1.3.2.4. Using `super` inside wrappers](#1324-using-super-inside-wrappers)
  24. - [1.3.2.5. Patching Mixins](#1325-patching-mixins)
  25. - [1.3.3. LibWrapper API](#133-libwrapper-api)
  26. - [1.3.3.1. Registering a wrapper](#1331-registering-a-wrapper)
  27. - [1.3.3.2. Unregistering a wrapper](#1332-unregistering-a-wrapper)
  28. - [1.3.3.3. Unregister all wrappers for a given package](#1333-unregister-all-wrappers-for-a-given-package)
  29. - [1.3.3.4. Ignore conflicts matching specific filters](#1334-ignore-conflicts-matching-specific-filters)
  30. - [1.3.3.5. Library Versioning](#1335-library-versioning)
  31. - [1.3.3.5.1. Testing for a specific libWrapper version](#13351-testing-for-a-specific-libwrapper-version)
  32. - [1.3.3.6. Fallback / Polyfill detection](#1336-fallback--polyfill-detection)
  33. - [1.3.3.7. Exceptions](#1337-exceptions)
  34. - [1.3.3.8. Hooks](#1338-hooks)
  35. - [1.3.3.9. Enumerations](#1339-enumerations)
  36. - [1.3.3.10. Examples](#13310-examples)
  37. - [1.3.4. Using libWrapper inside a System](#134-using-libwrapper-inside-a-system)
  38. - [1.3.5. Compatibility Shim](#135-compatibility-shim)
  39. - [1.4. Support](#14-support)
  40. - [1.4.1. Module-specific Support](#141-module-specific-support)
  41. - [1.4.2. Community Support](#142-community-support)
  42. - [1.4.3. LibWrapper Support](#143-libwrapper-support)
  43. ## 1.1. Why?
  44. The libWrapper library is intended to be used as a replacement for traditional monkey-patching methods, to make interoperability and troubleshooting easier.
  45. It provides a standardized API, improving consistency and compatibility while reducing the likelihood of mistakes.
  46. Its wrapping mechanisms attempt to detect and prevent conflicts between different packages. When conflicts cannot be prevented, libWrapper aids troubleshooting by notifying the game master of what went wrong, and which packages are responsible.
  47. | | Traditional monkey-patching | libWrapper |
  48. |-|-|-|
  49. | Conflict troubleshooting | Requires waiting until something goes wrong.<br>User is responsible for figuring out if an error is caused by a conflict, and which package(s) caused it. | Able to detect most conflicts and warn the user, in many cases automatically upon game launch. |
  50. | Error Detection | None by default. | When any error occurs, libWrapper will detect which package(s) caused it (if any), and tell the user. |
  51. | API | None.<br>Each developer is on their own. | Provides a standard API enforcing best-practices with included error-checking. |
  52. | Wrapper execution order | Package execution order, i.e. random. | Customizable.<br>Developers can request to run first or last, if their module requires it.<br>Game masters can troubleshoot conflicts by prioritising or deprioritising packages. |
  53. | Edge cases | Each developer must understand the intricacies of Javascript. | Handled automatically and transparently. |
  54. <img src="https://raw.githubusercontent.com/ruipin/fvtt-lib-wrapper/7cb19d4def1d5ebf84f4df5753f8e48ecfc1523c/example_priorities.png" width="200">
  55. <img src="https://raw.githubusercontent.com/ruipin/fvtt-lib-wrapper/7cb19d4def1d5ebf84f4df5753f8e48ecfc1523c/example_conflicts.png" width="200">
  56. <img src="https://raw.githubusercontent.com/ruipin/fvtt-lib-wrapper/7cb19d4def1d5ebf84f4df5753f8e48ecfc1523c/example_active_wrappers.png" width="200">
  57. <sup>Note: Images may be out-of-date.</sup>
  58. ## 1.2. Installation
  59. ### 1.2.1. As a Module
  60. 1. Copy this link and use it in Foundry's Module Manager to install the Module
  61. > https://github.com/ruipin/fvtt-lib-wrapper/releases/latest/download/module.json
  62. 2. Enable the Module in your World's Module Settings
  63. ### 1.2.2. As a Library
  64. You have multiple options here.
  65. 1. Include the provided [shim](#135-compatibility-shim) in your project.
  66. or
  67. 2. Write your own shim. **Please do not make your custom shim available in the global scope.**
  68. or
  69. 3. Trigger a different code path depending on whether libWrapper is installed and active or not. For example:
  70. ```javascript
  71. if(typeof libWrapper === 'function') {
  72. /* libWrapper is available in global scope and can be used */
  73. }
  74. else {
  75. /* libWrapper is not available in global scope and can't be used */
  76. }
  77. ```
  78. or
  79. 4. Require your users to install this library. One simple example that achieves this is provided below. Reference the more complex example in the provided [shim](#135-compatibility-shim) if you prefer a dialog (including an option to dismiss it permanently) instead of a simple notification.
  80. ```javascript
  81. Hooks.once('ready', () => {
  82. if(!game.modules.get('lib-wrapper')?.active && game.user.isGM)
  83. ui.notifications.error("Module XYZ requires the 'libWrapper' module. Please install and activate it.");
  84. });
  85. ```
  86. Note that if you choose this option, i.e. require the user to install this library, you should make sure to list libWrapper as a dependency. This can be done by adding one of the following entries to your package's manifest:
  87. 1. Foundry VTT v10 and newer:
  88. ```javascript
  89. "relationships": {
  90. "requires": [
  91. {
  92. "id": "lib-wrapper",
  93. "type": "module",
  94. "compatibility": {
  95. "minimum": "1.0.0.0",
  96. "verified": "1.12.6.0"
  97. }
  98. }
  99. ]
  100. }
  101. ```
  102. The `"compatibility"` section and all fields within it are optional, and serve to declare the versions of the dependency which your package requires. This can be useful if you rely on libWrapper features added by newer versions (by using `"minimum"`), as well as to communicate to the user what version of the library you tested against (by using `"verified"`).
  103. 2. Foundry VTT v9 and older (forward-compatible with v10):
  104. ```javascript
  105. "dependencies": [
  106. {
  107. "name": "lib-wrapper",
  108. "type": "module"
  109. }
  110. ]
  111. ```
  112. If you pick options #2 or #3 and actively recommend to the user to install libWrapper using e.g. a notification, it is a good idea to give the user a way to permanently dismiss said notification. The provided [shim](#135-compatibility-shim) does this by having a "Don't remind me again" option in the alert dialog.
  113. Once your package is released, you should consider adding it to the wiki list of [Modules using libWrapper](https://github.com/ruipin/fvtt-lib-wrapper/wiki/Modules-using-libWrapper). This list can also be used as an additional (unofficial) source of libWrapper usage examples.
  114. ### 1.2.3. As a Contributor
  115. See [CONTRIBUTING.md](CONTRIBUTING.md).
  116. ## 1.3. Usage
  117. ### 1.3.1. Summary
  118. In order to wrap a method, you should call the `libWrapper.register` method during or after the `init` hook, and provide it with your package ID, the scope of the method you want to override, and a wrapper function.
  119. You can also specify the type of wrapper you want in the fourth (optional) parameter:
  120. - `WRAPPER`:
  121. - Use if your wrapper will *always* continue the chain (i.e. call `wrapped`).
  122. - This type has priority over every other type. It should be used whenever possible as it massively reduces the likelihood of conflicts.
  123. - ⚠ If you use this type but do not call the original function, your wrapper will be automatically unregistered.
  124. - `MIXED` (default):
  125. - Your wrapper will be allowed to decide whether it should continue the chain (i.e. call `wrapped`) or not.
  126. - These will always come after `WRAPPER`-type wrappers. Order is not guaranteed, but conflicts will be auto-detected.
  127. - `OVERRIDE`:
  128. - Use if your wrapper will *never* continue the chain (i.e. call `wrapped`). This type has the lowest priority, and will always be called last.
  129. - If another package already has an `OVERRIDE` wrapper registered to the same method:
  130. - If the GM has explicitly given your package priority over the existing one, libWrapper will trigger a `libWrapper.OverrideLost` hook, and your wrapper will take over.
  131. - Otherwise, libWrapper will throw a `libWrapper.AlreadyOverriddenError` exception. This exception can be caught by your package in order to fail gracefully and activate fallback code.
  132. If using `WRAPPER` or `MIXED`, the first parameter passed to your wrapper will be the next wrapper in the wrapper chain, which you can use to continue the call.
  133. ```javascript
  134. libWrapper.register('my-fvtt-package', 'Foo.prototype.bar', function (wrapped, ...args) {
  135. console.log('Foo.prototype.bar was called');
  136. // ... do things ...
  137. let result = wrapped(...args);
  138. // ... do things ...
  139. return result;
  140. }, 'MIXED' /* optional, since this is the default type */ );
  141. ```
  142. ### 1.3.2. Common Issues and Pitfalls
  143. #### 1.3.2.1. Not allowed to register wrappers before the `init` hook.
  144. Due to Foundry limitations, information related to installed packages is not available until the FVTT `init` hook. As such, libWrapper will wait until then to initialize itself.
  145. Any attempts to register wrappers before then will throw an exception. If using the [shim](#135-compatibility-shim), its `libWrapper` symbol will be undefined until then.
  146. ⚠ Note that while the full library provides the `libWrapper.Ready` hook, which fires as soon as libWrapper is ready to register wrappers, this hook is not provided by the [shim](#135-compatibility-shim).
  147. #### 1.3.2.2. OVERRIDE wrappers have a different call signature
  148. When using `OVERRIDE`, wrappers do not receive the next function in the wrapper chain as the first parameter. Make sure to account for this.
  149. ```javascript
  150. libWrapper.register('my-fvtt-package', 'Foo.prototype.bar', function (...args) { // There is no 'wrapped' parameter in the wrapper signature
  151. console.log('Foo.prototype.bar was overridden');
  152. return;
  153. }, 'OVERRIDE');
  154. ```
  155. #### 1.3.2.3. Arrow Functions do not support `this`
  156. Per the Javascript specification, arrow function syntax (`(args) => { body() }`) does not bind a `this` object, and instead keeps whatever `this` was defined in the declaration scope.
  157. As such, if you use arrow functions to define your wrapper, you will be unable to use the wrapper's `this`:
  158. ```javascript
  159. libWrapper.register('my-fvtt-package', 'Foo.prototype.bar', (wrapped, ...args) => {
  160. console.log(this); // -> 'Window'
  161. }, 'MIXED' /* optional, since this is the default type */ );
  162. ```
  163. If you want access to the `this` object of the wrapped method, you must use the `function(args) { body() }` syntax:
  164. ```javascript
  165. libWrapper.register('my-fvtt-package', 'Foo.prototype.bar', function (wrapped, ...args) {
  166. console.log(this); // -> 'Foo'
  167. }, 'MIXED' /* optional, since this is the default type */ );
  168. ```
  169. #### 1.3.2.4. Using `super` inside wrappers
  170. Sometimes, it is desired to call a superclass method directly. Traditionally, `super` would be the right tool to do this. However, due to the specifics of how `super` works in Javascript it cannot be used outside of the class definition, and therefore does not work inside wrappers.
  171. As a result, to call a superclass method directly you will need to manually find the superclass method definition yourself. This can be done multiple ways, and two examples are provided below.
  172. The examples below assume `this` is of class `ChildClass`, that the superclass has the name `SuperClass`, and that the method we wish to call is `superclass_method`.
  173. 1. Travel the class hierarchy automatically, using `Object.getPrototypeOf`:
  174. ```javascript
  175. Object.getPrototypeOf(ChildClass).prototype.superclass_method.apply(this, args);
  176. ```
  177. 2. Hardcode the class we wish to call:
  178. ```javascript
  179. SuperClass.prototype.superclass_method.apply(this, args);
  180. ```
  181. The first option should be preferred, as it will work even if the superclass name (`SuperClass` in this example) changes in a future Foundry update.
  182. #### 1.3.2.5. Patching Mixins
  183. Since FoundryVTT 0.8.x, the core Foundry code makes heavy use of mixins. Since mixins are essentially a function that returns a class, patching the mixin directly is not possible.
  184. Instead, you should patch these methods on the classes that inherit from the mixins.
  185. For example, in the Foundry code we have the following (with irrelevant code stripped):
  186. ```javascript
  187. const CanvasDocumentMixin = Base => class extends ClientDocumentMixin(Base) {
  188. /* ... */
  189. _onCreate(data, options, userId) {
  190. /* ... */
  191. }
  192. /* ... */
  193. }
  194. /* ... */
  195. class TileDocument extends CanvasDocumentMixin(foundry.documents.BaseTile) {
  196. /* ... */
  197. }
  198. ```
  199. If we wanted to patch the method `_onCreate` which `TileDocument` inherits from `CanvasDocumentMixin(foundry.documents.BaseTile)`, we could do the following:
  200. ```javascript
  201. libWrapper.register('my-fvtt-package', 'TileDocument.prototype._onCreate', function(wrapped, ...args) {
  202. console.log("TileDocument.prototype._onCreate called");
  203. return wrapped(...args);
  204. }, 'WRAPPER');
  205. ```
  206. ### 1.3.3. LibWrapper API
  207. ⚠ Anything not documented in this section is not officially supported, and could change or break at any moment without notice.
  208. #### 1.3.3.1. Registering a wrapper
  209. To register a wrapper function, you should call the method `libWrapper.register(package_id, target, fn, type)`:
  210. ```javascript
  211. /**
  212. * Register a new wrapper.
  213. * Important: If called before the 'init' hook, this method will fail.
  214. *
  215. * In addition to wrapping class methods, there is also support for wrapping methods on specific object instances, as well as class methods inherited from parent classes.
  216. * However, it is recommended to wrap methods directly in the class that defines them whenever possible, as inheritance/instance wrapping is less thoroughly tested and will incur a performance penalty.
  217. *
  218. * Triggers FVTT hook 'libWrapper.Register' when successful.
  219. *
  220. * Returns a unique numeric target identifier, which can be used as a replacement for 'target' in future calls to 'libWrapper.register' and 'libWrapper.unregister'.
  221. *
  222. * @param {string} package_id The package identifier, i.e. the 'id' field in your module/system/world's manifest.
  223. *
  224. * @param {number|string} target The target identifier, specifying which wrapper should be registered.
  225. *
  226. * This can be either:
  227. * 1. A unique target identifier obtained from a previous 'libWrapper.register' call.
  228. * 2. A string containing the path to the function you wish to add the wrapper to, starting at global scope, for example 'SightLayer.prototype.updateToken'.
  229. *
  230. * Support for the unique target identifiers (option #1) was added in v1.11.0.0, with previous versions only supporting option #2.
  231. *
  232. * Since v1.8.0.0, the string path (option #2) can contain string array indexing.
  233. * For example, 'CONFIG.Actor.sheetClasses.character["dnd5e.ActorSheet5eCharacter"].cls.prototype._onLongRest' is a valid path.
  234. * It is important to note that indexing in libWrapper does not work exactly like in JavaScript:
  235. * - The index must be a single string, quoted using the ' or " characters. It does not support e.g. numbers or objects.
  236. * - A backslash \ can be used to escape another character so that it loses its special meaning, e.g. quotes i.e. ' and " as well as the character \ itself.
  237. *
  238. * By default, libWrapper searches for normal methods or property getters only. To wrap a property's setter, append '#set' to the name, for example 'SightLayer.prototype.blurDistance#set'.
  239. *
  240. * @param {function} fn Wrapper function. The first argument will be the next function in the chain, except for 'OVERRIDE' wrappers.
  241. * The remaining arguments will correspond to the parameters passed to the wrapped method.
  242. *
  243. * @param {string} type [Optional] The type of the wrapper. Default is 'MIXED'.
  244. *
  245. * The possible types are:
  246. *
  247. * 'WRAPPER' / libWrapper.WRAPPER:
  248. * Use if your wrapper will *always* continue the chain.
  249. * This type has priority over every other type. It should be used whenever possible as it massively reduces the likelihood of conflicts.
  250. * Note that the library will auto-detect if you use this type but do not call the original function, and automatically unregister your wrapper.
  251. *
  252. * 'MIXED' / libWrapper.MIXED:
  253. * Default type. Your wrapper will be allowed to decide whether it continue the chain or not.
  254. * These will always come after 'WRAPPER'-type wrappers. Order is not guaranteed, but conflicts will be auto-detected.
  255. *
  256. * 'OVERRIDE' / libWrapper.OVERRIDE:
  257. * Use if your wrapper will *never* continue the chain. This type has the lowest priority, and will always be called last.
  258. * If another package already has an 'OVERRIDE' wrapper registered to the same method, using this type will throw a <libWrapper.ERRORS.package> exception.
  259. * Catching this exception should allow you to fail gracefully, and for example warn the user of the conflict.
  260. * Note that if the GM has explicitly given your package priority over the existing one, no exception will be thrown and your wrapper will take over.
  261. *
  262. * @param {Object} options [Optional] Additional options to libWrapper.
  263. *
  264. * @param {boolean} options.chain [Optional] If 'true', the first parameter to 'fn' will be a function object that can be called to continue the chain.
  265. * This parameter must be 'true' when registering non-OVERRIDE wrappers.
  266. * Default is 'false' if type=='OVERRIDE', otherwise 'true'.
  267. * First introduced in v1.3.6.0.
  268. *
  269. * @param {string} options.perf_mode [Optional] Selects the preferred performance mode for this wrapper. Default is 'AUTO'.
  270. * It will be used if all other wrappers registered on the same target also prefer the same mode, otherwise the default will be used instead.
  271. * This option should only be specified with good reason. In most cases, using 'AUTO' in order to allow the GM to choose is the best option.
  272. * First introduced in v1.5.0.0.
  273. *
  274. * The possible modes are:
  275. *
  276. * 'NORMAL' / libWrapper.PERF_NORMAL:
  277. * Enables all conflict detection capabilities provided by libWrapper. Slower than 'FAST'.
  278. * Useful if wrapping a method commonly modified by other packages, to ensure most issues are detected.
  279. * In most other cases, this mode is not recommended and 'AUTO' should be used instead.
  280. *
  281. * 'FAST' / libWrapper.PERF_FAST:
  282. * Disables some conflict detection capabilities provided by libWrapper, in exchange for performance. Faster than 'NORMAL'.
  283. * Will guarantee wrapper call order and per-package prioritization, but fewer conflicts will be detectable.
  284. * This performance mode will result in comparable performance to traditional non-libWrapper wrapping methods.
  285. * Useful if wrapping a method called repeatedly in a tight loop, for example 'WallsLayer.testWall'.
  286. * In most other cases, this mode is not recommended and 'AUTO' should be used instead.
  287. *
  288. * 'AUTO' / libWrapper.PERF_AUTO:
  289. * Default performance mode. If unsure, choose this mode.
  290. * Will allow the GM to choose which performance mode to use.
  291. * Equivalent to 'FAST' when the libWrapper 'High-Performance Mode' setting is enabled by the GM, otherwise 'NORMAL'.
  292. *
  293. * @param {any[]} options.bind [Optional] An array of parameters that should be passed to 'fn'.
  294. *
  295. * This allows avoiding an extra function call, for instance:
  296. * libWrapper.register(PACKAGE_ID, "foo", function(wrapped, ...args) { return someFunction.call(this, wrapped, "foo", "bar", ...args) });
  297. * becomes
  298. * libWrapper.register(PACKAGE_ID, "foo", someFunction, "WRAPPER", {bind: ["foo", "bar"]});
  299. *
  300. * First introduced in v1.12.0.0.
  301. *
  302. * @returns {number} Unique numeric 'target' identifier which can be used in future 'libWrapper.register' and 'libWrapper.unregister' calls.
  303. * Added in v1.11.0.0.
  304. */
  305. static register(package_id, target, fn, type='MIXED', options={}) { /* ... */ }
  306. ```
  307. See the usage example above.
  308. #### 1.3.3.2. Unregistering a wrapper
  309. To unregister a wrapper function, you should call the method `libWrapper.unregister(package_id, target)`.
  310. ```javascript
  311. /**
  312. * Unregister an existing wrapper.
  313. *
  314. * Triggers FVTT hook 'libWrapper.Unregister' when successful.
  315. *
  316. * @param {string} package_id The package identifier, i.e. the 'id' field in your module/system/world's manifest.
  317. *
  318. * @param {number|string} target The target identifier, specifying which wrapper should be unregistered.
  319. *
  320. * This can be either:
  321. * 1. A unique target identifier obtained from a previous 'libWrapper.register' call. This is the recommended option.
  322. * 2. A string containing the path to the function you wish to remove the wrapper from, starting at global scope, with the same syntax as the 'target' parameter to 'libWrapper.register'.
  323. *
  324. * It is recommended to use option #1 if possible, in order to guard against the case where the class or object at the given path is no longer the same as when `libWrapper.register' was called.
  325. *
  326. * Support for the unique target identifiers (option #1) was added in v1.11.0.0, with previous versions only supporting option #2.
  327. *
  328. * @param {function} fail [Optional] If true, this method will throw an exception if it fails to find the method to unwrap. Default is 'true'.
  329. */
  330. static unregister(package_id, target, fail=true) { /* ... */ }
  331. ```
  332. #### 1.3.3.3. Unregister all wrappers for a given package
  333. To clear all wrapper functions belonging to a given package, you should call the method `libWrapper.unregister_all(package_id)`.
  334. ```javascript
  335. /**
  336. * Unregister all wrappers created by a given package.
  337. *
  338. * Triggers FVTT hook 'libWrapper.UnregisterAll' when successful.
  339. *
  340. * @param {string} package_id The package identifier, i.e. the 'id' field in your module/system/world's manifest.
  341. */
  342. static unregister_all(package_id) { /* ... */ }
  343. ```
  344. #### 1.3.3.4. Ignore conflicts matching specific filters
  345. To ask libWrapper to ignore specific conflicts when detected, instead of warning the user, you should call the method `libWrapper.ignore_conflicts(package_id, ignore_ids, targets)`.
  346. ```javascript
  347. /**
  348. * Ignore conflicts matching specific filters when detected, instead of warning the user.
  349. *
  350. * This can be used when there are conflict warnings that are known not to cause any issues, but are unable to be resolved.
  351. * Conflicts will be ignored if they involve both 'package_id' and one of 'ignore_ids', and relate to one of 'targets'.
  352. *
  353. * Note that the user can still see which detected conflicts were ignored, by toggling "Show ignored conflicts" in the "Conflicts" tab in the libWrapper settings.
  354. *
  355. * First introduced in v1.7.0.0.
  356. *
  357. * @param {string} package_id The package identifier, i.e. the 'id' field in your module/system/world's manifest. This will be the package that owns this ignore entry.
  358. *
  359. * @param {(string|string[])} ignore_ids Other package ID(s) with which conflicts should be ignored.
  360. *
  361. * @param {(string|string[])} targets Target(s) for which conflicts should be ignored, corresponding to the 'target' parameter to 'libWrapper.register'.
  362. * This method does not accept the unique target identifiers returned by 'libWrapper.register'.
  363. *
  364. * @param {Object} options [Optional] Additional options to libWrapper.
  365. *
  366. * @param {boolean} options.ignore_errors [Optional] If 'true', will also ignore confirmed conflicts (i.e. errors), rather than only potential conflicts (i.e. warnings).
  367. * Be careful when setting this to 'true', as confirmed conflicts are almost certainly something the user should be made aware of.
  368. * Defaults to 'false'.
  369. */
  370. static ignore_conflicts(package_id, ignore_ids, targets, options={}) { /* ... */ }
  371. ```
  372. #### 1.3.3.5. Library Versioning
  373. This library follows [Semantic Versioning](https://semver.org/), with two custom fields `SUFFIX` and `META`. These are used to track manifest-only changes (e.g. when `compatibleCoreVersion` increases) and track release meta-data (e.g. release candidates and unstable versions) respectively. See below for examples.
  374. The version string will always have format `<MAJOR>.<MINOR>.<PATCH>.<SUFFIX><META>`.
  375. The `MAJOR`, `MINOR`, `PATCH` and `SUFFIX` fields will always be integers.
  376. The `META` field is always a string, although it will often be empty. The `-` character between `SUFFIX` and `META` is optional if `META` is empty or does not start with a digit.
  377. This last field `META` is unnecessary when comparing versions, as a change to this field will always cause one of the other fields to be incremented.
  378. A few (non-exhaustive) examples of valid version strings and the corresponding `[MAJOR, MINOR, PATCH, SUFFIX, META]`:
  379. | `libWrapper.version` | `libWrapper.versions` |
  380. | -------------------- | ------------------------- |
  381. | `1.2.3.4` | `[1, 2, 3, 4, '']` |
  382. | `1.3.4.0rc` | `[1, 3, 4, 0, 'rc']` |
  383. | `2.1.0.2a` | `[2, 1, 0, 2, 'a']` |
  384. | `3.4.5.6dev` | `[3, 4, 5, 6, 'dev']` |
  385. The `libWrapper` object provides a few properties and methods to query or react to the library version:
  386. ```javascript
  387. // Properties
  388. /**
  389. * Get libWrapper version
  390. * @returns {string} libWrapper version in string form, i.e. "<MAJOR>.<MINOR>.<PATCH>.<SUFFIX><META>"
  391. */
  392. static get version() { /* ... */ }
  393. /**
  394. * Get libWrapper version
  395. * @returns {[number,number,number,number,string]} libWrapper version in array form, i.e. [<MAJOR>, <MINOR>, <PATCH>, <SUFFIX>, <META>]
  396. */
  397. static get versions() { /* ... */ }
  398. /**
  399. * Get the Git version identifier.
  400. * @returns {string} Git version identifier, usually 'HEAD' or the commit hash.
  401. */
  402. static get git_version() { /* ... */ };
  403. // Methods
  404. /**
  405. * Test for a minimum libWrapper version.
  406. * First introduced in v1.4.0.0.
  407. *
  408. * @param {number} major Minimum major version
  409. * @param {number} minor [Optional] Minimum minor version. Default is 0.
  410. * @param {number} patch [Optional] Minimum patch version. Default is 0.
  411. * @param {number} suffix [Optional] Minimum suffix version. Default is 0. First introduced in v1.5.2.0.
  412. * @returns {boolean} Returns true if the libWrapper version is at least the queried version, otherwise false.
  413. */
  414. static version_at_least(major, minor=0, patch=0, suffix=0) { /* ... */ }
  415. ```
  416. ##### 1.3.3.5.1. Testing for a specific libWrapper version
  417. Sometimes you might wish to alert the user when an old version is detected, for example when you use functionality introduced in more recent versions.
  418. To test for libWrapper v1.4.0.0 or higher, the simplest way is to use `version_at_least`:
  419. ```javascript
  420. if(libWrapper.version_at_least?.(major, minor, patch, suffix)) {
  421. // libWrapper is at least major.minor.patch.suffix
  422. }
  423. else {
  424. // libWrapper is older than major.minor.patch.suffix
  425. }
  426. ```
  427. The arguments `minor`, `patch` and `suffix` are optional. Note the usage of `?.` to ensure this works (and is falsy) before v1.4.0.0.
  428. If you wish to detect versions below v1.4.0.0, you should use `versions` instead:
  429. ```javascript
  430. const [lwmajor, lwminor, lwpatch, lwsuffix] = libWrapper.versions;
  431. if(
  432. lwmajor > major || (lwmajor == major && (
  433. lwminor > minor || (lwminor == minor && (
  434. lwpatch > patch || (lwpatch == patch && lwsuffix >= suffix)
  435. ))
  436. ))
  437. ) {
  438. // libWrapper is at least major.minor.patch.suffix
  439. }
  440. else {
  441. // libWrapper is older than major.minor.patch.suffix
  442. }
  443. ```
  444. #### 1.3.3.6. Fallback / Polyfill detection
  445. To detect whether the `libWrapper` object contains the full library or a fallback/polyfill implementation (e.g. the [shim](#135-compatibility-shim)), you can check `libWrapper.is_fallback`.
  446. The library module will set this property to `false`, while fallback/polyfill implementations will set it to `true`.
  447. ```javascript
  448. /**
  449. * @returns {boolean} The real libWrapper module will always return false. Fallback implementations (e.g. poly-fill / shim) should return true.
  450. */
  451. static get is_fallback() { /* ... */ }
  452. ```
  453. #### 1.3.3.7. Exceptions
  454. Since v1.2.0.0, various custom exception classes are used by libWrapper, and available in the global `libWrapper` object.
  455. * `LibWrapperError`:
  456. - Base class for libWrapper exceptions.
  457. * `LibWrapperInternalError extends LibWrapperError`:
  458. - Internal LibWrapper error, usually indicating something is broken with the libWrapper library.
  459. - Public fields:
  460. - `package_id`: Package ID which triggered the error, if any.
  461. * `LibWrapperPackageError extends LibWrapperError`:
  462. - Error caused by a package external to libWrapper. These usually indicate conflicts, usage errors, or out-dated packages.
  463. - Public fields:
  464. - `package_id`: Package ID which triggered the error.
  465. * `LibWrapperAlreadyOverriddenError extends LibWrapperError`:
  466. - Thrown when a `libWrapper.register` call with `type='OVERRIDE'` fails because another `OVERRIDE` wrapper is already registered.
  467. - Public fields:
  468. - `package_id`: Package ID which failed to register the `OVERRIDE` wrapper.
  469. - `conflicting_id`: Package ID which already has a registered `OVERRIDE` wrapper.
  470. - `target`: Wrapper target (the `target` parameter to `libWrapper.register`).
  471. * `LibWrapperInvalidWrapperChainError extends LibWrapperError`:
  472. - Thrown when a wrapper tries to call the next method in the wrapper chain, but this call is invalid. This can occur, for example, if this call happens after the wrapper has already returned and all associated promises have resolved.
  473. - Public fields:
  474. - `package_id`: Package ID which triggered the error, if any.
  475. These are available both with and without the `LibWrapper` prefix, for example `libWrapper.Error` and `libWrapper.LibWrapperError` are equivalent and return the same exception class.
  476. #### 1.3.3.8. Hooks
  477. Since v1.4.0.0, the libWrapper library triggers Hooks for various events, listed below:
  478. * `libWrapper.Ready`:
  479. - Triggered when libWrapper is ready to register wrappers. This will happen shortly before the FVTT `init` hook.
  480. - No Parameters.
  481. * `libWrapper.Register`:
  482. - Triggered when a `libWrapper.register` call completes successfully.
  483. - Parameters:
  484. - `1`: Package ID whose wrapper is being registered (the `package_id` parameter to `libWrapper.register`).
  485. - `2`: Wrapper target path (the `target` parameter to `libWrapper.register` when it is a string, otherwise the first parameter provided by any module when registering a wrapper to the same method).
  486. - `3`: Wrapper type (the `type` parameter to `libWrapper.register`).
  487. - `4`: Options object (the `options` parameter to `libWrapper.register`).
  488. - `5`: Wrapper ID (the return value of `libWrapper.register`).
  489. * `libWrapper.Unregister`:
  490. - Triggered when a `libWrapper.unregister` call completes successfully.
  491. - Parameters:
  492. - `1`: Package ID whose wrapper is being unregistered (the `package_id` parameter to `libWrapper.unregister`).
  493. - `2`: Wrapper target (the `target` parameter to `libWrapper.unregister` when it is a string, otherwise the first parameter provided by any module when registering a wrapper to the same method).
  494. - `3`: Wrapper ID (the return value of `libWrapper.Register`).
  495. * `libWrapper.UnregisterAll`:
  496. - Triggered when a `libWrapper.unregister_all` call completes successfully.
  497. - Parameters:
  498. - `1`: Package ID whose wrappers are being unregistered (the `package_id` parameter to `libWrapper.unregister_all`).
  499. * `libWrapper.ConflictDetected`:
  500. - Triggered when a conflict is detected.
  501. - Parameters:
  502. - `1`: Package ID which triggered the conflict, or `«unknown»` if unknown.
  503. - `2`: Conflicting package ID.
  504. - `3`: Wrapper name (first `target` parameter provided by any module when registering a wrapper to the same method).
  505. - `4`: List of all unique `target` strings provided by modules when registering a wrapper to the same method.
  506. - If this hook returns `false`, the user will not be notified of this conflict.
  507. * `libWrapper.OverrideLost`:
  508. - Triggered when an `OVERRIDE` wrapper is replaced by a higher-priority wrapper.
  509. - Parameters:
  510. - `1`: Existing package ID whose wrapper is being unregistered.
  511. - `2`: New package ID whose wrapper is being registered.
  512. - `3`: Wrapper name (first `target` parameter provided by any module when registering a wrapper to the same method).
  513. - `4`: List of all unique `target` strings provided by modules when registering a wrapper to the same method.
  514. - If this hook returns `false`, this event will not be treated as a conflict.
  515. #### 1.3.3.9. Enumerations
  516. Since v1.9.0.0, libWrapper defines a couple of enumeration objects that can be passed to the libWrapper API methods, instead of using strings.
  517. For example, instead of using `'OVERRIDE'` in the `libWrapper.register` call, one could instead use `libWrapper.OVERRIDE`:
  518. ```javascript
  519. libWrapper.register('my-fvtt-package', 'Foo.prototype.bar', function (...args) {
  520. /* ... */
  521. }, libWrapper.OVERRIDE /* instead of 'OVERRIDE' */);
  522. ```
  523. A full list of the enumeration values provided by libWrapper follows:
  524. ```javascript
  525. static get WRAPPER() { /* ... */ };
  526. static get MIXED() { /* ... */ };
  527. static get OVERRIDE() { /* ... */ };
  528. static get PERF_NORMAL() { /* ... */ };
  529. static get PERF_AUTO() { /* ... */ };
  530. static get PERF_FAST() { /* ... */ };
  531. ```
  532. #### 1.3.3.10. Examples
  533. A list of packages using libWrapper, which can be used as further examples, can be found in the wiki page [Modules using libWrapper](https://github.com/ruipin/fvtt-lib-wrapper/wiki/Modules-using-libWrapper).
  534. ### 1.3.4. Using libWrapper inside a System
  535. The libWrapper library has official support for all types of packages, including systems.
  536. However, it is recommended that you read through the warnings and recommendations in [SYSTEMS.md](SYSTEMS.md) before you use it inside a system.
  537. ### 1.3.5. Compatibility Shim
  538. The [shim.js](shim/shim.js) file in this repository can be used to avoid a hard dependency on libWrapper.
  539. See the respective documentation in [shim/SHIM.md](shim/SHIM.md).
  540. ## 1.4. Support
  541. As with any piece of software, you might sometimes encounter issues with libWrapper that are not already answered above. This section covers what you can do to find support.
  542. ### 1.4.1. Module-specific Support
  543. When libWrapper notifies you of an error, it will usually let you know whether the issue is caused by a specific module or by libWrapper itself.
  544. Many modules have support channels set up by their developers. If libWrapper warns you about a specific module, and you are aware of such a support channel, you should use it.
  545. Most libWrapper errors are not caused by libWrapper itself, but instead by a module that uses it. Reporting these issues to the libWrapper team directly is a waste of time, as we will not be able to help. These issues will simply be closed as "invalid".
  546. ### 1.4.2. Community Support
  547. The easiest way to find support when there are no module-specific support channels is to ask the community.
  548. The largest community-provided support channels are:
  549. - [FoundryVTT Discord](https://discord.gg/foundryvtt)'s #modules-troubleshooting channel
  550. - [FoundryVTT Reddit](https://www.reddit.com/r/FoundryVTT)
  551. ### 1.4.3. LibWrapper Support
  552. *Do not open a support ticket using the link below unless you are seeing an **internal libWrapper error** or are a **package developer**. We also do not provide support for packages that promote or otherwise endorse piracy. Your issue will be closed as invalid if you do not fulfill these requirements.*
  553. If you encounter an internal libWrapper error, or are a package developer looking for support (i.e. bug reports, feature requests, questions, etc), you may get in touch by opening a new issue on the [libWrapper issue tracker](https://github.com/ruipin/fvtt-lib-wrapper/issues). It is usually a good idea to search the existing issues first in case yours has already been answered before.
  554. If your support request relates to an error, please describe with as much detail as possible the error you are seeing, and what you have already done to troubleshoot it. Providing a step-by-step description of how to reproduce it or a snippet of code that triggers the issue is especially welcome, and will ensure you get an answer as fast as possible.