@storylet-studio/play-helpers 0.11.0 → 0.11.1

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.
@@ -1,4 +1,4 @@
1
- "use strict";var StoryletEngine=(()=>{var Re=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var er=Object.getOwnPropertyNames;var tr=Object.prototype.hasOwnProperty;var rr=(n,e)=>{for(var t in e)Re(n,t,{get:e[t],enumerable:!0})},nr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of er(e))!tr.call(n,s)&&s!==t&&Re(n,s,{get:()=>e[s],enumerable:!(r=Zt(e,s))||r.enumerable});return n};var sr=n=>nr(Re({},"__esModule",{value:!0}),n);var Hr={};rr(Hr,{DURABLE_SCHEMA:()=>de,Engine:()=>ve,Flow:()=>ae,StoryletError:()=>b,applyLiveBundle:()=>Xt,boardFrame:()=>Xe,createBundleInspector:()=>Jt,createKernelStateLogger:()=>re,createLiveLink:()=>Qt,createPropertyInspector:()=>Kt,createStateLogger:()=>zt,createWorldContainer:()=>Yt,describeBundle:()=>Se,deserializeState:()=>ke,diffState:()=>te,ensureInspectorStyle:()=>le,formatLogEntry:()=>Ke,formatPropertySummary:()=>Je,formatScopeLabel:()=>Qe,loadState:()=>We,makePrng:()=>V,saveState:()=>Ue,serializeState:()=>Ee,shuffleInPlace:()=>H,snapshotState:()=>_t});function Q(n,e){return n!==void 0&&Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0}function j(n){switch(n[0]){case"b":return{kind:"bool",value:n[1]};case"n":return{kind:"number",value:n[1]};case"s":return{kind:"string",value:n[1]};case"sv":return{kind:"scopedvar",scope:n[1],name:n[2]};case"u":return{kind:"unary",op:n[1],operand:j(n[2])};case"bin":return{kind:"binary",op:n[1],left:j(n[2]),right:j(n[3])};case"call":{let e=n.slice(2).map(j);return{kind:"call",name:n[1],args:e}}case"fd":return{kind:"flagdelta",sign:n[1],name:n[2]}}}var S=class extends Error{constructor(e){super(e),this.name="EvalError"}};function ue(n,e,t){let r=new Map(t.scopes.map(o=>[o.token,o.missing??"false"])),s=o=>{switch(o.kind){case"bool":return o.value;case"number":return o.value;case"string":return o.value;case"scopedvar":{let i=Q(e.scopes,o.scope);if(i===void 0)return!1;let a=typeof i.get=="function"?i.get(o.name):Q(i,o.name);if(a===void 0){if(r.get(o.scope)==="throw")throw new S(`@${o.scope}.${o.name} is not declared on the current ${o.scope}.`);return!1}return a}case"call":{if(o.name==="advance"&&!Q(t.functions,o.name)){let a=o.args[0];if(o.args.length!==1||a===void 0)throw new S(`advance() takes exactly 1 argument, got ${o.args.length}`);let d=Me(a,e);if(d===void 0)throw new S("advance() needs a quality reference (@scope.name of a quality property)");let l=T(s(a),d,"advance");return d[Math.min(l+1,d.length-1)]}let i=Q(t.functions,o.name);if(!i)throw new S(`unknown function '${o.name}'`);return i.eval(o.args,{evaluate:s,ctx:e})}case"flagdelta":throw new S("flagdelta node is only valid as an argument to a flag-delta function");case"unary":{if(o.op==="not"){let a=s(o.operand);if(typeof a!="boolean")throw new S(`'not' requires a boolean operand, got ${typeof a}`);return!a}let i=s(o.operand);if(typeof i!="number")throw new S(`unary '-' requires a numeric operand, got ${typeof i}`);return-i}case"binary":{if(o.op==="and"){let p=s(o.left);if(typeof p!="boolean")throw new S(`'and' requires boolean operands, left is ${typeof p}`);if(!p)return!1;let g=s(o.right);if(typeof g!="boolean")throw new S(`'and' requires boolean operands, right is ${typeof g}`);return g}if(o.op==="or"){let p=s(o.left);if(typeof p!="boolean")throw new S(`'or' requires boolean operands, left is ${typeof p}`);if(p)return!0;let g=s(o.right);if(typeof g!="boolean")throw new S(`'or' requires boolean operands, right is ${typeof g}`);return g}let i=s(o.left),a=s(o.right),d=Me(o.left,e),l=Me(o.right,e),c=d??l;if(c!==void 0){if(d&&l&&!or(d,l)&&(o.op===">"||o.op===">="||o.op==="<"||o.op==="<="))throw new S(`'${o.op}' compares two different qualities, whose stage orders are unrelated`);switch(o.op){case">":return T(i,c,">")>T(a,c,">");case">=":return T(i,c,">=")>=T(a,c,">=");case"<":return T(i,c,"<")<T(a,c,"<");case"<=":return T(i,c,"<=")<=T(a,c,"<=");case"+":case"-":case"*":case"/":throw new S(`'${o.op}' cannot be applied to a quality - a stage is a position, not a number; use advance() to move it`);default:break}}switch(o.op){case"==":return at(i,a);case"!=":return!at(i,a);case">":return N(i,a,">"),i>a;case">=":return N(i,a,">="),i>=a;case"<":return N(i,a,"<"),i<a;case"<=":return N(i,a,"<="),i<=a;case"+":if(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string")return i+a;throw new S(`'+' requires two numbers or two strings, got ${typeof i} and ${typeof a}`);case"-":return N(i,a,"-"),i-a;case"*":return N(i,a,"*"),i*a;case"/":if(N(i,a,"/"),a===0)throw new S("division by zero");return i/a}}}};return s(n)}function at(n,e){if(Array.isArray(n)||Array.isArray(e)){if(!Array.isArray(n)||!Array.isArray(e)||n.length!==e.length)return!1;let t=[...n].sort(),r=[...e].sort();for(let s=0;s<t.length;s++)if(t[s]!==r[s])return!1;return!0}return n===e}function N(n,e,t){if(typeof n!="number"||typeof e!="number")throw new S(`'${t}' requires numeric operands, got ${typeof n} and ${typeof e}`)}function Me(n,e){if(!(n.kind!=="scopedvar"||e.qualities===void 0))return e.qualities(n.scope,n.name)}function T(n,e,t){if(typeof n!="string")throw new S(`'${t}' on a quality compares stages, got ${typeof n}`);let r=e.indexOf(n);if(r<0)throw new S(`"${n}" is not a stage of this quality (stages: ${e.join(", ")})`);return r}var or=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]);function dt(n){if(Number.isNaN(n)||!Number.isFinite(n))return 0;let e=Math.trunc(n)%4294967296;return e<0?e+4294967296:e}function V(n){let e=dt(n);return{next(){e=e+1831565813>>>0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296},state(){return e}}}function H(n,e){for(let t=n.length-1;t>0;t--){let r=Math.floor(e.next()*(t+1));[n[t],n[r]]=[n[r],n[t]]}}var ir={name:"check_flags",count:n=>Math.max(1,n.args.length-1)},ar=[ir];function lt(n,e,t){let r=t?.countingCalls??ar;return ge(n,t?.want??!0,e,r)}function ge(n,e,t,r){if(n.kind==="binary"&&(n.op==="and"||n.op==="or")){let s=ge(n.left,e,t,r),o=ge(n.right,e,t,r);return n.op==="and"===e?s>0&&o>0?s+o:0:Math.max(s,o)}if(n.kind==="unary"&&n.op==="not")return ge(n.operand,!e,t,r);if(n.kind==="call"){let s=r.find(o=>o.name===n.name);if(s){let o=s.count(n),i=t(n);return e?i?o:0:i?0:1}}return t(n)===e?1:0}var ct=[{token:"patter",engine:"Patterplay",means:"Patter's shared globals"},{token:"story",engine:"Storylet Engine",means:"the Storylet Engine's shared @story properties"}];var fe=9999,X=n=>n.ctx.host??{},z=(n,e,t,r)=>{let s=t.evaluate(e[r]);if(typeof s!="string"||s==="")throw new S(`${n}() argument ${r+1} must be a non-empty string`);return s},pt=(n,e,t)=>{if(e.length===0)throw new S(`${n}() requires at least one argument (the flags property)`);let r=t.evaluate(e[0]);if(Array.isArray(r))return r;if(r===!1)return[];throw new S(`${n}() first argument must be a flags property`)},ut=["story","world","box","deck","hand"],dr=ct.map(n=>n.token).filter(n=>!ut.includes(n)),Le={scopes:[...ut.map(n=>({token:n,missing:"throw"})),...dr.map(n=>({token:n,missing:"throw"}))],defaultScope:"story",functions:{random:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){if(n.length!==2)throw new S("random(a, b) requires exactly 2 arguments");let t=X(e).nextRandom;if(!t)throw new S("random() called without a PRNG in context");let r=e.evaluate(n[0]),s=e.evaluate(n[1]);if(typeof r!="number"||typeof s!="number")throw new S("random(a, b) arguments must be numbers");if(!Number.isInteger(r)||!Number.isInteger(s))throw new S("random(a, b) arguments must be integers");let o=Math.min(r,s),i=Math.max(r,s);return Math.floor(t()*(i-o+1))+o}},check_flags:{minArgs:1,returnType:"boolean",flagDeltaArgs:!0,eval(n,e){let t=pt("check_flags",n,e);for(let r=1;r<n.length;r++){let s=n[r];if(s.kind!=="flagdelta")throw new S("check_flags() flag args must be +flagName or -flagName");if(s.sign==="+"?!t.includes(s.name):t.includes(s.name))return!1}return!0}},set_flags:{minArgs:1,returnType:"flags",flagDeltaArgs:!0,eval(n,e){let t=[...pt("set_flags",n,e)];for(let r=1;r<n.length;r++){let s=n[r];if(s.kind!=="flagdelta")throw new S("set_flags() flag args must be +flagName or -flagName");if(s.sign==="+")t.includes(s.name)||t.push(s.name);else{let o=t.indexOf(s.name);o>=0&&t.splice(o,1)}}return t.sort()}},count_played:{minArgs:1,maxArgs:1,returnType:"number",eval(n,e){let t=z("count_played",n,e,0),r=X(e).countPlayed;if(!r)throw new S("count_played() called without a play log in context");return r(t)}},turns_since_played:{minArgs:1,maxArgs:1,returnType:"number",eval(n,e){let t=z("turns_since_played",n,e,0),r=X(e).turnsSincePlayed;if(!r)throw new S("turns_since_played() called without a play log in context");return r(t)}},count_played_in:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){let t=z("count_played_in",n,e,0),r=z("count_played_in",n,e,1),s=X(e).countPlayedIn;if(!s)throw new S("count_played_in() called without a play log in context");return s(t,r)}},turns_since_played_in:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){let t=z("turns_since_played_in",n,e,0),r=z("turns_since_played_in",n,e,1),s=X(e).turnsSincePlayedIn;if(!s)throw new S("turns_since_played_in() called without a play log in context");return s(t,r)}}}};function lr(n){return n.toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function f(n){let e=n.gameId?.trim();return e||(n.title?lr(n.title):"")||n.id}function gt(n){let e=[];for(let a of n.boxes){let d=f(a);for(let l of a.tagGroups)for(let c of l.tags){let p=f(c);e.push({id:c.id,gameId:p,qualified:`${d}/${p}`})}}let t=new Map;for(let a of e){let d=t.get(a.gameId)??[];d.includes(a.qualified)||d.push(a.qualified),t.set(a.gameId,d)}let r=new Map,s=new Map,o=new Map,i=new Map;for(let a of e){let d=t.get(a.gameId)??[a.qualified],l=d.length>1;r.set(a.id,l?a.qualified:a.gameId),s.has(a.qualified)||s.set(a.qualified,a.id),!l&&!s.has(a.gameId)&&s.set(a.gameId,a.id),l&&o.set(a.gameId,d)}for(let a of n.map?.group.tags??[]){let d=f(a);r.set(a.id,d),s.has(d)||s.set(d,a.id);for(let l of n.boxes)i.set(`${f(l)}/${d}`,d)}return{print:r,accept:s,repeated:o,zoneQualified:i}}function ft(n,e,t){return`"value.${n}.${t}": "${e}" is a zone of the project map, which belongs to no box; write "value.${e}.${t}"`}function ht(n,e,t){let r=t.map(o=>`"value.${o}.${e}"`),s=r.length<=1?r[0]??"":`${r.slice(0,-1).join(", ")} or ${r[r.length-1]}`;return`"value.${n}.${e}" names a tag in ${t.length} boxes; write ${s}`}var L="place",cr=/^@(hand|world|story)\.([a-z][a-z0-9_-]*)$/,he=n=>n.startsWith("@"),mt=n=>{let e=cr.exec(n);return e===null?void 0:{scope:e[1],name:e[2]}},pr="storylets/bundle@1",ur="storylets/bundle@0",Ie=[ur,pr];function Y(n,e){return e.usesMap===!0&&n.map!==void 0?[...e.tagGroups,n.map.group]:e.tagGroups}function yt(n){let e=n.boxes.flatMap(t=>t.tagGroups);return n.map!==void 0?[...e,n.map.group]:e}var Z="storylets/save@2",ee="storylets/save@1",me="storylets/savefile@1";function te(n,e){let t=[],r=new Set([...Object.keys(n),...Object.keys(e)]);for(let s of[...r].sort()){let o=n[s],i=e[s];JSON.stringify(o)!==JSON.stringify(i)&&t.push({path:s,from:o,to:i})}return t}var wt=n=>n===void 0?"<unset>":JSON.stringify(n),bt=n=>n.pathPrefix??n.bag.pathPrefix;function re(n,e={}){let t=e.sink??(p=>console.log(p)),r=e.label??"",s=p=>{t(`${r}${p.path}: ${wt(p.from)} -> ${wt(p.to)}`)},o=()=>{let p={};for(let g of n.mounts()){let u=bt(g);for(let[m,h]of Object.entries(g.bag.values))p[u+m]=h}return Object.assign(p,n.extra?.()??{}),structuredClone(p)},i=o(),a=[],d=[],l=(p,g)=>g.onAudit(u=>{let m=structuredClone({path:p+u.name,from:u.prev,to:u.next});s(m),a.push(m),i[m.path]=structuredClone(u.next)}),c=()=>{let p=n.mounts();if(!(d.length===p.length&&p.every((u,m)=>d[m].bag===u.bag))){for(let u of d)u.off();d=p.map(u=>({bag:u.bag,off:l(bt(u),u.bag)}))}};return c(),{snapshot:o,capture(){let p=o(),g=te(i,p);for(let m of g)s(m);let u=[...a,...g];return a=[],i=p,c(),u},dispose(){for(let p of d)p.off();d=[],a=[]}}}var F=class n{values=Object.create(null);decls=new Map;subscribers=new Set;auditors=new Set;norm;pathPrefix;constructor(e=[],t){this.norm=t?.normalise??(r=>r.toLowerCase()),this.pathPrefix=t?.pathPrefix??"",this.seed(e)}seed(e){for(let t of e){let r=this.norm(t.name);this.decls.set(r,t),this.values[r]=structuredClone(t.default??we(t))}}get(e){return this.values[this.norm(e)]}normalise(e){return this.norm(e)}writable(e){return this.decls.get(this.norm(e))?.writable!==!1}set(e,t,r){let s=this.norm(e);if(!r?.host&&!this.writable(s))throw new Error(`'${e}' is read-only`);let o={name:s,prev:this.values[s],next:t,silent:r?.silent??!1,reason:r?.reason};this.values[s]=t;for(let i of[...this.auditors])i(o);if(!o.silent)for(let i of[...this.subscribers])i(o);return o}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}onAudit(e){return this.auditors.add(e),()=>this.auditors.delete(e)}rows(){return[...this.decls.entries()].map(([e,t])=>xt(t,this.get(e),void 0,e,this.pathPrefix))}declarations(){return[...this.decls.values()]}clone(){let e=new n([],{normalise:this.norm,pathPrefix:this.pathPrefix});return e.decls=new Map(this.decls),Object.assign(e.values,structuredClone(this.values)),e}reseed(e){for(let t of Object.keys(this.values))delete this.values[t];this.decls.clear(),this.seed(e)}save(){return structuredClone(this.values)}load(e){for(let[t,r]of Object.entries(e))this.values[this.norm(t)]=r}};function xt(n,e,t,r,s=""){let o=r??n.name.toLowerCase();return{name:o,path:s+o,type:n.type,value:e,default:n.default??we(n),...n.values!==void 0?{values:n.values}:{},...n.stages!==void 0?{stages:n.stages}:{},writable:t??n.writable??!0}}var gr=n=>n.toLowerCase(),De=1,ye=class{scopes=new Map;parked=new Map;rev=0;get revision(){return this.rev}defineOwned(e,t,r){let s=typeof r=="string"?{pathPrefix:r}:r??{},o=new F(t,{pathPrefix:s.pathPrefix??`${e}.`,...s.normalise?{normalise:s.normalise}:{}});return this.mountOwned(e,o,s.owner!==void 0?{owner:s.owner}:void 0)}mountOwned(e,t,r){this.assertFree(e,r?.owner),this.scopes.set(e,{kind:"owned",bag:t,...r?.owner!==void 0?{owner:r.owner}:{}}),this.rev++;let s=this.parked.get(e);return s&&(t.load(s),this.parked.delete(e)),this}remove(e,t){let r=this.scopes.get(e);if(!r)throw new Error(`unknown scope '@${e}'`);return t?.keep&&r.kind==="owned"&&this.parked.set(e,r.bag.save()),this.scopes.delete(e),this.rev++,this}discardParked(e){if(e===void 0)this.parked.clear();else for(let t of[...this.parked.keys()])t.startsWith(e)&&this.parked.delete(t);return this}ownedBag(e){let t=this.scopes.get(e);if(!t||t.kind!=="owned")throw new Error(`'@${e}' is not an owned scope`);return t.bag}reseedOwned(e,t){return this.ownedBag(e).reseed(t),this}defineForeign(e,t,r=[],s=!0){let o=typeof s=="boolean"?{writable:s}:s;this.assertFree(e,o.owner);let i=o.normalise??gr,a=new Map;for(let d of r)a.set(i(d.name),d);return this.scopes.set(e,{kind:"foreign",resolver:t,decls:a,scopeWritable:o.writable??!0,norm:i,...o.owner!==void 0?{owner:o.owner}:{}}),this.rev++,this}has(e){return this.scopes.has(e)}get(e,t){let r=this.scopes.get(e);if(r)return r.kind==="owned"?r.bag.get(t):r.resolver.get(r.norm(t))}set(e,t,r,s){let o=this.scopes.get(e);if(!o)throw new Error(`unknown scope '@${e}'`);if(o.kind==="owned"){if(!s?.host&&!o.bag.writable(t))throw new Error(`'@${e}.${t}' is read-only`);o.bag.set(t,r,s?.host?{host:!0}:void 0);return}let i=o.norm(t);if(!o.resolver.set)throw new Error(`'@${e}.${t}' is read-only`);if(!s?.host&&!this.foreignWritable(o,i))throw new Error(`'@${e}.${t}' is read-only`);o.resolver.set(i,r)}foreignWritable(e,t){return e.resolver.set?e.decls.get(t)?.writable??e.scopeWritable:!1}listProperties(){let e=[];for(let[t,r]of this.scopes){let s=r.owner!==void 0?{owner:r.owner}:{};if(r.kind==="owned")for(let o of r.bag.rows())e.push({scope:t,...s,...o});else for(let[o,i]of r.decls)e.push({scope:t,...s,...xt(i,r.resolver.get(o),this.foreignWritable(r,o),o,`${t}.`)})}return e}toEvalContext(e,t){let r=this.view(t?.aliases),s={};for(let[i,a]of r)s[i]=a.kind==="owned"?a.bag.values:a.resolver;let o=this.qualityLadders(r);return o.size===0?{scopes:s,host:e}:{scopes:s,host:e,qualities:(i,a)=>{let d=r.get(i);return d?o.get(i)?.get(fr(d)(a)):void 0}}}view(e){let t=new Map(this.scopes);for(let[r,s]of Object.entries(e??{})){let o=this.scopes.get(s);if(!o)throw new Error(`alias '@${r}' names '${s}', which is not registered`);t.set(r,o)}return t}qualityLadders(e){let t=new Map;for(let[r,s]of e)for(let[o,i]of vt(s)){if(i.type!=="quality"||i.stages===void 0)continue;let a=t.get(r);a||(a=new Map,t.set(r,a)),a.set(o,i.stages)}return t}toSchema(e){let t=new Map;for(let[r,s]of this.view(e?.aliases)){let o=vt(s);if(o.length===0)continue;let i=new Map;for(let[a,d]of o)i.set(a,{type:d.type,enumValues:d.values,...d.stages!==void 0?{stages:d.stages}:{}});t.set(r,i)}return{properties:t}}save(){let e={};for(let[t,r]of this.scopes)r.kind==="owned"&&(e[t]=r.bag.save());for(let[t,r]of this.parked)e[t]=structuredClone(r);return e}load(e,t){t?.keepParked||this.parked.clear();for(let[r,s]of Object.entries(e)){let o=this.scopes.get(r);o?.kind==="owned"?o.bag.load(s):o||this.parked.set(r,structuredClone(s))}}saveFragment(){return{version:De,scopes:this.save()}}loadFragment(e){if(e.version!==De)throw new Error(`unsupported owned-state fragment version ${e.version} (supported: ${De})`);this.load(e.scopes)}assertFree(e,t){let r=this.scopes.get(e);if(!r)return;let s=r.owner!==void 0?` by ${r.owner}`:"",o=t!==void 0?` (wanted by ${t})`:"";throw new Error(`scope '@${e}' is already registered${s}${o}`)}};function vt(n){return n.kind==="foreign"?[...n.decls.entries()]:n.bag.declarations().map(e=>[n.bag.normalise(e.name),e])}function fr(n){return n.kind==="foreign"?n.norm:e=>n.bag.normalise(e)}function we(n){if(n.default!==void 0)return n.default;switch(n.type){case"boolean":return!1;case"number":return 0;case"string":return"";case"enum":return n.values?.[0]??"";case"flags":return[];case"quality":return n.stages?.[0]??"";default:return!1}}var St=(n,e,t)=>`${n}${e}${t}`,b=class extends Error{constructor(e){super(e),this.name="StoryletError"}},de="storylets/durable@1",oe=(n,e)=>n.shared??e,hr=(n,e)=>n.redraw==="never"&&(n.durable??e.durable??!1)===!0,Lt=n=>n.sharedCopies??n.copies??1,U="Storylet Engine",He=n=>n,qe=n=>n.replace(/%/g,"%25").replace(/\//g,"%2F"),Te=n=>n.replace(/%2F/g,"/").replace(/%25/g,"%"),Ae=(n,e)=>`storylets/${n}/${qe(e)}`,Fe=n=>`storylets/flow/${qe(n)}/`,_e=(n,e,t)=>e==="story"?`${Fe(n)}story`:`${Fe(n)}${e}/${qe(t)}`,ie=()=>({story:{},box:{},deck:{},hand:{},value:{}});function mr(n,e){let t=ie(),r=new Map,s={},o=i=>{let a=Te(i);if(!e.has(a))return;let d=r.get(a);return d||(d=ie(),r.set(a,d)),d};for(let[i,a]of Object.entries(n)){let d;if(i==="story")t.story=a;else if(d=/^storylets\/(box|deck|hand|value)\/([^/]+)$/.exec(i))t[d[1]][Te(d[2])]=a;else if(d=/^storylets\/flow\/([^/]+)\/story$/.exec(i)){let l=o(d[1]);l&&(l.story=a)}else if(d=/^storylets\/flow\/([^/]+)\/(box|deck|hand|value)\/([^/]+)$/.exec(i)){let l=o(d[1]);l&&(l[d[2]][Te(d[3])]=a)}else i.startsWith("storylets/")||(s[i]=a)}return{shared:t,flows:r,rest:s}}function Et(n,e,t){Object.keys(n.story).length>0&&(t[e("story")]=n.story);for(let r of O)for(let[s,o]of Object.entries(n[r]))Object.keys(o).length>0&&(t[e(r,s)]=o)}var kt=(n,e)=>new F(n,{normalise:He,pathPrefix:e}),R=(n,e)=>n!==void 0&&Object.prototype.hasOwnProperty.call(n.values,e)?n.values[e]:void 0,Ve=Object.freeze(Object.create(null));function Pt(n){return typeof n=="boolean"?n:typeof n=="number"?n!==0:typeof n=="string"?n!=="":n.length>0}var yr={story:!0,box:!1,deck:!1,hand:!1,value:!1},It=(n,e)=>e.shared??yr[n],wr=(n,e)=>e.filter(t=>It(n,t)),br=(n,e)=>e.filter(t=>!It(n,t)),O=["box","deck","hand","value"],Dt=n=>O.includes(n??""),be=()=>({gameId:new Map,id:new Map,repeated:new Map,zoneQualified:new Map}),vr=()=>({box:be(),deck:be(),hand:be(),value:be()}),je=(n,e)=>{let t=f(e);n.gameId.set(e.id,t),n.id.has(t)||n.id.set(t,e.id)},xr=(n,e)=>{let t=gt(e);for(let[r,s]of t.print)n.gameId.set(r,s);for(let[r,s]of t.accept)n.id.set(r,s);for(let[r,s]of t.repeated)n.repeated.set(r,s);for(let[r,s]of t.zoneQualified)n.zoneQualified.set(r,s)},Ct=(n,e)=>{let t=[],r=new Set,s=o=>{r.has(o.address)||(r.add(o.address),t.push(o))};for(let o of e.story)o.durable===!0&&s({address:`story.${o.name}`,kind:"story",decl:o});for(let o of O)for(let[i,a]of e[o])for(let d of a)d.durable===!0&&s({address:`${A(n,o,i)}.${d.name}`,kind:o,owner:i,decl:d});return t},ze=(n,e)=>e.kind==="story"?n.story:n[e.kind].get(e.owner),Tt=(n,e)=>{let t=[];for(let r of e){let s=R(ze(n,r),r.decl.name);s!==void 0&&t.push([r.address,s])}return Object.fromEntries(W(t,([r])=>r))};function Bt(n,e,t,r,s,o){let i=g=>({...s!==void 0?{flow:s}:{},path:g}),a=new Map(e.map(g=>[g.address,g])),d=new Map,l=r.values??{};for(let[g,u]of Object.entries(l)){let m=a.get(g);if(m===void 0){o.droppedProperties.push(i(g));continue}if(!Ht(m.decl,u)){o.retypedProperties.push(i(g));continue}d.set(m,u)}for(let g of e)Object.prototype.hasOwnProperty.call(l,g.address)||o.defaultedProperties.push(i(g.address));let c=new Set(t.map(g=>g.card.id)),p=[];for(let g of r.spent??[]){let u=n.cardsByGameId.get(g);u!==void 0&&c.has(u.card.id)?p.push(u.card.id):s!==void 0?o.droppedCooldowns.push({flow:s,card:g}):o.droppedSpent.push(g)}return{values:d,cards:p}}var $t=(n,e)=>{let t=e?.schema;if(t!==de)throw new b(`unsupported durable schema: ${String(t)}`);let r=n.bundle.content.project;if(e.content?.project!==r)throw new b(`durable state is for project "${String(e.content?.project)}", bundle is "${r}"`)},At=(n,e,t)=>{n?.set(e,structuredClone(t),{silent:!0,reason:"host durable",host:!0})},Ot=(n,e)=>e.template!==void 0?n.templatesById.get(e.template)?.properties??[]:e.properties??[],A=(n,e,t)=>`${e}.${n.owners[e].gameId.get(t)??t}`,Sr=(n,e,t)=>{let r=n.owners[e].repeated.get(t);if(r!==void 0)return{ambiguous:r};let s=n.owners[e].zoneQualified.get(t);if(s!==void 0)return{zone:s};let o=n.owners[e].id.get(t);if(o!==void 0)return{id:o,legacy:!1};if(n.owners[e].gameId.has(t))return{id:t,legacy:!0}},Vt=(n,e,t,r)=>{let s=Sr(n,e,t);if(s===void 0)throw new b(`no ${e} store "${t}"`);if("ambiguous"in s)throw new b(ht(t,r,s.ambiguous));if("zone"in s)throw new b(ft(t,s.zone,r));return s},jt=(n,e,t,r)=>`"${e}.${t}.${r}" names the ${e} by its internal id; write "${A(n,e,t)}.${r}". The internal-id form is refused after the next release.`,Nt=(n,e)=>{let t=r=>new Map([...e[r]].map(([s,o])=>[s,kt(o,`${A(n,r,s)}.`)]));return{story:kt(e.story,"story."),box:t("box"),deck:t("deck"),hand:t("hand"),value:t("value")}},Er=n=>({story:n.story.values,box:Object.fromEntries([...n.box].map(([e,t])=>[e,t.values])),deck:Object.fromEntries([...n.deck].map(([e,t])=>[e,t.values])),hand:Object.fromEntries([...n.hand].map(([e,t])=>[e,t.values])),value:Object.fromEntries([...n.value].map(([e,t])=>[e,t.values]))}),kr=(n,e)=>{n.story.load(e?.story??{});for(let t of O)for(let[r,s]of Object.entries(e?.[t]??{}))n[t].get(r)?.load(s)},ne=()=>({evicted:[],droppedCooldowns:[],droppedSpent:[],droppedProperties:[],defaultedProperties:[],retypedProperties:[]}),Ge="",W=(n,e)=>[...n].map(t=>({item:t,k:e(t)})).sort((t,r)=>t.k<r.k?-1:t.k>r.k?1:0).map(t=>t.item),Ne=n=>`${n.flow??""}${Ge}${n.path}`;function Ht(n,e){switch(n.type){case"boolean":return typeof e=="boolean";case"number":return typeof e=="number";case"string":return typeof e=="string";case"enum":return typeof e=="string"&&(n.values===void 0||n.values.includes(e));case"quality":return typeof e=="string"&&(n.stages===void 0||n.stages.includes(e));case"flags":return Array.isArray(e)&&e.every(t=>typeof t=="string"&&(n.values===void 0||n.values.includes(t)));default:return!0}}function Rt(n,e,t,r,s){let o=l=>({...r!==void 0?{flow:r}:{},path:t(l)}),i=new Map((n??[]).map(l=>[l.name,l])),a=e??{},d={};for(let[l,c]of Object.entries(a)){let p=i.get(l);if(p===void 0){s.droppedProperties.push(o(l));continue}if(!Ht(p,c)){s.retypedProperties.push(o(l));continue}d[l]=c}for(let l of n??[])l.name in a||s.defaultedProperties.push(o(l.name));return d}function Mt(n,e,t,r,s){let o={story:Rt(e.story,t?.story,i=>`story.${i}`,r,s),box:{},deck:{},hand:{},value:{}};for(let i of O){let a=t?.[i]??{},d=[...new Set([...e[i].keys(),...Object.keys(a)])].sort();for(let l of d){let c=A(n,i,l);o[i][l]=Rt(e[i].get(l),a[l],p=>`${c}.${p}`,r,s)}}return o}function se(n,e,t,r){let s=e.version!==n.version||e.hash!==n.hash,o=W(r.evicted,p=>[p.flow,p.hand,p.card,p.reason].join(Ge)),i=W(r.droppedCooldowns,p=>`${p.flow}${Ge}${p.card}`),a=[...r.droppedSpent].sort(),d=W(r.droppedProperties,Ne),l=W(r.defaultedProperties,Ne),c=W(r.retypedProperties,Ne);return{exact:!s&&o.length===0&&i.length===0&&a.length===0&&d.length===0&&l.length===0&&c.length===0,project:n.project,version:{saved:e.version,bundle:n.version},hash:{saved:e.hash,bundle:n.hash},flows:t,evicted:o,droppedCooldowns:i,droppedSpent:a,droppedProperties:d,defaultedProperties:l,retypedProperties:c}}var Pr=n=>{let e=n.schema;if(typeof e!="string"||!Ie.includes(e))throw new b(`unsupported bundle schema: ${String(e)} (this runtime reads ${Ie.join(" and ")})`);let t=[],r=n.map?.group,s=r!==void 0?f(r):void 0;r!==void 0&&s===L&&t.push(`the project map's tag group is called "${L}", which is reserved for a box's own hands`);let o=new Map;for(let i of n.boxes)for(let a of i.tagGroups)for(let d of a.tags){let l=f(d);o.has(l)||o.set(l,{box:f(i),group:f(a)})}for(let i of r?.tags??[]){let a=f(i),d=o.get(a);d!==void 0&&t.push(`the project map's zone "${a}" has the name of tag "${a}" in box "${d.box}", group "${d.group}", so "value.${a}.<name>" would name two things`)}for(let i of n.boxes){let a=f(i);if(i.usesMap===!0){if(r===void 0){t.push(`box "${a}" uses the project map, but the bundle has no map`);continue}i.tagGroups.find(c=>f(c)===s)!==void 0&&t.push(`box "${a}" uses the project map and declares its own tag group "${s}", the map's name`);continue}if(r===void 0)continue;let d=l=>{t.push(`box "${a}" is not on the project map, but ${l} names the map's tag group "${s}"`)};for(let l of i.decks)for(let c of l.cards)c.tags?.[r.id]!==void 0&&d(`card "${f(c)}"`);for(let l of i.handTemplates)(l.bindings?.[r.id]!==void 0||l.chooses?.includes(r.id)===!0)&&d(`hand template "${f(l)}"`);for(let l of i.hands)(l.chosen?.[r.id]!==void 0||l.rule?.bindings?.[r.id]!==void 0)&&d(`hand "${f(l)}"`)}if(t.length>0)throw new b(`bundle refused: ${t.join("; ")}`)},ve=class n{internals;seed;onReplacedFlow;flowsById=new Map;engineTraceHandlers=new Set;hostWorld;creationOptions;sharedMounts=[];constructor(e,t={}){Pr(e),this.creationOptions=t,this.seed=t.seed??0,this.onReplacedFlow=t.onReplacedFlow,t.world!==void 0&&(this.hostWorld=t.world);let r={bundle:e,...t.log?{logCap:typeof t.log=="object"?t.log.cap??1e3:1e3}:{},cardsById:new Map,cardsByGameId:new Map,boxesByGameId:new Map,boxesById:new Map,handsById:new Map,handsByGameId:new Map,owners:vr(),templatesById:new Map,groupsById:new Map,requiredGroups:new Set,nodeCache:new WeakMap,ladders:{world:new Map,story:new Map,box:new Map,deck:new Map,value:new Map,hand:new Map},hasQualities:!1,hasShared:!1,flowDecls:{story:[],box:new Map,deck:new Map,hand:new Map,value:new Map},sharedDecls:{story:[],box:new Map,deck:new Map,hand:new Map,value:new Map},durable:{shared:[],flow:[],sharedCards:[],flowCards:[]},shared:void 0,registry:t.registry??new ye,ownsRegistry:t.registry===void 0,selfWorld:!1,registryView:()=>i(),worldResolver:void 0,worldReadOnly:new Set,emitEngine:(d,l,c)=>{this.internals.logCap!==void 0&&(this.engineLog.push({...l,flow:d,seq:this.engineSeq++,...c!==void 0?{turn:c}:{}}),this.engineLog.length>this.internals.logCap&&this.engineLog.splice(0,this.engineLog.length-this.internals.logCap));for(let p of[...this.engineTraceHandlers])p(d,l)},engineTracing:()=>this.engineTraceHandlers.size>0};this.internals=r;let s=-1,o={scopes:{},qualities:void 0},i=()=>{let d=r.registry;if(d.revision!==s){let l=d.toEvalContext(),c={};for(let[p,g]of Object.entries(l.scopes))p.includes("/")||(c[p]=g);o={scopes:c,qualities:l.qualities},s=d.revision}return o};xr(r.owners.value,e);for(let d of e.boxes){r.boxesById.set(d.id,d),r.boxesByGameId.set(f(d),d),je(r.owners.box,d);for(let l of d.tagGroups)r.groupsById.set(l.id,{group:l,box:d}),l.required===!0&&r.requiredGroups.add(l.id);for(let l of d.decks){je(r.owners.deck,l),l.shared===!0&&(r.hasShared=!0);for(let c of l.cards){let p={card:c,deck:l,box:d};r.cardsById.set(c.id,p),r.cardsByGameId.set(f(c),p),c.shared===!0&&(r.hasShared=!0),hr(c,l)&&(oe(c,l.shared??!1)?r.durable.sharedCards:r.durable.flowCards).push(p)}}for(let l of d.handTemplates)r.templatesById.set(l.id,l);for(let l of d.hands)r.handsById.set(l.id,{hand:l,box:d}),r.handsByGameId.set(f(l),{hand:l,box:d}),je(r.owners.hand,l)}e.map!==void 0&&(r.groupsById.set(e.map.group.id,{group:e.map.group}),e.map.group.required===!0&&r.requiredGroups.add(e.map.group.id)),this.initLadders();let a=d=>({story:d("story",e.story.properties),box:new Map(e.boxes.map(l=>[l.id,d("box",l.properties)])),deck:new Map(e.boxes.flatMap(l=>l.decks.map(c=>[c.id,d("deck",c.properties)]))),hand:new Map(e.boxes.flatMap(l=>l.hands.map(c=>[c.id,d("hand",Ot(r,c))]))),value:new Map(yt(e).flatMap(l=>l.tags.map(c=>[c.id,d("value",c.properties??[])])))});r.flowDecls=a(br),r.sharedDecls=a(wr),r.durable.shared=Ct(r,r.sharedDecls),r.durable.flow=Ct(r,r.flowDecls),this.initShared(this.hostWorld)}initShared(e){let t=this.internals,r=t.registry,s=t.bundle.world.properties;t.shared=Nt(t,t.sharedDecls),t.worldReadOnly=new Set(t.bundle.world.properties.filter(a=>a.writable===!1).map(a=>a.name));let o=[],i=(a,d)=>{d(),o.push(a),this.sharedMounts.push({key:a,mount:d})};try{let a=t.shared.story;i("story",()=>{r.mountOwned("story",a,{owner:U})});for(let d of O)for(let[l,c]of t.shared[d])c.declarations().length!==0&&i(Ae(d,l),()=>{r.mountOwned(Ae(d,l),c,{owner:U})});if(e!==void 0)i("world",()=>{r.defineForeign("world",e,s,{normalise:He,owner:U})});else if(t.ownsRegistry&&!r.has("world")){r.defineOwned("world",s,{normalise:He,pathPrefix:"world.",owner:U});let d=r.ownedBag("world");o.push("world"),this.sharedMounts.push({key:"world",mount:()=>{r.mountOwned("world",d,{owner:U})}}),t.selfWorld=!0}}catch(a){for(let d of o)r.remove(d,{keep:!0});throw a}t.worldResolver={get:a=>r.get("world",a),set:(a,d)=>{r.set("world",a,d)}},e!==void 0?t.worldSet=e.set!==void 0?(a,d)=>{r.set("world",a,d,{host:!0})}:void 0:t.worldSet=(a,d,l)=>{r.set("world",a,d,l===!0?{host:!0}:void 0)}}reseedShared(){let{shared:e,sharedDecls:t,registry:r}=this.internals;e.story.reseed(t.story);for(let s of O)for(let[o,i]of e[s])i.reseed(t[s].get(o)??[]);this.internals.selfWorld&&r.reseedOwned("world",this.internals.bundle.world.properties)}initLadders(){let e=this.internals,t=o=>{let i=new Map;for(let a of o??[])a.type==="quality"&&a.stages!==void 0&&i.set(a.name,a.stages);return i},r=e.bundle;e.ladders.world=t(r.world.properties),e.ladders.story=t(r.story.properties);for(let o of r.boxes){e.ladders.box.set(o.id,t(o.properties));for(let i of o.decks)e.ladders.deck.set(i.id,t(i.properties));for(let i of o.tagGroups)for(let a of i.tags)e.ladders.value.set(a.id,t(a.properties));for(let i of o.hands)e.ladders.hand.set(i.id,t(Ot(e,i)))}for(let o of r.map?.group.tags??[])e.ladders.value.set(o.id,t(o.properties));let s=o=>[...o.values()].some(i=>i.size>0);e.hasQualities=e.ladders.world.size>0||e.ladders.story.size>0||s(e.ladders.box)||s(e.ladders.deck)||s(e.ladders.value)||s(e.ladders.hand)}get registry(){return this.internals.registry}openFlow(e,t={}){return this.open(e,t,!1)}open(e,t,r){if(t.durable!==void 0&&t.restore!==void 0)throw new b(`openFlow "${e}": restore and durable cannot be given together; a restore already carries the flow's durable state`);let s;if(t.durable!==void 0){$t(this.internals,t.durable);let d=ne(),{flow:l,flowCards:c}=this.internals.durable;s={plan:Bt(this.internals,l,c,t.durable,e,d),draft:d,content:t.durable.content}}this.assertExternalScopes();let o=t.restore!==void 0?this.sharedClaims(e):void 0,i=this.flowsById.get(e);if(i){let d=i.heldCardIds().length;d>0&&this.onReplacedFlow?.(e,d),i.markClosed()}r||this.internals.registry.discardParked(Fe(e));let a=new ae(this,this.internals,e,t.seed??this.seed);if(this.flowsById.set(e,a),t.restore!==void 0){let d=ne(),l=this.planFlowRestore(e,structuredClone(t.restore),o,d);a.restore(l);let c=this.internals.bundle.content;t.onRestoreReport?.(se(c,c,[e],d))}return s!==void 0&&(a.writeDurable(s.plan),t.onRestoreReport?.(se(this.internals.bundle.content,s.content,[e],s.draft))),a}getFlow(e){return this.flowsById.get(e)}flows(){return[...this.flowsById.values()]}closeFlow(e){let t=this.flowsById.get(e);t&&(this.flowsById.delete(e),t.markClosed())}dropFlow(e,t){this.flowsById.get(e)===t&&this.flowsById.delete(e)}reset(){this.dropRun(!1),this.reseedShared(),this.internals.registry.discardParked("storylets/")}dropRun(e){this.engineLog=[];for(let[t,r]of this.flowsById)r.releaseBags(e!==!1&&e.has(t)),r.markClosed();this.flowsById.clear(),this.spent.clear()}spent=new Set;isTaken(e){return this.spent.has(e)}markTaken(e){this.spent.add(e)}engineLog=[];engineSeq=0;log(){return this.engineLog}clearLog(){this.engineLog=[]}sharedClaims(e){let t=new Map;for(let[r,s]of this.flowsById)if(r!==e)for(let o of s.heldCardIds())t.set(o,(t.get(o)??0)+1);return t}getProperty(e){let t=this.resolveShared(e),r=t.kind==="world"?this.internals.worldResolver.get(t.name):t.kind==="scope"?this.internals.registry.get(t.token,t.name):t.bag.get(t.name);if(r===void 0)throw new b(`no property at "${e}"`);return r}setProperty(e,t){let r=this.resolveShared(e);if(r.kind==="world"){if(!this.internals.worldSet)throw new b("@world is read-only here: the host bound no write");this.internals.worldSet(r.name,t,!0);return}if(r.kind==="scope"){this.internals.registry.set(r.token,r.name,t,{host:!0});return}r.bag.set(r.name,t,{silent:!0,reason:"host setProperty",host:!0})}resolveShared(e){let t=e.split("."),r=()=>{throw new b(`"${e}" is per-flow state - read it on a Flow, not the Engine`)};if(t.length===2&&t[0]==="world")return{kind:"world",name:t[1]};if(t.length===2&&t[0]!=="story"&&this.internals.registry.has(t[0]))return{kind:"scope",token:t[0],name:t[1]};if(t.length===2&&t[0]==="story"){let s=t[1];if(R(this.internals.shared.story,s)!==void 0)return{kind:"bag",bag:this.internals.shared.story,name:s};throw this.internals.flowDecls.story.some(o=>o.name===s)&&r(),new b(`no property at "${e}"`)}if(t.length===3&&Dt(t[0])){let s=t[0],[,o,i]=t,a=Vt(this.internals,s,o,i);a.legacy&&this.diagnose(jt(this.internals,s,o,i));let d=a.id,l=this.internals.shared[s].get(d);if(l!==void 0&&R(l,i)!==void 0)return{kind:"bag",bag:l,name:i};throw this.internals.flowDecls[s].get(d)?.some(c=>c.name===i)&&r(),l===void 0&&!this.internals.flowDecls[s].has(d)?new b(`no ${s} store "${o}"`):new b(`no property at "${e}"`)}throw new b(`bad property path "${e}"`)}diagnose(e){this.internals.emitEngine("",{type:"diagnostic",where:"property address",message:e})}assertExternalScopes(){for(let e of this.internals.bundle.externalScopes??[])if(!this.internals.registry.has(e))throw new b(`this content names @${e}, which no engine on this registry registered: give every engine the game's one registry`)}listProperties(){let e=[];for(let r of this.internals.bundle.world.properties){let s=this.internals.worldResolver.get(r.name);e.push({path:`world.${r.name}`,name:r.name,type:r.type,value:s??r.default,default:r.default,...r.values!==void 0?{values:r.values}:{},...r.stages!==void 0?{stages:r.stages}:{},writable:this.internals.worldSet!==void 0&&!this.internals.worldReadOnly.has(r.name)})}let t=(r,s)=>{for(let o of s.rows())e.push(o)};t("story",this.internals.shared.story);for(let r of O)for(let[s,o]of this.internals.shared[r])t(A(this.internals,r,s),o);return e}listBags(){let e=[{prefix:"story",bag:this.internals.shared.story}];for(let t of O)for(let[r,s]of this.internals.shared[t])e.push({prefix:A(this.internals,t,r),bag:s});return e}subscribeTrace(e){return this.engineTraceHandlers.add(e),()=>{this.engineTraceHandlers.delete(e)}}hotSwap(e,t={}){if(e.content.project!==this.internals.bundle.content.project)throw new b(`hotSwap: the bundle is for project "${e.content.project}", this engine runs "${this.internals.bundle.content.project}"`);let r={...this.creationOptions,...t},s=this.saveGame(),o=this.internals.registry;if(this.internals.ownsRegistry){let c=new n(e,{...r,registry:void 0});return{engine:c,report:c.loadGame(s)}}let i={};for(let[c,p]of Object.entries(o.save()))(c==="story"||c.startsWith("storylets/"))&&(i[c]=p);let a=new Set([...this.sharedMounts.map(c=>c.key),...[...this.flowsById.values()].flatMap(c=>c.registeredKeys())]),d=Object.fromEntries(Object.entries(i).filter(([c])=>!a.has(c)));for(let{key:c}of this.sharedMounts)o.has(c)&&o.remove(c);for(let c of this.flowsById.values())c.releaseBags(!1);let l;try{l=new n(e,{...r,registry:o});let c=l.loadGame({...s,registry:i}),p=Object.fromEntries(Object.entries(d).filter(([g])=>!o.has(g)));return Object.keys(p).length>0&&o.load(p,{keepParked:!0}),this.dropRun(!1),{engine:l,report:c}}catch(c){l?.dropRun(!1);for(let{key:p}of l?.sharedMounts??[])o.has(p)&&o.remove(p);o.discardParked("storylets/");for(let{mount:p}of this.sharedMounts)p();for(let p of this.flowsById.values())p.mountBags();throw this.reseedShared(),o.load(i,{keepParked:!0}),c}}saveGame(){return structuredClone({schema:Z,content:this.internals.bundle.content,...this.internals.ownsRegistry?{registry:this.registrySection()}:{},shared:{spent:[...this.spent].sort()},flows:Object.fromEntries([...this.flowsById].map(([e,t])=>[e,t.snapshot(!1)]))})}registrySection(){let e=this.internals.registry.save(),t={},r=s=>{Object.prototype.hasOwnProperty.call(e,s)&&!Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=e[s])};for(let{key:s}of this.sharedMounts)r(s);for(let s of Object.values(Object.fromEntries(this.flowsById)))for(let o of s.registeredKeys())r(o);for(let s of Object.keys(e))r(s);return t}saveFlow(e){let t=this.flowsById.get(e);if(!t)throw new b(`unknown flow "${e}"`);return structuredClone(t.snapshot(!0))}saveDurable(){let{bundle:e,shared:t,durable:r}=this.internals;return structuredClone({schema:de,content:e.content,values:Tt(t,r.shared),spent:r.sharedCards.filter(s=>this.spent.has(s.card.id)).map(s=>f(s.card)).sort()})}loadDurable(e){let t=this.internals;$t(t,e);let r=ne(),s=Bt(t,t.durable.shared,t.durable.sharedCards,e,void 0,r);for(let o of t.durable.shared){let i=s.values.has(o)?s.values.get(o):we(o.decl);At(ze(t.shared,o),o.decl.name,i)}for(let o of s.cards)this.spent.add(o);return se(t.bundle.content,e.content,[],r)}previewLoad(e){return this.assertSameProject(e),this.planLoad(e).report}previewFlowRestore(e,t){let r=ne();this.planFlowRestore(e,t,this.sharedClaims(e),r);let s=this.internals.bundle.content;return se(s,s,[e],r)}loadGame(e){this.assertSameProject(e),this.assertExternalScopes();let t=this.planLoad(structuredClone(e)),r=this.internals.registry;t.sections!==void 0?(this.reset(),this.internals.ownsRegistry?r.load(t.sections):r.load(t.sections,{keepParked:!0})):this.dropRun(new Set(t.flows.map(([s])=>s)));for(let s of t.spent)this.spent.add(s);for(let[s,o]of t.flows)this.open(s,{},!0).restore(o);return t.report}assertSameProject(e){if(e.content.project!==this.internals.bundle.content.project)throw new b(`save is for project "${e.content.project}", bundle is "${this.internals.bundle.content.project}"`)}planLoad(e){let t=e.schema;if(t!==Z&&t!==ee)throw new b(`unsupported save schema: ${String(t)}`);let r=ne(),s=new Set(Object.keys(e.flows??{})),o;e.schema===ee?o={shared:e.shared?.props??ie(),flows:new Map(Object.entries(e.flows??{}).map(([c,p])=>[c,p.props??ie()])),rest:{}}:e.registry!==void 0&&(o=mr(e.registry,s));let i=o!==void 0?Mt(this.internals,this.internals.sharedDecls,o.shared,void 0,r):void 0,a=[];for(let c of e.shared?.spent??[])this.internals.cardsById.has(c)?a.push(c):r.droppedSpent.push(c);let d=[],l=o!==void 0?{...o.rest}:void 0;l!==void 0&&i!==void 0&&Et(i,(c,p)=>c==="story"?"story":Ae(c,p),l);for(let[c,p]of Object.entries(e.flows??{})){let g=o!==void 0?{...p,props:o.flows.get(c)??ie()}:{...p},u=this.planFlowRestore(c,g,void 0,r);l!==void 0&&u.props!==void 0&&(Et(u.props,(m,h)=>_e(c,m,h),l),delete u.props),d.push([c,u])}return{report:se(this.internals.bundle.content,e.content,d.map(([c])=>c),r),...l!==void 0?{sections:l}:{},spent:a,flows:d}}planFlowRestore(e,t,r,s){let o=this.internals,i=t.props!==void 0?Mt(o,o.flowDecls,t.props,e,s):void 0,a={};for(let[p,g]of Object.entries(t.cooldowns??{}))o.cardsById.has(p)?a[p]=g:s.droppedCooldowns.push({flow:e,card:p});let d=p=>{let g=o.cardsById.get(p);return g?f(g.card):p},l={},c=new Map;for(let[p,g]of Object.entries(t.board??{})){let u=o.handsById.get(p);if(u===void 0){for(let x of g)s.evicted.push({flow:e,hand:p,card:d(x),reason:"hand-vanished"});continue}let m=f(u.hand),h=[];for(let x of g){let v=o.cardsById.get(x);if(v===void 0){s.evicted.push({flow:e,hand:m,card:x,reason:"vanished"});continue}if(r!==void 0&&oe(v.card,v.deck.shared??!1)){if((r.get(x)??0)+(c.get(x)??0)>=Lt(v.card)){s.evicted.push({flow:e,hand:m,card:f(v.card),reason:"claimed-elsewhere"});continue}c.set(x,(c.get(x)??0)+1)}h.push(x)}l[p]=h}return{...i!==void 0?{props:i}:{},turns:t.turns??{},prng:t.prng,cooldowns:a,board:l,playLog:t.playLog??[]}}},ae=class{id;engine;internals;closed=!1;prng;turnCounts=new Map;cooldowns={};boardContents=new Map;playLog=[];playCount=new Map;lastPlayOf=new Map;tagPlayCount=new Map;lastPlayInTag=new Map;stores;registered=[];bagKeys=[];traceHandlers=new Set;logEntries=[];logSeq=0;storyReader;boxReaders=new Map;deckReaders=new Map;constructor(e,t,r,s){this.engine=e,this.internals=t,this.id=r,this.prng=V(s),this.stores=Nt(t,t.flowDecls);let o=(a,d)=>{d.declarations().length!==0&&this.bagKeys.push([a,d])};o(_e(r,"story"),this.stores.story);for(let a of O)for(let[d,l]of this.stores[a])o(_e(r,a,d),l);this.mountBags();for(let a of t.bundle.boxes){this.turnCounts.set(a.id,0);for(let d of a.hands)this.boardContents.set(d.id,[])}let i=(a,d)=>({get:l=>R(a,l)??R(d,l)});this.storyReader=i(this.stores.story,t.shared.story);for(let a of t.bundle.boxes){this.boxReaders.set(a.id,i(this.stores.box.get(a.id),t.shared.box.get(a.id)));for(let d of a.decks)this.deckReaders.set(d.id,i(this.stores.deck.get(d.id),t.shared.deck.get(d.id)))}}get isClosed(){return this.closed}close(){this.closed||(this.engine.dropFlow(this.id,this),this.markClosed())}markClosed(){this.releaseBags(!1),this.closed=!0}releaseBags(e){for(let t of this.registered)this.internals.registry.remove(t,{keep:e});this.registered.length=0}registeredKeys(){return[...this.registered]}mountBags(){for(let[e,t]of this.bagKeys)this.internals.registry.mountOwned(e,t,{owner:U}),this.registered.push(e)}assertOpen(){if(this.closed)throw new b(`flow "${this.id}" is closed`)}resolveBox(e){let t=this.internals.boxesByGameId.get(e)??this.internals.boxesById.get(e);if(!t)throw new b(`unknown box "${e}"`);return t}turn(e){return this.assertOpen(),this.turnCounts.get(this.resolveBox(e).id)??0}subscribeTrace(e){return this.traceHandlers.add(e),()=>{this.traceHandlers.delete(e)}}get tracing(){return this.traceHandlers.size>0||this.internals.logCap!==void 0||this.internals.engineTracing()}emit(e,t){this.internals.logCap!==void 0&&(this.logEntries.push({...e,seq:this.logSeq++,...t!==void 0?{turn:t}:{}}),this.logEntries.length>this.internals.logCap&&this.logEntries.splice(0,this.logEntries.length-this.internals.logCap));for(let r of[...this.traceHandlers])r(e);this.internals.emitEngine(this.id,e,t)}log(){return this.logEntries}clearLog(){this.logEntries=[]}node(e){let t=this.internals.nodeCache.get(e);return t||(t=j(e.ast),this.internals.nodeCache.set(e,t)),t}groupInBox(e,t){let r=Y(this.internals.bundle,e);return r.find(s=>f(s)===t)??r.find(s=>s.id===t)}indexPlay(e){this.playCount.set(e.card,(this.playCount.get(e.card)??0)+1),this.lastPlayOf.set(e.card,e);let t=this.internals.cardsByGameId.get(e.card);if(t)for(let[r,s]of Object.entries(t.card.tags??{}))for(let o of s){let i=St(t.box.id,r,o);this.tagPlayCount.set(i,(this.tagPlayCount.get(i)??0)+1),this.lastPlayInTag.set(i,e)}}rebuildPlayIndex(){this.playCount.clear(),this.lastPlayOf.clear(),this.tagPlayCount.clear(),this.lastPlayInTag.clear();for(let e of this.playLog)this.indexPlay(e)}hostsByBox=new Map;host(e){let t=this.hostsByBox.get(e.id);if(t!==void 0)return t;let r=this.makeHost(e);return this.hostsByBox.set(e.id,r),r}makeHost(e){let t=new Map,r=(o,i)=>{let a=`${o}${i}`;if(t.has(a))return t.get(a);let d=this.groupInBox(e,o),l=d?.tags.find(p=>p.gameId===i),c=d&&l?St(e.id,d.id,l.id):void 0;return t.set(a,c),c},s=o=>{let i=this.internals.cardsByGameId.get(o.card);return i?(this.turnCounts.get(i.box.id)??0)-o.turn:fe};return{nextRandom:()=>this.prng.next(),countPlayed:o=>this.playCount.get(o)??0,turnsSincePlayed:o=>{let i=this.lastPlayOf.get(o);return i?s(i):fe},countPlayedIn:(o,i)=>{let a=r(o,i);return a===void 0?0:this.tagPlayCount.get(a)??0},turnsSincePlayedIn:(o,i)=>{let a=r(o,i),d=a===void 0?void 0:this.lastPlayInTag.get(a);return d?s(d):fe}}}evalCtx(e,t,r){let s=this.internals.registryView();return{scopes:{...s.scopes,world:this.internals.worldResolver,story:this.storyReader,box:this.boxReaders.get(e.id)??Ve,deck:t?this.deckReaders.get(t.id)??Ve:Ve,hand:r.bag},host:this.host(e),...this.internals.hasQualities||s.qualities!==void 0?{qualities:(o,i)=>o==="world"?this.internals.ladders.world.get(i)??s.qualities?.(o,i):o==="story"?this.internals.ladders.story.get(i):o==="box"?this.internals.ladders.box.get(e.id)?.get(i):o==="deck"&&t?this.internals.ladders.deck.get(t.id)?.get(i):o==="hand"?this.handLadder(r,i):s.qualities?.(o,i)}:{}}}handLadder(e,t){let r=e.sources.get(t);if(r)return r.kind==="value"?this.internals.ladders.value.get(r.id)?.get(t):r.kind==="hand"?this.internals.ladders.hand.get(r.id)?.get(t):void 0}eval(e,t){return ue(this.node(e),t,Le)}passes(e,t,r){if(!e)return!0;try{return Pt(this.eval(e,t))}catch(s){return this.tracing&&this.emit({type:"diagnostic",where:r??"condition",message:s instanceof Error?s.message:String(s)}),!1}}tagByGameId(e,t){return e.tags.find(r=>r.gameId===t)}askForHand(e,t){let r=new Map,s={},o=a=>{for(let[d,l]of Object.entries(a??{})){if(he(l)){this.fillHoleFromProperty(e,d,l,r,s);continue}r.set(d,l);let c=this.internals.groupsById.get(d),p=c?.group.tags.find(g=>g.id===l);c&&p&&(s[f(c.group)]=f(p))}},i;if(e.template!==void 0){let a=this.internals.templatesById.get(e.template);if(!a)throw new b(`hand "${f(e)}": unknown template "${e.template}"`);for(let[d,l]of Object.entries(a.bindings??{}))r.set(d,l);o(e.chosen),i=a.condition}else o(e.rule?.bindings),i=e.rule?.condition;return r.set(L,e.id),this.bindStateGroups(t,r,s),{box:t,hand:e,...i!==void 0?{condition:i}:{},boundTags:r,askNames:s}}askForPeek(e,t){let r=new Map,s={};for(let[o,i]of Object.entries(t)){if(o===L){let l=this.internals.handsByGameId.get(i)??this.internals.handsById.get(i);if(!l)throw new b(`peek: unknown hand "${i}" in home criteria`);r.set(L,l.hand.id);continue}let a=this.groupInBox(e,o);if(!a)throw new b(`peek: unknown tag group "${o}" in box "${f(e)}"`);let d=this.tagByGameId(a,i)??a.tags.find(l=>l.id===i);if(!d)throw new b(`peek: unknown tag "${i}" in group "${f(a)}"`);r.set(a.id,d.id),s[f(a)]=f(d)}return this.bindStateGroups(e,r,s),{box:e,boundTags:r,askNames:s}}fillHoleFromProperty(e,t,r,s,o){let i=this.internals.groupsById.get(t),a=i?f(i.group):t,d=`hand ${f(e)}, tag group ${a}`,l=mt(r);if(!l){this.emit({type:"diagnostic",where:d,message:`"${r}" is not a @hand, @world or @story property reference`});return}if(!i){this.emit({type:"diagnostic",where:d,message:`"${r}" fills a tag group that is not in this box`});return}let c;if(l.scope==="hand")c=this.valuesOf("hand",e.id)[l.name];else try{c=this.getProperty(`${l.scope}.${l.name}`)}catch{c=void 0}if(c===void 0){this.emit({type:"diagnostic",where:d,message:`"${r}" names a property that is not declared`});return}let p=typeof c=="string"?c:String(c),g=i.group.tags.find(u=>f(u)===p);if(!g){this.emit({type:"diagnostic",where:d,message:`${r} is "${p}", which is not one of the tags of "${a}"`});return}s.set(t,g.id),o[a]=f(g)}bindStateGroups(e,t,r){for(let s of Y(this.internals.bundle,e)){if(s.boundBy===void 0||t.has(s.id))continue;let o=/^@(world|story)\.([a-z][a-z0-9_-]*)$/.exec(s.boundBy);if(!o){this.emit({type:"diagnostic",where:`tag group ${f(s)}`,message:`boundBy "${s.boundBy}" is not a @world or @story property reference`});continue}let i;try{i=this.getProperty(`${o[1]}.${o[2]}`)}catch{this.emit({type:"diagnostic",where:`tag group ${f(s)}`,message:`boundBy "${s.boundBy}" names a property that is not declared`});continue}let a=typeof i=="string"?i:String(i),d=s.tags.find(l=>f(l)===a);if(!d){this.emit({type:"diagnostic",where:`tag group ${f(s)}`,message:`${s.boundBy} is "${a}", which is not one of its tags`});continue}t.set(s.id,d.id),r[f(s)]=f(d)}}valuesOf(e,t){return Object.assign(Object.create(null),this.internals.shared[e].get(t)?.values??{},this.stores[e].get(t)?.values??{})}buildHandEnv(e){let t=Object.create(null),r=new Map;for(let[s,o]of e.boundTags)if(s!==L)for(let[i,a]of Object.entries(this.valuesOf("value",o)))t[i]=a,r.set(i,{kind:"value",id:o});if(e.hand)for(let[s,o]of Object.entries(this.valuesOf("hand",e.hand.id)))t[s]=o,r.set(s,{kind:"hand",id:e.hand.id});for(let[s,o]of Object.entries(e.askNames))t[s]=o,r.set(s,{kind:"criteria"});return{bag:t,sources:r,boundTags:e.boundTags}}claims(){let e=new Map;for(let t of this.boardContents.values())for(let r of t)e.set(r,(e.get(r)??0)+1);return e}heldCardIds(){return[...this.boardContents.values()].flat()}copiesOf(e){return e.copies??1}claimVerdict(e,t,r,s){let o=e.id;return(r.get(o)??0)>=this.copiesOf(e)?"claimed":t&&(s.get(o)??0)>=Lt(e)?"claimed-elsewhere":null}tagsMatch(e,t){let r=e.tags?.[L];if(r!==void 0&&r.length>0){let s=t.get(L);if(s===void 0||!r.includes(s))return!1}for(let[s,o]of t){if(s===L)continue;let i=e.tags?.[s];if(i===void 0){if(this.internals.requiredGroups.has(s))return!1;continue}if(!i.includes(o))return!1}return!0}runAsk(e,t,r){let{box:s}=e,o=this.buildHandEnv(e),i=(p,g)=>{r?.push({id:f(p),verdict:g})};if(!this.passes(e.condition,this.evalCtx(s,void 0,o),`hand ${e.hand?f(e.hand):""} condition`))return{ordered:[],handEnv:o};let a=new Map;for(let p of s.decks)a.set(p.id,this.passes(p.condition,this.evalCtx(s,p,o),`deck ${p.gameId} gate`));let d=this.turnCounts.get(s.id)??0,l=[];for(let p of s.decks){let g=this.evalCtx(s,p,o),u=p.shared??!1;for(let m of p.cards){let h=oe(m,u);if(!a.get(p.id)){i(m,"deck-gate");continue}if(h&&this.engine.isTaken(m.id)){i(m,"taken");continue}if((this.cooldowns[m.id]??0)>d){i(m,"cooldown");continue}if(!this.tagsMatch(m,o.boundTags)){i(m,"tags");continue}if(m.condition&&!this.passes(m.condition,g,this.tracing?`card ${m.gameId} condition`:void 0)){i(m,"condition");continue}let x=t(m,h);if(x){i(m,x);continue}let v;if(typeof m.priority=="number")v=m.priority;else try{let y=this.eval(m.priority,g);if(typeof y!="number"||Number.isNaN(y)){i(m,"priority");continue}v=y}catch(y){this.tracing&&this.emit({type:"diagnostic",where:`card ${m.gameId} priority`,message:y instanceof Error?y.message:String(y)}),i(m,"priority");continue}let w=0;if(s.ranking.specificity&&m.condition){let y=this.node(m.condition);w=lt(y,k=>{try{return Pt(ue(k,g,Le))}catch{return!1}})}l.push({entry:{card:m,deck:p,box:s},priority:v,spec:w})}}l.sort((p,g)=>g.priority-p.priority||g.spec-p.spec);let c=0;for(;c<l.length;){let p=c+1;for(;p<l.length&&l[p].priority===l[c].priority&&l[p].spec===l[c].spec;)p++;if(p-c>1){let g=l.slice(c,p);H(g,this.prng);for(let u=0;u<g.length;u++)l[c+u]=g[u]}c=p}for(let p of l)r?.push({id:f(p.entry.card),verdict:"dealt",priority:p.priority,specificity:p.spec});return{ordered:l.map(p=>p.entry),handEnv:o}}capTrace(e,t){for(let r of e)r.verdict==="dealt"&&!t.has(r.id)&&(r.verdict="capped")}view(e){let{card:t}=e;return{id:t.id,gameId:f(t),...t.title!==void 0?{title:t.title}:{},...t.purpose!==void 0?{purpose:t.purpose}:{},...t.fields!==void 0?{fields:t.fields}:{}}}handCapacity(e){if(e.slots!==void 0)return e.slots;let t=e.template!==void 0?this.internals.templatesById.get(e.template)?.slots:e.rule?.slots;return t===void 0||t==="unbounded"?1/0:t}resolveHand(e){let t=this.internals.handsByGameId.get(e)??this.internals.handsById.get(e);if(!t)throw new b(`unknown hand "${e}"`);return t}peek(e,t={},r){this.assertOpen();let s=this.resolveBox(e),o=this.askForPeek(s,t),i=this.claims(),a=this.internals.hasShared?this.engine.sharedClaims():new Map,d=this.tracing?[]:void 0,l=this.prng;this.prng=V(l.state());let c;try{({ordered:c}=this.runAsk(o,(g,u)=>this.claimVerdict(g,u,i,a),d))}finally{this.prng=l}let p=r===void 0?c:c.slice(0,Math.max(r,0));return d&&(this.capTrace(d,new Set(p.map(g=>f(g.card)))),this.emit({type:"peek",box:f(s),criteria:t,cards:d},this.turnCounts.get(s.id)??0)),{box:f(s),cards:p.map(g=>this.view(g))}}deal(e){this.assertOpen();let{hand:t}=this.resolveHand(e);return this.dealMany([e])[f(t)]??[]}dealMany(e){this.assertOpen();let t=(e??[...this.internals.handsById.keys()].sort()).map(o=>this.resolveHand(o));H(t,this.prng);for(let{hand:o,box:i}of t){let a=this.askForHand(o,i),d=this.buildHandEnv(a),l=this.passes(a.condition,this.evalCtx(i,void 0,d)),c=new Map,p=new Map;for(let v of i.decks){let w=this.evalCtx(i,v,d);p.set(v.id,w),c.set(v.id,this.passes(v.condition,w))}let g=this.tracing,u=this.turnCounts.get(i.id)??0,m=[],h=(v,w)=>{let y=this.internals.cardsById.get(v);return m.push({card:y?f(y.card):v,reason:w}),!1},x=(this.boardContents.get(o.id)??[]).filter(v=>{if(!l)return h(v,"hand-condition");let w=this.internals.cardsById.get(v);return!w||w.box.id!==i.id?h(v,"vanished"):c.get(w.deck.id)?oe(w.card,w.deck.shared??!1)&&this.engine.isTaken(v)?h(v,"taken"):(this.cooldowns[v]??0)>u?h(v,"cooldown"):this.tagsMatch(w.card,d.boundTags)?this.passes(w.card.condition,p.get(w.deck.id),g?`card ${w.card.gameId} condition`:void 0)?!0:h(v,"condition"):h(v,"tags"):h(v,"deck-gate")});if(this.boardContents.set(o.id,x),g)for(let v of m)this.emit({type:"evict",hand:f(o),card:v.card,reason:v.reason},u)}let r=this.claims(),s=this.internals.hasShared?this.engine.sharedClaims():new Map;for(let{hand:o,box:i}of t){let a=this.boardContents.get(o.id)??[],d=this.handCapacity(o)-a.length;if(d<=0)continue;let l=this.askForHand(o,i),c=new Set(a),p=this.tracing?[]:void 0,{ordered:g}=this.runAsk(l,(h,x)=>c.has(h.id)?"claimed":this.claimVerdict(h,x,r,s),p),u=g.slice(0,d),m=u.map(h=>h.card.id);this.boardContents.set(o.id,[...a,...m]);for(let h of m)r.set(h,(r.get(h)??0)+1),s.set(h,(s.get(h)??0)+1);p&&(this.capTrace(p,new Set(u.map(h=>f(h.card)))),this.emit({type:"deal",hand:f(o),cards:p},this.turnCounts.get(i.id)??0))}return Object.fromEntries(t.map(({hand:o})=>[f(o),(this.boardContents.get(o.id)??[]).map(i=>this.view(this.internals.cardsById.get(i)))]))}board(e){this.assertOpen();let t=e!==void 0?this.resolveBox(e).id:void 0;return Object.fromEntries([...this.boardContents.entries()].filter(([r])=>t===void 0||this.internals.handsById.get(r).box.id===t).map(([r,s])=>[f(this.internals.handsById.get(r).hand),s.map(o=>this.view(this.internals.cardsById.get(o)))]))}resolveDealt(e,t){let r=this.internals.cardsById.get(e)??this.internals.cardsByGameId.get(e);if(!r)throw new b(`unknown card "${e}"`);let{hand:s,box:o}=this.resolveHand(t);if(!(this.boardContents.get(s.id)??[]).includes(r.card.id))throw new b(`card "${f(r.card)}" is not dealt to hand "${f(s)}"`);return{entry:r,ask:this.askForHand(s,o)}}outcomes(e,t){this.assertOpen();let{entry:r,ask:s}=this.resolveDealt(e,t),o=this.evalCtx(r.box,r.deck,this.buildHandEnv(s));return r.card.outcomes.map(i=>({id:i.id,gameId:f(i),...i.title!==void 0?{title:i.title}:{},...i.purpose!==void 0?{purpose:i.purpose}:{},...i.fields!==void 0?{fields:i.fields}:{},available:this.passes(i.condition,o)}))}play(e,t,r,s={}){this.assertOpen();let{entry:o,ask:i}=this.resolveDealt(e,r),a=t==="";if(a&&o.card.outcomes.length>0)throw new b(`card "${f(o.card)}" has outcomes (${o.card.outcomes.map(y=>f(y)).join(", ")}); name the one played`);let d=a?void 0:o.card.outcomes.find(y=>f(y)===t);if(!a&&!d)throw new b(`card "${f(o.card)}" has no outcome "${t}"`);let l=this.buildHandEnv(i),c=this.evalCtx(o.box,o.deck,l);if(d&&!this.passes(d.condition,c))throw new b(`outcome "${t}" on "${f(o.card)}" is gated shut`);let p=o.box.turn!==void 0?0:this.internals.bundle.settings.playAdvancesTurns,g=(this.turnCounts.get(o.box.id)??0)+(s.advanceTurns??p),m=Object.entries(d?.changes??{}).map(([y,k])=>({target:y,expr:k,plan:this.planWrite(y,o,l)})).map(y=>({...y,value:this.eval(y.expr,c)})),h=[];try{for(let y of m)h.push({target:y.target,plan:y.plan,value:y.value,prev:this.landWrite(y.plan,y.value)})}catch(y){for(let k of[...h].reverse())this.undoWrite(k.plan,k.prev);throw y}if(this.tracing)for(let{target:y,plan:k,value:I,prev:pe}of h)this.emit({type:"write",target:y,path:k.path,value:I,...pe!==void 0?{prev:pe}:{}},g);let x=d?f(d):"",v={card:f(o.card),outcome:x,turn:g};this.playLog.push(v),this.indexPlay(v),o.card.redraw==="never"?oe(o.card,o.deck.shared??!1)?this.engine.markTaken(o.card.id):this.cooldowns[o.card.id]=Number.MAX_SAFE_INTEGER:typeof o.card.redraw=="number"&&(this.cooldowns[o.card.id]=g+o.card.redraw);let w=i.hand.id;this.boardContents.set(w,(this.boardContents.get(w)??[]).filter(y=>y!==o.card.id)),this.turnCounts.set(o.box.id,g),this.tracing&&this.emit({type:"play",card:f(o.card),outcome:x,turn:g},g)}address(e,t){return A(this.internals,e,t)}planBag(e,t,r,s){let o=e==="story"?this.stores.story:t!==void 0?this.stores[e].get(t):void 0,i=e==="story"?this.internals.shared.story:t!==void 0?this.internals.shared[e].get(t):void 0,a=R(o,r)!==void 0?o:R(i,r)!==void 0?i:void 0;if(a===void 0)throw new b(`no property at "${s}"`);if(a.declarations().some(d=>d.name===r&&d.writable===!1))throw new b(`'${r}' is read-only`);return{kind:"bag",bag:a,name:r,path:s}}planWrite(e,t,r){let s=/^@([a-z]+)\.([A-Za-z_][A-Za-z0-9_-]*)$/.exec(e);if(!s)throw new b(`bad change target "${e}"`);let[,o,i]=s;switch(o){case"world":{if(!this.internals.worldSet)throw new b(`@world.${i} cannot be written: the host bound @world read-only`);if(this.internals.worldReadOnly.has(i))throw new b(`'@world.${i}' is read-only (writable: false)`);return{kind:"world",name:i,path:`world.${i}`}}case"story":return this.planBag("story",void 0,i,`story.${i}`);case"box":return this.planBag("box",t.box.id,i,`${this.address("box",t.box.id)}.${i}`);case"deck":return this.planBag("deck",t.deck.id,i,`${this.address("deck",t.deck.id)}.${i}`);case"hand":{let a=r.sources.get(i);if(!a)throw new b(`@hand.${i} is not composed in this ask`);if(a.kind==="criteria")throw new b(`@hand.${i} is a chosen tag / criteria name and cannot be written`);return this.planBag(a.kind,a.id,i,`${this.address(a.kind,a.id)}.${i}`)}default:{if(this.internals.registry.has(o))return{kind:"scope",scope:o,name:i,path:`${o}.${i}`};throw this.internals.bundle.externalScopes?.includes(o)?new b(`@${o}.${i} cannot be written: no engine on this registry registered @${o}`):new b(`bad change target scope "@${o}"`)}}}landWrite(e,t){switch(e.kind){case"world":{let r=this.internals.worldResolver.get(e.name);return this.internals.worldSet(e.name,t),r}case"bag":return e.bag.set(e.name,t).prev;case"scope":{let r=this.internals.registry.get(e.scope,e.name);return this.internals.registry.set(e.scope,e.name,t),r}}}undoWrite(e,t){if(t!==void 0)switch(e.kind){case"world":this.internals.worldSet(e.name,t,!0);return;case"bag":e.bag.set(e.name,t,{silent:!0,reason:"play refused",host:!0});return;case"scope":this.internals.registry.set(e.scope,e.name,t,{host:!0});return}}advanceTurns(e,t=1){this.assertOpen();let r=this.resolveBox(e),s=(this.turnCounts.get(r.id)??0)+t;this.turnCounts.set(r.id,s),this.tracing&&this.emit({type:"turns",box:f(r),turn:s},s)}listBoxes(){return this.assertOpen(),this.internals.bundle.boxes.map(e=>({id:e.id,gameId:f(e),...e.title!==void 0?{title:e.title}:{},turn:this.turnCounts.get(e.id)??0}))}listBags(){this.assertOpen();let e=[{prefix:"story",bag:this.stores.story}];for(let t of O)for(let[r,s]of this.stores[t])e.push({prefix:A(this.internals,t,r),bag:s});return e}listProperties(){this.assertOpen();let e=[];for(let r of this.internals.bundle.world.properties){let s=this.internals.worldResolver.get(r.name);e.push({path:`world.${r.name}`,name:r.name,type:r.type,value:s??r.default,default:r.default,...r.values!==void 0?{values:r.values}:{},...r.stages!==void 0?{stages:r.stages}:{},writable:this.internals.worldSet!==void 0&&!this.internals.worldReadOnly.has(r.name)})}let t=(r,s,o)=>{for(let i of[s,o])if(i!==void 0)for(let a of i.rows())e.push(a)};t("story",this.internals.shared.story,this.stores.story);for(let r of O){let s=new Set([...this.internals.shared[r].keys(),...this.stores[r].keys()]);for(let o of s)t(A(this.internals,r,o),this.internals.shared[r].get(o),this.stores[r].get(o))}return e}getProperty(e){this.assertOpen();let t=this.resolvePath(e),r=t.kind==="world"?this.internals.worldResolver.get(t.name):t.kind==="scope"?this.internals.registry.get(t.token,t.name):R(t.own,t.name)??R(t.shared,t.name);if(r===void 0)throw new b(`no property at "${e}"`);return r}setProperty(e,t){this.assertOpen();let r=this.resolvePath(e);if(r.kind==="world"){if(!this.internals.worldSet)throw new b("@world is read-only here: the host bound no write");this.internals.worldSet(r.name,t,!0);return}if(r.kind==="scope"){this.internals.registry.set(r.token,r.name,t,{host:!0});return}let s=R(r.own,r.name)!==void 0?r.own:R(r.shared,r.name)!==void 0?r.shared:void 0;if(s===void 0)throw new b(`no property at "${e}"`);s.set(r.name,t,{silent:!0,reason:"host setProperty",host:!0})}resolvePath(e){let t=e.split(".");if(t.length===2&&t[0]==="world")return{kind:"world",name:t[1]};if(t.length===2&&t[0]!=="story"&&this.internals.registry.has(t[0]))return{kind:"scope",token:t[0],name:t[1]};if(t.length===2&&t[0]==="story")return{kind:"bag",own:this.stores.story,shared:this.internals.shared.story,name:t[1]};if(t.length===3&&Dt(t[0])){let r=t[0],[,s,o]=t,i=Vt(this.internals,r,s,o);i.legacy&&this.tracing&&this.emit({type:"diagnostic",where:"property address",message:jt(this.internals,r,s,o)});let a=this.stores[r].get(i.id),d=this.internals.shared[r].get(i.id);if(a===void 0&&d===void 0)throw new b(`no ${r} store "${s}"`);return{kind:"bag",...a!==void 0?{own:a}:{},...d!==void 0?{shared:d}:{},name:o}}throw new b(`bad property path "${e}"`)}saveDurable(){this.assertOpen();let{bundle:e,durable:t}=this.internals;return structuredClone({schema:de,content:e.content,values:Tt(this.stores,t.flow),spent:t.flowCards.filter(r=>this.cooldowns[r.card.id]===Number.MAX_SAFE_INTEGER).map(r=>f(r.card)).sort()})}writeDurable(e){for(let[t,r]of e.values)At(ze(this.stores,t),t.decl.name,r);for(let t of e.cards)this.cooldowns[t]=Number.MAX_SAFE_INTEGER}snapshot(e){return{...e?{props:Er(this.stores)}:{},turns:Object.fromEntries(this.turnCounts),prng:this.prng.state(),cooldowns:this.cooldowns,board:Object.fromEntries(this.boardContents),playLog:this.playLog}}restore(e){e.props!==void 0&&kr(this.stores,e.props),this.turnCounts=new Map(this.internals.bundle.boxes.map(t=>[t.id,0]));for(let[t,r]of Object.entries(e.turns??{}))this.turnCounts.has(t)&&this.turnCounts.set(t,r);this.prng=V(e.prng),this.cooldowns=e.cooldowns??{},this.playLog=e.playLog??[],this.rebuildPlayIndex(),this.boardContents=new Map(Object.entries(e.board??{}).filter(([t])=>this.internals.handsById.has(t)).map(([t,r])=>[t,r.filter(s=>this.internals.cardsById.has(s))]));for(let t of this.internals.handsById.keys())this.boardContents.has(t)||this.boardContents.set(t,[])}};var xe=n=>n.map(e=>({name:e.name,type:e.type,default:e.default,...e.values!==void 0?{values:e.values}:{},...e.durable===!0?{durable:!0}:{},...e.purpose!==void 0?{purpose:e.purpose}:{}})),Ft=n=>n.decks.reduce((e,t)=>e+t.cards.filter(r=>(r.durable??t.durable)===!0).length,0),Cr=(n,e)=>n.template!==void 0?e.handTemplates.find(t=>t.id===n.template)?.properties??[]:n.properties??[],Br=(n,e,t)=>{let r=e.template!==void 0?e.chosen:e.rule?.bindings,s=[];for(let[o,i]of Object.entries(r??{})){if(!he(i))continue;let a=Y(n,t).find(d=>d.id===o);a!==void 0&&s.push({group:f(a),from:i})}return s},$r=(n,e)=>{if(n.slots!==void 0)return n.slots;let t=n.template!==void 0?e.handTemplates.find(r=>r.id===n.template)?.slots:n.rule?.slots;return t===void 0?"unbounded":t};function Se(n){let e=[],t=[],r=[{scope:"world",owner:"",properties:xe(n.world.properties)},{scope:"story",owner:"",properties:xe(n.story.properties)}],s={boxes:0,decks:0,cards:0,hands:0,templates:0,tagGroups:0};for(let i of n.boxes){let a=f(i),d=i.decks.reduce((c,p)=>c+p.cards.length,0);e.push({gameId:a,...i.title!==void 0?{title:i.title}:{},...i.usesMap===!0?{usesMap:!0}:{},ranking:{specificity:i.ranking.specificity},...i.turn!==void 0?{turn:{seconds:i.turn.seconds}}:{},...Ft(i)>0?{durableCards:Ft(i)}:{},tagGroups:i.tagGroups.map(c=>({gameId:f(c),tags:c.tags.map(p=>f(p))})),counts:{decks:i.decks.length,cards:d,hands:i.hands.length,templates:i.handTemplates.length,tagGroups:i.tagGroups.length}}),s.boxes+=1,s.decks+=i.decks.length,s.cards+=d,s.hands+=i.hands.length,s.templates+=i.handTemplates.length,s.tagGroups+=i.tagGroups.length;for(let c of i.hands){let p=c.template!==void 0?i.handTemplates.find(u=>u.id===c.template):void 0,g=Br(n,c,i);t.push({gameId:f(c),...c.title!==void 0?{title:c.title}:{},box:a,slots:$r(c,i),...p!==void 0?{template:f(p)}:{},...g.length>0?{movable:g}:{}})}let l=(c,p,g,u)=>{g.length!==0&&r.push({scope:c,owner:p,box:a,...u!==void 0?{group:u}:{},properties:xe(g)})};l("box",a,i.properties);for(let c of i.decks)l("deck",f(c),c.properties);for(let c of i.hands)l("hand",f(c),Cr(c,i));for(let c of i.tagGroups)for(let p of c.tags)l("tag",f(p),p.properties??[],f(c))}let o=n.map;if(o!==void 0){let i=f(o.group);for(let a of o.group.tags){let d=a.properties??[];d.length>0&&r.push({scope:"tag",owner:f(a),group:i,properties:xe(d)})}s.tagGroups+=1}return{identity:{schema:n.schema,project:n.content.project,version:n.content.version,hash:n.content.hash,metadata:n.metadata},totals:s,boxes:e,hands:t,properties:r,...o!==void 0?{map:{group:f(o.group),tags:o.group.tags.map(i=>f(i)),boxes:n.boxes.filter(i=>i.usesMap===!0).map(i=>f(i)),zones:o.geometry?.zones.length??0,backgrounds:o.geometry?.backgrounds?.length??0,sites:Object.fromEntries(Object.entries(o.geometry?.sites??{}).map(([i,a])=>[i,a.length]))}}:{}}}function _t(n,e){let t={};for(let{bag:r}of[...n.listBags(),...e.listBags()])for(let s of r.rows())s.value!==void 0&&(t[s.path]=s.value);return Object.assign(t,qt(Gt(n,e.id))),t}function Gt(n,e){return n.getFlow(e)!==void 0?n.saveFlow(e):void 0}function qt(n){let e={};if(n===void 0)return e;for(let[t,r]of Object.entries(n.turns))e[`turn:${t}`]=r;for(let[t,r]of Object.entries(n.cooldowns))e[`cooldown:${t}`]=r;for(let[t,r]of Object.entries(n.board))e[`board:${t}`]=[...r];return e}function zt(n,e,t={}){let r=e.id,s=()=>n.getFlow(r);return re({mounts:()=>[...n.listBags(),...s()?.listBags()??[]].map(({bag:o})=>({bag:o})),extra:()=>qt(Gt(n,r))},t)}function Ee(n,e){return JSON.stringify(Ue(n,e),null,2)}function Ue(n,e){return{schema:me,engine:n.saveGame(),...e!==void 0?{world:e}:{}}}function We(n,e,t={}){if(!e||typeof e!="object"||e.schema!==me||e.engine?.schema!==Z&&e.engine?.schema!==ee)throw new Error(`not a storylets save (expected schema "${me}")`);let r=n.loadGame(e.engine);return t.onReport?.(r),e.world}function ke(n,e,t={}){let r;try{r=JSON.parse(e)}catch{throw new Error("not valid JSON")}return We(n,r,t)}var Ut="sl-inspector-style",Or=`
1
+ "use strict";var StoryletEngine=(()=>{var Re=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var er=Object.getOwnPropertyNames;var tr=Object.prototype.hasOwnProperty;var rr=(n,e)=>{for(var t in e)Re(n,t,{get:e[t],enumerable:!0})},nr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of er(e))!tr.call(n,s)&&s!==t&&Re(n,s,{get:()=>e[s],enumerable:!(r=Zt(e,s))||r.enumerable});return n};var sr=n=>nr(Re({},"__esModule",{value:!0}),n);var Hr={};rr(Hr,{DURABLE_SCHEMA:()=>de,Engine:()=>ve,Flow:()=>ae,StoryletError:()=>b,applyLiveBundle:()=>Xt,boardFrame:()=>Xe,createBundleInspector:()=>Jt,createKernelStateLogger:()=>re,createLiveLink:()=>Qt,createPropertyInspector:()=>Kt,createStateLogger:()=>zt,createWorldContainer:()=>Yt,describeBundle:()=>Se,deserializeState:()=>ke,diffState:()=>te,ensureInspectorStyle:()=>le,formatLogEntry:()=>Ke,formatPropertySummary:()=>Je,formatScopeLabel:()=>Qe,loadState:()=>We,makePrng:()=>V,saveState:()=>Ue,serializeState:()=>Ee,shuffleInPlace:()=>H,snapshotState:()=>_t});function Q(n,e){return n!==void 0&&Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0}function j(n){switch(n[0]){case"b":return{kind:"bool",value:n[1]};case"n":return{kind:"number",value:n[1]};case"s":return{kind:"string",value:n[1]};case"sv":return{kind:"scopedvar",scope:n[1],name:n[2]};case"u":return{kind:"unary",op:n[1],operand:j(n[2])};case"bin":return{kind:"binary",op:n[1],left:j(n[2]),right:j(n[3])};case"call":{let e=n.slice(2).map(j);return{kind:"call",name:n[1],args:e}}case"fd":return{kind:"flagdelta",sign:n[1],name:n[2]}}}var S=class extends Error{constructor(e){super(e),this.name="EvalError"}};function ue(n,e,t){let r=new Map(t.scopes.map(o=>[o.token,o.missing??"false"])),s=o=>{switch(o.kind){case"bool":return o.value;case"number":return o.value;case"string":return o.value;case"scopedvar":{let i=Q(e.scopes,o.scope);if(i===void 0)return!1;let a=typeof i.get=="function"?i.get(o.name):Q(i,o.name);if(a===void 0){if(r.get(o.scope)==="throw")throw new S(`@${o.scope}.${o.name} is not declared on the current ${o.scope}.`);return!1}return a}case"call":{if(o.name==="advance"&&!Q(t.functions,o.name)){let a=o.args[0];if(o.args.length!==1||a===void 0)throw new S(`advance() takes exactly 1 argument, got ${o.args.length}`);let d=Me(a,e);if(d===void 0)throw new S("advance() needs a quality reference (@scope.name of a quality property)");let l=T(s(a),d,"advance");return d[Math.min(l+1,d.length-1)]}let i=Q(t.functions,o.name);if(!i)throw new S(`unknown function '${o.name}'`);return i.eval(o.args,{evaluate:s,ctx:e})}case"flagdelta":throw new S("flagdelta node is only valid as an argument to a flag-delta function");case"unary":{if(o.op==="not"){let a=s(o.operand);if(typeof a!="boolean")throw new S(`'not' requires a boolean operand, got ${typeof a}`);return!a}let i=s(o.operand);if(typeof i!="number")throw new S(`unary '-' requires a numeric operand, got ${typeof i}`);return-i}case"binary":{if(o.op==="and"){let p=s(o.left);if(typeof p!="boolean")throw new S(`'and' requires boolean operands, left is ${typeof p}`);if(!p)return!1;let g=s(o.right);if(typeof g!="boolean")throw new S(`'and' requires boolean operands, right is ${typeof g}`);return g}if(o.op==="or"){let p=s(o.left);if(typeof p!="boolean")throw new S(`'or' requires boolean operands, left is ${typeof p}`);if(p)return!0;let g=s(o.right);if(typeof g!="boolean")throw new S(`'or' requires boolean operands, right is ${typeof g}`);return g}let i=s(o.left),a=s(o.right),d=Me(o.left,e),l=Me(o.right,e),c=d??l;if(c!==void 0){if(d&&l&&!or(d,l)&&(o.op===">"||o.op===">="||o.op==="<"||o.op==="<="))throw new S(`'${o.op}' compares two different qualities, whose stage orders are unrelated`);switch(o.op){case">":return T(i,c,">")>T(a,c,">");case">=":return T(i,c,">=")>=T(a,c,">=");case"<":return T(i,c,"<")<T(a,c,"<");case"<=":return T(i,c,"<=")<=T(a,c,"<=");case"+":case"-":case"*":case"/":throw new S(`'${o.op}' cannot be applied to a quality - a stage is a position, not a number; use advance() to move it`);default:break}}switch(o.op){case"==":return at(i,a);case"!=":return!at(i,a);case">":return N(i,a,">"),i>a;case">=":return N(i,a,">="),i>=a;case"<":return N(i,a,"<"),i<a;case"<=":return N(i,a,"<="),i<=a;case"+":if(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string")return i+a;throw new S(`'+' requires two numbers or two strings, got ${typeof i} and ${typeof a}`);case"-":return N(i,a,"-"),i-a;case"*":return N(i,a,"*"),i*a;case"/":if(N(i,a,"/"),a===0)throw new S("division by zero");return i/a}}}};return s(n)}function at(n,e){if(Array.isArray(n)||Array.isArray(e)){if(!Array.isArray(n)||!Array.isArray(e)||n.length!==e.length)return!1;let t=[...n].sort(),r=[...e].sort();for(let s=0;s<t.length;s++)if(t[s]!==r[s])return!1;return!0}return n===e}function N(n,e,t){if(typeof n!="number"||typeof e!="number")throw new S(`'${t}' requires numeric operands, got ${typeof n} and ${typeof e}`)}function Me(n,e){if(!(n.kind!=="scopedvar"||e.qualities===void 0))return e.qualities(n.scope,n.name)}function T(n,e,t){if(typeof n!="string")throw new S(`'${t}' on a quality compares stages, got ${typeof n}`);let r=e.indexOf(n);if(r<0)throw new S(`"${n}" is not a stage of this quality (stages: ${e.join(", ")})`);return r}var or=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]);function dt(n){if(Number.isNaN(n)||!Number.isFinite(n))return 0;let e=Math.trunc(n)%4294967296;return e<0?e+4294967296:e}function V(n){let e=dt(n);return{next(){e=e+1831565813>>>0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296},state(){return e}}}function H(n,e){for(let t=n.length-1;t>0;t--){let r=Math.floor(e.next()*(t+1));[n[t],n[r]]=[n[r],n[t]]}}var ir={name:"check_flags",count:n=>Math.max(1,n.args.length-1)},ar=[ir];function lt(n,e,t){let r=t?.countingCalls??ar;return ge(n,t?.want??!0,e,r)}function ge(n,e,t,r){if(n.kind==="binary"&&(n.op==="and"||n.op==="or")){let s=ge(n.left,e,t,r),o=ge(n.right,e,t,r);return n.op==="and"===e?s>0&&o>0?s+o:0:Math.max(s,o)}if(n.kind==="unary"&&n.op==="not")return ge(n.operand,!e,t,r);if(n.kind==="call"){let s=r.find(o=>o.name===n.name);if(s){let o=s.count(n),i=t(n);return e?i?o:0:i?0:1}}return t(n)===e?1:0}var ct=[{token:"patter",engine:"Patterplay",means:"Patter's shared globals"},{token:"story",engine:"Storylet Engine",means:"the Storylet Engine's shared @story properties"}];var fe=9999,X=n=>n.ctx.host??{},z=(n,e,t,r)=>{let s=t.evaluate(e[r]);if(typeof s!="string"||s==="")throw new S(`${n}() argument ${r+1} must be a non-empty string`);return s},pt=(n,e,t)=>{if(e.length===0)throw new S(`${n}() requires at least one argument (the flags property)`);let r=t.evaluate(e[0]);if(Array.isArray(r))return r;if(r===!1)return[];throw new S(`${n}() first argument must be a flags property`)},ut=["story","world","box","deck","hand"],dr=ct.map(n=>n.token).filter(n=>!ut.includes(n)),Le={scopes:[...ut.map(n=>({token:n,missing:"throw"})),...dr.map(n=>({token:n,missing:"throw"}))],defaultScope:"story",functions:{random:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){if(n.length!==2)throw new S("random(a, b) requires exactly 2 arguments");let t=X(e).nextRandom;if(!t)throw new S("random() called without a PRNG in context");let r=e.evaluate(n[0]),s=e.evaluate(n[1]);if(typeof r!="number"||typeof s!="number")throw new S("random(a, b) arguments must be numbers");if(!Number.isInteger(r)||!Number.isInteger(s))throw new S("random(a, b) arguments must be integers");let o=Math.min(r,s),i=Math.max(r,s);return Math.floor(t()*(i-o+1))+o}},check_flags:{minArgs:1,returnType:"boolean",flagDeltaArgs:!0,eval(n,e){let t=pt("check_flags",n,e);for(let r=1;r<n.length;r++){let s=n[r];if(s.kind!=="flagdelta")throw new S("check_flags() flag args must be +flagName or -flagName");if(s.sign==="+"?!t.includes(s.name):t.includes(s.name))return!1}return!0}},set_flags:{minArgs:1,returnType:"flags",flagDeltaArgs:!0,eval(n,e){let t=[...pt("set_flags",n,e)];for(let r=1;r<n.length;r++){let s=n[r];if(s.kind!=="flagdelta")throw new S("set_flags() flag args must be +flagName or -flagName");if(s.sign==="+")t.includes(s.name)||t.push(s.name);else{let o=t.indexOf(s.name);o>=0&&t.splice(o,1)}}return t.sort()}},count_played:{minArgs:1,maxArgs:1,returnType:"number",eval(n,e){let t=z("count_played",n,e,0),r=X(e).countPlayed;if(!r)throw new S("count_played() called without a play log in context");return r(t)}},turns_since_played:{minArgs:1,maxArgs:1,returnType:"number",eval(n,e){let t=z("turns_since_played",n,e,0),r=X(e).turnsSincePlayed;if(!r)throw new S("turns_since_played() called without a play log in context");return r(t)}},count_played_in:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){let t=z("count_played_in",n,e,0),r=z("count_played_in",n,e,1),s=X(e).countPlayedIn;if(!s)throw new S("count_played_in() called without a play log in context");return s(t,r)}},turns_since_played_in:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){let t=z("turns_since_played_in",n,e,0),r=z("turns_since_played_in",n,e,1),s=X(e).turnsSincePlayedIn;if(!s)throw new S("turns_since_played_in() called without a play log in context");return s(t,r)}}}};function lr(n){return n.toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function f(n){let e=n.gameId?.trim();return e||(n.title?lr(n.title):"")||n.id}function gt(n){let e=[];for(let a of n.boxes){let d=f(a);for(let l of a.tagGroups)for(let c of l.tags){let p=f(c);e.push({id:c.id,gameId:p,qualified:`${d}/${p}`})}}let t=new Map;for(let a of e){let d=t.get(a.gameId)??[];d.includes(a.qualified)||d.push(a.qualified),t.set(a.gameId,d)}let r=new Map,s=new Map,o=new Map,i=new Map;for(let a of e){let d=t.get(a.gameId)??[a.qualified],l=d.length>1;r.set(a.id,l?a.qualified:a.gameId),s.has(a.qualified)||s.set(a.qualified,a.id),!l&&!s.has(a.gameId)&&s.set(a.gameId,a.id),l&&o.set(a.gameId,d)}for(let a of n.map?.group.tags??[]){let d=f(a);r.set(a.id,d),s.has(d)||s.set(d,a.id);for(let l of n.boxes)i.set(`${f(l)}/${d}`,d)}return{print:r,accept:s,repeated:o,zoneQualified:i}}function ft(n,e,t){return`"value.${n}.${t}": "${e}" is a zone of the project map, which belongs to no box; write "value.${e}.${t}"`}function ht(n,e,t){let r=t.map(o=>`"value.${o}.${e}"`),s=r.length<=1?r[0]??"":`${r.slice(0,-1).join(", ")} or ${r[r.length-1]}`;return`"value.${n}.${e}" names a tag in ${t.length} boxes; write ${s}`}var L="place",cr=/^@(hand|world|story)\.([a-z][a-z0-9_-]*)$/,he=n=>n.startsWith("@"),mt=n=>{let e=cr.exec(n);return e===null?void 0:{scope:e[1],name:e[2]}},pr="storylets/bundle@1",ur="storylets/bundle@0",Ie=[ur,pr];function Y(n,e){return e.usesMap===!0&&n.map!==void 0?[...e.tagGroups,n.map.group]:e.tagGroups}function yt(n){let e=n.boxes.flatMap(t=>t.tagGroups);return n.map!==void 0?[...e,n.map.group]:e}var Z="storylets/save@2",ee="storylets/save@1",me="storylets/savefile@1";function te(n,e){let t=[],r=new Set([...Object.keys(n),...Object.keys(e)]);for(let s of[...r].sort()){let o=n[s],i=e[s];JSON.stringify(o)!==JSON.stringify(i)&&t.push({path:s,from:o,to:i})}return t}var wt=n=>n===void 0?"<unset>":JSON.stringify(n),bt=n=>n.pathPrefix??n.bag.pathPrefix;function re(n,e={}){let t=e.sink??(p=>console.log(p)),r=e.label??"",s=p=>{t(`${r}${p.path}: ${wt(p.from)} -> ${wt(p.to)}`)},o=()=>{let p={};for(let g of n.mounts()){let u=bt(g);for(let[m,h]of Object.entries(g.bag.values))p[u+m]=h}return Object.assign(p,n.extra?.()??{}),structuredClone(p)},i=o(),a=[],d=[],l=(p,g)=>g.onAudit(u=>{let m=structuredClone({path:p+u.name,from:u.prev,to:u.next});s(m),a.push(m),i[m.path]=structuredClone(u.next)}),c=()=>{let p=n.mounts();if(!(d.length===p.length&&p.every((u,m)=>d[m].bag===u.bag))){for(let u of d)u.off();d=p.map(u=>({bag:u.bag,off:l(bt(u),u.bag)}))}};return c(),{snapshot:o,capture(){let p=o(),g=te(i,p);for(let m of g)s(m);let u=[...a,...g];return a=[],i=p,c(),u},dispose(){for(let p of d)p.off();d=[],a=[]}}}var F=class n{values=Object.create(null);decls=new Map;subscribers=new Set;auditors=new Set;norm;pathPrefix;constructor(e=[],t){this.norm=t?.normalise??(r=>r.toLowerCase()),this.pathPrefix=t?.pathPrefix??"",this.seed(e)}seed(e){for(let t of e){let r=this.norm(t.name);this.decls.set(r,t),this.values[r]=structuredClone(t.default??we(t))}}get(e){return this.values[this.norm(e)]}normalise(e){return this.norm(e)}writable(e){return this.decls.get(this.norm(e))?.writable!==!1}set(e,t,r){let s=this.norm(e);if(!r?.host&&!this.writable(s))throw new Error(`'${e}' is read-only`);let o={name:s,prev:this.values[s],next:t,silent:r?.silent??!1,reason:r?.reason};this.values[s]=t;for(let i of[...this.auditors])i(o);if(!o.silent)for(let i of[...this.subscribers])i(o);return o}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}onAudit(e){return this.auditors.add(e),()=>this.auditors.delete(e)}rows(){return[...this.decls.entries()].map(([e,t])=>xt(t,this.get(e),void 0,e,this.pathPrefix))}declarations(){return[...this.decls.values()]}clone(){let e=new n([],{normalise:this.norm,pathPrefix:this.pathPrefix});return e.decls=new Map(this.decls),Object.assign(e.values,structuredClone(this.values)),e}reseed(e){for(let t of Object.keys(this.values))delete this.values[t];this.decls.clear(),this.seed(e)}save(){return structuredClone(this.values)}load(e){for(let[t,r]of Object.entries(e))this.values[this.norm(t)]=r}};function xt(n,e,t,r,s=""){let o=r??n.name.toLowerCase();return{name:o,path:s+o,type:n.type,value:e,default:n.default??we(n),...n.values!==void 0?{values:n.values}:{},...n.stages!==void 0?{stages:n.stages}:{},writable:t??n.writable??!0}}var gr=n=>n.toLowerCase(),De=1,ye=class{scopes=new Map;parked=new Map;rev=0;get revision(){return this.rev}defineOwned(e,t,r){let s=typeof r=="string"?{pathPrefix:r}:r??{},o=new F(t,{pathPrefix:s.pathPrefix??`${e}.`,...s.normalise?{normalise:s.normalise}:{}});return this.mountOwned(e,o,s.owner!==void 0?{owner:s.owner}:void 0)}mountOwned(e,t,r){this.assertFree(e,r?.owner),this.scopes.set(e,{kind:"owned",bag:t,...r?.owner!==void 0?{owner:r.owner}:{}}),this.rev++;let s=this.parked.get(e);return s&&(t.load(s),this.parked.delete(e)),this}remove(e,t){let r=this.scopes.get(e);if(!r)throw new Error(`unknown scope '@${e}'`);return t?.keep&&r.kind==="owned"&&this.parked.set(e,r.bag.save()),this.scopes.delete(e),this.rev++,this}discardParked(e){if(e===void 0)this.parked.clear();else for(let t of[...this.parked.keys()])t.startsWith(e)&&this.parked.delete(t);return this}ownedBag(e){let t=this.scopes.get(e);if(!t||t.kind!=="owned")throw new Error(`'@${e}' is not an owned scope`);return t.bag}reseedOwned(e,t){return this.ownedBag(e).reseed(t),this}defineForeign(e,t,r=[],s=!0){let o=typeof s=="boolean"?{writable:s}:s;this.assertFree(e,o.owner);let i=o.normalise??gr,a=new Map;for(let d of r)a.set(i(d.name),d);return this.scopes.set(e,{kind:"foreign",resolver:t,decls:a,scopeWritable:o.writable??!0,norm:i,...o.owner!==void 0?{owner:o.owner}:{}}),this.rev++,this}has(e){return this.scopes.has(e)}get(e,t){let r=this.scopes.get(e);if(r)return r.kind==="owned"?r.bag.get(t):r.resolver.get(r.norm(t))}set(e,t,r,s){let o=this.scopes.get(e);if(!o)throw new Error(`unknown scope '@${e}'`);if(o.kind==="owned"){if(!s?.host&&!o.bag.writable(t))throw new Error(`'@${e}.${t}' is read-only`);o.bag.set(t,r,s?.host?{host:!0}:void 0);return}let i=o.norm(t);if(!o.resolver.set)throw new Error(`'@${e}.${t}' is read-only`);if(!s?.host&&!this.foreignWritable(o,i))throw new Error(`'@${e}.${t}' is read-only`);o.resolver.set(i,r)}foreignWritable(e,t){return e.resolver.set?e.decls.get(t)?.writable??e.scopeWritable:!1}listProperties(){let e=[];for(let[t,r]of this.scopes){let s=r.owner!==void 0?{owner:r.owner}:{};if(r.kind==="owned")for(let o of r.bag.rows())e.push({scope:t,...s,...o});else for(let[o,i]of r.decls)e.push({scope:t,...s,...xt(i,r.resolver.get(o),this.foreignWritable(r,o),o,`${t}.`)})}return e}toEvalContext(e,t){let r=this.view(t?.aliases),s={};for(let[i,a]of r)s[i]=a.kind==="owned"?a.bag.values:a.resolver;let o=this.qualityLadders(r);return o.size===0?{scopes:s,host:e}:{scopes:s,host:e,qualities:(i,a)=>{let d=r.get(i);return d?o.get(i)?.get(fr(d)(a)):void 0}}}view(e){let t=new Map(this.scopes);for(let[r,s]of Object.entries(e??{})){let o=this.scopes.get(s);if(!o)throw new Error(`alias '@${r}' names '${s}', which is not registered`);t.set(r,o)}return t}qualityLadders(e){let t=new Map;for(let[r,s]of e)for(let[o,i]of vt(s)){if(i.type!=="quality"||i.stages===void 0)continue;let a=t.get(r);a||(a=new Map,t.set(r,a)),a.set(o,i.stages)}return t}toSchema(e){let t=new Map;for(let[r,s]of this.view(e?.aliases)){let o=vt(s);if(o.length===0)continue;let i=new Map;for(let[a,d]of o)i.set(a,{type:d.type,enumValues:d.values,...d.stages!==void 0?{stages:d.stages}:{}});t.set(r,i)}return{properties:t}}save(){let e={};for(let[t,r]of this.scopes)r.kind==="owned"&&(e[t]=r.bag.save());for(let[t,r]of this.parked)e[t]=structuredClone(r);return e}load(e,t){t?.keepParked||this.parked.clear();for(let[r,s]of Object.entries(e)){let o=this.scopes.get(r);o?.kind==="owned"?o.bag.load(s):o||this.parked.set(r,structuredClone(s))}}saveFragment(){return{version:De,scopes:this.save()}}loadFragment(e){if(e.version!==De)throw new Error(`unsupported owned-state fragment version ${e.version} (supported: ${De})`);this.load(e.scopes)}assertFree(e,t){let r=this.scopes.get(e);if(!r)return;let s=r.owner!==void 0?` by ${r.owner}`:"",o=t!==void 0?` (wanted by ${t})`:"";throw new Error(`scope '@${e}' is already registered${s}${o}`)}};function vt(n){return n.kind==="foreign"?[...n.decls.entries()]:n.bag.declarations().map(e=>[n.bag.normalise(e.name),e])}function fr(n){return n.kind==="foreign"?n.norm:e=>n.bag.normalise(e)}function we(n){if(n.default!==void 0)return n.default;switch(n.type){case"boolean":return!1;case"number":return 0;case"string":return"";case"enum":return n.values?.[0]??"";case"flags":return[];case"quality":return n.stages?.[0]??"";default:return!1}}var St=(n,e,t)=>`${n}${e}${t}`,b=class extends Error{constructor(e){super(e),this.name="StoryletError"}},de="storylets/durable@1",oe=(n,e)=>n.shared??e,hr=(n,e)=>n.redraw==="never"&&(n.durable??e.durable??!1)===!0,Lt=n=>n.sharedCopies??n.copies??1,U="Storylet Engine",He=n=>n,qe=n=>n.replace(/%/g,"%25").replace(/\//g,"%2F"),Te=n=>n.replace(/%2F/g,"/").replace(/%25/g,"%"),Ae=(n,e)=>`storylets/${n}/${qe(e)}`,Fe=n=>`storylets/flow/${qe(n)}/`,_e=(n,e,t)=>e==="story"?`${Fe(n)}story`:`${Fe(n)}${e}/${qe(t)}`,ie=()=>({story:{},box:{},deck:{},hand:{},value:{}});function mr(n,e){let t=ie(),r=new Map,s={},o=i=>{let a=Te(i);if(!e.has(a))return;let d=r.get(a);return d||(d=ie(),r.set(a,d)),d};for(let[i,a]of Object.entries(n)){let d;if(i==="story")t.story=a;else if(d=/^storylets\/(box|deck|hand|value)\/([^/]+)$/.exec(i))t[d[1]][Te(d[2])]=a;else if(d=/^storylets\/flow\/([^/]+)\/story$/.exec(i)){let l=o(d[1]);l&&(l.story=a)}else if(d=/^storylets\/flow\/([^/]+)\/(box|deck|hand|value)\/([^/]+)$/.exec(i)){let l=o(d[1]);l&&(l[d[2]][Te(d[3])]=a)}else i.startsWith("storylets/")||(s[i]=a)}return{shared:t,flows:r,rest:s}}function Et(n,e,t){Object.keys(n.story).length>0&&(t[e("story")]=n.story);for(let r of O)for(let[s,o]of Object.entries(n[r]))Object.keys(o).length>0&&(t[e(r,s)]=o)}var kt=(n,e)=>new F(n,{normalise:He,pathPrefix:e}),R=(n,e)=>n!==void 0&&Object.prototype.hasOwnProperty.call(n.values,e)?n.values[e]:void 0,Ve=Object.freeze(Object.create(null));function Pt(n){return typeof n=="boolean"?n:typeof n=="number"?n!==0:typeof n=="string"?n!=="":n.length>0}var yr={story:!0,box:!1,deck:!1,hand:!1,value:!1},It=(n,e)=>e.shared??yr[n],wr=(n,e)=>e.filter(t=>It(n,t)),br=(n,e)=>e.filter(t=>!It(n,t)),O=["box","deck","hand","value"],Dt=n=>O.includes(n??""),be=()=>({gameId:new Map,id:new Map,repeated:new Map,zoneQualified:new Map}),vr=()=>({box:be(),deck:be(),hand:be(),value:be()}),je=(n,e)=>{let t=f(e);n.gameId.set(e.id,t),n.id.has(t)||n.id.set(t,e.id)},xr=(n,e)=>{let t=gt(e);for(let[r,s]of t.print)n.gameId.set(r,s);for(let[r,s]of t.accept)n.id.set(r,s);for(let[r,s]of t.repeated)n.repeated.set(r,s);for(let[r,s]of t.zoneQualified)n.zoneQualified.set(r,s)},Ct=(n,e)=>{let t=[],r=new Set,s=o=>{r.has(o.address)||(r.add(o.address),t.push(o))};for(let o of e.story)o.durable===!0&&s({address:`story.${o.name}`,kind:"story",decl:o});for(let o of O)for(let[i,a]of e[o])for(let d of a)d.durable===!0&&s({address:`${A(n,o,i)}.${d.name}`,kind:o,owner:i,decl:d});return t},ze=(n,e)=>e.kind==="story"?n.story:n[e.kind].get(e.owner),Tt=(n,e)=>{let t=[];for(let r of e){let s=R(ze(n,r),r.decl.name);s!==void 0&&t.push([r.address,s])}return Object.fromEntries(W(t,([r])=>r))};function Bt(n,e,t,r,s,o){let i=g=>({...s!==void 0?{flow:s}:{},path:g}),a=new Map(e.map(g=>[g.address,g])),d=new Map,l=r.values??{};for(let[g,u]of Object.entries(l)){let m=a.get(g);if(m===void 0){o.droppedProperties.push(i(g));continue}if(!Ht(m.decl,u)){o.retypedProperties.push(i(g));continue}d.set(m,u)}for(let g of e)Object.prototype.hasOwnProperty.call(l,g.address)||o.defaultedProperties.push(i(g.address));let c=new Set(t.map(g=>g.card.id)),p=[];for(let g of r.spent??[]){let u=n.cardsByGameId.get(g);u!==void 0&&c.has(u.card.id)?p.push(u.card.id):s!==void 0?o.droppedCooldowns.push({flow:s,card:g}):o.droppedSpent.push(g)}return{values:d,cards:p}}var $t=(n,e)=>{let t=e?.schema;if(t!==de)throw new b(`unsupported durable schema: ${String(t)}`);let r=n.bundle.content.project;if(e.content?.project!==r)throw new b(`durable state is for project "${String(e.content?.project)}", bundle is "${r}"`)},At=(n,e,t)=>{n?.set(e,structuredClone(t),{silent:!0,reason:"host durable",host:!0})},Ot=(n,e)=>e.template!==void 0?n.templatesById.get(e.template)?.properties??[]:e.properties??[],A=(n,e,t)=>`${e}.${n.owners[e].gameId.get(t)??t}`,Sr=(n,e,t)=>{let r=n.owners[e].repeated.get(t);if(r!==void 0)return{ambiguous:r};let s=n.owners[e].zoneQualified.get(t);if(s!==void 0)return{zone:s};let o=n.owners[e].id.get(t);if(o!==void 0)return{id:o,legacy:!1};if(n.owners[e].gameId.has(t))return{id:t,legacy:!0}},Vt=(n,e,t,r)=>{let s=Sr(n,e,t);if(s===void 0)throw new b(`no ${e} store "${t}"`);if("ambiguous"in s)throw new b(ht(t,r,s.ambiguous));if("zone"in s)throw new b(ft(t,s.zone,r));return s},jt=(n,e,t,r)=>`"${e}.${t}.${r}" names the ${e} by its internal id; write "${A(n,e,t)}.${r}". The internal-id form is refused after the next release.`,Nt=(n,e)=>{let t=r=>new Map([...e[r]].map(([s,o])=>[s,kt(o,`${A(n,r,s)}.`)]));return{story:kt(e.story,"story."),box:t("box"),deck:t("deck"),hand:t("hand"),value:t("value")}},Er=n=>({story:n.story.values,box:Object.fromEntries([...n.box].map(([e,t])=>[e,t.values])),deck:Object.fromEntries([...n.deck].map(([e,t])=>[e,t.values])),hand:Object.fromEntries([...n.hand].map(([e,t])=>[e,t.values])),value:Object.fromEntries([...n.value].map(([e,t])=>[e,t.values]))}),kr=(n,e)=>{n.story.load(e?.story??{});for(let t of O)for(let[r,s]of Object.entries(e?.[t]??{}))n[t].get(r)?.load(s)},ne=()=>({evicted:[],droppedCooldowns:[],droppedSpent:[],droppedProperties:[],defaultedProperties:[],retypedProperties:[]}),Ge="",W=(n,e)=>[...n].map(t=>({item:t,k:e(t)})).sort((t,r)=>t.k<r.k?-1:t.k>r.k?1:0).map(t=>t.item),Ne=n=>`${n.flow??""}${Ge}${n.path}`;function Ht(n,e){switch(n.type){case"boolean":return typeof e=="boolean";case"number":return typeof e=="number";case"string":return typeof e=="string";case"enum":return typeof e=="string"&&(n.values===void 0||n.values.includes(e));case"quality":return typeof e=="string"&&(n.stages===void 0||n.stages.includes(e));case"flags":return Array.isArray(e)&&e.every(t=>typeof t=="string"&&(n.values===void 0||n.values.includes(t)));default:return!0}}function Rt(n,e,t,r,s){let o=l=>({...r!==void 0?{flow:r}:{},path:t(l)}),i=new Map((n??[]).map(l=>[l.name,l])),a=e??{},d={};for(let[l,c]of Object.entries(a)){let p=i.get(l);if(p===void 0){s.droppedProperties.push(o(l));continue}if(!Ht(p,c)){s.retypedProperties.push(o(l));continue}d[l]=c}for(let l of n??[])l.name in a||s.defaultedProperties.push(o(l.name));return d}function Mt(n,e,t,r,s){let o={story:Rt(e.story,t?.story,i=>`story.${i}`,r,s),box:{},deck:{},hand:{},value:{}};for(let i of O){let a=t?.[i]??{},d=[...new Set([...e[i].keys(),...Object.keys(a)])].sort();for(let l of d){let c=A(n,i,l);o[i][l]=Rt(e[i].get(l),a[l],p=>`${c}.${p}`,r,s)}}return o}function se(n,e,t,r){let s=e.version!==n.version||e.hash!==n.hash,o=W(r.evicted,p=>[p.flow,p.hand,p.card,p.reason].join(Ge)),i=W(r.droppedCooldowns,p=>`${p.flow}${Ge}${p.card}`),a=[...r.droppedSpent].sort(),d=W(r.droppedProperties,Ne),l=W(r.defaultedProperties,Ne),c=W(r.retypedProperties,Ne);return{exact:!s&&o.length===0&&i.length===0&&a.length===0&&d.length===0&&l.length===0&&c.length===0,project:n.project,version:{saved:e.version,bundle:n.version},hash:{saved:e.hash,bundle:n.hash},flows:t,evicted:o,droppedCooldowns:i,droppedSpent:a,droppedProperties:d,defaultedProperties:l,retypedProperties:c}}var Pr=n=>{let e=n.schema;if(typeof e!="string"||!Ie.includes(e))throw new b(`unsupported bundle schema: ${String(e)} (this runtime reads ${Ie.join(" and ")})`);let t=[],r=n.map?.group,s=r!==void 0?f(r):void 0;r!==void 0&&s===L&&t.push(`the project map's tag group is called "${L}", which is reserved for a box's own hands`);let o=new Map;for(let i of n.boxes)for(let a of i.tagGroups)for(let d of a.tags){let l=f(d);o.has(l)||o.set(l,{box:f(i),group:f(a)})}for(let i of r?.tags??[]){let a=f(i),d=o.get(a);d!==void 0&&t.push(`the project map's zone "${a}" has the name of tag "${a}" in box "${d.box}", group "${d.group}", so "value.${a}.<name>" would name two things`)}for(let i of n.boxes){let a=f(i);if(i.usesMap===!0){if(r===void 0){t.push(`box "${a}" uses the project map, but the bundle has no map`);continue}i.tagGroups.find(c=>f(c)===s)!==void 0&&t.push(`box "${a}" uses the project map and declares its own tag group "${s}", the map's name`);continue}if(r===void 0)continue;let d=l=>{t.push(`box "${a}" is not on the project map, but ${l} names the map's tag group "${s}"`)};for(let l of i.decks)for(let c of l.cards)c.tags?.[r.id]!==void 0&&d(`card "${f(c)}"`);for(let l of i.handTemplates)(l.bindings?.[r.id]!==void 0||l.chooses?.includes(r.id)===!0)&&d(`hand template "${f(l)}"`);for(let l of i.hands)(l.chosen?.[r.id]!==void 0||l.rule?.bindings?.[r.id]!==void 0)&&d(`hand "${f(l)}"`)}if(t.length>0)throw new b(`bundle refused: ${t.join("; ")}`)},ve=class n{internals;seed;onReplacedFlow;flowsById=new Map;engineTraceHandlers=new Set;hostWorld;creationOptions;sharedMounts=[];constructor(e,t={}){Pr(e),this.creationOptions=t,this.seed=t.seed??0,this.onReplacedFlow=t.onReplacedFlow,t.world!==void 0&&(this.hostWorld=t.world);let r={bundle:e,...t.log?{logCap:typeof t.log=="object"?t.log.cap??1e3:1e3}:{},cardsById:new Map,cardsByGameId:new Map,boxesByGameId:new Map,boxesById:new Map,handsById:new Map,handsByGameId:new Map,owners:vr(),templatesById:new Map,groupsById:new Map,requiredGroups:new Set,nodeCache:new WeakMap,ladders:{world:new Map,story:new Map,box:new Map,deck:new Map,value:new Map,hand:new Map},hasQualities:!1,hasShared:!1,flowDecls:{story:[],box:new Map,deck:new Map,hand:new Map,value:new Map},sharedDecls:{story:[],box:new Map,deck:new Map,hand:new Map,value:new Map},durable:{shared:[],flow:[],sharedCards:[],flowCards:[]},shared:void 0,registry:t.registry??new ye,ownsRegistry:t.registry===void 0,selfWorld:!1,registryView:()=>i(),worldResolver:void 0,worldReadOnly:new Set,emitEngine:(d,l,c)=>{this.internals.logCap!==void 0&&(this.engineLog.push({...l,flow:d,seq:this.engineSeq++,...c!==void 0?{turn:c}:{}}),this.engineLog.length>this.internals.logCap&&this.engineLog.splice(0,this.engineLog.length-this.internals.logCap));for(let p of[...this.engineTraceHandlers])p(d,l)},engineTracing:()=>this.engineTraceHandlers.size>0};this.internals=r;let s=-1,o={scopes:{},qualities:void 0},i=()=>{let d=r.registry;if(d.revision!==s){let l=d.toEvalContext(),c={};for(let[p,g]of Object.entries(l.scopes))p.includes("/")||(c[p]=g);o={scopes:c,qualities:l.qualities},s=d.revision}return o};xr(r.owners.value,e);for(let d of e.boxes){r.boxesById.set(d.id,d),r.boxesByGameId.set(f(d),d),je(r.owners.box,d);for(let l of d.tagGroups)r.groupsById.set(l.id,{group:l,box:d}),l.required===!0&&r.requiredGroups.add(l.id);for(let l of d.decks){je(r.owners.deck,l),l.shared===!0&&(r.hasShared=!0);for(let c of l.cards){let p={card:c,deck:l,box:d};r.cardsById.set(c.id,p),r.cardsByGameId.set(f(c),p),c.shared===!0&&(r.hasShared=!0),hr(c,l)&&(oe(c,l.shared??!1)?r.durable.sharedCards:r.durable.flowCards).push(p)}}for(let l of d.handTemplates)r.templatesById.set(l.id,l);for(let l of d.hands)r.handsById.set(l.id,{hand:l,box:d}),r.handsByGameId.set(f(l),{hand:l,box:d}),je(r.owners.hand,l)}e.map!==void 0&&(r.groupsById.set(e.map.group.id,{group:e.map.group}),e.map.group.required===!0&&r.requiredGroups.add(e.map.group.id)),this.initLadders();let a=d=>({story:d("story",e.story.properties),box:new Map(e.boxes.map(l=>[l.id,d("box",l.properties)])),deck:new Map(e.boxes.flatMap(l=>l.decks.map(c=>[c.id,d("deck",c.properties)]))),hand:new Map(e.boxes.flatMap(l=>l.hands.map(c=>[c.id,d("hand",Ot(r,c))]))),value:new Map(yt(e).flatMap(l=>l.tags.map(c=>[c.id,d("value",c.properties??[])])))});r.flowDecls=a(br),r.sharedDecls=a(wr),r.durable.shared=Ct(r,r.sharedDecls),r.durable.flow=Ct(r,r.flowDecls),this.initShared(this.hostWorld)}initShared(e){let t=this.internals,r=t.registry,s=t.bundle.world.properties;t.shared=Nt(t,t.sharedDecls),t.worldReadOnly=new Set(t.bundle.world.properties.filter(a=>a.writable===!1).map(a=>a.name));let o=[],i=(a,d)=>{d(),o.push(a),this.sharedMounts.push({key:a,mount:d})};try{let a=t.shared.story;i("story",()=>{r.mountOwned("story",a,{owner:U})});for(let d of O)for(let[l,c]of t.shared[d])c.declarations().length!==0&&i(Ae(d,l),()=>{r.mountOwned(Ae(d,l),c,{owner:U})});if(e!==void 0)i("world",()=>{r.defineForeign("world",e,s,{normalise:He,owner:U})});else if(t.ownsRegistry&&!r.has("world")){r.defineOwned("world",s,{normalise:He,pathPrefix:"world.",owner:U});let d=r.ownedBag("world");o.push("world"),this.sharedMounts.push({key:"world",mount:()=>{r.mountOwned("world",d,{owner:U})}}),t.selfWorld=!0}}catch(a){for(let d of o)r.remove(d,{keep:!0});throw a}t.worldResolver={get:a=>r.get("world",a),set:(a,d)=>{r.set("world",a,d)}},e!==void 0?t.worldSet=e.set!==void 0?(a,d)=>{r.set("world",a,d,{host:!0})}:void 0:t.worldSet=(a,d,l)=>{r.set("world",a,d,l===!0?{host:!0}:void 0)}}reseedShared(){let{shared:e,sharedDecls:t,registry:r}=this.internals;e.story.reseed(t.story);for(let s of O)for(let[o,i]of e[s])i.reseed(t[s].get(o)??[]);this.internals.selfWorld&&r.reseedOwned("world",this.internals.bundle.world.properties)}initLadders(){let e=this.internals,t=o=>{let i=new Map;for(let a of o??[])a.type==="quality"&&a.stages!==void 0&&i.set(a.name,a.stages);return i},r=e.bundle;e.ladders.world=t(r.world.properties),e.ladders.story=t(r.story.properties);for(let o of r.boxes){e.ladders.box.set(o.id,t(o.properties));for(let i of o.decks)e.ladders.deck.set(i.id,t(i.properties));for(let i of o.tagGroups)for(let a of i.tags)e.ladders.value.set(a.id,t(a.properties));for(let i of o.hands)e.ladders.hand.set(i.id,t(Ot(e,i)))}for(let o of r.map?.group.tags??[])e.ladders.value.set(o.id,t(o.properties));let s=o=>[...o.values()].some(i=>i.size>0);e.hasQualities=e.ladders.world.size>0||e.ladders.story.size>0||s(e.ladders.box)||s(e.ladders.deck)||s(e.ladders.value)||s(e.ladders.hand)}get registry(){return this.internals.registry}openFlow(e,t={}){return this.open(e,t,!1)}open(e,t,r){if(t.durable!==void 0&&t.restore!==void 0)throw new b(`openFlow "${e}": restore and durable cannot be given together; a restore already carries the flow's durable state`);let s;if(t.durable!==void 0){$t(this.internals,t.durable);let d=ne(),{flow:l,flowCards:c}=this.internals.durable;s={plan:Bt(this.internals,l,c,t.durable,e,d),draft:d,content:t.durable.content}}this.assertExternalScopes();let o=t.restore!==void 0?this.sharedClaims(e):void 0,i=this.flowsById.get(e);if(i){let d=i.heldCardIds().length;d>0&&this.onReplacedFlow?.(e,d),i.markClosed()}r||this.internals.registry.discardParked(Fe(e));let a=new ae(this,this.internals,e,t.seed??this.seed);if(this.flowsById.set(e,a),t.restore!==void 0){let d=ne(),l=this.planFlowRestore(e,structuredClone(t.restore),o,d);a.restore(l);let c=this.internals.bundle.content;t.onRestoreReport?.(se(c,c,[e],d))}return s!==void 0&&(a.writeDurable(s.plan),t.onRestoreReport?.(se(this.internals.bundle.content,s.content,[e],s.draft))),a}getFlow(e){return this.flowsById.get(e)}flows(){return[...this.flowsById.values()]}closeFlow(e){let t=this.flowsById.get(e);t&&(this.flowsById.delete(e),t.markClosed())}dropFlow(e,t){this.flowsById.get(e)===t&&this.flowsById.delete(e)}reset(){this.dropRun(!1),this.reseedShared(),this.internals.registry.discardParked("storylets/")}dropRun(e){this.engineLog=[];for(let[t,r]of this.flowsById)r.releaseBags(e!==!1&&e.has(t)),r.markClosed();this.flowsById.clear(),this.spent.clear()}spent=new Set;isTaken(e){return this.spent.has(e)}markTaken(e){this.spent.add(e)}engineLog=[];engineSeq=0;log(){return this.engineLog}clearLog(){this.engineLog=[]}sharedClaims(e){let t=new Map;for(let[r,s]of this.flowsById)if(r!==e)for(let o of s.heldCardIds())t.set(o,(t.get(o)??0)+1);return t}getProperty(e){let t=this.resolveShared(e),r=t.kind==="world"?this.internals.worldResolver.get(t.name):t.kind==="scope"?this.internals.registry.get(t.token,t.name):t.bag.get(t.name);if(r===void 0)throw new b(`no property at "${e}"`);return r}setProperty(e,t){let r=this.resolveShared(e);if(r.kind==="world"){if(!this.internals.worldSet)throw new b("@world is read-only here: the host bound no write");this.internals.worldSet(r.name,t,!0);return}if(r.kind==="scope"){this.internals.registry.set(r.token,r.name,t,{host:!0});return}r.bag.set(r.name,t,{silent:!0,reason:"host setProperty",host:!0})}resolveShared(e){let t=e.split("."),r=()=>{throw new b(`"${e}" is per-flow state - read it on a Flow, not the Engine`)};if(t.length===2&&t[0]==="world")return{kind:"world",name:t[1]};if(t.length===2&&t[0]!=="story"&&this.internals.registry.has(t[0]))return{kind:"scope",token:t[0],name:t[1]};if(t.length===2&&t[0]==="story"){let s=t[1];if(R(this.internals.shared.story,s)!==void 0)return{kind:"bag",bag:this.internals.shared.story,name:s};throw this.internals.flowDecls.story.some(o=>o.name===s)&&r(),new b(`no property at "${e}"`)}if(t.length===3&&Dt(t[0])){let s=t[0],[,o,i]=t,a=Vt(this.internals,s,o,i);a.legacy&&this.diagnose(jt(this.internals,s,o,i));let d=a.id,l=this.internals.shared[s].get(d);if(l!==void 0&&R(l,i)!==void 0)return{kind:"bag",bag:l,name:i};throw this.internals.flowDecls[s].get(d)?.some(c=>c.name===i)&&r(),l===void 0&&!this.internals.flowDecls[s].has(d)?new b(`no ${s} store "${o}"`):new b(`no property at "${e}"`)}throw new b(`bad property path "${e}"`)}diagnose(e){this.internals.emitEngine("",{type:"diagnostic",where:"property address",message:e})}assertExternalScopes(){for(let e of this.internals.bundle.externalScopes??[])if(!this.internals.registry.has(e))throw new b(`this content names @${e}, which no engine on this registry registered: give every engine the game's one registry`)}listProperties(){let e=[];for(let r of this.internals.bundle.world.properties){let s=this.internals.worldResolver.get(r.name);e.push({path:`world.${r.name}`,name:r.name,type:r.type,value:s??r.default,default:r.default,...r.values!==void 0?{values:r.values}:{},...r.stages!==void 0?{stages:r.stages}:{},writable:this.internals.worldSet!==void 0&&!this.internals.worldReadOnly.has(r.name)})}let t=(r,s)=>{for(let o of s.rows())e.push(o)};t("story",this.internals.shared.story);for(let r of O)for(let[s,o]of this.internals.shared[r])t(A(this.internals,r,s),o);return e}listBags(){let e=[{prefix:"story",bag:this.internals.shared.story}];for(let t of O)for(let[r,s]of this.internals.shared[t])e.push({prefix:A(this.internals,t,r),bag:s});return e}subscribeTrace(e){return this.engineTraceHandlers.add(e),()=>{this.engineTraceHandlers.delete(e)}}hotSwap(e,t={}){if(e.content.project!==this.internals.bundle.content.project)throw new b(`hotSwap: the bundle is for project "${e.content.project}", this engine runs "${this.internals.bundle.content.project}"`);let r={...this.creationOptions,...t},s=this.saveGame(),o=this.internals.registry;if(this.internals.ownsRegistry){let c=new n(e,{...r,registry:void 0});return{engine:c,report:c.loadGame(s)}}let i={};for(let[c,p]of Object.entries(o.save()))(c==="story"||c.startsWith("storylets/"))&&(i[c]=p);let a=new Set([...this.sharedMounts.map(c=>c.key),...[...this.flowsById.values()].flatMap(c=>c.registeredKeys())]),d=Object.fromEntries(Object.entries(i).filter(([c])=>!a.has(c)));for(let{key:c}of this.sharedMounts)o.has(c)&&o.remove(c);for(let c of this.flowsById.values())c.releaseBags(!1);let l;try{l=new n(e,{...r,registry:o});let c=l.loadGame({...s,registry:i}),p=Object.fromEntries(Object.entries(d).filter(([g])=>!o.has(g)));return Object.keys(p).length>0&&o.load(p,{keepParked:!0}),this.dropRun(!1),{engine:l,report:c}}catch(c){l?.dropRun(!1);for(let{key:p}of l?.sharedMounts??[])o.has(p)&&o.remove(p);o.discardParked("storylets/");for(let{mount:p}of this.sharedMounts)p();for(let p of this.flowsById.values())p.mountBags();throw this.reseedShared(),o.load(i,{keepParked:!0}),c}}saveGame(){return structuredClone({schema:Z,content:this.internals.bundle.content,...this.internals.ownsRegistry?{registry:this.registrySection()}:{},shared:{spent:[...this.spent].sort()},flows:Object.fromEntries([...this.flowsById].map(([e,t])=>[e,t.snapshot(!1)]))})}registrySection(){let e=this.internals.registry.save(),t={},r=s=>{Object.prototype.hasOwnProperty.call(e,s)&&!Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=e[s])};for(let{key:s}of this.sharedMounts)r(s);for(let s of Object.values(Object.fromEntries(this.flowsById)))for(let o of s.registeredKeys())r(o);for(let s of Object.keys(e))r(s);return t}saveFlow(e){let t=this.flowsById.get(e);if(!t)throw new b(`unknown flow "${e}"`);return structuredClone(t.snapshot(!0))}saveDurable(){let{bundle:e,shared:t,durable:r}=this.internals;return structuredClone({schema:de,content:e.content,values:Tt(t,r.shared),spent:r.sharedCards.filter(s=>this.spent.has(s.card.id)).map(s=>f(s.card)).sort()})}loadDurable(e){let t=this.internals;$t(t,e);let r=ne(),s=Bt(t,t.durable.shared,t.durable.sharedCards,e,void 0,r);for(let o of t.durable.shared){let i=s.values.has(o)?s.values.get(o):we(o.decl);At(ze(t.shared,o),o.decl.name,i)}for(let o of s.cards)this.spent.add(o);return se(t.bundle.content,e.content,[],r)}previewLoad(e){return this.assertSameProject(e),this.planLoad(e).report}previewFlowRestore(e,t){let r=ne();this.planFlowRestore(e,t,this.sharedClaims(e),r);let s=this.internals.bundle.content;return se(s,s,[e],r)}loadGame(e){this.assertSameProject(e),this.assertExternalScopes();let t=this.planLoad(structuredClone(e)),r=this.internals.registry;t.sections!==void 0?(this.reset(),this.internals.ownsRegistry?r.load(t.sections):r.load(t.sections,{keepParked:!0})):this.dropRun(new Set(t.flows.map(([s])=>s)));for(let s of t.spent)this.spent.add(s);for(let[s,o]of t.flows)this.open(s,{},!0).restore(o);return t.report}assertSameProject(e){if(e.content.project!==this.internals.bundle.content.project)throw new b(`save is for project "${e.content.project}", bundle is "${this.internals.bundle.content.project}"`)}planLoad(e){let t=e.schema;if(t!==Z&&t!==ee)throw new b(`unsupported save schema: ${String(t)}`);let r=ne(),s=new Set(Object.keys(e.flows??{})),o;e.schema===ee?o={shared:e.shared?.props??ie(),flows:new Map(Object.entries(e.flows??{}).map(([c,p])=>[c,p.props??ie()])),rest:{}}:e.registry!==void 0&&(o=mr(e.registry,s));let i=o!==void 0?Mt(this.internals,this.internals.sharedDecls,o.shared,void 0,r):void 0,a=[];for(let c of e.shared?.spent??[])this.internals.cardsById.has(c)?a.push(c):r.droppedSpent.push(c);let d=[],l=o!==void 0?{...o.rest}:void 0;l!==void 0&&i!==void 0&&Et(i,(c,p)=>c==="story"?"story":Ae(c,p),l);for(let[c,p]of Object.entries(e.flows??{})){let g=o!==void 0?{...p,props:o.flows.get(c)??ie()}:{...p},u=this.planFlowRestore(c,g,void 0,r);l!==void 0&&u.props!==void 0&&(Et(u.props,(m,h)=>_e(c,m,h),l),delete u.props),d.push([c,u])}return{report:se(this.internals.bundle.content,e.content,d.map(([c])=>c),r),...l!==void 0?{sections:l}:{},spent:a,flows:d}}planFlowRestore(e,t,r,s){let o=this.internals,i=t.props!==void 0?Mt(o,o.flowDecls,t.props,e,s):void 0,a={};for(let[p,g]of Object.entries(t.cooldowns??{}))o.cardsById.has(p)?a[p]=g:s.droppedCooldowns.push({flow:e,card:p});let d=p=>{let g=o.cardsById.get(p);return g?f(g.card):p},l={},c=new Map;for(let[p,g]of Object.entries(t.board??{})){let u=o.handsById.get(p);if(u===void 0){for(let x of g)s.evicted.push({flow:e,hand:p,card:d(x),reason:"hand-vanished"});continue}let m=f(u.hand),h=[];for(let x of g){let v=o.cardsById.get(x);if(v===void 0){s.evicted.push({flow:e,hand:m,card:x,reason:"vanished"});continue}if(r!==void 0&&oe(v.card,v.deck.shared??!1)){if((r.get(x)??0)+(c.get(x)??0)>=Lt(v.card)){s.evicted.push({flow:e,hand:m,card:f(v.card),reason:"claimed-elsewhere"});continue}c.set(x,(c.get(x)??0)+1)}h.push(x)}l[p]=h}return{...i!==void 0?{props:i}:{},turns:t.turns??{},prng:t.prng,cooldowns:a,board:l,playLog:t.playLog??[]}}},ae=class{id;engine;internals;closed=!1;prng;turnCounts=new Map;cooldowns={};boardContents=new Map;playLog=[];playCount=new Map;lastPlayOf=new Map;tagPlayCount=new Map;lastPlayInTag=new Map;stores;registered=[];bagKeys=[];traceHandlers=new Set;logEntries=[];logSeq=0;storyReader;boxReaders=new Map;deckReaders=new Map;constructor(e,t,r,s){this.engine=e,this.internals=t,this.id=r,this.prng=V(s),this.stores=Nt(t,t.flowDecls);let o=(a,d)=>{d.declarations().length!==0&&this.bagKeys.push([a,d])};o(_e(r,"story"),this.stores.story);for(let a of O)for(let[d,l]of this.stores[a])o(_e(r,a,d),l);this.mountBags();for(let a of t.bundle.boxes){this.turnCounts.set(a.id,0);for(let d of a.hands)this.boardContents.set(d.id,[])}let i=(a,d)=>({get:l=>R(a,l)??R(d,l)});this.storyReader=i(this.stores.story,t.shared.story);for(let a of t.bundle.boxes){this.boxReaders.set(a.id,i(this.stores.box.get(a.id),t.shared.box.get(a.id)));for(let d of a.decks)this.deckReaders.set(d.id,i(this.stores.deck.get(d.id),t.shared.deck.get(d.id)))}}get isClosed(){return this.closed}close(){this.closed||(this.engine.dropFlow(this.id,this),this.markClosed())}markClosed(){this.releaseBags(!1),this.traceHandlers.clear(),this.closed=!0}releaseBags(e){for(let t of this.registered)this.internals.registry.remove(t,{keep:e});this.registered.length=0}registeredKeys(){return[...this.registered]}mountBags(){for(let[e,t]of this.bagKeys)this.internals.registry.mountOwned(e,t,{owner:U}),this.registered.push(e)}assertOpen(){if(this.closed)throw new b(`flow "${this.id}" is closed`)}resolveBox(e){let t=this.internals.boxesByGameId.get(e)??this.internals.boxesById.get(e);if(!t)throw new b(`unknown box "${e}"`);return t}turn(e){return this.assertOpen(),this.turnCounts.get(this.resolveBox(e).id)??0}subscribeTrace(e){return this.traceHandlers.add(e),()=>{this.traceHandlers.delete(e)}}get tracing(){return this.traceHandlers.size>0||this.internals.logCap!==void 0||this.internals.engineTracing()}emit(e,t){this.internals.logCap!==void 0&&(this.logEntries.push({...e,seq:this.logSeq++,...t!==void 0?{turn:t}:{}}),this.logEntries.length>this.internals.logCap&&this.logEntries.splice(0,this.logEntries.length-this.internals.logCap));for(let r of[...this.traceHandlers])r(e);this.internals.emitEngine(this.id,e,t)}log(){return this.logEntries}clearLog(){this.logEntries=[]}node(e){let t=this.internals.nodeCache.get(e);return t||(t=j(e.ast),this.internals.nodeCache.set(e,t)),t}groupInBox(e,t){let r=Y(this.internals.bundle,e);return r.find(s=>f(s)===t)??r.find(s=>s.id===t)}indexPlay(e){this.playCount.set(e.card,(this.playCount.get(e.card)??0)+1),this.lastPlayOf.set(e.card,e);let t=this.internals.cardsByGameId.get(e.card);if(t)for(let[r,s]of Object.entries(t.card.tags??{}))for(let o of s){let i=St(t.box.id,r,o);this.tagPlayCount.set(i,(this.tagPlayCount.get(i)??0)+1),this.lastPlayInTag.set(i,e)}}rebuildPlayIndex(){this.playCount.clear(),this.lastPlayOf.clear(),this.tagPlayCount.clear(),this.lastPlayInTag.clear();for(let e of this.playLog)this.indexPlay(e)}hostsByBox=new Map;host(e){let t=this.hostsByBox.get(e.id);if(t!==void 0)return t;let r=this.makeHost(e);return this.hostsByBox.set(e.id,r),r}makeHost(e){let t=new Map,r=(o,i)=>{let a=`${o}${i}`;if(t.has(a))return t.get(a);let d=this.groupInBox(e,o),l=d?.tags.find(p=>p.gameId===i),c=d&&l?St(e.id,d.id,l.id):void 0;return t.set(a,c),c},s=o=>{let i=this.internals.cardsByGameId.get(o.card);return i?(this.turnCounts.get(i.box.id)??0)-o.turn:fe};return{nextRandom:()=>this.prng.next(),countPlayed:o=>this.playCount.get(o)??0,turnsSincePlayed:o=>{let i=this.lastPlayOf.get(o);return i?s(i):fe},countPlayedIn:(o,i)=>{let a=r(o,i);return a===void 0?0:this.tagPlayCount.get(a)??0},turnsSincePlayedIn:(o,i)=>{let a=r(o,i),d=a===void 0?void 0:this.lastPlayInTag.get(a);return d?s(d):fe}}}evalCtx(e,t,r){let s=this.internals.registryView();return{scopes:{...s.scopes,world:this.internals.worldResolver,story:this.storyReader,box:this.boxReaders.get(e.id)??Ve,deck:t?this.deckReaders.get(t.id)??Ve:Ve,hand:r.bag},host:this.host(e),...this.internals.hasQualities||s.qualities!==void 0?{qualities:(o,i)=>o==="world"?this.internals.ladders.world.get(i)??s.qualities?.(o,i):o==="story"?this.internals.ladders.story.get(i):o==="box"?this.internals.ladders.box.get(e.id)?.get(i):o==="deck"&&t?this.internals.ladders.deck.get(t.id)?.get(i):o==="hand"?this.handLadder(r,i):s.qualities?.(o,i)}:{}}}handLadder(e,t){let r=e.sources.get(t);if(r)return r.kind==="value"?this.internals.ladders.value.get(r.id)?.get(t):r.kind==="hand"?this.internals.ladders.hand.get(r.id)?.get(t):void 0}eval(e,t){return ue(this.node(e),t,Le)}passes(e,t,r){if(!e)return!0;try{return Pt(this.eval(e,t))}catch(s){return this.tracing&&this.emit({type:"diagnostic",where:r??"condition",message:s instanceof Error?s.message:String(s)}),!1}}tagByGameId(e,t){return e.tags.find(r=>r.gameId===t)}askForHand(e,t){let r=new Map,s={},o=a=>{for(let[d,l]of Object.entries(a??{})){if(he(l)){this.fillHoleFromProperty(e,d,l,r,s);continue}r.set(d,l);let c=this.internals.groupsById.get(d),p=c?.group.tags.find(g=>g.id===l);c&&p&&(s[f(c.group)]=f(p))}},i;if(e.template!==void 0){let a=this.internals.templatesById.get(e.template);if(!a)throw new b(`hand "${f(e)}": unknown template "${e.template}"`);for(let[d,l]of Object.entries(a.bindings??{}))r.set(d,l);o(e.chosen),i=a.condition}else o(e.rule?.bindings),i=e.rule?.condition;return r.set(L,e.id),this.bindStateGroups(t,r,s),{box:t,hand:e,...i!==void 0?{condition:i}:{},boundTags:r,askNames:s}}askForPeek(e,t){let r=new Map,s={};for(let[o,i]of Object.entries(t)){if(o===L){let l=this.internals.handsByGameId.get(i)??this.internals.handsById.get(i);if(!l)throw new b(`peek: unknown hand "${i}" in home criteria`);r.set(L,l.hand.id);continue}let a=this.groupInBox(e,o);if(!a)throw new b(`peek: unknown tag group "${o}" in box "${f(e)}"`);let d=this.tagByGameId(a,i)??a.tags.find(l=>l.id===i);if(!d)throw new b(`peek: unknown tag "${i}" in group "${f(a)}"`);r.set(a.id,d.id),s[f(a)]=f(d)}return this.bindStateGroups(e,r,s),{box:e,boundTags:r,askNames:s}}fillHoleFromProperty(e,t,r,s,o){let i=this.internals.groupsById.get(t),a=i?f(i.group):t,d=`hand ${f(e)}, tag group ${a}`,l=mt(r);if(!l){this.emit({type:"diagnostic",where:d,message:`"${r}" is not a @hand, @world or @story property reference`});return}if(!i){this.emit({type:"diagnostic",where:d,message:`"${r}" fills a tag group that is not in this box`});return}let c;if(l.scope==="hand")c=this.valuesOf("hand",e.id)[l.name];else try{c=this.getProperty(`${l.scope}.${l.name}`)}catch{c=void 0}if(c===void 0){this.emit({type:"diagnostic",where:d,message:`"${r}" names a property that is not declared`});return}let p=typeof c=="string"?c:String(c),g=i.group.tags.find(u=>f(u)===p);if(!g){this.emit({type:"diagnostic",where:d,message:`${r} is "${p}", which is not one of the tags of "${a}"`});return}s.set(t,g.id),o[a]=f(g)}bindStateGroups(e,t,r){for(let s of Y(this.internals.bundle,e)){if(s.boundBy===void 0||t.has(s.id))continue;let o=/^@(world|story)\.([a-z][a-z0-9_-]*)$/.exec(s.boundBy);if(!o){this.emit({type:"diagnostic",where:`tag group ${f(s)}`,message:`boundBy "${s.boundBy}" is not a @world or @story property reference`});continue}let i;try{i=this.getProperty(`${o[1]}.${o[2]}`)}catch{this.emit({type:"diagnostic",where:`tag group ${f(s)}`,message:`boundBy "${s.boundBy}" names a property that is not declared`});continue}let a=typeof i=="string"?i:String(i),d=s.tags.find(l=>f(l)===a);if(!d){this.emit({type:"diagnostic",where:`tag group ${f(s)}`,message:`${s.boundBy} is "${a}", which is not one of its tags`});continue}t.set(s.id,d.id),r[f(s)]=f(d)}}valuesOf(e,t){return Object.assign(Object.create(null),this.internals.shared[e].get(t)?.values??{},this.stores[e].get(t)?.values??{})}buildHandEnv(e){let t=Object.create(null),r=new Map;for(let[s,o]of e.boundTags)if(s!==L)for(let[i,a]of Object.entries(this.valuesOf("value",o)))t[i]=a,r.set(i,{kind:"value",id:o});if(e.hand)for(let[s,o]of Object.entries(this.valuesOf("hand",e.hand.id)))t[s]=o,r.set(s,{kind:"hand",id:e.hand.id});for(let[s,o]of Object.entries(e.askNames))t[s]=o,r.set(s,{kind:"criteria"});return{bag:t,sources:r,boundTags:e.boundTags}}claims(){let e=new Map;for(let t of this.boardContents.values())for(let r of t)e.set(r,(e.get(r)??0)+1);return e}heldCardIds(){return[...this.boardContents.values()].flat()}copiesOf(e){return e.copies??1}claimVerdict(e,t,r,s){let o=e.id;return(r.get(o)??0)>=this.copiesOf(e)?"claimed":t&&(s.get(o)??0)>=Lt(e)?"claimed-elsewhere":null}tagsMatch(e,t){let r=e.tags?.[L];if(r!==void 0&&r.length>0){let s=t.get(L);if(s===void 0||!r.includes(s))return!1}for(let[s,o]of t){if(s===L)continue;let i=e.tags?.[s];if(i===void 0){if(this.internals.requiredGroups.has(s))return!1;continue}if(!i.includes(o))return!1}return!0}runAsk(e,t,r){let{box:s}=e,o=this.buildHandEnv(e),i=(p,g)=>{r?.push({id:f(p),verdict:g})};if(!this.passes(e.condition,this.evalCtx(s,void 0,o),`hand ${e.hand?f(e.hand):""} condition`))return{ordered:[],handEnv:o};let a=new Map;for(let p of s.decks)a.set(p.id,this.passes(p.condition,this.evalCtx(s,p,o),`deck ${p.gameId} gate`));let d=this.turnCounts.get(s.id)??0,l=[];for(let p of s.decks){let g=this.evalCtx(s,p,o),u=p.shared??!1;for(let m of p.cards){let h=oe(m,u);if(!a.get(p.id)){i(m,"deck-gate");continue}if(h&&this.engine.isTaken(m.id)){i(m,"taken");continue}if((this.cooldowns[m.id]??0)>d){i(m,"cooldown");continue}if(!this.tagsMatch(m,o.boundTags)){i(m,"tags");continue}if(m.condition&&!this.passes(m.condition,g,this.tracing?`card ${m.gameId} condition`:void 0)){i(m,"condition");continue}let x=t(m,h);if(x){i(m,x);continue}let v;if(typeof m.priority=="number")v=m.priority;else try{let y=this.eval(m.priority,g);if(typeof y!="number"||Number.isNaN(y)){i(m,"priority");continue}v=y}catch(y){this.tracing&&this.emit({type:"diagnostic",where:`card ${m.gameId} priority`,message:y instanceof Error?y.message:String(y)}),i(m,"priority");continue}let w=0;if(s.ranking.specificity&&m.condition){let y=this.node(m.condition);w=lt(y,k=>{try{return Pt(ue(k,g,Le))}catch{return!1}})}l.push({entry:{card:m,deck:p,box:s},priority:v,spec:w})}}l.sort((p,g)=>g.priority-p.priority||g.spec-p.spec);let c=0;for(;c<l.length;){let p=c+1;for(;p<l.length&&l[p].priority===l[c].priority&&l[p].spec===l[c].spec;)p++;if(p-c>1){let g=l.slice(c,p);H(g,this.prng);for(let u=0;u<g.length;u++)l[c+u]=g[u]}c=p}for(let p of l)r?.push({id:f(p.entry.card),verdict:"dealt",priority:p.priority,specificity:p.spec});return{ordered:l.map(p=>p.entry),handEnv:o}}capTrace(e,t){for(let r of e)r.verdict==="dealt"&&!t.has(r.id)&&(r.verdict="capped")}view(e){let{card:t}=e;return{id:t.id,gameId:f(t),...t.title!==void 0?{title:t.title}:{},...t.purpose!==void 0?{purpose:t.purpose}:{},...t.fields!==void 0?{fields:t.fields}:{}}}handCapacity(e){if(e.slots!==void 0)return e.slots;let t=e.template!==void 0?this.internals.templatesById.get(e.template)?.slots:e.rule?.slots;return t===void 0||t==="unbounded"?1/0:t}resolveHand(e){let t=this.internals.handsByGameId.get(e)??this.internals.handsById.get(e);if(!t)throw new b(`unknown hand "${e}"`);return t}peek(e,t={},r){this.assertOpen();let s=this.resolveBox(e),o=this.askForPeek(s,t),i=this.claims(),a=this.internals.hasShared?this.engine.sharedClaims():new Map,d=this.tracing?[]:void 0,l=this.prng;this.prng=V(l.state());let c;try{({ordered:c}=this.runAsk(o,(g,u)=>this.claimVerdict(g,u,i,a),d))}finally{this.prng=l}let p=r===void 0?c:c.slice(0,Math.max(r,0));return d&&(this.capTrace(d,new Set(p.map(g=>f(g.card)))),this.emit({type:"peek",box:f(s),criteria:t,cards:d},this.turnCounts.get(s.id)??0)),{box:f(s),cards:p.map(g=>this.view(g))}}deal(e){this.assertOpen();let{hand:t}=this.resolveHand(e);return this.dealMany([e])[f(t)]??[]}dealMany(e){this.assertOpen();let t=(e??[...this.internals.handsById.keys()].sort()).map(o=>this.resolveHand(o));H(t,this.prng);for(let{hand:o,box:i}of t){let a=this.askForHand(o,i),d=this.buildHandEnv(a),l=this.passes(a.condition,this.evalCtx(i,void 0,d)),c=new Map,p=new Map;for(let v of i.decks){let w=this.evalCtx(i,v,d);p.set(v.id,w),c.set(v.id,this.passes(v.condition,w))}let g=this.tracing,u=this.turnCounts.get(i.id)??0,m=[],h=(v,w)=>{let y=this.internals.cardsById.get(v);return m.push({card:y?f(y.card):v,reason:w}),!1},x=(this.boardContents.get(o.id)??[]).filter(v=>{if(!l)return h(v,"hand-condition");let w=this.internals.cardsById.get(v);return!w||w.box.id!==i.id?h(v,"vanished"):c.get(w.deck.id)?oe(w.card,w.deck.shared??!1)&&this.engine.isTaken(v)?h(v,"taken"):(this.cooldowns[v]??0)>u?h(v,"cooldown"):this.tagsMatch(w.card,d.boundTags)?this.passes(w.card.condition,p.get(w.deck.id),g?`card ${w.card.gameId} condition`:void 0)?!0:h(v,"condition"):h(v,"tags"):h(v,"deck-gate")});if(this.boardContents.set(o.id,x),g)for(let v of m)this.emit({type:"evict",hand:f(o),card:v.card,reason:v.reason},u)}let r=this.claims(),s=this.internals.hasShared?this.engine.sharedClaims():new Map;for(let{hand:o,box:i}of t){let a=this.boardContents.get(o.id)??[],d=this.handCapacity(o)-a.length;if(d<=0)continue;let l=this.askForHand(o,i),c=new Set(a),p=this.tracing?[]:void 0,{ordered:g}=this.runAsk(l,(h,x)=>c.has(h.id)?"claimed":this.claimVerdict(h,x,r,s),p),u=g.slice(0,d),m=u.map(h=>h.card.id);this.boardContents.set(o.id,[...a,...m]);for(let h of m)r.set(h,(r.get(h)??0)+1),s.set(h,(s.get(h)??0)+1);p&&(this.capTrace(p,new Set(u.map(h=>f(h.card)))),this.emit({type:"deal",hand:f(o),cards:p},this.turnCounts.get(i.id)??0))}return Object.fromEntries(t.map(({hand:o})=>[f(o),(this.boardContents.get(o.id)??[]).map(i=>this.view(this.internals.cardsById.get(i)))]))}board(e){this.assertOpen();let t=e!==void 0?this.resolveBox(e).id:void 0;return Object.fromEntries([...this.boardContents.entries()].filter(([r])=>t===void 0||this.internals.handsById.get(r).box.id===t).map(([r,s])=>[f(this.internals.handsById.get(r).hand),s.map(o=>this.view(this.internals.cardsById.get(o)))]))}resolveDealt(e,t){let r=this.internals.cardsById.get(e)??this.internals.cardsByGameId.get(e);if(!r)throw new b(`unknown card "${e}"`);let{hand:s,box:o}=this.resolveHand(t);if(!(this.boardContents.get(s.id)??[]).includes(r.card.id))throw new b(`card "${f(r.card)}" is not dealt to hand "${f(s)}"`);return{entry:r,ask:this.askForHand(s,o)}}outcomes(e,t){this.assertOpen();let{entry:r,ask:s}=this.resolveDealt(e,t),o=this.evalCtx(r.box,r.deck,this.buildHandEnv(s));return r.card.outcomes.map(i=>({id:i.id,gameId:f(i),...i.title!==void 0?{title:i.title}:{},...i.purpose!==void 0?{purpose:i.purpose}:{},...i.fields!==void 0?{fields:i.fields}:{},available:this.passes(i.condition,o)}))}play(e,t,r,s={}){this.assertOpen();let{entry:o,ask:i}=this.resolveDealt(e,r),a=t==="";if(a&&o.card.outcomes.length>0)throw new b(`card "${f(o.card)}" has outcomes (${o.card.outcomes.map(y=>f(y)).join(", ")}); name the one played`);let d=a?void 0:o.card.outcomes.find(y=>f(y)===t);if(!a&&!d)throw new b(`card "${f(o.card)}" has no outcome "${t}"`);let l=this.buildHandEnv(i),c=this.evalCtx(o.box,o.deck,l);if(d&&!this.passes(d.condition,c))throw new b(`outcome "${t}" on "${f(o.card)}" is gated shut`);let p=o.box.turn!==void 0?0:this.internals.bundle.settings.playAdvancesTurns,g=(this.turnCounts.get(o.box.id)??0)+(s.advanceTurns??p),m=Object.entries(d?.changes??{}).map(([y,k])=>({target:y,expr:k,plan:this.planWrite(y,o,l)})).map(y=>({...y,value:this.eval(y.expr,c)})),h=[];try{for(let y of m)h.push({target:y.target,plan:y.plan,value:y.value,prev:this.landWrite(y.plan,y.value)})}catch(y){for(let k of[...h].reverse())this.undoWrite(k.plan,k.prev);throw y}if(this.tracing)for(let{target:y,plan:k,value:I,prev:pe}of h)this.emit({type:"write",target:y,path:k.path,value:I,...pe!==void 0?{prev:pe}:{}},g);let x=d?f(d):"",v={card:f(o.card),outcome:x,turn:g};this.playLog.push(v),this.indexPlay(v),o.card.redraw==="never"?oe(o.card,o.deck.shared??!1)?this.engine.markTaken(o.card.id):this.cooldowns[o.card.id]=Number.MAX_SAFE_INTEGER:typeof o.card.redraw=="number"&&(this.cooldowns[o.card.id]=g+o.card.redraw);let w=i.hand.id;this.boardContents.set(w,(this.boardContents.get(w)??[]).filter(y=>y!==o.card.id)),this.turnCounts.set(o.box.id,g),this.tracing&&this.emit({type:"play",card:f(o.card),outcome:x,turn:g},g)}address(e,t){return A(this.internals,e,t)}planBag(e,t,r,s){let o=e==="story"?this.stores.story:t!==void 0?this.stores[e].get(t):void 0,i=e==="story"?this.internals.shared.story:t!==void 0?this.internals.shared[e].get(t):void 0,a=R(o,r)!==void 0?o:R(i,r)!==void 0?i:void 0;if(a===void 0)throw new b(`no property at "${s}"`);if(a.declarations().some(d=>d.name===r&&d.writable===!1))throw new b(`'${r}' is read-only`);return{kind:"bag",bag:a,name:r,path:s}}planWrite(e,t,r){let s=/^@([a-z]+)\.([A-Za-z_][A-Za-z0-9_-]*)$/.exec(e);if(!s)throw new b(`bad change target "${e}"`);let[,o,i]=s;switch(o){case"world":{if(!this.internals.worldSet)throw new b(`@world.${i} cannot be written: the host bound @world read-only`);if(this.internals.worldReadOnly.has(i))throw new b(`'@world.${i}' is read-only (writable: false)`);return{kind:"world",name:i,path:`world.${i}`}}case"story":return this.planBag("story",void 0,i,`story.${i}`);case"box":return this.planBag("box",t.box.id,i,`${this.address("box",t.box.id)}.${i}`);case"deck":return this.planBag("deck",t.deck.id,i,`${this.address("deck",t.deck.id)}.${i}`);case"hand":{let a=r.sources.get(i);if(!a)throw new b(`@hand.${i} is not composed in this ask`);if(a.kind==="criteria")throw new b(`@hand.${i} is a chosen tag / criteria name and cannot be written`);return this.planBag(a.kind,a.id,i,`${this.address(a.kind,a.id)}.${i}`)}default:{if(this.internals.registry.has(o))return{kind:"scope",scope:o,name:i,path:`${o}.${i}`};throw this.internals.bundle.externalScopes?.includes(o)?new b(`@${o}.${i} cannot be written: no engine on this registry registered @${o}`):new b(`bad change target scope "@${o}"`)}}}landWrite(e,t){switch(e.kind){case"world":{let r=this.internals.worldResolver.get(e.name);return this.internals.worldSet(e.name,t),r}case"bag":return e.bag.set(e.name,t).prev;case"scope":{let r=this.internals.registry.get(e.scope,e.name);return this.internals.registry.set(e.scope,e.name,t),r}}}undoWrite(e,t){if(t!==void 0)switch(e.kind){case"world":this.internals.worldSet(e.name,t,!0);return;case"bag":e.bag.set(e.name,t,{silent:!0,reason:"play refused",host:!0});return;case"scope":this.internals.registry.set(e.scope,e.name,t,{host:!0});return}}advanceTurns(e,t=1){this.assertOpen();let r=this.resolveBox(e),s=(this.turnCounts.get(r.id)??0)+t;this.turnCounts.set(r.id,s),this.tracing&&this.emit({type:"turns",box:f(r),turn:s},s)}listBoxes(){return this.assertOpen(),this.internals.bundle.boxes.map(e=>({id:e.id,gameId:f(e),...e.title!==void 0?{title:e.title}:{},turn:this.turnCounts.get(e.id)??0}))}listBags(){this.assertOpen();let e=[{prefix:"story",bag:this.stores.story}];for(let t of O)for(let[r,s]of this.stores[t])e.push({prefix:A(this.internals,t,r),bag:s});return e}listProperties(){this.assertOpen();let e=[];for(let r of this.internals.bundle.world.properties){let s=this.internals.worldResolver.get(r.name);e.push({path:`world.${r.name}`,name:r.name,type:r.type,value:s??r.default,default:r.default,...r.values!==void 0?{values:r.values}:{},...r.stages!==void 0?{stages:r.stages}:{},writable:this.internals.worldSet!==void 0&&!this.internals.worldReadOnly.has(r.name)})}let t=(r,s,o)=>{for(let i of[s,o])if(i!==void 0)for(let a of i.rows())e.push(a)};t("story",this.internals.shared.story,this.stores.story);for(let r of O){let s=new Set([...this.internals.shared[r].keys(),...this.stores[r].keys()]);for(let o of s)t(A(this.internals,r,o),this.internals.shared[r].get(o),this.stores[r].get(o))}return e}getProperty(e){this.assertOpen();let t=this.resolvePath(e),r=t.kind==="world"?this.internals.worldResolver.get(t.name):t.kind==="scope"?this.internals.registry.get(t.token,t.name):R(t.own,t.name)??R(t.shared,t.name);if(r===void 0)throw new b(`no property at "${e}"`);return r}setProperty(e,t){this.assertOpen();let r=this.resolvePath(e);if(r.kind==="world"){if(!this.internals.worldSet)throw new b("@world is read-only here: the host bound no write");this.internals.worldSet(r.name,t,!0);return}if(r.kind==="scope"){this.internals.registry.set(r.token,r.name,t,{host:!0});return}let s=R(r.own,r.name)!==void 0?r.own:R(r.shared,r.name)!==void 0?r.shared:void 0;if(s===void 0)throw new b(`no property at "${e}"`);s.set(r.name,t,{silent:!0,reason:"host setProperty",host:!0})}resolvePath(e){let t=e.split(".");if(t.length===2&&t[0]==="world")return{kind:"world",name:t[1]};if(t.length===2&&t[0]!=="story"&&this.internals.registry.has(t[0]))return{kind:"scope",token:t[0],name:t[1]};if(t.length===2&&t[0]==="story")return{kind:"bag",own:this.stores.story,shared:this.internals.shared.story,name:t[1]};if(t.length===3&&Dt(t[0])){let r=t[0],[,s,o]=t,i=Vt(this.internals,r,s,o);i.legacy&&this.tracing&&this.emit({type:"diagnostic",where:"property address",message:jt(this.internals,r,s,o)});let a=this.stores[r].get(i.id),d=this.internals.shared[r].get(i.id);if(a===void 0&&d===void 0)throw new b(`no ${r} store "${s}"`);return{kind:"bag",...a!==void 0?{own:a}:{},...d!==void 0?{shared:d}:{},name:o}}throw new b(`bad property path "${e}"`)}saveDurable(){this.assertOpen();let{bundle:e,durable:t}=this.internals;return structuredClone({schema:de,content:e.content,values:Tt(this.stores,t.flow),spent:t.flowCards.filter(r=>this.cooldowns[r.card.id]===Number.MAX_SAFE_INTEGER).map(r=>f(r.card)).sort()})}writeDurable(e){for(let[t,r]of e.values)At(ze(this.stores,t),t.decl.name,r);for(let t of e.cards)this.cooldowns[t]=Number.MAX_SAFE_INTEGER}snapshot(e){return{...e?{props:Er(this.stores)}:{},turns:Object.fromEntries(this.turnCounts),prng:this.prng.state(),cooldowns:this.cooldowns,board:Object.fromEntries(this.boardContents),playLog:this.playLog}}restore(e){e.props!==void 0&&kr(this.stores,e.props),this.turnCounts=new Map(this.internals.bundle.boxes.map(t=>[t.id,0]));for(let[t,r]of Object.entries(e.turns??{}))this.turnCounts.has(t)&&this.turnCounts.set(t,r);this.prng=V(e.prng),this.cooldowns=e.cooldowns??{},this.playLog=e.playLog??[],this.rebuildPlayIndex(),this.boardContents=new Map(Object.entries(e.board??{}).filter(([t])=>this.internals.handsById.has(t)).map(([t,r])=>[t,r.filter(s=>this.internals.cardsById.has(s))]));for(let t of this.internals.handsById.keys())this.boardContents.has(t)||this.boardContents.set(t,[])}};var xe=n=>n.map(e=>({name:e.name,type:e.type,default:e.default,...e.values!==void 0?{values:e.values}:{},...e.durable===!0?{durable:!0}:{},...e.purpose!==void 0?{purpose:e.purpose}:{}})),Ft=n=>n.decks.reduce((e,t)=>e+t.cards.filter(r=>(r.durable??t.durable)===!0).length,0),Cr=(n,e)=>n.template!==void 0?e.handTemplates.find(t=>t.id===n.template)?.properties??[]:n.properties??[],Br=(n,e,t)=>{let r=e.template!==void 0?e.chosen:e.rule?.bindings,s=[];for(let[o,i]of Object.entries(r??{})){if(!he(i))continue;let a=Y(n,t).find(d=>d.id===o);a!==void 0&&s.push({group:f(a),from:i})}return s},$r=(n,e)=>{if(n.slots!==void 0)return n.slots;let t=n.template!==void 0?e.handTemplates.find(r=>r.id===n.template)?.slots:n.rule?.slots;return t===void 0?"unbounded":t};function Se(n){let e=[],t=[],r=[{scope:"world",owner:"",properties:xe(n.world.properties)},{scope:"story",owner:"",properties:xe(n.story.properties)}],s={boxes:0,decks:0,cards:0,hands:0,templates:0,tagGroups:0};for(let i of n.boxes){let a=f(i),d=i.decks.reduce((c,p)=>c+p.cards.length,0);e.push({gameId:a,...i.title!==void 0?{title:i.title}:{},...i.usesMap===!0?{usesMap:!0}:{},ranking:{specificity:i.ranking.specificity},...i.turn!==void 0?{turn:{seconds:i.turn.seconds}}:{},...Ft(i)>0?{durableCards:Ft(i)}:{},tagGroups:i.tagGroups.map(c=>({gameId:f(c),tags:c.tags.map(p=>f(p))})),counts:{decks:i.decks.length,cards:d,hands:i.hands.length,templates:i.handTemplates.length,tagGroups:i.tagGroups.length}}),s.boxes+=1,s.decks+=i.decks.length,s.cards+=d,s.hands+=i.hands.length,s.templates+=i.handTemplates.length,s.tagGroups+=i.tagGroups.length;for(let c of i.hands){let p=c.template!==void 0?i.handTemplates.find(u=>u.id===c.template):void 0,g=Br(n,c,i);t.push({gameId:f(c),...c.title!==void 0?{title:c.title}:{},box:a,slots:$r(c,i),...p!==void 0?{template:f(p)}:{},...g.length>0?{movable:g}:{}})}let l=(c,p,g,u)=>{g.length!==0&&r.push({scope:c,owner:p,box:a,...u!==void 0?{group:u}:{},properties:xe(g)})};l("box",a,i.properties);for(let c of i.decks)l("deck",f(c),c.properties);for(let c of i.hands)l("hand",f(c),Cr(c,i));for(let c of i.tagGroups)for(let p of c.tags)l("tag",f(p),p.properties??[],f(c))}let o=n.map;if(o!==void 0){let i=f(o.group);for(let a of o.group.tags){let d=a.properties??[];d.length>0&&r.push({scope:"tag",owner:f(a),group:i,properties:xe(d)})}s.tagGroups+=1}return{identity:{schema:n.schema,project:n.content.project,version:n.content.version,hash:n.content.hash,metadata:n.metadata},totals:s,boxes:e,hands:t,properties:r,...o!==void 0?{map:{group:f(o.group),tags:o.group.tags.map(i=>f(i)),boxes:n.boxes.filter(i=>i.usesMap===!0).map(i=>f(i)),zones:o.geometry?.zones.length??0,backgrounds:o.geometry?.backgrounds?.length??0,sites:Object.fromEntries(Object.entries(o.geometry?.sites??{}).map(([i,a])=>[i,a.length]))}}:{}}}function _t(n,e){let t={};for(let{bag:r}of[...n.listBags(),...e.listBags()])for(let s of r.rows())s.value!==void 0&&(t[s.path]=s.value);return Object.assign(t,qt(Gt(n,e.id))),t}function Gt(n,e){return n.getFlow(e)!==void 0?n.saveFlow(e):void 0}function qt(n){let e={};if(n===void 0)return e;for(let[t,r]of Object.entries(n.turns))e[`turn:${t}`]=r;for(let[t,r]of Object.entries(n.cooldowns))e[`cooldown:${t}`]=r;for(let[t,r]of Object.entries(n.board))e[`board:${t}`]=[...r];return e}function zt(n,e,t={}){let r=e.id,s=()=>n.getFlow(r);return re({mounts:()=>[...n.listBags(),...s()?.listBags()??[]].map(({bag:o})=>({bag:o})),extra:()=>qt(Gt(n,r))},t)}function Ee(n,e){return JSON.stringify(Ue(n,e),null,2)}function Ue(n,e){return{schema:me,engine:n.saveGame(),...e!==void 0?{world:e}:{}}}function We(n,e,t={}){if(!e||typeof e!="object"||e.schema!==me||e.engine?.schema!==Z&&e.engine?.schema!==ee)throw new Error(`not a storylets save (expected schema "${me}")`);let r=n.loadGame(e.engine);return t.onReport?.(r),e.world}function ke(n,e,t={}){let r;try{r=JSON.parse(e)}catch{throw new Error("not valid JSON")}return We(n,r,t)}var Ut="sl-inspector-style",Or=`
2
2
  .sl-insp { font: 12px system-ui, sans-serif; color: var(--ink, #222); background: var(--surface, #fafafa);
3
3
  border: 1px solid var(--line, #ccc); border-radius: 8px; padding: 10px 12px; max-width: 26rem; }
4
4
  .sl-insp h3 { margin: 0 0 8px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em;