const e={base:Error,internal:Error,package:Error,already_overridden:Error,invalid_chain:Error};Object.seal(e);const t="lib-wrapper",r=function(e,t,r,i=!0){if(Object.isFrozen(e))throw new Error(`libWrapper: Enum '${e.name}' is frozen.`);if(t!==t.toUpperCase())throw new Error("libWrapper: Enum keys must be all uppercase.");const n=new(Function("x",`return class ${t} extends x {}`)(e.value_cls));if(n.name!=t)throw new Error(`libWrapper: Incorrect value_obj name ${n.name}. Expected ${t}.`);if(void 0!==r&&(n.value=r),Object.freeze(n),Object.freeze(n.prototype),Object.freeze(n.constructor),Object.freeze(n.constructor.prototype),t in e)throw new Error(`libWrapper: Name '${t}' is already present in ${e.name}.`);if(e[t]=n,void 0!==r){if(e.reverse.has(r))throw new Error(`libWrapper: Value '${r}' is already present in ${e.name}.`);e.reverse.set(r,n)}return e.list.push(n),i&&e.sort_list_by_value(),n},i=function(e,t,i=!0){let n;if("string"!=typeof e)throw new Error("libWrapper: Enum name must be a string");if("object"!=typeof t)throw new Error("libWrapper: Enum collection must be a dictionary or an array");const a=!(t instanceof Array),s=`${e}Enum`,o={[s]:class{constructor(e,t){return this.constructor.get(e,t)}static get(t,r){if(t instanceof n)return t;if("string"==typeof t){const e=this[t.toUpperCase()];if(e)return e}{let e=this.reverse.get(t);if(void 0===e&&"string"==typeof t){const r=parseInt(t);Number.isInteger(r)&&(e=this.reverse.get(r))}if(void 0!==e)return e}if(void 0===r)throw new Error(`libWrapper: '${t}' is not a valid key or value for the enum ${e}.`);return r}static has(e){return e instanceof n}static toString(){return this.name}static get value_cls(){return n}static sort_list_by_value(){return this.list.sort((function(e,t){return(e.value??0)-(t.value??0)}))}}}[s],c=`${e}Value`;if(n={[c]:class{static toString(){return c}get name(){return this.constructor.name}get enum(){return o}toString(){return this.name}get lower(){return this.name.toLowerCase()}}}[c],Object.freeze(n),Object.freeze(n.prototype),o.list=[],a&&(o.reverse=new Map),t instanceof Array)for(const e of t)r(o,e,void 0,!1);else for(const e in t)r(o,e,t[e],!1);return o.sort_list_by_value(),i&&(Object.freeze(o),Object.freeze(o.prototype),Object.freeze(o.list),a&&Object.freeze(o.reverse)),o},n=function(t=!1){const r=globalThis.game?.user?.data;if(r)return r;const i=globalThis.game?.userId??globalThis.game?.data?.userId;if(!i){if(t)return null;throw new e.internal("Unable to obtain the current user ID")}const n=globalThis.game?.data?.users?.find((e=>e._id==i));if(!n){if(t)return null;throw new e.internal("Unable to obtain the current user data object")}return n},a=function(t,r,i=!1,n=!0){try{const e=globalThis.game?.settings?.get;if(e)return e.call(game.settings,t,r)}catch(e){if(!i)throw e}const a=`${t}.${r}`;try{const t=globalThis.localStorage?.[a];if(null==t){if(n)return null;throw new e.internal(`Unable to obtain the setting '${a}'`)}const r=JSON.parse(t);if(null==r){if(n)return null;throw new e.internal(`Unable to obtain the setting '${a}'`)}return r}catch(t){if(n)return null;throw new e.internal(`Unable to obtain the setting '${a}' due to exception in polyfill:`,t)}},s=i("PackageType",{ZERO:0,TRACE:100,DEBUG:200,INFO:300,WARNING:400,ERROR:500,CRITICAL:Number.MAX_SAFE_INTEGER-1,ALWAYS:Number.MAX_SAFE_INTEGER}),o={NEVER:s.ZERO,ALL:s.ZERO,WARN:s.WARNING},c={[s.ZERO.value]:[console,"debug"],[s.TRACE.value]:[console,"debug"],[s.DEBUG.value]:[console,"debug"],[s.INFO.value]:[console,"info"],[s.WARNING.value]:[console,"warn"],[s.ERROR.value]:[console,"error"],[s.CRITICAL.value]:[console,"error"],[s.ALWAYS.value]:[console,"info"]},l={never:s.ZERO,trace:s.TRACE,debug:s.DEBUG,info:s.INFO,warning:s.WARNING,warn:s.WARNING,error:s.ERROR,critical:s.CRITICAL,always:s.ALWAYS},p="libWrapper:",d={[s.ZERO.value]:"[0] libWrapper:",[s.TRACE.value]:"[T] libWrapper:",[s.DEBUG.value]:"[D] libWrapper:",[s.INFO.value]:"[I] libWrapper:",[s.WARNING.value]:"[W] libWrapper:",[s.ERROR.value]:"[E] libWrapper:",[s.CRITICAL.value]:"[!] libWrapper:",[s.ALWAYS.value]:p};let u=null;const h=function(e){return null==e?0:e.value??e},g=function(e,t,r){const i=h(e);{const e=t[i];if(e)return e}for(const e of s.list)if(!(i>e.value))return t[e.value];return r};function f(){for(const e in l){const t=l[e],r=Log.fn(t);Log[e]=r??(()=>{}),Log[`${e}$`]=r}Log.stack=console.trace&&Log.has_trace?console.trace.bind(console):()=>{}}class Log{static get verbosity(){return u??s.WARNING}static set verbosity(t){const r=s.get(t,parseInt(t));if(!s.has(r)&&!Number.isInteger(r))throw new e.internal(`Parameter 'value' must be a 'VERBOSITY' enum value or an integer, but got '${t}'.`);u=r,f()}static get verbosity_value(){return h(this.verbosity)}static get verbosities(){return s}static init(e=!1){if(!e&&null!=u)return;const r=a(t,"log-verbosity",!0,!0);if(null!=r)try{this.verbosity=r}catch(e){console.error("libWrapper: Unable to set logging verbosity.\n",e)}}static enabled(e=null){return h(e)>=this.verbosity_value}static fn(e,t=e){if(!this.enabled(e))return null;const[r,i]=function(e){return g(e,c,[console,"log"])}(t),n=function(e,t){return g(e,d,p)}(e);return r[i].bind(r,n)}static log(e,...t){return this.fn(e)?.(...t)}}!function(){for(const e of s.list)Log[e.name]=e;for(const e in o)Log[e]=o[e]}(),function(){for(const e in l){const t=l[e];Object.defineProperty(Log,`has_${e}`,{get:Log.enabled.bind(Log,t),configurable:!1})}}(),f(),Log.init(!0),Object.seal(Log);var _={"lib-wrapper":{settings:{yes:"Yes",no:"No",save:"Save",reload:"Reload",reset:"Reset","notify-issues-gm":{name:"Notify GM of Issues",hint:"Whether to notify GMs when an issue is detected, for example a conflict."},"notify-issues-player":{name:"Notify Players of Issues",hint:"Whether to notify Players when an issue is detected, for example a conflict."},"high-performance-mode":{name:"High-Performance Mode",hint:"This disables most dynamic conflict detection capabilities in exchange for performance, especially relevant on low-end systems. Note that this will significantly decrease the chance conflicts are detected. As such, it is recommended to turn this off when installing or updating packages."},"log-verbosity":{name:"Verbosity",hint:"The verbosity of libWrapper's Javascript console messages.",choices:{never:"Never",all:"All",trace:"Trace",debug:"Debug",info:"Information",warning:"Warning",error:"Error",critical:"Critical",always:"Always"}},menu:{title:"libWrapper Settings Menu",priorities:{name:"Priorities","package-inactive":"Inactive","statistics-disabled":"Note: Statistics collection is disabled, not able to show unprioritized packages.",prioritized:{title:"Prioritized Packages",hint:"These packages will be prioritized compared to any package not in this list.\nHigher positions in the list result in a higher priority."},unprioritized:{title:"Unprioritized Packages",hint:"These packages will be neither prioritized nor deprioritized.\nPriorities among these packages are decided on a first-come-first-served basis.\nNew packages will default to this list."},deprioritized:{title:"Deprioritized Packages",hint:"These packages will be deprioritized compared to any package not in this list.\nHigher positions in the list result in a higher priority.",note:"Note that packages that do not use libWrapper are deprioritized even compared to these."}},conflicts:{name:"Conflicts","none-detected":"No conflicts have been detected.","statistics-disabled":"Statistics collection is disabled.","show-ignored":"Show ignored conflicts"},"active-wrappers":{name:"Active Wrappers","none-active":"No wrappers are active right now."},about:{name:"About","full-name":"About libWrapper",credits:"{name} {version} by {author}.","credits-translation":"",description:"'libWrapper' is a library which provides package developers with a simple way to modify core Foundry VTT code, while reducing the likelihood of conflict with other packages.",info:'You can find more information about this module in the Foundry VTT package repository, as well as the project\'s Github page.',support:"If you encounter any issues, the easiest way to find support is to ask the community. The largest community-provided support channels are:","issue-tracker":'If you encounter an internal libWrapper error, or are a package developer, you may also submit a support request in the libWrapper Github Issue Tracker.'},"warning-reset-priorities":"Resetting the package priorities will move all packages back to 'Unprioritized'. This action cannot be undone. Are you sure you want to continue?","warning-save":"It is recommended you reload this page to apply the new package priorities. Do you wish to reload?"}},packages:{"unknown-title":"Unknown","type-plus-id":"{type} {id}","type-plus-title":"{type} {title}",types:{module:"module",system:"system",world:"world script",unknown:"package"}},error:{"see-js-console":"(See JS Console)","tech-details":"== Technical Details:","community-support":"Ask the community for support:","not-lw":"This is *not* a libWrapper bug.",external:{notification:"{title}: Error detected in {type}.",message:"Error detected in {type} {title}.",info:"Find information about this {type} here: {url}",report:"Report this issue here: {url}","likely-not-updated":"It is likely this {type} has not been updated for FVTT {version}."},internal:{message:"Internal error detected.","message-with-package":"Internal error detected, involving {type} {title}.",info:"Find information about libWrapper here: {url}",report:"Report this issue here: {url}"},conflict:{potential:"Potential conflict detected between {main} and {other}.",confirmed:"Conflict detected between {main} and {other}.",info:"Find information about these packages here:",report:"Report this conflict here:"}},"support-channels":[{title:"FoundryVTT Discord's #modules-troubleshooting channel",url:"https://discord.gg/foundryvtt"},{title:"FoundryVTT Reddit",url:"https://www.reddit.com/r/FoundryVTT"}]}};const b=["en","es","ja","pt-BR","pt-PT"],w=import.meta?.url?.endsWith("dist/lib-wrapper.js")?"../lang":"./lang";class i18n{static async _fetch(e){if(Array.isArray(b)&&!b.includes(e))return null;try{const t=new URL(`${w}/${e}.json`,import.meta.url),r=await fetch(t);return 200===r.status&&r.ok?r.json():null}catch(e){return Log.warn$?.(`Failed to load or parse ${url.href}.`,e),null}}static async init(){this.jsons=[];const e=[];try{const t=a("core","language",!0,!1);t&&"en"!==t&&e.push(t)}catch(e){Log.debug$?.("Could not find or parse client language settings.")}const t=game?.i18n?.lang;if(t&&"en"!==t&&e.push(t),e.length>0){const t=await Promise.all(e.map((e=>this._fetch(e))));for(const e of t)e&&this.jsons.push(e)}}static on_ready(){delete this.jsons}static localize(e){if(game?.i18n){const t=game.i18n.localize(e);if(t!==e)return t}try{const t=e.split(".");if(this.jsons)for(const e of this.jsons){const r=t.reduce(((e,t)=>e?.[t]),e);if(r)return r}return t.reduce(((e,t)=>e?.[t]),_)??e}catch(t){return Log.error(t),e}}static format(e,t){if(game?.i18n){const r=game.i18n.format(e,t);if(r!==e)return r}const r=this.localize(e);if(r===e)return r;try{return r.replace(/\{(.*?)\}/g,((e,r)=>t?.[r]))}catch(t){return Log.error(t),e}}}Hooks.once("ready",i18n.on_ready.bind(i18n));const m=i("PackageType",["UNKNOWN","MODULE","SYSTEM","WORLD"]),y=new RegExp("^[a-z0-9_-]+$","i"),k=/^.*?\/(worlds|systems|modules)\/(.+?)(?=\/).*?$/gim;const v=function(e,t,r){if(void 0!==t){if("string"!=typeof t)throw new Error(`libWrapper: Parameter 'stack_trace' must be a string, got ${typeof t}.`)}else{const e=Error.stackTraceLimit;try{Error.stackTraceLimit=1/0,t=Error().stack}finally{Error.stackTraceLimit=e}if("string"!=typeof t)return!0}if(!t)return!0;const i=t.matchAll(k);if(!i)return!0;for(const t of i){const i=t[1],n=t[2];if(!i||!n)continue;let a,s;if("worlds"===i){const e=globalThis.game?.data?.world?.id;if(e&&n!=e)continue;a=n,s=m.WORLD}else if("systems"===i){const e=globalThis.game?.data?.system?.id;if(e&&n!=e)continue;a=n,s=m.SYSTEM}else{if("modules"!==i)throw new Error(`libWrapper: Invalid script type: ${i}`);if(globalThis.game?.modules&&!globalThis.game.modules.has(n))continue;if(r&&(n===r||r?.includes?.(n)))continue;a=n,s=m.MODULE}if(!1===e(a,s,t[0]))return!1}return!0};class PackageInfo{static get UNKNOWN(){return new PackageInfo("«unknown»",m.UNKNOWN)}static collect_all(e,t,r){const i=new Set;v(((e,r,n)=>{const a=`${r.lower}:${e}`;return!!i.has(a)||(void 0!==t&&!t(e,r,n)||(i.add(a),!0))}),e,r);const n=[];for(const e of i)n.push(new PackageInfo(e));return n}static is_valid_key_or_id(e){return this.is_valid_key(e)||this.is_valid_id(e)}static is_valid_key(e){if(!e||"string"!=typeof e)return!1;const[t,r]=this.parse_key(e);return!(!t||!r)&&!!this.is_valid_id(t)}static is_valid_id(e){return!(!e||"string"!=typeof e)&&!!y.test(e)}static parse_key(e){const t=e.split(":");if(2!==t.length)return[null,null];return[t[1],m.get(t[0])]}constructor(e=null,t=null){this.set(e,t)}set(e=null,t=null,r=!0){if(!e)return this.detect_id();if("string"!=typeof e)throw new Error("libWrapper: PackageInfo IDs must be strings");if("«unknown»"!==e){if(null!==t||!this.from_key(e,!1)){if(!this.constructor.is_valid_id(e))throw new Error(`libWrapper: Invalid package ID '${e}'`);if(null!==t&&!m.has(t))throw new Error(`libWrapper: Package type for '${e}' must belong to the PACKAGE_TYPES enum, but got '${t}'.`);this.id=e,this.type=t,t||this.detect_type(),r&&Object.freeze(this)}}else this.set_unknown()}set_unknown(){this.id="«unknown»",this.type=m.UNKNOWN}equals(e){return e&&e.constructor===this.constructor&&e.id===this.id&&e.type===this.type}detect_id(e){this.set_unknown(),v(((e,t)=>(this.set(e,t),!1)),e,"lib-wrapper")}detect_type(){globalThis.game?.modules?globalThis.game.modules?.get(this.id)?.active?this.type=m.MODULE:this.id===globalThis.game.data?.system?.id?this.type=m.SYSTEM:this.id===globalThis.game.data?.world?.id?this.type=m.WORLD:this.type=m.UNKNOWN:this.id===t?this.type=m.MODULE:this.type=m.UNKNOWN}from_key(e,t=!0){const[r,i]=this.constructor.parse_key(e);if(!r||!i){if(t)throw new Error(`libWrapper: Invalid key '${e}'`);return!1}return this.set(r,i),!0}toString(){return this.key}get known(){return this.type!=m.UNKNOWN}get exists(){switch(this.type){case m.MODULE:return globalThis.game?.modules?.get(this.id)?.active;case m.SYSTEM:return globalThis.game?.data?.system?.id===this.id;case m.WORLD:return globalThis.game?.data?.world?.id===this.id;default:return!1}}get data(){if(!this.exists)return null;const e=globalThis.game?.release?.generation,t=e&&e>=10;switch(this.type){case m.MODULE:return t?globalThis.game?.modules?.get(this.id):globalThis.game?.modules?.get(this.id)?.data;case m.SYSTEM:return t?globalThis.game?.data?.system:globalThis.game?.data?.system?.data;case m.WORLD:return globalThis.game?.data?.world;default:return null}}static get unknown_title(){return i18n.localize("lib-wrapper.packages.unknown-title")}get title(){if(!this.exists)return this.constructor.unknown_title;switch(this.type){case m.MODULE:case m.SYSTEM:case m.WORLD:return this.data.title;default:return this.constructor.unknown_title}}get key(){return`${this.type.lower}:${this.id}`}get type_i18n(){return i18n.localize(`lib-wrapper.packages.types.${this.type.lower}`)}get type_plus_id(){return`${this.type.lower} ${this.id}`}get type_plus_id_capitalized(){let e=this.type_plus_id;return e.charAt(0).toUpperCase()+e.slice(1)}get type_plus_id_i18n(){return i18n.format("lib-wrapper.packages.type-plus-id",{type:this.type_i18n,id:this.id})}get type_plus_title(){return`${this.type.lower} ${this.title}`}get type_plus_title_i18n(){return i18n.format("lib-wrapper.packages.type-plus-title",{type:this.type_i18n,title:this.title})}get logId(){return this.type==m.MODULE?this.id:this.key}get settingsName(){switch(this.type){case m.MODULE:return this.id;case m.SYSTEM:return`${this.id} [System]`;case m.WORLD:return`${this.id} [World]`;default:return this.id}}get url(){return this.data?.url}get bugs(){return this.data?.bugs}get version(){return this.data?.version}get core_version_range(){const e=this.data;return e?e.compatibility?[e.compatibility.minimum,e.compatibility.verified,e.compatibility.maximum]:[e.minimumCoreVersion,e.compatibleCoreVersion,null]:null}get compatible_with_core(){const t=this.core_version_range,r=function(t=!0){const r=globalThis.game?.version??globalThis.game?.release?.version??globalThis.game?.data?.version??null;if(!t&&null===r)throw new e.internal("Unable to obtain the Foundry version");return r}(!0),i=r?.split(".")[0];if(!t||!r||!i)return!0;const[n,a,s]=t;if(n){const e=n.includes(".")?r:i;if(n!==e&&!isNewerVersion(e,n))return!1}if(a){const e=a.includes(".")?r:i;if(isNewerVersion(e,a))return!1}if(s){const e=s.includes(".")?r:i;if(e==s||isNewerVersion(e,s))return!1}return!0}}Object.freeze(PackageInfo);const W=eval;function E(e,t){try{e.displayName=t,Object.defineProperty(e,"name",{value:t,writable:!1,enumerable:!1,configurable:!0})}catch(e){}}function L(e,t=""){return""!==t?`🎁${e}#${t}`:`🎁${e}`}function I(e){const t=Object.getOwnPropertyNames(e);t.push(...Object.getOwnPropertySymbols(e));for(const r of t){const t=Object.getOwnPropertyDescriptor(e,r);"function"==typeof t.value&&E(t.value,L(r)),"function"==typeof t.get&&E(t.get,L(r,"getter")),"function"==typeof t.set&&E(t.set,L(r,"setter"))}e.prototype&&I(e.prototype)}function O(e){return null!=e&&"object"==typeof e&&("message"in e&&"stack"in e)}const R=["/listeners.js",L("call_wrapped"),L("Application.prototype._render")];function A(e,r){const i=function(e,r){return PackageInfo.collect_all(e,((e,r,i)=>{if(e!==t||r!==m.MODULE)return!0;for(const e of R)if(i.includes(e))return!1;return!0}),r)}(e,r),n=i.length;return n<=0?"[No packages detected]":1==n?`[Detected 1 package: ${i[0].logId}]`:`[Detected ${n} packages: ${i.map((e=>e.logId)).join(", ")}]`}function T(e,t){if(!(t in e))return!1;const r=Object.getOwnPropertyDescriptor(e,t);if(r){if(!("value"in r))return!1;if("string"!=typeof r.value)return!1;if(!r.writable)return!1}else{if("string"!=typeof e[t])return!1}return!0}function N(e,t){let r;try{if(!O(e))return;if(e.libwrapper_skip_package_detection)return;if(!function(e){return!Object.isFrozen(e)&&!(!T(e,"message")||!T(e,"stack"))}(e))return;if(r=A(e.stack,t),e.message.endsWith(r))return void(e.libwrapper_skip_package_detection=!0)}catch(e){Log.error("Exception thrown while attempting to inject package information into an error.",e)}try{const t=e.message;e.message+=`\n${r}`,e.stack=e.stack.replace(t,e.message),e.libwrapper_skip_package_detection=!0}catch(e){Log.debug$?.("Exception thrown while modifying error object.",e)}}class LibWrapperError extends Error{get notification_verbosity(){return Log.ERROR}constructor(e,r,...i){super(r,...i),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.ui_msg=e,this.console_msg=r,N(this,this instanceof LibWrapperInternalError?null:t)}onUnhandled(){}}Object.freeze(LibWrapperError),e.base=LibWrapperError;class LibWrapperInternalError extends LibWrapperError{static construct_message(e,t){const r="lib-wrapper.error",i=`${r}.internal`,n=t.known?i18n.format(`${type.prefix}.message-with-package`,{type:t.type_i18n,title:t.title}):i18n.localize(`${i}.message`);return[`libWrapper: ${n}`,`${n}\n\n${i18n.format(`${i}.info`,{url:"https://github.com/ruipin/fvtt-lib-wrapper"})}\n${i18n.format(`${i}.report`,{url:"https://github.com/ruipin/fvtt-lib-wrapper/issues"})}\n\n${i18n.localize(`${r}.tech-details`)}\nInternal libWrapper error.\n${t.known?`Related Package ID= ${t.logId}\n`:""}Error= ${e}\n`]}constructor(e,...t){const r=new PackageInfo,[i,n]=LibWrapperInternalError.construct_message(e,r);super(i,n,...t),this.package_info=r}get package_id(){return this.package_info?.id}}Object.freeze(LibWrapperInternalError),e.internal=LibWrapperInternalError;class LibWrapperPackageError extends LibWrapperError{static get_community_support_message(){const e=[],t=i18n.localize("lib-wrapper.support-channels");if(Array.isArray(t))for(const r of t)"title"in r&&"url"in r&&e.push(`- ${r.title}: ${r.url}`);return e.length>0?e.join("\n"):null}static construct_message(t,r){const i="lib-wrapper.error",n=`${i}.external`,a=r.title,s=r.type_i18n;let o=i18n.format(`${n}.notification`,{title:a,type:s}),c=i18n.format(`${n}.message`,{title:a,type:s});if(!r.compatible_with_core){const t=function(t=!0){const r=globalThis.game?.release?.display??globalThis.game?.version??globalThis.game?.data?.version??null;if(!t&&null===r)throw new e.internal("Unable to obtain the Foundry display version");return r}(!0);if(t){const e=` ${i18n.format(`${n}.likely-not-updated`,{type:s,version:t})}`;o+=e,c+=e}}let l=`${c}\n\n${i18n.localize(`${i}.not-lw`)}\n\n`;const p=r.url,d="string"==typeof p;d&&(l+=i18n.format(`${n}.info`,{type:s,url:p}));const u=r.bugs;if("string"==typeof u)d&&(l+="\n"),l+=i18n.format(`${n}.report`,{url:u});else{const e=this.get_community_support_message();e&&(d&&(l+="\n\n"),l+=i18n.localize(`${i}.community-support`),l+="\n",l+=e)}return l+="\n\n",l+=i18n.localize(`${i}.tech-details`),l+=`\nDetected by libWrapper.\nPackage ID= ${r.logId}\nError= ${t}\n`,[o,l]}constructor(e,t,...r){t?t?.constructor!==PackageInfo&&(t=new PackageInfo(t)):t=new PackageInfo;const[i,n]=LibWrapperPackageError.construct_message(e,t);super(i,n,...r),this.package_info=t}get package_id(){return this.package_info?.id}}function P(e,r){try{return game?.settings?.get(t,e)}catch(e){if(void 0!==r)return r;throw e}}function z(){const e=function(e=!1){const t=globalThis.game?.user?.isGM;if(void 0!==t)return t;const r=n(e);return r?4===r.role:null}(!0);return null===e||P(e?"notify-issues-gm":"notify-issues-player",!0)}Object.freeze(LibWrapperPackageError),e.package=LibWrapperPackageError;const S={[Log.INFO.value]:"info",[Log.WARNING.value]:"warn",[Log.ERROR.value]:"error"};class LibWrapperNotifications{static get ui_notifications_enabled(){try{if(!z())return!1}catch(e){return Log.error("Could not decide whether to show notifications or not. Defaulting to 'yes'.\n",e),!0}return!0}static init(){this.NOTIFICATION_SET=new Set,Object.seal(this)}static _ui(t,r=Log.ERROR,i=!0){if(!this.ui_notifications_enabled)return;const n=globalThis?.ui?.notifications;if(!n)return;const a=function(t){if("string"!=typeof t)throw e.internal("Parameter 'str' must be a string.");const r=t.length;let i=0;for(let e=0;e1?`[${t.map((e=>e.type_plus_title_i18n)).join(", ")}]`:t[0].type_plus_title_i18n:t.type_plus_title_i18n;const a={main:e.type_plus_title_i18n,other:n};this.console_ui(r?i18n.format("lib-wrapper.error.conflict.potential",a):i18n.format("lib-wrapper.error.conflict.confirmed",a),i,r?Log.WARNING:Log.ERROR)}}I(LibWrapperNotifications);class LibWrapperStats{static _collect_stats(){try{return function(e,t=!1){const r=globalThis.game?.user?.can;if(r)return r.call(game.user,e);const i=n(t);if(!i)return null;if(4===i.role)return!0;if(e in i.permissions)return i.permissions[e];const a=globalThis.game?.data?.settings?.find((e=>"core.permissions"===e.key));if(a?.value){const t=JSON.parse(a.value)[e];if(t&&t.includes(i.role))return!0}return!1}("SETTINGS_MODIFY")}catch(e){return LibWrapperNotifications.console_ui("A non-critical error occurred while initializing libWrapper.","Could not read user permissions during initialization.\n",Log.WARNING,e),!0}}static init(){this.collect_stats=this._collect_stats(),this.collect_stats&&(this.PACKAGES=new Set,this.CONFLICTS=new Map,Object.seal(this))}static register_package(e){this.collect_stats&&e.id!=t&&this.PACKAGES.add(e.key)}static register_conflict(e,t,r,i){if(!this.collect_stats)return;const n=`${e.key}/${t.key}`;let a=this.CONFLICTS.get(n);a||(a={count:0,ignored:0,package_info:e,other_info:t,targets:new Map},this.CONFLICTS.set(n,a));const s=r.name;let o=a.targets.get(s);o||(o={count:0,ignored:0},a.targets.set(s,o)),i?(a.ignored++,o.ignored++):(a.count++,o.count++)}static get conflicts(){return this.CONFLICTS}static get packages(){return this.PACKAGES}}class IgnoredConflictEntry{constructor(e,t,r){this.ignore_infos=new Set(e.map((e=>e.key))),this.targets=new Set(t),this.ignore_errors=r,Object.seal(this)}is_ignored(e,t,r){if(!r&&!this.ignore_errors)return!1;if(!this.ignore_infos.has(e.key))return!1;return void 0!==t.names.find((e=>this.targets.has(e)))}}class LibWrapperConflicts{static init(){this.IGNORED=new Map,Object.seal(this)}static register_ignore(e,t,r,i){const n=new IgnoredConflictEntry(t,r,i),a=e.key;let s=this.IGNORED.get(a);s||(s=[],this.IGNORED.set(a,s)),s.push(n)}static clear_ignores(){this.IGNORED.clear()}static _is_ignored_oneway(e,t,r,i){const n=e.key,a=this.IGNORED.get(n);if(!a)return!1;for(const e of a)if(e.is_ignored(t,r,i))return!0;return!1}static _is_ignored(e,t,r,i){return this._is_ignored_oneway(e,t,r,i)||this._is_ignored_oneway(t,e,r,i)}static register_conflict(t,r,i,n,a){if(!r)return!1;if(Array.isArray(r)){let e=!1;return r.forEach((r=>{e|=this.register_conflict(t,r,i,n,a)})),e}if(t.constructor!==PackageInfo)throw new e.internal(`LibWrapperConflicts.register_conflict: 'package_info' must be a PackageInfo object, but got '${t}'.`);if(r.constructor!==PackageInfo)throw new e.internal(`LibWrapperConflicts.register_conflict: 'other_info' must be a PackageInfo object, but got '${r}'.`);if(null!=n&&"string"!=typeof n)throw new e.internal(`LibWrapperConflicts.register_conflict: 'target' must be a string, or null, but got '${n}'.`);if("boolean"!=typeof a)throw new e.internal(`LibWrapperConflicts.register_conflict: 'is_warning' must be a boolean, but got '${a}'.`);let s=!1;return!s&&this._is_ignored(t,r,i,a)&&(s=!0,Log.debug$?.(`Conflict between ${t.type_plus_id} and ${r.type_plus_id} over '${i.name}' ignored through 'ignore_conflicts' API.`)),s||!1!==Hooks.call("libWrapper.ConflictDetected",t.id,r.id,n,i.frozen_names)||(s=!0,Log.debug$?.(`Conflict between ${t.type_plus_id} and ${r.type_plus_id} over '${i.name}' ignored, as 'libWrapper.ConflictDetected' hook returned false.`)),LibWrapperStats.register_conflict(t,r,i,s),!s}}class LibWrapperAlreadyOverriddenError extends LibWrapperError{static construct_message(e,t,r){const i="lib-wrapper.error",n=`${i}.conflict`,a=e.type_plus_title_i18n,s=a.charAt(0).toUpperCase()+a.slice(1),o=t.type_plus_title_i18n,c=o.charAt(0).toUpperCase()+o.slice(1),l=i18n.format(`${n}.confirmed`,{main:a,other:o});let p=`libWrapper: ${l}`,d=`${l}\n\n${i18n.localize(`${i}.not-lw`)}\n\n`,u="";const h=e.url;"string"==typeof h&&(u+=`\n- ${s}: ${h}`);const g=t.url;"string"==typeof g&&(u+=`\n- ${c}: ${g}`),u&&(d+=`${i18n.localize(`${n}.info`)}${u}\n\n`);let f="";const _=e.bugs;"string"==typeof _&&(f+=`\n- ${s}: ${_}`);const b=t.bugs;"string"==typeof b&&(f+=`\n- ${c}: ${b}`),f&&(d+=`${i18n.localize(`${n}.report`)}${f}\n\n`);const w=LibWrapperPackageError.get_community_support_message();return w&&(d+=i18n.localize(`${i}.community-support`),d+="\n",d+=w,d+="\n\n"),d+=i18n.localize(`${i}.tech-details`),d+=`\nDetected by libWrapper.\nPackage IDs= ${e.logId}, ${t.logId}\nError= ${r}\n`,[p,d]}constructor(e,t,r,i,...n){e?.constructor!==PackageInfo&&(e=new PackageInfo(e)),t?.constructor!==PackageInfo&&(t=new PackageInfo(t));const[a,s]=LibWrapperAlreadyOverriddenError.construct_message(e,t,`Failed to wrap '${i}' for ${e.type_plus_id} with type OVERRIDE. An OVERRIDE wrapper for the same method has already been registered by ${t.type_plus_id}.`);super(a,s,...n),this.package_info=e,this.conflicting_info=t,this.target=i,this._wrapper=r}get package_id(){return this.package_info?.id}get module(){return this.package_id}get conflicting_id(){return this.conflicting_info?.id}get conflicting_module(){return this.conflicting_id}onUnhandled(){super.onUnhandled(),LibWrapperConflicts.register_conflict(this.package_info,this.conflicting_info,this._wrapper,this.target,!1)}}Object.freeze(LibWrapperAlreadyOverriddenError),e.already_overridden=LibWrapperAlreadyOverriddenError;class LibWrapperInvalidWrapperChainError extends LibWrapperPackageError{constructor(e,t,r,...i){t?.constructor!==PackageInfo&&(t=new PackageInfo(t)),super(r,t,...i),this._wrapper=e}}Object.freeze(LibWrapperInvalidWrapperChainError),e.invalid_chain=LibWrapperInvalidWrapperChainError,Error.stackTraceLimit=1/0;const C=function(e){try{if(!O(e))return;e instanceof LibWrapperError&&function(e){e.ui_msg&&e.notification_verbosity&&LibWrapperNotifications.ui(`${e.ui_msg} ${i18n.localize("lib-wrapper.error.see-js-console")}`,e.notification_verbosity,!1),e.onUnhandled&&e.onUnhandled.apply(e)}(e),function(e){N(e)}(e)}catch(e){Log.error("Exception thrown while processing an unhandled error.",e)}},j=function(e){try{const t=e.reason??e.error??e;return C(t)}catch(e){Log.error("Exception thrown while processing an unhandled error event.",e)}};const D="1.12.11.0",x=1,U=12,F=11,M=0,G="",V="43cfb1808e2f5a3cc7d05e926f6038bfa9cf9c98",H="1.12.11.0 (43cfb18)",Y=function(e,t=0,r=0,i=0){return x==e?U==t?F==r?M==i:F>=r:U>t:x>e},B=i("WrapperType",{WRAPPER:1,MIXED:2,OVERRIDE:3}),K=i("PerformanceMode",{NORMAL:1,AUTO:2,FAST:3});const Z=new class WrapperStorage{constructor(){this.clear()}index_for_id(e){return Math.floor(e/2)}index_for_wrapper(e){return this.index_for_id(e.getter_id)}get_next_id_pair(){return[this.next_id++,this.next_id++]}_delete(e){this.data.delete(e)}_set(e,t){if(null==t)return this._delete(e);const r=new WeakRef(t);this.data.set(e,r)}_deref(e,t){const r=t?.deref();return r||this._delete(e),r}_get(e){const t=this.data.get(e);return this._deref(e,t)}exists(t,r){void 0===r&&(r=this.index_for_wrapper(t));const i=this._get(r);if(i){if(i!==t)throw new e.internal(`Sanity check failed: The WrapperStorage index ${r} does not contain the wrapper object '${t.name}'.`);return!0}return!1}add(e){const t=this.index_for_wrapper(e);this.exists(e,t)||this._set(t,e)}remove(e){const t=this.index_for_wrapper(e);this.exists(e,t)&&this._delete(t)}clear(){this.data=new Map,this.next_id=0}*wrappers(){for(const[e,t]of this.data.entries()){const r=this._deref(e,t);r&&(yield r)}}forEach(e){for(const t of this.wrappers())e(t)}find(e){for(const t of this.wrappers())if(e(t))return t}find_by_id(e){const t=this.index_for_id(e);return this._get(t)}};class Wrapper{get_id(e=!1){return e?this.setter_id:this.getter_id}get name(){return this.names[0]}get frozen_names(){return Object.freeze(this.names),this.names}get_name(e=!1){return e?`${this.name}#set`:this.name}get_names(e=!1){return e?this.names.map((e=>`${e}#set`)):this.frozen_names}_add_name(e){this.names.includes(e)||(Object.isFrozen(this.names)&&(this.names=this.names.slice()),this.names.push(e))}_callstack_name(e,t=this.name){return L(t,e)}constructor(t,r,i,n){this.fn_name=r,this.object=t;let a=Object.getOwnPropertyDescriptor(t,r);if(a){if(a.get?._lib_wrapper){const t=a.get?._lib_wrapper;if(!(t instanceof this.constructor))throw new e.internal(`'${i}' cannot be wrapped, the descriptor already has a wrapper, but of an unexpected class ('${t.constructor.name}' vs '${this.constructor.name}').`);return t._add_name(i),t}if(!1===a.configurable)throw new e.package(`'${i}' cannot be wrapped, the corresponding descriptor has 'configurable=false'.`,n);a.get?(this.is_property=!0,this._wrapped_getter=a.get,this._wrapped_setter=a.set):(this.is_property=!1,this._wrapped=a.value)}else{if(a=this._get_inherited_descriptor(),!a)throw new e.package(`Can't wrap '${i}', target does not exist or could not be found.`,n);const t=a.get?._lib_wrapper;t?this.is_property=t.is_property:a.get??a.set?this.is_property=!0:this.is_property=!1}[this.getter_id,this.setter_id]=Z.get_next_id_pair(),this.names=[],this.getter_data=[],this.is_property&&(this.setter_data=[]),this.active=!1,this._outstanding_wrappers=0,this.is_property||(this._current_handler_id=0,this._pending_wrapped_calls=[],this._pending_wrapped_calls_cnt=0),this.use_static_dispatch=!1,i||(i=r),this._add_name(i),this._wrap()}_get_handler(){if(this.is_property)throw new e.internal("Unreachable: _get_handler with is_property=false");const t=this._current_handler_id;if(t===this._cached_handler_id)return this._cached_handler;const r=this,i=this._callstack_name(t),n=this._wrapped??null,a={[i]:function(...e){const i=r.use_static_dispatch;return r.should_skip_wrappers(this,t,i)?r.get_wrapped(this,!1,n).apply(this,e):i?r.get_static_dispatch_chain(this).apply(this,e):r.call_wrapper(null,this,...e)}}[i];return a.toString=function(){return"/* WARNING: libWrapper wrappers present! */\n"+r.get_wrapped(this).toString()},this._cached_handler=a,this._cached_handler_id=t,a}should_skip_wrappers(t,r,i){if(r==this._current_handler_id)return!1;if(r>this._current_handler_id)throw new e.internal(`Unreachable: handler_id=${r} > this._current_handler_id=${this._current_handler_id}`);if(!this.is_property){if(this._pending_wrapped_calls_cnt<=0)return!1;if(!i){if(this._pending_wrapped_calls.indexOf(t)<0)return!1}}return!0}skip_existing_handlers(){this._current_handler_id++}_get_static_dispatch_chain_cache(e){return this._static_dispatch_weakmap?.get(e)??this._static_dispatch_strongmap?.get(e)}_set_static_dispatch_chain_cache(e,t){try{this._static_dispatch_weakmap||(this._static_dispatch_weakmap=new WeakMap),this._static_dispatch_weakmap.set(e,t)}catch{this._static_dispatch_strongmap||(this._static_dispatch_strongmap=new Map),this._static_dispatch_strongmap.set(e,t)}}clear_static_dispatch_chain_cache(){this._static_dispatch_weakmap?.clear?this._static_dispatch_weakmap.clear():delete this._static_dispatch_weakmap,this._static_dispatch_strongmap?.clear()}get_static_dispatch_chain(t){if(this.is_property)throw new e.internal("Unreachable: get_static_dispatch_chain with is_property=false");let r=this._get_static_dispatch_chain_cache(t);if(!r){r=this.call_wrapped.bind(this,null,t);const e=this.get_fn_data(!1);for(let i=e.length-1;i>=0;i--){const n=e[i],a=n.fn;r=n.chain?a.bind(t,r,...n.bind??[]):a.bind(t,...n.bind??[])}this._set_static_dispatch_chain_cache(t,r)}return r}_calc_use_static_dispatch(){if(this.is_property)return!1;let e=K.AUTO;const t=this.get_fn_data(!1);for(const r of t)if(r.perf_mode)if(e===K.AUTO)e=r.perf_mode;else if(e!==r.perf_mode){e=K.AUTO;break}return e===K.AUTO&&(e=P("high-performance-mode",!1)?K.FAST:K.NORMAL),e===K.FAST}update_use_static_dispatch(){this.use_static_dispatch=this._calc_use_static_dispatch()}_wrap(){if(this.active)return;const e=this._callstack_name("getter"),t=this._callstack_name("setter"),r=this;let i;i=this.is_property?{[e]:function(...e){return r.call_wrapper(null,this,...e)},[t]:function(...e){return r.call_wrapper({setter:!0},this,...e)}}:{[e]:r._get_handler.bind(r),[t]:function(e){return r.set_nonproperty(e,this)}};const n=i[e],a=i[t];n._lib_wrapper=this,Object.defineProperty(this.object,this.fn_name,{get:n,set:a,configurable:false}),this.active=!0,Log.debug$?.(`Wrapped '${this.name}'.`)}unwrap(){if(this.active)throw new e.internal("libWrapper: Cannot unwrap when PROPERTIES_CONFIGURABLE==false")}_get_inherited_descriptor(){let e=Object.getPrototypeOf(this.object);for(;e;){const t=Object.getOwnPropertyDescriptor(e,this.fn_name);if(t)return t;e=Object.getPrototypeOf(e)}return null}get_wrapped(t,r=!1,i){let n;if(n=void 0!==i?i:this.is_property?r?this._wrapped_setter:this._wrapped_getter:this._wrapped,null===n&&(n=void 0),void 0===n){const i=this._get_inherited_descriptor();if(i)if(this.is_property){if(!i.get&&!i.set)throw new e.internal("This wrapper is set up to wrap a property, but the inherited descriptor is a method.");n=r?i.set:i.get}else n=i.value??i.get.apply(t)}return void 0===n&&Log.warn$?.(`There is no wrapped method for '${this.name}', returning 'undefined'.`),n}call_wrapped(e,t,...r){e&&this._call_wrapper_update_state(e);const i=e?.setter??!1,n=!!e;let a,s;this.is_property||(this._pending_wrapped_calls_cnt++,n&&(a=t,this._pending_wrapped_calls.push(a)));try{s=this.get_wrapped(this.object,i)?.apply(t,r)}catch(e){throw this.is_property||this._cleanup_call_wrapped(a,n),e}return this.is_property||("function"==typeof s?.then?s=s.then((e=>(this._cleanup_call_wrapped(a,n),e)),(e=>{throw this._cleanup_call_wrapped(a,n),e})):this._cleanup_call_wrapped(a,n)),s}_cleanup_call_wrapped(t,r){if(this._pending_wrapped_calls_cnt<=0)throw new e.internal(`this._pending_wrapped_calls_cnt=${this._pending_wrapped_calls_cnt} should be unreachable at this point.`);if(this._pending_wrapped_calls_cnt--,r){const r=this._pending_wrapped_calls.indexOf(t);if(r<0)throw new e.internal("Could not find 'pend' inside 'this._pending_wrapped_calls'.");this._pending_wrapped_calls.splice(r,1)}}call_wrapper(t,r,...i){t&&this._call_wrapper_update_state(t);const n=t?.index??0,a=t?.setter??!1,s=t?.fn_data??this.get_fn_data(a),o=s[n];if(!o){if(s.length>0)throw new e.internal(`Must not have 'data===${o}' when 'fn_data.length==${s.length}'.`);return this.call_wrapped(t,r,...i)}const c=o.fn;if(!o.chain)return c.apply(r,...o.bind??[],i);const l=n+1,p=l>=s.length,d={index:l,called:!1,valid:!0,setter:a,prev_data:o,fn_data:s},u=p?this.call_wrapped.bind(this,d,r):this.call_wrapper.bind(this,d,r);let h;this._outstanding_wrappers++;try{h=c.call(r,u,...o.bind??[],...i)}catch(e){return this._cleanup_call_wrapper_thrown(d,e)}return h="function"==typeof h?.then?h.then((e=>this._cleanup_call_wrapper(e,d,o,s,u,r,i)),(e=>this._cleanup_call_wrapper_thrown(d,e))):this._cleanup_call_wrapper(h,d,o,s,u,r,i),h}_call_wrapper_update_state(t){if(!1===t.valid)throw new e.invalid_chain(this,t.prev_data?.package_info,`This wrapper function for '${this.name}' is no longer valid, and must not be called.`);t.called=!0}_invalidate_state(t){if(t.valid=!1,this._outstanding_wrappers--,this._outstanding_wrappers<0)throw new e.internal(`Outstanding wrappers = ${this._outstanding_wrappers}, should never fall below 0.`)}_cleanup_call_wrapper_thrown(e,t){throw this._invalidate_state(e),t}_cleanup_call_wrapper(t,r,i,n,a,s,o){try{if(!r.called){let c=!i.warned_conflict||LibWrapperStats.collect_stats,l=null,p=!1,d=!1;if(c&&(l=n.slice(r.index).filter((e=>!e.package_info.equals(i.package_info))).map((e=>e.package_info)),p=0==l.length,p||(d=LibWrapperConflicts.register_conflict(i.package_info,l,this,null,!0))),i.type===B.WRAPPER){const r=new e.package(`The wrapper for '${i.target}' registered by ${i.package_info.type_plus_id} with type WRAPPER did not chain the call to the next wrapper, which breaks a libWrapper API requirement. This wrapper will be unregistered.`,i.package_info);C(r),Log.error$?.(r),globalThis.libWrapper.unregister(i.package_info.id,this.get_id(i.setter)),p||(t=a.apply(s,o))}else d&&!i.warned_conflict&&(LibWrapperNotifications.conflict(i.package_info,l,!0,`${i.package_info.type_plus_id_capitalized} did not chain the wrapper for '${i.target}'.`),i.warned_conflict=!0)}}finally{this._invalidate_state(r)}return t}set_nonproperty(t,r=null){if(this.is_property)throw new e.internal("Must not call 'set_nonproperty' for a property wrapper.");r!==this.object?Object.defineProperty(r,this.fn_name,{value:t,configurable:!0,enumerable:!0,writable:!0}):(this._wrapped=t,this.skip_existing_handlers(),this.warn_classic_wrapper())}get_affected_packages(){return this.getter_data.map((e=>e.package_info))}warn_classic_wrapper(){const e=new PackageInfo,t=this.get_affected_packages();if(t.length>0){LibWrapperConflicts.register_conflict(e,t,this,null,!0)&&(LibWrapperNotifications.conflict(e,t,!0,`Detected non-libWrapper wrapping of '${this.name}' by ${e.type_plus_id}. This will potentially lead to conflicts.`),Log.trace())}this.detected_classic_wrapper||(this.detected_classic_wrapper=[]),this.detected_classic_wrapper.push(e.key)}get_fn_data(t,r=!1){if(t&&!this.is_property)throw new e.internal(`'${this.name}' does not wrap a property, thus setter=true is illegal.`);const i=t?"setter_data":"getter_data";let n=this[i];return r&&this._outstanding_wrappers>0&&(n=this[i].slice(0),this[i]=n),n}_post_update_fn_data(){this.update_use_static_dispatch(),this.clear_static_dispatch_chain_cache()}sort(){for(let e of[!1,!0]){if(e&&!this.is_property)continue;this.get_fn_data(e).sort(((e,t)=>e.type.value-t.type.value||t.priority-e.priority))}}add(e){const t=e.fn;t.name&&"anonymous"!==t.name||E(t,this._callstack_name(e.package_info.id??""));this.get_fn_data(e.setter,!0).splice(0,0,e),this.sort(e.setter),this._post_update_fn_data()}remove(e){const t=this.get_fn_data(e.setter,!0),r=t.indexOf(e);t.splice(r,1),this._post_update_fn_data()}clear(){this.getter_data=[],this.is_property&&(this.setter_data=[]),this._post_update_fn_data()}is_empty(){return!this.getter_data.length&&!this.setter_data?.length}}I(Wrapper),Object.freeze(Wrapper);const q=new Map;function X(e,t){return!!PackageInfo.is_valid_key_or_id(e)&&(!!t&&("string"==typeof t.id&&"string"==typeof t.title&&"number"==typeof t.index))}const J=function(e=null){q.clear();const r=e??game?.settings?.get(t,"module-priorities");if(r)for(let e of["prioritized","deprioritized"]){const t=r[e];if(!t)continue;const i="prioritized"==e?1e4:-1e4;Object.entries(t).forEach((e=>{let[t,r]=e;X(t,r)?q.has(t)||q.set(t,i-r.index):Log.warn$?.(`Ignoring '${t}' entry while loading module priorities due to invalid format.`)}))}};class LibWrapperSettings extends FormApplication{static init(){game.settings.register(t,"notify-issues-gm",{name:"lib-wrapper.settings.notify-issues-gm.name",hint:"lib-wrapper.settings.notify-issues-gm.hint",default:!0,type:Boolean,scope:"world",config:!0}),game.settings.register(t,"notify-issues-player",{name:"lib-wrapper.settings.notify-issues-player.name",hint:"lib-wrapper.settings.notify-issues-player.hint",default:!1,type:Boolean,scope:"world",config:!0}),game.settings.register(t,"high-performance-mode",{name:"lib-wrapper.settings.high-performance-mode.name",hint:"lib-wrapper.settings.high-performance-mode.hint",default:!1,type:Boolean,scope:"world",config:!0}),game.settings.register(t,"log-verbosity",{name:"lib-wrapper.settings.log-verbosity.name",hint:"lib-wrapper.settings.log-verbosity.hint",default:Log.WARNING.value,type:Number,choices:{0:i18n.localize("lib-wrapper.settings.log-verbosity.choices.all"),[Log.DEBUG.value]:i18n.localize("lib-wrapper.settings.log-verbosity.choices.debug"),[Log.INFO.value]:i18n.localize("lib-wrapper.settings.log-verbosity.choices.info"),[Log.WARNING.value]:i18n.localize("lib-wrapper.settings.log-verbosity.choices.warning")},scope:"client",config:!0,onChange:e=>Log.init(!0)}),game.settings.registerMenu(t,"menu",{name:"",label:"lib-wrapper.settings.menu.title",icon:"fas fa-cog",type:LibWrapperSettings,restricted:!0}),game.settings.register(t,"module-priorities",{name:"",default:{},type:Object,scope:"world",config:!1,onChange:e=>J()}),this.show_ignored_conflicts=!1,Log.init(),J(),Object.seal(this)}static get defaultOptions(){return{...super.defaultOptions,template:"modules/lib-wrapper/templates/settings.html",height:700,title:i18n.localize("lib-wrapper.settings.menu.title"),width:600,classes:[t,"settings"],tabs:[{navSelector:".tabs",contentSelector:"form",initial:"name"}],submitOnClose:!1,closeOnSubmit:!1}}constructor(e={},t){super(e,t)}static showYesNoDialog(e,t){new Dialog({content:e,buttons:{yes:{icon:'',label:i18n.localize("lib-wrapper.settings.yes"),callback:t},no:{icon:'',label:i18n.localize("lib-wrapper.settings.no")}}}).render(!0)}getActiveWrappers(){let e=[];return Z.forEach((r=>{for(let i of[!1,!0]){if(i&&!r.is_property)continue;const n=[];if(r.get_fn_data(i).forEach((e=>{if(e.package_info.id==t)return;const r={name:e.package_info.settingsName,type:e.type.name,perf_mode:e.perf_mode.name};"AUTO"==r.perf_mode?r.perf_mode=null:r.perf_mode=`, ${r.perf_mode}`,n.push(r)})),r.detected_classic_wrapper&&r.detected_classic_wrapper.forEach((e=>{n.push({name:new PackageInfo(e).settingsName,type:"MANUAL",perf_mode:null})})),n.length<=0)continue;const a=r.get_id(i),s=r.get_names(i);e.push({id:a,name:s[0],names:s.slice(1),packages:n})}})),e.sort(((e,t)=>t.packages.length-e.packages.length)),e}getConflicts(){if(!LibWrapperStats.collect_stats)return null;let e=[];return LibWrapperStats.conflicts.forEach((t=>{let r=t.count;if(this.show_ignored_conflicts&&(r+=t.ignored),0==r)return;const i=[];e.push({count:t.count,ignored:this.show_ignored_conflicts?t.ignored:0,total:r,package_id:t.package_info.settingsName,other_id:t.other_info.settingsName,targets:i}),t.targets.forEach(((e,t)=>{let r=e.count;this.show_ignored_conflicts&&(r+=e.ignored),r>0&&i.push({target:t,count:e.count,total:r,ignored:this.show_ignored_conflicts?e.ignored:0})})),i.sort(((e,t)=>e.total-t.total))})),e.sort(((e,t)=>e.total-t.total)),e}getPackages(){let e={prioritized:[],normal:[],deprioritized:[]};const r=game.settings.get(t,"module-priorities"),i=r.prioritized??{},n=r.deprioritized??{},a=i18n.localize("lib-wrapper.settings.menu.priorities.package-inactive");return LibWrapperStats.collect_stats&&(LibWrapperStats.packages.forEach((t=>{const r=new PackageInfo(t);r.key in i||r.key in n||e.normal.push(r)})),e.normal.sort(((e,t)=>e.id.localeCompare(t.id)))),Object.entries(i).forEach((t=>{let[r,i]=t;X(r,i)?e.prioritized.push({key:r,id:i.id,title:i.title??`${i.title} <${a}>`,index:i.index}):Log.warn$?.(`Ignoring '${r}' entry while loading module priorities due to invalid format.`)})),e.prioritized.sort(((e,t)=>e.index-t.index)),Object.entries(n).forEach((t=>{let[r,n]=t;r in i||(X(r,n)?e.deprioritized.push({key:r,id:n.id,title:n.title??`${n.title} <${a}>`,index:n.index}):Log.warn$?.(`Ignoring '${r}' entry while loading module priorities due to invalid format.`))})),e.deprioritized.sort(((e,t)=>e.index-t.index)),e}getData(){const e=[];{const t="lib-wrapper.support-channels",r=i18n.localize(t);if(Array.isArray(r))for(const t of r)"title"in t&&"url"in t&&e.push(t)}return{about:{name:"libWrapper",version:H,collect_stats:LibWrapperStats.collect_stats,translation_credits:i18n.localize("lib-wrapper.settings.menu.about.credits-translation"),support:e},wrappers:this.getActiveWrappers(),conflicts:this.getConflicts(),packages:this.getPackages(),show_ignored_conflicts:this.show_ignored_conflicts}}activateListeners(e){super.activateListeners(e);let t=this;e.find(".caret.has-nested").on("click",(function(e){const t=$(this);t.parent().find(".nested").toggleClass("active"),t.toggleClass("caret-down")})),e.find("button.reload").on("click",(function(e){t.render(!0)})),e.find(".lw-show-ignored-conflicts").on("change",(function(e){const r=$(this).find("input[type=checkbox]").prop("checked");t.show_ignored_conflicts=r,t.render(!0)})),e.find(".package-priority-group").on("click",(function(e){const t=$(this).find("select");t.is(":focus")||t.focus()})),e.find("button.change-priority").on("click",(function(t){const r=$(this),i=r.data("which"),n="up"===r.data("direction"),a=e.find(`.${i}`).find("option:selected"),s=n?a.prev():a.next();s.length&&(n?s.before(a):s.after(a))})),e.find("button.change-category").on("click",(function(t){const r=$(this),i=r.data("from"),n=r.data("to"),a=e.find(`.${i}`),s=e.find(`.${n}`),o=a.find("option:selected");let c=o.next();if(0==c.length&&(c=o.prev()),s.append(o),"packages-normal"==n){const e=s.find("option");e.sort(((e,t)=>$(e).val()>$(t).val()?1:-1)),s.empty().append(e)}c.length&&a.val(c.val()),a.focus()})),e.find(".submit").on("click",(function(t){for(let t of["packages-prioritized","packages-deprioritized"]){const r=e.find(`.${t}`).find("option");let i=[];r.each(((e,t)=>{i.push($(t).val())})),$("").attr("type","hidden").attr("name",`${t}-hidden`).attr("value",i.join(",")).appendTo(e)}e.submit()})),e.find(".reset").on("click",(function(t){$("input[type=hidden]").remove(),LibWrapperSettings.showYesNoDialog(`
`,(()=>{for(let t of["packages-prioritized","packages-deprioritized"])$("").attr("type","hidden").attr("name",`${t}-hidden`).attr("value","").appendTo(e);e.submit()}))}))}async _updateObject(e,r){const i=game.settings.get(t,"module-priorities");for(let e of["prioritized","deprioritized"]){const t=`packages-${e}-hidden`;if(!(t in r))continue;const n=r[t],a=""===n?[]:n.split(",");let s=i[e]??{},o={},c=0;a.forEach((e=>{if(!e)return;const t=s[e],r=new PackageInfo(e);o[e]={id:r.id,title:r.exists?r.title:t.title,index:c++}})),i[e]=o}Object.keys(i.deprioritized).forEach((e=>{e in i.prioritized&&delete i.deprioritized[e]})),await game.settings.set(t,"module-priorities",i),this.render(!0),LibWrapperSettings.showYesNoDialog(`
`,(()=>location.reload()))}}let Q=!1,ee=!0;const te=new RegExp(["(","[^.[]+","|","\\[","(","'","(","[^'\\\\]","|","\\\\.",")+?","'","|",'"',"(",'[^"\\\\]',"|","\\\\.",")+?",'"',")","\\]",")"].join(""),"g"),re=new RegExp(["(","^\\['","|","'\\]$","|",'^\\["',"|",'"\\]$',")"].join(""),"g");function ie(e){let t=e.endsWith("#set");return[t?e.slice(0,-4):e,t]}function ne(e){return/^[a-zA-Z_$][0-9a-zA-Z_$]*?([.[]|$)/.test(e)}function ae(t,r){const i=ie(t)[0];if(!ne(i))throw new e.package(`Invalid target '${i}'.`,r);const n=i.match(te).map((e=>e.replace(/\\(.)/g,"$1").replace(re,""))),a=n.splice(0,1)[0];if(!/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a))throw new e.package(`Invalid target '${i}': Invalid root scope '${a}'.`,r);if("libWrapper"==a)throw new e.package("Not allowed to wrap libWrapper internals.",r);let s,o;if(0==n.length){if(!(a in globalThis))throw new e.package(`Could not find target '${i}': Could not find scope 'globalThis.${a}'.`,r);o=a,s=globalThis}else{o=n.pop();const t=function(e){try{return globalThis[e]??W(e)}catch(e){return}}(a);if(!t)throw new e.package(`Could not find target '${i}': Could not find root scope '${a}'.`,r);s=t;for(const t of n)if(s=s[t],!s)throw new e.package(`Could not find target '${i}': Could not find scope '${t}'.`,r)}return[s,o,i]}function se(e,t){return function(e,t,r,i){const n=new Wrapper(e,t,r,i);return Z.add(n),n}(...ae(e,t),t)}function oe(e,t){return function(e,t){return Object.getOwnPropertyDescriptor(e,t)?.get?._lib_wrapper??null}(...ae(e,t))}function ce(e){const t=Z.find_by_id(e);return[t,e===t?.setter_id]}function le(e,t,r){return t.get_fn_data(r).find((t=>t.package_info?.equals(e)))}function pe(t,r,i){const n=function(e,t){let r,i=null;if("number"==typeof t)[i,r]=ce(t);else{const e=ie(t);i=oe(e[0]),r=e[1]}return i?r&&!i.is_property?null:le(e,i,r):null}(t,r);if(!n){if(i)throw new e.package(`Cannot unregister '${r}' by ${t.type_plus_id} as no such wrapper has been registered`,t);return}const a=n.wrapper;return a.remove(n),function(e){e.is_empty()}(a),n}function de(r){let i=new PackageInfo;if(!PackageInfo.is_valid_key_or_id(r))throw new e.package("Parameter 'package_id' is invalid.",i);const n=new PackageInfo(r);if(i.exists){if(!i.equals(n))throw new e.package(`${i.type_plus_id_capitalized} is not allowed to call libWrapper with package_id='${r}'.`,i)}else i=n;if(r==t){if(!ee)throw new e.package(`Not allowed to call libWrapper with package_id='${r}'.`,i)}else if(!i.exists&&globalThis.game?.modules?.size)throw new e.package(`Package '${r}' is not a valid package.`,i);return i}class libWrapper$1{static get version(){return D}static get versions(){return[x,U,F,M,G]}static get git_version(){return V}static get is_fallback(){return!1}static get LibWrapperError(){return e.base}static get Error(){return e.base}static get LibWrapperInternalError(){return e.internal}static get InternalError(){return e.internal}static get LibWrapperPackageError(){return e.package}static get PackageError(){return e.package}static get LibWrapperAlreadyOverriddenError(){return e.already_overridden}static get AlreadyOverriddenError(){return e.already_overridden}static get LibWrapperInvalidWrapperChainError(){return e.invalid_chain}static get InvalidWrapperChainError(){return e.invalid_chain}static get onUnhandledError(){return C}static get WRAPPER(){return B.WRAPPER}static get MIXED(){return B.MIXED}static get OVERRIDE(){return B.OVERRIDE}static get PERF_NORMAL(){return K.NORMAL}static get PERF_AUTO(){return K.AUTO}static get PERF_FAST(){return K.FAST}static get version_at_least(){return Y}static register(r,i,n,a="MIXED",s={}){const o=de(r);if(r!=t&&!Q)throw new e.package("Not allowed to register wrappers before the 'libWrapper.Ready' hook fires",o);if("string"!=typeof i&&"number"!=typeof i)throw new e.package("Parameter 'target' must be a number or a string.",o);if(!(n&&n instanceof Function))throw new e.package("Parameter 'fn' must be a function.",o);if(null===(a=B.get(a,null)))throw new e.package(`Parameter 'type' must be one of [${B.list.join(", ")}].`,o);const c=s?.chain??a.value=B.OVERRIDE.value){const t=d.get_fn_data(u).find((e=>e.type===B.OVERRIDE));if(t){if(f<=t.priority)throw new e.already_overridden(o,t.package_info,d,i);if(!1!==Hooks.call("libWrapper.OverrideLost",t.package_info.id,o.id,d.name,d.frozen_names)){LibWrapperConflicts.register_conflict(o,t.package_info,d,null,!1)&&LibWrapperNotifications.conflict(t.package_info,o,!1,`${o.type_plus_id_capitalized} has higher priority, and is replacing the 'OVERRIDE' registered by ${o.type_plus_id} for '${g}'.`)}}}let _={package_info:o,target:i,setter:u,fn:n,type:a,wrapper:d,priority:f,chain:c,perf_mode:l,bind:p};return d.add(_),o.id!=t&&Hooks.callAll("libWrapper.Register",o.id,"number"==typeof i?g:i,a,s,h),Log.info$?.(`Registered a wrapper for '${g}' (ID=${h}) by ${o.type_plus_id} with type ${a}.`),h}static unregister(r,i,n=!0){const a=de(r);if(r!=t&&!Q)throw new e.package("Not allowed to unregister wrappers before the 'libWrapper.Ready' hook fires",a);if("string"!=typeof i&&"number"!=typeof i)throw new e.package("Parameter 'target' must be a number or a string.",a);const s=pe(a,i,n);if(!s)return;const o=s.wrapper.get_id(s.setter),c=s.wrapper.get_name(s.setter);a.id!=t&&Hooks.callAll("libWrapper.Unregister",a.id,"number"==typeof i?c:i,o),Log.info$?.(`Unregistered the wrapper for '${c}' (ID=${o}) by ${a.type_plus_id}.`)}static unregister_all(r){const i=de(r);if(r!=t&&!Q)throw new e.package("Not allowed to unregister wrappers before the 'libWrapper.Ready' hook fires",i);Z.forEach((e=>{this.unregister(i.id,e.getter_id,!1),e.is_property&&this.unregister(i.id,e.setter_id,!1)})),i.id!=t&&Hooks.callAll("libWrapper.UnregisterAll",i.id),Log.info$?.(`Unregistered all wrapper functions by ${i.type_plus_id}.`)}static ignore_conflicts(r,i,n,a={}){const s=de(r);if(!Q)throw new e.package("Not allowed to ignore conflicts before the 'libWrapper.Ready' hook fires",s);Array.isArray(i)||(i=[i]),Array.isArray(n)||(n=[n]);const o=e=>"string"==typeof e;if(!i.every(o))throw new e.package("Parameter 'ignore_ids' must be a string, or an array of strings.",s);if(!n.every(o))throw new e.package("Parameter 'targets' must be a string, or an array of strings.",s);if(!n.every((e=>ne(e))))throw new e.package("Parameter 'targets' must only contain valid targets.",s);const c=a.ignore_errors??!1;if("boolean"!=typeof c)throw new e.package("Parameter 'options.ignore_errors' must be a boolean.",s);const l=i.map((e=>new PackageInfo(e))).filter((e=>e.exists));0!=l.length?(LibWrapperConflicts.register_ignore(s,l,n,c),s.id!=t&&Log.info$?.(`Ignoring conflicts involving ${s.type_plus_id} and [${l.map((e=>e.type_plus_id)).join(", ")}] for targets [${n.join(", ")}].`)):Log.debug$?.(`Ignoring 'ignore_conflict' call for ${s.type_plus_id} since none of the package IDs provided exist or are active.`)}}I(libWrapper$1),Object.freeze(libWrapper$1),delete globalThis.libWrapper,Object.defineProperty(globalThis,"libWrapper",{get:()=>libWrapper$1,set:t=>{throw new e.package("Not allowed to re-assign the global instance of libWrapper")},configurable:!1}),globalThis.addEventListener("error",j),globalThis.addEventListener("unhandledrejection",j),Hooks.onError?function(){try{libWrapper.register("lib-wrapper","Hooks.onError",(function(e,...t){const r=t[1];return C(r),e(...t)}),"WRAPPER",{perf_mode:"FAST"})}catch(e){LibWrapperNotifications.console_ui("A non-critical error occurred while initializing libWrapper.","Could not setup 'Hooks.onError' wrapper.\n",Log.WARNING,e)}}():function(){try{const e="() => function "+Hooks._call.toString(),t=e.replace(/catch[\s\n]*\((.*)\)[\s\n]*{/gim,"$& globalThis.libWrapper.onUnhandledError($1);");if(e===t)throw new Error(`Could not patch 'Hooks._call' method:\n${e}`);Log.debug$?.(`Patched Hooks._call: ${t}`);const r=W(t)?.();if("function"!=typeof r)throw new Error(`Evaluation of patched 'Hooks._call' method did not return a function:\nPatched Method: ${t}\nReturned: ${r}`);Hooks._call=r}catch(e){LibWrapperNotifications.console_ui("A non-critical error occurred while initializing libWrapper.","Could not setup 'Hooks._call' wrapper.\n",Log.WARNING,e)}try{libWrapper.register("lib-wrapper","Application.prototype._render",(function(e,...t){return e(...t).catch((e=>{throw C(e),e}))}),"WRAPPER",{perf_mode:"FAST"})}catch(e){LibWrapperNotifications.console_ui("A non-critical error occurred while initializing libWrapper.","Could not setup 'Application.prototype._render' wrapper.\n",Log.WARNING,e)}}();{let t,r;const i=L("libWrapperInit"),n={[i]:async function(e,...i){{const e=new PackageInfo("lib-wrapper",m.MODULE);pe(e,r,!0),pe(e,t,!0)}return Q=!0,await i18n.init(),LibWrapperSettings.init(),LibWrapperStats.init(),LibWrapperConflicts.init(),LibWrapperNotifications.init(),Log.fn(Log.ALWAYS,Log.INFO)(`Version ${H} ready.`),Hooks.callAll("libWrapper.Ready",libWrapper$1),e(...i)}};t=libWrapper$1.register("lib-wrapper","Game.prototype.initialize",n[i],libWrapper$1.WRAPPER,{perf_mode:libWrapper$1.PERF_FAST}),r=libWrapper$1.register("lib-wrapper","Game.toString",(function(){throw new e.package("Using 'Game.toString()' before libWrapper initialises is not allowed for compatibility reasons.")}),libWrapper$1.WRAPPER,{perf_mode:libWrapper$1.PERF_FAST}),Hooks.once("init",(()=>{if(!Q)throw new e.internal("Could not successfuly initialise libWrapper, likely due to a compatibility issue with another module.")}))}ee=!1;//# sourceMappingURL=lib-wrapper.js.map