@champions-digital-game/mod-sdk 0.50.0 → 0.52.0

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 (44) hide show
  1. package/README.md +3 -3
  2. package/dist/build.js +1 -1
  3. package/dist/chunks/chunk-3ZP7JFBM.js +7 -0
  4. package/dist/chunks/chunk-DH3FUEOQ.js +22 -0
  5. package/dist/chunks/{chunk-JYDEFRIZ.js → chunk-GIPUMXZ5.js} +11 -11
  6. package/dist/chunks/{chunk-A3WBGQ2N.js → chunk-KWTX5B5J.js} +1 -1
  7. package/dist/chunks/{chunk-URLIN52M.js → chunk-RRZU6F4D.js} +1 -1
  8. package/dist/chunks/chunk-STQU5RJP.js +1 -0
  9. package/dist/chunks/{chunk-DKCXOHRM.js → chunk-XDNO5DKC.js} +1 -1
  10. package/dist/import.js +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/mc-pack.js +2 -2
  13. package/dist/testing.js +1 -1
  14. package/package.json +1 -1
  15. package/types/cards/src/dsl/abilities.d.ts +91 -1
  16. package/types/cards/src/dsl/effects.d.ts +33 -0
  17. package/types/cards/src/dsl/engine-only-features.d.ts +0 -10
  18. package/types/cards/src/dsl/values.d.ts +15 -2
  19. package/types/cards/src/playable/custom.d.ts +3 -2
  20. package/types/cards/src/wave2/ant/obligation-nemesis.d.ts +0 -1
  21. package/types/cards/src/wave5/sm/campaign/shield-tech.d.ts +2 -0
  22. package/types/content/src/index.d.ts +1 -1
  23. package/types/content/src/schema/cards/player-cards.d.ts +7 -0
  24. package/types/content/src/schema/packs.d.ts +5 -0
  25. package/types/engine/src/abilities.d.ts +40 -1
  26. package/types/engine/src/actions.d.ts +3 -1
  27. package/types/engine/src/campaign.d.ts +46 -0
  28. package/types/engine/src/choices.d.ts +2 -0
  29. package/types/engine/src/cost-damage.d.ts +2 -2
  30. package/types/engine/src/effects.d.ts +39 -2
  31. package/types/engine/src/events.d.ts +1 -1
  32. package/types/engine/src/index.d.ts +3 -3
  33. package/types/engine/src/keywords.d.ts +3 -3
  34. package/types/engine/src/legal.d.ts +22 -1
  35. package/types/engine/src/query.d.ts +7 -0
  36. package/types/engine/src/resolve/hand-discard.d.ts +20 -0
  37. package/types/engine/src/select.d.ts +4 -0
  38. package/types/engine/src/spec.d.ts +62 -1
  39. package/types/engine/src/stack.d.ts +5 -0
  40. package/types/engine/src/state.d.ts +30 -0
  41. package/types/engine/src/trigger-events.d.ts +53 -2
  42. package/dist/chunks/chunk-2XS47E3T.js +0 -7
  43. package/dist/chunks/chunk-HVUCR22H.js +0 -1
  44. package/dist/chunks/chunk-PB6KXNXP.js +0 -22
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @champions-digital-game/mod-sdk
2
2
 
