@archivist-gg/dnd5e 0.3.29 → 0.3.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/background/background.codec.js +1 -1
  2. package/dist/background/background.parser.js +1 -1
  3. package/dist/background/background.schema.js +1 -1
  4. package/dist/chunk-34ZLX4TM.js +1 -0
  5. package/dist/{chunk-WXL7ABDO.js → chunk-3CHDDX6S.js} +1 -1
  6. package/dist/chunk-4F5F5A3X.js +1 -0
  7. package/dist/{chunk-OV4FG4KO.js → chunk-5NGQM3TO.js} +1 -1
  8. package/dist/{chunk-ADX7435T.js → chunk-655UY3MP.js} +1 -1
  9. package/dist/{chunk-IR5BA2DZ.js → chunk-65VM2BAA.js} +1 -1
  10. package/dist/{chunk-5QDSAZG6.js → chunk-6GFBSYE3.js} +1 -1
  11. package/dist/{chunk-J27N3KUE.js → chunk-6WRU5I75.js} +1 -1
  12. package/dist/{chunk-YWKC2LJY.js → chunk-73HBCVPD.js} +1 -1
  13. package/dist/{chunk-E4E6YEN6.js → chunk-7S4VMK3R.js} +1 -1
  14. package/dist/{chunk-EON7T2SN.js → chunk-7TH4WPSU.js} +1 -1
  15. package/dist/{chunk-EBFLUJIW.js → chunk-A25HLCQ7.js} +1 -1
  16. package/dist/{chunk-M2UA2FAK.js → chunk-FC4OPNZM.js} +1 -1
  17. package/dist/{chunk-7HOOPNF5.js → chunk-FDWQ6P7Z.js} +1 -1
  18. package/dist/{chunk-RR26E7LH.js → chunk-HI2BXTGB.js} +1 -1
  19. package/dist/{chunk-J6FIBUI4.js → chunk-HPBEMAM6.js} +1 -1
  20. package/dist/{chunk-NB4QWMF5.js → chunk-I6J6ZGZB.js} +1 -1
  21. package/dist/{chunk-GKNOCYDT.js → chunk-IK7XM6BW.js} +1 -1
  22. package/dist/{chunk-XFFFTR6O.js → chunk-IOFGBEGA.js} +1 -1
  23. package/dist/{chunk-U7BPRRY5.js → chunk-JLW7XFFL.js} +1 -1
  24. package/dist/{chunk-XCF5R5XX.js → chunk-JOLGJYDS.js} +1 -1
  25. package/dist/{chunk-NU6WP4P5.js → chunk-KGRRQ4US.js} +1 -1
  26. package/dist/chunk-KWETUSIQ.js +1 -0
  27. package/dist/chunk-LXISMSPG.js +1 -0
  28. package/dist/{chunk-2OVDSMPY.js → chunk-MJJQQI44.js} +1 -1
  29. package/dist/{chunk-D2BXAFOL.js → chunk-Q2U7MWMC.js} +1 -1
  30. package/dist/{chunk-AFEWQFQZ.js → chunk-QCCA46KM.js} +1 -1
  31. package/dist/{chunk-C4T6BUSP.js → chunk-RI4YYU75.js} +1 -1
  32. package/dist/{chunk-R2YRQM7G.js → chunk-TGZ6WQUX.js} +1 -1
  33. package/dist/{chunk-PFQPP77Q.js → chunk-YDN6GD2B.js} +1 -1
  34. package/dist/{chunk-VY5ZEOLG.js → chunk-Z362RQTB.js} +1 -1
  35. package/dist/{chunk-VHIE2KYQ.js → chunk-ZK3P4RSE.js} +1 -1
  36. package/dist/{chunk-CCFIINBA.js → chunk-ZKDHCDJ2.js} +1 -1
  37. package/dist/{chunk-DXJ5NKKB.js → chunk-ZYMWQ7PG.js} +1 -1
  38. package/dist/{chunk-KGZXAAFN.js → chunk-ZZ6QHLWX.js} +1 -1
  39. package/dist/class/class.codec.js +1 -1
  40. package/dist/class/class.parser.js +1 -1
  41. package/dist/class/class.schema.js +1 -1
  42. package/dist/class/class.slug.d.ts +1 -0
  43. package/dist/class/class.slug.js +1 -1
  44. package/dist/feat/feat.codec.js +1 -1
  45. package/dist/feat/feat.parser.js +1 -1
  46. package/dist/feat/feat.schema.d.ts +12 -0
  47. package/dist/feat/feat.schema.js +1 -1
  48. package/dist/index.js +17 -13
  49. package/dist/monster/monster.parser.js +1 -1
  50. package/dist/monster/monster.schema.js +1 -1
  51. package/dist/optional-feature/optional-feature.codec.js +1 -1
  52. package/dist/optional-feature/optional-feature.parser.js +1 -1
  53. package/dist/optional-feature/optional-feature.schema.d.ts +13 -0
  54. package/dist/optional-feature/optional-feature.schema.js +1 -1
  55. package/dist/pc/pc.additional-spells.js +1 -1
  56. package/dist/pc/pc.amount-bindings.d.ts +1 -0
  57. package/dist/pc/pc.amount-bindings.js +1 -1
  58. package/dist/pc/pc.decision-engine.js +1 -1
  59. package/dist/pc/pc.entry-overrides.js +1 -1
  60. package/dist/pc/pc.equipment.js +1 -1
  61. package/dist/pc/pc.feature-effects.d.ts +18 -0
  62. package/dist/pc/pc.feature-effects.js +1 -1
  63. package/dist/pc/pc.granted-spends.d.ts +2 -0
  64. package/dist/pc/pc.infusions.js +1 -1
  65. package/dist/pc/pc.item-effects.js +1 -1
  66. package/dist/pc/pc.member-choices.js +1 -1
  67. package/dist/pc/pc.pools.js +1 -1
  68. package/dist/pc/pc.proficiencies.js +1 -1
  69. package/dist/pc/pc.recalc.js +1 -1
  70. package/dist/pc/pc.resolver.js +1 -1
  71. package/dist/pc/pc.resource-seed.js +1 -1
  72. package/dist/pc/pc.resources.js +1 -1
  73. package/dist/pc/pc.rest.js +1 -1
  74. package/dist/pc/pc.schema.d.ts +1 -1
  75. package/dist/pc/pc.spellcasting.js +1 -1
  76. package/dist/pc/pc.types.d.ts +25 -0
  77. package/dist/race/race.codec.js +1 -1
  78. package/dist/race/race.parser.js +1 -1
  79. package/dist/race/race.schema.js +1 -1
  80. package/dist/schemas/choice-schema.js +1 -1
  81. package/dist/schemas/feature-effect-schema.d.ts +12 -0
  82. package/dist/schemas/feature-effect-schema.js +1 -1
  83. package/dist/schemas/feature-schema.js +1 -1
  84. package/dist/schemas/resource-schema.d.ts +1 -0
  85. package/dist/schemas/resource-schema.js +1 -1
  86. package/dist/spell/spell.access.js +1 -1
  87. package/dist/subclass/subclass.codec.js +1 -1
  88. package/dist/subclass/subclass.parser.js +1 -1
  89. package/dist/subclass/subclass.schema.js +1 -1
  90. package/dist/types/feature-effect.d.ts +10 -0
  91. package/dist/types/resource.d.ts +1 -0
  92. package/package.json +1 -1
  93. package/dist/chunk-53SHSS4M.js +0 -1
  94. package/dist/chunk-B2JSF2LL.js +0 -1
  95. package/dist/chunk-CAPYNIGK.js +0 -1
  96. package/dist/chunk-JSI2G6LE.js +0 -1
@@ -1 +1 @@
1
- import{backgroundCodec}from"../chunk-WXL7ABDO.js";import"../chunk-IR5BA2DZ.js";import"../chunk-XFFFTR6O.js";import"../chunk-TKIEPC6F.js";import"../chunk-VHIE2KYQ.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";export{backgroundCodec};
1
+ import{backgroundCodec}from"../chunk-3CHDDX6S.js";import"../chunk-65VM2BAA.js";import"../chunk-IOFGBEGA.js";import"../chunk-TKIEPC6F.js";import"../chunk-ZK3P4RSE.js";import"../chunk-7TH4WPSU.js";import"../chunk-I26FHSI6.js";export{backgroundCodec};
@@ -1 +1 @@
1
- import{parseBackground}from"../chunk-IR5BA2DZ.js";import"../chunk-XFFFTR6O.js";import"../chunk-TKIEPC6F.js";import"../chunk-VHIE2KYQ.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";export{parseBackground};
1
+ import{parseBackground}from"../chunk-65VM2BAA.js";import"../chunk-IOFGBEGA.js";import"../chunk-TKIEPC6F.js";import"../chunk-ZK3P4RSE.js";import"../chunk-7TH4WPSU.js";import"../chunk-I26FHSI6.js";export{parseBackground};
@@ -1 +1 @@
1
- import{backgroundEntitySchema,langProfSchema}from"../chunk-XFFFTR6O.js";import"../chunk-TKIEPC6F.js";import"../chunk-VHIE2KYQ.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";export{backgroundEntitySchema,langProfSchema};
1
+ import{backgroundEntitySchema,langProfSchema}from"../chunk-IOFGBEGA.js";import"../chunk-TKIEPC6F.js";import"../chunk-ZK3P4RSE.js";import"../chunk-7TH4WPSU.js";import"../chunk-I26FHSI6.js";export{backgroundEntitySchema,langProfSchema};
@@ -0,0 +1 @@
1
+ import{equipmentCategoryKey,isCategoryGrant}from"./chunk-2EOGK6R6.js";import{withSubspeciesParent}from"./chunk-4AJYEWFQ.js";import{TOOL_CATEGORIES,backgroundToolPicks,categoryWords,classToolPicks,expandToolPool,toolCategoriesOf}from"./chunk-RQZCGXUZ.js";import{replacementChoiceId,replacementDescription,replacementOwner,replacementPick}from"./chunk-CLZRWPWT.js";import{assembleEffectFeatures,classifyProficiencyEffect,collectProficiencyEffectGrants,foldsNow,selfEffectsOf}from"./chunk-KWETUSIQ.js";import{ALL_LANGUAGES,ALL_SKILL_SLUGS,ALL_TOOLS}from"./chunk-4JEF3CET.js";import{humanizeProficiency,proficiencyLabel,toProfSlug}from"./chunk-VTQ4RWEG.js";import{buildItemFeatures}from"./chunk-ZYMWQ7PG.js";import{classPactWeaponPick,featOfSite,featPickSites,isTargetChoice,memberChoices,pactWeaponPick,poolMemberSites,poolMemberSitesOf,raceFeatSites}from"./chunk-6WRU5I75.js";import{collectAdditionalSpells}from"./chunk-HI2BXTGB.js";import{resolveFeatureResources,resolveResourceIndex}from"./chunk-MJJQQI44.js";import{attributeUnclassedSpell,effectiveSpellcastingAbility,normalizeKnownSpell,resolveSpellcasting}from"./chunk-YDN6GD2B.js";import{convertibleLegacyAsi,flattenAsiOrFeat,resolveLegacyAsiFeat}from"./chunk-QVWT67WA.js";import{bindFeatureConsumers,buildInfusionContext,classOfSource,resolveAllPools,resolveOptionRows,storedSpellNumbers,strandedPicks,withoutStrandedSites}from"./chunk-7S4VMK3R.js";import{countColumnsFor,readTableColumn}from"./chunk-CSTAQQGX.js";import{recognizeDecision}from"./chunk-3LWOVRLA.js";import{isItemEntity,resolveEntityForEntry}from"./chunk-4IAMSRHD.js";import{FEATURE_TYPE_FOR_CATEGORY,featCategoryOf,featProgressionCategory}from"./chunk-3QQOATV3.js";import{warnOnce}from"./chunk-DZITM5AG.js";import{resolveBaseItem}from"./chunk-PZ4L2EEG.js";import{bucketOf}from"./chunk-QMEKQTUT.js";import{isValidMaxFormula}from"./chunk-EAARMPCW.js";import{bareEntitySlug,wikilinkTailSlug}from"./chunk-63YJPWTM.js";import{mirrorSpellShapes}from"./chunk-4KVVAENP.js";import{ABILITY_KEYS,ALL_SKILLS}from"./chunk-EVT7MGAC.js";import{withResolvedActionCost}from"./chunk-S5UCI27C.js";function attachGrantedSpends(features,classes){var _a;const moves=[];features.forEach((rf,i)=>{var _a2;const target=(_a2=rf.feature.consumes)==null?void 0:_a2.for_feature;if(!target)return;const candidates=features.map((t,j)=>({t,j})).filter(({t,j})=>j!==i&&t.feature.id===target&&!t.renderSuppressed&&!t.buildOnly);if(candidates.length===0)return;const own=classOfSource(rf.source,classes);const pick=own&&candidates.find(({t})=>classOfSource(t.source,classes)===own)||candidates[0];moves.push({from:i,to:pick.j})});if(moves.length===0)return features;const out=[...features];for(const{from,to}of moves){const grantor=out[from];const{consumes,...rest}=grantor.feature;if(!consumes)continue;const spend={...consumes};delete spend.for_feature;const granted={consumes:spend,name:grantor.feature.name,source:grantor.source};out[from]={...grantor,feature:rest};const holder=out[to];out[to]={...holder,grantedSpends:[...(_a=holder.grantedSpends)!=null?_a:[],granted]}}return out}var UNKNOWN_SOURCE="Unknown";var UNKNOWN_GRANT_SOURCE=UNKNOWN_SOURCE;function grantSourceName(resolved,kind,slug){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r;switch(kind){case"class":return(_d=(_c=(_b=(_a=resolved.classes)==null?void 0:_a.find(c=>{var _a2;return((_a2=c.entity)==null?void 0:_a2.slug)===slug}))==null?void 0:_b.entity)==null?void 0:_c.name)!=null?_d:UNKNOWN_SOURCE;case"subclass":return(_h=(_g=(_f=(_e=resolved.classes)==null?void 0:_e.find(c=>{var _a2;return((_a2=c.subclass)==null?void 0:_a2.slug)===slug}))==null?void 0:_f.subclass)==null?void 0:_g.name)!=null?_h:UNKNOWN_SOURCE;case"race":return(_j=(_i=resolved.race)==null?void 0:_i.name)!=null?_j:UNKNOWN_SOURCE;case"background":return(_l=(_k=resolved.background)==null?void 0:_k.name)!=null?_l:UNKNOWN_SOURCE;case"feat":return(_o=(_n=(_m=resolved.feats)==null?void 0:_m.find(f=>f.slug===slug))==null?void 0:_n.name)!=null?_o:UNKNOWN_SOURCE;case"item":return(_r=(_q=(_p=resolved.itemFeatures)==null?void 0:_p.find(f=>f.source.slug===slug))==null?void 0:_q.feature.name)!=null?_r:UNKNOWN_SOURCE;default:return UNKNOWN_SOURCE}}function collectProficiencyGrants(resolved){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x;const classArmor=[];const classWeaponFixed=[];const classWeaponCategories=[];const classToolFixed=[];for(const c of resolved.classes){const prof=(_a=c.entity)==null?void 0:_a.proficiencies;if(!prof)continue;const source=(_c=(_b=c.entity)==null?void 0:_b.name)!=null?_c:UNKNOWN_SOURCE;for(const a of(_d=prof.armor)!=null?_d:[])classArmor.push({value:a,source});for(const w of(_f=(_e=prof.weapons)==null?void 0:_e.fixed)!=null?_f:[])classWeaponFixed.push({value:w,source});for(const w of(_h=(_g=prof.weapons)==null?void 0:_g.categories)!=null?_h:[])classWeaponCategories.push({value:w,source});for(const t of(_j=(_i=prof.tools)==null?void 0:_i.fixed)!=null?_j:[])classToolFixed.push({value:t,source});for(const t of classToolPicks(c.entity).grants)classToolFixed.push({value:t,source})}const raceSource=(_l=(_k=resolved.race)==null?void 0:_k.name)!=null?_l:UNKNOWN_SOURCE;const raceLangFixed=((_o=(_n=(_m=resolved.race)==null?void 0:_m.languages)==null?void 0:_n.fixed)!=null?_o:[]).map(l=>({value:l,source:raceSource}));const bgToolFixed=[];const bgLangFixed=[];const bg=resolved.background;if(bg){const source=(_p=bg.name)!=null?_p:UNKNOWN_SOURCE;for(const entry of(_q=bg.tool_proficiencies)!=null?_q:[]){if(entry.kind==="fixed"){for(const t of entry.items)bgToolFixed.push({value:t,source})}}for(const t of backgroundToolPicks(bg).grants)bgToolFixed.push({value:t,source});for(const entry of(_r=bg.language_proficiencies)!=null?_r:[]){if(entry.kind==="fixed"){for(const l of entry.languages)bgLangFixed.push({value:l,source})}}}const featArmor=[];const featWeapons=[];const featTools=[];const featLanguages=[];for(const f of(_s=resolved.feats)!=null?_s:[]){const featView=f;const grants=featView.proficiencies;if(!grants)continue;const source=(_t=f.name)!=null?_t:UNKNOWN_SOURCE;for(const a of(_u=grants.armor)!=null?_u:[])featArmor.push({value:a,source});for(const w of(_v=grants.weapons)!=null?_v:[])featWeapons.push({value:w,source});for(const t of(_w=grants.tools)!=null?_w:[])featTools.push({value:t,source});for(const l of(_x=grants.languages)!=null?_x:[])featLanguages.push({value:l,source})}const{features:effectFeatures,activeBuffs}=assembleEffectFeatures(resolved);const fx=collectProficiencyEffectGrants(effectFeatures,activeBuffs);const nameFor=(kind,slug)=>grantSourceName(resolved,kind,slug);const toGrants=(list,useRaw)=>list.map(g=>({value:useRaw?g.raw:g.value,source:nameFor(g.sourceKind,g.sourceSlug),...g.expertise?{expertise:true}:{}}));const effectArmor=toGrants(fx.armor,true);const effectWeapons=toGrants(fx.weapons,true);const effectTools=toGrants(fx.tools,false);const effectLanguages=toGrants(fx.languages,false);return{classArmor,classWeaponFixed,classWeaponCategories,classToolFixed,raceLangFixed,bgToolFixed,bgLangFixed,featArmor,featWeapons,featTools,featLanguages,effectArmor,effectWeapons,effectTools,effectLanguages}}function inventoryOptions(resolved,registry,entityType){var _a,_b,_c,_d;const out=[];const seen=new Set;const find=ref=>{var _a2,_b2;const withSlug=registry;if(typeof withSlug.getBySlug==="function")return resolveBaseItem(ref,withSlug);const bare=ref.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].trim();return(_b2=(_a2=registry.getByTypeAndSlug(entityType,bare))!=null?_a2:registry.getByTypeAndSlug("item",bare))!=null?_b2:null};for(const entry of(_b=(_a=resolved.definition)==null?void 0:_a.equipment)!=null?_b:[]){if(typeof entry.item!=="string")continue;const e=find(entry.item);if(!e||seen.has(e.slug))continue;const value=e.slug;const base=e.entityType===entityType?e:typeof e.data.base_item==="string"?find(e.data.base_item):null;if(!base||base.entityType!==entityType)continue;seen.add(value);const name=(_d=(_c=entry.overrides)==null?void 0:_c.name)!=null?_d:e.name;out.push({value,label:name,entity:e})}return out}var warnedDegradedEquipment=new Set;var warnedAmbiguousBare=new Set;var foldedTypeMemo=new Map;function foldedType(s){let v=foldedTypeMemo.get(s);if(v===void 0){v=categoryWords(s).join(" ");foldedTypeMemo.set(s,v)}return v}function matchesFilter(e,where,ownerBare){var _a,_b,_c,_d,_e,_f;const d=e.data;if(where.feature_type&&d.feature_type!==where.feature_type)return false;if(where.category&&featCategoryOf((_a=d.category)!=null?_a:"")!==featCategoryOf(where.category))return false;if(where.list&&!((_b=d.classes)!=null?_b:[]).includes(where.list))return false;if(where.level!==void 0&&((_c=d.level)!=null?_c:0)!==where.level)return false;if(where.edition&&d.edition!==where.edition)return false;if(where.ritual&&d.ritual!==true)return false;if(where.weapon_category){const cat=((_d=d.category)!=null?_d:"").toLowerCase();if(!cat.startsWith(`${where.weapon_category}-`)&&cat!==where.weapon_category)return false}if(where.armor_category){if(((_e=d.category)!=null?_e:"").toLowerCase()!==where.armor_category)return false}if(where.item_type){const t=foldedType(typeof d.type==="string"?d.type:"");if(!t||!where.item_type.some(x=>foldedType(x)===t))return false}if(where.mundane){const r=typeof d.rarity==="string"?d.rarity.trim().toLowerCase():"";if(r&&r!=="none"&&r!=="mundane")return false}if(where.parent_class==="self"){if(!d.parent_class||wikilinkTailSlug(d.parent_class)!==ownerBare)return false}if(where.available_to==="self"){const list=(_f=d.available_to)!=null?_f:[];if(!list.some(l=>wikilinkTailSlug(l)===ownerBare))return false}return true}var __matchesFilterForTest=matchesFilter;function parseEquipmentCategory(category){const tools=toolCategoriesOf(category);if(tools)return{kind:"tool",tools};const words=categoryWords(category).filter(w=>w!=="any");const has=w=>words.includes(w);const only=allowed=>words.every(w=>allowed.includes(w));if(words.length===1&&has("shield"))return{kind:"shield"};if(has("armor")&&only(["armor","light","medium","heavy"])&&words.length<=2){const armor=["light","medium","heavy"].find(k=>has(k));return{kind:"armor",armor}}if(has("weapon")&&only(["weapon","simple","martial","melee","ranged"])){const klass=["simple","martial"].filter(k=>has(k));const range=["melee","ranged"].filter(k=>has(k));if(klass.length===1&&range.length<=1&&words.length===2+range.length){return{kind:"weapon",weapon:klass[0],range:range[0]}}}return void 0}function categoryToEntitySelect(category,id){const spec=parseEquipmentCategory(category);const pick={kind:"select-entity",id,count:1};switch(spec==null?void 0:spec.kind){case"shield":return{...pick,label:"Choose a shield",entity_type:"armor",where:{armor_category:"shield"}};case"armor":return spec.armor?{...pick,label:`Choose ${spec.armor} armor`,entity_type:"armor",where:{armor_category:spec.armor}}:{...pick,label:"Choose armor",entity_type:"armor"};case"weapon":return{...pick,label:`Choose a ${spec.weapon}${spec.range?` ${spec.range}`:""} weapon`,entity_type:"weapon",where:{weapon_category:spec.weapon}};case"tool":return{...pick,label:`Choose ${spec.tools.map(t=>TOOL_CATEGORIES[t].label).join(" or ")}`,entity_type:"item",where:{item_type:spec.tools.map(t=>TOOL_CATEGORIES[t].itemType),mundane:true}};default:warnOnce(`equipment-category:${category}`,`Archivist: starting-equipment category "${category}" is not a known item category; its pick offers no options.`);return{...pick,label:`Choose a ${category.replace(/[-_]+/g," ")}`,entity_type:"item",from:[]}}}var __categoryToEntitySelectForTest=categoryToEntitySelect;function equipmentDecisions(entries,ownerSlug){const out=[];let degraded=false;(entries!=null?entries:[]).forEach((eq,i)=>{var _a;if((eq==null?void 0:eq.kind)!=="choice")return;const options=(_a=eq.options)!=null?_a:[];out.push({kind:"select-inline",id:`equipment-${i}`,label:"Starting Equipment",count:1,options:options.map((opt,j)=>{var _a2;const label=typeof opt==="string"?opt:(_a2=opt==null?void 0:opt.label)!=null?_a2:"";const wellFormed=!!opt&&typeof opt==="object"&&Array.isArray(opt.grants);if(!wellFormed)degraded=true;const grants=wellFormed?opt.grants:[];return{value:`option-${j}`,label,choices:grants.flatMap((g,k)=>isCategoryGrant(g)?[categoryToEntitySelect(g.category,equipmentCategoryKey(i,j,k))]:[])}})})});if(degraded&&!warnedDegradedEquipment.has(ownerSlug)){warnedDegradedEquipment.add(ownerSlug);console.warn(`[archivist] Starting equipment for "${ownerSlug}" is in an outdated/unstructured format; its nested picks and seeding are skipped. Re-sync the compendium (delete _compendium.md and reload) to fix.`)}return out}function authoredProficiencyPool(choice){if(!choice.from)return void 0;return choice.domain==="tool"?expandToolPool(choice.from):choice.from}function enumerateOptions(choice,ctx,ownerBare){var _a,_b;switch(choice.kind){case"select-inline":return choice.options.map(o=>({value:o.value,label:o.label,description:o.description}));case"select-entity":{if(choice.from){let byBare;const bareIndex=()=>{var _a2,_b2,_c,_d;if(byBare)return byBare;const built=new Map;const pool=ctx.registry.search("",choice.entity_type,Number.POSITIVE_INFINITY).slice().sort((a,b)=>a.name.localeCompare(b.name)||a.slug.localeCompare(b.slug));const seed=e=>{const bare=bareEntitySlug(e.slug);if(built.has(bare)){if(!warnedAmbiguousBare.has(bare)){warnedAmbiguousBare.add(bare);console.warn(`Archivist: bare slug "${bare}" matches multiple ${choice.entity_type} entities; using "${built.get(bare).slug}"`)}return}built.set(bare,e)};for(const e of pool)if((_b2=(_a2=ctx.isEntityVisible)==null?void 0:_a2.call(ctx,e))!=null?_b2:true)seed(e);for(const e of pool)if(!((_d=(_c=ctx.isEntityVisible)==null?void 0:_c.call(ctx,e))!=null?_d:true))seed(e);byBare=built;return built};return choice.from.map(slug=>{var _a2;const e=(_a2=ctx.registry.getByTypeAndSlug(choice.entity_type,slug))!=null?_a2:bareIndex().get(slug);return e?{value:e.slug,label:e.name,entity:e}:{value:slug,label:slug,missing:true}})}const all=ctx.registry.search("",choice.entity_type,Number.POSITIVE_INFINITY);const filtered=choice.where?all.filter(e=>matchesFilter(e,choice.where,ownerBare)):all;return filtered.map(e=>({value:e.slug,label:e.name,entity:e}))}case"select-proficiency":{const pool=(_a=authoredProficiencyPool(choice))!=null?_a:choice.domain==="skill"?[...ALL_SKILL_SLUGS]:choice.domain==="language"?[...ALL_LANGUAGES]:choice.domain==="tool"?[...ALL_TOOLS]:[];return pool.map(v=>({value:v,label:humanizeProficiency(v)}))}case"ability-points":{const pool=(_b=choice.pool)!=null?_b:["str","dex","con","int","wis","cha"];return pool.map(a=>({value:a,label:a.toUpperCase()}))}}}function selectionCount(choice,selected){if(selected===void 0)return 0;if(choice.kind==="ability-points"){if(typeof selected!=="object"||Array.isArray(selected))return 0;return Object.values(selected).reduce((s,v)=>s+(typeof v==="number"?v:0),0)}if(Array.isArray(selected))return selected.length;return typeof selected==="string"&&selected.length>0?1:0}function requiredCount(choice){var _a;if(choice.kind==="ability-points")return choice.points;if(choice.kind==="select-proficiency")return choice.count;return(_a=choice.count)!=null?_a:1}function capAtCount(choice,value){const folds=choice.kind==="select-proficiency"||choice.kind==="select-entity"&&choice.entity_type==="weapon"&&choice.id!=="weapon-mastery"&&!isTargetChoice(choice);if(!folds||!Array.isArray(value))return value;const n=requiredCount(choice);return value.length>n?value.slice(0,n):value}function statusOf(choice,selected,satisfied){const n=selectionCount(choice,selected);const need=requiredCount(choice);if(satisfied)return"resolved";if(n===0)return"unresolved";return n>=need?"resolved":"partial"}var matchPool=(v,pool)=>pool.find(p=>toProfSlug(p)===toProfSlug(v));var canonicalizeSelection=(value,pool)=>{var _a;if(typeof value==="string")return(_a=matchPool(value,pool))!=null?_a:value;if(Array.isArray(value))return value.map(v=>{var _a2;return(_a2=matchPool(v,pool))!=null?_a2:v});return value};function resolveEntityRef(ctx,entityType,value){if(typeof value!=="string"||value.length===0)return void 0;const raw=value.replace(/^\[\[/,"").replace(/\]\]$/,"");const direct=ctx.registry.getByTypeAndSlug(entityType,raw);if(direct)return direct;for(const e of ctx.registry.search("",entityType,Number.POSITIVE_INFINITY)){if(e.slug===raw||bareEntitySlug(e.slug)===raw)return e}return void 0}function buildItem(inputChoice,source,level,featureName,readValue,ctx,ownerBare,effective,opts){var _a,_b,_c,_d,_e;const choice=flattenAsiOrFeat(inputChoice);const keyPrefix=(_a=opts==null?void 0:opts.keyPrefix)!=null?_a:"";const expandFeatChildren=(_b=opts==null?void 0:opts.expandFeatChildren)!=null?_b:true;const key=keyPrefix+choice.id;const raw=capAtCount(choice,readValue(key));const preExclusionOptions=choice.kind==="select-entity"&&((_c=choice.where)==null?void 0:_c.inventory)===true?effective.inventory(choice.entity_type):enumerateOptions(choice,ctx,ownerBare);let options=preExclusionOptions;const mine=new Set((Array.isArray(raw)?raw:raw===void 0?[]:[raw]).map(v=>toProfSlug(String(v))));if(choice.kind==="select-proficiency"&&choice.domain==="skill"&&choice.from_proficient){options=options.filter(o=>effective.skill.has(toProfSlug(o.value))||mine.has(toProfSlug(o.value)))}const postInclusionOptions=options;const excludes=choice.kind==="select-proficiency"&&(choice.domain==="language"||choice.domain==="tool"||choice.domain==="skill"&&choice.expertise===true);if(excludes&&choice.kind==="select-proficiency"){const known=choice.domain==="skill"?effective.skillExpertise:effective[choice.domain];options=options.filter(o=>!known.has(toProfSlug(o.value))||mine.has(toProfSlug(o.value)))}const satisfied=excludes&&postInclusionOptions.length>0&&options.length===0;const selected=choice.kind==="select-proficiency"?canonicalizeSelection(raw,options.map(o=>o.value)):raw;const item={key,source,level,featureName,choice,description:opts==null?void 0:opts.description,options,selected,status:statusOf(choice,selected,satisfied),satisfied};if(choice.kind==="select-inline"&&typeof selected==="string"){const branch=choice.options.find(o=>o.value===selected);if((_d=branch==null?void 0:branch.choices)==null?void 0:_d.length){item.children=branch.choices.map(c=>buildItem(c,source,level,featureName,readValue,ctx,ownerBare,effective,{keyPrefix,expandFeatChildren}));if(item.status==="resolved"&&item.children.some(c=>c.status!=="resolved")){item.status="partial"}}}if(choice.kind==="select-entity"&&choice.entity_type==="feat"&&expandFeatChildren&&typeof selected==="string"){const entity=resolveEntityRef(ctx,"feat",selected);const rawChoices=(_e=entity==null?void 0:entity.data)==null?void 0:_e.choices;const featChoices=Array.isArray(rawChoices)?rawChoices:[];if(featChoices.length){const childPrefix=`${keyPrefix}feat:`;item.children=featChoices.map(c=>buildItem(c,source,level,featureName,readValue,ctx,ownerBare,effective,{keyPrefix:childPrefix,expandFeatChildren:false}));if(item.status==="resolved"&&item.children.some(c=>c.status!=="resolved")){item.status="partial"}}}return item}function buildSubclassItem(choice,source,level,featureName,c,ctx,ownerBare,description){const selected=c.subclass?c.subclass.slug:void 0;return{key:"subclass",source,level,featureName,description,choice,options:enumerateOptions(choice,ctx,ownerBare),selected,status:selected?"resolved":"unresolved",satisfied:false}}function visitProficiencyChoices(resolved,visit){var _a,_b,_c,_d,_e,_f;const walk=(choices,read,owner,kind)=>{for(const ch of choices!=null?choices:[]){visit(ch,read(ch.id),owner,kind);if(ch.kind==="select-inline"){const sel=read(ch.id);const branch=typeof sel==="string"?ch.options.find(o=>o.value===sel):void 0;if(branch==null?void 0:branch.choices)walk(branch.choices,read,owner,kind)}}};const oc=(_a=resolved.definition.origin_choices)!=null?_a:{};const originRead=ns=>id=>oc[`${ns}:${id}`];const stripRef=ref=>ref.replace(/^\[\[/,"").replace(/\]\]$/,"");const featBySlug=new Map(((_b=resolved.feats)!=null?_b:[]).map(f=>[f.slug,f]));const memberSites=poolMemberSitesOf(resolved);const featSites=featPickSites(resolved.classes,memberSites,ci=>{var _a2,_b2,_c2,_d2;return(_d2=(_c2=(_b2=(_a2=resolved.classes)==null?void 0:_a2[ci])==null?void 0:_b2.entity)==null?void 0:_c2.slug)!=null?_d2:null});resolved.classes.forEach((c,i)=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g,_h;if(!c.entity)return;const entity=c.entity;const readAt=lvl=>id=>{var _a3;return(_a3=c.choices[lvl])==null?void 0:_a3[id]};const className=entity.name;if(i===0&&((_b2=(_a2=entity.skill_choices)==null?void 0:_a2.from)==null?void 0:_b2.length)){visit({kind:"select-proficiency",id:"skills",count:entity.skill_choices.count,domain:"skill",from:entity.skill_choices.from},readAt(1)("skills"),className,"class")}if(i===0)walk(entity.choices,readAt(1),className,"class");if(i===0)walk(classToolPicks(entity).decisions,readAt(1),className,"class");for(const rf of resolved.features){if(rf.source.kind!=="class"&&rf.source.kind!=="subclass")continue;const belongs=rf.source.kind==="class"?rf.source.slug===entity.slug:c.subclass!=null&&rf.source.slug===c.subclass.slug;if(!belongs)continue;const featureOwner=rf.source.kind==="subclass"?(_d2=(_c2=c.subclass)==null?void 0:_c2.name)!=null?_d2:className:className;for(const copy of(_e2=rf.foldedFrom)!=null?_e2:[])walk(copy.choices,readAt(copy.level),featureOwner,"class");walk(rf.feature.choices,readAt(rf.source.level),featureOwner,"class")}for(const site of featSites){if(site.classIndex!==i)continue;const feat=(_g=featBySlug.get(stripRef(site.slug)))!=null?_g:featOfSite(site,(_f2=resolved.feats)!=null?_f2:[]);if(!feat)continue;walk(feat.choices,site.read,feat.name,"feat")}for(const site of memberSites)if(site.classIndex===i)walk(site.choices,site.read,(_h=site.member.name)!=null?_h:className,"class")});if(resolved.race){const raceName=resolved.race.name;walk(resolved.race.choices,originRead("race"),raceName,"race");for(const t of(_c=resolved.race.traits)!=null?_c:[])walk(t.choices,originRead("race"),raceName,"race")}if(resolved.background){const bgName=resolved.background.name;walk(resolved.background.choices,originRead("background"),bgName,"background");walk(backgroundToolPicks(resolved.background).decisions,originRead("background"),bgName,"background");if(resolved.background.feature){const feature=resolved.background.feature;walk(feature.choices,originRead("background"),bgName,"background")}}for(const r of(_d=resolved.proficiencyReplacements)!=null?_d:[]){walk([r.choice],originRead(r.carrier.kind),replacementOwner(r),r.carrier.kind)}if(resolved.originFeatSlug){const of=featBySlug.get(resolved.originFeatSlug);if(of)walk(of.choices,id=>oc[`background:feat:${id}`],of.name,"feat")}for(const site of raceFeatSites(resolved.race,oc)){const rf=(_f=featBySlug.get(stripRef(site.slug)))!=null?_f:((_e=resolved.feats)!=null?_e:[]).find(f=>bareEntitySlug(f.slug)===bareEntitySlug(site.slug));if(rf)walk(rf.choices,site.read,rf.name,"feat")}}var filterToPool=(vals,pool)=>pool?vals.map(v=>matchPool(v,pool)).filter(v=>!!v):vals;function collectChosenProficiencies(resolved){const out={skills:[],expertise:[],languages:[],tools:[],weapons:[],saves:[]};forEachChosenProficiency(resolved,(bucket,value)=>{const list=out[bucket];if(!list.includes(value))list.push(value)});return out}function forEachChosenProficiency(resolved,on){const isAbility=v=>ABILITY_KEYS.includes(v);visitProficiencyChoices(resolved,(choice,stored,owner,ownerKind)=>{const selected=capAtCount(choice,stored);const vals=Array.isArray(selected)?selected:typeof selected==="string"?[selected]:[];if(choice.kind==="select-entity"&&choice.entity_type==="weapon"){if(choice.id==="weapon-mastery"||isTargetChoice(choice))return;for(const v of vals){const bare=bareEntitySlug(String(v));if(bare)on("weapons",bare,owner,ownerKind)}return}if(choice.kind!=="select-proficiency")return;const valid=filterToPool(vals,authoredProficiencyPool(choice));if(choice.domain==="save"){for(const v of valid)if(isAbility(v))on("saves",v,owner,ownerKind);return}const bucket=choice.domain==="skill"?choice.expertise?"expertise":"skills":choice.domain==="language"?"languages":choice.domain==="tool"?"tools":null;if(bucket)for(const v of valid)on(bucket,v,owner,ownerKind)})}function collectRuleProficiencySources(resolved){var _a,_b,_c,_d;const out={skills:{},expertise:{},saves:{}};const add=(rec,key,source)=>{var _a2;const list=(_a2=rec[key])!=null?_a2:rec[key]=[];if(!list.includes(source))list.push(source)};const firstClass=(_b=(_a=resolved.classes)==null?void 0:_a[0])==null?void 0:_b.entity;if(firstClass)for(const ab of(_c=firstClass.saving_throws)!=null?_c:[])add(out.saves,ab,firstClass.name);const bg=resolved.background;const replaced=new Set(pickedReplacements(resolved).map(({r})=>`${r.carrier.kind}:${r.domain}:${r.value}`));if(bg)for(const sk of(_d=bg.skill_proficiencies)!=null?_d:[]){if(!replaced.has(`background:skill:${toProfSlug(sk)}`))add(out.skills,sk,bg.name)}forEachChosenProficiency(resolved,(bucket,value,owner)=>{if(bucket==="skills"||bucket==="expertise"||bucket==="saves")add(out[bucket],value,owner)});const{features,activeBuffs}=assembleEffectFeatures(resolved);for(const rf of features){if(!foldsNow(rf,activeBuffs))continue;for(const eff of selfEffectsOf(rf.feature)){const c=classifyProficiencyEffect(eff);if(!c||c.bucket!=="skills"&&c.bucket!=="saves")continue;if(c.bucket==="skills"&&!c.expertise&&replaced.has(`${rf.source.kind}:skill:${toProfSlug(c.value)}`))continue;const named=grantSourceName(resolved,rf.source.kind,rf.source.slug);const source=named===UNKNOWN_GRANT_SOURCE?rf.feature.name:named;if(c.bucket==="saves")add(out.saves,c.value,source);else add(c.expertise?out.expertise:out.skills,c.value,source)}}return out}function pickedReplacements(resolved){var _a,_b;const oc=(_a=resolved.definition)==null?void 0:_a.origin_choices;const out=[];for(const r of(_b=resolved.proficiencyReplacements)!=null?_b:[]){const pick=replacementPick(r,oc);if(pick)out.push({r,pick})}return out}var STEP_RANK={race:0,class:1,background:2,other:3};var stepOf=k=>k==="race"?"race":k==="background"?"background":k==="class"||k==="subclass"?"class":"other";function collectProficiencyReplacements(resolved){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l;const base={...resolved,proficiencyReplacements:void 0};const bg=base.background;const race=base.race;if(!bg&&!race)return[];const grants={skill:new Map,tool:new Map};const note=(domain,raw,g)=>{var _a2;if(typeof raw!=="string"||!raw.trim())return;const v=toProfSlug(raw);const list=(_a2=grants[domain].get(v))!=null?_a2:[];if(!list.some(x=>x.step===g.step&&x.name===g.name&&x.fixed===g.fixed))list.push(g);grants[domain].set(v,list)};const strings=v=>Array.isArray(v)?v:[];const{features,activeBuffs}=assembleEffectFeatures(base);const fx=collectProficiencyEffectGrants(features,activeBuffs);const effectName=g=>grantSourceName(base,g.sourceKind,g.sourceSlug);for(const g of fx.skills)if(!g.expertise)note("skill",g.value,{name:effectName(g),step:stepOf(g.sourceKind),fixed:true});for(const g of fx.tools)note("tool",g.value,{name:effectName(g),step:stepOf(g.sourceKind),fixed:true});if(bg){for(const sk of strings(bg.skill_proficiencies))note("skill",sk,{name:bg.name,step:"background",fixed:true});for(const e of strings(bg.tool_proficiencies)){if(e&&typeof e==="object"&&e.kind==="fixed"){for(const t of strings(e.items))note("tool",t,{name:bg.name,step:"background",fixed:true})}}for(const t of backgroundToolPicks(bg).grants)note("tool",t,{name:bg.name,step:"background",fixed:true})}const carried=[...grants.skill.values(),...grants.tool.values()].some(list=>list.some(g=>g.fixed&&(g.step==="race"||g.step==="background")));if(!carried)return[];for(const c of(_a=base.classes)!=null?_a:[]){const e=c.entity;if(!e)continue;const tools=(_b=e.proficiencies)==null?void 0:_b.tools;for(const t of[...strings(tools==null?void 0:tools.fixed),...classToolPicks(e).grants])note("tool",t,{name:e.name,step:"class",fixed:true})}for(const f of(_c=base.feats)!=null?_c:[]){const tools=(_d=f.proficiencies)==null?void 0:_d.tools;for(const t of strings(tools))note("tool",t,{name:f.name,step:"other",fixed:true})}forEachChosenProficiency(base,(bucket,value,owner,kind)=>{if(bucket==="skills")note("skill",value,{name:owner,step:stepOf(kind),fixed:false});else if(bucket==="tools")note("tool",value,{name:owner,step:stepOf(kind),fixed:false})});const held={skill:new Set([...(_g=(_f=(_e=base.definition)==null?void 0:_e.skills)==null?void 0:_f.proficient)!=null?_g:[],...(_j=(_i=(_h=base.definition)==null?void 0:_h.skills)==null?void 0:_i.expertise)!=null?_j:[],...fx.skills.map(g=>g.value),...grants.skill.keys(),...collectChosenProficiencies(base).expertise].map(toProfSlug)),tool:new Set};let toolsHeld=false;const heldTools=()=>{if(!toolsHeld){toolsHeld=true;for(const e of computeEffectiveProficiencies(base).tools)held.tool.add(toProfSlug(e.value))}return held.tool};const candidates=[];const skillOrder=v=>{const i=ALL_SKILL_SLUGS.indexOf(v);return i<0?999:i};for(const domain of["skill","tool"]){const entries=[...grants[domain].entries()];if(domain==="skill")entries.sort(([a],[b])=>skillOrder(a)-skillOrder(b));for(const[value,list]of entries){const sources=[];for(const g of[...list].sort((a,b)=>STEP_RANK[a.step]-STEP_RANK[b.step])){if(!sources.some(x=>x.step===g.step&&x.name===g.name))sources.push(g)}const names=keep=>[...new Set(sources.filter(keep).map(g=>g.name))];const label=domain==="skill"?(_k=ALL_SKILLS.find(d=>toProfSlug(d)===value))!=null?_k:humanizeProficiency(value):humanizeProficiency(value);const id=replacementChoiceId(domain,value);const bgCarries=!!bg&&list.some(g=>g.step==="background"&&g.fixed)&&names(g=>g.step!=="background").length>0;if(bg&&bgCarries){candidates.push({domain,value,label,id,carrier:{kind:"background",slug:bg.slug,name:bg.name},others:names(g=>g.step!=="background")})}const raceOthers=names(g=>g.step!=="race"&&!(bgCarries&&g.step==="background"));if(race&&list.some(g=>g.step==="race"&&g.fixed)&&raceOthers.length>0){candidates.push({domain,value,label,id,carrier:{kind:"race",slug:race.slug,name:race.name},others:raceOthers})}}}const oc=(_l=base.definition)==null?void 0:_l.origin_choices;const picks=candidates.map(c=>replacementPick({carrier:c.carrier,choice:{id:c.id}},oc));return candidates.map((c,i)=>{const vocab=c.domain==="skill"?ALL_SKILL_SLUGS:ALL_TOOLS;const taken=new Set(picks.filter((p,j)=>j!==i&&p&&candidates[j].domain===c.domain));const own=picks[i];const have=c.domain==="skill"?held.skill:heldTools();const from=vocab.filter(v=>v===own||!have.has(v)&&!taken.has(v));const{id,...rest}=c;return{...rest,choice:{kind:"select-proficiency",id,label:`Already proficient in ${c.label}: pick a replacement`,count:1,domain:c.domain,from}}})}function proficiencyEntryFor(raw,vocab,origin,sources,expertise){const hit=matchPool(raw,vocab);const value=hit?toProfSlug(hit):raw;const label=hit?humanizeProficiency(value):origin==="custom"?raw:proficiencyLabel(raw);return{value,label,sources,origin,...expertise?{expertise:true}:{}}}function computeEffectiveProficiencies(resolved){const c=composeLanguageToolProficiencies(resolved);return{languages:c.languages.kept,tools:c.tools.kept}}function computeSuppressedProficiencies(resolved){const c=composeLanguageToolProficiencies(resolved);return{languages:c.languages.suppressed,tools:c.tools.suppressed}}function composeLanguageToolProficiencies(resolved){const grants=collectProficiencyGrants(resolved);const chosen=collectChosenProficiencies(resolved);const build=domain=>{var _a,_b,_c,_d,_e,_f,_g,_h;const vocab=domain==="languages"?ALL_LANGUAGES:ALL_TOOLS;const ov=(_b=(_a=resolved.definition)==null?void 0:_a.overrides)==null?void 0:_b[domain];const adds=(_c=ov==null?void 0:ov.add)!=null?_c:[];const removes=(_d=ov==null?void 0:ov.remove)!=null?_d:[];const byValue=new Map;const push=(raw,origin,source,expertise)=>{const probe=proficiencyEntryFor(raw,vocab,origin,source?[source]:[],expertise);const existing=byValue.get(probe.value);if(!existing){byValue.set(probe.value,probe);return}if(source&&!existing.sources.includes(source))existing.sources.push(source);if(expertise)existing.expertise=true;const rank={grant:0,pick:1,manual:2,custom:3};if(rank[origin]<rank[existing.origin])existing.origin=origin};const grantBuckets=domain==="languages"?[grants.raceLangFixed,grants.bgLangFixed,grants.featLanguages,grants.effectLanguages]:[grants.classToolFixed,grants.bgToolFixed,grants.featTools,grants.effectTools];const replacedTools=domain==="tools"?pickedReplacements(resolved).filter(({r})=>r.domain==="tool"):[];for(const b of grantBuckets)for(const g of b){if(replacedTools.some(({r})=>r.carrier.name===g.source&&r.value===toProfSlug(g.value)))continue;push(g.value,"grant",g.source,g.expertise)}for(const{r,pick}of replacedTools)push(pick,"pick",replacementOwner(r));for(const v of domain==="languages"?chosen.languages:chosen.tools)push(v,"pick");for(const v of adds)push(v,matchPool(v,vocab)?"manual":"custom");const triSuppressed=new Set;if(domain==="tools"){const tri=(_h=(_g=(_f=(_e=resolved.definition)==null?void 0:_e.overrides)==null?void 0:_f.tools)==null?void 0:_g.proficiency)!=null?_h:{};for(const[tool,state]of Object.entries(tri)){const key=toProfSlug(tool);if(state==="none"){triSuppressed.add(key);continue}let entry=[...byValue.values()].find(e=>toProfSlug(e.value)===key);if(!entry){push(tool,matchPool(tool,vocab)?"manual":"custom");entry=[...byValue.values()].find(e=>toProfSlug(e.value)===key)}if(!entry)continue;if(state==="expertise")entry.expertise=true;else delete entry.expertise}}const suppressed=new Set([...removes.map(r=>toProfSlug(r)),...triSuppressed]);const byLabel=(a,b)=>a.label<b.label?-1:a.label>b.label?1:0;const kept=[...byValue.values()].filter(e=>!suppressed.has(toProfSlug(e.value))).sort(byLabel);return{kept,suppressed:[...byValue.values()].filter(e=>suppressed.has(toProfSlug(e.value))).sort(byLabel)}};return{languages:build("languages"),tools:build("tools")}}function collectChosenAbilityPoints(resolved){var _a,_b,_c;const oc=(_a=resolved.definition.origin_choices)!=null?_a:{};const out={race:{},background:{}};const fold=(ns,choices)=>{var _a2;for(const ch of choices!=null?choices:[]){if(ch.kind!=="ability-points")continue;const raw=oc[`${ns}:${ch.id}`];if(!raw||typeof raw!=="object"||Array.isArray(raw))continue;let left=ch.points;for(const ab of ABILITY_KEYS){if(ch.pool&&!ch.pool.includes(ab))continue;const v=raw[ab];if(typeof v!=="number"||v<=0||left<=0)continue;const take=Math.min(v,ch.max_per,left);out[ns][ab]=((_a2=out[ns][ab])!=null?_a2:0)+take;left-=take}}};const race=resolved.race;if(race){fold("race",race.choices);for(const t of(_b=race.traits)!=null?_b:[])fold("race",t.choices)}const bg=resolved.background;if(bg){fold("background",bg.choices);fold("background",(_c=bg.feature)==null?void 0:_c.choices)}return out}function buildDecisionLedger(resolved,ctx){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n;const eff=computeEffectiveProficiencies(resolved);const chosen=collectChosenProficiencies(resolved);const{features,activeBuffs}=assembleEffectFeatures(resolved);const effectGrants=collectProficiencyEffectGrants(features,activeBuffs);const effective={language:new Set(eff.languages.map(e=>toProfSlug(e.value))),tool:new Set(eff.tools.map(e=>toProfSlug(e.value))),skill:new Set([...(_c=(_b=(_a=resolved.definition)==null?void 0:_a.skills)==null?void 0:_b.proficient)!=null?_c:[],...(_e=(_d=resolved.background)==null?void 0:_d.skill_proficiencies)!=null?_e:[],...chosen.skills,...effectGrants.skills.map(g=>g.value)].map(toProfSlug)),skillExpertise:new Set([...(_h=(_g=(_f=resolved.definition)==null?void 0:_f.skills)==null?void 0:_g.expertise)!=null?_h:[],...chosen.expertise,...effectGrants.skills.filter(g=>g.expertise).map(g=>g.value)].map(toProfSlug)),inventory:entityType=>inventoryOptions(resolved,ctx.registry,entityType)};const classes=[];resolved.classes.forEach((c,classIndex)=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h2,_i2,_j2,_k2,_l2,_m2,_n2,_o;if(!c.entity)return;const entity=c.entity;const ownerBare=bareEntitySlug(entity.slug);const byLevel=new Map;const push=(lvl,item)=>{var _a3;const arr=(_a3=byLevel.get(lvl))!=null?_a3:[];arr.push(item);byLevel.set(lvl,arr)};const readAt=lvl=>id=>{var _a3;return(_a3=c.choices[lvl])==null?void 0:_a3[id]};let legacyAsiFeat;const legacyAsiReader=(choice,lvl)=>{const alloc=convertibleLegacyAsi(c.choices[lvl]);if(!alloc)return null;const flat=flattenAsiOrFeat(choice);if(flat.kind!=="select-entity"||flat.entity_type!=="feat"||flat.from||flat.where)return null;if(legacyAsiFeat===void 0)legacyAsiFeat=resolveLegacyAsiFeat(ctx.registry,entity);const asi=legacyAsiFeat;if(!asi)return null;const raw=readAt(lvl);const childKey=`feat:${asi.childId}`;return id=>id==="feat"?asi.slug:id===childKey?alloc:raw(id)};const featProgressions=[...(_a2=entity.feat_progression)!=null?_a2:[],...(_c2=(_b2=c.subclass)==null?void 0:_b2.feat_progression)!=null?_c2:[]];const suppressedFeatureTypes=new Set;for(const decl of[...(_d2=entity.selection_pools)!=null?_d2:[],...(_f2=(_e2=c.subclass)==null?void 0:_e2.selection_pools)!=null?_f2:[]]){const rp=resolved.pools.find(p=>p.classIndex===classIndex&&p.id===decl.id);if(rp&&rp.count>=1)suppressedFeatureTypes.add(decl.source.where.feature_type)}for(const entry of featProgressions){const category=featProgressionCategory(entry.category);const ft=category?FEATURE_TYPE_FOR_CATEGORY[category]:void 0;if(ft)suppressedFeatureTypes.add(ft)}if(classIndex===0&&((_h2=(_g2=entity.skill_choices)==null?void 0:_g2.from)==null?void 0:_h2.length)){const skillChoice={kind:"select-proficiency",id:"skills",label:"Skill Proficiencies",count:entity.skill_choices.count,domain:"skill",from:entity.skill_choices.from};push(1,buildItem(skillChoice,{kind:"class",slug:entity.slug,level:1},1,"Proficiencies",readAt(1),ctx,ownerBare,effective))}if(classIndex===0){for(const ch of[...(_i2=entity.choices)!=null?_i2:[],...classToolPicks(entity).decisions]){push(1,buildItem(ch,{kind:"class",slug:entity.slug,level:1},1,"Proficiencies",readAt(1),ctx,ownerBare,effective))}}if(classIndex===0){for(const ch of equipmentDecisions(entity.starting_equipment,entity.slug)){push(1,buildItem(ch,{kind:"class",slug:entity.slug,level:1},1,"Starting Equipment",readAt(1),ctx,ownerBare,effective))}}let sawAuthoredSubclass=false;const staged=[];const authoredRank=(kind,level,feature)=>{var _a3,_b3,_c3;const at=(_c3=(_b3=(_a3=kind==="class"?entity:c.subclass)==null?void 0:_a3.features_by_level)==null?void 0:_b3[level])!=null?_c3:[];const index=at.findIndex(f=>feature.id?f.id===feature.id:f.name===feature.name);return(kind==="class"?0:1)*1e6+(index<0?999999:index)};for(const rf of resolved.features){const src=rf.source;if(src.kind!=="class"&&src.kind!=="subclass")continue;const belongs=src.kind==="class"?src.slug===entity.slug:c.subclass!=null&&src.slug===c.subclass.slug;if(!belongs)continue;const lvl=src.level;const stage=(atLvl,item)=>{staged.push({level:atLvl,item,rank:authoredRank(src.kind,atLvl,rf.feature),seq:staged.length})};const emitChoices=(list,atLvl,name,description)=>{var _a3,_b3;for(const ch of list){if(ch.kind==="select-entity"&&ch.entity_type==="subclass"){sawAuthoredSubclass=true;stage(atLvl,buildSubclassItem(ch,src,atLvl,name,c,ctx,ownerBare,description));continue}let emitted=ch;if(ch.kind==="select-entity"){const columns=countColumnsFor(ch.id);const fromTable=columns?readTableColumn(entity.table,c.level,columns):null;if(fromTable!=null)emitted={...ch,count:Math.max((_a3=ch.count)!=null?_a3:1,fromTable)}}stage(atLvl,buildItem(emitted,src,atLvl,name,(_b3=legacyAsiReader(emitted,atLvl))!=null?_b3:readAt(atLvl),ctx,ownerBare,effective,{description}))}};const informationalItem=(atLvl,name,description)=>{var _a3,_b3;return{key:(_a3=rf.feature.id)!=null?_a3:name,source:src,level:atLvl,featureName:name,description,choice:{kind:"select-inline",id:(_b3=rf.feature.id)!=null?_b3:name,options:[{value:"_",label:"_"}]},options:[],selected:void 0,status:"informational",satisfied:false}};const emitCopy=copy=>{let list=copy.choices;if(!(list==null?void 0:list.length)){const recognized=recognizeDecision({id:rf.feature.id,name:copy.name,description:copy.description});if(recognized==="informational"){stage(copy.level,informationalItem(copy.level,copy.name,copy.prose));return}list=recognized!=null?recognized:void 0;if(list==null?void 0:list.length){list=list.filter(ch=>{var _a3;if(ch.kind!=="select-entity")return true;const ft=(_a3=ch.where)==null?void 0:_a3.feature_type;return!(ft!==void 0&&suppressedFeatureTypes.has(ft))})}}if(!(list==null?void 0:list.length)){if(copy.prose)stage(copy.level,informationalItem(copy.level,copy.name,copy.prose));return}emitChoices(list,copy.level,copy.name,copy.description)};for(const copy of(_j2=rf.foldedFrom)!=null?_j2:[])emitCopy({...copy,prose:copy.description});emitCopy({level:lvl,name:rf.feature.name,description:rf.feature.description,prose:rf.feature.description||(((_k2=rf.feature.entries)==null?void 0:_k2.length)?rf.feature.entries.join("\n\n"):void 0),choices:rf.feature.choices})}staged.sort((a,b)=>a.rank-b.rank||a.seq-b.seq);for(const s of staged)push(s.level,s.item);const subclassLevel=(_l2=entity.subclass_level)!=null?_l2:null;if(subclassLevel!=null&&subclassLevel<=c.level&&!sawAuthoredSubclass){const featureName=(_m2=entity.subclass_feature_name)!=null?_m2:"Subclass";const synthChoice={kind:"select-entity",id:"subclass",label:featureName,count:1,entity_type:"subclass",where:{parent_class:"self"}};push(subclassLevel,buildSubclassItem(synthChoice,{kind:"class",slug:entity.slug,level:subclassLevel},subclassLevel,featureName,c,ctx,ownerBare))}for(const pool of resolved.pools){if(pool.classIndex!==classIndex||pool.count<1)continue;const stranded=strandedPicks(pool);const strandedSlugs=new Set(stranded.map(e=>e.slug));const synth={kind:"select-entity",id:pool.id,label:pool.label,count:pool.count,entity_type:"optional-feature",from:[...pool.available.map(e=>e.slug),...stranded.map(e=>e.slug)]};const item=buildItem(synth,{kind:"class",slug:entity.slug,level:pool.anchorLevel},pool.anchorLevel,pool.label,()=>pool.selected.map(e=>e.key),ctx,ownerBare,effective);item.pool={id:pool.id,anchorLevel:pool.anchorLevel};const repeatables=pool.available.filter(e=>e.entity.repeatable===true);if(repeatables.length>0){item.repeatable=repeatables.map(e=>{var _a3,_b3;return{noteSlug:e.slug,itemChoice:(_a3=e.entity.item_choice)!=null?_a3:"learn",rows:resolveOptionRows(e.entity,ctx.registry,{edition:resolved.definition.edition,isEntityVisible:(_b3=ctx.isEntityVisible)==null?void 0:_b3.bind(ctx)})}})}for(const o of item.options)if(strandedSlugs.has(o.value))o.stranded=true;const memberChildren=[];for(const entry of pool.selected){for(const ch of memberChoices(entry.entity)){const child=buildItem(ch,{kind:"class",slug:entity.slug,level:pool.anchorLevel},pool.anchorLevel,entry.entity.name,readAt(pool.anchorLevel),ctx,ownerBare,effective,{keyPrefix:`${pool.id}:${entry.key}:`});child.parentLabel=entry.entity.name;memberChildren.push(child)}}if(memberChildren.length){item.children=memberChildren;if(item.status==="resolved"&&memberChildren.some(c2=>c2.status!=="resolved"))item.status="partial"}push(pool.anchorLevel,item)}for(const entry of featProgressions){const category=featProgressionCategory(entry.category);if(!category){warnOnce(`feat-progression-category:${entity.slug}:${entry.name}`,`Archivist: feat_progression "${entry.name}" on "${entity.slug}" carries no category this engine maps (${((_n2=entry.category)!=null?_n2:[]).join(", ")}); no decision is offered`);continue}const progression=entry.progression;if(Array.isArray(progression))continue;for(const key of Object.keys(progression)){const lvl=Number.parseInt(key,10);if(!Number.isInteger(lvl)||String(lvl)!==key)continue;if(lvl>c.level)continue;if(((_o=byLevel.get(lvl))!=null?_o:[]).some(i=>i.key==="feat")){warnOnce(`feat-progression-collision:${entity.slug}:${lvl}`,`Archivist: "${entry.name}" on "${entity.slug}" would add a second feat pick at level ${lvl}, where one already exists; skipping`);continue}const progressionChoice={kind:"select-entity",id:"feat",label:entry.name,count:1,entity_type:"feat",where:{category}};push(lvl,buildItem(progressionChoice,{kind:"class",slug:entity.slug,level:lvl},lvl,entry.name,readAt(lvl),ctx,ownerBare,effective))}}const levels=[...byLevel.entries()].sort(([a],[b])=>a-b).map(([level,items])=>({level,items}));classes.push({classIndex,levels})});const origin=[];const oc=(_i=resolved.definition.origin_choices)!=null?_i:{};const originRead=ns=>id=>oc[`${ns}:${id}`];const pushOrigin=(choices,ns,source,featureName,ownerBare,description)=>{for(const ch of choices!=null?choices:[]){origin.push(buildItem(ch,source,0,featureName,originRead(ns),ctx,ownerBare,effective,{description}))}};const pushReplacements=(kind,bare)=>{var _a2;for(const r of(_a2=resolved.proficiencyReplacements)!=null?_a2:[]){if(r.carrier.kind!==kind)continue;origin.push(buildItem(r.choice,{kind,slug:r.carrier.slug},0,r.carrier.name,originRead(kind),ctx,bare,effective,{description:replacementDescription(r)}))}};if(resolved.race){const bare=bareEntitySlug(resolved.race.slug);pushReplacements("race",bare);pushOrigin(resolved.race.choices,"race",{kind:"race",slug:resolved.race.slug},(_j=resolved.race.name)!=null?_j:"Race",bare);for(const t of(_k=resolved.race.traits)!=null?_k:[]){pushOrigin(t.choices,"race",{kind:"race",slug:resolved.race.slug},t.name,bare,t.description)}}if(resolved.background){const bare=bareEntitySlug(resolved.background.slug);pushReplacements("background",bare);pushOrigin([...(_l=resolved.background.choices)!=null?_l:[],...backgroundToolPicks(resolved.background).decisions],"background",{kind:"background",slug:resolved.background.slug},(_m=resolved.background.name)!=null?_m:"Background",bare);if(resolved.background.feature){pushOrigin(resolved.background.feature.choices,"background",{kind:"background",slug:resolved.background.slug},resolved.background.feature.name,bare,resolved.background.feature.description)}if(resolved.background.origin_feat){const originFeat=resolveOriginFeat(ctx.registry,resolved.background.origin_feat,resolved.background.slug);if(originFeat){const featSource={kind:"feat",slug:originFeat.feat.slug};const featBare=bareEntitySlug(originFeat.feat.slug);for(const ch of(_n=originFeat.feat.choices)!=null?_n:[]){origin.push(buildItem(ch,featSource,0,originFeat.display,originRead("background"),ctx,featBare,effective,{keyPrefix:"feat:"}))}}}for(const ch of equipmentDecisions(resolved.background.equipment,resolved.background.slug)){origin.push(buildItem(ch,{kind:"background",slug:resolved.background.slug},0,"Starting Equipment",originRead("background"),ctx,bare,effective))}}return{classes,origin}}var SLUG_RE=/^\[\[(.+?)\]\]$/;function stripSlug(ref){if(!ref)return null;const m=ref.match(SLUG_RE);return m?m[1]:ref}function resolveOriginFeat(entities,originFeatRef,ownerSlug){var _a,_b,_c;if(!originFeatRef)return null;const slug=wikilinkTailSlug(originFeatRef);const inner=originFeatRef.replace(/^\[\[/,"").replace(/\]\]$/,"").trim();const rawTail=(_b=(_a=inner.split("/").pop())==null?void 0:_a.trim())!=null?_b:"";const base=rawTail.replace(/\s*\([^()]*\)\s*$/,"").trim();const baseSlug=base&&base!==rawTail?wikilinkTailSlug(`[[${base}]]`):null;const baseInner=baseSlug?inner.slice(0,inner.length-rawTail.length)+base:null;const prefix=(ownerSlug==null?void 0:ownerSlug.includes("_"))?ownerSlug.slice(0,ownerSlug.indexOf("_")):null;const feats=bucketOf(entities,"feat");const byPath=p=>feats.find(f=>f.filePath===`${p}.md`||f.filePath.endsWith(`/${p}.md`));const sameCompendiumTail=s=>prefix?feats.find(f=>f.slug.startsWith(`${prefix}_feat_`)&&f.slug.endsWith(`_${s}`)):void 0;const anyTail=s=>feats.find(f=>f.slug.endsWith(`_${s}`));const tiers=[()=>{var _a2;return(_a2=feats.find(f=>f.slug===inner))!=null?_a2:feats.find(f=>f.slug===slug)},()=>byPath(inner),()=>baseInner?byPath(baseInner):void 0,()=>sameCompendiumTail(slug),()=>baseSlug?sameCompendiumTail(baseSlug):void 0,()=>anyTail(slug),()=>baseSlug?anyTail(baseSlug):void 0];let reg;let hitTier=0;for(let i=0;i<tiers.length&&!reg;i++){reg=tiers[i]();hitTier=i+1}if(!reg)return null;const variantName=baseSlug&&(hitTier===3||hitTier===5||hitTier===7)?rawTail:void 0;const data=reg.data;const feat=data.slug==null?{...data,slug:reg.slug}:data;return{feat,display:(_c=variantName!=null?variantName:feat.name)!=null?_c:slug}}var PCResolver=class{constructor(entities){this.entities=entities}get registry(){return this.entities}resolve(character){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const warnings=[];const lookup=(rawRef,type)=>{const slug=stripSlug(rawRef);if(!slug)return null;const reg=this.entities.getByTypeAndSlug(type,slug);if(!reg){warnings.push(`Slug [[${slug}]] not found in compendium as ${type}.`);return null}const data=reg.data;return data.slug==null?{...data,slug:reg.slug}:data};const race=withSubspeciesParent(lookup(character.race,"race"),this.entities);const background=lookup(character.background,"background");const classes=character.class.map(c=>({entity:lookup(c.name,"class"),level:c.level,subclass:lookup(c.subclass,"subclass"),choices:c.choices}));const memberSites=withoutStrandedSites(poolMemberSites(classes,this.entities),classes,this.entities,character.edition);const classSlugOf=i=>{var _a2,_b2,_c2,_d2,_e2;return(_e2=(_b2=(_a2=classes[i])==null?void 0:_a2.entity)==null?void 0:_b2.slug)!=null?_e2:stripSlug((_d2=(_c2=character.class[i])==null?void 0:_c2.name)!=null?_d2:null)};const featSites=featPickSites(character.class,memberSites,classSlugOf);const feats=[];const featVia=new Map;for(const site of featSites){const f=lookup(`[[${site.slug}]]`,"feat");if(!f)continue;if(!feats.some(x=>x.slug===f.slug))feats.push(f);if(site.via&&!featVia.has(f.slug))featVia.set(f.slug,site.via)}const originFeat=(background==null?void 0:background.origin_feat)?resolveOriginFeat(this.entities,background.origin_feat,background.slug):null;const originFeatSlug=originFeat==null?void 0:originFeat.feat.slug;if(originFeat&&!feats.some(f=>f.slug===originFeat.feat.slug)){feats.push(originFeat.feat)}if(originFeat&&background&&!featVia.has(originFeat.feat.slug)){featVia.set(originFeat.feat.slug,{kind:"background",slug:background.slug})}const raceFeats=[];for(const site of raceFeatSites(race,character.origin_choices)){const f=lookup(`[[${site.slug}]]`,"feat");if(!f)continue;raceFeats.push({feat:f,read:site.read});if(!feats.some(x=>x.slug===f.slug))feats.push(f);if(!featVia.has(f.slug))featVia.set(f.slug,site.via)}const totalLevel=classes.reduce((sum,c)=>sum+c.level,0);const features=collectResolvedFeatures(race,classes,background,feats,featVia);const extraFeatures=collectChosenGrantedFeatures(character,classes,this.entities,race,background,memberSites);features.push(...extraFeatures);const originChoices=(_a=character.origin_choices)!=null?_a:{};const featChoiceSites=[];for(const site of featSites){const f=lookup(`[[${site.slug}]]`,"feat");if(f)featChoiceSites.push({feat:f,via:site.via,read:site.read})}if(originFeat&&background){featChoiceSites.push({feat:originFeat.feat,via:{kind:"background",slug:background.slug},read:id=>originChoices[`background:feat:${id}`]})}for(const rf of raceFeats)featChoiceSites.push({feat:rf.feat,via:race?{kind:"race",slug:race.slug}:null,read:rf.read});features.push(...collectFeatChoiceGrants(featChoiceSites,this.entities));features.push(...collectAdditionalFeatures(character,this.entities,warnings));const casters=[];classes.forEach((c,i)=>{const profile=c.entity?resolveSpellcasting(c):null;const classSlug=profile?stripSlug(character.class[i].name):null;if(profile&&classSlug!=null)casters.push({classSlug,spellList:profile.spellList})});const spells=[];for(const raw of(_b=character.spells.known)!=null?_b:[]){const n=normalizeKnownSpell(raw);const reg=this.entities.getByTypeAndSlug("spell",n.slug);if(!reg){warnings.push(`Spell [[${n.slug}]] not found in compendium.`);continue}const entity=mirrorSpellShapes(reg.data);const isCantrip=((_c=entity.level)!=null?_c:0)===0;const classSlug=(_d=n.classSlug)!=null?_d:attributeUnclassedSpell(entity.classes,casters,this.entities);const prep=isCantrip||n.alwaysPrepared?true:(_e=n.preparedFlag)!=null?_e:false;spells.push({entity,slug:n.slug,classSlug,source:n.source,prepared:prep,alwaysPrepared:n.alwaysPrepared,persisted:true})}const oc=(_f=character.origin_choices)!=null?_f:{};if(originFeat){const read=childId=>oc[`background:feat:${childId}`];spells.push(...collectFeatGrantedSpells(originFeat.feat,read,this.entities,warnings))}for(const rf of raceFeats)spells.push(...collectFeatGrantedSpells(rf.feat,rf.read,this.entities,warnings));for(const site of featSites){const reg=this.entities.getByTypeAndSlug("feat",site.slug);if(!reg)continue;const feat=reg.data;spells.push(...collectFeatGrantedSpells(feat,site.read,this.entities,warnings))}for(const site of memberSites){const classSlug=stripSlug((_h=(_g=character.class[site.classIndex])==null?void 0:_g.name)!=null?_h:null);for(const ch of site.choices){if(ch.kind!=="select-entity"||ch.entity_type!=="spell"||isTargetChoice(ch))continue;const v=site.read(ch.id);for(const ref of Array.isArray(v)?v:typeof v==="string"?[v]:[]){const slug=typeof ref==="string"?stripSlug(ref):null;if(!slug)continue;const reg=this.entities.getByTypeAndSlug("spell",slug);if(!reg){warnings.push(`Spell [[${slug}]] not found in compendium.`);continue}const entity=mirrorSpellShapes(reg.data);spells.push({entity,slug,classSlug,source:"class",prepared:true,alwaysPrepared:true})}}}const ownSpellcastingAbility=(_i=classes.map(c=>{if(!c.entity)return null;const p=resolveSpellcasting(c);return p?effectiveSpellcastingAbility(c.entity.slug,p.ability,character.overrides):null}).find(a=>a!=null))!=null?_i:null;spells.push(...collectItemGrantedSpells(character,ownSpellcastingAbility,this.entities,warnings));const chosenMasteries=collectChosenWeaponMasteries(character);if(chosenMasteries.full.length>0){const target=features.find(rf=>{var _a2;return rf.feature.id==="weapon-mastery"||((_a2=rf.feature.choices)==null?void 0:_a2.some(ch=>ch.kind==="select-entity"&&ch.id==="weapon-mastery"&&ch.entity_type==="weapon"))});if(target){const names=chosenMasteries.full.map(fullSlug=>{var _a2,_b2;return(_b2=(_a2=this.entities.getByTypeAndSlug("weapon",fullSlug))==null?void 0:_a2.name)!=null?_b2:fullSlug});const entry={label:"Mastered weapons",description:names.join(", ")};target.chosenInline=target.chosenInline?[...target.chosenInline,entry]:[entry]}}const featureResources=resolveFeatureResources(features);const resolvedCharacter={definition:character,race,classes,background,feats,...originFeatSlug?{originFeatSlug}:{},totalLevel,features,spells:[],pools:[],resources:featureResources,weaponMasteries:chosenMasteries.bare,...(()=>{var _a2;const p=(_a2=pactWeaponPick(memberSites))!=null?_a2:classPactWeaponPick(character,classes);return p?{pactWeapon:p}:{}})(),state:character.state};resolvedCharacter.pools=resolveAllPools(resolvedCharacter,this.entities,featureResources);spells.push(...collectAdditionalSpells({race,feats,classes,totalLevel,ownAbility:ownSpellcastingAbility,alreadyCollected:spells,entities:this.entities,warnings,raceChoice:id=>oc[`race:${id}`],pools:resolvedCharacter.pools}));resolvedCharacter.spells=dedupeResolvedSpells(spells);resolvedCharacter.resources=resolveResourceIndex(resolvedCharacter);resolvedCharacter.features=bindFeatureConsumers(resolvedCharacter.features,resolvedCharacter.resources,classes);resolvedCharacter.features=attachGrantedSpends(resolvedCharacter.features,classes);const infusions=buildInfusionContext(character,resolvedCharacter,this.entities);if(infusions)resolvedCharacter.infusions=infusions;const itemFeatures=buildItemFeatures((_j=character.equipment)!=null?_j:[],this.entities,infusions,warnings);if(itemFeatures.length)resolvedCharacter.itemFeatures=itemFeatures;try{resolvedCharacter.proficiencyReplacements=collectProficiencyReplacements(resolvedCharacter)}catch(e){resolvedCharacter.proficiencyReplacements=[];warnings.push(`Duplicate proficiency check skipped: ${e instanceof Error?e.message:String(e)}`)}return{character:resolvedCharacter,warnings}}};function collectChosenWeaponMasteries(character){var _a,_b;const full=new Set;for(const cls of(_a=character.class)!=null?_a:[]){for(const lvl of Object.values((_b=cls.choices)!=null?_b:{})){const pick=lvl["weapon-mastery"];if(Array.isArray(pick)){for(const s of pick)if(typeof s==="string")full.add(s)}}}return{full:[...full],bare:[...new Set([...full].map(bareEntitySlug))]}}function collectFeatPicks(character){const picks=new Map;for(const site of featPickSites(character.class,[],()=>null)){if(!picks.has(site.slug))picks.set(site.slug,{slug:site.slug,classIndex:site.classIndex,level:site.level})}return[...picks.values()]}function collectFeatGrantedSpells(feat,read,entities,warnings){var _a;const ability=readChosenSpellAbility(read);const slugs=[];collectSpellPickSlugs(feat.choices,read,slugs);const out=[];for(const rawSlug of slugs){const slug=(_a=stripSlug(rawSlug))!=null?_a:rawSlug;const reg=entities.getByTypeAndSlug("spell",slug);if(!reg){warnings.push(`Feat spell [[${slug}]] not found in compendium.`);continue}const entity=mirrorSpellShapes(reg.data);out.push({entity,slug,classSlug:null,source:"feat",prepared:true,alwaysPrepared:true,ability})}return out}function collectItemGrantedSpells(character,ownAbility,entities,warnings){var _a;const out=[];((_a=character.equipment)!=null?_a:[]).forEach((entry,entryIndex)=>{var _a2,_b,_c,_d,_e,_f;const spellRef=(_a2=entry.overrides)==null?void 0:_a2.spell;if(!spellRef)return;const{entity:itemEntity}=resolveEntityForEntry(entry.item,entities);const scrollLevel=isItemEntity(itemEntity)?itemEntity.scroll_level:void 0;if(scrollLevel==null)return;const slug=(_b=stripSlug(spellRef))!=null?_b:spellRef;const reg=entities.getByTypeAndSlug("spell",slug);if(!reg){warnings.push(`Scroll spell [[${slug}]] not found in compendium.`);return}const entity=mirrorSpellShapes(reg.data);const ability=(_f=(_d=(_c=entry.overrides)==null?void 0:_c.spell_ability)!=null?_d:ownAbility)!=null?_f:(_e=character.overrides)==null?void 0:_e.spellcasting_ability;const itemCasting=storedSpellNumbers(itemEntity);out.push({entity,slug,classSlug:null,source:"item",prepared:true,alwaysPrepared:true,ability,entryIndex,...itemCasting?{itemCasting}:{}})});return out}function dedupeResolvedSpells(spells){const byKey=new Map;for(const s of spells){const key=s.source==="item"?`${s.slug}#${s.entryIndex}`:s.atWill?`${s.slug}#atwill`:s.slug;const existing=byKey.get(key);if(!existing){byKey.set(key,s);continue}if(existing.source==="feat"&&s.source!=="feat"){byKey.set(key,{...s,alwaysPrepared:s.alwaysPrepared||existing.alwaysPrepared,prepared:s.prepared||existing.alwaysPrepared,...existing.persisted||s.persisted?{persisted:true}:{}})}else if(s.alwaysPrepared&&!existing.alwaysPrepared){byKey.set(key,{...existing,alwaysPrepared:true,prepared:true})}}return[...byKey.values()]}function readChosenSpellAbility(read){const pick=read("spellcasting-ability");return typeof pick==="string"&&ABILITY_KEYS.includes(pick)?pick:null}function collectSpellPickSlugs(choices,read,out){for(const ch of choices!=null?choices:[]){if(ch.kind==="select-entity"&&ch.entity_type==="spell"){const sel=read(ch.id);const picks=Array.isArray(sel)?sel:typeof sel==="string"?[sel]:[];for(const p of picks)if(typeof p==="string"&&p.length>0)out.push(p)}else if(ch.kind==="select-inline"){const sel=read(ch.id);const branch=typeof sel==="string"?ch.options.find(o=>o.value===sel):void 0;if(branch==null?void 0:branch.choices)collectSpellPickSlugs(branch.choices,read,out)}}}function collectChosenGrantedFeatures(character,classes,registry,race=null,background=null,memberSites=[]){var _a,_b,_c,_d;const out=[];for(const site of memberSites){const classSlug=(_b=(_a=classes[site.classIndex])==null?void 0:_a.entity)==null?void 0:_b.slug;if(!classSlug)continue;const at={};const grants=site.choices.filter(ch=>!isTargetChoice(ch));for(const ch of grants)at[ch.id]=site.read(ch.id);walkChoiceGrants(grants,at,(granted,suppress)=>{out.push({feature:granted,source:{kind:"class",slug:classSlug,level:site.level},...suppress?{renderSuppressed:true}:{}})},registry)}classes.forEach((c,i)=>{var _a2,_b2,_c2,_d2;if(!c.entity)return;const entity=c.entity;const entry=character.class[i];if(!entry)return;for(const[lvlStr,atLevel]of Object.entries(entry.choices)){const lvl=Number(lvlStr);if(!Number.isFinite(lvl)||lvl>entry.level)continue;const features=(_b2=((_a2=entity.features_by_level)!=null?_a2:{})[lvl])!=null?_b2:[];const subFeatures=c.subclass?(_d2=((_c2=c.subclass.features_by_level)!=null?_c2:{})[lvl])!=null?_d2:[]:[];for(const feature of[...features,...subFeatures]){walkChoiceGrants(feature.choices,atLevel,(granted,suppress)=>{out.push({feature:granted,source:{kind:"class",slug:entity.slug,level:lvl},...suppress?{renderSuppressed:true}:{}})},registry)}}});const oc=(_c=character.origin_choices)!=null?_c:{};const originAt=ns=>{const at={};for(const[key,val]of Object.entries(oc)){if(key.startsWith(`${ns}:`))at[key.slice(ns.length+1)]=val}return at};if(race){const atRace=originAt("race");const emitRace=(granted,suppress)=>{out.push({feature:granted,source:{kind:"race",slug:race.slug},...suppress?{renderSuppressed:true}:{}})};walkChoiceGrants(race.choices,atRace,emitRace,registry);for(const trait of(_d=race.traits)!=null?_d:[]){walkChoiceGrants(trait.choices,atRace,emitRace,registry)}}if(background){const atBg=originAt("background");const emitBg=(granted,suppress)=>{out.push({feature:granted,source:{kind:"background",slug:background.slug},...suppress?{renderSuppressed:true}:{}})};walkChoiceGrants(background.choices,atBg,emitBg,registry);if(background.feature){walkChoiceGrants(background.feature.choices,atBg,emitBg,registry)}}return out}function choiceIdsOf(choices,out=[]){for(const ch of choices!=null?choices:[]){out.push(ch.id);if(ch.kind==="select-inline")for(const o of ch.options)choiceIdsOf(o.choices,out)}return out}function collectFeatChoiceGrants(sites,registry){var _a;const out=[];for(const site of sites){const choices=(_a=site.feat.choices)!=null?_a:[];if(!choices.length)continue;const at={};for(const id of choiceIdsOf(choices))at[id]=site.read(id);const source={kind:"feat",slug:site.feat.slug,...site.via?{via:site.via}:{}};walkChoiceGrants(choices,at,granted=>{var _a2;out.push({feature:{...granted,name:(_a2=site.feat.name)!=null?_a2:granted.name},source,renderSuppressed:true})},registry,{inlineOnly:true})}return out}function collectAdditionalFeatures(character,entities,warnings){var _a,_b,_c,_d,_e,_f,_g,_h;const out=[];for(const entry of(_a=character.additional_features)!=null?_a:[]){const slug=(_b=stripSlug(entry))!=null?_b:entry;const reg=entities.getByTypeAndSlug("optional-feature",slug);if(!reg){warnings.push(`Granted feature [[${slug}]] not found in compendium as optional-feature.`);continue}const d=reg.data;const feature={id:(_c=d.slug)!=null?_c:slug,name:(_d=d.name)!=null?_d:slug,description:d.description,...((_e=d.effects)==null?void 0:_e.length)?{effects:d.effects}:{},...d.action_cost?{action:d.action_cost}:{},...d.passive!==void 0?{passive:d.passive}:{},...d.activatable!==void 0?{activatable:d.activatable}:{},...d.duration?{duration:d.duration}:{},...d.consumes?{consumes:d.consumes}:{}};const uses=d.uses;if(uses){const maxFormula=String(uses.max);if(isValidMaxFormula(maxFormula)){feature.resources=[{id:(_f=d.slug)!=null?_f:slug,name:(_g=d.name)!=null?_g:slug,max_formula:maxFormula,reset:uses.recharge,...((_h=uses.recovery)==null?void 0:_h.length)?{recovery:uses.recovery}:{},...d.rendering_hint?{rendering_hint:d.rendering_hint}:{},...d.surface?{surface:d.surface}:{}}]}else{warnings.push(`Granted feature "${slug}" has a prose uses.max (${JSON.stringify(uses.max)}); no tracker.`)}}out.push({feature,source:{kind:"campaign",slug}})}return out}function walkChoiceGrants(choices,atLevel,emit,registry,opts={}){var _a,_b,_c,_d,_e;for(const ch of choices!=null?choices:[]){const sel=atLevel[ch.id];if(!opts.inlineOnly&&ch.kind==="select-entity"&&ch.entity_type==="optional-feature"){const slugs=Array.isArray(sel)?sel:typeof sel==="string"?[sel]:[];for(const slug of slugs){const reg=registry.getByTypeAndSlug("optional-feature",(_a=stripSlug(String(slug)))!=null?_a:String(slug));if(!reg)continue;const d=reg.data;emit({id:(_b=d.slug)!=null?_b:String(slug),name:(_c=d.name)!=null?_c:String(slug),description:d.description,effects:d.effects,...d.action_cost?{action:d.action_cost}:{}})}}if(ch.kind==="select-inline"){const picks=Array.isArray(sel)?sel.filter(v=>typeof v==="string"):typeof sel==="string"?[sel]:[];for(const value of picks){const branch=ch.options.find(o=>o.value===value);if((_d=branch==null?void 0:branch.effects)==null?void 0:_d.length){const wc=(_e=branch.choices)==null?void 0:_e.find(c=>c.kind==="select-entity"&&c.entity_type==="weapon");const picked=wc?atLevel==null?void 0:atLevel[wc.id]:void 0;const effects=branch.effects.map(e=>e.kind==="weapon-ability"&&e.weapons==="chosen"&&typeof picked==="string"?{...e,weapons:[bareEntitySlug(picked)]}:e);emit({id:`${ch.id}-${branch.value}`,name:branch.label,description:branch.description,effects},true)}if(branch==null?void 0:branch.choices)walkChoiceGrants(branch.choices,atLevel,emit,registry,opts)}}}}function resolveChosenInline(feature,atLevel){var _a;if(!atLevel)return void 0;const picks=[];for(const ch of(_a=feature.choices)!=null?_a:[]){if(ch.kind!=="select-inline")continue;const sel=atLevel[ch.id];if(typeof sel!=="string")continue;const opt=ch.options.find(o=>o.value===sel);if(!opt)continue;picks.push({label:opt.label,description:opt.description})}return picks.length?picks:void 0}function isAsiSlotFeature(feature){var _a,_b,_c,_d;return feature.id==="ability-score-improvement"&&!((_a=feature.effects)!=null?_a:[]).some(e=>!(e.kind==="ability-score-increase"&&e.abilities==="chosen"))&&!((_b=feature.resources)==null?void 0:_b.length)&&!feature.action&&!((_c=feature.sub_features)==null?void 0:_c.length)&&!((_d=feature.attacks)==null?void 0:_d.length)}function foldRepeated(list){const byId=new Map;for(const rf of list){const id=rf.feature.id;if(!id||rf.buildOnly)continue;const arr=byId.get(id);if(arr)arr.push(rf);else byId.set(id,[rf])}const out=[];for(const rf of list){if(!rf.feature.id||rf.buildOnly){out.push(rf);continue}const arr=byId.get(rf.feature.id);if(!arr||arr.length===1){out.push(rf);continue}const sorted=[...arr].sort((a,b)=>a.source.level-b.source.level);const top=sorted[sorted.length-1];if(rf!==top)continue;const effects=sorted.flatMap(c=>{var _a;return(_a=c.feature.effects)!=null?_a:[]});const seen=new Set;const resources=sorted.flatMap(c=>{var _a;return((_a=c.feature.resources)!=null?_a:[]).filter(r=>!seen.has(r.id)&&seen.add(r.id))});const chosenInline=sorted.flatMap(c=>c.chosenInline?[c.chosenInline]:[]);const cardProse=f=>{var _a,_b;return(_b=f.description)!=null?_b:((_a=f.entries)==null?void 0:_a.length)?f.entries.join("\n\n"):void 0};const foldedFrom=sorted.slice(0,-1).map(c=>{var _a;return{level:c.source.level,name:c.feature.name,...cardProse(c.feature)?{description:cardProse(c.feature)}:{},...((_a=c.feature.choices)==null?void 0:_a.length)?{choices:c.feature.choices}:{}}});out.push({...top,feature:{...top.feature,...effects.length?{effects}:{},...resources.length?{resources}:{}},...chosenInline.length?{chosenInline:chosenInline.flat()}:{},...foldedFrom.length?{foldedFrom}:{}})}return out}function collectResolvedFeatures(race,classes,background,feats,featVia=new Map){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o;const out=[];for(const c of classes){if(!c.entity)continue;const slug=c.entity.slug;const byLevel=(_a=c.entity.features_by_level)!=null?_a:{};const classFeatures=[];const subclassFeatures=[];for(const[lvlStr,feats0]of Object.entries(byLevel)){const lvl=parseInt(lvlStr,10);if(Number.isNaN(lvl)||lvl>c.level)continue;for(const feat of feats0){const chosenInline=resolveChosenInline(feat,(_b=c.choices)==null?void 0:_b[lvl]);const feature=withResolvedActionCost(feat);classFeatures.push({feature,source:{kind:"class",slug,level:lvl},...chosenInline?{chosenInline}:{},...isAsiSlotFeature(feature)?{buildOnly:true}:{}})}}if(c.subclass){const sSlug=c.subclass.slug;const sByLevel=(_c=c.subclass.features_by_level)!=null?_c:{};for(const[lvlStr,feats0]of Object.entries(sByLevel)){const lvl=parseInt(lvlStr,10);if(Number.isNaN(lvl)||lvl>c.level)continue;for(const feat of feats0){const chosenInline=resolveChosenInline(feat,(_d=c.choices)==null?void 0:_d[lvl]);const feature=withResolvedActionCost(feat);subclassFeatures.push({feature,source:{kind:"subclass",slug:sSlug,level:lvl},...chosenInline?{chosenInline}:{},...isAsiSlotFeature(feature)?{buildOnly:true}:{}})}}}const foldedClass=foldRepeated(classFeatures);const foldedSubclass=foldRepeated(subclassFeatures);out.push(...foldedClass);if((_e=c.entity.resources)==null?void 0:_e.length){out.push({feature:{name:c.entity.name,resources:c.entity.resources},source:{kind:"class",slug,level:1}})}out.push(...foldedSubclass);if((_g=(_f=c.subclass)==null?void 0:_f.resources)==null?void 0:_g.length){out.push({feature:{name:c.subclass.name,resources:c.subclass.resources},source:{kind:"subclass",slug:c.subclass.slug,level:1}})}}if(race){const traits=(_h=race.traits)!=null?_h:[];for(const feat of traits){out.push({feature:withResolvedActionCost(feat),source:{kind:"race",slug:race.slug}})}}if(background){const bgFeature=background.feature;if(bgFeature){out.push({feature:withResolvedActionCost(bgFeature),source:{kind:"background",slug:background.slug}})}}for(const feat of feats){const via=featVia.get(feat.slug);const featSource={kind:"feat",slug:feat.slug,...via?{via}:{}};const bundled=(_i=feat.features)!=null?_i:[];const entityEffects=(_j=feat.effects)!=null?_j:[];if(bundled.length>0){bundled.forEach((f,i)=>{var _a2,_b2;const feature=i===0?{...f,action:(_a2=f.action)!=null?_a2:feat.action_cost,...entityEffects.length>0?{effects:[...(_b2=f.effects)!=null?_b2:[],...entityEffects]}:{}}:f;out.push({feature,source:featSource})})}else{const name=(_k=feat.name)!=null?_k:feat.slug;const foldedDesc=[feat.description,...(_l=feat.benefits)!=null?_l:[]].filter(Boolean).join("\n\n")||void 0;const buildOnly=((_m=feat.choices)!=null?_m:[]).some(c=>c.kind==="ability-points"&&c.points>=2)&&!((_n=feat.effects)==null?void 0:_n.length)&&!((_o=feat.resources)==null?void 0:_o.length)&&bundled.length===0;out.push({feature:{name,...foldedDesc?{description:foldedDesc}:{},...feat.resources?{resources:feat.resources}:{},...feat.action_cost?{action:feat.action_cost}:{},...entityEffects.length>0?{effects:entityEffects}:{}},source:featSource,...buildOnly?{buildOnly:true}:{}})}}return out}export{stripSlug,resolveOriginFeat,PCResolver,collectChosenWeaponMasteries,collectFeatPicks,collectFeatGrantedSpells,collectItemGrantedSpells,dedupeResolvedSpells,collectChosenGrantedFeatures,collectFeatChoiceGrants,collectAdditionalFeatures,collectResolvedFeatures,collectProficiencyGrants,__matchesFilterForTest,__categoryToEntitySelectForTest,collectChosenProficiencies,collectRuleProficiencySources,collectProficiencyReplacements,computeEffectiveProficiencies,computeSuppressedProficiencies,collectChosenAbilityPoints,buildDecisionLedger};
@@ -1 +1 @@
1
- import{parseBackground}from"./chunk-IR5BA2DZ.js";import yaml from"js-yaml";var backgroundCodec={parse(doc){return parseBackground(doc.body)},serialize(entity){return yaml.dump(entity,{lineWidth:-1,sortKeys:false})}};export{backgroundCodec};
1
+ import{parseBackground}from"./chunk-65VM2BAA.js";import yaml from"js-yaml";var backgroundCodec={parse(doc){return parseBackground(doc.body)},serialize(entity){return yaml.dump(entity,{lineWidth:-1,sortKeys:false})}};export{backgroundCodec};
@@ -0,0 +1 @@
1
+ function bareSlug(ref){if(typeof ref!=="string")return"";const m=ref.match(/^\[\[(.+?)\]\]$/);return(m?m[1]:ref).toLowerCase()}function baseClassName(ref){const bare=bareSlug(ref);const p=bare.split("_");return p.length>=3?p.slice(2).join("_"):p[p.length-1]}function matchesSpellClass(word,classSlug){if(word===void 0)return true;const w=word.trim().toLowerCase().replace(/\s+/g,"-");if(w==="any")return true;if(!classSlug)return false;return baseClassName(w)===baseClassName(classSlug)}export{bareSlug,baseClassName,matchesSpellClass};
@@ -1 +1 @@
1
- import{optionalFeatureEntitySchema}from"./chunk-U7BPRRY5.js";import{parseYaml}from"@archivist-gg/core";function parseOptionalFeature(source){const raw=parseYaml(source,["name","slug","feature_type"]);if(!raw.success)return raw;const result=optionalFeatureEntitySchema.safeParse({edition:"2014",...raw.data});if(!result.success){return{success:false,error:`optional-feature schema validation failed: ${result.error.message}`}}return{success:true,data:result.data}}export{parseOptionalFeature};
1
+ import{optionalFeatureEntitySchema}from"./chunk-JLW7XFFL.js";import{parseYaml}from"@archivist-gg/core";function parseOptionalFeature(source){const raw=parseYaml(source,["name","slug","feature_type"]);if(!raw.success)return raw;const result=optionalFeatureEntitySchema.safeParse({edition:"2014",...raw.data});if(!result.success){return{success:false,error:`optional-feature schema validation failed: ${result.error.message}`}}return{success:true,data:result.data}}export{parseOptionalFeature};
@@ -1 +1 @@
1
- import{poolGrantSchema,selectionPoolSchema,tabDeclSchema}from"./chunk-GCYUCIDN.js";import{casterTypeEnum}from"./chunk-X22SISGM.js";import{featureSchema}from"./chunk-M2UA2FAK.js";import{resourceSchema}from"./chunk-CCFIINBA.js";import{startingEquipmentEntrySchema,startingGoldSchema}from"./chunk-TKIEPC6F.js";import{choiceSchema}from"./chunk-VHIE2KYQ.js";import{additionalSpellsEntrySchema,imageField,progressionSchema}from"./chunk-I26FHSI6.js";import{z}from"zod";var abilityEnum=z.enum(["str","dex","con","int","wis","cha"]);var skillEnum=z.enum(["acrobatics","animal-handling","arcana","athletics","deception","history","insight","intimidation","investigation","medicine","nature","perception","performance","persuasion","religion","sleight-of-hand","stealth","survival"]);var armorCategoryEnum=z.enum(["light","medium","heavy","shield"]);var weaponCategoryEnum=z.enum(["simple","martial"]);var hitDieEnum=z.enum(["d6","d8","d10","d12"]);var editionEnum=z.enum(["2014","2024"]);var weaponProficiencySchema=z.object({fixed:z.array(z.string()).optional(),categories:z.array(weaponCategoryEnum).optional(),conditional:z.array(z.object({category:weaponCategoryEnum,where_property:z.array(z.string()).nonempty()})).optional()}).refine(w=>{var _a,_b,_c,_d,_e,_f;return((_b=(_a=w.fixed)==null?void 0:_a.length)!=null?_b:0)+((_d=(_c=w.categories)==null?void 0:_c.length)!=null?_d:0)+((_f=(_e=w.conditional)==null?void 0:_e.length)!=null?_f:0)>0},{message:"weapon proficiency must declare at least one of fixed/categories/conditional"});var toolProficiencySchema=z.object({fixed:z.array(z.string()).optional(),choice:z.object({count:z.number().int().positive(),from:z.array(z.string()).nonempty()}).optional()}).refine(t=>{var _a,_b;return((_b=(_a=t.fixed)==null?void 0:_a.length)!=null?_b:0)>0||t.choice!==void 0},{message:"tool proficiency must declare fixed or choice"});var spellcastingSchema=z.object({caster_type:casterTypeEnum,ability:abilityEnum,preparation:z.enum(["known","prepared"]),spell_list:z.string().min(1)});var weaponMasterySchema=z.object({starting_count:z.number().int().nonnegative().optional(),scaling:z.record(z.string(),z.number().int().nonnegative()).optional()});var classTableRowSchema=z.object({prof_bonus:z.number().int().positive(),columns:z.record(z.string(),z.union([z.string(),z.number()])).optional(),feature_ids:z.array(z.string())});var classEntitySchema=z.object({slug:z.string().min(1),name:z.string().min(1),edition:editionEnum,source:z.string().min(1),description:z.string(),hit_die:hitDieEnum,primary_abilities:z.array(abilityEnum).nonempty(),standard_array:z.strictObject({str:z.number().int(),dex:z.number().int(),con:z.number().int(),int:z.number().int(),wis:z.number().int(),cha:z.number().int()}).optional(),saving_throws:z.array(abilityEnum).length(2),proficiencies:z.object({armor:z.array(armorCategoryEnum),weapons:weaponProficiencySchema,tools:toolProficiencySchema.optional()}),skill_choices:z.object({count:z.number().int().positive(),from:z.array(skillEnum).nonempty()}),choices:z.array(choiceSchema).optional(),starting_equipment:z.array(startingEquipmentEntrySchema),starting_gold:startingGoldSchema.optional(),spellcasting:spellcastingSchema.nullable(),subclass_level:z.number().int().positive(),subclass_feature_name:z.string().min(1),weapon_mastery:weaponMasterySchema.nullable(),epic_boon_level:z.number().int().positive().nullable(),table:z.record(z.string(),classTableRowSchema),features_by_level:z.record(z.string(),z.array(featureSchema)),resources:z.array(resourceSchema),selection_pools:z.array(selectionPoolSchema).optional(),pool_grants:z.array(poolGrantSchema).optional(),tabs:z.array(tabDeclSchema).optional(),rendering_hint:z.string().optional(),has_fluff:z.boolean().optional(),has_fluff_images:z.boolean().optional(),table_col_labels:z.array(z.string().min(1)).optional(),starting_equipment_additional_from_background:z.boolean().optional(),multiclassing:z.unknown().optional(),cantrip_progression:z.array(z.number()).optional(),prepared_spells:z.string().min(1).optional(),prepared_spells_change:z.string().min(1).optional(),prepared_spells_progression:z.array(z.number()).optional(),spells_known_progression:z.array(z.number()).optional(),spells_known_progression_fixed:z.array(z.number()).optional(),spells_known_progression_fixed_allow_lower_level:z.boolean().optional(),spells_known_progression_fixed_by_level:z.record(z.string(),z.record(z.string(),z.number())).optional(),feat_progression:z.array(progressionSchema).optional(),optionalfeature_progression:z.array(progressionSchema).optional(),additional_spells:z.array(additionalSpellsEntrySchema).optional(),image:imageField});export{classEntitySchema};
1
+ import{poolGrantSchema,selectionPoolSchema,tabDeclSchema}from"./chunk-GCYUCIDN.js";import{casterTypeEnum}from"./chunk-X22SISGM.js";import{featureSchema}from"./chunk-FC4OPNZM.js";import{resourceSchema}from"./chunk-ZKDHCDJ2.js";import{startingEquipmentEntrySchema,startingGoldSchema}from"./chunk-TKIEPC6F.js";import{choiceSchema}from"./chunk-ZK3P4RSE.js";import{additionalSpellsEntrySchema,imageField,progressionSchema}from"./chunk-I26FHSI6.js";import{z}from"zod";var abilityEnum=z.enum(["str","dex","con","int","wis","cha"]);var skillEnum=z.enum(["acrobatics","animal-handling","arcana","athletics","deception","history","insight","intimidation","investigation","medicine","nature","perception","performance","persuasion","religion","sleight-of-hand","stealth","survival"]);var armorCategoryEnum=z.enum(["light","medium","heavy","shield"]);var weaponCategoryEnum=z.enum(["simple","martial"]);var hitDieEnum=z.enum(["d6","d8","d10","d12"]);var editionEnum=z.enum(["2014","2024"]);var weaponProficiencySchema=z.object({fixed:z.array(z.string()).optional(),categories:z.array(weaponCategoryEnum).optional(),conditional:z.array(z.object({category:weaponCategoryEnum,where_property:z.array(z.string()).nonempty()})).optional()}).refine(w=>{var _a,_b,_c,_d,_e,_f;return((_b=(_a=w.fixed)==null?void 0:_a.length)!=null?_b:0)+((_d=(_c=w.categories)==null?void 0:_c.length)!=null?_d:0)+((_f=(_e=w.conditional)==null?void 0:_e.length)!=null?_f:0)>0},{message:"weapon proficiency must declare at least one of fixed/categories/conditional"});var toolProficiencySchema=z.object({fixed:z.array(z.string()).optional(),choice:z.object({count:z.number().int().positive(),from:z.array(z.string()).nonempty()}).optional()}).refine(t=>{var _a,_b;return((_b=(_a=t.fixed)==null?void 0:_a.length)!=null?_b:0)>0||t.choice!==void 0},{message:"tool proficiency must declare fixed or choice"});var spellcastingSchema=z.object({caster_type:casterTypeEnum,ability:abilityEnum,preparation:z.enum(["known","prepared"]),spell_list:z.string().min(1)});var weaponMasterySchema=z.object({starting_count:z.number().int().nonnegative().optional(),scaling:z.record(z.string(),z.number().int().nonnegative()).optional()});var classTableRowSchema=z.object({prof_bonus:z.number().int().positive(),columns:z.record(z.string(),z.union([z.string(),z.number()])).optional(),feature_ids:z.array(z.string())});var classEntitySchema=z.object({slug:z.string().min(1),name:z.string().min(1),edition:editionEnum,source:z.string().min(1),description:z.string(),hit_die:hitDieEnum,primary_abilities:z.array(abilityEnum).nonempty(),standard_array:z.strictObject({str:z.number().int(),dex:z.number().int(),con:z.number().int(),int:z.number().int(),wis:z.number().int(),cha:z.number().int()}).optional(),saving_throws:z.array(abilityEnum).length(2),proficiencies:z.object({armor:z.array(armorCategoryEnum),weapons:weaponProficiencySchema,tools:toolProficiencySchema.optional()}),skill_choices:z.object({count:z.number().int().positive(),from:z.array(skillEnum).nonempty()}),choices:z.array(choiceSchema).optional(),starting_equipment:z.array(startingEquipmentEntrySchema),starting_gold:startingGoldSchema.optional(),spellcasting:spellcastingSchema.nullable(),subclass_level:z.number().int().positive(),subclass_feature_name:z.string().min(1),weapon_mastery:weaponMasterySchema.nullable(),epic_boon_level:z.number().int().positive().nullable(),table:z.record(z.string(),classTableRowSchema),features_by_level:z.record(z.string(),z.array(featureSchema)),resources:z.array(resourceSchema),selection_pools:z.array(selectionPoolSchema).optional(),pool_grants:z.array(poolGrantSchema).optional(),tabs:z.array(tabDeclSchema).optional(),rendering_hint:z.string().optional(),has_fluff:z.boolean().optional(),has_fluff_images:z.boolean().optional(),table_col_labels:z.array(z.string().min(1)).optional(),starting_equipment_additional_from_background:z.boolean().optional(),multiclassing:z.unknown().optional(),cantrip_progression:z.array(z.number()).optional(),prepared_spells:z.string().min(1).optional(),prepared_spells_change:z.string().min(1).optional(),prepared_spells_progression:z.array(z.number()).optional(),spells_known_progression:z.array(z.number()).optional(),spells_known_progression_fixed:z.array(z.number()).optional(),spells_known_progression_fixed_allow_lower_level:z.boolean().optional(),spells_known_progression_fixed_by_level:z.record(z.string(),z.record(z.string(),z.number())).optional(),feat_progression:z.array(progressionSchema).optional(),optionalfeature_progression:z.array(progressionSchema).optional(),additional_spells:z.array(additionalSpellsEntrySchema).optional(),image:imageField});export{classEntitySchema};
@@ -1 +1 @@
1
- import{backgroundEntitySchema}from"./chunk-XFFFTR6O.js";import{parseYaml}from"@archivist-gg/core";function parseBackground(source){const raw=parseYaml(source,["name","slug"]);if(!raw.success)return raw;const result=backgroundEntitySchema.safeParse({edition:"2014",...raw.data});if(!result.success){return{success:false,error:`background schema validation failed: ${result.error.message}`}}return{success:true,data:result.data}}export{parseBackground};
1
+ import{backgroundEntitySchema}from"./chunk-IOFGBEGA.js";import{parseYaml}from"@archivist-gg/core";function parseBackground(source){const raw=parseYaml(source,["name","slug"]);if(!raw.success)return raw;const result=backgroundEntitySchema.safeParse({edition:"2014",...raw.data});if(!result.success){return{success:false,error:`background schema validation failed: ${result.error.message}`}}return{success:true,data:result.data}}export{parseBackground};
@@ -1 +1 @@
1
- import{featureObjectSchema}from"./chunk-M2UA2FAK.js";import{imageField}from"./chunk-I26FHSI6.js";import{z}from"zod";var str=z.string();var num=z.number();var bool=z.boolean();var strArr=z.array(z.string());var damageQualifierSchema=z.object({get types(){return z.array(z.union([str,damageQualifierSchema])).optional()},note:str.optional(),pre_note:str.optional(),cond:bool.optional(),special:str.optional()});var qualifierList=z.array(z.union([str,damageQualifierSchema])).optional();var speedValue=z.union([num,z.object({number:num,condition:str.optional()})]);var monsterSpeedSchema=z.object({walk:speedValue.optional(),fly:speedValue.optional(),swim:speedValue.optional(),climb:speedValue.optional(),burrow:speedValue.optional(),hover:bool.optional(),can_hover:bool.optional(),alternate:z.record(str,z.array(z.object({number:num,condition:str.optional()}))).optional(),choose:z.object({from:strArr,amount:num,note:str.optional()}).optional()});var monsterTypeSchema=z.object({type:z.union([str,z.object({choose:strArr})]),tags:z.array(z.union([str,z.object({tag:str,prefix:str,prefix_hidden:bool.optional()})])).optional(),sidekick_type:str.optional(),sidekick_tags:strArr.optional(),swarm_size:str.optional(),sidekick_hidden:bool.optional()});var monsterCRSchema=z.object({cr:str,lair:str.optional(),coven:str.optional(),xp:num.optional(),xp_lair:num.optional()});var monsterACSchema=z.object({ac:num.optional(),from:strArr.optional(),condition:str.optional(),braces:bool.optional(),special:str.optional()});var monsterHPSchema=z.object({average:num.optional(),formula:str.optional(),special:str.optional()});var alignmentEntrySchema=z.object({alignment:strArr.optional(),chance:num.optional(),note:str.optional(),special:str.optional()});var spellEntry=z.union([str,z.object({entry:str,hidden:bool.optional()})]);var spellList=z.array(spellEntry);var spellLevel=z.object({slots:num.optional(),lower:num.optional(),spells:strArr});var monsterSpellcastingSchema=z.object({name:str.optional(),type:str.optional(),headerEntries:strArr.optional(),footerEntries:strArr.optional(),ability:str.optional(),displayAs:str.optional(),hidden:strArr.optional(),spells:z.record(str,spellLevel).optional(),will:spellList.optional(),ritual:spellList.optional(),daily:z.record(str,spellList).optional(),rest:z.record(str,spellList).optional(),restLong:z.record(str,spellList).optional(),recharge:z.record(str,spellList).optional(),legendary:z.record(str,spellList).optional(),charges:z.record(str,spellList).optional(),chargesItem:str.optional()});var initiativeSchema=z.union([num,z.object({proficiency:num.optional(),advantage_mode:str.optional()})]);var gearEntrySchema=z.union([str,z.object({item:str,quantity:num.optional(),displayName:str.optional()})]);var featureArr=z.array(featureObjectSchema).optional();var monsterSchema=z.object({name:str.min(1),size:z.union([str,strArr]).optional(),size_note:str.optional(),type:z.union([str,monsterTypeSchema]).optional(),subtype:str.optional(),alignment:z.union([str,z.array(z.union([str,alignmentEntrySchema]))]).optional(),alignment_prefix:str.optional(),cr:z.union([str,monsterCRSchema]).optional(),pb_note:str.optional(),ac:z.array(monsterACSchema).optional(),hp:monsterHPSchema.optional(),speed:monsterSpeedSchema.optional(),abilities:z.object({str:num,dex:num,con:num,int:num,wis:num,cha:num}).optional(),saves:z.record(str,num).optional(),skills:z.record(str,num).optional(),skills_other:z.array(z.unknown()).optional(),senses:strArr.nullable().optional(),passive_perception:num.optional(),languages:strArr.nullable().optional(),damage_vulnerabilities:qualifierList,damage_resistances:qualifierList,damage_immunities:qualifierList,condition_immunities:qualifierList,traits:featureArr,actions:featureArr,bonus_actions:featureArr,reactions:featureArr,legendary_actions:featureArr,mythic:featureArr,mythic_header:strArr.optional(),legendary_action_uses:num.optional(),legendary_resistance:num.optional(),legendary_actions_lair_count:num.optional(),section_headers:z.array(z.object({section:str,header:strArr})).optional(),action_note:str.optional(),reaction_note:str.optional(),spellcasting:z.array(monsterSpellcastingSchema).optional(),legendary_group:z.object({name:str,source:str}).optional(),lair_actions:z.array(z.unknown()).optional(),regional_actions:z.array(z.unknown()).optional(),variant:z.array(z.unknown()).optional(),initiative:initiativeSchema.optional(),gear:z.array(gearEntrySchema).optional(),is_named_creature:bool.optional(),is_npc:bool.optional(),familiar:bool.optional(),short_name:z.union([str,bool]).optional(),level:num.optional(),dragon_age:str.optional(),dragon_casting_color:str.optional(),environment:strArr.optional(),treasure:strArr.optional(),attached_items:strArr.optional(),group:strArr.nullable().optional(),summoned_by_spell:str.optional(),summoned_by_spell_level:num.optional(),summoned_by_class:str.optional(),trait_tags:strArr.optional(),action_tags:strArr.optional(),sense_tags:strArr.optional(),language_tags:strArr.optional(),spellcasting_tags:strArr.optional(),misc_tags:strArr.optional(),damage_tags:strArr.optional(),damage_tags_spell:strArr.optional(),damage_tags_legendary:strArr.optional(),condition_inflict:strArr.optional(),condition_inflict_spell:strArr.optional(),condition_inflict_legendary:strArr.optional(),saving_throw_forced:strArr.optional(),saving_throw_forced_spell:strArr.optional(),saving_throw_forced_legendary:strArr.optional(),has_fluff:bool.optional(),has_fluff_images:bool.optional(),has_token:bool.optional(),token_credit:str.optional(),token_custom:bool.optional(),sound_clip:z.object({type:str,path:str}).optional(),alt_art:z.array(z.object({name:str,source:str.optional(),page:num.optional()})).optional(),image:imageField,thumbnail:imageField,rendering_hint:str.optional(),columns:num.optional(),slug:str.optional(),edition:str.optional(),source:str.optional(),raw:z.record(str,z.unknown()).optional()});var MONSTER_KNOWN_KEYS=new Set(Object.keys(monsterSchema.shape));export{damageQualifierSchema,monsterSpeedSchema,monsterTypeSchema,monsterCRSchema,monsterACSchema,monsterHPSchema,alignmentEntrySchema,monsterSpellcastingSchema,initiativeSchema,gearEntrySchema,monsterSchema,MONSTER_KNOWN_KEYS};
1
+ import{featureObjectSchema}from"./chunk-FC4OPNZM.js";import{imageField}from"./chunk-I26FHSI6.js";import{z}from"zod";var str=z.string();var num=z.number();var bool=z.boolean();var strArr=z.array(z.string());var damageQualifierSchema=z.object({get types(){return z.array(z.union([str,damageQualifierSchema])).optional()},note:str.optional(),pre_note:str.optional(),cond:bool.optional(),special:str.optional()});var qualifierList=z.array(z.union([str,damageQualifierSchema])).optional();var speedValue=z.union([num,z.object({number:num,condition:str.optional()})]);var monsterSpeedSchema=z.object({walk:speedValue.optional(),fly:speedValue.optional(),swim:speedValue.optional(),climb:speedValue.optional(),burrow:speedValue.optional(),hover:bool.optional(),can_hover:bool.optional(),alternate:z.record(str,z.array(z.object({number:num,condition:str.optional()}))).optional(),choose:z.object({from:strArr,amount:num,note:str.optional()}).optional()});var monsterTypeSchema=z.object({type:z.union([str,z.object({choose:strArr})]),tags:z.array(z.union([str,z.object({tag:str,prefix:str,prefix_hidden:bool.optional()})])).optional(),sidekick_type:str.optional(),sidekick_tags:strArr.optional(),swarm_size:str.optional(),sidekick_hidden:bool.optional()});var monsterCRSchema=z.object({cr:str,lair:str.optional(),coven:str.optional(),xp:num.optional(),xp_lair:num.optional()});var monsterACSchema=z.object({ac:num.optional(),from:strArr.optional(),condition:str.optional(),braces:bool.optional(),special:str.optional()});var monsterHPSchema=z.object({average:num.optional(),formula:str.optional(),special:str.optional()});var alignmentEntrySchema=z.object({alignment:strArr.optional(),chance:num.optional(),note:str.optional(),special:str.optional()});var spellEntry=z.union([str,z.object({entry:str,hidden:bool.optional()})]);var spellList=z.array(spellEntry);var spellLevel=z.object({slots:num.optional(),lower:num.optional(),spells:strArr});var monsterSpellcastingSchema=z.object({name:str.optional(),type:str.optional(),headerEntries:strArr.optional(),footerEntries:strArr.optional(),ability:str.optional(),displayAs:str.optional(),hidden:strArr.optional(),spells:z.record(str,spellLevel).optional(),will:spellList.optional(),ritual:spellList.optional(),daily:z.record(str,spellList).optional(),rest:z.record(str,spellList).optional(),restLong:z.record(str,spellList).optional(),recharge:z.record(str,spellList).optional(),legendary:z.record(str,spellList).optional(),charges:z.record(str,spellList).optional(),chargesItem:str.optional()});var initiativeSchema=z.union([num,z.object({proficiency:num.optional(),advantage_mode:str.optional()})]);var gearEntrySchema=z.union([str,z.object({item:str,quantity:num.optional(),displayName:str.optional()})]);var featureArr=z.array(featureObjectSchema).optional();var monsterSchema=z.object({name:str.min(1),size:z.union([str,strArr]).optional(),size_note:str.optional(),type:z.union([str,monsterTypeSchema]).optional(),subtype:str.optional(),alignment:z.union([str,z.array(z.union([str,alignmentEntrySchema]))]).optional(),alignment_prefix:str.optional(),cr:z.union([str,monsterCRSchema]).optional(),pb_note:str.optional(),ac:z.array(monsterACSchema).optional(),hp:monsterHPSchema.optional(),speed:monsterSpeedSchema.optional(),abilities:z.object({str:num,dex:num,con:num,int:num,wis:num,cha:num}).optional(),saves:z.record(str,num).optional(),skills:z.record(str,num).optional(),skills_other:z.array(z.unknown()).optional(),senses:strArr.nullable().optional(),passive_perception:num.optional(),languages:strArr.nullable().optional(),damage_vulnerabilities:qualifierList,damage_resistances:qualifierList,damage_immunities:qualifierList,condition_immunities:qualifierList,traits:featureArr,actions:featureArr,bonus_actions:featureArr,reactions:featureArr,legendary_actions:featureArr,mythic:featureArr,mythic_header:strArr.optional(),legendary_action_uses:num.optional(),legendary_resistance:num.optional(),legendary_actions_lair_count:num.optional(),section_headers:z.array(z.object({section:str,header:strArr})).optional(),action_note:str.optional(),reaction_note:str.optional(),spellcasting:z.array(monsterSpellcastingSchema).optional(),legendary_group:z.object({name:str,source:str}).optional(),lair_actions:z.array(z.unknown()).optional(),regional_actions:z.array(z.unknown()).optional(),variant:z.array(z.unknown()).optional(),initiative:initiativeSchema.optional(),gear:z.array(gearEntrySchema).optional(),is_named_creature:bool.optional(),is_npc:bool.optional(),familiar:bool.optional(),short_name:z.union([str,bool]).optional(),level:num.optional(),dragon_age:str.optional(),dragon_casting_color:str.optional(),environment:strArr.optional(),treasure:strArr.optional(),attached_items:strArr.optional(),group:strArr.nullable().optional(),summoned_by_spell:str.optional(),summoned_by_spell_level:num.optional(),summoned_by_class:str.optional(),trait_tags:strArr.optional(),action_tags:strArr.optional(),sense_tags:strArr.optional(),language_tags:strArr.optional(),spellcasting_tags:strArr.optional(),misc_tags:strArr.optional(),damage_tags:strArr.optional(),damage_tags_spell:strArr.optional(),damage_tags_legendary:strArr.optional(),condition_inflict:strArr.optional(),condition_inflict_spell:strArr.optional(),condition_inflict_legendary:strArr.optional(),saving_throw_forced:strArr.optional(),saving_throw_forced_spell:strArr.optional(),saving_throw_forced_legendary:strArr.optional(),has_fluff:bool.optional(),has_fluff_images:bool.optional(),has_token:bool.optional(),token_credit:str.optional(),token_custom:bool.optional(),sound_clip:z.object({type:str,path:str}).optional(),alt_art:z.array(z.object({name:str,source:str.optional(),page:num.optional()})).optional(),image:imageField,thumbnail:imageField,rendering_hint:str.optional(),columns:num.optional(),slug:str.optional(),edition:str.optional(),source:str.optional(),raw:z.record(str,z.unknown()).optional()});var MONSTER_KNOWN_KEYS=new Set(Object.keys(monsterSchema.shape));export{damageQualifierSchema,monsterSpeedSchema,monsterTypeSchema,monsterCRSchema,monsterACSchema,monsterHPSchema,alignmentEntrySchema,monsterSpellcastingSchema,initiativeSchema,gearEntrySchema,monsterSchema,MONSTER_KNOWN_KEYS};
@@ -1 +1 @@
1
- import{heldPicks,parsePickKey,poolAnchorLevel}from"./chunk-E4E6YEN6.js";import{featProgressionCategory}from"./chunk-3QQOATV3.js";import{warnOnce}from"./chunk-DZITM5AG.js";import{bucketOf}from"./chunk-QMEKQTUT.js";import{bareEntitySlug,twinKey,wikilinkTailSlug}from"./chunk-63YJPWTM.js";var OPTIONAL_FEATURE_TYPE_CODE={"MV:B":"maneuver",MV:"maneuver",EI:"invocation",MM:"metamagic","FS:F":"fighting_style"};function spellFilter(choose,edition){const where={edition};for(const part of choose.split("|")){const[rawKey,rawValue=""]=part.split("=");const key=rawKey.trim().toLowerCase();const value=rawValue.trim();if(key==="level"){const n=Number(value.split(";")[0]);if(!Number.isInteger(n))return null;where.level=n}else if(key==="class")where.list=value.toLowerCase();else if(key==="components & miscellaneous"&&/ritual/i.test(value))where.ritual=true}return where}function isTargetChoice(ch){return ch.kind==="select-entity"&&ch.target===true}var PACT_WEAPON_CHOICE_ID="pact-weapon";function pactWeaponPick(sites){for(const site of sites){for(const ch of site.choices){if(ch.kind!=="select-entity"||ch.id!==PACT_WEAPON_CHOICE_ID)continue;const v=site.read(ch.id);const first=Array.isArray(v)?v.find(x=>typeof x==="string"&&x.trim()!==""):v;if(typeof first!=="string"||!first.trim())continue;return first.trim().replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].trim()}}return void 0}function classPactWeaponPick(character,classes){var _a,_b,_c,_d,_e,_f,_g;const inBlock=(choices,block)=>{for(const ch of choices!=null?choices:[]){if(ch.kind==="select-inline"){const sel=block[ch.id];const branch=typeof sel==="string"?ch.options.find(o=>o.value===sel):void 0;const hit=inBlock(branch==null?void 0:branch.choices,block);if(hit)return hit}else if(ch.kind==="select-entity"&&ch.id===PACT_WEAPON_CHOICE_ID){const hit=pactWeaponPick([{choices:[ch],read:id=>block[id]}]);if(hit)return hit}}return void 0};for(let i=0;i<classes.length;i++){const entity=(_a=classes[i])==null?void 0:_a.entity;const entry=character.class[i];if(!entity||!entry)continue;for(const[lvl,raw]of Object.entries((_b=entry.choices)!=null?_b:{})){const block=raw!=null?raw:{};const features=[...(_d=((_c=entity.features_by_level)!=null?_c:{})[Number(lvl)])!=null?_d:[],...(_g=((_f=(_e=classes[i].subclass)==null?void 0:_e.features_by_level)!=null?_f:{})[Number(lvl)])!=null?_g:[]];for(const f of features){const hit=inBlock(f.choices,block);if(hit)return hit}}}return void 0}function progressionCount(p){var _a;if(Array.isArray(p))return 0;return(_a=p["*"])!=null?_a:Math.max(0,...Object.values(p))}function spellChoices(entity,used){var _a,_b;const out=[];for(const block of(_a=entity.additional_spells)!=null?_a:[]){for(const bucket of["known","prepared"]){const byLevel=block[bucket];if(!byLevel||typeof byLevel!=="object")continue;for(const rows of Object.values(byLevel)){for(const row of Array.isArray(rows)?rows:[]){const r=row;if(typeof r.choose!=="string")continue;const where=spellFilter(r.choose,entity.edition);if(!where)continue;const base=where.ritual?"rituals":where.level===0?"cantrips":`spells-${(_b=where.level)!=null?_b:"any"}`;const label=where.ritual?"Rituals":where.level===0?"Cantrips":`Level ${where.level} spells`;let id=base;for(let i=2;used.has(id);i++)id=`${base}-${i}`;used.add(id);out.push({kind:"select-entity",id,label,count:typeof r.count==="number"?r.count:1,entity_type:"spell",where})}}}}return out}function memberChoices(entity){var _a,_b,_c,_d,_e,_f;if(!entity)return[];if((_a=entity.choices)==null?void 0:_a.length)return entity.choices;const out=[];const used=new Set;for(const fp of(_b=entity.feat_progression)!=null?_b:[]){const category=featProgressionCategory(fp.category);const count=progressionCount(fp.progression);if(!category||count<1)continue;const id=used.has("feat")?`feat-${used.size}`:"feat";used.add(id);out.push({kind:"select-entity",id,label:fp.name,count,entity_type:"feat",where:{category,edition:entity.edition}})}for(const op of(_c=entity.optionalfeature_progression)!=null?_c:[]){const codes=(_e=(_d=op.feature_type)!=null?_d:op.featureType)!=null?_e:[];const featureType=codes.map(c=>OPTIONAL_FEATURE_TYPE_CODE[c]).find(t=>!!t);const count=progressionCount(op.progression);if(!featureType||count<1){if(!featureType)warnOnce(`member-of-code:${entity.slug}`,`Archivist: "${entity.slug}" asks for optional features of type ${codes.join(", ")}, which this engine does not map; no pick is offered`);continue}const id=op.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"option";used.add(id);out.push({kind:"select-entity",id,label:op.name,count,entity_type:"optional-feature",where:{feature_type:featureType,edition:entity.edition}})}out.push(...spellChoices(entity,used));for(const pre of(_f=entity.prerequisites)!=null?_f:[]){if(pre.kind!=="spell-choose")continue;const where=spellFilter(pre.choose,entity.edition);if(!where||used.has("cantrip"))continue;used.add("cantrip");out.push({kind:"select-entity",id:"cantrip",label:where.level===0?"Cantrip":"Spell",count:1,entity_type:"spell",where,target:true})}return out}function memberSpellTargets(member,read){var _a;const refs=[];const open=[];for(const ch of memberChoices(member)){if(ch.kind!=="select-entity"||!isTargetChoice(ch)||ch.entity_type!=="spell")continue;const v=read(ch.id);const picked=(Array.isArray(v)?v:[v]).filter(x=>typeof x==="string"&&x.trim()!=="");if(picked.length)refs.push(...picked);else if(ch.where)open.push(ch.where)}for(const pre of(_a=member.prerequisites)!=null?_a:[])if(pre.kind==="spell-known")refs.push(pre.spell);return refs.length||open.length?{refs,open}:null}function spellMatchesFilter(d,where){var _a,_b;if(where.list&&!((_a=d.classes)!=null?_a:[]).includes(where.list))return false;if(where.level!==void 0&&((_b=d.level)!=null?_b:0)!==where.level)return false;if(where.edition&&d.edition!==where.edition)return false;if(where.ritual&&d.ritual!==true)return false;return true}function spellsReached(targets,spells){if(!targets)return[];const hit=new Set;for(const ref of targets.refs){const full=stripRef(ref);const exact=spells.filter(s=>s.slug===full);const bare=wikilinkTailSlug(ref);for(const s of exact.length?exact:spells.filter(s2=>bareEntitySlug(s2.slug)===bare))hit.add(s.slug)}for(const where of targets.open){const legal=new Set(spells.filter(s=>{var _a;return spellMatchesFilter(s.entity,where)&&!!((_a=s.entity.damage_roll)==null?void 0:_a.trim())}).map(s=>s.slug));if(legal.size===1)hit.add([...legal][0])}return[...new Set(spells.map(s=>s.slug))].filter(slug=>hit.has(slug))}function siteOf(classIndex,level,poolId,pickKey,member,memberSlug,block){const choices=memberChoices(member);if(!choices.length)return null;const prefix=`${poolId}:${pickKey}:`;return{classIndex,level,poolId,pickKey,member,memberSlug,choices,prefix,block,read:id=>block[`${prefix}${id}`]}}function poolMemberSites(classes,registry){const out=[];let byBare=null;let all=null;const lookup=(s,ownerPrefix)=>{all!=null?all:all=bucketOf(registry,"optional-feature");const bare=bareEntitySlug(s);const twin=twinKey(s);const owned=all.find(e=>twinKey(e.slug)===twin&&e.slug.split("_")[0]===ownerPrefix);if(owned)return owned;const direct=registry.getByTypeAndSlug("optional-feature",s);if(direct)return direct;byBare!=null?byBare:byBare=new Map(all.map(e=>[bareEntitySlug(e.slug),e]));return byBare.get(bare)};classes.forEach((rc,classIndex)=>{var _a,_b,_c,_d,_e;if(!rc.entity)return;const seen=new Set;for(const pool of[...(_a=rc.entity.selection_pools)!=null?_a:[],...(_c=(_b=rc.subclass)==null?void 0:_b.selection_pools)!=null?_c:[]]){if(seen.has(pool.id))continue;seen.add(pool.id);const{anchorLevel}=poolAnchorLevel(rc.entity,pool);const block=(_e=(_d=rc.choices)==null?void 0:_d[anchorLevel])!=null?_e:{};const raw=block[pool.id];const picks=Array.isArray(raw)?raw:typeof raw==="string"?[raw]:[];for(const s of picks){if(typeof s!=="string")continue;const{slugPart,param}=parsePickKey(s);const reg=lookup(slugPart,rc.entity.slug.split("_")[0]);if(!reg)continue;const member=reg.data;const key=member.repeatable===true||param!==null?s:reg.slug;const site=siteOf(classIndex,anchorLevel,pool.id,key,member,reg.slug,block);if(site)out.push(site)}}});return out}function poolMemberSitesOf(resolved){var _a,_b,_c,_d,_e;const out=[];for(const pool of(_a=resolved.pools)!=null?_a:[]){const block=(_e=(_d=(_c=(_b=resolved.classes)==null?void 0:_b[pool.classIndex])==null?void 0:_c.choices)==null?void 0:_d[pool.anchorLevel])!=null?_e:{};for(const e of heldPicks(pool)){const site=siteOf(pool.classIndex,pool.anchorLevel,pool.id,e.key,e.entity,e.slug,block);if(site)out.push(site)}}return out}var stripRef=ref=>ref.replace(/^\[\[/,"").replace(/\]\]$/,"");function featPickSites(classEntries,memberSites,classSlugOf){const out=[];(classEntries!=null?classEntries:[]).forEach((c,classIndex)=>{var _a;for(const[lvl,choiceBlock]of Object.entries((_a=c.choices)!=null?_a:{})){const block=choiceBlock;const feat=block==null?void 0:block.feat;if(!block||typeof feat!=="string")continue;const slug=stripRef(feat);if(!slug)continue;const level=/^\d+$/.test(lvl)?Number(lvl):null;const cls=classSlugOf(classIndex);out.push({slug,classIndex,level,via:cls&&level!==null?{kind:"class",slug:cls,level}:null,read:id=>block[`feat:${id}`]})}});for(const site of memberSites){for(const ch of site.choices){if(ch.kind!=="select-entity"||ch.entity_type!=="feat"||ch.target===true)continue;const v=site.read(ch.id);for(const ref of Array.isArray(v)?v:typeof v==="string"?[v]:[]){if(typeof ref!=="string")continue;const slug=stripRef(ref);if(!slug)continue;const cls=classSlugOf(site.classIndex);out.push({slug,classIndex:site.classIndex,level:site.level,via:cls?{kind:"pool",slug:site.memberSlug,name:site.member.name,classSlug:cls,level:site.level}:null,read:id=>site.block[`${site.prefix}feat:${id}`]})}}}return out}function raceFeatSites(race,originChoices){var _a;if(!race)return[];const oc=originChoices!=null?originChoices:{};const out=[];for(const list of[race.choices,...((_a=race.traits)!=null?_a:[]).map(t=>t==null?void 0:t.choices)]){for(const ch of Array.isArray(list)?list:[]){if((ch==null?void 0:ch.kind)!=="select-entity"||ch.entity_type!=="feat")continue;const v=oc[`race:${ch.id}`];for(const ref of Array.isArray(v)?v:typeof v==="string"?[v]:[]){const slug=typeof ref==="string"?stripRef(ref):"";if(slug)out.push({slug,via:{kind:"race",slug:race.slug},read:id=>oc[`race:feat:${id}`]})}}}return out}function featOfSite(site,feats){var _a;return(_a=feats.find(f=>f.slug===site.slug))!=null?_a:feats.find(f=>bareEntitySlug(f.slug)===bareEntitySlug(site.slug))}function nestedPickKeysToPrune(block,key,next){const prev=block==null?void 0:block[key];if(!block||!Array.isArray(prev))return[];const keep=new Set(next);const gone=prev.filter(k=>typeof k==="string"&&!keep.has(k));if(!gone.length)return[];return Object.keys(block).filter(k=>gone.some(g=>k.startsWith(`${key}:${g}:`)))}export{isTargetChoice,PACT_WEAPON_CHOICE_ID,pactWeaponPick,classPactWeaponPick,memberChoices,memberSpellTargets,spellsReached,poolMemberSites,poolMemberSitesOf,featPickSites,raceFeatSites,featOfSite,nestedPickKeysToPrune};
1
+ import{heldPicks,parsePickKey,poolAnchorLevel}from"./chunk-7S4VMK3R.js";import{featProgressionCategory}from"./chunk-3QQOATV3.js";import{warnOnce}from"./chunk-DZITM5AG.js";import{bucketOf}from"./chunk-QMEKQTUT.js";import{bareEntitySlug,twinKey,wikilinkTailSlug}from"./chunk-63YJPWTM.js";var OPTIONAL_FEATURE_TYPE_CODE={"MV:B":"maneuver",MV:"maneuver",EI:"invocation",MM:"metamagic","FS:F":"fighting_style"};function spellFilter(choose,edition){const where={edition};for(const part of choose.split("|")){const[rawKey,rawValue=""]=part.split("=");const key=rawKey.trim().toLowerCase();const value=rawValue.trim();if(key==="level"){const n=Number(value.split(";")[0]);if(!Number.isInteger(n))return null;where.level=n}else if(key==="class")where.list=value.toLowerCase();else if(key==="components & miscellaneous"&&/ritual/i.test(value))where.ritual=true}return where}function isTargetChoice(ch){return ch.kind==="select-entity"&&ch.target===true}var PACT_WEAPON_CHOICE_ID="pact-weapon";function pactWeaponPick(sites){for(const site of sites){for(const ch of site.choices){if(ch.kind!=="select-entity"||ch.id!==PACT_WEAPON_CHOICE_ID)continue;const v=site.read(ch.id);const first=Array.isArray(v)?v.find(x=>typeof x==="string"&&x.trim()!==""):v;if(typeof first!=="string"||!first.trim())continue;return first.trim().replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].trim()}}return void 0}function classPactWeaponPick(character,classes){var _a,_b,_c,_d,_e,_f,_g;const inBlock=(choices,block)=>{for(const ch of choices!=null?choices:[]){if(ch.kind==="select-inline"){const sel=block[ch.id];const branch=typeof sel==="string"?ch.options.find(o=>o.value===sel):void 0;const hit=inBlock(branch==null?void 0:branch.choices,block);if(hit)return hit}else if(ch.kind==="select-entity"&&ch.id===PACT_WEAPON_CHOICE_ID){const hit=pactWeaponPick([{choices:[ch],read:id=>block[id]}]);if(hit)return hit}}return void 0};for(let i=0;i<classes.length;i++){const entity=(_a=classes[i])==null?void 0:_a.entity;const entry=character.class[i];if(!entity||!entry)continue;for(const[lvl,raw]of Object.entries((_b=entry.choices)!=null?_b:{})){const block=raw!=null?raw:{};const features=[...(_d=((_c=entity.features_by_level)!=null?_c:{})[Number(lvl)])!=null?_d:[],...(_g=((_f=(_e=classes[i].subclass)==null?void 0:_e.features_by_level)!=null?_f:{})[Number(lvl)])!=null?_g:[]];for(const f of features){const hit=inBlock(f.choices,block);if(hit)return hit}}}return void 0}function progressionCount(p){var _a;if(Array.isArray(p))return 0;return(_a=p["*"])!=null?_a:Math.max(0,...Object.values(p))}function spellChoices(entity,used){var _a,_b;const out=[];for(const block of(_a=entity.additional_spells)!=null?_a:[]){for(const bucket of["known","prepared"]){const byLevel=block[bucket];if(!byLevel||typeof byLevel!=="object")continue;for(const rows of Object.values(byLevel)){for(const row of Array.isArray(rows)?rows:[]){const r=row;if(typeof r.choose!=="string")continue;const where=spellFilter(r.choose,entity.edition);if(!where)continue;const base=where.ritual?"rituals":where.level===0?"cantrips":`spells-${(_b=where.level)!=null?_b:"any"}`;const label=where.ritual?"Rituals":where.level===0?"Cantrips":`Level ${where.level} spells`;let id=base;for(let i=2;used.has(id);i++)id=`${base}-${i}`;used.add(id);out.push({kind:"select-entity",id,label,count:typeof r.count==="number"?r.count:1,entity_type:"spell",where})}}}}return out}function memberChoices(entity){var _a,_b,_c,_d,_e,_f;if(!entity)return[];if((_a=entity.choices)==null?void 0:_a.length)return entity.choices;const out=[];const used=new Set;for(const fp of(_b=entity.feat_progression)!=null?_b:[]){const category=featProgressionCategory(fp.category);const count=progressionCount(fp.progression);if(!category||count<1)continue;const id=used.has("feat")?`feat-${used.size}`:"feat";used.add(id);out.push({kind:"select-entity",id,label:fp.name,count,entity_type:"feat",where:{category,edition:entity.edition}})}for(const op of(_c=entity.optionalfeature_progression)!=null?_c:[]){const codes=(_e=(_d=op.feature_type)!=null?_d:op.featureType)!=null?_e:[];const featureType=codes.map(c=>OPTIONAL_FEATURE_TYPE_CODE[c]).find(t=>!!t);const count=progressionCount(op.progression);if(!featureType||count<1){if(!featureType)warnOnce(`member-of-code:${entity.slug}`,`Archivist: "${entity.slug}" asks for optional features of type ${codes.join(", ")}, which this engine does not map; no pick is offered`);continue}const id=op.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"option";used.add(id);out.push({kind:"select-entity",id,label:op.name,count,entity_type:"optional-feature",where:{feature_type:featureType,edition:entity.edition}})}out.push(...spellChoices(entity,used));for(const pre of(_f=entity.prerequisites)!=null?_f:[]){if(pre.kind!=="spell-choose")continue;const where=spellFilter(pre.choose,entity.edition);if(!where||used.has("cantrip"))continue;used.add("cantrip");out.push({kind:"select-entity",id:"cantrip",label:where.level===0?"Cantrip":"Spell",count:1,entity_type:"spell",where,target:true})}return out}function memberSpellTargets(member,read){var _a;const refs=[];const open=[];for(const ch of memberChoices(member)){if(ch.kind!=="select-entity"||!isTargetChoice(ch)||ch.entity_type!=="spell")continue;const v=read(ch.id);const picked=(Array.isArray(v)?v:[v]).filter(x=>typeof x==="string"&&x.trim()!=="");if(picked.length)refs.push(...picked);else if(ch.where)open.push(ch.where)}for(const pre of(_a=member.prerequisites)!=null?_a:[])if(pre.kind==="spell-known")refs.push(pre.spell);return refs.length||open.length?{refs,open}:null}function spellMatchesFilter(d,where){var _a,_b;if(where.list&&!((_a=d.classes)!=null?_a:[]).includes(where.list))return false;if(where.level!==void 0&&((_b=d.level)!=null?_b:0)!==where.level)return false;if(where.edition&&d.edition!==where.edition)return false;if(where.ritual&&d.ritual!==true)return false;return true}function spellsReached(targets,spells){if(!targets)return[];const hit=new Set;for(const ref of targets.refs){const full=stripRef(ref);const exact=spells.filter(s=>s.slug===full);const bare=wikilinkTailSlug(ref);for(const s of exact.length?exact:spells.filter(s2=>bareEntitySlug(s2.slug)===bare))hit.add(s.slug)}for(const where of targets.open){const legal=new Set(spells.filter(s=>{var _a;return spellMatchesFilter(s.entity,where)&&!!((_a=s.entity.damage_roll)==null?void 0:_a.trim())}).map(s=>s.slug));if(legal.size===1)hit.add([...legal][0])}return[...new Set(spells.map(s=>s.slug))].filter(slug=>hit.has(slug))}function siteOf(classIndex,level,poolId,pickKey,member,memberSlug,block){const choices=memberChoices(member);if(!choices.length)return null;const prefix=`${poolId}:${pickKey}:`;return{classIndex,level,poolId,pickKey,member,memberSlug,choices,prefix,block,read:id=>block[`${prefix}${id}`]}}function poolMemberSites(classes,registry){const out=[];let byBare=null;let all=null;const lookup=(s,ownerPrefix)=>{all!=null?all:all=bucketOf(registry,"optional-feature");const bare=bareEntitySlug(s);const twin=twinKey(s);const owned=all.find(e=>twinKey(e.slug)===twin&&e.slug.split("_")[0]===ownerPrefix);if(owned)return owned;const direct=registry.getByTypeAndSlug("optional-feature",s);if(direct)return direct;byBare!=null?byBare:byBare=new Map(all.map(e=>[bareEntitySlug(e.slug),e]));return byBare.get(bare)};classes.forEach((rc,classIndex)=>{var _a,_b,_c,_d,_e;if(!rc.entity)return;const seen=new Set;for(const pool of[...(_a=rc.entity.selection_pools)!=null?_a:[],...(_c=(_b=rc.subclass)==null?void 0:_b.selection_pools)!=null?_c:[]]){if(seen.has(pool.id))continue;seen.add(pool.id);const{anchorLevel}=poolAnchorLevel(rc.entity,pool);const block=(_e=(_d=rc.choices)==null?void 0:_d[anchorLevel])!=null?_e:{};const raw=block[pool.id];const picks=Array.isArray(raw)?raw:typeof raw==="string"?[raw]:[];for(const s of picks){if(typeof s!=="string")continue;const{slugPart,param}=parsePickKey(s);const reg=lookup(slugPart,rc.entity.slug.split("_")[0]);if(!reg)continue;const member=reg.data;const key=member.repeatable===true||param!==null?s:reg.slug;const site=siteOf(classIndex,anchorLevel,pool.id,key,member,reg.slug,block);if(site)out.push(site)}}});return out}function poolMemberSitesOf(resolved){var _a,_b,_c,_d,_e;const out=[];for(const pool of(_a=resolved.pools)!=null?_a:[]){const block=(_e=(_d=(_c=(_b=resolved.classes)==null?void 0:_b[pool.classIndex])==null?void 0:_c.choices)==null?void 0:_d[pool.anchorLevel])!=null?_e:{};for(const e of heldPicks(pool)){const site=siteOf(pool.classIndex,pool.anchorLevel,pool.id,e.key,e.entity,e.slug,block);if(site)out.push(site)}}return out}var stripRef=ref=>ref.replace(/^\[\[/,"").replace(/\]\]$/,"");function featPickSites(classEntries,memberSites,classSlugOf){const out=[];(classEntries!=null?classEntries:[]).forEach((c,classIndex)=>{var _a;for(const[lvl,choiceBlock]of Object.entries((_a=c.choices)!=null?_a:{})){const block=choiceBlock;const feat=block==null?void 0:block.feat;if(!block||typeof feat!=="string")continue;const slug=stripRef(feat);if(!slug)continue;const level=/^\d+$/.test(lvl)?Number(lvl):null;const cls=classSlugOf(classIndex);out.push({slug,classIndex,level,via:cls&&level!==null?{kind:"class",slug:cls,level}:null,read:id=>block[`feat:${id}`]})}});for(const site of memberSites){for(const ch of site.choices){if(ch.kind!=="select-entity"||ch.entity_type!=="feat"||ch.target===true)continue;const v=site.read(ch.id);for(const ref of Array.isArray(v)?v:typeof v==="string"?[v]:[]){if(typeof ref!=="string")continue;const slug=stripRef(ref);if(!slug)continue;const cls=classSlugOf(site.classIndex);out.push({slug,classIndex:site.classIndex,level:site.level,via:cls?{kind:"pool",slug:site.memberSlug,name:site.member.name,classSlug:cls,level:site.level}:null,read:id=>site.block[`${site.prefix}feat:${id}`]})}}}return out}function raceFeatSites(race,originChoices){var _a;if(!race)return[];const oc=originChoices!=null?originChoices:{};const out=[];for(const list of[race.choices,...((_a=race.traits)!=null?_a:[]).map(t=>t==null?void 0:t.choices)]){for(const ch of Array.isArray(list)?list:[]){if((ch==null?void 0:ch.kind)!=="select-entity"||ch.entity_type!=="feat")continue;const v=oc[`race:${ch.id}`];for(const ref of Array.isArray(v)?v:typeof v==="string"?[v]:[]){const slug=typeof ref==="string"?stripRef(ref):"";if(slug)out.push({slug,via:{kind:"race",slug:race.slug},read:id=>oc[`race:feat:${id}`]})}}}return out}function featOfSite(site,feats){var _a;return(_a=feats.find(f=>f.slug===site.slug))!=null?_a:feats.find(f=>bareEntitySlug(f.slug)===bareEntitySlug(site.slug))}function nestedPickKeysToPrune(block,key,next){const prev=block==null?void 0:block[key];if(!block||!Array.isArray(prev))return[];const keep=new Set(next);const gone=prev.filter(k=>typeof k==="string"&&!keep.has(k));if(!gone.length)return[];return Object.keys(block).filter(k=>gone.some(g=>k.startsWith(`${key}:${g}:`)))}export{isTargetChoice,PACT_WEAPON_CHOICE_ID,pactWeaponPick,classPactWeaponPick,memberChoices,memberSpellTargets,spellsReached,poolMemberSites,poolMemberSitesOf,featPickSites,raceFeatSites,featOfSite,nestedPickKeysToPrune};
@@ -1 +1 @@
1
- import{qualifiedGrantCovers}from"./chunk-T55DELVL.js";import{classifyWeaponRange}from"./chunk-SEOASDO4.js";import{resolveContainment}from"./chunk-4E2GIWJE.js";import{foldsNow,pushDefenseGrant}from"./chunk-B2JSF2LL.js";import{normKey}from"./chunk-VTQ4RWEG.js";import{itemBenefitsActive,itemLabel,itemRowEffects}from"./chunk-DXJ5NKKB.js";import{WEAPON_DEFAULT_ACTION_COST,resolveEntryEntity}from"./chunk-E4E6YEN6.js";import{isActivatedSpeedItem}from"./chunk-DVUXUIPV.js";import{readNumericBonus}from"./chunk-NEMX7QGG.js";import{defaultSlotForType,effectiveArmor,effectiveWeapon,isItemEntity,isShieldArmor,isTwoHandedWeapon,slotAcTerms}from"./chunk-4IAMSRHD.js";import{resolveBaseItem}from"./chunk-PZ4L2EEG.js";import{bareEntitySlug}from"./chunk-63YJPWTM.js";var MASTERY={cleave:{label:"Cleave",description:"If you hit a creature with a melee attack roll using this weapon, you can make an attack roll with the weapon against a second creature within 5 feet of the first that is also within your reach. On a hit, the second creature takes the weapon's damage, but don't add your ability modifier to that damage unless it is negative. You can make this extra attack only once per turn.",gist:"hit a 2nd creature in reach"},graze:{label:"Graze",description:"If your attack roll with this weapon misses a creature, you can deal damage to that creature equal to the ability modifier you used to make the attack roll. This damage is the same type dealt by the weapon, and the damage can be increased only by increasing the ability modifier.",gist:"on miss: ability-mod damage"},nick:{label:"Nick",description:"When you make the extra attack of the Light property, you can make it as part of the Attack action instead of as a Bonus Action. You can make this extra attack only once per turn.",gist:"extra Light attack (no Bonus Action)"},push:{label:"Push",description:"If you hit a creature with this weapon, you can push the creature up to 10 feet straight away from yourself if it is Large or smaller.",gist:"on hit: pushed 10 ft."},sap:{label:"Sap",description:"If you hit a creature with this weapon, that creature has Disadvantage on its next attack roll before the start of your next turn.",gist:"on hit: target Disadvantage"},slow:{label:"Slow",description:"If you hit a creature with this weapon and deal damage, you can reduce its Speed by 10 feet until the start of your next turn. If the creature is hit more than once by weapons that have this property, the Speed reduction doesn't exceed 10 feet.",gist:"on hit: -10 ft. Speed"},topple:{label:"Topple",description:"If you hit a creature with this weapon, you can force the creature to make a Constitution saving throw (DC 8 plus the ability modifier used to make the attack roll and your Proficiency Bonus). On a failed save, the creature has the Prone condition.",gist:"on fail: Prone"},vex:{label:"Vex",description:"If you hit a creature with this weapon and deal damage, you have Advantage on your next attack roll against that creature before the end of your next turn.",gist:"on hit: you gain Advantage next"}};function masteryGist(slug){var _a;return(_a=MASTERY[slug])==null?void 0:_a.gist}function masteryDerived(slug,abilityMod,proficiencyBonus){if(slug==="topple")return{label:"Save DC",value:8+proficiencyBonus+abilityMod};if(slug==="graze")return{label:"On miss",value:abilityMod};return void 0}var ABILITY_KEYS=["str","dex","con","int","wis","cha"];function isAbilityKey(k){return ABILITY_KEYS.includes(k)}function emptyAppliedBonuses(){return{ability_bonuses:{},ability_statics:{},ability_terms:[],ability_static_terms:[],save_bonus:0,save_terms:[],speed_bonuses:{walk:0,fly:null,swim:0,climb:0},speed_walk_set:0,speed_walk_set_terms:[],speed_terms:[],spell_attack:0,spell_save_dc:0,defenses:{resistances:[],immunities:[],vulnerabilities:[],condition_immunities:[]},informational:[],senses:{darkvision:0,blindsight:0,tremorsense:0,truesight:0}}}function unwrapSlug(item){const m=item.match(/^\[\[(.+)\]\]$/);return m?m[1]:null}function unwrapClassSlug(maybeWiki){if(!maybeWiki)return"";const m=/^\[\[([^\]]+)\]\]$/.exec(maybeWiki);return(m?m[1]:maybeWiki).toLowerCase()}function buildConditionContext(resolved,equippedSlots,registry){var _a,_b;return{derived:{equippedSlots},classList:(_a=resolved.definition.class)!=null?_a:[],race:resolved.definition.race,subclasses:((_b=resolved.definition.class)!=null?_b:[]).map(c=>c.subclass).filter(s=>typeof s==="string"&&s.length>0).map(unwrapClassSlug),registry}}function pushApply(outcome,field,source,pool,onApply){if(!outcome)return;if(outcome.kind==="applied")onApply(outcome.value);else if(outcome.kind==="informational"){pool.push({field,source,value:outcome.value,conditions:outcome.conditions})}}function isOtherSpeedMode(mode){return mode==="fly"||mode==="swim"||mode==="climb"||mode==="burrow"}function computeAppliedBonuses(resolved,_profs,registry,warnings){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u;const out=emptyAppliedBonuses();const equipment=(_a=resolved.definition.equipment)!=null?_a:[];const ctx=buildConditionContext(resolved,{},registry);for(let index=0;index<equipment.length;index++){const entry=equipment[index];const{entity,entityType}=resolveEntryEntity(entry,index,registry,resolved.infusions);if(!entity){const slug=unwrapSlug(entry.item);if(slug&&entry.equipped&&!((_b=resolved.infusions)==null?void 0:_b.views.has(index)))warnings.push(`Equipped item [[${slug}]] not found in compendium.`);continue}if(!itemBenefitsActive(entry,entity,registry,(_c=resolved.infusions)==null?void 0:_c.views.get(index)))continue;if(entityType!=="item")continue;const item=entity;const label=itemLabel(entry,item);const grant=(bucket,values)=>{for(const v of values!=null?values:[])if(typeof v==="string")pushDefenseGrant(out.defenses[bucket],v,label,void 0,{index,name:label})};grant("resistances",item.resist);grant("immunities",item.immune);grant("vulnerabilities",item.vulnerable);grant("condition_immunities",item.condition_immune);grant("resistances",(_d=entry.overrides)==null?void 0:_d.resist);grant("immunities",(_e=entry.overrides)==null?void 0:_e.immune);grant("vulnerabilities",(_f=entry.overrides)==null?void 0:_f.vulnerable);grant("condition_immunities",(_g=entry.overrides)==null?void 0:_g.condition_immune);const gs=(_h=item.grants)==null?void 0:_h.senses;if(gs){if(typeof gs.darkvision==="number")out.senses.darkvision=Math.max(out.senses.darkvision,gs.darkvision);if(typeof gs.blindsight==="number")out.senses.blindsight=Math.max(out.senses.blindsight,gs.blindsight);if(typeof gs.tremorsense==="number")out.senses.tremorsense=Math.max(out.senses.tremorsense,gs.tremorsense);if(typeof gs.truesight==="number")out.senses.truesight=Math.max(out.senses.truesight,gs.truesight)}const floor=(_j=(_i=item.modify_speed)==null?void 0:_i.static)==null?void 0:_j.walk;if(typeof floor==="number"&&floor>0){out.speed_walk_set=Math.max(out.speed_walk_set,floor);out.speed_walk_set_terms.push({source:label,amount:floor})}const activatedSpeed=isActivatedSpeedItem(String((_k=item.slug)!=null?_k:"")||((_l=unwrapSlug(entry.item))!=null?_l:entry.item),item);const itemSpeed=(mode,kind,amount)=>{if(!activatedSpeed&&isOtherSpeedMode(mode))out.speed_terms.push({mode,kind,source:label,amount})};for(const[mode,n]of Object.entries((_n=(_m=item.modify_speed)==null?void 0:_m.static)!=null?_n:{}))if(typeof n==="number"&&n>0)itemSpeed(mode,"grant",n);for(const[mode,to]of Object.entries((_p=(_o=item.modify_speed)==null?void 0:_o.equal)!=null?_p:{}))if(to==="walk")itemSpeed(mode,"walk",0);const b=item.bonuses;if(!b)continue;const saveSource=(_r=(_q=entry.overrides)==null?void 0:_q.name)!=null?_r:item.name;pushApply(readNumericBonus(b.saving_throws,ctx),"saving_throws",saveSource,out.informational,v=>{out.save_bonus+=v;out.save_terms.push({source:saveSource,amount:v})});pushApply(readNumericBonus(b.spell_attack,ctx),"spell_attack",item.name,out.informational,v=>{out.spell_attack+=v});pushApply(readNumericBonus(b.spell_save_dc,ctx),"spell_save_dc",item.name,out.informational,v=>{out.spell_save_dc+=v});if((_s=b.ability_scores)==null?void 0:_s.bonus){for(const[k,v]of Object.entries(b.ability_scores.bonus)){if(!isAbilityKey(k))continue;pushApply(readNumericBonus(v,ctx),`ability_scores.bonus.${k}`,item.name,out.informational,val=>{var _a2,_b2;out.ability_bonuses[k]=((_a2=out.ability_bonuses[k])!=null?_a2:0)+val;((_b2=out.ability_terms)!=null?_b2:out.ability_terms=[]).push({ability:k,source:saveSource,amount:val})})}}if((_t=b.ability_scores)==null?void 0:_t.static){for(const[k,n]of Object.entries(b.ability_scores.static)){if(!isAbilityKey(k)||typeof n!=="number")continue;((_u=out.ability_static_terms)!=null?_u:out.ability_static_terms=[]).push({ability:k,source:saveSource,value:n});const prev=out.ability_statics[k];if(prev===void 0){out.ability_statics[k]=n}else{if(n!==prev){warnings.push(`Multiple static ${k.toUpperCase()} bonuses on equipped+attuned items; using highest (${Math.max(prev,n)}).`)}out.ability_statics[k]=Math.max(prev,n)}}}if(b.speed){pushApply(readNumericBonus(b.speed.walk,ctx),"speed.walk",item.name,out.informational,v=>{out.speed_bonuses.walk+=v;out.speed_terms.push({mode:"walk",kind:"bonus",source:label,amount:v})});if(b.speed.fly==="walk"){out.speed_bonuses.fly="walk";itemSpeed("fly","walk",0)}else{pushApply(readNumericBonus(b.speed.fly,ctx),"speed.fly",item.name,out.informational,v=>{const cur=out.speed_bonuses.fly;out.speed_bonuses.fly=(typeof cur==="number"?cur:0)+v;itemSpeed("fly","grant",v)})}pushApply(readNumericBonus(b.speed.swim,ctx),"speed.swim",item.name,out.informational,v=>{out.speed_bonuses.swim+=v;itemSpeed("swim","grant",v)});pushApply(readNumericBonus(b.speed.climb,ctx),"speed.climb",item.name,out.informational,v=>{out.speed_bonuses.climb+=v;itemSpeed("climb","grant",v)})}}return out}function assignSlots(resolved,registry,warnings){var _a;const slots={};const eq=(_a=resolved.definition.equipment)!=null?_a:[];for(let i=0;i<eq.length;i++){const entry=eq[i];if(!entry.equipped||!entry.slot)continue;const{entity,entityType}=resolveEntryEntity(entry,i,registry,resolved.infusions);if(slots[entry.slot])continue;const placed={index:i,entity,entityType,entry};slots[entry.slot]=placed}for(let i=0;i<eq.length;i++){const entry=eq[i];if(!entry.equipped||entry.slot)continue;const{entity,entityType}=resolveEntryEntity(entry,i,registry,resolved.infusions);if(!entity||!entityType)continue;const defaultSlot=defaultSlotForType(entityType,entity,registry);if(!defaultSlot){if(isItemEntity(entity)&&typeof entity.base_item==="string"&&entity.base_item.length>0){warnings.push(`Magic item "${entity.name}" base_item ${entity.base_item} did not resolve to a base weapon or armor; not slotted (AC/attack not applied).`)}continue}const placed={index:i,entity,entityType,entry};if(defaultSlot==="mainhand"){if(!slots.mainhand)slots.mainhand=placed;else if(!slots.offhand)slots.offhand=placed}else if(!slots[defaultSlot]){slots[defaultSlot]=placed}}return slots}function pickShield(equippedSlots,equipment,registry,infusions){const slotted=equippedSlots.shield;const slottedArmor=effectiveArmor(slotted==null?void 0:slotted.entity,registry);if(slotted&&slottedArmor&&isShieldArmor(slottedArmor)){return{index:slotted.index,shield:slottedArmor,entity:slotted.entity,entry:slotted.entry}}for(let i=0;i<equipment.length;i++){const entry=equipment[i];if(!entry.equipped)continue;const{entity}=resolveEntryEntity(entry,i,registry,infusions);const armor=effectiveArmor(entity,registry);if(armor&&isShieldArmor(armor))return{index:i,shield:armor,entity,entry}}return null}function twoHandedShieldWarnings(equipment,registry,warnings,infusions){const equipped=equipment.flatMap((entry,i)=>{if(!entry.equipped)return[];const{entity}=resolveEntryEntity(entry,i,registry,infusions);return[{entry,entity}]});const isShield=e=>{const armor=effectiveArmor(e.entity,registry);return!!armor&&isShieldArmor(armor)};for(const e of equipped){if(!e.entity||!isTwoHandedWeapon(e.entity,registry))continue;if(!equipped.some(other=>other!==e&&isShield(other)))continue;warnings.push(`${e.entity.name} is two-handed and a Shield is also equipped.`)}}function computeAC(equippedSlots,resolved,mods,registry,warnings){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const breakdown=[];const armorSlot=equippedSlots.armor;const armorEntity=(_a=armorSlot==null?void 0:armorSlot.entity)!=null?_a:null;const armor=effectiveArmor(armorEntity,registry);if(isItemEntity(armorEntity)&&typeof armorEntity.base_item==="string"&&!armor){warnings.push(`Magic armor "${armorEntity.name}" base_item ${armorEntity.base_item} did not resolve to a base armor; AC not applied.`)}const acCtx=buildConditionContext(resolved,equippedSlots,registry);const skip=new Set;const slotBonus=slot=>{var _a2,_b2;const view=slot?(_a2=resolved.infusions)==null?void 0:_a2.views.get(slot.index):void 0;if(!slot||!(view==null?void 0:view.entity)||!isItemEntity(view.entity)||!itemBenefitsActive(slot.entry,view.entity,registry,view))return 0;const out=readNumericBonus((_b2=view.entity.bonuses)==null?void 0:_b2.ac,acCtx);if((out==null?void 0:out.kind)!=="applied")return 0;skip.add(slot.index);return out.value};const armorTerms=slotAcTerms(armor,armorSlot==null?void 0:armorSlot.entry);let ac=10;if(armor&&armorTerms.armor!==null){const armorBase=armorTerms.armor+slotBonus(armorSlot);ac=armorBase;breakdown.push({source:(_b=armorEntity==null?void 0:armorEntity.name)!=null?_b:armor.name,amount:armorBase,kind:"armor"});if(armor.ac.add_dex){const dexCap=(_c=armor.ac.dex_max)!=null?_c:Number.POSITIVE_INFINITY;const dexAdd=Math.min(mods.dex,dexCap);ac+=dexAdd;const capped=mods.dex>dexCap;breakdown.push({source:`DEX modifier${capped?" (capped)":""}`,amount:dexAdd,kind:"dex"})}}else{ac=10+mods.dex;breakdown.push({source:"Base",amount:10,kind:"unarmored"});breakdown.push({source:"DEX modifier",amount:mods.dex,kind:"dex"})}const acBonus=armorTerms.override;if(acBonus!==0){ac+=acBonus;breakdown.push({source:`${(_d=armorEntity==null?void 0:armorEntity.name)!=null?_d:"Armor"} (override)`,amount:acBonus,kind:"override"})}const picked=pickShield(equippedSlots,(_e=resolved.definition.equipment)!=null?_e:[],registry,resolved.infusions);if(picked){const{shield,entity:shieldEntity}=picked;const shieldTerms=slotAcTerms(shield,picked.entry);const n=shieldTerms.armor+slotBonus(picked);ac+=n;breakdown.push({source:(_f=shieldEntity==null?void 0:shieldEntity.name)!=null?_f:shield.name,amount:n,kind:"shield"});const shieldAcBonus=shieldTerms.override;if(shieldAcBonus!==0){ac+=shieldAcBonus;breakdown.push({source:`${(_g=shieldEntity==null?void 0:shieldEntity.name)!=null?_g:shield.name} (override)`,amount:shieldAcBonus,kind:"shield"})}}const acInformational=[];const acEquipment=(_h=resolved.definition.equipment)!=null?_h:[];for(let index=0;index<acEquipment.length;index++){if(skip.has(index))continue;const entry=acEquipment[index];const{entity,entityType}=resolveEntryEntity(entry,index,registry,resolved.infusions);if(!entity||entityType!=="item")continue;if(!itemBenefitsActive(entry,entity,registry,(_i=resolved.infusions)==null?void 0:_i.views.get(index)))continue;const item=entity;const out=readNumericBonus((_j=item.bonuses)==null?void 0:_j.ac,acCtx);if(!out)continue;if(out.kind==="applied"){ac+=out.value;breakdown.push({source:item.name,amount:out.value,kind:"item"})}else if(out.kind==="informational"){acInformational.push({field:"ac",source:item.name,value:out.value,conditions:out.conditions})}}return{ac,breakdown,informational:acInformational}}function hasProperty(weapon,prop){return weapon.properties.some(p=>p===prop)}function attackAbility(weapon,mods,weaponAbilities){const modes=classifyWeaponRange(weapon);const finesse=hasProperty(weapon,"finesse");if(modes.melee){const scoped=weaponAbilities.find(o2=>{var _a;return(_a=o2.weaponSlugs)==null?void 0:_a.includes(bareEntitySlug(weapon.slug))});const glob=weaponAbilities.find(o2=>!o2.weaponSlugs);const o=scoped!=null?scoped:glob;if(o)return o.ability;if(finesse)return mods.dex>=mods.str?"dex":"str";return"str"}return finesse&&mods.str>mods.dex?"str":"dex"}function pactScopedAbilities(overrides,pactPicked,isPact){if(!overrides.some(o=>o.pactWeapon))return overrides;return overrides.flatMap(o=>{if(!o.pactWeapon)return[o];return!pactPicked||isPact?[{ability:o.ability}]:[]})}function pactWeaponIndexes(resolved,registry){var _a;const pick=resolved.pactWeapon;if(!pick)return null;const out=new Set;const bare=bareEntitySlug(pick);((_a=resolved.definition.equipment)!=null?_a:[]).forEach((entry,i)=>{var _a2;if(typeof entry.item!=="string")return;const slugs=[unwrapSlug(entry.item),registry?(_a2=resolveBaseItem(entry.item,registry))==null?void 0:_a2.slug:void 0];if(slugs.some(s=>!!s&&(s===pick||bareEntitySlug(s)===bare)))out.add(i)});return out.size?out:null}function isWeaponSlugProficient(weapon,weaponSlug,profs){const wp=profs.weapons;if(wp.specific.some(e=>e===weaponSlug||normKey(e)===normKey(weapon.name)))return true;if(wp.specific.some(e=>qualifiedGrantCovers(e,weapon)))return true;const cat=weapon.category;if(typeof cat==="string"){if(/^simple\b/.test(cat)&&wp.categories.includes("simple"))return true;if(/^martial\b/.test(cat)&&wp.categories.includes("martial"))return true;if(wp.categories.includes(cat))return true}return false}function magicBonusesForWeaponEntry(entry,registry,ctx,index,infusions){var _a,_b,_c,_d;const{entity}=resolveEntryEntity(entry,index,registry,infusions);const ovr=(_a=entry.overrides)!=null?_a:{};const entryAttack=typeof ovr.bonus==="number"?ovr.bonus:0;const entryDamage=typeof ovr.damage_bonus==="number"?ovr.damage_bonus:0;const extra=typeof ovr.extra_damage==="string"?ovr.extra_damage:void 0;let itemAttack=0;let itemDamage=0;let sourceName;let itemName;let damageTypeOverride;let propertiesOverride;const informational=[];let itemRiders=[];let critRange;const conditionalCrits=[];if(entity&&isItemEntity(entity)){sourceName=entity.name;itemName=entity.name;damageTypeOverride=typeof entity.damage_type==="string"&&entity.damage_type.length>0?entity.damage_type:void 0;propertiesOverride=Array.isArray(entity.properties)&&entity.properties.length>0?entity.properties:void 0}if(entity&&isItemEntity(entity)&&itemBenefitsActive(entry,entity,registry,infusions==null?void 0:infusions.views.get(index))){const b=entity.bonuses;const atkOut=readNumericBonus(b==null?void 0:b.weapon_attack,ctx);const dmgOut=readNumericBonus(b==null?void 0:b.weapon_damage,ctx);if((atkOut==null?void 0:atkOut.kind)==="applied")itemAttack=atkOut.value;else if((atkOut==null?void 0:atkOut.kind)==="informational")informational.push({field:"weapon_attack",source:entity.name,value:atkOut.value,conditions:atkOut.conditions});if((dmgOut==null?void 0:dmgOut.kind)==="applied")itemDamage=dmgOut.value;else if((dmgOut==null?void 0:dmgOut.kind)==="informational")informational.push({field:"weapon_damage",source:entity.name,value:dmgOut.value,conditions:dmgOut.conditions});itemRiders=Array.isArray(entity.damage_riders)?entity.damage_riders.filter(r=>{var _a2;return((_a2=r.applies_to)!=null?_a2:"weapon")!=="spell"}).map(r=>({amount:r.amount,damage_type:r.damage_type,source:entity.name,...r.condition?{condition:r.condition}:{}})):[];for(const eff of itemRowEffects(entity)){if(eff.kind==="damage-bonus"&&((_b=eff.applies_to)!=null?_b:"weapon")!=="spell"){itemRiders.push({amount:eff.amount,damage_type:eff.damage_type,source:entity.name,...eff.condition?{condition:eff.condition}:{}})}else if(eff.kind==="crit-range"&&((_c=eff.applies_to)!=null?_c:"weapon")!=="spell"){if((_d=eff.condition)==null?void 0:_d.trim())conditionalCrits.push({minRoll:eff.min_roll,condition:eff.condition.trim(),source:entity.name});else critRange=Math.min(critRange!=null?critRange:20,eff.min_roll)}}}return{...critRange!==void 0&&critRange<20?{critRange}:{},...conditionalCrits.length?{conditionalCrits}:{},atk:itemAttack+entryAttack,dmg:itemDamage+entryDamage,extra,sourceName,itemName,damageTypeOverride,propertiesOverride,informational,riders:itemRiders}}function buildAttackRow(args){var _a,_b,_c,_d;const{id,name,weapon,baseDice,ability,mods,proficient,proficiencyBonus,magic,weaponMasteries}=args;const abilityMod=mods[ability];const pb=proficient?proficiencyBonus:0;const toHit=abilityMod+pb+magic.atk;const dmgFlat=abilityMod+magic.dmg;const formatDice=dice=>`${dice}${dmgFlat>=0?"+":""}${dmgFlat}`.replace(/\+0$/,"");const damageDice=formatDice(baseDice);const magicSource=magic.sourceName?`${magic.sourceName} bonus`:"Magic weapon";const toHitBreakdown=[{source:`${ability.toUpperCase()} modifier`,amount:abilityMod,kind:"ability"},{source:"Proficiency bonus",amount:proficient?proficiencyBonus:0,kind:"ability"},{source:magicSource,amount:magic.atk,kind:"item"}];const damageBreakdown=[{source:"Base damage",amount:0,kind:"ability"},{source:`${ability.toUpperCase()} modifier`,amount:abilityMod,kind:"ability"},{source:magicSource,amount:magic.dmg,kind:"item"}];const modes=classifyWeaponRange(weapon);const fmtRanged=r=>r.long>r.normal?`${r.normal}/${r.long} ft.`:`${r.normal} ft.`;const range=modes.melee?`${modes.melee.reach} ft.`:modes.ranged?fmtRanged(modes.ranged):void 0;const thrownRange=modes.melee&&modes.ranged?fmtRanged(modes.ranged):void 0;const stringProps=weapon.properties.filter(p=>typeof p==="string");const finalProps=(_a=magic.propertiesOverride)!=null?_a:stringProps;const row={id,name,...range!==void 0?{range}:{},...thrownRange!==void 0?{thrownRange}:{},toHit,damageDice,damageType:(_b=magic.damageTypeOverride)!=null?_b:weapon.damage.type,...(()=>{const riders=[...magic.riders,...magic.extra?[{amount:magic.extra}]:[]];return riders.length?{damageRiders:riders}:{}})(),weaponCategory:modes.melee?"melee":"ranged",properties:finalProps,proficient,breakdown:{toHit:toHitBreakdown,damage:damageBreakdown},informational:args.magic.informational.length>0?args.magic.informational:void 0,slotKey:args.slotKey,subLabel:formatWeaponSubLabel(weapon,finalProps,modes),actionCost:args.actionCost,versatile:args.versatileDice?{damageDice:formatDice(args.versatileDice)}:void 0,...magic.critRange!==void 0?{critRange:magic.critRange}:{},...((_c=magic.conditionalCrits)==null?void 0:_c.length)?{conditionalCrits:magic.conditionalCrits}:{}};const mSlug=(_d=weapon.mastery)==null?void 0:_d[0];if(mSlug&&proficient&&weaponMasteries.includes(bareEntitySlug(weapon.slug))){const g=MASTERY[mSlug];if(g){const derived=masteryDerived(mSlug,mods[ability],proficiencyBonus);row.mastery={slug:mSlug,label:g.label,description:g.description,gist:masteryGist(mSlug),...derived?{derived}:{}}}}return row}function buildUnarmedRow(mods,proficiencyBonus,spec){var _a;const strike=unarmedStrikeNumbers(mods,proficiencyBonus,["str",...(_a=spec==null?void 0:spec.abilities)!=null?_a:[]],spec==null?void 0:spec.dice);return{id:"unarmed-strike",name:"Unarmed Strike",unarmed:true,range:"5 ft.",...strike,damageType:"bludgeoning",properties:[],proficient:true,subLabel:"Unarmed",actionCost:"action"}}function unarmedStrikeNumbers(mods,proficiencyBonus,candidates,dice){var _a;let ability=(_a=candidates[0])!=null?_a:"str";for(const ab of candidates)if(mods[ab]>=mods[ability])ability=ab;const abilityMod=mods[ability];const flat=`${abilityMod>=0?"+":""}${abilityMod}`.replace(/^\+0$/,"");const label=`${ability.toUpperCase()} modifier`;return{toHit:abilityMod+proficiencyBonus,damageDice:dice?`${dice}${flat}`:String(Math.max(0,1+abilityMod)),breakdown:{toHit:[{source:label,amount:abilityMod,kind:"ability"},{source:"Proficiency bonus",amount:proficiencyBonus,kind:"ability"}],damage:[{source:"Base damage",amount:dice?0:1,kind:"ability"},{source:label,amount:abilityMod,kind:"ability"}]}}}function buildFeatureAttackRows(resolved,mods,profs,proficiencyBonus,weaponAbilities=[],opts={}){var _a,_b,_c,_d;const rows=[];const abilities=weaponAbilities.filter(o=>!o.pactWeapon);const active=new Set((_a=opts.activeBuffs)!=null?_a:[]);for(const rf of(_b=resolved.features)!=null?_b:[]){if(rf.renderSuppressed||rf.buildOnly||!foldsNow(rf,active))continue;const featureId=(_c=rf.feature.id)!=null?_c:rf.feature.name;((_d=rf.feature.attacks)!=null?_d:[]).forEach((a,n)=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h;const id=`feature-attack:${rf.source.kind}:${rf.source.slug}:${featureId}:${n}`;if(!a.weapon_category&&a.unarmed===true){const natural=buildNaturalWeaponRow(a,id,mods,proficiencyBonus,(_a2=opts.unarmedAbilities)!=null?_a2:[]);if(natural)rows.push({...natural,grantedBy:rf.feature.name});return}if(!a.weapon_category||a.type!=="melee"&&a.type!=="ranged"||typeof a.damage!=="string"||!a.damage.trim())return;const long=(_d2=(_b2=a.range)==null?void 0:_b2.long)!=null?_d2:(_c2=a.range)==null?void 0:_c2.normal;const weapon={name:a.name,slug:`feature-attack_${featureId}_${n}`,category:`${a.weapon_category}-${a.type}`,damage:{dice:a.damage.trim(),type:(_e=a.damage_type)!=null?_e:""},properties:((_f=a.properties)!=null?_f:[]).map(p=>p.trim().toLowerCase()),...((_g=a.range)==null?void 0:_g.normal)!==void 0&&long!==void 0?{range:{normal:a.range.normal,long}}:{},...a.mastery?{mastery:[a.mastery.trim().toLowerCase()]}:{}};const proficient=isWeaponSlugProficient(weapon,weapon.slug,profs);const row=buildAttackRow({id,name:a.name,weapon,baseDice:weapon.damage.dice,ability:attackAbility(weapon,mods,abilities),mods,proficient,proficiencyBonus,magic:{atk:0,dmg:0,informational:[],riders:[]},actionCost:(_h=a.action)!=null?_h:WEAPON_DEFAULT_ACTION_COST,weaponMasteries:a.mastery?[bareEntitySlug(weapon.slug)]:[]});row.grantedBy=rf.feature.name;rows.push(row)})}return rows}function buildNaturalWeaponRow(a,id,mods,proficiencyBonus,unarmedAbilities){var _a,_b,_c,_d;const dice=typeof a.damage==="string"?a.damage.trim():"";if(a.type!=="melee"||!dice)return null;const own=a.ability===void 0?["str"]:Array.isArray(a.ability)?[...a.ability]:[a.ability];return{id,name:a.name,naturalWeapon:true,range:`${(_b=(_a=a.range)==null?void 0:_a.reach)!=null?_b:5} ft.`,...unarmedStrikeNumbers(mods,proficiencyBonus,[...own,...unarmedAbilities],dice),damageType:((_c=a.damage_type)==null?void 0:_c.trim())||"bludgeoning",properties:[],proficient:true,subLabel:"Unarmed",actionCost:(_d=a.action)!=null?_d:"action"}}function humanizeWeaponToken(s){return s.replace(/[-_]/g," ").replace(/(^|[\s(])\w/g,c=>c.toUpperCase())}function formatWeaponSubLabel(weapon,properties,modes){const parts=[];if(weapon.category){const cat=modes.melee&&/ranged/.test(weapon.category)?weapon.category.replace("ranged","melee"):weapon.category;parts.push(humanizeWeaponToken(cat))}if(properties.length>0)parts.push(properties.map(humanizeWeaponToken).join(", "));return parts.join(" \xB7 ")}function computeAttacks(equippedSlots,equipment,mods,profs,registry,warnings,proficiencyBonus,ctx,weaponMasteries,weaponAbilities=[],infusions,pactIndexes=null){var _a,_b;const rows=[];const rowFor=(index,entry,weapon,slotKey,versatileDice)=>{var _a2,_b2,_c,_d,_e;const slugFromEntry=(_a2=unwrapSlug(entry.item))!=null?_a2:weapon.slug;const proficient=isWeaponSlugProficient(weapon,slugFromEntry,profs)||isWeaponSlugProficient(weapon,weapon.slug,profs);if(!proficient){warnings.push(`Character not proficient with ${weapon.name}; proficiency bonus excluded.`)}const isPact=(pactIndexes==null?void 0:pactIndexes.has(index))===true;const ability=attackAbility(weapon,mods,pactScopedAbilities(weaponAbilities,pactIndexes!==null,isPact));const magic=magicBonusesForWeaponEntry(entry,registry,ctx,index,infusions);const ovr=(_b2=entry.overrides)!=null?_b2:{};const row=buildAttackRow({id:`${index}:standard`,name:(_d=(_c=ovr.name)!=null?_c:magic.itemName)!=null?_d:weapon.name,weapon,baseDice:weapon.damage.dice,ability,mods,proficient,proficiencyBonus,magic,slotKey,actionCost:(_e=ovr.action)!=null?_e:WEAPON_DEFAULT_ACTION_COST,versatileDice,weaponMasteries});if(isPact)row.pactWeapon=true;return row};const handedSlots=[{key:"mainhand",placed:equippedSlots.mainhand},{key:"offhand",placed:equippedSlots.offhand}];for(const{key,placed}of handedSlots){if(!placed)continue;const{entity,entry}=placed;if(!entity)continue;const weapon=effectiveWeapon(entity,registry);if(!weapon){if(isItemEntity(entity)&&typeof entity.base_item==="string"&&!resolveBaseItem(entity.base_item,registry)){warnings.push(`Magic weapon ${entity.name} references missing base_item ${entity.base_item}.`)}continue}const versatileDice=key==="mainhand"&&hasProperty(weapon,"versatile")&&typeof weapon.damage.versatile_dice==="string"&&!equippedSlots.offhand?weapon.damage.versatile_dice:void 0;rows.push(rowFor(placed.index,entry,weapon,key,versatileDice))}const handIndex=new Set([(_a=equippedSlots.mainhand)==null?void 0:_a.index,(_b=equippedSlots.offhand)==null?void 0:_b.index]);equipment.forEach((entry,index)=>{if(!entry.equipped||handIndex.has(index))return;const{entity}=resolveEntryEntity(entry,index,registry,infusions);const weapon=effectiveWeapon(entity,registry);if(!weapon)return;rows.push(rowFor(index,entry,weapon))});return rows}function coerceWeight(raw){if(typeof raw==="number"&&Number.isFinite(raw)&&raw>=0)return raw;if(typeof raw==="string"){const n=Number.parseFloat(raw);if(Number.isFinite(n)&&n>=0)return n}return 0}function computeCarriedWeight(resolved,registry){var _a;const equipment=(_a=resolved.definition.equipment)!=null?_a:[];const view=resolveContainment(equipment,registry);const weightlessContainer=equipment.map(entry=>{var _a2,_b,_c;const data=(_a2=resolveBaseItem(entry.item,registry))==null?void 0:_a2.data;return((_c=(_b=data==null?void 0:data.container)==null?void 0:_b.capacity)==null?void 0:_c.weightless)===true});const exempt=i=>{for(let p=view.parentOf[i];p!==null;p=view.parentOf[p])if(weightlessContainer[p])return true;return false};let total=0;equipment.forEach((entry,i)=>{if(exempt(i))return;const found=resolveBaseItem(entry.item,registry);if(!found)return;const entity=found.data;const w=coerceWeight(entity.weight);if(w===0)return;const qty=typeof entry.qty==="number"&&entry.qty>=0?entry.qty:1;total+=w*qty});return total}function computeSlotsAndAttacks(resolved,mods,profs,registry,warnings,proficiencyBonus,weaponAbilities=[],weaponMasteries=[],attunementFloor=0){var _a,_b,_c,_d,_e;const equippedSlots=assignSlots(resolved,registry,warnings);twoHandedShieldWarnings((_a=resolved.definition.equipment)!=null?_a:[],registry,warnings,resolved.infusions);const overrides=(_b=resolved.definition.overrides)!=null?_b:{};const acOut=computeAC(equippedSlots,resolved,mods,registry,warnings);const ctx=buildConditionContext(resolved,equippedSlots,registry);const attacks=computeAttacks(equippedSlots,(_c=resolved.definition.equipment)!=null?_c:[],mods,profs,registry,warnings,proficiencyBonus,ctx,weaponMasteries,weaponAbilities,resolved.infusions,pactWeaponIndexes(resolved,registry));return{ac:acOut.ac,acBreakdown:acOut.breakdown,acInformational:acOut.informational,attacks,equippedSlots,carriedWeight:computeCarriedWeight(resolved,registry),attunementUsed:((_d=resolved.definition.equipment)!=null?_d:[]).filter(e=>e.attuned).length,attunementLimit:(_e=overrides.attunement_limit)!=null?_e:Math.max(3,attunementFloor)}}export{emptyAppliedBonuses,computeAppliedBonuses,pactWeaponIndexes,isWeaponSlugProficient,buildUnarmedRow,buildFeatureAttackRows,computeSlotsAndAttacks};
1
+ import{qualifiedGrantCovers}from"./chunk-T55DELVL.js";import{classifyWeaponRange}from"./chunk-SEOASDO4.js";import{resolveContainment}from"./chunk-4E2GIWJE.js";import{foldsNow,pushDefenseGrant}from"./chunk-KWETUSIQ.js";import{normKey}from"./chunk-VTQ4RWEG.js";import{itemBenefitsActive,itemLabel,itemRowEffects}from"./chunk-ZYMWQ7PG.js";import{WEAPON_DEFAULT_ACTION_COST,resolveEntryEntity}from"./chunk-7S4VMK3R.js";import{isActivatedSpeedItem}from"./chunk-DVUXUIPV.js";import{readNumericBonus}from"./chunk-NEMX7QGG.js";import{defaultSlotForType,effectiveArmor,effectiveWeapon,isItemEntity,isShieldArmor,isTwoHandedWeapon,slotAcTerms}from"./chunk-4IAMSRHD.js";import{resolveBaseItem}from"./chunk-PZ4L2EEG.js";import{bareEntitySlug}from"./chunk-63YJPWTM.js";var MASTERY={cleave:{label:"Cleave",description:"If you hit a creature with a melee attack roll using this weapon, you can make an attack roll with the weapon against a second creature within 5 feet of the first that is also within your reach. On a hit, the second creature takes the weapon's damage, but don't add your ability modifier to that damage unless it is negative. You can make this extra attack only once per turn.",gist:"hit a 2nd creature in reach"},graze:{label:"Graze",description:"If your attack roll with this weapon misses a creature, you can deal damage to that creature equal to the ability modifier you used to make the attack roll. This damage is the same type dealt by the weapon, and the damage can be increased only by increasing the ability modifier.",gist:"on miss: ability-mod damage"},nick:{label:"Nick",description:"When you make the extra attack of the Light property, you can make it as part of the Attack action instead of as a Bonus Action. You can make this extra attack only once per turn.",gist:"extra Light attack (no Bonus Action)"},push:{label:"Push",description:"If you hit a creature with this weapon, you can push the creature up to 10 feet straight away from yourself if it is Large or smaller.",gist:"on hit: pushed 10 ft."},sap:{label:"Sap",description:"If you hit a creature with this weapon, that creature has Disadvantage on its next attack roll before the start of your next turn.",gist:"on hit: target Disadvantage"},slow:{label:"Slow",description:"If you hit a creature with this weapon and deal damage, you can reduce its Speed by 10 feet until the start of your next turn. If the creature is hit more than once by weapons that have this property, the Speed reduction doesn't exceed 10 feet.",gist:"on hit: -10 ft. Speed"},topple:{label:"Topple",description:"If you hit a creature with this weapon, you can force the creature to make a Constitution saving throw (DC 8 plus the ability modifier used to make the attack roll and your Proficiency Bonus). On a failed save, the creature has the Prone condition.",gist:"on fail: Prone"},vex:{label:"Vex",description:"If you hit a creature with this weapon and deal damage, you have Advantage on your next attack roll against that creature before the end of your next turn.",gist:"on hit: you gain Advantage next"}};function masteryGist(slug){var _a;return(_a=MASTERY[slug])==null?void 0:_a.gist}function masteryDerived(slug,abilityMod,proficiencyBonus){if(slug==="topple")return{label:"Save DC",value:8+proficiencyBonus+abilityMod};if(slug==="graze")return{label:"On miss",value:abilityMod};return void 0}var ABILITY_KEYS=["str","dex","con","int","wis","cha"];function isAbilityKey(k){return ABILITY_KEYS.includes(k)}function emptyAppliedBonuses(){return{ability_bonuses:{},ability_statics:{},ability_terms:[],ability_static_terms:[],save_bonus:0,save_terms:[],speed_bonuses:{walk:0,fly:null,swim:0,climb:0},speed_walk_set:0,speed_walk_set_terms:[],speed_terms:[],spell_attack:0,spell_save_dc:0,defenses:{resistances:[],immunities:[],vulnerabilities:[],condition_immunities:[]},informational:[],senses:{darkvision:0,blindsight:0,tremorsense:0,truesight:0}}}function unwrapSlug(item){const m=item.match(/^\[\[(.+)\]\]$/);return m?m[1]:null}function unwrapClassSlug(maybeWiki){if(!maybeWiki)return"";const m=/^\[\[([^\]]+)\]\]$/.exec(maybeWiki);return(m?m[1]:maybeWiki).toLowerCase()}function buildConditionContext(resolved,equippedSlots,registry){var _a,_b;return{derived:{equippedSlots},classList:(_a=resolved.definition.class)!=null?_a:[],race:resolved.definition.race,subclasses:((_b=resolved.definition.class)!=null?_b:[]).map(c=>c.subclass).filter(s=>typeof s==="string"&&s.length>0).map(unwrapClassSlug),registry}}function pushApply(outcome,field,source,pool,onApply){if(!outcome)return;if(outcome.kind==="applied")onApply(outcome.value);else if(outcome.kind==="informational"){pool.push({field,source,value:outcome.value,conditions:outcome.conditions})}}function isOtherSpeedMode(mode){return mode==="fly"||mode==="swim"||mode==="climb"||mode==="burrow"}function computeAppliedBonuses(resolved,_profs,registry,warnings){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u;const out=emptyAppliedBonuses();const equipment=(_a=resolved.definition.equipment)!=null?_a:[];const ctx=buildConditionContext(resolved,{},registry);for(let index=0;index<equipment.length;index++){const entry=equipment[index];const{entity,entityType}=resolveEntryEntity(entry,index,registry,resolved.infusions);if(!entity){const slug=unwrapSlug(entry.item);if(slug&&entry.equipped&&!((_b=resolved.infusions)==null?void 0:_b.views.has(index)))warnings.push(`Equipped item [[${slug}]] not found in compendium.`);continue}if(!itemBenefitsActive(entry,entity,registry,(_c=resolved.infusions)==null?void 0:_c.views.get(index)))continue;if(entityType!=="item")continue;const item=entity;const label=itemLabel(entry,item);const grant=(bucket,values)=>{for(const v of values!=null?values:[])if(typeof v==="string")pushDefenseGrant(out.defenses[bucket],v,label,void 0,{index,name:label})};grant("resistances",item.resist);grant("immunities",item.immune);grant("vulnerabilities",item.vulnerable);grant("condition_immunities",item.condition_immune);grant("resistances",(_d=entry.overrides)==null?void 0:_d.resist);grant("immunities",(_e=entry.overrides)==null?void 0:_e.immune);grant("vulnerabilities",(_f=entry.overrides)==null?void 0:_f.vulnerable);grant("condition_immunities",(_g=entry.overrides)==null?void 0:_g.condition_immune);const gs=(_h=item.grants)==null?void 0:_h.senses;if(gs){if(typeof gs.darkvision==="number")out.senses.darkvision=Math.max(out.senses.darkvision,gs.darkvision);if(typeof gs.blindsight==="number")out.senses.blindsight=Math.max(out.senses.blindsight,gs.blindsight);if(typeof gs.tremorsense==="number")out.senses.tremorsense=Math.max(out.senses.tremorsense,gs.tremorsense);if(typeof gs.truesight==="number")out.senses.truesight=Math.max(out.senses.truesight,gs.truesight)}const floor=(_j=(_i=item.modify_speed)==null?void 0:_i.static)==null?void 0:_j.walk;if(typeof floor==="number"&&floor>0){out.speed_walk_set=Math.max(out.speed_walk_set,floor);out.speed_walk_set_terms.push({source:label,amount:floor})}const activatedSpeed=isActivatedSpeedItem(String((_k=item.slug)!=null?_k:"")||((_l=unwrapSlug(entry.item))!=null?_l:entry.item),item);const itemSpeed=(mode,kind,amount)=>{if(!activatedSpeed&&isOtherSpeedMode(mode))out.speed_terms.push({mode,kind,source:label,amount})};for(const[mode,n]of Object.entries((_n=(_m=item.modify_speed)==null?void 0:_m.static)!=null?_n:{}))if(typeof n==="number"&&n>0)itemSpeed(mode,"grant",n);for(const[mode,to]of Object.entries((_p=(_o=item.modify_speed)==null?void 0:_o.equal)!=null?_p:{}))if(to==="walk")itemSpeed(mode,"walk",0);const b=item.bonuses;if(!b)continue;const saveSource=(_r=(_q=entry.overrides)==null?void 0:_q.name)!=null?_r:item.name;pushApply(readNumericBonus(b.saving_throws,ctx),"saving_throws",saveSource,out.informational,v=>{out.save_bonus+=v;out.save_terms.push({source:saveSource,amount:v})});pushApply(readNumericBonus(b.spell_attack,ctx),"spell_attack",item.name,out.informational,v=>{out.spell_attack+=v});pushApply(readNumericBonus(b.spell_save_dc,ctx),"spell_save_dc",item.name,out.informational,v=>{out.spell_save_dc+=v});if((_s=b.ability_scores)==null?void 0:_s.bonus){for(const[k,v]of Object.entries(b.ability_scores.bonus)){if(!isAbilityKey(k))continue;pushApply(readNumericBonus(v,ctx),`ability_scores.bonus.${k}`,item.name,out.informational,val=>{var _a2,_b2;out.ability_bonuses[k]=((_a2=out.ability_bonuses[k])!=null?_a2:0)+val;((_b2=out.ability_terms)!=null?_b2:out.ability_terms=[]).push({ability:k,source:saveSource,amount:val})})}}if((_t=b.ability_scores)==null?void 0:_t.static){for(const[k,n]of Object.entries(b.ability_scores.static)){if(!isAbilityKey(k)||typeof n!=="number")continue;((_u=out.ability_static_terms)!=null?_u:out.ability_static_terms=[]).push({ability:k,source:saveSource,value:n});const prev=out.ability_statics[k];if(prev===void 0){out.ability_statics[k]=n}else{if(n!==prev){warnings.push(`Multiple static ${k.toUpperCase()} bonuses on equipped+attuned items; using highest (${Math.max(prev,n)}).`)}out.ability_statics[k]=Math.max(prev,n)}}}if(b.speed){pushApply(readNumericBonus(b.speed.walk,ctx),"speed.walk",item.name,out.informational,v=>{out.speed_bonuses.walk+=v;out.speed_terms.push({mode:"walk",kind:"bonus",source:label,amount:v})});if(b.speed.fly==="walk"){out.speed_bonuses.fly="walk";itemSpeed("fly","walk",0)}else{pushApply(readNumericBonus(b.speed.fly,ctx),"speed.fly",item.name,out.informational,v=>{const cur=out.speed_bonuses.fly;out.speed_bonuses.fly=(typeof cur==="number"?cur:0)+v;itemSpeed("fly","grant",v)})}pushApply(readNumericBonus(b.speed.swim,ctx),"speed.swim",item.name,out.informational,v=>{out.speed_bonuses.swim+=v;itemSpeed("swim","grant",v)});pushApply(readNumericBonus(b.speed.climb,ctx),"speed.climb",item.name,out.informational,v=>{out.speed_bonuses.climb+=v;itemSpeed("climb","grant",v)})}}return out}function assignSlots(resolved,registry,warnings){var _a;const slots={};const eq=(_a=resolved.definition.equipment)!=null?_a:[];for(let i=0;i<eq.length;i++){const entry=eq[i];if(!entry.equipped||!entry.slot)continue;const{entity,entityType}=resolveEntryEntity(entry,i,registry,resolved.infusions);if(slots[entry.slot])continue;const placed={index:i,entity,entityType,entry};slots[entry.slot]=placed}for(let i=0;i<eq.length;i++){const entry=eq[i];if(!entry.equipped||entry.slot)continue;const{entity,entityType}=resolveEntryEntity(entry,i,registry,resolved.infusions);if(!entity||!entityType)continue;const defaultSlot=defaultSlotForType(entityType,entity,registry);if(!defaultSlot){if(isItemEntity(entity)&&typeof entity.base_item==="string"&&entity.base_item.length>0){warnings.push(`Magic item "${entity.name}" base_item ${entity.base_item} did not resolve to a base weapon or armor; not slotted (AC/attack not applied).`)}continue}const placed={index:i,entity,entityType,entry};if(defaultSlot==="mainhand"){if(!slots.mainhand)slots.mainhand=placed;else if(!slots.offhand)slots.offhand=placed}else if(!slots[defaultSlot]){slots[defaultSlot]=placed}}return slots}function pickShield(equippedSlots,equipment,registry,infusions){const slotted=equippedSlots.shield;const slottedArmor=effectiveArmor(slotted==null?void 0:slotted.entity,registry);if(slotted&&slottedArmor&&isShieldArmor(slottedArmor)){return{index:slotted.index,shield:slottedArmor,entity:slotted.entity,entry:slotted.entry}}for(let i=0;i<equipment.length;i++){const entry=equipment[i];if(!entry.equipped)continue;const{entity}=resolveEntryEntity(entry,i,registry,infusions);const armor=effectiveArmor(entity,registry);if(armor&&isShieldArmor(armor))return{index:i,shield:armor,entity,entry}}return null}function twoHandedShieldWarnings(equipment,registry,warnings,infusions){const equipped=equipment.flatMap((entry,i)=>{if(!entry.equipped)return[];const{entity}=resolveEntryEntity(entry,i,registry,infusions);return[{entry,entity}]});const isShield=e=>{const armor=effectiveArmor(e.entity,registry);return!!armor&&isShieldArmor(armor)};for(const e of equipped){if(!e.entity||!isTwoHandedWeapon(e.entity,registry))continue;if(!equipped.some(other=>other!==e&&isShield(other)))continue;warnings.push(`${e.entity.name} is two-handed and a Shield is also equipped.`)}}function computeAC(equippedSlots,resolved,mods,registry,warnings){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const breakdown=[];const armorSlot=equippedSlots.armor;const armorEntity=(_a=armorSlot==null?void 0:armorSlot.entity)!=null?_a:null;const armor=effectiveArmor(armorEntity,registry);if(isItemEntity(armorEntity)&&typeof armorEntity.base_item==="string"&&!armor){warnings.push(`Magic armor "${armorEntity.name}" base_item ${armorEntity.base_item} did not resolve to a base armor; AC not applied.`)}const acCtx=buildConditionContext(resolved,equippedSlots,registry);const skip=new Set;const slotBonus=slot=>{var _a2,_b2;const view=slot?(_a2=resolved.infusions)==null?void 0:_a2.views.get(slot.index):void 0;if(!slot||!(view==null?void 0:view.entity)||!isItemEntity(view.entity)||!itemBenefitsActive(slot.entry,view.entity,registry,view))return 0;const out=readNumericBonus((_b2=view.entity.bonuses)==null?void 0:_b2.ac,acCtx);if((out==null?void 0:out.kind)!=="applied")return 0;skip.add(slot.index);return out.value};const armorTerms=slotAcTerms(armor,armorSlot==null?void 0:armorSlot.entry);let ac=10;if(armor&&armorTerms.armor!==null){const armorBase=armorTerms.armor+slotBonus(armorSlot);ac=armorBase;breakdown.push({source:(_b=armorEntity==null?void 0:armorEntity.name)!=null?_b:armor.name,amount:armorBase,kind:"armor"});if(armor.ac.add_dex){const dexCap=(_c=armor.ac.dex_max)!=null?_c:Number.POSITIVE_INFINITY;const dexAdd=Math.min(mods.dex,dexCap);ac+=dexAdd;const capped=mods.dex>dexCap;breakdown.push({source:`DEX modifier${capped?" (capped)":""}`,amount:dexAdd,kind:"dex"})}}else{ac=10+mods.dex;breakdown.push({source:"Base",amount:10,kind:"unarmored"});breakdown.push({source:"DEX modifier",amount:mods.dex,kind:"dex"})}const acBonus=armorTerms.override;if(acBonus!==0){ac+=acBonus;breakdown.push({source:`${(_d=armorEntity==null?void 0:armorEntity.name)!=null?_d:"Armor"} (override)`,amount:acBonus,kind:"override"})}const picked=pickShield(equippedSlots,(_e=resolved.definition.equipment)!=null?_e:[],registry,resolved.infusions);if(picked){const{shield,entity:shieldEntity}=picked;const shieldTerms=slotAcTerms(shield,picked.entry);const n=shieldTerms.armor+slotBonus(picked);ac+=n;breakdown.push({source:(_f=shieldEntity==null?void 0:shieldEntity.name)!=null?_f:shield.name,amount:n,kind:"shield"});const shieldAcBonus=shieldTerms.override;if(shieldAcBonus!==0){ac+=shieldAcBonus;breakdown.push({source:`${(_g=shieldEntity==null?void 0:shieldEntity.name)!=null?_g:shield.name} (override)`,amount:shieldAcBonus,kind:"shield"})}}const acInformational=[];const acEquipment=(_h=resolved.definition.equipment)!=null?_h:[];for(let index=0;index<acEquipment.length;index++){if(skip.has(index))continue;const entry=acEquipment[index];const{entity,entityType}=resolveEntryEntity(entry,index,registry,resolved.infusions);if(!entity||entityType!=="item")continue;if(!itemBenefitsActive(entry,entity,registry,(_i=resolved.infusions)==null?void 0:_i.views.get(index)))continue;const item=entity;const out=readNumericBonus((_j=item.bonuses)==null?void 0:_j.ac,acCtx);if(!out)continue;if(out.kind==="applied"){ac+=out.value;breakdown.push({source:item.name,amount:out.value,kind:"item"})}else if(out.kind==="informational"){acInformational.push({field:"ac",source:item.name,value:out.value,conditions:out.conditions})}}return{ac,breakdown,informational:acInformational}}function hasProperty(weapon,prop){return weapon.properties.some(p=>p===prop)}function attackAbility(weapon,mods,weaponAbilities){const modes=classifyWeaponRange(weapon);const finesse=hasProperty(weapon,"finesse");if(modes.melee){const scoped=weaponAbilities.find(o2=>{var _a;return(_a=o2.weaponSlugs)==null?void 0:_a.includes(bareEntitySlug(weapon.slug))});const glob=weaponAbilities.find(o2=>!o2.weaponSlugs);const o=scoped!=null?scoped:glob;if(o)return o.ability;if(finesse)return mods.dex>=mods.str?"dex":"str";return"str"}return finesse&&mods.str>mods.dex?"str":"dex"}function pactScopedAbilities(overrides,pactPicked,isPact){if(!overrides.some(o=>o.pactWeapon))return overrides;return overrides.flatMap(o=>{if(!o.pactWeapon)return[o];return!pactPicked||isPact?[{ability:o.ability}]:[]})}function pactWeaponIndexes(resolved,registry){var _a;const pick=resolved.pactWeapon;if(!pick)return null;const out=new Set;const bare=bareEntitySlug(pick);((_a=resolved.definition.equipment)!=null?_a:[]).forEach((entry,i)=>{var _a2;if(typeof entry.item!=="string")return;const slugs=[unwrapSlug(entry.item),registry?(_a2=resolveBaseItem(entry.item,registry))==null?void 0:_a2.slug:void 0];if(slugs.some(s=>!!s&&(s===pick||bareEntitySlug(s)===bare)))out.add(i)});return out.size?out:null}function isWeaponSlugProficient(weapon,weaponSlug,profs){const wp=profs.weapons;if(wp.specific.some(e=>e===weaponSlug||normKey(e)===normKey(weapon.name)))return true;if(wp.specific.some(e=>qualifiedGrantCovers(e,weapon)))return true;const cat=weapon.category;if(typeof cat==="string"){if(/^simple\b/.test(cat)&&wp.categories.includes("simple"))return true;if(/^martial\b/.test(cat)&&wp.categories.includes("martial"))return true;if(wp.categories.includes(cat))return true}return false}function magicBonusesForWeaponEntry(entry,registry,ctx,index,infusions){var _a,_b,_c,_d;const{entity}=resolveEntryEntity(entry,index,registry,infusions);const ovr=(_a=entry.overrides)!=null?_a:{};const entryAttack=typeof ovr.bonus==="number"?ovr.bonus:0;const entryDamage=typeof ovr.damage_bonus==="number"?ovr.damage_bonus:0;const extra=typeof ovr.extra_damage==="string"?ovr.extra_damage:void 0;let itemAttack=0;let itemDamage=0;let sourceName;let itemName;let damageTypeOverride;let propertiesOverride;const informational=[];let itemRiders=[];let critRange;const conditionalCrits=[];if(entity&&isItemEntity(entity)){sourceName=entity.name;itemName=entity.name;damageTypeOverride=typeof entity.damage_type==="string"&&entity.damage_type.length>0?entity.damage_type:void 0;propertiesOverride=Array.isArray(entity.properties)&&entity.properties.length>0?entity.properties:void 0}if(entity&&isItemEntity(entity)&&itemBenefitsActive(entry,entity,registry,infusions==null?void 0:infusions.views.get(index))){const b=entity.bonuses;const atkOut=readNumericBonus(b==null?void 0:b.weapon_attack,ctx);const dmgOut=readNumericBonus(b==null?void 0:b.weapon_damage,ctx);if((atkOut==null?void 0:atkOut.kind)==="applied")itemAttack=atkOut.value;else if((atkOut==null?void 0:atkOut.kind)==="informational")informational.push({field:"weapon_attack",source:entity.name,value:atkOut.value,conditions:atkOut.conditions});if((dmgOut==null?void 0:dmgOut.kind)==="applied")itemDamage=dmgOut.value;else if((dmgOut==null?void 0:dmgOut.kind)==="informational")informational.push({field:"weapon_damage",source:entity.name,value:dmgOut.value,conditions:dmgOut.conditions});itemRiders=Array.isArray(entity.damage_riders)?entity.damage_riders.filter(r=>{var _a2;return((_a2=r.applies_to)!=null?_a2:"weapon")!=="spell"}).map(r=>({amount:r.amount,damage_type:r.damage_type,source:entity.name,...r.condition?{condition:r.condition}:{}})):[];for(const eff of itemRowEffects(entity)){if(eff.kind==="damage-bonus"&&((_b=eff.applies_to)!=null?_b:"weapon")!=="spell"){itemRiders.push({amount:eff.amount,damage_type:eff.damage_type,source:entity.name,...eff.condition?{condition:eff.condition}:{}})}else if(eff.kind==="crit-range"&&((_c=eff.applies_to)!=null?_c:"weapon")!=="spell"){if((_d=eff.condition)==null?void 0:_d.trim())conditionalCrits.push({minRoll:eff.min_roll,condition:eff.condition.trim(),source:entity.name});else critRange=Math.min(critRange!=null?critRange:20,eff.min_roll)}}}return{...critRange!==void 0&&critRange<20?{critRange}:{},...conditionalCrits.length?{conditionalCrits}:{},atk:itemAttack+entryAttack,dmg:itemDamage+entryDamage,extra,sourceName,itemName,damageTypeOverride,propertiesOverride,informational,riders:itemRiders}}function buildAttackRow(args){var _a,_b,_c,_d;const{id,name,weapon,baseDice,ability,mods,proficient,proficiencyBonus,magic,weaponMasteries}=args;const abilityMod=mods[ability];const pb=proficient?proficiencyBonus:0;const toHit=abilityMod+pb+magic.atk;const dmgFlat=abilityMod+magic.dmg;const formatDice=dice=>`${dice}${dmgFlat>=0?"+":""}${dmgFlat}`.replace(/\+0$/,"");const damageDice=formatDice(baseDice);const magicSource=magic.sourceName?`${magic.sourceName} bonus`:"Magic weapon";const toHitBreakdown=[{source:`${ability.toUpperCase()} modifier`,amount:abilityMod,kind:"ability"},{source:"Proficiency bonus",amount:proficient?proficiencyBonus:0,kind:"ability"},{source:magicSource,amount:magic.atk,kind:"item"}];const damageBreakdown=[{source:"Base damage",amount:0,kind:"ability"},{source:`${ability.toUpperCase()} modifier`,amount:abilityMod,kind:"ability"},{source:magicSource,amount:magic.dmg,kind:"item"}];const modes=classifyWeaponRange(weapon);const fmtRanged=r=>r.long>r.normal?`${r.normal}/${r.long} ft.`:`${r.normal} ft.`;const range=modes.melee?`${modes.melee.reach} ft.`:modes.ranged?fmtRanged(modes.ranged):void 0;const thrownRange=modes.melee&&modes.ranged?fmtRanged(modes.ranged):void 0;const stringProps=weapon.properties.filter(p=>typeof p==="string");const finalProps=(_a=magic.propertiesOverride)!=null?_a:stringProps;const row={id,name,...range!==void 0?{range}:{},...thrownRange!==void 0?{thrownRange}:{},toHit,damageDice,damageType:(_b=magic.damageTypeOverride)!=null?_b:weapon.damage.type,...(()=>{const riders=[...magic.riders,...magic.extra?[{amount:magic.extra}]:[]];return riders.length?{damageRiders:riders}:{}})(),weaponCategory:modes.melee?"melee":"ranged",properties:finalProps,proficient,breakdown:{toHit:toHitBreakdown,damage:damageBreakdown},informational:args.magic.informational.length>0?args.magic.informational:void 0,slotKey:args.slotKey,subLabel:formatWeaponSubLabel(weapon,finalProps,modes),actionCost:args.actionCost,versatile:args.versatileDice?{damageDice:formatDice(args.versatileDice)}:void 0,...magic.critRange!==void 0?{critRange:magic.critRange}:{},...((_c=magic.conditionalCrits)==null?void 0:_c.length)?{conditionalCrits:magic.conditionalCrits}:{}};const mSlug=(_d=weapon.mastery)==null?void 0:_d[0];if(mSlug&&proficient&&weaponMasteries.includes(bareEntitySlug(weapon.slug))){const g=MASTERY[mSlug];if(g){const derived=masteryDerived(mSlug,mods[ability],proficiencyBonus);row.mastery={slug:mSlug,label:g.label,description:g.description,gist:masteryGist(mSlug),...derived?{derived}:{}}}}return row}function buildUnarmedRow(mods,proficiencyBonus,spec){var _a;const strike=unarmedStrikeNumbers(mods,proficiencyBonus,["str",...(_a=spec==null?void 0:spec.abilities)!=null?_a:[]],spec==null?void 0:spec.dice);return{id:"unarmed-strike",name:"Unarmed Strike",unarmed:true,range:"5 ft.",...strike,damageType:"bludgeoning",properties:[],proficient:true,subLabel:"Unarmed",actionCost:"action"}}function unarmedStrikeNumbers(mods,proficiencyBonus,candidates,dice){var _a;let ability=(_a=candidates[0])!=null?_a:"str";for(const ab of candidates)if(mods[ab]>=mods[ability])ability=ab;const abilityMod=mods[ability];const flat=`${abilityMod>=0?"+":""}${abilityMod}`.replace(/^\+0$/,"");const label=`${ability.toUpperCase()} modifier`;return{toHit:abilityMod+proficiencyBonus,damageDice:dice?`${dice}${flat}`:String(Math.max(0,1+abilityMod)),breakdown:{toHit:[{source:label,amount:abilityMod,kind:"ability"},{source:"Proficiency bonus",amount:proficiencyBonus,kind:"ability"}],damage:[{source:"Base damage",amount:dice?0:1,kind:"ability"},{source:label,amount:abilityMod,kind:"ability"}]}}}function buildFeatureAttackRows(resolved,mods,profs,proficiencyBonus,weaponAbilities=[],opts={}){var _a,_b,_c,_d;const rows=[];const abilities=weaponAbilities.filter(o=>!o.pactWeapon);const active=new Set((_a=opts.activeBuffs)!=null?_a:[]);for(const rf of(_b=resolved.features)!=null?_b:[]){if(rf.renderSuppressed||rf.buildOnly||!foldsNow(rf,active))continue;const featureId=(_c=rf.feature.id)!=null?_c:rf.feature.name;((_d=rf.feature.attacks)!=null?_d:[]).forEach((a,n)=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h;const id=`feature-attack:${rf.source.kind}:${rf.source.slug}:${featureId}:${n}`;if(!a.weapon_category&&a.unarmed===true){const natural=buildNaturalWeaponRow(a,id,mods,proficiencyBonus,(_a2=opts.unarmedAbilities)!=null?_a2:[]);if(natural)rows.push({...natural,grantedBy:rf.feature.name});return}if(!a.weapon_category||a.type!=="melee"&&a.type!=="ranged"||typeof a.damage!=="string"||!a.damage.trim())return;const long=(_d2=(_b2=a.range)==null?void 0:_b2.long)!=null?_d2:(_c2=a.range)==null?void 0:_c2.normal;const weapon={name:a.name,slug:`feature-attack_${featureId}_${n}`,category:`${a.weapon_category}-${a.type}`,damage:{dice:a.damage.trim(),type:(_e=a.damage_type)!=null?_e:""},properties:((_f=a.properties)!=null?_f:[]).map(p=>p.trim().toLowerCase()),...((_g=a.range)==null?void 0:_g.normal)!==void 0&&long!==void 0?{range:{normal:a.range.normal,long}}:{},...a.mastery?{mastery:[a.mastery.trim().toLowerCase()]}:{}};const proficient=isWeaponSlugProficient(weapon,weapon.slug,profs);const row=buildAttackRow({id,name:a.name,weapon,baseDice:weapon.damage.dice,ability:attackAbility(weapon,mods,abilities),mods,proficient,proficiencyBonus,magic:{atk:0,dmg:0,informational:[],riders:[]},actionCost:(_h=a.action)!=null?_h:WEAPON_DEFAULT_ACTION_COST,weaponMasteries:a.mastery?[bareEntitySlug(weapon.slug)]:[]});row.grantedBy=rf.feature.name;rows.push(row)})}return rows}function buildNaturalWeaponRow(a,id,mods,proficiencyBonus,unarmedAbilities){var _a,_b,_c,_d;const dice=typeof a.damage==="string"?a.damage.trim():"";if(a.type!=="melee"||!dice)return null;const own=a.ability===void 0?["str"]:Array.isArray(a.ability)?[...a.ability]:[a.ability];return{id,name:a.name,naturalWeapon:true,range:`${(_b=(_a=a.range)==null?void 0:_a.reach)!=null?_b:5} ft.`,...unarmedStrikeNumbers(mods,proficiencyBonus,[...own,...unarmedAbilities],dice),damageType:((_c=a.damage_type)==null?void 0:_c.trim())||"bludgeoning",properties:[],proficient:true,subLabel:"Unarmed",actionCost:(_d=a.action)!=null?_d:"action"}}function humanizeWeaponToken(s){return s.replace(/[-_]/g," ").replace(/(^|[\s(])\w/g,c=>c.toUpperCase())}function formatWeaponSubLabel(weapon,properties,modes){const parts=[];if(weapon.category){const cat=modes.melee&&/ranged/.test(weapon.category)?weapon.category.replace("ranged","melee"):weapon.category;parts.push(humanizeWeaponToken(cat))}if(properties.length>0)parts.push(properties.map(humanizeWeaponToken).join(", "));return parts.join(" \xB7 ")}function computeAttacks(equippedSlots,equipment,mods,profs,registry,warnings,proficiencyBonus,ctx,weaponMasteries,weaponAbilities=[],infusions,pactIndexes=null){var _a,_b;const rows=[];const rowFor=(index,entry,weapon,slotKey,versatileDice)=>{var _a2,_b2,_c,_d,_e;const slugFromEntry=(_a2=unwrapSlug(entry.item))!=null?_a2:weapon.slug;const proficient=isWeaponSlugProficient(weapon,slugFromEntry,profs)||isWeaponSlugProficient(weapon,weapon.slug,profs);if(!proficient){warnings.push(`Character not proficient with ${weapon.name}; proficiency bonus excluded.`)}const isPact=(pactIndexes==null?void 0:pactIndexes.has(index))===true;const ability=attackAbility(weapon,mods,pactScopedAbilities(weaponAbilities,pactIndexes!==null,isPact));const magic=magicBonusesForWeaponEntry(entry,registry,ctx,index,infusions);const ovr=(_b2=entry.overrides)!=null?_b2:{};const row=buildAttackRow({id:`${index}:standard`,name:(_d=(_c=ovr.name)!=null?_c:magic.itemName)!=null?_d:weapon.name,weapon,baseDice:weapon.damage.dice,ability,mods,proficient,proficiencyBonus,magic,slotKey,actionCost:(_e=ovr.action)!=null?_e:WEAPON_DEFAULT_ACTION_COST,versatileDice,weaponMasteries});if(isPact)row.pactWeapon=true;return row};const handedSlots=[{key:"mainhand",placed:equippedSlots.mainhand},{key:"offhand",placed:equippedSlots.offhand}];for(const{key,placed}of handedSlots){if(!placed)continue;const{entity,entry}=placed;if(!entity)continue;const weapon=effectiveWeapon(entity,registry);if(!weapon){if(isItemEntity(entity)&&typeof entity.base_item==="string"&&!resolveBaseItem(entity.base_item,registry)){warnings.push(`Magic weapon ${entity.name} references missing base_item ${entity.base_item}.`)}continue}const versatileDice=key==="mainhand"&&hasProperty(weapon,"versatile")&&typeof weapon.damage.versatile_dice==="string"&&!equippedSlots.offhand?weapon.damage.versatile_dice:void 0;rows.push(rowFor(placed.index,entry,weapon,key,versatileDice))}const handIndex=new Set([(_a=equippedSlots.mainhand)==null?void 0:_a.index,(_b=equippedSlots.offhand)==null?void 0:_b.index]);equipment.forEach((entry,index)=>{if(!entry.equipped||handIndex.has(index))return;const{entity}=resolveEntryEntity(entry,index,registry,infusions);const weapon=effectiveWeapon(entity,registry);if(!weapon)return;rows.push(rowFor(index,entry,weapon))});return rows}function coerceWeight(raw){if(typeof raw==="number"&&Number.isFinite(raw)&&raw>=0)return raw;if(typeof raw==="string"){const n=Number.parseFloat(raw);if(Number.isFinite(n)&&n>=0)return n}return 0}function computeCarriedWeight(resolved,registry){var _a;const equipment=(_a=resolved.definition.equipment)!=null?_a:[];const view=resolveContainment(equipment,registry);const weightlessContainer=equipment.map(entry=>{var _a2,_b,_c;const data=(_a2=resolveBaseItem(entry.item,registry))==null?void 0:_a2.data;return((_c=(_b=data==null?void 0:data.container)==null?void 0:_b.capacity)==null?void 0:_c.weightless)===true});const exempt=i=>{for(let p=view.parentOf[i];p!==null;p=view.parentOf[p])if(weightlessContainer[p])return true;return false};let total=0;equipment.forEach((entry,i)=>{if(exempt(i))return;const found=resolveBaseItem(entry.item,registry);if(!found)return;const entity=found.data;const w=coerceWeight(entity.weight);if(w===0)return;const qty=typeof entry.qty==="number"&&entry.qty>=0?entry.qty:1;total+=w*qty});return total}function computeSlotsAndAttacks(resolved,mods,profs,registry,warnings,proficiencyBonus,weaponAbilities=[],weaponMasteries=[],attunementFloor=0){var _a,_b,_c,_d,_e;const equippedSlots=assignSlots(resolved,registry,warnings);twoHandedShieldWarnings((_a=resolved.definition.equipment)!=null?_a:[],registry,warnings,resolved.infusions);const overrides=(_b=resolved.definition.overrides)!=null?_b:{};const acOut=computeAC(equippedSlots,resolved,mods,registry,warnings);const ctx=buildConditionContext(resolved,equippedSlots,registry);const attacks=computeAttacks(equippedSlots,(_c=resolved.definition.equipment)!=null?_c:[],mods,profs,registry,warnings,proficiencyBonus,ctx,weaponMasteries,weaponAbilities,resolved.infusions,pactWeaponIndexes(resolved,registry));return{ac:acOut.ac,acBreakdown:acOut.breakdown,acInformational:acOut.informational,attacks,equippedSlots,carriedWeight:computeCarriedWeight(resolved,registry),attunementUsed:((_d=resolved.definition.equipment)!=null?_d:[]).filter(e=>e.attuned).length,attunementLimit:(_e=overrides.attunement_limit)!=null?_e:Math.max(3,attunementFloor)}}export{emptyAppliedBonuses,computeAppliedBonuses,pactWeaponIndexes,isWeaponSlugProficient,buildUnarmedRow,buildFeatureAttackRows,computeSlotsAndAttacks};