3
3
  The mod SDK for [Marvel Champions Digital](https://github.com/quincarter/marvel-champions-digital-game) content
4
- packs, version 0.50.0: the pack schema, the ability DSL the game's own cards are written in, and the `mc-pack`
4
+ packs, version 0.52.0: the pack schema, the ability DSL the game's own cards are written in, and the `mc-pack`
5
5
  tool that validates, builds, tests and imports packs. It carries the game's rules engine, so `mc-pack test` plays
6
6
  real headless games.
7
7
 
@@ -11,10 +11,10 @@ of Fantasy Flight Games and Marvel.
11
11
  ## Install
12
12
 
13
13
  ```sh
14
- npm install --save-dev @champions-digital-game/mod-sdk@0.50.0
14
+ npm install --save-dev @champions-digital-game/mod-sdk@0.52.0
15
15
  ```
16
16
 
17
- The SDK is versioned with the game: a pack built with SDK 0.50.0 runs on app 0.50.0 and later. Every game
17
+ The SDK is versioned with the game: a pack built with SDK 0.52.0 runs on app 0.52.0 and later. Every game
18
18
  release also carries this package as a tarball, which installs the same way (`npm install --save-dev ./<file>.tgz`).
19
19
 
20
20
  ## A pack's source folder
package/dist/build.js CHANGED
@@ -1 +1 @@
1
- import{PackBuildError,assemblePack,buildPack,loadPackSource,zipPack}from"./chunks/chunk-URLIN52M.js";import"./chunks/chunk-2XS47E3T.js";import"./chunks/chunk-JYDEFRIZ.js";export{PackBuildError,assemblePack,buildPack,loadPackSource,zipPack};
1
+ import{PackBuildError,assemblePack,buildPack,loadPackSource,zipPack}from"./chunks/chunk-RRZU6F4D.js";import"./chunks/chunk-3ZP7JFBM.js";import"./chunks/chunk-GIPUMXZ5.js";export{PackBuildError,assemblePack,buildPack,loadPackSource,zipPack};
@@ -0,0 +1,7 @@
1
+ import{CAMPAIGNS,ENGINE_ONLY_DSL_EXAMPLES,PACK_COVER_MAX_BYTES,PACK_HOUSE_RULE_MODES,PACK_KINDS,PACK_PERMISSION_STATUSES,PLAYABLE_CARDS,PLAYABLE_DEPS,campaignDefinitionProblems,campaignInstructionsOf,customCardPrefix,customScenarioProblems,houseRuleMayRebuild,isBaseEncounterSetId,isBaseScenarioId,isLanguageTag,isPackCoverPath,isPackId,isSafePackPath,officialCardsByPictureCode,officialFaceOfCode,opsOfKind,packAchievementProblems,packCatalogFieldProblems,packStagedPictureCodes,parsePackCardImagePath,validateCard,validateDefinition,validateEncounterSet,validateScenario,validateStarterDeck,webpSize}from"./chunk-GIPUMXZ5.js";function dslFeatures(registry,campaigns=[]){let found=new Set;for(let definition of Object.values(registry??{}))isRecord(definition)&&collectDefinition(definition,found);for(let definition of campaigns)isRecord(definition)&&collectCampaign(definition,found);return[...found].sort()}function campaignDefinitionsOf(campaigns){return(campaigns??[]).flatMap(entry=>isRecord(entry)&&isRecord(entry.definition)?[entry.definition]:[])}function collectCampaignExprs(value,found){if(Array.isArray(value)){for(let item of value)collectCampaignExprs(item,found);return}if(isRecord(value)){typeof value.kind=="string"&&(found.add(`campaign:${value.kind}`),recordFields(`campaign:${value.kind}`,value,found));for(let child of Object.values(value))collectCampaignExprs(child,found)}}function collectCampaign(definition,found){let graph=definition.graph;isRecord(graph)&&typeof graph.kind=="string"&&found.add(`campaign-graph:${graph.kind}`);for(let field of Array.isArray(definition.logFields)?definition.logFields:[])isRecord(field)&&isRecord(field.type)&&typeof field.type.kind=="string"&&found.add(`campaign-field:${field.type.kind}`);let instructions=[];try{instructions=campaignInstructionsOf(definition)}catch{}for(let instruction of instructions){if(!isRecord(instruction))continue;collectCampaignExprs([instruction.when,instruction.whenModes],found);let step=instruction.step;isRecord(step)&&(step.kind==="inGame"?(typeof step.window=="string"&&found.add(`campaign-window:${step.window}`),visit(step.effects,"effect",found)):collectCampaignExprs(step,found))}let nodes=isRecord(graph)&&Array.isArray(graph.nodes)?graph.nodes:[];for(let node of nodes)isRecord(node)&&node.scenarioRuleSpecs!==void 0&&visit(node.scenarioRuleSpecs,"rule",found);collectCampaignExprs([definition.elimination,definition.loss],found)}var isRecord=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),isStringArray=value=>Array.isArray(value)&&value.length>0&&value.every(item=>typeof item=="string"),EFFECT_SLOTS={if:["then","otherwise"],replaceTriggeringEvent:["with"],enemyScheme:["wouldPlaceThreat"]};function slotFor(kind,slot,key){return key==="effects"?"effect":key==="rules"?"rule":slot==="effect"&&kind!==void 0&&EFFECT_SLOTS[kind]?.includes(key)?"effect":"expr"}function collectDefinition(definition,found){for(let[key,value]of Object.entries(definition))value!==void 0&&(key==="trigger"?collectTrigger(value,found):key==="cost"?collectCost(value,found):key==="effects"?visit(value,"effect",found):(found.add(`ability:${key}`),recordFields(`ability:${key}`,value,found),visit(value,slotFor(void 0,"expr",key),found)))}function recordFields(prefix,value,found,skip="kind"){if(isRecord(value))for(let[field,child]of Object.entries(value))field!==skip&&child!==void 0&&found.add(`${prefix}.${field}`)}function collectTrigger(trigger,found){if(isRecord(trigger)){typeof trigger.kind=="string"&&found.add(`trigger:${trigger.kind}`);for(let[key,value]of Object.entries(trigger))if(!(key==="kind"||value===void 0)){if(key==="on"){visit(value,"expr",found,!0);continue}found.add(`trigger-option:${key}`),recordFields(`trigger-option:${key}`,value,found),visit(value,slotFor(void 0,"expr",key),found)}}}function collectCost(cost,found){if(isRecord(cost)){for(let[key,value]of Object.entries(cost))if(value!==void 0)if(found.add(`cost:${key}`),key==="either"&&Array.isArray(value))for(let branch of value)collectCost(branch,found);else if(key==="conditional"&&isRecord(value)){collectCost(value.then,found),collectCost(value.else,found);let{then:_then,else:_else,...rest}=value;recordFields("cost:conditional",rest,found),visit(rest,"expr",found)}else recordFields(`cost:${key}`,value,found),visit(value,"expr",found)}}var TARGET_QUERY_FIELDS=["categories","inScenarioPlayArea","controller","engagedWith","trait","withoutTrait","anyTrait","withKeyword","withoutKeyword","keywordNotFromSelf","anyOf","not","cardTypeIs","playerSideScheme","accusation","chosenVillain","name","printedId","hostOfSelf","host","hasAttachment","canHaveAttached","canAttachTo","canAttachToCategory","canEnterPlay","canEnterPlayControllerStated","canFlip","facedown","flipped","starIcon","boostCard","printsBoostAbility","unique","printedResource","anyPrintedResource","printedResourceNamed","owner","aspect","anyAspect","exhausted","hasThreat","hasCounter","hasAccelerationToken","damaged","hasStatus","hasAnyStatus","canTakeStatus","self","maxPrintedHp","statCompare","remainingHpCompare","maxPrintedCost","minPrintedCost","attackableBy","canTakeAttackInProgress","canAttackOneOf","excludeSlots","excluding","inSlot","controlledBy","extensionOf","actsFor","engagedWithPlayer","inPlayAreaOf","signatureSideScheme","identitySetOf","nemesisMinionOf","obligationOf","nemesisSideSchemeOf","nemesisSetOf","sharesTraitWith","sharesTraitWithHeroOf","sharesTitleWith","otherFaceOf","encounterSetOf","scenarioSpecific","inEncounterSet","inCampaignLogField","titled","identitySetTitled","sameClassificationAs","classification","printedForm","abilityTiming","printsAbility","hasTaggedAbility"],SHARED_QUERY_FIELDS=new Set(["name","trait","aspect","self","owner","host","unique","exhausted","facedown","flipped","damaged","controller","not","anyOf","inSlot","excluding","titled","anyTrait","classification","printedForm"]),QUERY_FIELD_SET=new Set(TARGET_QUERY_FIELDS);function recordQueryFields(value,found){if(typeof value.kind=="string")return;let own=Object.keys(value).filter(key=>value[key]!==void 0&&QUERY_FIELD_SET.has(key));if(own.some(key=>!SHARED_QUERY_FIELDS.has(key)))for(let key of own)found.add(`query:${key}`)}function visit(value,slot,found,isPattern=!1){if(Array.isArray(value)){for(let item of value)visit(item,slot,found,isPattern);return}if(!isRecord(value))return;let kind=typeof value.kind=="string"?value.kind:void 0;recordQueryFields(value,found),kind!==void 0&&(found.add(`${slot}:${kind}`),recordFields(`${slot}:${kind}`,value,found));let on=value.on,hearsEvents=(isPattern||kind===void 0)&&(typeof on=="string"||isStringArray(on));if(hearsEvents)for(let event of typeof on=="string"?[on]:on)found.add(`event:${event}`);for(let[childKey,child]of Object.entries(value))hearsEvents&&childKey==="on"||visit(child,slotFor(kind,slot,childKey),found,childKey==="anyOf")}var SUPPORTED_DSL_FEATURES=dslFeatures({...PLAYABLE_DEPS.abilities,...ENGINE_ONLY_DSL_EXAMPLES},Object.values(CAMPAIGNS));var PACK_ABILITY_ID=/^x\.[a-z0-9]+(?:-[a-z0-9]+)*\.\d+[a-z]?\.[a-z0-9-]+$/;function definePackAbilities(definitions){let problems=[];for(let[id,definition]of Object.entries(definitions)){PACK_ABILITY_ID.test(id)||problems.push(`${id}: not an x.<pack-id>.<card number>.<slug> ability id`);for(let problem of validateDefinition(definition))problems.push(`${id}: ${problem}`)}if(problems.length>0)throw new Error(`invalid pack ability definitions:
2
+ ${problems.join(`
3
+ `)}`);return definitions}var K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),rotr=(x,n)=>x>>>n|x<<32-n;function sha256Hex(data){let h=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),length=data.length,padded=new Uint8Array(length+9+63>>6<<6);padded.set(data),padded[length]=128;let view=new DataView(padded.buffer);view.setUint32(padded.length-8,Math.floor(length/536870912),!1),view.setUint32(padded.length-4,length<<3>>>0,!1);let w=new Uint32Array(64);for(let offset=0;offset<padded.length;offset+=64){for(let i=0;i<16;i++)w[i]=view.getUint32(offset+i*4,!1);for(let i=16;i<64;i++){let s0=rotr(w[i-15],7)^rotr(w[i-15],18)^w[i-15]>>>3,s1=rotr(w[i-2],17)^rotr(w[i-2],19)^w[i-2]>>>10;w[i]=w[i-16]+s0+w[i-7]+s1|0}let[a,b,c,d,e,f,g,hh]=[h[0],h[1],h[2],h[3],h[4],h[5],h[6],h[7]];for(let i=0;i<64;i++){let s1=rotr(e,6)^rotr(e,11)^rotr(e,25),ch=e&f^~e&g,t1=hh+s1+ch+K[i]+w[i]|0,s0=rotr(a,2)^rotr(a,13)^rotr(a,22),maj=a&b^a&c^b&c,t2=s0+maj|0;hh=g,g=f,f=e,e=d+t1|0,d=c,c=b,b=a,a=t1+t2|0}h[0]=h[0]+a|0,h[1]=h[1]+b|0,h[2]=h[2]+c|0,h[3]=h[3]+d|0,h[4]=h[4]+e|0,h[5]=h[5]+f|0,h[6]=h[6]+g|0,h[7]=h[7]+hh|0}return[...h].map(n=>(n>>>0).toString(16).padStart(8,"0")).join("")}var isObj=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),text=value=>typeof value=="string"&&value.trim()!=="";function isPlainJson(value){if(value===null||typeof value=="string"||typeof value=="boolean")return!0;if(typeof value=="number")return Number.isFinite(value);if(Array.isArray(value))return value.every(isPlainJson);if(isObj(value)){let proto=Object.getPrototypeOf(value);return(proto===Object.prototype||proto===null)&&Object.values(value).every(isPlainJson)}return!1}var LIMITED_OPS={spend:"spending a currency (a market or shop) is not available to a pack campaign yet",composeVillain:"choosing a villain between games is not available to a pack campaign yet",composeEncounterSets:"composing encounter sets between games is not available to a pack campaign yet",setAsideCards:"setting cards aside between games is not available to a pack campaign yet"};function checkPackCampaigns(input){let{add}=input,ids=new Set,requiredScenarioIds=new Set(input.required.scenarios.map(scenario=>scenario.id)),requiredSetIds=new Set(input.required.encounterSets.map(set=>set.id));for(let[index,entry]of input.campaigns.entries()){if(!isObj(entry)){add(`campaigns[${index}]`,"must be a campaign object");continue}let id=typeof entry.id=="string"?entry.id:"",at=`campaigns/${id||index}`;(input.packId===""||!id.startsWith(`${input.packId}-`)||id.length===input.packId.length+1)&&add(at,`campaign id must be "${input.packId}-<name>"`),Object.hasOwn(CAMPAIGNS,id)&&add(at,"campaign id is a base-game campaign id (the base game always wins)"),ids.has(id)&&add(at,"campaign id is used by two campaigns"),ids.add(id);for(let field of["name","description"])text(entry[field])||add(at,`${field} must be a non-empty string`);entry.tagline!==void 0&&!text(entry.tagline)&&add(at,"tagline must be a non-empty string"),text(entry.version)||add(at,"version must be a non-empty string");let definition=entry.definition;if(!isObj(definition)){add(at,"definition must be a campaign definition object");continue}isPlainJson(definition)||add(at,"definition must be plain JSON (no undefined, functions or NaN)"),definition.campaignId!==id&&add(at,`definition.campaignId must equal the campaign's id "${id}"`),definition.version!==entry.version&&add(at,"definition.version must equal the campaign's version");let problems=campaignDefinitionProblems(definition,{isCardId:input.isCardId,isScenarioId:scenarioId=>input.packScenarioIds.has(scenarioId)||isBaseScenarioId(scenarioId)||requiredScenarioIds.has(scenarioId)});for(let problem of problems)add(at,problem);if(!isReadable(definition))continue;let readable=definition;try{checkLimits(at,readable,add),checkRecord(at,entry,readable,input,requiredSetIds),checkStory(at,entry,readable,add)}catch(error){add(at,`could not be checked: ${error instanceof Error?error.message:String(error)}`)}if(entry.art!==void 0){let cover=isObj(entry.art)?entry.art.cover:void 0;!isObj(entry.art)||cover!==void 0&&(typeof cover!="string"||!isSafePackPath(cover))?add(at,"art must be { cover?: a pack file path }"):typeof cover=="string"&&!input.listedFiles.has(cover)&&add(at,`art.cover "${cover}" is not a listed file`)}}}function isReadable(definition){let graph=definition.graph,listOfObjects=value=>Array.isArray(value)&&value.every(isObj);return isObj(graph)&&listOfObjects(graph.nodes)&&graph.nodes.every(node=>Array.isArray(node.setup)&&Array.isArray(node.victory))&&listOfObjects(definition.logFields)}function checkLimits(at,definition,add){let graph=definition.graph;graph.kind!=="linear"&&add(at,`the graph must be "linear" (a "${String(graph.kind)}" graph is not available yet)`);for(let node of graph.nodes){let name=`node "${String(node.id)}"`;node.scenario?.kind!=="fixed"&&add(at,`${name}: the scenario must be "fixed" (a named scenario record)`),node.composition!==void 0&&node.composition.length>0&&add(at,`${name}: composition (choosing a villain or sets between games) is not available yet`),node.requiredModularSetIds!==void 0&&node.requiredModularSetIds.length>0&&add(at,`${name}: requiredModularSetIds is not available yet`)}definition.elimination!==void 0&&add(at,"an elimination policy is not available yet (it is part of an expert campaign)");let everything=[definition.everyNodeSetup,definition.everyNodeVictory,definition.conditionalInstructions,definition.logUpgrades,definition.loss,graph.nodes];for(let[kind,message]of Object.entries(LIMITED_OPS))opsOfKind(everything,kind).length>0&&add(at,message);opsOfKind(everything,"perSeatSet").length>0&&add(at,"a per-seat set (an expert campaign's numbered sets) is not available yet"),JSON.stringify(everything).includes('"unitCostExactly"')&&add(at,"a Unit Cost filter (a market) is not available yet"),JSON.stringify(everything).includes('"expertCampaign"')&&add(at,"an instruction gated by expertCampaign is not available yet (no expert campaign rules)"),definition.logFields.some(field=>field.whenModes!==void 0)&&add(at,"a log field gated by modes (whenModes) is not available yet")}function checkRecord(at,entry,definition,input,requiredSetIds){let{add}=input,record=entry.record;if(!isObj(record)){add(at,"record must be { scenarioIds, campaignSetIds }");return}let nodeScenarios=definition.graph.nodes.flatMap(node=>node.scenario?.kind==="fixed"?[String(node.scenario.scenarioId)]:[]),listed=record.scenarioIds;!Array.isArray(listed)||listed.some(scenarioId=>typeof scenarioId!="string")?add(at,"record.scenarioIds must be a list of scenario ids"):listed.join(`
4
+ `)!==nodeScenarios.join(`
5
+ `)&&add(at,`record.scenarioIds must list the nodes' scenarios in order: ${nodeScenarios.join(", ")}`);let sets=record.campaignSetIds;if(!Array.isArray(sets)||sets.some(setId=>typeof setId!="string"))add(at,"record.campaignSetIds must be a list of encounter set ids (empty is fine)");else{for(let setId of sets)isBaseEncounterSetId(setId)?add(at,`record.campaignSetIds: "${setId}" is a base-game set`):!input.packSetIds.has(setId)&&!requiredSetIds.has(setId)&&add(at,`record.campaignSetIds: "${setId}" is not an encounter set of this pack or a required pack`);let own=new Set(sets);for(let source of opsOfKind([definition.everyNodeSetup,definition.everyNodeVictory,definition.conditionalInstructions,definition.logUpgrades,definition.graph],"campaignSet"))own.has(String(source.encounterSetId))||add(at,`draws from "${String(source.encounterSetId)}", which is not in record.campaignSetIds`)}record.prohibited!==void 0&&!isObj(record.prohibited)&&add(at,"record.prohibited must be an object")}var SPEAKERS=["narrator","villain","npc"];function checkStory(at,entry,definition,add){let story=entry.story;if(story===void 0)return;if(!isObj(story)){add(at,"story must be an object");return}text(story.blurb)||add(at,"story.blurb must be a non-empty string"),story.rosterBanner!==void 0&&!text(story.rosterBanner)&&add(at,"story.rosterBanner must be text");let nodeIds=new Set(definition.graph.nodes.map(node=>String(node.id))),line=(where,value)=>{!isObj(value)||!text(value.text)||!isObj(value.speaker)||!SPEAKERS.includes(String(value.speaker.kind))?add(at,`${where} must be { speaker: narrator | villain | npc, text }`):value.speaker.kind==="npc"&&!text(value.speaker.name)&&add(at,`${where}: an npc speaker needs a name`)};if(story.issues!==void 0){Array.isArray(story.issues)||add(at,"story.issues must be a list");let seen=new Set;for(let issue of Array.isArray(story.issues)?story.issues:[]){if(!isObj(issue)){add(at,"every story issue must be an object");continue}let nodeId=String(issue.nodeId);nodeIds.has(nodeId)||add(at,`story issue names node "${nodeId}", which the campaign does not have`),seen.has(nodeId)&&add(at,`story has two issues for node "${nodeId}"`),seen.add(nodeId);for(let field of["title","villain"])text(issue[field])||add(at,`story issue "${nodeId}": ${field} must be text`);for(let field of["blurb","rewindTaunt"])issue[field]!==void 0&&!text(issue[field])&&add(at,`story issue "${nodeId}": ${field} must be text`);for(let field of["briefing","aftermath"])issue[field]!==void 0&&line(`story issue "${nodeId}": ${field}`,issue[field])}}let finale=story.finale;finale!==void 0&&(!isObj(finale)||!text(finale.caption)||!text(finale.headline)||!text(finale.villainLine)||!Array.isArray(finale.heroLines)||finale.heroLines.length===0||finale.heroLines.some(heroLine=>!text(heroLine)))&&add(at,"story.finale must be { caption, headline, villainLine, heroLines: [text, ...] }")}function packCampaignsOf(campaigns){return(campaigns??[]).filter(entry=>isObj(entry)&&typeof entry.id=="string"&&isObj(entry.definition)&&isObj(entry.record))}var isUnscriptedAbilityIssue=issue=>issue.category==="unscripted-ability";function splitIssues(issues){return{unscripted:issues.filter(isUnscriptedAbilityIssue),defects:issues.filter(issue=>!isUnscriptedAbilityIssue(issue))}}var REQUIRED_PACK_FILES=["CREDITS.md","PERMISSION.md"],SEMVER=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,CARD_NUMBER=/^\d+[a-z]?$/,SHA256=/^[0-9a-f]{64}$/,defaultBaseCodes,baseCodes=()=>defaultBaseCodes??=new Set(PLAYABLE_CARDS.map(card=>card.id)),defaultBaseCards,baseCardsById=cards=>cards?new Map(cards.map(card=>[card.id,card])):defaultBaseCards??=new Map(PLAYABLE_CARDS.map(card=>[card.id,card])),isObj2=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),has=(record,key)=>Object.hasOwn(record,key),errorText=error=>error instanceof Error?error.message:String(error);function validatePack(input,options={}){let issues=[],add=(path,message,category)=>{issues.push(category?{path,message,category}:{path,message})};try{validateInto(input,options,add)}catch(error){add("pack",`could not be checked: ${errorText(error)}`)}return issues}function validateInto(input,options,add){if(!isObj2(input)||!isObj2(input.manifest)){add("pack.json","must be a JSON object");return}let baseAbilities=options.baseAbilities??PLAYABLE_DEPS.abilities,baseCardCodes=options.baseCardCodes??baseCodes(),supported=new Set(options.supportedFeatures??SUPPORTED_DSL_FEATURES),{manifest}=input;checkManifestFields(manifest,add);let packId=typeof manifest.id=="string"?manifest.id:"",prefix=customCardPrefix(packId),cards=[];Array.isArray(input.cards)?input.cards.forEach((card,index)=>{isObj2(card)?cards.push(card):add(`cards[${index}]`,"must be a card object")}):add("data/cards.json","must be a list of cards");let packCodes=new Set;for(let card of cards){let code=typeof card.id=="string"?card.id:"",at=`cards/${code||"?"}`;code===""?add(at,"card needs an id"):code.startsWith(prefix)?CARD_NUMBER.test(code.slice(prefix.length))||add(at,`card code must be "${prefix}<number>" with an optional face letter, e.g. "${prefix}01a"`):add(at,`card code must start with "${prefix}"`),packCodes.has(code)&&add(at,"card code is used by two cards"),packCodes.add(code),runContentCheck(at,()=>validateCard(card),add)}let knownCard=code=>packCodes.has(code)||baseCardCodes.has(code)||(options.requiredPackCards?.has(code)??!1);for(let card of cards){let at=`cards/${String(card.id)}`;card.type==="hero_identity"&&!knownCard(String(card.obligationCardId))&&add(at,`obligationCardId "${String(card.obligationCardId)}" is in neither the pack nor the base game`),card.otherFaceId!==void 0&&!knownCard(String(card.otherFaceId))&&add(at,`otherFaceId "${String(card.otherFaceId)}" is in neither the pack nor the base game`)}let cardNumbers=new Set([...packCodes].map(code=>digitsOf(code.slice(prefix.length)))),abilities=isObj2(input.abilities)?input.abilities:{};input.abilities!==void 0&&!isObj2(input.abilities)&&add("data/abilities.json","must be a JSON object");for(let[id,definition]of Object.entries(abilities)){let at=`abilities/${id}`;if(!PACK_ABILITY_ID.test(id)||!id.startsWith(prefix)?add(at,`ability id must be "${prefix}<card number>.<slug>"`):cardNumbers.has(digitsOf(id.slice(prefix.length).split(".")[0]))||add(at,"ability id names a card number the pack has no card for"),has(baseAbilities,id)&&add(at,"ability id is already defined by the base game"),!isObj2(definition)){add(at,"must be an ability definition object");continue}try{for(let problem of validateDefinition(definition))add(at,problem)}catch(error){add(at,`could not be checked: ${errorText(error)}`)}}for(let card of cards)for(let ref of abilityRefsOf(card))!has(abilities,ref)&&!has(baseAbilities,ref)&&add(`cards/${String(card.id)}`,`ability "${ref}" is defined by neither the pack nor the base game (not scripted yet)`,"unscripted-ability");let features=dslFeatures(abilities,campaignDefinitionsOf(Array.isArray(input.campaigns)?input.campaigns:void 0));for(let feature of features)supported.has(feature)||add("abilities",`uses DSL feature "${feature}", which this game version lacks`);let declared=manifest.requires?.dslFeatures;Array.isArray(declared)&&declared.join(`
6
+ `)!==features.join(`
7
+ `)&&add("pack.json requires.dslFeatures",`must list exactly the features the abilities use: ${features.join(", ")}`),checkFiles(input,add),checkCover(input,add);let isPackFace=code=>code.startsWith(prefix)&&CARD_NUMBER.test(code.slice(prefix.length))&&cardNumbers.has(digitsOf(code.slice(prefix.length))),officialById=baseCardsById(options.baseCards),officialPictures=officialCardsByPictureCode(options.baseCards??PLAYABLE_CARDS),ruleBlock=manifest.houseRule,isRuleFace=code=>manifest.kind==="house-rule"&&officialPictures.has(code)&&isObj2(ruleBlock)&&houseRuleMayRebuild(ruleBlock,code);checkLanguagesAndArt(input,code=>knownCard(code)||isPackFace(code),code=>isPackFace(code)||isRuleFace(code),add),checkHouseRule(input,officialById,add),checkStagePictures(input,cards,add);let deckIds=new Set,decks=input.decks;decks!==void 0&&!Array.isArray(decks)&&add("data/decks.json","must be a list of decks");for(let[index,deck]of(Array.isArray(decks)?decks:[]).entries()){if(!isObj2(deck)){add(`decks[${index}]`,"must be a deck object");continue}let id=typeof deck.id=="string"?deck.id:"",at=`decks/${id||index}`;(!id.startsWith(`${packId}-`)||packId==="")&&add(at,`deck id must start with "${packId}-"`),deckIds.has(id)&&add(at,"deck id is used by two decks"),deckIds.add(id),runContentCheck(at,()=>validateStarterDeck(deck),add),knownCard(String(deck.identityCardId))||add(at,`identity "${String(deck.identityCardId)}" is in neither the pack nor the base game`);for(let entry of Array.isArray(deck.cards)?deck.cards:[]){if(!isObj2(entry)){add(at,"every deck line must be an object");continue}knownCard(String(entry.cardId))||add(at,`card "${String(entry.cardId)}" is in neither the pack nor the base game`),(typeof entry.quantity!="number"||!Number.isInteger(entry.quantity)||entry.quantity<1)&&add(at,`card "${String(entry.cardId)}" needs a whole quantity of at least 1`)}}checkEncounterSets(input,cards,packId,options,add),checkScenarios(input,cards,packId,options,add);let campaigns=input.campaigns;if(campaigns!==void 0&&!Array.isArray(campaigns))add("data/campaigns.json","must be a list of campaigns");else if(campaigns!==void 0){let required=options.requiredPackContent,requiredCards=new Set((required?.cards??[]).map(card=>card.id));checkPackCampaigns({packId,campaigns,packScenarioIds:new Set((Array.isArray(input.scenarios)?input.scenarios:[]).flatMap(scenario=>isObj2(scenario)&&typeof scenario.id=="string"?[scenario.id]:[])),packSetIds:new Set((Array.isArray(input.encounterSets)?input.encounterSets:[]).flatMap(set=>isObj2(set)&&typeof set.id=="string"?[set.id]:[])),isCardId:code=>knownCard(code)||requiredCards.has(code),required:{scenarios:required?.scenarios??[],encounterSets:required?.encounterSets??[]},listedFiles:new Set(Array.isArray(manifest.files)?manifest.files.flatMap(f=>isObj2(f)&&typeof f.path=="string"?[f.path]:[]):[]),add})}checkAchievements(input,cards,packId,add);for(let message of packCatalogFieldProblems(input.manifest))add("pack.json",message)}function checkAchievements(input,cards,packId,add){let{manifest}=input,idsOf=list=>new Set((Array.isArray(list)?list:[]).flatMap(one=>isObj2(one)&&typeof one.id=="string"?[one.id]:[])),rule=manifest.houseRule,toggle=manifest.kind==="house-rule"&&isObj2(rule)&&Array.isArray(rule.traitAdditions)&&rule.traitAdditions.length>0&&rule.enablesMode===void 0,problems=packAchievementProblems(manifest.achievements,{packId,heroIds:new Set(cards.filter(card=>card.type==="hero_identity").map(card=>String(card.id))),scenarioIds:idsOf(input.scenarios),campaignIds:idsOf(input.campaigns),houseRuleToggle:toggle});for(let message of problems)add("pack.json achievements",message)}function checkEncounterSets(input,cards,packId,options,add){let sets=input.encounterSets;sets!==void 0&&!Array.isArray(sets)&&add("data/encounter-sets.json","must be a list of encounter sets");let ids=new Set;for(let[index,set]of(Array.isArray(sets)?sets:[]).entries()){if(!isObj2(set)){add(`encounterSets[${index}]`,"must be an encounter set object");continue}let id=typeof set.id=="string"?set.id:"",at=`encounterSets/${id||index}`;(!id.startsWith(`${packId}-`)||packId==="")&&add(at,`encounter set id must start with "${packId}-"`),ids.has(id)&&add(at,"encounter set id is used by two sets"),isBaseEncounterSetId(id)&&add(at,"encounter set id is a base-game set id (the base game always wins)"),ids.add(id),runContentCheck(at,()=>validateEncounterSet(set),add),Array.isArray(set.packCodes)||add(at,"packCodes must be a list");for(let field of UNSUPPORTED_SET_FIELDS)set[field]!==void 0&&add(at,`"${field}" is not available to a pack's encounter set yet`);let nemesisOf=cards.find(card=>card.type==="hero_identity"&&card.nemesisEncounterSetId===id);if(set.nemesisOfIdentityId!==void 0){let owner=cards.find(card=>card.id===set.nemesisOfIdentityId);!owner||owner.type!=="hero_identity"?add(at,`nemesisOfIdentityId "${String(set.nemesisOfIdentityId)}" is not a hero identity of this pack`):owner.nemesisEncounterSetId!==id&&add(at,`the identity names "${String(owner.nemesisEncounterSetId)}" as its nemesis set, not this one`)}else nemesisOf&&add(at,`is ${String(nemesisOf.id)}'s nemesis set, so it needs nemesisOfIdentityId (or it is offered as a modular set)`)}let required=new Set((options.requiredPackContent?.encounterSets??[]).map(set=>set.id)),belongsToPack=id=>id===packId||id.startsWith(`${packId}-`);for(let card of cards){let at=`cards/${String(card.id)}`;for(let id of Array.isArray(card.encounterSetIds)?card.encounterSetIds:[])typeof id=="string"&&(belongsToPack(id)?ids.has(id)||add(at,`encounter set "${id}" has no record in the pack's encounter sets`):required.has(id)||add(at,`encounter set "${id}" is not this pack's: a card may not join a base-game set (RRG 1.8 p. 29)`));let nemesis=card.type==="hero_identity"?card.nemesisEncounterSetId:void 0;typeof nemesis=="string"&&belongsToPack(nemesis)&&!ids.has(nemesis)&&add(at,`nemesis set "${nemesis}" has no record in the pack's encounter sets`)}}function checkHouseRule(input,officialById,add){let{manifest}=input,at=field=>`pack.json ${field}`,rule=manifest.houseRule;if(manifest.kind!=="house-rule"){rule!==void 0&&add(at("houseRule"),'only a "house-rule" pack may carry a house rule');return}if(!isObj2(rule)){add(at("houseRule"),"a house-rule pack needs its houseRule: { traitAdditions?, enablesMode? }");return}for(let key of Object.keys(rule))key!=="traitAdditions"&&key!=="enablesMode"&&add(at(`houseRule.${key}`),"is not a house rule field");let lengthOf=value=>Array.isArray(value)?value.length:0,cards=Array.isArray(input.cards)?input.cards:[];for(let[index,card]of cards.entries()){let aspect=isObj2(card)&&typeof card.aspect=="string"?card.aspect:"",identityId=aspect.startsWith("hero:")?aspect.slice(5):"",official=officialById.get(identityId);(!isObj2(card)||card.optionalForIdentity!==!0||official?.type!=="hero_identity")&&add(`data/cards.json[${index}]`,"a house-rule pack adds only cards for an official hero that no deck must hold (optionalForIdentity, aspect hero:<official identity id>): it changes official ones otherwise")}cards.length===0&&Object.keys(isObj2(input.abilities)?input.abilities:{}).length>0&&add("data/abilities.json","a house-rule pack carries no abilities (its rules are data, or the game's own)"),cards.length===0&&lengthOf(input.decks)>0&&add("data/decks.json","a house-rule pack carries none");for(let[field,path]of[["scenarios","data/scenarios.json"],["encounterSets","data/encounter-sets.json"],["campaigns","data/campaigns.json"]])lengthOf(input[field])>0&&add(path,"a house-rule pack carries none");manifest.altArt!==void 0&&add(at("altArt"),"a house rule's faces are its cards/<lang>/<code>.webp pictures, not altArt");let mode=rule.enablesMode;mode!==void 0&&!PACK_HOUSE_RULE_MODES.includes(mode)&&add(at("houseRule.enablesMode"),`must be one of ${PACK_HOUSE_RULE_MODES.join(", ")}`);let additions=rule.traitAdditions;if(mode!==void 0&&lengthOf(additions)>0&&add(at("houseRule"),"enablesMode and traitAdditions cannot be combined: make two packs"),additions!==void 0&&!Array.isArray(additions)){add(at("houseRule.traitAdditions"),"must be a list of { code, traits }");return}mode===void 0&&lengthOf(additions)===0&&cards.length===0&&add(at("houseRule"),"does nothing: give it traitAdditions, enablesMode or a card for an official hero");let seen=new Set;for(let[index,addition]of(Array.isArray(additions)?additions:[]).entries()){let where=at(`houseRule.traitAdditions[${index}]`);if(!isObj2(addition)){add(where,"must be { code, traits }");continue}for(let key of Object.keys(addition))key!=="code"&&key!=="traits"&&add(`${where}.${key}`,"is not a trait addition field (traits are only added)");let code=typeof addition.code=="string"?addition.code:"";(code===""||officialFaceOfCode(code,officialById)===void 0)&&add(where,`code "${code}" is not a face of an official card (a card code, or a hero identity's alter-ego "b")`),seen.has(code)&&add(where,`code "${code}" is listed twice`),seen.add(code);let traits=addition.traits;(!Array.isArray(traits)||traits.length===0||traits.some(name=>typeof name!="string"||name.trim()===""||name.length>40))&&add(where,"traits must list at least one trait name")}}var UNSUPPORTED_SET_FIELDS=["campaignSpecific","competitiveOnly","side","separateDecks","singleVillainOnly","extraModular","autoIncluded"];function checkScenarios(input,cards,packId,options,add){let scenarios=input.scenarios;scenarios!==void 0&&!Array.isArray(scenarios)&&add("data/scenarios.json","must be a list of scenarios");let ids=new Set,checked=[];for(let[index,scenario]of(Array.isArray(scenarios)?scenarios:[]).entries()){if(!isObj2(scenario)){add(`scenarios[${index}]`,"must be a scenario object");continue}let id=typeof scenario.id=="string"?scenario.id:"",at=`scenarios/${id||index}`;(!id.startsWith(`${packId}-`)||packId==="")&&add(at,`scenario id must start with "${packId}-"`),ids.has(id)&&add(at,"scenario id is used by two scenarios"),isBaseScenarioId(id)&&add(at,"scenario id is a base-game scenario id (the base game always wins)"),ids.add(id),typeof scenario.packCode=="string"&&scenario.packCode!==packId&&add(at,`packCode must be the pack's id "${packId}"`);let problems=0;runContentCheck(at,()=>{let result=validateScenario(scenario);return problems=result.errors.length,result},add),problems===0&&checked.push(scenario)}let custom={cards:[...cards,...options.requiredPackContent?.cards??[]],encounterSets:[...(Array.isArray(input.encounterSets)?input.encounterSets:[]).filter(isObj2),...options.requiredPackContent?.encounterSets??[]],scenarios:checked};for(let scenario of checked)try{for(let problem of customScenarioProblems(scenario,custom))add(`scenarios/${String(scenario.id)}`,problem)}catch(error){add(`scenarios/${String(scenario.id)}`,`could not be checked: ${errorText(error)}`)}}var digitsOf=cardNumber=>cardNumber.replace(/[a-z]$/,"");function runContentCheck(path,check,add){try{for(let message of check().errors)add(path,message)}catch(error){add(path,`could not be checked: ${errorText(error)}`)}}function checkManifestFields(manifest,add){let at=field=>`pack.json ${field}`;manifest.schema!==1&&add(at("schema"),`must be ${1}`),(typeof manifest.id!="string"||!isPackId(manifest.id))&&add(at("id"),"must be lowercase letters, digits and single dashes, at most 64 characters"),(typeof manifest.version!="string"||!SEMVER.test(manifest.version))&&add(at("version"),"must be semver"),PACK_KINDS.includes(manifest.kind)||add(at("kind"),`must be one of ${PACK_KINDS.join(", ")}`);for(let field of["name","description","license"])(typeof manifest[field]!="string"||manifest[field].trim()==="")&&add(at(field),"must be a non-empty string");(!Array.isArray(manifest.authors)||manifest.authors.length===0||manifest.authors.some(a=>typeof a!="string"||a.trim()===""))&&add(at("authors"),"must list at least one author");let requires=manifest.requires;isObj2(requires)?((typeof requires.app!="string"||requires.app.trim()==="")&&add(at("requires.app"),"must be a semver range"),Array.isArray(requires.dslFeatures)||add(at("requires.dslFeatures"),"must be a list"),!Array.isArray(requires.packs)||requires.packs.some(p=>typeof p!="string"||!isPackId(p))?add(at("requires.packs"),"must be a list of pack ids"):requires.packs.includes(manifest.id)&&add(at("requires.packs"),"a pack cannot require itself")):add(at("requires"),"is required");let contents=manifest.contents;(!isObj2(contents)||typeof contents.cards!="string")&&add(at("contents.cards"),"must name the cards file"),Array.isArray(manifest.files)||add(at("files"),"must be a list"),(typeof manifest.totalBytes!="number"||!Number.isInteger(manifest.totalBytes)||manifest.totalBytes<0)&&add(at("totalBytes"),"must be a whole number"),manifest.pictures!==void 0&&!isObj2(manifest.pictures)&&add(at("pictures"),"must be an object"),checkCredits(manifest,add)}var ISO_DATE=/^\d{4}-\d{2}-\d{2}$/;function checkCredits(manifest,add){let at=field=>`pack.json ${field}`,text2=value=>typeof value=="string"&&value.trim()!=="",permission=manifest.permission;if(permission!==void 0)if(!isObj2(permission))add(at("permission"),"must be an object");else{text2(permission.by)||add(at("permission.by"),"must say who gave permission"),permission.date!==void 0&&(typeof permission.date!="string"||!ISO_DATE.test(permission.date))&&add(at("permission.date"),"must be YYYY-MM-DD");for(let field of["evidence","scope","note"])permission[field]!==void 0&&!text2(permission[field])&&add(at(`permission.${field}`),"must be text");let status=permission.status;status!==void 0&&!PACK_PERMISSION_STATUSES.includes(status)&&add(at("permission.status"),`must be one of ${PACK_PERMISSION_STATUSES.join(", ")}`);let languages=permission.languages;if(languages!==void 0&&(!Array.isArray(languages)||languages.some(lang=>typeof lang!="string"||!isLanguageTag(lang)))&&add(at("permission.languages"),"must be a list of language tags"),status==="granted"){for(let field of["date","evidence","scope"])permission[field]===void 0&&add(at(`permission.${field}`),"is required when the status is granted");languages===void 0&&add(at("permission.languages"),"is required when the status is granted")}}manifest.templateCredit!==void 0&&!text2(manifest.templateCredit)&&add(at("templateCredit"),"must be text");let translators=manifest.translators;if(translators!==void 0)if(!isObj2(translators))add(at("translators"),"must map language tags to names");else for(let[lang,name]of Object.entries(translators))(!isLanguageTag(lang)||!text2(name))&&add(at(`translators.${lang}`),"needs a language tag and a name")}function publishIssues(manifest){let issues=[],add=(path,message)=>{issues.push({path:`pack.json ${path}`,message})},permission=manifest.permission;if(!isObj2(permission))return add("permission","is required to publish: record the creator's grant (status, by, date, evidence, scope, languages)"),issues;if(permission.status!=="granted"){let status=typeof permission.status=="string"?permission.status:"missing",note=typeof permission.note=="string"&&permission.note.trim()!==""?`: ${permission.note}`:"";return add("permission.status",`is ${status}, not granted, so the pack is not published${note}`),issues}let covered=new Set(Array.isArray(permission.languages)?permission.languages:[]),missing=(manifest.languages?.available??[]).filter(lang=>!covered.has(lang));return missing.length>0&&add("permission.languages",`does not cover ${missing.join(", ")}: a translation needs the creator's permission too`),issues}function checkLanguagesAndArt(input,knownCard,isPackFace,add){let{manifest}=input,at=field=>`pack.json ${field}`,languages=manifest.languages,available;if(languages!==void 0)if(!isObj2(languages))add(at("languages"),"must be { base, available }");else{let list=languages.available;!Array.isArray(list)||list.length===0||list.some(l=>typeof l!="string"||!isLanguageTag(l))?add(at("languages.available"),'must list language tags such as "en"'):(available=new Set(list),available.size!==list.length&&add(at("languages.available"),"lists a language twice"),(typeof languages.base!="string"||!available.has(languages.base))&&add(at("languages.base"),"must be one of the available languages")),languages.text!==void 0&&(typeof languages.text!="string"||!isLanguageTag(languages.text))&&add(at("languages.text"),"must be a language tag")}let listed=new Set(Array.isArray(manifest.files)?manifest.files.flatMap(f=>isObj2(f)&&typeof f.path=="string"?[f.path]:[]):[]);for(let path of listed){let picture=parsePackCardImagePath(path);picture&&(available?available.has(picture.lang)||add(path,`language "${picture.lang}" is not in languages.available`):add(path,'card pictures need "languages" in pack.json'),isPackFace(picture.code)||add(path,`"${picture.code}" is not a card of this pack`+(manifest.kind==="house-rule"?" (a house rule rebuilds only its trait additions' faces, or the Balanced cards for enablesMode balanced)":"")))}let altArt=manifest.altArt;if(altArt!==void 0){if(!isObj2(altArt)){add(at("altArt"),"must map languages to card codes to file paths");return}for(let[lang,byCode]of Object.entries(altArt)){if(!isObj2(byCode)){add(at(`altArt.${lang}`),"must map card codes to file paths");continue}(!isLanguageTag(lang)||available&&!available.has(lang))&&add(at(`altArt.${lang}`),"language is not in languages.available");for(let[code,path]of Object.entries(byCode))knownCard(code)||add(at(`altArt.${lang}.${code}`),"is a card neither the pack nor the base game has"),(typeof path!="string"||!listed.has(path))&&add(at(`altArt.${lang}.${code}`),`"${String(path)}" is not a listed file`)}}}function checkStagePictures(input,cards,add){let languages=input.manifest.languages,base=isObj2(languages)&&typeof languages.base=="string"?languages.base:void 0;if(!base||!Array.isArray(input.manifest.files))return;let shipped=new Set;for(let f of input.manifest.files){let picture=isObj2(f)&&typeof f.path=="string"?parsePackCardImagePath(f.path):void 0;picture?.lang===base&&shipped.add(picture.code)}for(let card of cards){let id=String(card.id),wanted=packStagedPictureCodes(card);if(wanted.length<2)continue;let number=digitsOf(id);if([...shipped].some(code=>digitsOf(code)===number))for(let code of wanted)shipped.has(code)||add(`cards/${id}`,`stage picture "cards/${base}/${code}.webp" is not a listed file`)}}var COVER_ASPECT={min:.5,max:.8},COVER_HEIGHT={min:300,max:4096};function checkCover(input,add){let cover=input.manifest.cover;if(cover===void 0)return;let at="pack.json cover";if(typeof cover!="string"||!isPackCoverPath(cover)){add(at,'must be the path of a .webp file in the pack, such as "cover.webp"');return}let bytes=input.files instanceof Map?input.files.get(cover):void 0;if(!(bytes instanceof Uint8Array)){add(at,`"${cover}" is not a file of the pack`);return}bytes.length>PACK_COVER_MAX_BYTES&&add(at,`"${cover}" is ${bytes.length} bytes, more than a cover's ${PACK_COVER_MAX_BYTES}`);let size=webpSize(bytes);if(!size){add(at,`"${cover}" is not a WebP picture`);return}let{width,height}=size,aspect=width/height;(aspect<COVER_ASPECT.min||aspect>COVER_ASPECT.max)&&add(at,`"${cover}" is ${width}x${height}: a cover is portrait, about 600x984 (width/height 0.5 to 0.8)`),(height<COVER_HEIGHT.min||height>COVER_HEIGHT.max)&&add(at,`"${cover}" is ${width}x${height}: its height must be ${COVER_HEIGHT.min} to ${COVER_HEIGHT.max} pixels`)}function checkFiles(input,add){let{manifest,files}=input;if(!(files instanceof Map)){add("files","the pack's files must be a Map of path to bytes");return}for(let[path,bytes]of files)bytes instanceof Uint8Array||add(String(path),"file content must be bytes");if(!Array.isArray(manifest.files))return;let listed=new Set,total=0;for(let entry of manifest.files){if(!isObj2(entry)||typeof entry.path!="string"){add("pack.json files","every entry needs a string path");continue}let path=entry.path;if(!isSafePackPath(path)){add(path,"unsafe file path (must be relative, with / separators and no .. or empty parts)");continue}if(path==="pack.json"&&add(path,"pack.json does not list itself"),listed.has(path)&&add(path,"listed twice"),listed.add(path),typeof entry.sha256!="string"||!SHA256.test(entry.sha256)){add(path,"sha256 must be 64 lowercase hex characters");continue}if(typeof entry.bytes!="number"||!Number.isInteger(entry.bytes)||entry.bytes<0){add(path,"bytes must be a whole number");continue}let bytes=files.get(path);if(!(bytes instanceof Uint8Array)){add(path,"listed in pack.json but missing from the pack");continue}total+=entry.bytes,bytes.length!==entry.bytes?add(path,`size is ${bytes.length} bytes, pack.json says ${entry.bytes}`):sha256Hex(bytes)!==entry.sha256&&add(path,"sha256 does not match pack.json")}for(let path of files.keys())listed.has(path)||add(path,"in the pack but not listed in pack.json");Number.isInteger(manifest.totalBytes)&&manifest.totalBytes!==total&&add("pack.json totalBytes",`is ${manifest.totalBytes}, the listed files add up to ${total}`);for(let required of REQUIRED_PACK_FILES){let bytes=files.get(required);bytes instanceof Uint8Array?bytes.length===0&&add(required,"required file is empty"):add(required,"required file is missing")}if(isObj2(manifest.contents))for(let[role,path]of Object.entries(manifest.contents))typeof path=="string"&&!listed.has(path)&&add(`pack.json contents.${role}`,`"${path}" is not a listed file`);if(isObj2(manifest.pictures))for(let[role,byCard]of Object.entries(manifest.pictures)){if(!isObj2(byCard)){add(`pack.json pictures.${role}`,"must map card codes to file paths");continue}for(let[code,path]of Object.entries(byCard))(typeof path!="string"||!listed.has(path))&&add(`pack.json pictures.${role}.${code}`,`"${String(path)}" is not a listed file`)}}function abilityRefsOf(value){let refs=[],visit2=(node,key)=>{if(Array.isArray(node))for(let item of node)visit2(item,key);else if(isObj2(node)){key==="abilities"&&typeof node.id=="string"&&refs.push(node.id);for(let[childKey,child]of Object.entries(node))visit2(child,childKey)}};return visit2(value,""),refs}var decoder=new TextDecoder;function readPackInput(manifest,files){let parse=path=>{if(path===void 0)return;let bytes=files.get(path);if(!bytes)throw new Error(`${path}: missing from the pack`);try{return JSON.parse(decoder.decode(bytes))}catch{throw new Error(`${path}: not valid JSON`)}},list=path=>{let parsed=parse(path);if(parsed!==void 0){if(!Array.isArray(parsed))throw new Error(`${path}: must be a JSON array`);return parsed}},abilities=parse(manifest.contents.abilities)??{};if(typeof abilities!="object"||abilities===null||Array.isArray(abilities))throw new Error(`${manifest.contents.abilities}: must be a JSON object`);let decks=list(manifest.contents.decks),scenarios=list(manifest.contents.scenarios),encounterSets=list(manifest.contents.encounterSets),campaigns=list(manifest.contents.campaigns);return{manifest,files,cards:list(manifest.contents.cards)??[],abilities,...decks?{decks}:{},...scenarios?{scenarios}:{},...encounterSets?{encounterSets}:{},...campaigns?{campaigns}:{}}}export{dslFeatures,campaignDefinitionsOf,SUPPORTED_DSL_FEATURES,PACK_ABILITY_ID,definePackAbilities,sha256Hex,isPlainJson,checkPackCampaigns,packCampaignsOf,isUnscriptedAbilityIssue,splitIssues,REQUIRED_PACK_FILES,validatePack,publishIssues,abilityRefsOf,readPackInput};
@@ -0,0 +1,22 @@
1
+ import{assemblePack}from"./chunk-RRZU6F4D.js";import{abilityRefsOf,readPackInput,splitIssues,validatePack}from"./chunk-3ZP7JFBM.js";import{PACK_KINDS,isLanguageTag,isPackId,packCardImagePath}from"./chunk-GIPUMXZ5.js";import{copyFileSync,existsSync,mkdirSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";var isObj=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),str=value=>typeof value=="string"&&value!==""?value:void 0,normalizer;function registerMarvelCdbNormalizer(normalize){normalizer=normalize}async function loadNormalizer(){if(normalizer)return normalizer;let module=await import(new URL("../../content/scripts/marvelcdb/normalize.ts",import.meta.url).href);if(typeof module.normalizePack!="function")throw new Error("the content package's normalizePack is missing");return normalizer=module.normalizePack}var kebab=text=>text.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),KIND_ALIASES=Object.fromEntries(PACK_KINDS.flatMap(kind=>[[kind,kind],[`${kind}_pack`,kind]]));function dataFileOf(srcDir,modId){let named=join(srcDir,`${modId}.json`);if(existsSync(named))return named;let others=readdirSync(srcDir).filter(name=>name.endsWith(".json")&&name!=="mod.json");if(others.length!==1)throw new Error(`${srcDir}: expected ${modId}.json (or one .json besides mod.json)`);return join(srcDir,others[0])}var tailOf=code=>{let match=/^(.*\d)([a-z])$/.exec(code);return match?{key:match[1],letter:match[2]}:{key:code,letter:""}};function planCodes(records,packId){let order=[],visit=record2=>{let code=str(record2.code);if(code===void 0)throw new Error("a card record has no code");order.push(code),isObj(record2.linked_card)&&visit(record2.linked_card)};records.forEach(visit);let numbers=new Map,out=new Map;for(let code of order){if(out.has(code))throw new Error(`card code ${code} appears twice`);let{key,letter}=tailOf(code);numbers.has(key)||numbers.set(key,numbers.size+1);let n=numbers.get(key);out.set(code,`x.${packId}.${String(n).padStart(numbers.size>99?3:2,"0")}${letter}`)}return out}function planSets(records,packId){let all=records.flatMap(r=>isObj(r.linked_card)?[r,r.linked_card]:[r]),heroSet=all.map(r=>r.type_code==="hero"?str(r.card_set_code):void 0).find(Boolean),out=new Map;for(let record2 of all){let set=str(record2.card_set_code);if(!(set===void 0||out.has(set)))if(set===heroSet)out.set(set,packId);else{let rest=heroSet!==void 0&&set.startsWith(`${heroSet}_`)?set.slice(heroSet.length+1):set;out.set(set,`${packId}-${kebab(rest)}`)}}let finals=[...out.values()];if(new Set(finals).size!==finals.length)throw new Error("two source sets map to the same encounter set id");return out}var escapeRegExp=text=>text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function makeRewriter(map){let keys=[...map.keys()].sort((a,b)=>b.length-a.length).map(escapeRegExp),pattern=new RegExp(`(?<![A-Za-z0-9_])(?:${keys.join("|")})(?![A-Za-z0-9_])`,"g"),walk=node=>typeof node=="string"?node.replace(pattern,hit=>map.get(hit)??hit):Array.isArray(node)?node.map(walk):isObj(node)?Object.fromEntries(Object.entries(node).filter(([key])=>key!=="images"&&key!=="image").map(([key,child])=>[key,walk(child)])):node;return walk}var collectorOf=finalCode=>(/\.(\d+[a-z]?)$/.exec(finalCode)?.[1]??finalCode).replace(/^0+(?=\d)/,"").toUpperCase();function toSourceCodes(curation,finalToSource){let source=code=>finalToSource.get(code)??code,pattern=new RegExp(`^(${[...finalToSource.keys()].map(escapeRegExp).join("|")})(?=\\.|$)`),fixKeys=record2=>isObj(record2)?Object.fromEntries(Object.entries(record2).map(([key,value])=>[key.replace(pattern,m=>source(m)),value])):record2,fixCode=list=>Array.isArray(list)?list.map(e=>isObj(e)&&typeof e.code=="string"?{...e,code:source(e.code)}:e):list,out={...curation};for(let key of["corrections","errata","ignoredRecords"])key in out&&(out[key]=fixCode(out[key]));for(let key of["cardNotes","scriptingNotes"])key in out&&(out[key]=fixKeys(out[key]));return out}function markFlipSides(records,notes,codes){let IDENTITY_TYPES=new Set(["hero","alter_ego","villain","main_scheme"]);return records.map(record2=>{let back=record2.linked_card,type=record2.type_code;if(!isObj(back)||back.hidden!==void 0||IDENTITY_TYPES.has(type)||IDENTITY_TYPES.has(back.type_code))return record2;let code=str(back.code)??"?";return notes.push(`marked ${codes.get(code)??code} as the hidden flip side of ${str(record2.name)??"?"}, as the API does`),{...record2,linked_card:{...back,hidden:!0}}})}function dashCostCorrections(records,finalOf,skip){let found=[];for(let record2 of records){let code=str(record2.code);if(code===void 0||skip.has(code))continue;let noCost=record2.cost===void 0||record2.cost===null;if(record2.permanent!==!0||!noCost||record2.cost_per_hero===!0||record2.type_code!=="upgrade"&&record2.type_code!=="support")continue;let what=`${String(record2.name)}: a permanent ${String(record2.type_code)} with no cost in the source reads as a printed dash cost (cannot be played, enters play through its own text)`;found.push({correction:{code,reason:what,evidence:"pack importer: permanent card, no cost in the MarvelCDB-shaped record; check the card image",specialCost:"dash"},auto:{code,finalCode:finalOf(code),what}})}return found}var APPENDED=new Set(["corrections","errata","scenarios","starterDecks","separateDecks","ignoredRecords"]);function mergeCuration(base,extra){let out={...base};for(let[key,value]of Object.entries(extra)){let current=out[key];APPENDED.has(key)&&Array.isArray(current)&&Array.isArray(value)?out[key]=[...current,...value]:isObj(current)&&isObj(value)?out[key]={...current,...value}:out[key]=value}return out}function semverOf(text){let match=/^\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?![\d.])/.exec(text);return match?`${match[1]}.${match[2]??"0"}.${match[3]??"0"}`:void 0}function readMod(srcDir){let mod=JSON.parse(readFileSync(join(srcDir,"mod.json"),"utf8"));if(!isObj(mod)||!str(mod.id)||!str(mod.name)||!str(mod.kind)||!str(mod.author))throw new Error(`${join(srcDir,"mod.json")}: needs id, name, kind and author`);return mod}var subDirs=dir=>existsSync(dir)?readdirSync(dir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name):[];function mapPictures(srcDir,codes){let copies=[],missing=[],unmatched=[],languages=subDirs(join(srcDir,"images")).sort();for(let lang of languages){let dir=join(srcDir,"images",lang),present=new Set(readdirSync(dir));for(let[source,final]of codes)present.delete(`${source}.webp`)?copies.push({from:join(dir,`${source}.webp`),to:packCardImagePath(lang,final)}):missing.push(`${lang}/${source}`);unmatched.push(...[...present].sort().map(name=>`images/${lang}/${name}`))}let altArt={};for(let lang of subDirs(join(srcDir,"alt-art")).sort()){let dir=join(srcDir,"alt-art",lang);for(let name of readdirSync(dir).sort()){let match=/^(.+)\.webp$/.exec(name);if(!match){unmatched.push(`alt-art/${lang}/${name}`);continue}let stem=match[1],own=codes.get(stem.replace(/-alt$/,"")),code=own!==void 0&&stem.endsWith("-alt")?own:stem,to=`alt-art/${lang}/${code}.webp`;(altArt[lang]??={})[code]=to,copies.push({from:join(dir,name),to})}}return{copies,languages,missing,unmatched,altArt}}var bytesOf=path=>new Uint8Array(readFileSync(path));function creditsMarkdown(mod,packId,languages,base){let translators=Object.entries(mod.languages??{}).filter(([lang,who])=>lang!=="base"&&who!=="author");return["# Credits","",`${mod.name} (\`${packId}\`) is a fan-made pack by ${mod.author}.`,"",`- Card design and art direction: ${mod.author}.`,...mod.template?[`- Card template: ${mod.template}.`]:[],...translators.map(([lang,who])=>`- Translation and layout (${lang}): ${who}.`),`- Pictures: ${languages.join(", ")} (base language ${base}).`,...mod.version?[`- Source version: ${mod.version}.`]:[],"","The card data was converted from MarvelCDB-shaped records with the mod SDK's `importMarvelCdbPack`.","Character art is Marvel comics art, as used by each author.","","Marvel Champions: The Card Game is the property of Fantasy Flight Games and Marvel.",""].join(`
2
+ `)}function permissionMarkdown(mod,granted){let p=mod.permission??{};return["# Permission","",granted?`${mod.author}, the author of ${mod.name}, gave permission for this pack to be distributed through the mod store.`:`**Permission is not recorded as granted for this pack (status: ${p.status??"none"}). Do not publish it.**`,"",`- Status: ${p.status??"not recorded"}`,`- Scope: ${p.scope??"not recorded"}`,`- Date: ${p.date??"not recorded"}`,"","Recorded in the pack's draft `mod.json`. The registry review asks for the evidence (a link or a quoted message).",""].join(`
3
+ `)}function abilityFacesOf(card){let faces=[],walk=(node,title)=>{if(Array.isArray(node))return void node.forEach(n=>walk(n,title));if(!isObj(node))return;let ids=Array.isArray(node.abilities)?node.abilities.flatMap(a=>isObj(a)&&typeof a.id=="string"?[a.id]:[]):[],here=str(node.faceName)??str(node.name)??title;if(ids.length>0){let text=isObj(node.text)?str(node.text.printed)??"":"";faces.push({title:here,text,ids})}for(let[key,child]of Object.entries(node))key!=="abilities"&&key!=="text"&&walk(child,here)};return walk(card,card.name),faces}function abilitiesStub(cards,packName){let ids=[],blocks=[];for(let card of cards)for(let face of abilityFacesOf(card)){let fresh=face.ids.filter(id=>!ids.includes(id));if(fresh.length===0)continue;ids.push(...fresh);let text=face.text.split(`
4
+ `).map(line=>` // ${line}`);blocks.push([` // ${String(card.id)} ${face.title} (${card.type})`,...text,...fresh.map(id=>` // ${id}`)].join(`
5
+ `))}return{source:["/**",` * ${packName}: abilities still to script (${ids.length}).`," *"," * Generated by the mod SDK's importMarvelCdbPack. Every card below names the ability ids listed under it; until",' * a script exists, `validatePack` reports each as an "unscripted-ability" issue, apart from real defects.',' * Write each one with the DSL (see the sample pack), as `"<id>": heroAction(...)` and so on, and delete its'," * comment. The printed text is above its ids."," */",'import { definePackAbilities } from "@champions-digital-game/mod-sdk";',"","export default definePackAbilities({",blocks.join(`
6
+
7
+ `),"});",""].join(`
8
+ `),ids}}var writeText=(path,text)=>{mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,text)},jsonText=value=>`${JSON.stringify(value,null,2)}
9
+ `;async function importMarvelCdbPack(srcDir,options={}){let mod=readMod(srcDir),packId=options.packId??kebab(mod.id);if(!isPackId(packId))throw new Error(`"${packId}" is not a legal pack id`);let kind=KIND_ALIASES[mod.kind];if(!kind)throw new Error(`mod.json kind "${mod.kind}" is not one of ${PACK_KINDS.join(", ")} (or ..._pack)`);let data=JSON.parse(readFileSync(dataFileOf(srcDir,mod.id),"utf8"));if(!isObj(data)||!Array.isArray(data.cards))throw new Error(`${basename(srcDir)}: no "cards" list in the data file`);let records=data.cards.filter(isObj);if(records.length!==data.cards.length)throw new Error("every card record must be an object");let notes=[],codes=planCodes(records,packId),sets=planSets(records,packId),finalToSource=new Map([...codes].map(([source2,final])=>[final,source2])),rewrite=makeRewriter(new Map([...codes,...sets])),sourceToFinal=Object.fromEntries(codes),nested=records.flatMap(r=>isObj(r.linked_card)?[r,r.linked_card]:[r]),shaped=markFlipSides(records,notes,codes),userCuration=toSourceCodes(options.curation??{},finalToSource),corrected=new Set((Array.isArray(userCuration.corrections)?userCuration.corrections:[]).flatMap(c=>isObj(c)&&typeof c.code=="string"?[c.code]:[])),auto=options.noAutoCuration?[]:dashCostCorrections(records,c=>codes.get(c)??c,corrected),bare={packCode:packId,cycle:{id:packId,name:mod.name,order:0},pack:{name:mod.name,releaseDate:"custom",releaseDateSource:"custom pack: no release date"},outDir:"",exportPrefix:packId.toUpperCase().replace(/[^A-Z0-9]/g,"_"),corrections:auto.map(a=>a.correction),errata:[],scriptingNotes:{},cardNotes:{},scenarios:[],starterDecks:[]},curation=mergeCuration(bare,userCuration),base={packId,name:mod.name,sourceToFinal,autoCurations:auto.map(a=>a.auto),notes},empty={cards:0,copies:0,unscriptedAbilities:[],validationIssues:[],unscriptedIssues:[]},noPictures={missingImages:[],unmatchedImages:[],altArt:{}},normalized;try{normalized=(await loadNormalizer())(shaped,curation)}catch(error){let message=error instanceof Error?error.message:String(error),failures=message.includes(`
10
+ - `)?message.split(`
11
+ - `).slice(1):[message];return{...base,...empty,...noPictures,normalized:!1,normalizerFailures:failures,languages:{base:mod.languages?.base??"en",available:[]}}}let rewritten=normalized.cards.map(c=>rewrite(c)).map(card=>{let numbers=(normalized.provenance.find(p=>rewrite(p.cardId)===card.id)?.marvelcdbCodes??[]).map(s=>collectorOf(codes.get(s)??s));return numbers.length>0?{...card,collectorNumber:numbers.join("/")}:card}),decks=normalized.starterDecks.map(d=>rewrite(d)),scenarios=normalized.scenarios.map(s=>rewrite(s)),encounterSets=normalized.encounterSets.map(set=>rewrite(set)),topCopies=records.reduce((n,r)=>n+(typeof r.quantity=="number"?r.quantity:0),0),pictures=mapPictures(srcDir,codes),baseLanguage=mod.languages?.base??pictures.languages[0]??"en",declared=Object.keys(mod.languages??{}).filter(l=>l!=="base"&&isLanguageTag(l)),available=[...new Set([baseLanguage,...declared,...pictures.languages])].filter(isLanguageTag).sort(),withPictures=pictures.copies.length>0||pictures.languages.length>0,languages={base:baseLanguage,available},textLanguage=options.textLanguage??"en",assets=new Map;for(let{from,to}of pictures.copies)assets.set(to,bytesOf(from));let granted=mod.permission?.status==="granted";assets.set("CREDITS.md",new TextEncoder().encode(creditsMarkdown(mod,packId,pictures.languages,baseLanguage))),assets.set("PERMISSION.md",new TextEncoder().encode(permissionMarkdown(mod,granted)));let translators=Object.fromEntries(Object.entries(mod.languages??{}).filter(([lang,who])=>lang!=="base"&&who!=="author"&&isLanguageTag(lang))),version=semverOf(mod.version??"");version===void 0&&notes.push(`version "${mod.version??""}" is not semver: the pack is 0.1.0`);let permission=granted?{status:"pending",by:mod.author,...mod.permission?.date?{date:mod.permission.date}:{},...mod.permission?.scope?{scope:mod.permission.scope}:{},note:"imported: record the date, the evidence and the languages covered, then set the status to granted"}:void 0;granted?mod.permission?.date||notes.push("permission has no date recorded"):notes.push(`permission is not granted (status: ${mod.permission?.status??"none"})`),mod.status&&mod.status!=="ready"&&notes.push(`mod.json status: ${mod.status}`);for(let open of mod.open??[])notes.push(`open: ${open}`);for(let dropped of normalized.dropped)notes.push(`dropped ${dropped.marvelcdbCode}: ${dropped.reason}`);let author={id:packId,version:version??"0.1.0",kind,name:mod.name,authors:[mod.author],description:options.description??`Fan-made ${kind} pack by ${mod.author}: ${mod.name}.`,license:"Fan-made, non-commercial; see CREDITS.md",requires:{app:options.app??">=0.1.0",packs:[]},...withPictures?{languages:{...languages,...textLanguage!==baseLanguage?{text:textLanguage}:{}}}:{},...Object.keys(pictures.altArt).length>0?{altArt:pictures.altArt}:{},...permission?{permission}:{},...mod.template?{templateCredit:mod.template}:{},...Object.keys(translators).length>0?{translators}:{}},sortedCards=[...rewritten].sort((a,b)=>a.id<b.id?-1:1),built=assemblePack({author,cards:sortedCards,abilities:{},decks,scenarios,encounterSets,assets}),{unscripted,defects}=splitIssues(validatePack(readPackInput(built.manifest,built.files))),stub=abilitiesStub(sortedCards,mod.name),unscriptedAbilities=[...new Set(sortedCards.flatMap(c=>abilityRefsOf(c)))],extensions={};for(let record2 of nested){let own=Object.fromEntries(Object.entries(record2).filter(([key])=>key.startsWith("x_"))),code=str(record2.code);code!==void 0&&Object.keys(own).length>0&&(extensions[codes.get(code)??code]=own)}let report={...base,normalized:!0,normalizerFailures:[],cards:normalized.cards.length,copies:topCopies,unscriptedAbilities,validationIssues:defects,unscriptedIssues:unscripted,missingImages:pictures.missing,unmatchedImages:pictures.unmatched,languages,altArt:pictures.altArt,...options.outDir?{outDir:options.outDir}:{}};if(!options.outDir)return report;let out=options.outDir;for(let dir of["cards","alt-art","decks","scenarios","encounter-sets"])rmSync(join(out,dir),{recursive:!0,force:!0});writeText(join(out,"pack.json"),jsonText(author));for(let card of sortedCards)writeText(join(out,"cards",`${card.id}.json`),jsonText(card));for(let deck of decks)writeText(join(out,"decks",`${deck.id}.json`),jsonText(deck));for(let set of encounterSets)writeText(join(out,"encounter-sets",`${set.id}.json`),jsonText(set));scenarios.forEach((s,i)=>writeText(join(out,"scenarios",`${str(s.id)??i}.json`),jsonText(s)));for(let{from,to}of pictures.copies)mkdirSync(dirname(join(out,to)),{recursive:!0}),copyFileSync(from,join(out,to));writeText(join(out,"CREDITS.md"),new TextDecoder().decode(assets.get("CREDITS.md"))),writeText(join(out,"PERMISSION.md"),new TextDecoder().decode(assets.get("PERMISSION.md")));let stubPath=join(out,"abilities","index.ts");return existsSync(stubPath)?notes.push("abilities/index.ts already exists and was left alone"):writeText(stubPath,stub.source),Object.keys(extensions).length>0&&writeText(join(out,"extensions.json"),jsonText(extensions)),report}function formatImportReport(report){let lines=[`${report.name} (${report.packId})`];if(!report.normalized){lines.push(` normalizer FAILED (${report.normalizerFailures.length}):`);for(let failure of report.normalizerFailures)lines.push(` - ${failure}`);return lines.join(`
12
+ `)}lines.push(` cards: ${report.cards} (${report.copies} copies)`),lines.push(" normalizer failures: 0");for(let auto of report.autoCurations)lines.push(` auto-curation ${auto.code} -> ${auto.finalCode}: ${auto.what}`);lines.push(` unscripted abilities: ${report.unscriptedAbilities.length}`),lines.push(` validation issues (not counting unscripted abilities): ${report.validationIssues.length}`);for(let issue of report.validationIssues)lines.push(` - ${issue.path}: ${issue.message}`);lines.push(` languages: ${report.languages.available.join(", ")} (base ${report.languages.base})`),lines.push(` missing images: ${report.missingImages.length}, unmatched files: ${report.unmatchedImages.length}`);let altCount=Object.values(report.altArt).reduce((n,byCode)=>n+Object.keys(byCode).length,0);lines.push(` alt art: ${altCount}`);for(let note of report.notes)lines.push(` note: ${note}`);return lines.join(`
13
+ `)}var brand=(_k,v)=>v,traitOf=v=>v.trim().toUpperCase();import{readdirSync as readdirSync2,readFileSync as readFileSync2}from"node:fs";import{fileURLToPath}from"node:url";var CORE_ART_BY_NAME=new Map,ART_BY_CODE=new Map,CORE_ENCOUNTER_SET_CODES=new Set,PRIORITY_ORDER=["core","cap","msm","thor","bkw","drs","hlk","gob","twc"];function recordArt(cards){for(let c of cards){c.imagesrc&&ART_BY_CODE.set(c.code,c.imagesrc);let key=`${c.type_code} ${c.name}`;if(c.imagesrc&&!CORE_ART_BY_NAME.has(key)&&CORE_ART_BY_NAME.set(key,c),c.linked_card){let linkedKey=`${c.linked_card.type_code} ${c.linked_card.name}`;c.linked_card.imagesrc&&!CORE_ART_BY_NAME.has(linkedKey)&&CORE_ART_BY_NAME.set(linkedKey,c.linked_card)}}}try{let rawDir=fileURLToPath(new URL("../../../raw/marvelcdb/",import.meta.url)),allPacks=readdirSync2(rawDir).filter(f=>f.endsWith(".json")).map(f=>f.slice(0,-5)),ordered=[...PRIORITY_ORDER.filter(p=>allPacks.includes(p)),...allPacks.filter(p=>!PRIORITY_ORDER.includes(p)).sort()];for(let pack of ordered){let raw=JSON.parse(readFileSync2(`${rawDir}${pack}.json`,"utf8"));if(recordArt(raw.cards),pack==="core")for(let c of raw.cards)c.faction_code==="encounter"&&c.type_code!=="obligation"&&c.card_set_code&&CORE_ENCOUNTER_SET_CODES.add(c.card_set_code)}}catch{}var imagesOf=(frontSrc,backSrc)=>{let front=imageOf(frontSrc),back=imageOf(backSrc);if(!(!front&&!back))return{...front?{front}:{},...back?{back}:{}}};var imageOf=src=>src?brand("image",src):void 0,RAW_TO_SCHEMA_TYPE={ally:"ally",event:"event",support:"support",upgrade:"upgrade",resource:"resource",player_side_scheme:"player_side_scheme",minion:"minion",attachment:"attachment",treachery:"treachery",obligation:"obligation",environment:"environment",side_scheme:"side_scheme"},reprintImages=r=>{if(!RAW_TO_SCHEMA_TYPE[r.type_code])return;let named=CORE_ART_BY_NAME.get(`${r.type_code} ${r.name}`),src=(r.duplicate_of_code?ART_BY_CODE.get(r.duplicate_of_code):void 0)??(named&&samePrintedStats(r,named)?named.imagesrc:void 0);return src?{front:brand("image",src)}:void 0},PRINTED_STATS=["cost","attack","thwart","defense","recover","health","scheme","boost"],samePrintedStats=(r,original)=>PRINTED_STATS.every(stat=>(r[stat]??null)===(original[stat]??null));function printedFaces(card){switch(card.type){case"hero_identity":return[{what:"the hero face",...card.hero.image?{image:card.hero.image}:{}},{what:"the alter-ego face",...card.alterEgo.image?{image:card.alterEgo.image}:{}},...card.separatedIdentity?[{what:"the hero card's other side",...card.separatedIdentity.heroCardOtherSide.image?{image:card.separatedIdentity.heroCardOtherSide.image}:{}},{what:"the alter-ego card's other side",...card.separatedIdentity.alterEgoCardOtherSide.image?{image:card.separatedIdentity.alterEgoCardOtherSide.image}:{}}]:[]];case"villain":return card.sides.flatMap(side=>side.stages.map(stage=>({what:`side ${side.side} stage ${stage.stageNumber}`,...stage.image?{image:stage.image}:{}})));case"main_scheme":return card.stages.flatMap(stage=>[{what:`stage ${stage.stageNumber}A`,...stage.aSide.image?{image:stage.aSide.image}:{}},{what:`stage ${stage.stageNumber}B`,...stage.image?{image:stage.image}:{}}]);default:return[{what:"the card front",...card.images?.front?{image:card.images.front}:{}}]}}function checkStaleCuration(ctx){let{curation,errors}=ctx;curation.corrections.forEach((c,i)=>{ctx.usedCorrections.has(i)||errors.push(`curation correction for ${c.code} matched no record`)});for(let e of curation.errata)ctx.usedErrata.has(e.code)||errors.push(`curation errata for ${e.code} matched no record`);for(let id of Object.keys(curation.scriptingNotes))ctx.usedNotes.has(id)||errors.push(`scripting note for ${id} matches no emitted ability id`);let cardIds=new Set(ctx.cards.map(c=>c.id));for(let id of Object.keys(curation.cardNotes))cardIds.has(id)||errors.push(`cardNotes entry ${id} matches no card`);for(let code of Object.keys(curation.imageOverrides??{}))ctx.usedImageOverrides.has(code)||errors.push(`curation imageOverride for ${code} matched no face that needed it`);for(let code of ctx.curation.printedBSideSchemeScans??[])ctx.usedPrintedBSideScans.has(code)||errors.push(`curation printedBSideSchemeScans entry ${code} matched no main scheme B side with a scan`)}function checkCoverage(ctx){let{errors}=ctx,dropped=new Set(ctx.dropped.map(d=>d.marvelcdbCode)),allCodes=[...ctx.byCode.keys()].filter(c=>!ctx.isAggregate(c)&&!dropped.has(c)),covered=new Set(ctx.provenance.flatMap(p=>p.marvelcdbCodes));for(let c of allCodes)covered.has(c)||errors.push(`MarvelCDB record ${c} was not turned into any card`);for(let id of Object.keys(ctx.curation.encounterSets??{}))ctx.usedEncounterSetOverrides.has(id)||errors.push(`curation encounterSets entry for ${id} matched no set`);for(let card of ctx.cards){let faces=printedFaces(card),codes=ctx.faceCodesByCardId.get(card.id),codesLineUp=codes!==void 0&&codes.length===faces.length;faces.forEach((face,i)=>{if(face.image)return;let code=codesLineUp?codes[i]:void 0;if((code!==void 0?ctx.curation.artUnavailable?.[code]:void 0)!==void 0){ctx.usedArtUnavailable.add(code);return}if(ctx.curation.artUnavailable?.[card.id]!==void 0){ctx.usedArtUnavailable.add(card.id);return}errors.push(`${card.id}: no artwork reference for ${face.what}`)})}for(let code of Object.keys(ctx.curation.artUnavailable??{}))ctx.usedArtUnavailable.has(code)||errors.push(`curation artUnavailable entry for ${code} matched no face`)}var ICON_CLASS_TO_TOKEN={energy:"[energy]",mental:"[mental]",physical:"[physical]",wild:"[wild]",per_hero:"[per_hero]","per-hero":"[per_hero]",star:"[star]",boost:"[boost]",crisis:"[crisis]",per_group:"[per_group]","per-group":"[per_group]"},ENTITIES={"&amp;":"&","&quot;":'"',"&#039;":"'","&#39;":"'","&apos;":"'","&lt;":"<","&gt;":">","&nbsp;":" "};function toPlainText(html){if(html==null)return"";let s=html.replace(/\r\n?/g,`
14
+ `);return s=s.replace(/<span class="icon-([\w-]+)"[^>]*>\s*<\/span>/g,(_m,icon)=>{let token=ICON_CLASS_TO_TOKEN[icon];if(token===void 0)throw new Error(`Unknown MarvelCDB icon class "${icon}" \u2014 add it to ICON_CLASS_TO_TOKEN`);return token}),s=s.replace(/<br\s*\/?>/gi,`
15
+ `).replace(/<\/p>\s*<p>/gi,`
16
+ `),s=s.replace(/([.)!])(<(?!\/))/g,"$1 $2"),s=s.replace(/<[^>]+>/g,""),s=s.replace(/&[#\w]+;/g,e=>ENTITIES[e]??e),s=s.replace(/\[\[([^\]]+)\]\]/g,"$1"),s=s.replace(/ \u2212 /g," \u2014 "),s.split(`
17
+ `).map(line=>line.replace(/[ \t ]+/g," ").trim()).filter(line=>line.length>0).join(`
18
+ `)}var KNOWN_TEXT_TOKENS=["[energy]","[mental]","[physical]","[wild]","[per_hero]","[star]","[boost]","[crisis]","[per_group]","[amplify]","[hazard]","[acceleration]","[unique]","[cost]","[physics]"];function unknownTokens(text){let known=new Set(KNOWN_TEXT_TOKENS);return(text.match(/\[[a-z_]+\]/g)??[]).filter(t=>!known.has(t))}function parseTraits(raw){if(!raw)return[];let guarded=raw.replace(/(?:[A-Za-z]\.)+[A-Za-z](?=\.)/g,m=>m.replaceAll(".","\uE000")+"\uE001"),out=[];for(let part of guarded.split(".")){let trait=part.trim();trait&&out.push(trait.replace(/\uE001$/,".").replaceAll("\uE000",".").toUpperCase())}return out}function slugify(s){return s.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/['’"“”!?.,]/g,"").replace(/&/g," and ").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}var STRUCTURAL_KINDS=new Set(["setup","boost","preparation","when-revealed","when-revealed-hero","when-revealed-alter-ego","when-defeated","when-completed","obligation"]),TRIGGER=String.raw`(?:(?:Hero |Alter-Ego )?(?:Forced )?(?:Action|Resource|Response|Interrupt)(?: \((?:Hero|Alter-Ego)\))?|Mission Response|Special|Setup|Boost|Preparation|When Revealed\/Defeated|When Revealed/Defeated|When Revealed(?: \((?:Hero|Alter-Ego)\))?|When Defeated|When Completed|Contents)`,HEADER_RE=new RegExp(String.raw`(?:^|(?<=[.)!]\s+)|(?<=\s{2,}))(?:\[star\]\s*)?(${TRIGGER})(?: \((attack|thwart|defense)\))?:`,"g"),QUOTED_HEADER_RE=new RegExp(String.raw`(?:^|(?<=[.)!]\s+)|(?<=\s{2,})|(?<=["'“‘]))(?:\[star\]\s*)?(${TRIGGER})(?: \((attack|thwart|defense)\))?:`,"g"),NAMED_RE=new RegExp(String.raw`^(.+?) — (${TRIGGER})(?: \((attack|thwart|defense)\))?:`);function findHeaders(line,opts){let headers=[],named=NAMED_RE.exec(line);named&&headers.push({index:0,length:named[0].length,trigger:named[2],...named[3]?{label:named[3]}:{},name:named[1].trim()});let headerRe=opts?.allowQuoted?QUOTED_HEADER_RE:HEADER_RE;headerRe.lastIndex=0;for(let m=headerRe.exec(line);m!==null;m=headerRe.exec(line))named&&m.index<named[0].length||headers.push({index:m.index,length:m[0].length,trigger:m[1],...m[2]?{label:m[2]}:{}});return headers.sort((a,b)=>a.index-b.index)}function kindOf(rawTrigger){let suffix=/^((?:Forced )?(?:Action|Resource|Response|Interrupt)) \((Hero|Alter-Ego)\)$/.exec(rawTrigger),trigger=suffix?suffix[1]:rawTrigger,form=suffix?suffix[2]==="Hero"?"hero":"alter-ego":trigger.startsWith("Hero ")?"hero":trigger.startsWith("Alter-Ego ")?"alter-ego":void 0,bare=trigger.replace(/^(Hero|Alter-Ego) /,""),withForm=kind=>form?{kind,form}:{kind};switch(bare){case"Action":return withForm("action");case"Resource":return withForm("resource");case"Response":return withForm("response");case"Interrupt":return withForm("interrupt");case"Forced Action":return withForm("forced-action");case"Forced Response":return withForm("forced-response");case"Mission Response":return{kind:"forced-response"};case"Forced Interrupt":return withForm("forced-interrupt");case"Special":return{kind:"special"};case"Setup":return{kind:"setup"};case"Boost":return{kind:"boost"};case"Preparation":return{kind:"preparation"};case"When Revealed":return{kind:"when-revealed"};case"When Revealed (Hero)":return{kind:"when-revealed-hero"};case"When Revealed (Alter-Ego)":return{kind:"when-revealed-alter-ego"};case"When Defeated":return{kind:"when-defeated"};case"When Completed":return{kind:"when-completed"};case"Contents":return{kind:"contents"};default:throw new Error(`Unhandled trigger "${trigger}"`)}}function splitSentences(text){let out=[],depth=0,start=0;for(let i=0;i<text.length;i++){let ch=text[i];ch==="("?depth++:ch===")"&&(depth=Math.max(0,depth-1));let next=text[i+1];if(!(next===void 0||/\s/.test(next))||depth>0)continue;let isAcronymDot=ch==="."&&/[A-Z]/.test(text[i-1]??"")&&/[.\s]|^$/.test(text[i-2]??"");if((ch==="."||ch==="!")&&!isAcronymDot||ch===")"&&/^\s+[A-Z[(•]/.test(text.slice(i+1))||next===void 0){let s=text.slice(start,i+1).trim();s&&out.push(s),start=i+1}}let rest=text.slice(start).trim();return rest&&out.push(rest),out}var SIMPLE_KEYWORDS={guard:"guard",toughness:"toughness",surge:"surge",quickstrike:"quickstrike",overkill:"overkill",peril:"peril",restricted:"restricted",permanent:"permanent",piercing:"piercing",ranged:"ranged",villainous:"villainous",stalwart:"stalwart",steady:"steady",patrol:"patrol",assault:"assault",temporary:"temporary",vulnerable:"vulnerable",alliance:"alliance",amplify:"amplify",starting:"starting"},RESOURCE_ICON_RE=/\[(energy|mental|physical|wild)\]/g;function parseKeyword(sentence){let form=/^([A-Za-z]+) form\.?$/.exec(sentence);if(form)return{name:"form",formType:form[1].toLowerCase()};let usesPerHero=/^Uses \((\d+)\[per_hero\] ([\w\- ]+?) counters?\)\.?$/.exec(sentence);if(usesPerHero)return{name:"uses",count:0,countPerPlayer:Number(usesPerHero[1]),counterType:usesPerHero[2]};let usesPlusPerHero=/^Uses \((\d+) ([\w\- ]+?) counters?, plus (\d+)\[per_hero\] additional [\w\- ]+? counters?\)\.?$/.exec(sentence);if(usesPlusPerHero)return{name:"uses",count:Number(usesPlusPerHero[1]),countPerPlayer:Number(usesPlusPerHero[3]),counterType:usesPlusPerHero[2]};let uses=/^Uses \((\d+) ([\w\- ]+?) counters?\)\.?$/.exec(sentence);if(uses)return{name:"uses",count:Number(uses[1]),counterType:uses[2]};let teamUp=/^Team-Up \((.+?) and (.+)\)\.?$/.exec(sentence);if(teamUp)return{name:"teamUp",names:[teamUp[1].trim(),teamUp[2].trim()]};let teamwork=/^Teamwork \((.+)\)\.?$/.exec(sentence);if(teamwork)return{name:"teamwork",sharedTrait:teamwork[1].trim().toUpperCase()};let linked=/^Linked(?: \((.+)\))?\.?$/.exec(sentence);if(linked){if(linked[1]===void 0)return{name:"linked"};let typed=/^(.+?) (minion|upgrade|ally|support|event|attachment)$/.exec(linked[1].trim());return typed?{name:"linked",cardTitle:typed[1],cardType:typed[2]}:{name:"linked",cardTitle:linked[1].trim()}}let requirement=/^Requirement \(((?:\[(?:energy|mental|physical|wild)\]\s*)+)\)\.?$/.exec(sentence);if(requirement){let icons=[...requirement[1].matchAll(RESOURCE_ICON_RE)].map(mm=>mm[1]);if(icons.length===1)return{name:"requirement",icon:icons[0]};let resources={};for(let icon of icons)resources[icon]=(resources[icon]??0)+1;return{name:"requirement",resources}}let discount=/^Discount (\d+) \((.+)\)\.?$/.exec(sentence);if(discount){let traits=discount[2].split(/\s+or\s+/).map(t=>t.trim().toUpperCase());return{name:"discount",value:Number(discount[1]),traits}}let prerequisite=/^Prerequisite \((.+)\)\.?$/.exec(sentence);if(prerequisite){let inner=prerequisite[1].trim(),formMatch=/^(hero|alter-ego) form$/i.exec(inner);return formMatch?{name:"prerequisite",form:formMatch[1].toLowerCase()==="hero"?"hero":"alterEgo"}:{name:"prerequisite",traits:inner.split(/\s+or\s+/).map(t=>t.trim().toUpperCase())}}let s=sentence.replace(/\s*\([^)]*\)\.?$/,"").replace(/\.$/,"").trim(),simple=SIMPLE_KEYWORDS[s.toLowerCase()];if(simple)return{name:simple};if(s==="Setup"&&/^Setup\.?$/.test(sentence))return{name:"setup"};let hinderPerHero=/^Hinder (\d+)\[per_hero\]$/.exec(s);if(hinderPerHero)return{name:"hinder",value:0,perPlayer:Number(hinderPerHero[1])};let m=/^(Retaliate|Incite|Hinder) (\d+)$|^(Victory) (-?\d+)$/.exec(s);if(m){let name=(m[1]??m[3]).toLowerCase(),value=Number(m[2]??m[4]);return{name,value}}}var ATTACH_CLAUSE_VERB=/\band (?:heal|give|move|change|exhaust|stun|confuse|ready|deal|discard|place|remove|add|draw|flip|take|put|set)\b/;function parseAttach(sentence,villainNames,multiVillain,titles){let s=sentence.replace(/\.$/,""),m=/^Attach to (.+)$/.exec(s);if(!m)return;let target=m[1];if(titles)for(let dot of target.matchAll(/\. (?=[A-Z])/g)){let head=target.slice(0,dot.index);if(titles.has(head)||titles.has(`${head}.`)){target=head;break}}if(ATTACH_CLAUSE_VERB.test(target))return;let simple={"a minion":{kind:"minion"},"a minion of the enemy team's choice":{kind:"minion"},"an enemy":{kind:"enemy"},"an ally":{kind:"ally"},"a hero":{kind:"hero"},"a character":{kind:"anyCharacter"},"the villain":{kind:"villain"},"the main scheme":{kind:"mainScheme"},"a side scheme":{kind:"sideScheme"},"a scheme":{kind:"scheme"},"your identity card":{kind:"yourIdentity"},"your identity":{kind:"yourIdentity"},"your hero":{kind:"yourIdentity",form:"hero"},"your alter-ego":{kind:"yourIdentity",form:"alterEgo"},"a friendly character":{kind:"friendlyCharacter"},"the active villain's side scheme":{kind:"villainSideScheme",of:"activeVillain"},"the enemy leader":{kind:"leader",of:"enemy"},"your leader":{kind:"leader",of:"yours"},"the villain who is not the active villain":{kind:"nonActiveVillain"},"an encounter card in play":{kind:"encounterCard"},"a card":{kind:"anyCard"}},hit=simple[target.toLowerCase()];if(hit)return{host:hit};let identityWithout=/^your identity if a copy of (.+) is not attached to you$/.exec(target);if(identityWithout)return{host:{kind:"yourIdentity",withoutAttachmentNamed:identityWithout[1]}};if(/^your .+ leader$/i.test(target))return{host:{kind:"leader",of:"yours"}};if(/^an? ally you control$/i.test(target))return{host:{kind:"ally"}};let classified=/^(?:an?|the) (identity-specific|aspect|basic) (ally|character|friendly character)( you control)?$/i.exec(target);if(classified){let word=classified[1].toLowerCase(),categoryWord=classified[2].toLowerCase();return{host:{kind:"qualified",category:categoryWord==="friendly character"?"friendlyCharacter":categoryWord,classification:word==="identity-specific"?"identitySpecific":word,...classified[3]?{controlledBy:"you"}:{}}}}let namedVillainSuffix=/^the (.+) villain$/i.exec(target);if(namedVillainSuffix){let name=namedVillainSuffix[1];if(villainNames.has(name))return multiVillain?{host:{kind:"namedVillain",name},villainName:name}:{host:{kind:"villain"},villainName:name}}let orParts=target.split(/\s+or\s+/i);if(orParts.length===2){let sharedCategory=/^(?:an?|the) (.+?) or (.+?) (ally|minion|enemy|character|friendly character)$/i.exec(target);if(sharedCategory){let categoryWord=sharedCategory[3].toLowerCase(),category=categoryWord==="friendly character"?"friendlyCharacter":categoryWord,h12={kind:"qualified",category,trait:sharedCategory[1].trim().toUpperCase()},h22={kind:"qualified",category,trait:sharedCategory[2].trim().toUpperCase()};return{host:{kind:"anyOf",hosts:[h12,h22]}}}let resolveHalf=part=>{let p=part.trim(),bySimple=simple[p.toLowerCase()]??simple[`a ${p.toLowerCase()}`]??simple[`an ${p.toLowerCase()}`];if(bySimple)return bySimple;if(/^[A-Z]/.test(p)&&!/^(?:a|an|the|your)\b/.test(p))return{kind:"namedCard",name:p}},h1=resolveHalf(orParts[0]),h2=resolveHalf(orParts[1]);if(h1&&h2)return{host:{kind:"anyOf",hosts:[h1,h2]}}}if(villainNames.has(target))return multiVillain?{host:{kind:"namedVillain",name:target},villainName:target}:{host:{kind:"villain"},villainName:target};let shortNameOf=name=>name.replace(/\s*\([^)]*\)\s*$/,"").trim();if(!multiVillain){let villainShortMatch=[...villainNames].find(name=>shortNameOf(name)===target);if(villainShortMatch)return{host:{kind:"villain"},villainName:villainShortMatch}}let highest=/^the minion with the highest printed hit points(?: and without another (.+) attached)?$/.exec(target);if(highest)return{host:highest[1]?{kind:"minionWithHighestPrintedHp",withoutAttachmentNamed:highest[1]}:{kind:"minionWithHighestPrintedHp"}};let superlativeEnemyHp=/^the enemy with the highest printed hit points(?: and without another (.+) attached)?$/.exec(target);if(superlativeEnemyHp)return{host:{kind:"superlative",among:"enemy",order:"highest",measure:"printedHp",...superlativeEnemyHp[1]?{withoutAttachmentNamed:superlativeEnemyHp[1]}:{}}};let CATEGORY_NOUN="ally|minion|enemy|character|friendly character|side scheme|villain",bareWithout=new RegExp(`^(?:an?|the) (${CATEGORY_NOUN})\\s+(?:and\\s+)?without (?:a copy of |another copy of |another )?(.+?) attached$`,"i").exec(target);if(bareWithout){let categoryWord=bareWithout[1].toLowerCase();return{host:{kind:"qualified",category:categoryWord==="friendly character"?"friendlyCharacter":categoryWord==="side scheme"?"sideScheme":categoryWord,withoutAttachmentNamed:bareWithout[2].trim()}}}let qualified=new RegExp(`^(?:an?|the) (non-)?(.+?) (${CATEGORY_NOUN})(?:\\s+(?:and\\s+)?without (?:a copy of |another copy of |another )?(.+?) attached)?$`,"i").exec(target);if(qualified){let negated=!!qualified[1],word=qualified[2].trim(),categoryWord=qualified[3].toLowerCase(),category=categoryWord==="friendly character"?"friendlyCharacter":categoryWord==="side scheme"?"sideScheme":categoryWord,withoutAttachmentNamed=qualified[4]?.trim(),keywordName=SIMPLE_KEYWORDS[word.toLowerCase()];return{host:{kind:"qualified",category,...keywordName?negated?{withoutKeyword:keywordName}:{keyword:keywordName}:negated?{withoutTrait:word.toUpperCase()}:{trait:word.toUpperCase()},...withoutAttachmentNamed?{withoutAttachmentNamed}:{}}}}let titleContains=/^a character with "(.+)" in its title$/i.exec(target);if(titleContains)return{host:{kind:"qualified",category:"character",titleContains:titleContains[1]}};let attackedThisTurn=/^an enemy that (.+) attacked this turn$/i.exec(target);if(attackedThisTurn)return{host:{kind:"qualified",category:"enemy",attackedThisTurnBy:attackedThisTurn[1].split(/\s+or\s+/).map(n=>n.trim())}};let supRest=target,supWithoutAttachmentNamed,supWithoutTrait,supWithoutAttachmentTrait,traitAttachmentSuffix=/^(.*?)\s+(?:and\s+)?without an? ([A-Z][A-Za-z-]*) attachment$/.exec(supRest),namedSuffix=/^(.*?)\s+(?:and\s+)?without (?:a copy of |another copy of |another )?(.+?) attached$/i.exec(supRest);if(traitAttachmentSuffix)supRest=traitAttachmentSuffix[1],supWithoutAttachmentTrait=traitAttachmentSuffix[2];else if(namedSuffix)supRest=namedSuffix[1],supWithoutAttachmentNamed=namedSuffix[2].trim();else{let traitSuffix=/^(.*?)\s+(?:and\s+)?without the (.+?) trait$/i.exec(supRest);traitSuffix&&(supRest=traitSuffix[1],supWithoutTrait=traitSuffix[2].trim())}let supCore=/^(?:the|a) (?:([A-Za-z-]+) )?(minion|enemy|villain|friendly character|ally) with the (highest|lowest|most|fewest) (.+)$/i.exec(supRest);if(supCore){let supTrait=supCore[1],poolWord=supCore[2].toLowerCase(),among=poolWord==="friendly character"?"friendlyCharacter":poolWord,orderWord=supCore[3].toLowerCase(),order=orderWord==="highest"||orderWord==="most"?"highest":"lowest",descriptor=supCore[4].trim().toLowerCase(),measure=descriptor==="printed hit points"||descriptor==="base hit points"?"printedHp":descriptor==="hit points"||descriptor==="remaining hit points"?"remainingHp":descriptor==="printed atk"?"printedAtk":descriptor==="atk"?"atk":descriptor==="sch"?"sch":descriptor==="thw"?"thw":descriptor==="activation order value"?"activationOrder":descriptor==="traits"?"traitCount":descriptor==="cost"?"printedCost":void 0;if(measure)return{host:{kind:"superlative",among,order,measure,...supTrait?{trait:supTrait.toUpperCase()}:{},...supWithoutTrait?{withoutTrait:supWithoutTrait.toUpperCase()}:{},...supWithoutAttachmentNamed?{withoutAttachmentNamed:supWithoutAttachmentNamed}:{},...supWithoutAttachmentTrait?{withoutAttachmentTrait:supWithoutAttachmentTrait.toUpperCase()}:{}}}}let named=/^the (.+) (?:environment|side scheme|support|upgrade)$/.exec(target);if(named)return{host:{kind:"namedCard",name:named[1]}};if(/^[A-Z]/.test(target)&&!/^(?:a|an|the|your)\b/.test(target))return{host:{kind:"namedCard",name:titles&&!titles.has(target)&&titles.has(`${target}.`)?`${target}.`:target}}}function parseRestriction(sentence,into){let m=/^Max (\d+) per deck\.?$/.exec(sentence);if(m)return{maxPerDeck:Number(m[1])};if(m=/^Max (\d+) per player\.?$/.exec(sentence),m)return into.maxPerPlayer=Number(m[1]),{};if(m=/^Max (\d+) per round\.?$/.exec(sentence),m)return into.maxPerRound=Number(m[1]),{};if(m=/^Max (\d+) per phase\.?$/.exec(sentence),m)return into.maxPerPhase=Number(m[1]),{};if(m=/^(?:Max|Limit) (\d+) per (?:enemy|ally|minion|character|hero|encounter card|side scheme|scheme)\.?$/.exec(sentence),m)return into.maxPerHost=Number(m[1]),{};if(m=/^Max (\d+) ([A-Za-z-]+) upgrade per (?:enemy|ally|minion|character|hero)\.?$/.exec(sentence),m)return into.maxWithTrait={trait:m[2].toUpperCase(),per:"host",max:Number(m[1])},{};if(m=/^Max (\d+) ([A-Za-z-]+) cards? per player\.?$/.exec(sentence),m)return into.maxWithTrait={trait:m[2].toUpperCase(),per:"player",max:Number(m[1])},{};if(/^Hero form only\.?$/.test(sentence))return into.form="hero",{};if(/^Alter-Ego form only\.?$/.test(sentence))return into.form="alterEgo",{};if(/^Play under any player's control\.$/.test(sentence))return into.anyPlayerControl=!0,{};if(m=/^Play only if your identity has the (.+) trait\.$/.exec(sentence),m&&!/ (?:or|and) /.test(m[1]))return into.requiresIdentityTrait=m[1],{};if(m=/^Play only if you have the (.+) trait\.$/.exec(sentence),m&&!/ (?:or|and) /.test(m[1]))return into.requiresIdentityTrait=m[1],{};if(m=/^Play only if you are in (.+) hero form\.$/.exec(sentence),m)return into.form="hero",into.requiresIdentityTrait=m[1],{};if(m=/^Play only if you control an? (.+) character\.$/.exec(sentence),m)return into.requiresControlledCharacterTrait=m[1],{}}var STAGE_LOSS_REMINDER=/^If this (?:stage|scheme) is completed, the players lose the game\.?$/,STAGE_LOSS_COMPOUND_HALF=/\b(?:if|or) this (?:stage|scheme) is completed\b/i,STAGE_LOSS_COMPOUND_TAIL=/the players lose the game\.?$/i;function parseCardText(text,options){let keywords=[],abilities=[],restrictions={},unclassified=[],attachesTo,attachesToVillainNamed,maxPerDeckText,restrictedWeight,nemesisMinion,signatureOf,villainOf,modeOnly,completionLoses,extraConstantFound=0;if(options.obligation){let lines2=text.split(`
19
+ `),allHeaders=lines2.flatMap(oline=>findHeaders(oline,{allowQuoted:!0}).map(h2=>({...h2,oline}))),preambleLines=[];for(let oline of lines2){if(findHeaders(oline,{allowQuoted:!0}).length>0)break;oline.trim()&&preambleLines.push(oline.trim())}for(let pline of preambleLines)for(let sentence of splitSentences(pline)){let keyword=parseKeyword(sentence);keyword&&keywords.push(keyword)}let[h]=allHeaders;if(preambleLines.length>0&&allHeaders.length===1&&h){let{kind:hkind,form}=kindOf(h.trigger);if(hkind!=="contents"){let unheaded=options.unheadedWhenRevealed,constantText=preambleLines.join(" ");if(unheaded!==void 0){let count=constantText.split(unheaded).length-1;count!==1?unclassified.push(`unheaded When Revealed sentence "${unheaded}" found ${count} times (expected 1)`):(abilities.push({kind:"when-revealed",text:unheaded,cardQualifiedId:!0}),constantText=constantText.replace(unheaded,"").replace(/\s+/g," ").trim())}return abilities.push({kind:"constant",text:constantText}),abilities.push({kind:hkind,...form?{form}:{},...h.label?{label:h.label}:{},...h.name?{name:h.name}:{},text:h.oline.slice(h.index).trim()}),{keywords,abilities,restrictions,unclassified}}}if(text.trim()&&abilities.push({kind:"obligation",text}),allHeaders.length>=2)for(let oline of lines2){let oheaders=findHeaders(oline,{allowQuoted:!0});oheaders.forEach((h2,i)=>{let oend=oheaders[i+1]?.index??oline.length,obody=oline.slice(h2.index,oend).trim(),{kind:hkind,form}=kindOf(h2.trigger);hkind!=="contents"&&abilities.push({kind:hkind,...form?{form}:{},...h2.label?{label:h2.label}:{},...h2.name?{name:h2.name}:{},text:obody})})}return{keywords,abilities,restrictions,unclassified}}let lines=[],leadIn="";for(let raw of text.split(`
20
+ `)){if(leadIn===""&&/^If [^.]+:$/.test(raw)&&findHeaders(raw).length===0){leadIn=raw;continue}lines.push(leadIn===""?raw:`${leadIn} ${raw}`),leadIn=""}leadIn!==""&&lines.push(leadIn);let isListLine=l=>l.startsWith("\u2022")||/^\[[a-z_]+\]\s+[—–-]\s/.test(l);for(let i=lines.length-1;i>0;i--){if(!isListLine(lines[i]))continue;let j=i;for(;j>0&&isListLine(lines[j-1]);)j--;let owner=lines[j-1],twoLabelAction=/^(?:Hero |Alter-Ego )?Action \((?:attack|thwart|defense)\/(?:attack|thwart|defense)\)/.test(owner);j===0||!owner.endsWith(":")||findHeaders(owner).length===0&&!twoLabelAction||(lines.splice(j-1,i-j+2,[owner,...lines.slice(j,i+1)].join(" ")),i=j-1)}let preambleWhenRevealedFound=0,labelSentencesFound=new Set;for(let line of lines){let headers=findHeaders(line),preamble=line.slice(0,headers[0]?.index??line.length).trim(),constantBuffer=[],flushConstant=()=>{constantBuffer.length>0&&abilities.push({kind:"constant",text:constantBuffer.join(" ")}),constantBuffer=[]},sentences=splitSentences(preamble);for(let sentenceIndex=0;sentenceIndex<sentences.length;sentenceIndex++){let sentence=sentences[sentenceIndex].replace(/^\[star\]\s*/,"");if(sentence.startsWith("Attach to ")){let next=sentences[sentenceIndex+1],continuation=next?/^(?:Otherwise|If you cannot),?\s*(.+)$/i.exec(next):null,otherwiseAttach=continuation?/^attach to (.+)$/i.exec(continuation[1]):null;if(continuation&&otherwiseAttach){flushConstant();let preferredSentence=sentence.replace(/,\s*if able\.?$/i,"."),preferred=parseAttach(preferredSentence,options.villainNames,options.multipleVillains??!1,options.titles),otherwise=parseAttach(`Attach to ${otherwiseAttach[1]}`,options.villainNames,options.multipleVillains??!1,options.titles);if(preferred&&otherwise){attachesTo&&unclassified.push(`second attach rule: ${sentence}`);let namedNotVillain=preferred.villainName!==void 0&&otherwise.host.kind==="villain"&&(preferred.host.kind==="villain"||preferred.host.kind==="namedVillain");attachesTo={kind:"ifAble",preferred:namedNotVillain?{kind:"namedCard",name:preferred.villainName}:preferred.host,otherwise:otherwise.host},preferred.villainName&&!namedNotVillain&&(attachesToVillainNamed=preferred.villainName)}else unclassified.push(`ifAble attach host: could not parse ${preferred?"the fallback":"the preferred"} side: "${sentence}" / "${next}"`);sentenceIndex++;continue}}if(options.labelSentences?.includes(sentence)){flushConstant(),labelSentencesFound.add(sentence);continue}let keyword=parseKeyword(sentence);if(keyword){flushConstant(),keywords.push(keyword);continue}if(options.preambleWhenRevealed!==void 0&&sentence===options.preambleWhenRevealed){flushConstant(),abilities.push({kind:"when-revealed",text:sentence}),preambleWhenRevealedFound++;continue}let modeOnlyMatch=/^(Standard|Expert) Mode Only\.?$/.exec(sentence);if(modeOnlyMatch){modeOnly=modeOnlyMatch[1].toLowerCase();continue}if(/^\(.+ nemesis minion\.\)$/i.test(sentence)){nemesisMinion=!0;continue}if(/^\(.*\)\.?$/.test(sentence))continue;if(STAGE_LOSS_REMINDER.test(sentence)){completionLoses=!0;continue}STAGE_LOSS_COMPOUND_HALF.test(sentence)&&STAGE_LOSS_COMPOUND_TAIL.test(sentence)&&(completionLoses=!0);let weight=/^Counts as (\d+) restricted cards\.?$/.exec(sentence);if(weight){flushConstant(),restrictedWeight=Number(weight[1]);continue}let restriction=parseRestriction(sentence,restrictions);if(restriction){flushConstant(),restriction.maxPerDeck!==void 0&&(maxPerDeckText=restriction.maxPerDeck);continue}let attach=parseAttach(sentence,options.villainNames,options.multipleVillains??!1,options.titles);if(attach){flushConstant(),attachesTo&&unclassified.push(`second attach rule: ${sentence}`),attachesTo=attach.host,attach.villainName&&(attachesToVillainNamed=attach.villainName);continue}if(sentence.startsWith("Attach to ")){let clauseSplit=/^(Attach to .+?) and ((?:exhaust it|give it a tough status card)|(?:heal|give|move|change|exhaust|stun|confuse|ready|deal|discard|place|remove|add|draw|flip|take|put|set) .+?)\.?$/i.exec(sentence);if(clauseSplit){let hostOnly=parseAttach(`${clauseSplit[1]}.`,options.villainNames,options.multipleVillains??!1,options.titles);if(hostOnly){flushConstant(),attachesTo&&unclassified.push(`second attach rule: ${sentence}`),attachesTo=hostOnly.host,hostOnly.villainName&&(attachesToVillainNamed=hostOnly.villainName);let clause=`${clauseSplit[2][0]?.toUpperCase()}${clauseSplit[2].slice(1)}.`;options.preambleWhenRevealed!==void 0&&clause===options.preambleWhenRevealed?(abilities.push({kind:"when-revealed",text:clause}),preambleWhenRevealedFound++):constantBuffer.push(clause);continue}}}if(sentence.startsWith("Attach to ")){unclassified.push(`unrecognized attach rule: ${sentence}`);continue}let signature=/^(.+)'s Side Scheme\.$/.exec(sentence);signature&&(signatureOf=signature[1]);let villainScheme=/^(.+)'s Scheme\.$/.exec(sentence);villainScheme&&(villainOf=villainScheme[1]),constantBuffer.push(sentence);let grantedText=/gains the text:\s*"(.+)"\.?$/.exec(sentence);if(grantedText){let embedded=grantedText[1],embeddedHeaders=findHeaders(embedded);embeddedHeaders.forEach((h,i)=>{let end=embeddedHeaders[i+1]?.index??embedded.length,{kind:hkind,form}=kindOf(h.trigger);hkind!=="contents"&&abilities.push({kind:hkind,...form?{form}:{},...h.label?{label:h.label}:{},...h.name?{name:h.name}:{},text:embedded.slice(h.index,end).trim()})})}}flushConstant(),headers.forEach((h,i)=>{let end=headers[i+1]?.index??line.length,body=line.slice(h.index,end).trim();if(h.trigger==="When Revealed/Defeated"){abilities.push({kind:"when-revealed",text:body},{kind:"when-defeated",text:body});return}let{kind,form}=kindOf(h.trigger);if(kind!=="contents"){if(!attachesTo&&kind!=="action"){let firstSentence=splitSentences(body.slice(h.length).trim())[0];if(firstSentence){let bodyAttach=parseAttach(firstSentence,options.villainNames,options.multipleVillains??!1,options.titles);if(bodyAttach)attachesTo=bodyAttach.host,bodyAttach.villainName&&(attachesToVillainNamed=bodyAttach.villainName);else{let midSentence=/\bto attach this card to (.+?)\.?$/i.exec(firstSentence.replace(/\.$/,""));if(midSentence){let synthetic=parseAttach(`Attach to ${midSentence[1]}.`,options.villainNames,options.multipleVillains??!1,options.titles);synthetic&&(attachesTo=synthetic.host,synthetic.villainName&&(attachesToVillainNamed=synthetic.villainName))}}}}if(abilities.push({kind,...form?{form}:{},...h.label?{label:h.label}:{},...h.name?{name:h.name}:{},text:body}),kind!=="when-defeated"){let bodySentences=splitSentences(body),inlineDefeatedIndex=bodySentences.findIndex(s=>/^When (?:this scheme|this card|this attachment|it) is defeated,/i.test(s));inlineDefeatedIndex!==-1&&abilities.push({kind:"when-defeated",text:bodySentences.slice(inlineDefeatedIndex).join(" ")})}if(options.extraConstantFrom!==void 0){let bodySentences=splitSentences(body),from=bodySentences.findIndex(s=>s===options.extraConstantFrom);from!==-1&&(extraConstantFound++,abilities.push({kind:"constant",text:bodySentences.slice(from).join(" ")}))}}})}for(let label of options.labelSentences??[])labelSentencesFound.has(label)||unclassified.push(`label sentence "${label}" not found as a sentence of the text`);return options.preambleWhenRevealed!==void 0&&preambleWhenRevealedFound!==1&&unclassified.push(`preamble When Revealed sentence "${options.preambleWhenRevealed}" found ${preambleWhenRevealedFound} times (expected 1)`),options.extraConstantFrom!==void 0&&extraConstantFound!==1&&unclassified.push(`extra constant sentence "${options.extraConstantFrom}" found in ${extraConstantFound} ability bodies (expected 1)`),{keywords,abilities,restrictions,...maxPerDeckText!==void 0?{maxPerDeckText}:{},...restrictedWeight!==void 0?{restrictedWeight}:{},...attachesTo?{attachesTo}:{},...attachesToVillainNamed?{attachesToVillainNamed}:{},...nemesisMinion?{nemesisMinion}:{},...signatureOf?{signatureOf}:{},...villainOf?{villainOf}:{},...modeOnly?{modeOnly}:{},...completionLoses?{completionLoses}:{},unclassified}}function assignAbilityIds(cardCode,cardName,abilities,used){let cardSlug=slugify(cardName),out=[];for(let ability of abilities){let candidates=[];ability.name?candidates.push(slugify(ability.name)):ability.cardQualifiedId?candidates.push(`${cardSlug}-${ability.kind}`):STRUCTURAL_KINDS.has(ability.kind)?candidates.push(ability.kind):(candidates.push(`${cardSlug}-${ability.kind}`),ability.form&&candidates.push(`${cardSlug}-${ability.form}-${ability.kind}`));let id=candidates.map(c=>`${cardCode}.${c}`).find(c=>!used.has(c));if(id===void 0){let base=`${cardCode}.${candidates[candidates.length-1]}`,n=2;for(;used.has(`${base}-${n}`);)n++;id=`${base}-${n}`}used.add(id),out.push({id,ability})}return out}function applyTypeCorrections(raw,corrections,errors){let typed=corrections.filter(c=>c.cardType!==void 0);if(typed.length===0)return raw;let fix=r=>{let out=r;for(let c of typed)c.code===r.code&&(c.cardType===r.type_code?errors.push(`${r.code}: type correction to ${c.cardType} matches MarvelCDB already`):out={...out,type_code:c.cardType});return out};return raw.map(r=>{let top=fix(r);return r.linked_card?{...top,linked_card:fix(r.linked_card)}:top})}function applySetRecodes(raw,curation,errors){let recodes=curation.setRecodes??[];if(recodes.length===0)return raw;let target=new Map;for(let rc of recodes)for(let code of rc.codes){let rec=raw.find(r=>r.code===code);rec?rec.card_set_code===rc.setCode?errors.push(`set recode of ${code}: already in set ${rc.setCode}`):target.has(code)?errors.push(`set recode of ${code}: listed twice`):target.set(code,{setCode:rc.setCode,setName:rc.setName}):errors.push(`set recode of ${code}: no such top-level record`)}let move=(r,to)=>({...r,card_set_code:to.setCode,card_set_name:to.setName});return raw.map(r=>{let to=target.get(r.code);if(!to)return r;let top=move(r,to);return r.linked_card?{...top,linked_card:move(r.linked_card,to)}:top})}function applyAddedRecords(raw,curation,errors){let added=curation.addedRecords??[],overrides=curation.linkOverrides??[];if(added.length===0&&overrides.length===0)return raw;let known=new Set;for(let r of raw)known.add(r.code),r.linked_card&&known.add(r.linked_card.code);let addedByCode=new Map;for(let a of added){let code=a.record.code;if(known.has(code)||addedByCode.has(code)){errors.push(`added record ${code}: MarvelCDB already has a record with this code`);continue}addedByCode.set(code,a.record)}let nested=new Set,linkedTo=new Map;for(let o of overrides){let front=raw.find(r=>r.code===o.front);if(!front){errors.push(`link override ${o.front} -> ${o.back}: front record ${o.front} is missing`);continue}let target=addedByCode.get(o.back)??raw.flatMap(r=>r.linked_card?[r.linked_card]:[]).find(c=>c.code===o.back)??raw.find(r=>r.code===o.back);if(!target){errors.push(`link override ${o.front} -> ${o.back}: target record ${o.back} is missing`);continue}if(front.linked_card?.code===o.back){errors.push(`link override ${o.front} -> ${o.back}: MarvelCDB already links ${o.front} to ${o.back}`);continue}linkedTo.set(o.front,target),addedByCode.has(o.back)&&nested.add(o.back)}let out=raw.map(r=>{let target=linkedTo.get(r.code);return target?{...r,linked_to_code:target.code,linked_card:target}:r});for(let[code,record2]of addedByCode)nested.has(code)||out.push(record2);return out}function flatten(raw,errors){let byCode=new Map;for(let r of raw)byCode.has(r.code)&&errors.push(`duplicate MarvelCDB code ${r.code}`),byCode.set(r.code,r),r.linked_card&&byCode.set(r.linked_card.code,r.linked_card);let dropped=[],isAggregate=code=>/\d$/.test(code)&&byCode.has(`${code}a`),aggregateImage=aSideCode=>imageOf(byCode.get(aSideCode.replace(/a$/,""))?.imagesrc),topLevel=[];for(let r of raw){if(!isAggregate(r.code)){topLevel.push(r);continue}let variants=[...byCode.values()].filter(v=>new RegExp(`^${r.code}[a-z]$`).test(v.code));if(r.type_code==="main_scheme"){let b=byCode.get(`${r.code}b`),sameOrBothAbsent=(x,y)=>(x??null)===(y??null);(!b||!sameOrBothAbsent(b.threat,r.threat)||!sameOrBothAbsent(b.escalation_threat,r.escalation_threat))&&errors.push(`aggregate ${r.code} does not match its B side \u2014 inspect before dropping`),dropped.push({marvelcdbCode:r.code,reason:`MarvelCDB aggregate record duplicating main scheme stage ${r.code}a/${r.code}b.`})}else{let doubleSidedFace=variants.length===2?variants.find(v=>variants.some(o=>o.code===v.linked_card?.code)):void 0,sum=doubleSidedFace?doubleSidedFace.quantity:variants.reduce((n,v)=>n+v.quantity,0);sum!==r.quantity&&errors.push(`aggregate ${r.code} quantity ${r.quantity} != variants' total ${sum}`),dropped.push({marvelcdbCode:r.code,reason:doubleSidedFace?`MarvelCDB aggregate record duplicating the double-sided card ${r.code}a/${r.code}b (quantity ${r.quantity} = one physical card, not both faces summed).`:`MarvelCDB aggregate record for the printed variants ${variants.map(v=>v.code).join(", ")} (quantity ${r.quantity} = their total).`})}}return{byCode,topLevel,dropped,isAggregate,aggregateImage}}var ROMAN={I:1,II:2,III:3,IV:4,V:5},CORE_ASPECTS=["aggression","justice","leadership","protection","basic","pool"],PLAYER_TYPES=new Set(["ally","event","support","upgrade","resource","player_side_scheme"]),scalingOf=(value,perPlayer,perGroup=!1)=>perGroup?{base:0,perPlayer:0,perGroup:value}:perPlayer?{base:0,perPlayer:value}:{base:value,perPlayer:0},stripQuotes=s=>s.replace(/^["“](.*)["”]$/,"$1");function collector(codes){return codes.map(c=>c.slice(2).replace(/^0+/,"").toUpperCase()).join("/")}function resourceIcons(r){let out={};return r.resource_energy&&(out.energy=r.resource_energy),r.resource_mental&&(out.mental=r.resource_mental),r.resource_physical&&(out.physical=r.resource_physical),r.resource_wild&&(out.wild=r.resource_wild),out}function printedStat(value){return value==null?null:value===-1?"X":value}function schemeIcons(r){let icons=[];for(let i=0;i<(r.scheme_crisis??0);i++)icons.push("crisis");for(let i=0;i<(r.scheme_acceleration??0);i++)icons.push("acceleration");for(let i=0;i<(r.scheme_hazard??0);i++)icons.push("hazard");return icons}var SCHEME_ICON_HOLDERS=new Set(["obligation","ally","environment","attachment","upgrade","player_side_scheme","minion"]);function schemeIconsField(r){if(!SCHEME_ICON_HOLDERS.has(r.type_code))return{};let icons=schemeIcons(r);return icons.length>0?{schemeIcons:icons}:{}}function faceSchemeIconsField(r){let icons=schemeIcons(r);return icons.length>0?{schemeIcons:icons}:{}}var STAR_FIELDS=[["atk","attack_star"],["sch","scheme_star"],["thw","thwart_star"],["def","defense_star"],["hp","health_star"],["rec","recover_star"]];function statStarsField(r){let stars=STAR_FIELDS.filter(([,key])=>r[key]===!0).map(([stat])=>stat);return stars.length>0?{statStars:stars}:{}}function amplifyIconsField(r){return r.scheme_amplify?{amplifyIcons:r.scheme_amplify}:{}}function errataStatus(e){return{currentVersion:e.version,history:[{version:e.version,changedFields:[...e.changedFields],note:e.note}]}}function createContext(raw,curation){let errors=[],flat=flatten(applySetRecodes(applyTypeCorrections(applyAddedRecords(raw,curation,errors),curation.corrections,errors),curation,errors),errors),heroBySet=new Map;for(let r of flat.topLevel)r.type_code!=="hero"||!r.card_set_code||(r.linked_card?.type_code==="alter_ego"||curation.separatedIdentities?.[r.code])&&(heroBySet.has(r.card_set_code)||heroBySet.set(r.card_set_code,r));for(let[auxSet,primarySet]of Object.entries(curation.auxiliaryHeroSetCodes??{})){let hero=heroBySet.get(primarySet);hero&&heroBySet.set(auxSet,hero)}let handled=new Set;for(let ignored of curation.ignoredRecords??[])handled.add(ignored.code),flat.dropped.push({marvelcdbCode:ignored.code,reason:`${ignored.reason} [evidence: ${ignored.evidence}]`});return{...flat,curation,errors,setCode:brand("set",curation.packCode),cycleId:brand("cycle",curation.cycle.id),villainNames:new Set(flat.topLevel.filter(r=>r.type_code==="villain"||r.type_code==="leader").map(r=>r.name)),titles:new Set(flat.topLevel.map(r=>r.name)),packHasMultipleVillains:curation.scenarios.some(s=>s.multipleVillains!==void 0),heroBySet,cards:[],provenance:[],handled,prepared:new Map,usedCorrections:new Set,usedErrata:new Set,usedNotes:new Set,usedAbilityIds:new Set,usedImageOverrides:new Set,usedPrintedBSideScans:new Set,usedEncounterSetOverrides:new Set,usedArtUnavailable:new Set,faceCodesByCardId:new Map}}function imageOfWithOverride(ctx,code,src){let own=imageOf(src);if(own)return own;let override=ctx.curation.imageOverrides?.[code];if(override!==void 0)return ctx.usedImageOverrides.add(code),imageOf(override)}function parse(ctx,p){let parsed=parseCardText(p.text.current,{obligation:p.raw.type_code==="obligation",villainNames:ctx.villainNames,titles:ctx.titles,multipleVillains:ctx.packHasMultipleVillains,...p.unheadedWhenRevealed!==void 0?{unheadedWhenRevealed:p.unheadedWhenRevealed}:{},...p.extraConstantFrom!==void 0?{extraConstantFrom:p.extraConstantFrom}:{},...p.labelSentences!==void 0?{labelSentences:p.labelSentences}:{},...p.preambleWhenRevealed!==void 0?{preambleWhenRevealed:p.preambleWhenRevealed}:{}});for(let u of parsed.unclassified)ctx.errors.push(`${p.raw.code}: ${u}`);let hasBoostAbility=parsed.abilities.some(a=>a.kind==="boost");return p.boostGrantedBy?(!p.raw.boost_star||hasBoostAbility)&&ctx.errors.push(`${p.raw.code}: boostGrantedBy needs boost_star=true and no Boost ability in the text (boost_star=${String(p.raw.boost_star)}, text ${hasBoostAbility?"has":"has no"} a Boost ability)`):!!p.raw.boost_star!==hasBoostAbility&&!p.ignored.has("boost_star")&&ctx.errors.push(`${p.raw.code}: boost_star=${String(p.raw.boost_star)} but text ${hasBoostAbility?"has":"has no"} a Boost ability`),parsed}function abilityRefs(ctx,code,cardName,abilities){return assignAbilityIds(code,cardName,abilities,ctx.usedAbilityIds).map(({id,ability})=>{let note=ctx.curation.scriptingNotes[id];return note!==void 0&&ctx.usedNotes.add(id),{id:brand("ability",id),...ability.name?{label:stripQuotes(ability.name)}:{},...note!==void 0?{notesForScripting:note}:{}}})}function record(ctx,card,cardSetCode,parts){ctx.cards.push(card),parts.length===1&&!ctx.faceCodesByCardId.has(card.id)&&ctx.faceCodesByCardId.set(card.id,[parts[0].raw.code]);let note=ctx.curation.cardNotes[card.id],duplicateOf=parts.map(p=>p.raw.duplicate_of_code).find(c=>!!c);ctx.provenance.push({cardId:card.id,cardSetCode,marvelcdbCodes:parts.map(p=>p.raw.code),corrections:[...parts.flatMap(p=>p.notes),...note?[`data decision: ${note}`]:[]],...duplicateOf?{duplicateOfCardId:brand("card",duplicateOf)}:{}})}function baseFields(ctx,p,id,codes,images=imagesOf(p.raw.imagesrc,p.raw.backimagesrc)??reprintImages(p.raw)??null){return{id:brand("card",id),name:p.name,...p.subtitle?{subtitle:p.subtitle}:{},setCode:ctx.setCode,cycleId:ctx.cycleId,collectorNumber:collector(codes),quantityInSet:p.quantityInSet,unique:p.unique,...images?{images}:{},...p.cardBack?{cardBack:p.cardBack}:{},...p.definedCounterTypes?{definedCounterTypes:p.definedCounterTypes}:{},...p.errata?{errata:errataStatus(p.errata)}:{},...amplifyIconsField(p.raw),...schemeIconsField(p.raw)}}function checkNoSchemeFields(ctx,p){for(let f of["base_threat","scheme_crisis","scheme_acceleration","scheme_hazard"]){let v=p.raw[f];v!=null&&!p.ignored.has(f)&&ctx.errors.push(`${p.raw.code} (${p.raw.type_code}) has ${f}=${String(v)} \u2014 not a printed field on this card type; verify and add an ignoreFields correction`)}}function expectNoPlayerData(ctx,p,parsed){(Object.keys(parsed.restrictions).length>0||parsed.maxPerDeckText!==void 0)&&ctx.errors.push(`${p.raw.code}: play/deck restriction on a non-player card`),parsed.restrictedWeight!==void 0&&ctx.errors.push(`${p.raw.code}: "Counts as N restricted cards" on a non-player card`)}function expectNoAttach(ctx,p,parsed){parsed.attachesTo&&ctx.errors.push(`${p.raw.code}: attach rule on a ${p.raw.type_code}`)}function campaignSetCode(r){return r.faction_code==="campaign"&&r.card_set_code?r.card_set_code:void 0}var OWN_STEP_TYPES=new Set(["hero","alter_ego","villain","leader","main_scheme"]);function splitsIntoTwoCards(r){let b=r.linked_card;return!b||!b.hidden||b.type_code!==r.type_code||OWN_STEP_TYPES.has(r.type_code)?!1:r.type_code==="minion"||(b.card_set_code??null)!==(r.card_set_code??null)}function backFaceSet(r){let b=r.linked_card;if(!(!b||!splitsIntoTwoCards(r))&&!(r.faction_code!=="encounter"||b.faction_code!=="encounter")&&!(!b.card_set_code||b.card_set_code===r.card_set_code))return{code:b.card_set_code,name:b.card_set_name??b.card_set_code}}var hasLinkedKeyword=r=>/(^|\n)Linked \(/.test(r.text??"");function normalizeEncounterSets(ctx){let setNames=new Map,campaignSets=new Set;for(let r of ctx.topLevel){let campaignSet=campaignSetCode(r);if(campaignSet)campaignSets.add(campaignSet);else if(r.faction_code!=="encounter"||r.type_code==="obligation"||!r.card_set_code||ctx.heroBySet.has(r.card_set_code)&&hasLinkedKeyword(r))continue;let code=campaignSet??r.card_set_code;if(!code)continue;let prev=setNames.get(code),name=r.card_set_name??code;prev!==void 0&&prev!==name&&ctx.errors.push(`set ${code} has two names: ${prev} / ${name}`),setNames.set(code,name)}for(let r of ctx.topLevel){let back=backFaceSet(r);if(!back)continue;let prev=setNames.get(back.code);prev!==void 0&&prev!==back.name&&ctx.errors.push(`set ${back.code} has two names: ${prev} / ${back.name}`),setNames.set(back.code,back.name)}return{encounterSets:[...setNames.entries()].sort(([a],[b])=>a.localeCompare(b)).map(([id,name])=>{let hero=id.endsWith("_nemesis")?ctx.heroBySet.get(id.slice(0,-8)):void 0,override=ctx.curation.encounterSets?.[id];override&&ctx.usedEncounterSetOverrides.add(id);let separateDecks=override?.separateDecks?.map(d=>({name:d.name,contents:{...d.contents.encounterSetCodes?{encounterSetIds:d.contents.encounterSetCodes.map(c=>brand("encounterSet",c))}:{},...d.contents.cardType?{cardType:d.contents.cardType}:{},...d.contents.trait?{trait:d.contents.trait}:{}},discardPile:d.discardPile,whenEmpty:d.whenEmpty}));return{id:brand("encounterSet",id),name:override?.name??name,packCodes:[ctx.setCode],...hero?{nemesisOfIdentityId:brand("card",hero.code)}:{},...campaignSets.has(id)||override?.campaignSpecific?{campaignSpecific:!0}:{},...id==="standard_pvp"||override?.competitiveOnly?{competitiveOnly:!0}:{},...override?.side?{side:override.side}:{},...id==="standard"||id==="standard_ii"||id==="standard_iii"?{classification:"standard"}:{},...id==="expert"||id==="expert_ii"?{classification:"expert"}:{},...separateDecks?{separateDecks}:{},...override?.singleVillainOnly?{singleVillainOnly:!0}:{},...override?.extraModular?{extraModular:!0}:{},...override?.autoIncluded?{autoIncluded:{when:override.autoIncluded.when,shuffledIn:override.autoIncluded.shuffledIn.map(code=>brand("card",code))}}:{}}}),setNames}}function prepare(ctx,r){let{curation,errors}=ctx,cached=ctx.prepared.get(r.code);if(cached)return cached;let text=toPlainText(r.real_text??r.text),name=r.name,subtitle=r.subname||void 0,unique=!!r.is_unique,traits=parseTraits(r.real_traits??r.traits),boost=r.boost??0,attack=r.attack,attackIsCurated=!1,thwart,scheme,dashedMinionStats,schemeIcons2,startingThreatPerPlayer,startingThreat,specialCost=r.cost===-1?"X":void 0,quantityInSet=r.quantity,deckLimit,cardBack,impliedAttachHost,hostChosenBy,attachmentMaxPerHost,nemesisMinion,labelSentences,dashedThreatFields,evidenceIcon,definedCounterTypes,boostGrantedBy,unheadedWhenRevealed,extraConstantFrom,preambleWhenRevealed,notes=[],ignored=new Set;curation.corrections.forEach((c,i)=>{if(c.code===r.code){if(ctx.usedCorrections.add(i),c.impliedAttachHost!==void 0&&(impliedAttachHost=c.impliedAttachHost),c.hostChosenBy!==void 0&&(hostChosenBy=c.hostChosenBy),c.attachmentMaxPerHost!==void 0&&(attachmentMaxPerHost=c.attachmentMaxPerHost),c.nemesisMinion!==void 0&&(nemesisMinion=c.nemesisMinion),c.labelSentences!==void 0&&(labelSentences=c.labelSentences),c.unheadedWhenRevealed!==void 0&&(unheadedWhenRevealed=c.unheadedWhenRevealed),c.extraConstantFrom!==void 0&&(extraConstantFrom=c.extraConstantFrom),c.preambleWhenRevealed!==void 0&&(preambleWhenRevealed=c.preambleWhenRevealed),c.textReplace)if(c.textReplace.find==="")text!==""?errors.push(`${r.code}: correction textReplace expects no printed text, found "${text}"`):text=c.textReplace.replace;else{let count=text.split(c.textReplace.find).length-1;count!==1?errors.push(`${r.code}: correction text "${c.textReplace.find}" found ${count} times (expected 1)`):text=text.replace(c.textReplace.find,c.textReplace.replace)}c.name!==void 0&&(name=c.name),c.subtitle!==void 0&&(subtitle=c.subtitle),c.unique!==void 0&&(unique=c.unique),c.traits!==void 0&&(traits=c.traits.map(t=>t.toUpperCase())),c.boost!==void 0&&(boost=c.boost),c.attack!==void 0&&(attack=c.attack,attackIsCurated=!0),c.thwart!==void 0&&(thwart=c.thwart),c.scheme!==void 0&&(scheme=c.scheme),c.dashedMinionStats!==void 0&&(dashedMinionStats=c.dashedMinionStats),c.schemeIcons!==void 0&&(schemeIcons2=c.schemeIcons),c.startingThreatPerPlayer!==void 0&&(startingThreatPerPlayer=c.startingThreatPerPlayer),c.startingThreat!==void 0&&(startingThreat=c.startingThreat),c.specialCost!==void 0&&(specialCost=c.specialCost),c.cardBack!==void 0&&(cardBack=c.cardBack),c.quantityInSet!==void 0&&(quantityInSet=c.quantityInSet),c.deckLimit!==void 0&&(c.deckLimit===r.deck_limit&&errors.push(`${r.code}: correction deckLimit ${c.deckLimit} already matches raw`),deckLimit=c.deckLimit),c.dashedThreatFields!==void 0&&(dashedThreatFields=c.dashedThreatFields),c.evidenceIcon!==void 0&&(evidenceIcon=c.evidenceIcon),c.definedCounterTypes!==void 0&&(definedCounterTypes=c.definedCounterTypes),c.boostGrantedBy!==void 0&&(boostGrantedBy=c.boostGrantedBy);for(let f of c.ignoreFields??[])ignored.add(f);notes.push(`${r.code}: ${c.reason} [evidence: ${c.evidence}]`)}});for(let t of unknownTokens(text))errors.push(`${r.code}: unknown text token ${t}`);let errata=curation.errata.find(e=>e.code===r.code),printed=text,current=text;errata&&(ctx.usedErrata.add(errata.code),errata.printedReplace&&errata.currentReplace?errors.push(`${r.code}: errata sets both printedReplace and currentReplace \u2014 set exactly one`):errata.printedReplace?(printed=text.split(errata.printedReplace.find).join(errata.printedReplace.replace),printed===text&&errors.push(`${r.code}: errata printedReplace "${errata.printedReplace.find}" not found`)):errata.currentReplace&&(current=text.split(errata.currentReplace.find).join(errata.currentReplace.replace),current===text&&errors.push(`${r.code}: errata currentReplace "${errata.currentReplace.find}" not found`)),notes.push(`${r.code}: errata ${errata.version} \u2014 ${errata.note} [evidence: ${errata.evidence}]`));let flavor=toPlainText(r.flavor),p={raw:r,name,...subtitle?{subtitle}:{},unique,traits:traits.map(traitOf),boost,attack,attackIsCurated,...thwart!==void 0?{thwart}:{},...scheme!==void 0?{scheme}:{},...dashedMinionStats?{dashedMinionStats}:{},...schemeIcons2?{schemeIcons:schemeIcons2}:{},...startingThreatPerPlayer!==void 0?{startingThreatPerPlayer}:{},...startingThreat!==void 0?{startingThreat}:{},text:{printed,current},...flavor?{flavor}:{},...errata?{errata}:{},notes,ignored,quantityInSet,...deckLimit!==void 0?{deckLimit}:{},...specialCost?{specialCost}:{},...cardBack?{cardBack}:{},...impliedAttachHost?{impliedAttachHost}:{},...hostChosenBy?{hostChosenBy}:{},...attachmentMaxPerHost!==void 0?{attachmentMaxPerHost}:{},...nemesisMinion!==void 0?{nemesisMinion}:{},...labelSentences!==void 0?{labelSentences}:{},...unheadedWhenRevealed!==void 0?{unheadedWhenRevealed}:{},...extraConstantFrom!==void 0?{extraConstantFrom}:{},...preambleWhenRevealed!==void 0?{preambleWhenRevealed}:{},...dashedThreatFields?{dashedThreatFields}:{},...evidenceIcon?{evidenceIcon}:{},...definedCounterTypes?{definedCounterTypes}:{},...boostGrantedBy?{boostGrantedBy}:{}};return ctx.prepared.set(r.code,p),p}function buildExtraFace(ctx,r){let p=prepare(ctx,r),parsed=parse(ctx,p);expectNoPlayerData(ctx,p,parsed),expectNoAttach(ctx,p,parsed);let image=imageOf(r.imagesrc);return{prepared:p,face:{faceName:p.name,traits:p.traits,atk:r.attack??0,thw:p.thwart??r.thwart??0,def:r.defense??0,handSize:r.hand_size??0,...statStarsField(r),keywords:parsed.keywords,text:p.text,...p.flavor?{flavor:p.flavor}:{},abilities:abilityRefs(ctx,r.code,p.name,parsed.abilities),...faceSchemeIconsField(r),...image?{image}:{}}}}function buildCuratedFace(ctx,code,source){let text=toPlainText(source.text),traits=parseTraits(source.traits.join(". ")).map(traitOf),parsed=parseCardText(text,{villainNames:ctx.villainNames,multipleVillains:ctx.packHasMultipleVillains});for(let u of parsed.unclassified)ctx.errors.push(`${code}: ${u}`);return{traits,text:{printed:text,current:text},keywords:parsed.keywords,abilities:abilityRefs(ctx,code,source.name,parsed.abilities)}}function syntheticPrepared(ctx,code,name,note){return{raw:{code,name,pack_code:ctx.curation.packCode,type_code:"alter_ego",faction_code:"hero",position:0,quantity:1},name,unique:!1,traits:[],boost:0,attack:void 0,attackIsCurated:!1,text:{printed:"",current:""},notes:[note],ignored:new Set,quantityInSet:1}}function buildSeparatedIdentity(ctx,r,other,source,separateDecksByIdentity){let{errors,topLevel}=ctx,h=prepare(ctx,r),hp=parse(ctx,h);expectNoPlayerData(ctx,h,hp),expectNoAttach(ctx,h,hp);let pOther=prepare(ctx,other),parsedOther=parse(ctx,pOther);expectNoPlayerData(ctx,pOther,parsedOther),expectNoAttach(ctx,pOther,parsedOther);let set=r.card_set_code??"",obligations=topLevel.filter(x=>x.type_code==="obligation"&&x.card_set_code===set),nemesisSet=`${set}_nemesis`;obligations.length!==1&&errors.push(`${r.code}: expected exactly one obligation in set ${set}, found ${obligations.length}`),topLevel.some(x=>x.card_set_code===nemesisSet)||errors.push(`${r.code}: no nemesis set ${nemesisSet}`);let heroImage=imageOfWithOverride(ctx,r.code,r.imagesrc),alterEgoCode=source.alterEgoCardNumber,alterEgoImage=imageOf(source.alterEgo.image),alterEgo=buildCuratedFace(ctx,alterEgoCode,source.alterEgo),alterEgoOtherCode=`${alterEgoCode}b`,alterEgoOther=buildCuratedFace(ctx,alterEgoOtherCode,source.alterEgoOtherSide),separateDecks=separateDecksByIdentity.get(r.code),otherImage=imageOf(other.imagesrc),heroOtherFace={cardType:"support",name:pOther.name,traits:pOther.traits,keywords:parsedOther.keywords,text:pOther.text,...pOther.flavor?{flavor:pOther.flavor}:{},abilities:abilityRefs(ctx,other.code,pOther.name,parsedOther.abilities),...otherImage?{image:otherImage}:{}},alterEgoOtherImage=imageOf(source.alterEgoOtherSide.image),alterEgoOtherFace={cardType:"upgrade",name:source.alterEgoOtherSide.name,traits:alterEgoOther.traits,keywords:alterEgoOther.keywords,text:alterEgoOther.text,...source.alterEgoOtherSide.flavor?{flavor:source.alterEgoOtherSide.flavor}:{},abilities:alterEgoOther.abilities,...alterEgoOtherImage?{image:alterEgoOtherImage}:{},...source.alterEgoOtherSide.resourceIcons?{resourceIcons:source.alterEgoOtherSide.resourceIcons}:{}},syntheticAlterEgo=syntheticPrepared(ctx,alterEgoCode,source.alterEgo.name,`${alterEgoCode}: no MarvelCDB record exists for this card at all \u2014 every field transcribed from a second source [evidence: ${source.evidence}]`),syntheticAlterEgoOther=syntheticPrepared(ctx,alterEgoOtherCode,source.alterEgoOtherSide.name,`${alterEgoOtherCode}: no MarvelCDB record exists for this card at all \u2014 every field transcribed from a second source [evidence: ${source.evidence}]`),card={...baseFields(ctx,h,r.code,[r.code,other.code,alterEgoCode,alterEgoOtherCode],null),type:"hero_identity",hp:r.health??0,hero:{faceName:h.name,traits:h.traits,atk:r.attack??0,thw:h.thwart??r.thwart??0,def:r.defense??0,handSize:r.hand_size??0,...statStarsField(r),keywords:hp.keywords,text:h.text,...h.flavor?{flavor:h.flavor}:{},abilities:abilityRefs(ctx,r.code,h.name,hp.abilities),...faceSchemeIconsField(r),...heroImage?{image:heroImage}:{}},alterEgo:{faceName:source.alterEgo.name,traits:alterEgo.traits,rec:source.alterEgo.rec,handSize:source.alterEgo.handSize,keywords:alterEgo.keywords,text:alterEgo.text,...source.alterEgo.flavor?{flavor:source.alterEgo.flavor}:{},abilities:alterEgo.abilities,...alterEgoImage?{image:alterEgoImage}:{}},obligationCardId:brand("card",obligations[0]?.code??""),nemesisEncounterSetId:brand("encounterSet",nemesisSet),...separateDecks?{separateDecks}:{},separatedIdentity:{alterEgoCardNumber:alterEgoCode,heroCardOtherSide:heroOtherFace,alterEgoCardOtherSide:alterEgoOtherFace},...ctx.curation.identityDeckbuilding?.[r.code]?{deckbuilding:ctx.curation.identityDeckbuilding[r.code]}:{}};ctx.handled.add(r.code).add(other.code),record(ctx,card,set,[h,pOther,syntheticAlterEgo,syntheticAlterEgoOther])}function normalizeHeroes(ctx,separateDecksByIdentity){let{errors,topLevel}=ctx,heroRecords=topLevel.filter(x=>x.type_code==="hero"),extraFacesBySet=new Map;for(let r of heroRecords){let ae=r.linked_card;if(ae&&ae.type_code==="alter_ego"||ctx.curation.separatedIdentities?.[r.code]||!r.card_set_code)continue;let list=extraFacesBySet.get(r.card_set_code)??[];list.push(r),extraFacesBySet.set(r.card_set_code,list)}for(let r of heroRecords){let ae=r.linked_card,separatedSource=ae?ctx.curation.separatedIdentities?.[r.code]:void 0;if(separatedSource){buildSeparatedIdentity(ctx,r,ae,separatedSource,separateDecksByIdentity);continue}if(!ae||ae.type_code!=="alter_ego")continue;let h=prepare(ctx,r),a=prepare(ctx,ae),hp=parse(ctx,h),ap=parse(ctx,a);for(let[p,parsed]of[[h,hp],[a,ap]])expectNoPlayerData(ctx,p,parsed),expectNoAttach(ctx,p,parsed);r.health!==ae.health&&errors.push(`${r.code}: hero/alter-ego hit points differ`);let set=r.card_set_code??"",obligations=topLevel.filter(x=>x.type_code==="obligation"&&x.card_set_code===set),nemesisSet=`${set}_nemesis`;obligations.length!==1&&errors.push(`${r.code}: expected exactly one obligation in set ${set}, found ${obligations.length}`),topLevel.some(x=>x.card_set_code===nemesisSet)||errors.push(`${r.code}: no nemesis set ${nemesisSet}`);let heroImage=imageOfWithOverride(ctx,r.code,r.imagesrc),alterEgoImage=imageOfWithOverride(ctx,ae.code,ae.imagesrc);heroImage&&!r.imagesrc&&h.notes.push(`${r.code}: no artwork on MarvelCDB; art reference substituted from a curated second source [evidence: curation.imageOverrides]`),alterEgoImage&&!ae.imagesrc&&a.notes.push(`${ae.code}: no artwork on MarvelCDB; art reference substituted from a curated second source [evidence: curation.imageOverrides]`);let separateDecks=separateDecksByIdentity.get(r.code),extraFaceRecords=extraFacesBySet.get(set)??[],extraFaces=extraFaceRecords.map(ef=>buildExtraFace(ctx,ef)),progressingVersions=ctx.curation.progressingIdentity?.[r.code],card={...baseFields(ctx,h,r.code,[r.code,ae.code],imagesOf(r.imagesrc,ae.imagesrc)??null),type:"hero_identity",hp:r.health??0,hero:{faceName:h.name,traits:h.traits,atk:r.attack??0,thw:h.thwart??r.thwart??0,def:r.defense??0,handSize:r.hand_size??0,...statStarsField(r),keywords:hp.keywords,text:h.text,...h.flavor?{flavor:h.flavor}:{},abilities:abilityRefs(ctx,r.code,h.name,hp.abilities),...faceSchemeIconsField(r),...heroImage?{image:heroImage}:{}},alterEgo:{faceName:a.name,traits:a.traits,rec:ae.recover??0,handSize:ae.hand_size??0,...statStarsField(ae),keywords:ap.keywords,text:a.text,...a.flavor?{flavor:a.flavor}:{},abilities:abilityRefs(ctx,ae.code,a.name,ap.abilities),...faceSchemeIconsField(ae),...alterEgoImage?{image:alterEgoImage}:{}},obligationCardId:brand("card",obligations[0]?.code??""),nemesisEncounterSetId:brand("encounterSet",nemesisSet),...separateDecks?{separateDecks}:{},...extraFaces.length>0?{additionalHeroForms:extraFaces.map(f=>f.face)}:{},...ctx.curation.identityDeckbuilding?.[r.code]?{deckbuilding:ctx.curation.identityDeckbuilding[r.code]}:{},...progressingVersions!==void 0&&progressingVersions.length>=2?{progressingIdentity:{versions:progressingVersions.map(v=>brand("card",v))}}:{}};ctx.handled.add(r.code).add(ae.code);for(let ef of extraFaceRecords)ctx.handled.add(ef.code);record(ctx,card,set,[h,a,...extraFaces.map(f=>f.prepared)])}for(let[,records]of extraFacesBySet)for(let r of records)ctx.handled.has(r.code)||errors.push(`${r.code}: hero without a linked alter-ego`)}var EVIDENCE_KIND_OF={evidence_means:"means",evidence_motive:"motive",evidence_opportunity:"opportunity"};function normalizeEncounterCard(ctx,rec,flipSide,flipParts){let{errors,curation}=ctx,{r,p,parsed,set,common,abilities}=rec,isCampaignCard=r.faction_code==="campaign",separateDeck=curation.separateDecks?.find(d=>d.cardFamily==="encounter"&&d.cardCodes.includes(r.code));r.faction_code!=="encounter"&&!isCampaignCard&&!(separateDeck&&r.faction_code==="hero")&&errors.push(`${r.code}: ${r.type_code} with faction ${r.faction_code}`),expectNoPlayerData(ctx,p,parsed);let encounterCommon={encounterSetIds:separateDeck||!isCampaignCard&&ctx.heroBySet.has(set)&&(r.type_code==="obligation"||hasLinkedKeyword(r))?[]:[brand("encounterSet",set)],...separateDeck?{separateDeck:separateDeck.deckName}:{},boostIcons:p.boost,...parsed.abilities.some(a=>a.kind==="boost")||p.boostGrantedBy?{starIcon:!0}:{},...p.boostGrantedBy?{boostGrantedBy:p.boostGrantedBy.map(c=>brand("card",c))}:{},traits:p.traits,keywords:parsed.keywords,text:p.text,...p.flavor?{flavor:p.flavor}:{},abilities,...flipSide?{flipSide}:{},...parsed.modeOnly?{modeOnly:parsed.modeOnly}:{}};switch(r.type_code){case"minion":{checkNoSchemeFields(ctx,p),expectNoAttach(ctx,p,parsed);let rawAtk=p.attack;rawAtk===-1&&!curation.cardNotes[r.code]&&errors.push(`${r.code}: printed ATK is X (MarvelCDB -1) \u2014 needs a cardNotes entry`),rawAtk===void 0&&!curation.cardNotes[r.code]&&errors.push(`${r.code}: minion ATK is absent (printed "0" with a reminder star, or "\u2014"?) \u2014 needs a cardNotes entry`),(rawAtk===null||rawAtk!==void 0&&rawAtk<-1)&&errors.push(`${r.code}: minion ATK ${String(rawAtk)} invalid`),(p.scheme??r.scheme)==null&&!curation.cardNotes[r.code]&&errors.push(`${r.code}: minion has no scheme value (printed "0", or "\u2014"?) \u2014 needs a cardNotes entry`);let minion={...common,type:"minion",atk:p.dashedMinionStats?.includes("atk")?null:rawAtk===-1?"X":rawAtk??0,sch:p.dashedMinionStats?.includes("sch")?null:p.scheme??r.scheme??0,hp:r.health??0,...statStarsField(r),...r.health_per_hero?{hpPerPlayer:!0}:{},...r.health_per_group?{hpPerGroup:!0}:{},...encounterCommon,...parsed.nemesisMinion||p.nemesisMinion?{nemesisMinion:!0}:{}};record(ctx,minion,set,[p,...flipParts]);return}case"attachment":{let ownWhenRevealed=p.impliedAttachHost==="ownWhenRevealed",attachesTo=(typeof p.impliedAttachHost=="object"?p.impliedAttachHost:void 0)??parsed.attachesTo??(p.impliedAttachHost&&p.impliedAttachHost!=="ownWhenRevealed"&&typeof p.impliedAttachHost=="string"?{kind:p.impliedAttachHost}:void 0);if(!attachesTo&&!ownWhenRevealed){errors.push(`${r.code}: attachment without an attach rule`);return}if(parsed.attachesToVillainNamed){let sameSetVillains=ctx.topLevel.filter(x=>(x.type_code==="villain"||x.type_code==="leader")&&x.card_set_code===r.card_set_code);(sameSetVillains.length>0?sameSetVillains:isCampaignCard?ctx.topLevel.filter(x=>x.type_code==="villain"||x.type_code==="leader"):[]).some(v=>v.name===parsed.attachesToVillainNamed)||errors.push(`${r.code}: "Attach to ${parsed.attachesToVillainNamed}." is not this set's villain`)}p.hostChosenBy&&!attachesTo&&errors.push(`${r.code}: hostChosenBy on an attachment with no data host`);let mods=attachmentStatModifiers(ctx,r.code,p,r.scheme,r.thwart),flipMods=attachmentFlipStatModifiers(ctx,mods,r.linked_card,flipParts[0]),attachment={...common,type:"attachment",...attachesTo?{attachesTo}:{},...p.hostChosenBy?{hostChosenBy:p.hostChosenBy}:{},...p.attachmentMaxPerHost!==void 0?{playRestrictions:{maxPerHost:p.attachmentMaxPerHost}}:{},...Object.keys(mods).length>0?{statModifiers:mods}:{},...statStarsField(r),...encounterCommon,...encounterCommon.flipSide&&flipMods?{flipSide:{...encounterCommon.flipSide,statModifiers:flipMods}}:{}};record(ctx,attachment,set,[p,...flipParts]);return}case"treachery":expectNoAttach(ctx,p,parsed),record(ctx,{...common,type:"treachery",...encounterCommon},set,[p,...flipParts]);return;case"obligation":record(ctx,{...common,type:"obligation",...encounterCommon},set,[p,...flipParts]);return;case"environment":expectNoAttach(ctx,p,parsed),record(ctx,{...common,type:"environment",...encounterCommon},set,[p,...flipParts]);return;case"side_scheme":{expectNoAttach(ctx,p,parsed),(r.base_threat===null||r.base_threat===void 0)&&p.startingThreat===void 0&&!curation.cardNotes[r.code]&&errors.push(`${r.code}: side scheme without starting threat`);let{encounterSetIds,boostIcons,starIcon,boostGrantedBy,traits,keywords,text,abilities:abs}=encounterCommon,scheme={...common,type:"side_scheme",encounterSetIds,startingThreat:scalingOf(p.startingThreat??r.base_threat??0,p.startingThreatPerPlayer??!r.base_threat_fixed,r.base_threat_per_group),icons:schemeIcons(p.schemeIcons?{...r,scheme_crisis:p.schemeIcons.crisis??0,scheme_acceleration:p.schemeIcons.acceleration??0,scheme_hazard:p.schemeIcons.hazard??0}:r),boostIcons,...starIcon?{starIcon}:{},...boostGrantedBy?{boostGrantedBy}:{},traits,keywords,text,...p.flavor?{flavor:p.flavor}:{},abilities:abs,...parsed.signatureOf?{signatureOf:parsed.signatureOf}:{},...parsed.modeOnly?{modeOnly:parsed.modeOnly}:{}};record(ctx,scheme,set,[p,...flipParts]);return}case"evidence_means":case"evidence_motive":case"evidence_opportunity":{let evidence={...common,type:"evidence",evidence:EVIDENCE_KIND_OF[r.type_code],encounterSetIds:[brand("encounterSet",set)],traits:p.traits,text:p.text,abilities,...p.evidenceIcon?{evidenceIcon:p.evidenceIcon.icon,evidenceColor:p.evidenceIcon.color}:{}};record(ctx,evidence,set,[p,...flipParts]);return}default:errors.push(`${r.code}: unhandled type ${r.type_code}`)}}function attachmentStatModifiers(ctx,code,p,rawScheme,rawThwart){let mods={},printedX=p.attack===-1&&!p.attackIsCurated;printedX&&!ctx.curation.cardNotes[code]?ctx.errors.push(`${code}: attachment ATK is X (MarvelCDB -1) \u2014 needs a cardNotes entry or a Correction.attack`):p.attack!==null&&p.attack!==void 0&&!printedX&&(mods.atk=p.attack);let thwart=p.thwart??rawThwart;return thwart!=null&&(mods.thw=thwart),p.scheme!==void 0?mods.sch=p.scheme:p.thwart===void 0&&!(rawScheme===-1&&printedX&&ctx.curation.cardNotes[code])&&rawScheme!==null&&rawScheme!==void 0&&(mods.sch=rawScheme),mods}function attachmentFlipStatModifiers(ctx,front,back,pBack){if(!back||!pBack)return;let mods=attachmentStatModifiers(ctx,back.code,pBack,back.scheme,back.thwart);return[...new Set([...Object.keys(front),...Object.keys(mods)])].every(k=>(front[k]??0)===(mods[k]??0))?void 0:mods}var emptyText={printed:"",current:""};function normalizeLetteredSchemeChain(ctx,aSides,set,mainSchemeIdBySet){let{errors}=ctx,ordered=[...aSides].sort((x,y)=>(x.stage??"").localeCompare(y.stage??"")),first=ordered[0];if(!first)return;let firstPrepared=prepare(ctx,first),mainSchemeId=brand("card",first.code),stages=[],parts=[firstPrepared];for(let[i,ra]of ordered.entries()){let rb=ra.linked_card;if(!rb||rb.type_code!=="environment"){errors.push(`${ra.code}: lettered main scheme stage has no linked environment`);continue}let isFirst=i===0,a=isFirst?firstPrepared:prepare(ctx,ra),pa=parse(ctx,a);expectNoPlayerData(ctx,a,pa),expectNoAttach(ctx,a,pa),isFirst||parts.push(a);let envP=prepare(ctx,rb),envParsed=parse(ctx,envP),envCommon={...baseFields(ctx,envP,rb.code,[rb.code]),otherFaceId:mainSchemeId};normalizeEncounterCard(ctx,{r:rb,p:envP,parsed:envParsed,set,common:envCommon,abilities:abilityRefs(ctx,rb.code,envP.name,envParsed.abilities)},void 0,[]);let envId=brand("card",rb.code),dashed=[],field=(value,fixed,key,perGroup)=>isFirst?(dashed.push(key),{base:0,perPlayer:0}):value==null?(fixed?dashed.push(key):errors.push(`${ra.code}: missing ${key}`),{base:0,perPlayer:0}):scalingOf(value,!fixed,perGroup),startingThreat=field(ra.base_threat,ra.base_threat_fixed,"startingThreat",ra.base_threat_per_group),targetThreat=field(ra.threat,ra.threat_fixed,"targetThreat",ra.threat_per_group),acceleration=field(ra.escalation_threat,ra.escalation_threat_fixed,"acceleration",ra.escalation_threat_per_group),stageImage=imageOf(ra.imagesrc);stages.push({stageNumber:i+1,...ra.stage?{stageLetter:ra.stage}:{},...a.name!==firstPrepared.name?{name:a.name}:{},startingThreat,targetThreat,acceleration,...dashed.length>0?{dashedValues:dashed}:{},otherFaceId:envId,...isFirst?{}:{onCompletion:"flipToOtherFace"},icons:isFirst?[]:schemeIcons(ra),text:isFirst?emptyText:a.text,traits:isFirst?[]:a.traits,keywords:isFirst?[]:pa.keywords,abilities:isFirst?[]:abilityRefs(ctx,ra.code,a.name,pa.abilities),...stageImage?{image:stageImage}:{},aSide:{text:isFirst?a.text:emptyText,abilities:isFirst?abilityRefs(ctx,ra.code,a.name,pa.abilities):[],...stageImage?{image:stageImage}:{}}}),ctx.handled.add(ra.code)}let firstStage=stages[0];if(!firstStage)return;let card={...baseFields(ctx,firstPrepared,first.code,ordered.map(r=>r.code),null),type:"main_scheme",encounterSetIds:[brand("encounterSet",set)],stages:[firstStage,...stages.slice(1)]};mainSchemeIdBySet.set(set,card.id),record(ctx,card,set,parts)}function normalizeMainSchemes(ctx){let{errors,topLevel}=ctx,mainSchemeIdBySet=new Map,schemeSets=[...new Set(topLevel.filter(r=>r.type_code==="main_scheme").map(r=>r.card_set_code??""))];for(let set of schemeSets){let aSides=topLevel.filter(r=>r.type_code==="main_scheme"&&r.card_set_code===set).sort((x,y)=>x.code.localeCompare(y.code));if(aSides.length>0&&aSides.every(r=>r.linked_card?.type_code==="environment")){normalizeLetteredSchemeChain(ctx,aSides,set,mainSchemeIdBySet);continue}let stages=[],parts=[];for(let ra of aSides){let rb=ra.linked_card;if(!ra.code.endsWith("a")||!rb||!rb.code.endsWith("b")){errors.push(`${ra.code}: main scheme record is not an A side linked to a B side`);continue}let a=prepare(ctx,ra),b=prepare(ctx,rb),solo=/^[A-Z]$/.test(ra.stage??""),separate=!solo&&!!ctx.curation.separateMainSchemeCards?.includes(set),ownParts=solo||separate?[]:parts;ownParts.push(a,b);let pa=parse(ctx,a),pb=parse(ctx,b);for(let[p,parsed]of[[a,pa],[b,pb]])expectNoPlayerData(ctx,p,parsed),expectNoAttach(ctx,p,parsed);pa.keywords.length>0&&errors.push(`${ra.code}: keywords on a main scheme A side`);let stageNumber=solo?1:Number.parseInt(rb.stage??"",10);solo?(ra.stage!=="A"||rb.stage!=="B")&&errors.push(`${ra.code}: stage "${String(ra.stage)}"/"${String(rb.stage)}" not an A/B pair`):(!Number.isInteger(stageNumber)||`${stageNumber}A`!==ra.stage)&&errors.push(`${ra.code}: stage "${String(ra.stage)}"/"${String(rb.stage)}" not an NA/NB pair`);let dashedValues=[],missingOrDashed=(value,fixed,field,label)=>{if(b.dashedThreatFields?.includes(field)){dashedValues.push(field);return}value==null&&(fixed?dashedValues.push(field):errors.push(`${rb.code}: missing ${label}`))};missingOrDashed(rb.base_threat,rb.base_threat_fixed,"startingThreat","starting threat"),missingOrDashed(rb.threat,rb.threat_fixed,"targetThreat","target threat"),missingOrDashed(rb.escalation_threat,rb.escalation_threat_fixed,"acceleration","acceleration");let firstName=solo||separate?a.name:parts[0]?.name,printedB=ctx.curation.printedBSideSchemeScans?.includes(rb.code)?imageOf(rb.imagesrc):void 0;printedB&&ctx.usedPrintedBSideScans.add(rb.code);let bSideImage=printedB??ctx.aggregateImage(ra.code)??imageOf(rb.imagesrc),ownA=imageOf(ra.imagesrc),linkedA=imageOf(rb.imagesrc),aSideImage=printedB?ownA??ctx.aggregateImage(ra.code):(linkedA&&linkedA!==bSideImage?linkedA:ownA??linkedA)??ctx.aggregateImage(ra.code),printedX=[],schemeField=(value,fixed,field,perGroup)=>value===-1?(printedX.push(field),{base:0,perPlayer:0}):scalingOf(value??0,!fixed,perGroup),builtStage={stageNumber,printedCardId:brand("card",rb.code),...solo?{stageLetter:ra.stage}:{},...firstName!==void 0&&b.name!==firstName?{name:b.name}:{},startingThreat:schemeField(rb.base_threat,rb.base_threat_fixed,"startingThreat",rb.base_threat_per_group),targetThreat:schemeField(rb.threat,rb.threat_fixed,"targetThreat",rb.threat_per_group),acceleration:schemeField(rb.escalation_threat,rb.escalation_threat_fixed,"acceleration",rb.escalation_threat_per_group),...printedX.length>0?{printedX}:{},...dashedValues.length>0?{dashedValues}:{},icons:schemeIcons(rb),text:b.text,traits:b.traits,keywords:pb.keywords,abilities:abilityRefs(ctx,rb.code,b.name,pb.abilities),...pb.completionLoses?{completionLoses:!0}:{},...pb.villainOf?{villainOf:pb.villainOf}:{},...bSideImage?{image:bSideImage}:{},aSide:{text:a.text,abilities:abilityRefs(ctx,ra.code,a.name,pa.abilities),...aSideImage?{image:aSideImage}:{}}};if(ctx.handled.add(ra.code).add(rb.code),separate){let{printedCardId:_key,...stage}=builtStage,card2={...baseFields(ctx,a,ra.code,[ra.code,rb.code],null),type:"main_scheme",encounterSetIds:[brand("encounterSet",set)],stages:[stage]};record(ctx,card2,set,ownParts),mainSchemeIdBySet.has(set)||mainSchemeIdBySet.set(set,card2.id);continue}if(!solo){stages.push(builtStage);continue}let soloCard={...baseFields(ctx,a,ra.code,[ra.code,rb.code],null),type:"main_scheme",encounterSetIds:[brand("encounterSet",set)],stages:[builtStage]};record(ctx,soloCard,set,ownParts)}let numbers=stages.map(st=>st.stageNumber);if(new Set(numbers).size===numbers.length&&!ctx.curation.keepStagePrintedCardIds?.includes(set))for(let i=0;i<stages.length;i++){let{printedCardId:_key,...rest}=stages[i];stages[i]=rest}let first=parts[0],firstStage=stages[0];if(!first||!firstStage)continue;let card={...baseFields(ctx,first,first.raw.code,parts.map(p=>p.raw.code),null),type:"main_scheme",encounterSetIds:[brand("encounterSet",set)],stages:[firstStage,...stages.slice(1)]};mainSchemeIdBySet.set(set,card.id),record(ctx,card,set,parts)}return mainSchemeIdBySet}function normalizeScenarios(ctx,{setNames,villainIdBySet,mainSchemeIdBySet}){let{errors}=ctx,emittedCardIds=new Set(ctx.cards.map(c=>c.id)),resolveCardCode=(code,label)=>{if(!emittedCardIds.has(code)){errors.push(`scenario: ${label} names unknown card ${code}`);return}return code};return ctx.curation.scenarios.map(s=>{let schemeSetCode=s.mainSchemeSetCode??s.villainSetCode;for(let code of[s.villainSetCode,schemeSetCode,...s.recommendedModularSetCodes,...s.standardSetCodes,...s.expertSetCodes,...s.additionalEncounterSetCodes??[],...s.multipleVillains?.villainSetCodes??[],...s.separateDecks?.flatMap(d=>d.contents.encounterSetCodes??[])??[]])!setNames.has(code)&&!CORE_ENCOUNTER_SET_CODES.has(code)&&errors.push(`scenario ${s.id}: unknown encounter set ${code}`);let villainId=s.villainCardCode?resolveCardCode(s.villainCardCode,`scenario ${s.id} villainCardCode`):villainIdBySet.get(s.villainSetCode),schemeId=mainSchemeIdBySet.get(schemeSetCode);villainId||errors.push(`scenario ${s.id}: no villain in set ${s.villainSetCode}`),schemeId||errors.push(`scenario ${s.id}: no main scheme in set ${schemeSetCode}`);let setAsideVillainCardIds=(s.setAsideVillainCardCodes??[]).map(c=>resolveCardCode(c,`scenario ${s.id} setAsideVillainCardCodes`)).filter(id=>id!==void 0).map(id=>brand("card",id)),setAsideCardIds=(s.setAsideCardCodes??[]).map(c=>resolveCardCode(c,`scenario ${s.id} setAsideCardCodes`)).filter(id=>id!==void 0).map(id=>brand("card",id)),neutralCards=s.neutralCardCodes?{villainCardId:brand("card",resolveCardCode(s.neutralCardCodes.villainCardCode,`scenario ${s.id} neutralCardCodes.villainCardCode`)??""),mainSchemeCardId:brand("card",resolveCardCode(s.neutralCardCodes.mainSchemeCardCode,`scenario ${s.id} neutralCardCodes.mainSchemeCardCode`)??"")}:void 0,expertVillains=s.expertVillains?{villainCardId:brand("card",resolveCardCode(s.expertVillains.villainCardCode,`scenario ${s.id} expertVillains.villainCardCode`)??""),setAsideVillainCardIds:s.expertVillains.setAsideVillainCardCodes.map(c=>resolveCardCode(c,`scenario ${s.id} expertVillains.setAsideVillainCardCodes`)).filter(id=>id!==void 0).map(id=>brand("card",id))}:void 0,separateDecks=s.separateDecks?.map(d=>({name:d.name,contents:{...d.contents.encounterSetCodes?{encounterSetIds:d.contents.encounterSetCodes.map(c=>brand("encounterSet",c))}:{},...d.contents.cardType?{cardType:d.contents.cardType}:{},...d.contents.trait?{trait:d.contents.trait}:{},...d.contents.cardCodes?{cardIds:d.contents.cardCodes.map(c=>resolveCardCode(c,`scenario ${s.id} separate deck ${d.name} contents.cardCodes`)).filter(id=>id!==void 0).map(id=>brand("card",id))}:{}},discardPile:d.discardPile,whenEmpty:d.whenEmpty,...d.closedToPlayerCards?{closedToPlayerCards:!0}:{},...d.topCardInPlay?{topCardInPlay:!0}:{},...d.discardByTrait?{discardByTrait:d.discardByTrait}:{},...d.buildAtSetup?{buildAtSetup:!0}:{}})),multipleVillains,mv=s.multipleVillains,shared=mv?.encounterDecks==="shared";if(mv){mv.villainSetCodes[0]!==s.villainSetCode&&errors.push(`scenario ${s.id}: multipleVillains.villainSetCodes[0] must equal villainSetCode`),mv.signatureSideSchemeCodes&&mv.villainSetCodes.length!==mv.signatureSideSchemeCodes.length&&errors.push(`scenario ${s.id}: multipleVillains villainSetCodes/signatureSideSchemeCodes length mismatch`),mv.villainCardCodes&&mv.villainCardCodes.length!==mv.villainSetCodes.length&&errors.push(`scenario ${s.id}: multipleVillains villainSetCodes/villainCardCodes length mismatch`),mv.sideBCardCodes&&mv.sideBCardCodes.length!==mv.villainSetCodes.length&&errors.push(`scenario ${s.id}: multipleVillains villainSetCodes/sideBCardCodes length mismatch`);let villains=mv.villainSetCodes.map((set,i)=>{let vid=mv.villainCardCodes?resolveCardCode(mv.villainCardCodes[i]??"",`scenario ${s.id} multipleVillains.villainCardCodes[${i}]`):villainIdBySet.get(set);vid||errors.push(`scenario ${s.id}: no villain in set ${set}`);let sideB=mv.sideBCardCodes?.[i],sideBId=sideB!==void 0?resolveCardCode(sideB,`scenario ${s.id} multipleVillains.sideBCardCodes[${i}]`):void 0,sig=mv.signatureSideSchemeCodes?.[i];return sig!==void 0&&!emittedCardIds.has(sig)&&errors.push(`scenario ${s.id}: unknown signature side scheme ${sig}`),{villainCardId:brand("card",vid??""),encounterSetIds:shared?[]:[brand("encounterSet",set)],...sig!==void 0?{signatureSideSchemeCardId:brand("card",sig)}:{},...sideBId!==void 0?{sideBCardId:brand("card",sideBId)}:{}}}),[firstV,secondV,...restV]=villains;villains.length<2&&errors.push(`scenario ${s.id}: multipleVillains needs at least two villains`),firstV&&secondV&&(multipleVillains={villains:[firstV,secondV,...restV],encounterDecks:mv.encounterDecks??"perVillain",activation:"activeVillainOnly",winCondition:mv.winCondition??"allVillainsDefeated",...mv.atSetup?{atSetup:mv.atSetup}:{},...mv.theVillain?{theVillain:mv.theVillain}:{}})}let villainOptions;if(s.villainOptionSetCodes){let codes=s.villainOptionSetCodes;codes.includes(s.villainSetCode)||errors.push(`scenario ${s.id}: villainOptionSetCodes must include villainSetCode ${s.villainSetCode}`);for(let code of Object.keys(s.villainOptionDetails??{}))codes.includes(code)||errors.push(`scenario ${s.id}: villainOptionDetails names ${code}, not an option`);villainOptions={options:codes.map(code=>{setNames.has(code)||errors.push(`scenario ${s.id}: unknown villain option set ${code}`);let detail=s.villainOptionDetails?.[code],isDefault=code===s.villainSetCode,vid=isDefault?villainId:villainIdBySet.get(code);vid||errors.push(`scenario ${s.id}: no villain in option set ${code}`);let victory=detail?.victory??(isDefault?s.victory:void 0),stages=detail?.villainStages??s.villainStages;return{villainSetId:brand("encounterSet",code),villainCardId:brand("card",vid??""),villainStages:{standard:stages.standard,expert:stages.expert},...victory?{victory}:{}}}),defaultSetId:brand("encounterSet",s.villainSetCode)}}let vco=s.villainCardOptions;if(vco){s.villainOptionSetCodes&&errors.push(`scenario ${s.id}: villainCardOptions excludes villainOptionSetCodes`);let cardById=new Map(ctx.cards.map(c=>[c.id,c])),options=vco.options.map(o=>{let vid=resolveCardCode(o.villainCardCode,`scenario ${s.id} villainCardOptions villain`),card=vid?cardById.get(vid):void 0,set=card&&"encounterSetIds"in card?card.encounterSetIds[0]:void 0;card&&card.type!=="villain"&&errors.push(`scenario ${s.id}: option ${o.villainCardCode} is not a villain card`),set||errors.push(`scenario ${s.id}: option ${o.villainCardCode} has no encounter set`);let linked=o.linkedCardCodes.map(c=>resolveCardCode(c,`scenario ${s.id} villainCardOptions linked`)).filter(id=>id!==void 0).map(id=>brand("card",id)),stages=o.villainStages??s.villainStages;return{villainSetId:brand("encounterSet",set??""),villainCardId:brand("card",vid??""),villainStages:{standard:stages.standard,expert:stages.expert},...linked.length>0?{linkedCardIds:linked}:{}}}),defaultId=resolveCardCode(vco.defaultCardCode,`scenario ${s.id} villainCardOptions defaultCardCode`),defaultOption=options.find(o=>o.villainCardId===defaultId);defaultOption||errors.push(`scenario ${s.id}: villainCardOptions defaultCardCode is not an option`),villainOptions={options,defaultSetId:defaultOption?.villainSetId??brand("encounterSet",""),keyedBy:"card",defaultCardId:brand("card",defaultId??""),...vco.selection?{selection:vco.selection}:{},...vco.chosenVillain?{chosenVillain:vco.chosenVillain}:{}}}let mainSchemeChoice;if(s.perPlayerMainSchemeCodes){let cardIds=s.perPlayerMainSchemeCodes.map(c=>resolveCardCode(c,`scenario ${s.id} perPlayerMainSchemeCodes`)).filter(id=>id!==void 0).map(id=>brand("card",id));for(let id of cardIds)ctx.cards.find(c=>c.id===id)?.type!=="main_scheme"&&errors.push(`scenario ${s.id}: perPlayerMainSchemeCodes names ${id}, not a main scheme card`);cardIds[0]!==void 0&&cardIds[0]!==schemeId&&errors.push(`scenario ${s.id}: perPlayerMainSchemeCodes must start with the main scheme ${schemeId}`),mainSchemeChoice={kind:"perPlayer",cardIds,expert:"random"}}let mainSchemeStages;if(s.recommendedMainSchemeStageCodes){let[one,two]=s.recommendedMainSchemeStageCodes,scheme=ctx.cards.find(c=>c.id===schemeId),held=new Set(scheme?.type==="main_scheme"?scheme.stages.map(st=>st.printedCardId):[]);for(let code of[one,two])held.has(code)||errors.push(`scenario ${s.id}: main scheme ${schemeId} has no stage ${code}`);mainSchemeStages={recommended:[brand("card",one),brand("card",two)]}}return{id:brand("scenario",s.id),name:s.name,packCode:ctx.setCode,villainCardId:brand("card",villainId??""),mainSchemeCardId:brand("card",schemeId??""),encounterSetIds:multipleVillains&&!shared?[]:[brand("encounterSet",s.villainSetCode),...(s.additionalEncounterSetCodes??[]).map(c=>brand("encounterSet",c))],recommendedModularSetIds:s.recommendedModularSetCodes.map(c=>brand("encounterSet",c)),standardEncounterSetIds:s.standardSetCodes.map(c=>brand("encounterSet",c)),expertEncounterSetIds:s.expertSetCodes.map(c=>brand("encounterSet",c)),villainStages:{standard:s.villainStages.standard,expert:s.villainStages.expert},...multipleVillains?{multipleVillains}:{},...s.usesIdentityEncounterSets===!1?{usesIdentityEncounterSets:!1}:{},...s.nemesisSetsSetAside?{nemesisSetsSetAside:!0}:{},...s.modularSetCount!==void 0?{modularSetCount:s.modularSetCount}:{},...s.modularSetCountRange?{modularSetCountRange:s.modularSetCountRange}:{},...s.side?{side:s.side}:{},...mainSchemeStages?{mainSchemeStages}:{},...s.setAsideModularSetCount!==void 0?{setAsideModularSetCount:s.setAsideModularSetCount}:{},...s.modularSetPool?{modularSetPool:{setIds:s.modularSetPool.setCodes.map(c=>brand("encounterSet",c)),restricted:s.modularSetPool.restricted}}:{},...setAsideVillainCardIds.length>0?{setAsideVillainCardIds}:{},...setAsideCardIds.length>0?{setAsideCardIds}:{},...neutralCards?{neutralCards}:{},...s.referenceCards?{referenceCards:s.referenceCards.map(r=>({...r,image:brand("image",r.image)}))}:{},...expertVillains?{expertVillains}:{},...s.victory?{victory:s.victory}:{},...s.separateGameAreas?{separateGameAreas:s.separateGameAreas}:{},...separateDecks?{separateDecks}:{},...s.startingVillain?{startingVillain:s.startingVillain}:{},...s.randomVillainName?{randomVillainName:s.randomVillainName}:{},...s.victoryCondition?{victoryCondition:s.victoryCondition}:{},...villainOptions?{villainOptions}:{},...mainSchemeChoice?{mainSchemeChoice}:{}}})}function collectSeparateDecks(ctx){let ofCode=new Map,byIdentity=new Map;for(let sd of ctx.curation.separateDecks??[]){let deckCards=[];for(let code of sd.cardCodes){ofCode.set(code,{identityCode:sd.identityCode,deckName:sd.deckName});let raw=ctx.byCode.get(code);if(!raw){ctx.errors.push(`separate deck ${sd.deckName}: unknown card ${code}`);continue}deckCards.push({cardId:brand("card",code),quantity:raw.quantity})}let list=byIdentity.get(sd.identityCode)??[];list.push({name:sd.deckName,cards:deckCards,topCardFaceup:sd.topCardFaceup??!0,discardPile:sd.discardPile??"own",whenEmpty:sd.whenEmpty??"reshuffleDiscardWithoutPenalty",...sd.cardFamily!==void 0?{cardFamily:sd.cardFamily}:{},...sd.fixedOrder!==void 0?{fixedOrder:sd.fixedOrder}:{},...sd.ownerMayLookThrough!==void 0?{ownerMayLookThrough:sd.ownerMayLookThrough}:{}}),byIdentity.set(sd.identityCode,list)}return{ofCode,byIdentity}}var PRINTABLE_ASPECTS=["aggression","justice","leadership","protection","pool"];function normalizePlayerCard(ctx,rec,separateDeck,flipSide,flipParts=[]){let{errors,curation}=ctx,{r,p,parsed,set,common,abilities}=rec,aspect,specificTo,printedAspect;if(separateDeck)aspect=`hero:${separateDeck.identityCode}`;else if(r.faction_code==="hero"){let hero=ctx.heroBySet.get(r.card_set_code??"");hero||errors.push(`${r.code}: hero card in set ${String(r.card_set_code)} with no identity`),aspect=`hero:${hero?.code??"?"}`}else r.card_set_code&&ctx.heroBySet.has(r.card_set_code)&&PRINTABLE_ASPECTS.includes(r.faction_code)?(aspect=`hero:${ctx.heroBySet.get(r.card_set_code)?.code??"?"}`,printedAspect=r.faction_code):r.faction_code==="basic"&&r.card_set_type_name_code==="leader"&&r.card_set_code?(aspect="basic",specificTo={kind:"competitive",encounterSetId:brand("encounterSet",r.card_set_code)}):CORE_ASPECTS.includes(r.faction_code)?aspect=r.faction_code:r.faction_code==="encounter"&&r.card_set_code?(aspect="none",specificTo={kind:"scenario",encounterSetId:brand("encounterSet",r.card_set_code)}):r.faction_code==="campaign"&&r.card_set_code?(aspect="basic",specificTo={kind:"campaign",encounterSetId:brand("encounterSet",r.card_set_code)}):(errors.push(`${r.code}: unknown faction ${r.faction_code}`),aspect=r.faction_code);let isLinked=parsed.keywords.some(k=>k.name==="linked"),exemptFromDeckLimit=!!separateDeck||isLinked||specificTo!==void 0&&!r.is_unique,rawDeckLimit=p.deckLimit??r.deck_limit,deckLimit=separateDeck?0:rawDeckLimit??(isLinked||r.is_unique||specificTo!==void 0?1:0);!exemptFromDeckLimit&&(!Number.isInteger(deckLimit)||deckLimit<1)&&errors.push(`${r.code}: deck_limit ${String(rawDeckLimit)} invalid`),parsed.maxPerDeckText!==void 0&&parsed.maxPerDeckText!==deckLimit&&errors.push(`${r.code}: text says Max ${parsed.maxPerDeckText} per deck but deck_limit=${deckLimit}`);let restrictions={...parsed.restrictions};parsed.restrictions.requiresIdentityTrait!==void 0&&(restrictions.requiresIdentityTrait=traitOf(parsed.restrictions.requiresIdentityTrait)),parsed.restrictions.requiresControlledCharacterTrait!==void 0&&(restrictions.requiresControlledCharacterTrait=traitOf(parsed.restrictions.requiresControlledCharacterTrait)),parsed.restrictions.maxWithTrait!==void 0&&(restrictions.maxWithTrait={...parsed.restrictions.maxWithTrait,trait:traitOf(parsed.restrictions.maxWithTrait.trait)}),parsed.attachesToVillainNamed&&errors.push(`${r.code}: player card attaches to a villain by name`),parsed.attachesTo&&r.type_code!=="upgrade"&&errors.push(`${r.code}: attach rule on a ${r.type_code}`);let unitCostMatch=/^Unit Cost (\d+)\./.exec(p.text.printed),unitCost=unitCostMatch?Number(unitCostMatch[1]):void 0,playerCommon={aspect,traits:p.traits,keywords:parsed.keywords,deckLimit,...Object.keys(restrictions).length>0?{playRestrictions:restrictions}:{},text:p.text,...p.flavor?{flavor:p.flavor}:{},abilities,...separateDeck?{separateDeck:separateDeck.deckName}:{},...flipSide?{flipSide}:{},...specificTo?{specificTo}:{},...unitCost!==void 0?{unitCost}:{},...parsed.restrictedWeight!==void 0?{restrictedWeight:parsed.restrictedWeight}:{},...printedAspect?{printedAspect}:{}},cost=r.cost??null,needCost=()=>p.specialCost?(r.cost_per_hero&&errors.push(`${r.code}: cost_per_hero on a printed ${p.specialCost} cost`),{cost:0,specialCost:p.specialCost}):cost===null?(errors.push(`${r.code}: ${r.type_code} without a cost`),{cost:0}):{cost,...r.cost_per_hero?{costPerPlayer:!0}:{}};switch(r.type_code){case"ally":{for(let[field,value]of[["attack",r.attack],["thwart",r.thwart]])value==null&&!curation.cardNotes[r.code]&&errors.push(`${r.code}: ally has no ${field} (printed "\u2014"?) \u2014 needs a cardNotes entry explaining the data`);let ally={...common,type:"ally",...needCost(),resourceIcons:resourceIcons(r),atk:printedStat(p.attack),thw:printedStat(p.thwart??r.thwart),hp:r.health??0,...statStarsField(r),consequentialDamage:{attack:r.attack_cost??0,thwart:r.thwart_cost??0},...playerCommon};record(ctx,ally,set,[p,...flipParts]);break}case"event":record(ctx,{...common,type:"event",...needCost(),resourceIcons:resourceIcons(r),...playerCommon},set,[p,...flipParts]);break;case"support":record(ctx,{...common,type:"support",...needCost(),resourceIcons:resourceIcons(r),...playerCommon},set,[p,...flipParts]);break;case"upgrade":record(ctx,{...common,type:"upgrade",...needCost(),resourceIcons:resourceIcons(r),...parsed.attachesTo?{attachesTo:parsed.attachesTo}:{},...playerCommon},set,[p,...flipParts]);break;case"resource":cost!==null&&errors.push(`${r.code}: resource with a cost`),record(ctx,{...common,type:"resource",producesIcons:resourceIcons(r),...playerCommon},set,[p,...flipParts]);break;case"player_side_scheme":{(r.base_threat===null||r.base_threat===void 0)&&errors.push(`${r.code}: player side scheme without starting threat`);let scheme={...common,type:"player_side_scheme",...needCost(),resourceIcons:resourceIcons(r),startingThreat:scalingOf(r.base_threat??0,!r.base_threat_fixed,r.base_threat_per_group),...playerCommon};record(ctx,scheme,set,[p,...flipParts]);break}}}function normalizeSingleCards(ctx,separateDeckOfCode){for(let r of ctx.topLevel){if(ctx.handled.has(r.code))continue;if(r.linked_card&&(r.type_code==="side_scheme"&&r.linked_card.type_code==="side_scheme"&&r.linked_card.hidden||splitsIntoTwoCards(r))){let linked=r.linked_card;for(let face of[r,linked]){let other=face===r?linked:r,p2=prepare(ctx,face),parsed2=parse(ctx,p2),common={...baseFields(ctx,p2,face.code,[face.code]),otherFaceId:brand("card",other.code)};normalizeEncounterCard(ctx,{r:face,p:p2,parsed:parsed2,set:face.card_set_code??face.faction_code,common,abilities:abilityRefs(ctx,face.code,p2.name,parsed2.abilities)},void 0,[])}continue}if(r.linked_card&&r.linked_card.hidden&&r.linked_card.type_code!==r.type_code){for(let face of[r,r.linked_card]){let other=face===r?r.linked_card:r,p2=prepare(ctx,face),parsed2=parse(ctx,p2),common={...baseFields(ctx,p2,face.code,[face.code]),otherFaceId:brand("card",other.code)},faceRec={r:face,p:p2,parsed:parsed2,set:face.card_set_code??face.faction_code,common,abilities:abilityRefs(ctx,face.code,p2.name,parsed2.abilities)};PLAYER_TYPES.has(face.type_code)?normalizePlayerCard(ctx,faceRec,separateDeckOfCode.get(face.code)):normalizeEncounterCard(ctx,faceRec,void 0,[])}continue}let read=readFlipSide(ctx,r),{flipParts}=read,p=prepare(ctx,r),flipSide=read.flipSide&&withAllyFlipStats(read.flipSide,r,p,flipParts[0]),parsed=parse(ctx,p),rec={r,p,parsed,set:r.card_set_code??r.faction_code,common:baseFields(ctx,p,r.code,[r.code]),abilities:abilityRefs(ctx,r.code,p.name,parsed.abilities)};PLAYER_TYPES.has(r.type_code)?normalizePlayerCard(ctx,rec,separateDeckOfCode.get(r.code),flipSide,flipParts):normalizeEncounterCard(ctx,rec,flipSide,flipParts)}}function withAllyFlipStats(flipSide,r,p,pBack){let back=r.linked_card;if(r.type_code!=="ally"||!back||!pBack)return flipSide;let thw=printedStat(pBack.thwart??back.thwart),atk=printedStat(pBack.attack),hp=back.health??0;return{...flipSide,...thw!==printedStat(p.thwart??r.thwart)?{thw}:{},...atk!==printedStat(p.attack)?{atk}:{},...hp!==(r.health??0)?{hp}:{}}}function readFlipSide(ctx,r){if(r.linked_card&&r.linked_card.type_code===r.type_code&&r.linked_card.hidden){let back=r.linked_card,pBack=prepare(ctx,back),parsedBack=parse(ctx,pBack);PLAYER_TYPES.has(r.type_code)&&parsedBack.maxPerDeckText===void 0&&Object.keys(parsedBack.restrictions).every(k=>k==="maxPerPlayer")||expectNoPlayerData(ctx,pBack,parsedBack),r.type_code!=="attachment"&&expectNoAttach(ctx,pBack,parsedBack);let backImage=imageOf(back.imagesrc),backIcons=resourceIcons(back),flipSide={name:pBack.name,...back.subname?{subtitle:back.subname}:{},traits:pBack.traits,keywords:parsedBack.keywords,text:pBack.text,...pBack.flavor?{flavor:pBack.flavor}:{},abilities:abilityRefs(ctx,back.code,pBack.name,parsedBack.abilities),...backImage?{image:backImage}:{},...statStarsField(back),...amplifyIconsField(back),...Object.keys(backIcons).length>0?{resourceIcons:backIcons}:{}};return ctx.handled.add(back.code),{flipSide,flipParts:[pBack]}}if(r.linked_card&&ctx.errors.push(`${r.code}: unexpected linked card ${r.linked_card.code} on a ${r.type_code}`),r.double_sided&&r.back_text){let backCode=`${r.code}b`,backRaw={...r,code:backCode,name:r.back_name??r.name,real_name:r.back_name??r.name,subname:null,text:r.back_text,real_text:r.back_text,imagesrc:r.backimagesrc??null,backimagesrc:null,linked_card:null,double_sided:!1,back_name:null,back_text:null},pBack=prepare(ctx,backRaw),parsedBack=parse(ctx,pBack),backImage=imageOf(backRaw.imagesrc);return{flipSide:{name:pBack.name,traits:pBack.traits,keywords:parsedBack.keywords,text:pBack.text,...pBack.flavor?{flavor:pBack.flavor}:{},abilities:abilityRefs(ctx,backCode,pBack.name,parsedBack.abilities),...backImage?{image:backImage}:{}},flipParts:[pBack]}}return{flipSide:void 0,flipParts:[]}}function normalizeStarterDecks(ctx){let{errors,cards}=ctx,byId=new Map(cards.map(c=>[c.id,c]));return ctx.curation.starterDecks.map(d=>{let identity=byId.get(d.identityCode);(!identity||identity.type!=="hero_identity")&&errors.push(`deck ${d.id}: ${d.identityCode} is not an identity`);let total=0;for(let[code,qty]of Object.entries(d.cards)){total+=qty;let card=byId.get(code);if(!card){errors.push(`deck ${d.id}: unknown card ${code}`);continue}if(!("aspect"in card)){errors.push(`deck ${d.id}: ${code} is not a player card`);continue}qty>card.quantityInSet&&errors.push(`deck ${d.id}: ${qty}\xD7 ${code} but one box has ${card.quantityInSet}`),qty>card.deckLimit&&errors.push(`deck ${d.id}: ${qty}\xD7 ${code} exceeds deck limit ${card.deckLimit}`);let secondaryAspects=d.secondaryAspects??[],offAspectAllowanceCodes=d.offAspectAllowanceCodes??[];card.aspect===`hero:${d.identityCode}`||card.aspect===d.aspect||secondaryAspects.includes(card.aspect)||offAspectAllowanceCodes.includes(code)||card.aspect==="basic"||errors.push(`deck ${d.id}: ${code} has aspect ${card.aspect}`)}(total<40||total>50)&&errors.push(`deck ${d.id}: ${total} cards, expected 40-50`);for(let card of cards)"aspect"in card&&card.aspect===`hero:${d.identityCode}`&&!("separateDeck"in card&&card.separateDeck!==void 0)&&d.cards[card.id]!==card.quantityInSet&&errors.push(`deck ${d.id}: hero card ${card.id} must be included \xD7${card.quantityInSet}`);if(identity?.type==="hero_identity"){identity.obligationCardId!==d.obligationCode&&errors.push(`deck ${d.id}: source lists obligation ${d.obligationCode}, identity links ${identity.obligationCardId}`);let nemesis=cards.filter(c=>"encounterSetIds"in c&&c.encounterSetIds.includes(identity.nemesisEncounterSetId)).map(c=>c.id).sort();nemesis.join()!==[...d.nemesisCodes].sort().join()&&errors.push(`deck ${d.id}: source nemesis set [${d.nemesisCodes.join()}] != data [${nemesis.join()}]`)}return{id:brand("deck",d.id),name:d.name,packCode:ctx.setCode,identityCardId:brand("card",d.identityCode),aspects:[d.aspect,...d.secondaryAspects??[]],cards:Object.entries(d.cards).sort(([a],[b])=>a.localeCompare(b)).map(([cardId,quantity])=>({cardId:brand("card",cardId),quantity})),provenance:{verified:d.verified,sources:[...d.sources],...d.note?{note:d.note}:{}}}})}var MODE_LABEL_RE=/^([A-Z])(\d+)$/,FACE_LABEL_RE=/^([A-Z]?)(\d+)$/,stageOrder=rec=>{let s=rec.stage??"";if(ROMAN[s]!==void 0)return ROMAN[s];let modeMatch=FACE_LABEL_RE.exec(s);return modeMatch?Number(modeMatch[2]):/^[A-Z]$/.test(s)?s.charCodeAt(0)-64:0},stageLabelOf=rec=>{let s=rec.stage??"";if(ROMAN[s]===void 0)return MODE_LABEL_RE.test(s)||/^[A-Z]$/.test(s)?s:void 0},ACTIVATION_ORDER_RE=/^ACTIVATION ORDER (\d+)$/;function extractActivationOrder(traits){let activationOrder,kept=[];for(let t of traits){let m=ACTIVATION_ORDER_RE.exec(t);m?activationOrder=Number(m[1]):kept.push(t)}return activationOrder!==void 0?{traits:kept,activationOrder}:{traits:kept}}function buildVillainStage(ctx,r){let{errors}=ctx,p=prepare(ctx,r);checkNoSchemeFields(ctx,p);let parsed=parse(ctx,p);expectNoPlayerData(ctx,p,parsed),expectNoAttach(ctx,p,parsed);let stageNumber=stageOrder(r),stageLabel=stageLabelOf(r),stageImage=imageOf(r.imagesrc);stageNumber===0&&errors.push(`${r.code}: villain stage "${String(r.stage)}" is not a roman numeral`),(r.health===null||r.health===void 0)&&errors.push(`${r.code}: villain without hit points`);let dashedStats=[];(r.attack===null||r.attack===void 0)&&dashedStats.push("atk"),(r.scheme===null||r.scheme===void 0)&&dashedStats.push("sch");let{traits:stageTraits,activationOrder}=extractActivationOrder(p.traits),infiniteHp=MODE_LABEL_RE.test(r.stage??"")&&r.health===0||ctx.curation.corrections.some(c=>c.code===r.code&&c.infiniteHp===!0),hitPoints=ctx.curation.corrections.find(c=>c.code===r.code&&c.hitPoints!==void 0)?.hitPoints,stage={stageNumber,...stageLabel?{stageLabel}:{},hp:infiniteHp?scalingOf(0,!1,!1):scalingOf(hitPoints??r.health??0,!!r.health_per_hero,!!r.health_per_group),...infiniteHp?{infiniteHp:!0}:{},atk:r.attack??0,sch:r.scheme??0,...statStarsField(r),...dashedStats.length>0?{dashedStats}:{},text:p.text,traits:stageTraits,keywords:parsed.keywords,abilities:abilityRefs(ctx,r.code,p.name,parsed.abilities),...stageImage?{image:stageImage}:{}};return ctx.handled.add(r.code),{stage,prepared:p,...activationOrder!==void 0?{activationOrder}:{}}}function normalizeVillains(ctx){let{errors,topLevel}=ctx,isVillainLike=r=>r.type_code==="villain"||r.type_code==="leader",villainSets=[...new Set(topLevel.filter(isVillainLike).map(r=>r.card_set_code??""))],villainIdBySet=new Map;for(let set of villainSets){let stageRecords=topLevel.filter(r=>isVillainLike(r)&&r.card_set_code===set).sort((x,y)=>stageOrder(x)-stageOrder(y)),printedType=stageRecords.some(r=>r.type_code==="leader")?"leader":void 0,flipSet=ctx.curation.villainFlipSets?.includes(set)===!0,faceRecords=stageRecords.filter(r=>FACE_LABEL_RE.test(r.stage??"")||flipSet&&r.linked_card?.type_code==="villain");if(faceRecords.length>0){let modeOf=r=>(FACE_LABEL_RE.exec(r.stage??"")??[])[1]??"",modes=[...new Set(faceRecords.map(modeOf))];for(let mode of modes)for(let r of faceRecords.filter(rec=>modeOf(rec)===mode)){let linked=r.linked_card;if(!linked||linked.type_code!=="villain"){errors.push(`${r.code}: expected a mode+face villain stage linked to its other face`);continue}let front=buildVillainStage(ctx,r),back=buildVillainStage(ctx,linked);front.prepared.name!==back.prepared.name&&!ctx.curation.villainFaceNamesMayDiffer?.includes(set)&&errors.push(`${r.code}: villain face names differ`);let backStageNumber=back.stage.infiniteHp===!0?2:1,card2={...baseFields(ctx,front.prepared,front.prepared.raw.code,[r.code,linked.code],null),type:"villain",encounterSetIds:[brand("encounterSet",set)],sides:[{side:"A",name:front.prepared.name,stages:[{...front.stage,stageNumber:1}]},{side:"B",name:back.prepared.name,stages:[{...back.stage,stageNumber:backStageNumber}]}],...printedType?{printedType}:{},...front.activationOrder!==void 0||back.activationOrder!==void 0?{activationOrder:front.activationOrder??back.activationOrder}:{}};ctx.faceCodesByCardId.set(card2.id,[r.code,linked.code]),record(ctx,card2,set,[front.prepared,back.prepared])}if(stageRecords.splice(0,stageRecords.length,...stageRecords.filter(r=>!faceRecords.includes(r))),stageRecords.length===0)continue}let versionPairs=stageRecords.length>0&&stageRecords.every(r=>r.linked_card?.type_code==="villain"&&stageOrder(r.linked_card)!==stageOrder(r));if(versionPairs){let faces=stageRecords.flatMap(r=>[r.linked_card,r]);if(new Set(faces.map(stageOrder)).size!==faces.length||ctx.curation.separateVillainVersions?.includes(set)){for(let r of stageRecords){let pair=[r,r.linked_card].sort((x,y)=>stageOrder(x)-stageOrder(y)),built=pair.map(face=>buildVillainStage(ctx,face)),[first2,second]=built;if(!(!first2||!second)){first2.prepared.name!==second.prepared.name&&errors.push(`${r.code}: villain version names differ`);for(let[i,one]of built.entries()){let face=pair[i],card2={...baseFields(ctx,one.prepared,face.code,[face.code],null),type:"villain",encounterSetIds:[brand("encounterSet",set)],sides:[{side:"A",name:one.prepared.name,stages:[one.stage]}],...printedType?{printedType}:{}};ctx.faceCodesByCardId.set(card2.id,[face.code]),record(ctx,card2,set,[one.prepared])}}}continue}stageRecords.splice(0,stageRecords.length,...faces.sort((x,y)=>stageOrder(x)-stageOrder(y)))}let doubleSided=!versionPairs&&stageRecords.some(r=>r.linked_card?.type_code==="villain");if(!doubleSided){let stageNumbers=stageRecords.map(stageOrder);if(new Set(stageNumbers).size!==stageNumbers.length){let baseTitleOf=r=>{let m=/^(.*) (I{1,3}|IV|V)$/.exec(r.name??"");return m&&ROMAN[m[2]]!==void 0?m[1]:r.name??""},groups=new Map;for(let r of stageRecords){let title=baseTitleOf(r),group=groups.get(title)??[];group.push(r),groups.set(title,group)}let groupList=[...groups.values()],isGaplessRun=recs=>recs.map(stageOrder).sort((x,y)=>x-y).every((n,i)=>n===i+1),parallelVillains=groupList.length>1&&groupList.every(isGaplessRun);for(let group of parallelVillains?groupList:stageRecords.map(r=>[r])){let sorted=[...group].sort((x,y)=>stageOrder(x)-stageOrder(y)),stages2=[],parts2=[],activationOrder2;for(let r of sorted){let{stage,prepared,activationOrder:ao}=buildVillainStage(ctx,r);stages2.push(stage),parts2.push(prepared),activationOrder2??=ao}let first2=parts2[0],firstStage2=stages2[0];if(!first2||!firstStage2)continue;new Set(parts2.map(p=>p.name)).size!==1&&errors.push(`villain set ${set}: stage names differ`);let card2={...baseFields(ctx,first2,first2.raw.code,parts2.map(p=>p.raw.code),null),type:"villain",encounterSetIds:[brand("encounterSet",set)],sides:[{side:"A",name:first2.name,stages:[firstStage2,...stages2.slice(1)]}],...printedType?{printedType}:{},...activationOrder2!==void 0?{activationOrder:activationOrder2}:{}};ctx.faceCodesByCardId.set(card2.id,parts2.map(p=>p.raw.code)),record(ctx,card2,set,parts2)}continue}}if(doubleSided){let linkedRecords=stageRecords.filter(r=>r.linked_card?.type_code==="villain").sort((x,y)=>stageOrder(x)-stageOrder(y)),unlinkedExtras=stageRecords.filter(r=>r.linked_card?.type_code!=="villain").sort((x,y)=>stageOrder(x)-stageOrder(y)),threeSided=unlinkedExtras.length>0&&unlinkedExtras.length===linkedRecords.length,stagesA=[],stagesB=[],stagesC=[],partsA=[],partsB=[],partsC=[],codes=[],activationOrder2;for(let i=0;i<linkedRecords.length;i++){let r=linkedRecords[i],linked=r.linked_card;if(!linked||linked.type_code!=="villain"){errors.push(`${r.code}: expected a double-sided villain stage linked to another villain record`);continue}let frontIsA=ctx.curation.villainFrontIsSideA?.includes(set)===!0,{stage:stageB,prepared:pB,activationOrder:aoB}=buildVillainStage(ctx,frontIsA?linked:r),{stage:stageA,prepared:pA,activationOrder:aoA}=buildVillainStage(ctx,frontIsA?r:linked);if(stagesA.push(stageA),stagesB.push(stageB),partsA.push(pA),partsB.push(pB),codes.push(...frontIsA?[r.code,linked.code]:[linked.code,r.code]),activationOrder2??=aoA??aoB,threeSided){let c=unlinkedExtras[i];stageOrder(c)!==stageOrder(r)&&errors.push(`${c.code}: three-sided villain stage does not line up with ${r.code}'s stage`);let{stage:stageC,prepared:pC,activationOrder:aoC}=buildVillainStage(ctx,c);stagesC.push(stageC),partsC.push(pC),codes.push(c.code),activationOrder2??=aoC}}let firstA=partsA[0],firstB=partsB[0],firstC=partsC[0],firstStageA=stagesA[0],firstStageB=stagesB[0],firstStageC=stagesC[0];if(!firstA||!firstB||!firstStageA||!firstStageB)continue;new Set(partsA.map(p=>p.name)).size!==1&&errors.push(`villain set ${set}: side A stage names differ`),new Set(partsB.map(p=>p.name)).size!==1&&errors.push(`villain set ${set}: side B stage names differ`),threeSided&&new Set(partsC.map(p=>p.name)).size!==1&&errors.push(`villain set ${set}: side C stage names differ`);let sides=[{side:"A",name:firstA.name,stages:[firstStageA,...stagesA.slice(1)]},{side:"B",name:firstB.name,stages:[firstStageB,...stagesB.slice(1)]}];threeSided&&firstC&&firstStageC&&sides.push({side:"C",name:firstC.name,stages:[firstStageC,...stagesC.slice(1)]});let card2={...baseFields(ctx,firstA,firstA.raw.code,codes,null),type:"villain",encounterSetIds:[brand("encounterSet",set)],sides,startingSide:"A",...printedType?{printedType}:{},...activationOrder2!==void 0?{activationOrder:activationOrder2}:{}};villainIdBySet.set(set,card2.id),ctx.faceCodesByCardId.set(card2.id,[...partsA.map(p=>p.raw.code),...partsB.map(p=>p.raw.code),...threeSided?partsC.map(p=>p.raw.code):[]]),record(ctx,card2,set,[...partsA,...partsB,...partsC]);continue}let stages=[],parts=[],activationOrder;for(let r of stageRecords){let{stage,prepared,activationOrder:ao}=buildVillainStage(ctx,r);stages.push(stage),parts.push(prepared),activationOrder??=ao}let first=parts[0],firstStage=stages[0];if(!first||!firstStage)continue;new Set(parts.map(p=>p.name)).size!==1&&errors.push(`villain set ${set}: stage names differ`);let labelled=stages.map(s=>s.stageLabel!==void 0);labelled.some(Boolean)&&!labelled.every(Boolean)&&errors.push(`villain set ${set}: some stages are labelled ("A"/"B") and some are not`);let card={...baseFields(ctx,first,first.raw.code,parts.map(p=>p.raw.code),null),type:"villain",encounterSetIds:[brand("encounterSet",set)],sides:[{side:"A",name:first.name,stages:[firstStage,...stages.slice(1)]}],...printedType?{printedType}:{},...activationOrder!==void 0?{activationOrder}:{}};villainIdBySet.set(set,card.id),ctx.faceCodesByCardId.set(card.id,parts.map(p=>p.raw.code)),record(ctx,card,set,parts)}return villainIdBySet}function normalizePack(raw,curation){let ctx=createContext(raw,curation),separateDecks=collectSeparateDecks(ctx);normalizeHeroes(ctx,separateDecks.byIdentity);let villainIdBySet=normalizeVillains(ctx),mainSchemeIdBySet=normalizeMainSchemes(ctx);normalizeSingleCards(ctx,separateDecks.ofCode),checkStaleCuration(ctx);let{encounterSets,setNames}=normalizeEncounterSets(ctx),scenarios=normalizeScenarios(ctx,{setNames,villainIdBySet,mainSchemeIdBySet}),starterDecks=normalizeStarterDecks(ctx);if(checkCoverage(ctx),ctx.errors.length>0)throw new Error(`Normalization of pack "${curation.packCode}" failed:
21
+ - ${ctx.errors.join(`
22
+ - `)}`);let order=(a,b)=>{let ka="id"in a?a.id:a.cardId,kb="id"in b?b.id:b.cardId;return ka.localeCompare(kb)};return{cycle:{id:ctx.cycleId,name:curation.cycle.name,order:curation.cycle.order},pack:{code:ctx.setCode,name:curation.pack.name,cycleId:ctx.cycleId,releaseDate:curation.pack.releaseDate},cards:ctx.cards.sort(order),encounterSets,scenarios,starterDecks,provenance:ctx.provenance.sort(order),dropped:[...ctx.dropped].sort((a,b)=>a.marvelcdbCode.localeCompare(b.marvelcdbCode))}}registerMarvelCdbNormalizer(normalizePack);export{registerMarvelCdbNormalizer,importMarvelCdbPack,formatImportReport};