@patterkit/play-helpers 0.9.0 → 0.9.2

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,5 +1,5 @@
1
- "use strict";var Patterplay=(()=>{var Ce=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ir=Object.prototype.hasOwnProperty;var or=(n,e)=>{for(var t in e)Ce(n,t,{get:e[t],enumerable:!0})},ar=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of sr(e))!ir.call(n,s)&&s!==t&&Ce(n,s,{get:()=>e[s],enumerable:!(r=nr(e,s))||r.enumerable});return n};var lr=n=>ar(Ce({},"__esModule",{value:!0}),n);var Xr={};or(Xr,{Checkpoint:()=>pe,DEFAULT_PAD_AFTER:()=>$,Engine:()=>ve,Flow:()=>H,SAVE_SCHEMA:()=>K,applyLiveBundle:()=>$t,buildTagIndex:()=>Se,compareStages:()=>U,createAudioResolver:()=>tr,createBundleInspector:()=>er,createDebugLink:()=>Tt,createPropertyInspector:()=>Zt,createStateLogger:()=>Ft,describeBundle:()=>we,deserializeState:()=>ke,diffState:()=>te,effectiveGameData:()=>Pt,gameDataFields:()=>Ot,gameDataValue:()=>$e,getProperty:()=>Bt,loadState:()=>je,nextStage:()=>W,saveState:()=>Ve,serializeState:()=>xe,setProperties:()=>At,setProperty:()=>Lt,snapshotState:()=>qe,stageIndex:()=>_});function X(n,e){return n!==void 0&&Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0}function V(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:V(n[2])};case"bin":return{kind:"binary",op:n[1],left:V(n[2]),right:V(n[3])};case"call":{let e=n.slice(2).map(V);return{kind:"call",name:n[1],args:e}}case"fd":return{kind:"flagdelta",sign:n[1],name:n[2]}}}var b=class extends Error{constructor(e){super(e),this.name="EvalError"}};function ue(n,e,t){let r=new Map(t.scopes.map(i=>[i.token,i.missing??"false"])),s=i=>{switch(i.kind){case"bool":return i.value;case"number":return i.value;case"string":return i.value;case"scopedvar":{let o=X(e.scopes,i.scope);if(o===void 0)return!1;let a=typeof o.get=="function"?o.get(i.name):X(o,i.name);if(a===void 0){if(r.get(i.scope)==="throw")throw new b(`@${i.scope}.${i.name} is not declared on the current ${i.scope}.`);return!1}return a}case"call":{if(i.name==="advance"&&!X(t.functions,i.name)){let a=i.args[0];if(i.args.length!==1||a===void 0)throw new b(`advance() takes exactly 1 argument, got ${i.args.length}`);let l=De(a,e);if(l===void 0)throw new b("advance() needs a quality reference (@scope.name of a quality property)");let c=N(s(a),l,"advance");return l[Math.min(c+1,l.length-1)]}let o=X(t.functions,i.name);if(!o)throw new b(`unknown function '${i.name}'`);return o.eval(i.args,{evaluate:s,ctx:e})}case"flagdelta":throw new b("flagdelta node is only valid as an argument to a flag-delta function");case"unary":{if(i.op==="not"){let a=s(i.operand);if(typeof a!="boolean")throw new b(`'not' requires a boolean operand, got ${typeof a}`);return!a}let o=s(i.operand);if(typeof o!="number")throw new b(`unary '-' requires a numeric operand, got ${typeof o}`);return-o}case"binary":{if(i.op==="and"){let p=s(i.left);if(typeof p!="boolean")throw new b(`'and' requires boolean operands, left is ${typeof p}`);if(!p)return!1;let g=s(i.right);if(typeof g!="boolean")throw new b(`'and' requires boolean operands, right is ${typeof g}`);return g}if(i.op==="or"){let p=s(i.left);if(typeof p!="boolean")throw new b(`'or' requires boolean operands, left is ${typeof p}`);if(p)return!0;let g=s(i.right);if(typeof g!="boolean")throw new b(`'or' requires boolean operands, right is ${typeof g}`);return g}let o=s(i.left),a=s(i.right),l=De(i.left,e),c=De(i.right,e),u=l??c;if(u!==void 0){if(l&&c&&!cr(l,c)&&(i.op===">"||i.op===">="||i.op==="<"||i.op==="<="))throw new b(`'${i.op}' compares two different qualities, whose stage orders are unrelated`);switch(i.op){case">":return N(o,u,">")>N(a,u,">");case">=":return N(o,u,">=")>=N(a,u,">=");case"<":return N(o,u,"<")<N(a,u,"<");case"<=":return N(o,u,"<=")<=N(a,u,"<=");case"+":case"-":case"*":case"/":throw new b(`'${i.op}' cannot be applied to a quality - a stage is a position, not a number; use advance() to move it`);default:break}}switch(i.op){case"==":return Ke(o,a);case"!=":return!Ke(o,a);case">":return j(o,a,">"),o>a;case">=":return j(o,a,">="),o>=a;case"<":return j(o,a,"<"),o<a;case"<=":return j(o,a,"<="),o<=a;case"+":if(typeof o=="number"&&typeof a=="number"||typeof o=="string"&&typeof a=="string")return o+a;throw new b(`'+' requires two numbers or two strings, got ${typeof o} and ${typeof a}`);case"-":return j(o,a,"-"),o-a;case"*":return j(o,a,"*"),o*a;case"/":if(j(o,a,"/"),a===0)throw new b("division by zero");return o/a}}}};return s(n)}function Ke(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 j(n,e,t){if(typeof n!="number"||typeof e!="number")throw new b(`'${t}' requires numeric operands, got ${typeof n} and ${typeof e}`)}function De(n,e){if(!(n.kind!=="scopedvar"||e.qualities===void 0))return e.qualities(n.scope,n.name)}function N(n,e,t){if(typeof n!="string")throw new b(`'${t}' on a quality compares stages, got ${typeof n}`);let r=e.indexOf(n);if(r<0)throw new b(`"${n}" is not a stage of this quality (stages: ${e.join(", ")})`);return r}var cr=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]);function ee(n){if(Number.isNaN(n)||!Number.isFinite(n))return 0;let e=Math.trunc(n)%4294967296;return e<0?e+4294967296:e}function Ie(n){let e=ee(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}}}var Oe=n=>Array.isArray(n)?n:n.stages??[],pr=n=>Array.isArray(n)?"flags":n==null?"nothing":typeof n;function _(n,e){return typeof e=="string"?Oe(n).indexOf(e):-1}function Re(n,e){if(typeof e!="string")throw new b(`a stage is a name, got ${pr(e)}`);let t=n.indexOf(e);if(t<0)throw new b(`"${e}" is not a stage of this quality (stages: ${n.join(", ")})`);return t}function U(n,e,t){let r=Oe(n),s=Re(r,e)-Re(r,t);return s<0?-1:s>0?1:0}function W(n,e){let t=Oe(n);return t[Math.min(Re(t,e)+1,t.length-1)]}function Pe(n,e,t){switch(n.type){case"boolean":return typeof e=="boolean";case"number":return typeof e=="number";case"string":case"text":case"multiline":return typeof e=="string";case"enum":return typeof e!="string"?!1:e===""&&t?.noneChosen?!0:!Array.isArray(n.values)||n.values.includes(e);case"flags":return Array.isArray(e)&&e.every(r=>typeof r=="string"&&(!Array.isArray(n.values)||n.values.includes(r)));case"quality":return typeof e=="string"&&(!Array.isArray(n.stages)||n.stages.includes(e));default:return!0}}var dr={name:"check_flags",count:n=>Math.max(1,n.args.length-1)},ur=[dr];function ze(n,e,t){let r=t?.countingCalls??ur;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),i=ge(n.right,e,t,r);return n.op==="and"===e?s>0&&i>0?s+i:0:Math.max(s,i)}if(n.kind==="unary"&&n.op==="not")return ge(n.operand,!e,t,r);if(n.kind==="call"){let s=r.find(i=>i.name===n.name);if(s){let i=s.count(n),o=t(n);return e?o?i:0:o?0:1}}return t(n)===e?1:0}function te(n,e){let t=[],r=new Set([...Object.keys(n),...Object.keys(e)]);for(let s of[...r].sort()){let i=n[s],o=e[s];JSON.stringify(i)!==JSON.stringify(o)&&t.push({path:s,from:i,to:o})}return t}var Qe=n=>n===void 0?"<unset>":JSON.stringify(n),Ye=n=>n.pathPrefix??n.bag.pathPrefix;function Be(n,e={}){let t=e.sink??(p=>console.log(p)),r=e.label??"",s=p=>{t(`${r}${p.path}: ${Qe(p.from)} -> ${Qe(p.to)}`)},i=()=>{let p={};for(let g of n.mounts()){let f=Ye(g);for(let[y,d]of Object.entries(g.bag.values))p[f+y]=d}return Object.assign(p,n.extra?.()??{}),structuredClone(p)},o=i(),a=[],l=[],c=(p,g)=>g.onAudit(f=>{let y=structuredClone({path:p+f.name,from:f.prev,to:f.next});s(y),a.push(y),o[y.path]=structuredClone(f.next)}),u=()=>{let p=n.mounts();if(!(l.length===p.length&&p.every((f,y)=>l[y].bag===f.bag))){for(let f of l)f.off();l=p.map(f=>({bag:f.bag,off:c(Ye(f),f.bag)}))}};return u(),{snapshot:i,capture(){let p=i(),g=te(o,p);for(let y of g)s(y);let f=[...a,...g];return a=[],o=p,u(),f},dispose(){for(let p of l)p.off();l=[],a=[]}}}var T=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??J(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 i={name:s,prev:this.values[s],next:t,silent:r?.silent??!1,reason:r?.reason};this.values[s]=t;for(let o of[...this.auditors])o(i);if(!i.silent)for(let o of[...this.subscribers])o(i);return i}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])=>Xe(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,t){let r=new Map;for(let[i,o]of Object.entries(e)){let a=this.norm(i);this.values[a]=structuredClone(o),r.set(a,o)}let s=[];if(!t?.refit)return s;for(let[i,o]of this.decls){if(!r.has(i))continue;let a=r.get(i);Pe(o,a)||(this.values[i]=structuredClone(J(o)),s.push({name:i,value:a}))}return s}};function Xe(n,e,t,r,s=""){let i=r??n.name.toLowerCase();return{name:i,path:s+i,type:n.type,value:e,default:n.default??J(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(),Le=1,fe=class{scopes=new Map;parked=new Map;parkedRefit=new Set;misfits=[];rev=0;get revision(){return this.rev}defineOwned(e,t,r){let s=typeof r=="string"?{pathPrefix:r}:r??{},i=new T(t,{pathPrefix:s.pathPrefix??`${e}.`,...s.normalise?{normalise:s.normalise}:{}});return this.mountOwned(e,i,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&&(this.note(e,t.load(s,{refit:this.parkedRefit.has(e)})),this.parked.delete(e),this.parkedRefit.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.parkedRefit.delete(e)),this.scopes.delete(e),this.rev++,this}discardParked(e){if(e===void 0)this.parked.clear(),this.parkedRefit.clear();else for(let t of[...this.parked.keys()])t.startsWith(e)&&(this.parked.delete(t),this.parkedRefit.delete(t));return this}takeMisfits(e){if(!e){let r=this.misfits;return this.misfits=[],r}let t=this.misfits.filter(r=>e(r.scope));return this.misfits=this.misfits.filter(r=>!e(r.scope)),t}note(e,t){for(let r of t)this.misfits.push({scope:e,name:r.name,value:r.value})}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 i=typeof s=="boolean"?{writable:s}:s;this.assertFree(e,i.owner);let o=i.normalise??gr,a=new Map;for(let l of r)a.set(o(l.name),l);return this.scopes.set(e,{kind:"foreign",resolver:t,decls:a,scopeWritable:i.writable??!0,norm:o,...i.owner!==void 0?{owner:i.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 i=this.scopes.get(e);if(!i)throw new Error(`unknown scope '@${e}'`);if(i.kind==="owned"){if(!s?.host&&!i.bag.writable(t))throw new Error(`'@${e}.${t}' is read-only`);i.bag.set(t,r,s?.host?{host:!0}:void 0);return}let o=i.norm(t);if(!i.resolver.set)throw new Error(`'@${e}.${t}' is read-only`);if(!s?.host&&!this.foreignWritable(i,o))throw new Error(`'@${e}.${t}' is read-only`);i.resolver.set(o,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 i of r.bag.rows())e.push({scope:t,...s,...i});else for(let[i,o]of r.decls)e.push({scope:t,...s,...Xe(o,r.resolver.get(i),this.foreignWritable(r,i),i,`${t}.`)})}return e}toEvalContext(e,t){let r=this.view(t?.aliases),s={};for(let[o,a]of r)s[o]=a.kind==="owned"?a.bag.values:a.resolver;let i=this.qualityLadders(r);return i.size===0?{scopes:s,host:e}:{scopes:s,host:e,qualities:(o,a)=>{let l=r.get(o);return l?i.get(o)?.get(fr(l)(a)):void 0}}}view(e){let t=new Map(this.scopes);for(let[r,s]of Object.entries(e??{})){let i=this.scopes.get(s);if(!i)throw new Error(`alias '@${r}' names '${s}', which is not registered`);t.set(r,i)}return t}qualityLadders(e){let t=new Map;for(let[r,s]of e)for(let[i,o]of Ze(s)){if(o.type!=="quality"||o.stages===void 0)continue;let a=t.get(r);a||(a=new Map,t.set(r,a)),a.set(i,o.stages)}return t}toSchema(e){let t=new Map;for(let[r,s]of this.view(e?.aliases)){let i=Ze(s);if(i.length===0)continue;let o=new Map;for(let[a,l]of i)o.set(a,{type:l.type,enumValues:l.values,...l.stages!==void 0?{stages:l.stages}:{}});t.set(r,o)}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(),this.parkedRefit.clear());let r=t?.refit===!0;for(let[s,i]of Object.entries(e)){let o=this.scopes.get(s);o?.kind==="owned"?this.note(s,o.bag.load(i,{refit:r})):o||(this.parked.set(s,structuredClone(i)),r?this.parkedRefit.add(s):this.parkedRefit.delete(s))}}saveFragment(){return{version:Le,scopes:this.save()}}loadFragment(e){if(e.version!==Le)throw new Error(`unsupported owned-state fragment version ${e.version} (supported: ${Le})`);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}`:"",i=t!==void 0?` (wanted by ${t})`:"";throw new Error(`scope '@${e}' is already registered${s}${i}`)}};function Ze(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 J(n){if(n.default!==void 0)return n.default;switch(n.type){case"boolean":return!1;case"number":return 0;case"string":case"text":case"multiline":return"";case"enum":return n.values?.[0]??"";case"flags":return[];case"quality":return n.stages?.[0]??"";default:return!1}}var et=[{token:"patter",engine:"Patterplay",means:"Patter's shared globals"},{token:"story",engine:"Storylet Engine",means:"the Storylet Engine's shared @story properties"}];function re(n){return n.ctx.host??{}}var Ae={defaultScope:"patter",scopes:[{token:"patter"},{token:"scene"}],functions:{random:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){if(n.length!==2)throw new b("random(a, b) requires exactly 2 arguments");let t=re(e).nextRandom;if(!t)throw new b("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 b("random(a, b) arguments must be numbers");if(!Number.isInteger(r)||!Number.isInteger(s))throw new b("random(a, b) arguments must be integers");let i=Math.min(r,s),o=Math.max(r,s);return Math.floor(t()*(o-i+1))+i}},check_flags:{minArgs:1,returnType:"boolean",flagDeltaArgs:!0,validate:rt("check_flags"),eval(n,e){let t=tt(n[0],e,"check_flags");for(let r=1;r<n.length;r++){let s=n[r];if(s.kind!=="flagdelta")throw new b("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,validate:rt("set_flags"),eval(n,e){let t=[...tt(n[0],e,"set_flags")];for(let r=1;r<n.length;r++){let s=n[r];if(s.kind!=="flagdelta")throw new b("set_flags() flag args must be +flagName or -flagName");if(s.sign==="+")t.includes(s.name)||t.push(s.name);else{let i=t.indexOf(s.name);i>=0&&t.splice(i,1)}}return t}},visits:{minArgs:1,maxArgs:1,returnType:"number",validate:me("visits"),eval:(n,e)=>re(e).visits?.(he(n,e,"visits"))??0},seen:{minArgs:1,maxArgs:1,returnType:"boolean",validate:me("seen"),eval:(n,e)=>(re(e).visits?.(he(n,e,"seen"))??0)>0},patter_visits:{minArgs:1,maxArgs:1,returnType:"number",validate:me("patter_visits"),eval:(n,e)=>re(e).patterVisits?.(he(n,e,"patter_visits"))??0},patter_seen:{minArgs:1,maxArgs:1,returnType:"boolean",validate:me("patter_seen"),eval:(n,e)=>(re(e).patterVisits?.(he(n,e,"patter_seen"))??0)>0}}},Pn=et.map(n=>n.token).filter(n=>n!=="patter"&&n!=="scene");function nt(n,e){let t=n.replace(/^@/,"").split(".");return t.length===2&&e(t[0])?{scope:t[0],name:t[1].toLowerCase()}:{scope:"patter",name:t.join(".").toLowerCase()}}function he(n,e,t){let r=e.evaluate(n[0]);if(typeof r!="string")throw new b(`${t}(id) requires a string node id`);return r}function me(n){return(e,t)=>{let r=e[0];r&&r.kind!=="string"&&t.report({path:[...t.path,"args",0],kind:"wrong-arg-type",severity:"error",message:`${n}(id): the argument must be a string id literal (a scene / block / node id)`})}}function tt(n,e,t){if(!n)throw new b(`${t}() requires at least one argument (the flags variable)`);let r=e.evaluate(n);if(Array.isArray(r))return r;if(r===!1||r===null||r===void 0)return[];throw new b(`${t}() first argument must be a flags property`)}function rt(n){return(e,t)=>{if(e.length===0)return;let r=e[0];if(r.kind!=="scopedvar"){t.report({path:[...t.path,"args",0],kind:"wrong-arg-type",severity:"error",message:`${n}(): first argument must be a flags property reference (@name or @scope.name)`});return}let s=t.schema.properties.get(r.scope)?.get(r.name);if(s&&s.type!=="flags"){let i=r.scope===t.defaultScope?r.name:`${r.scope}.${r.name}`;t.report({path:[...t.path,"args",0],kind:"wrong-arg-type",severity:"error",message:`${n}(): '@${i}' is not a flags property (got ${s.type})`});return}for(let i=1;i<e.length;i++){let o=e[i];o.kind!=="flagdelta"?t.report({path:[...t.path,"args",i],kind:"wrong-arg-type",severity:"error",message:`${n}(): argument ${i+1} must be +flagName or -flagName`}):s?.type==="flags"&&s.enumValues&&!s.enumValues.includes(o.name)&&t.report({path:[...t.path,"args",i],kind:"unknown-flag-name",severity:"error",message:`${n}(): unknown flag '${o.name}'`,reference:o.name})}}}var hr=/^@[A-Za-z0-9_.]+$/;function*mr(n){let e="",t=0;for(;t<n.length;){let r=n[t];if(r==="{"&&n[t+1]==="{"){e+="{",t+=2;continue}if(r==="}"&&n[t+1]==="}"){e+="}",t+=2;continue}if(r==="{"){let s=n.indexOf("}",t+1);if(s!==-1){let i=n.slice(t,s+1),o=n.slice(t+1,s).trim();if(o.startsWith("@")){e&&(yield{kind:"text",value:e},e=""),yield{kind:"slot",raw:i,inner:o,ref:hr.test(o)?o:void 0},t=s+1;continue}e+=i,t=s+1;continue}}e+=r,t+=1}e&&(yield{kind:"text",value:e})}function yr(n){return Array.isArray(n)?n.join(", "):typeof n=="boolean"?n?"true":"false":String(n)}function br(n){return n===" "||n===" "||n===`
2
- `||n==="\r"||n==="\f"||n==="\v"}function Sr(n){let e="",t=!1;for(let r of n){if(br(r)){t=!0;continue}t&&e.length>0&&(e+=" "),t=!1,e+=r}return e}function st(n,e,t){if(e.length===0||n.indexOf(e)<0)return n;let r="",s=0,i=!1;for(;s<n.length;){if(n.startsWith(e,s)){let o=n.indexOf(t,s+e.length);if(o>=0){s=o+t.length,i=!0;continue}r+=n.slice(s);break}r+=n[s],s+=1}return i?Sr(r):n}function it(n,e){if(n.indexOf("{")<0)return n;let t="";for(let r of mr(n)){if(r.kind==="text"){t+=r.value;continue}if(!r.ref){t+=r.raw;continue}let s=e(r.ref);t+=s===void 0?"":yr(s)}return t}function G(n,e){for(let t of n){e(t);let r=t.children;r&&G(r,e)}}function vr(n){return n.toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function P(n){let e=n.gameId?.trim();return e||vr(n.name)}var $=.6;function ye(n){return`cast:${n}`}function be(n){return`qualifier:${n}`}function ot(n,e){return`speaker:${n}:${e}`}var at="speaker:pattern",lt="{name} ({qualifier})";function ct(n,e,t){return n.split("{name}").map(r=>r.split("{qualifier}").join(t)).join(e)}var Ne={open:"[",close:"]"},pt="SFX",K="patter/save@0",ne=3;function se(n){let e=new Set,t=[];for(let r of n)e.has(r)||(e.add(r),t.push(r));return t}function Se(n){let e=new Map,t=(r,s)=>{let i=se([...s,...r.tags??[]]);if(e.set(r.id,i),r.type==="group"&&r.prompt&&e.set(r.prompt.id,se([...i,...r.prompt.tags??[]])),r.type==="group")for(let o of r.children)t(o,i);else for(let o of r.beats??[])e.set(o.id,se([...i,...o.tags??[]]))};for(let r of Object.values(n.scenes)){let s=se(r.tags??[]);e.set(r.id,s);for(let i of r.blocks){let o=se([...s,...i.tags??[]]);e.set(i.id,o);for(let a of i.children)t(a,o)}}return e}var dt=n=>n.kind==="line"||n.kind==="text",ie=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0;function ut(n){let e=new Map,t=(i,o,a)=>{let l=i.kind==="gameEvent"?void 0:ie(i.padAfter),c=l??o;a&&c<0&&(c=0),e.set(i.id,l!==void 0?{own:l,resolved:c}:{resolved:c})},r=(i,o)=>{let a=ie(i.padAfterDefault)??o;if(i.type==="group"){i.prompt&&t(i.prompt,a,!1);for(let u of i.children)r(u,a);return}let l=i.beats??[],c=-1;l.forEach((u,p)=>{dt(u)&&(c=p)}),l.forEach((u,p)=>{dt(u)&&t(u,a,p===c)})},s=ie(n.padAfterDefault)??$;for(let i of Object.values(n.scenes)){let o=ie(i.padAfterDefault)??s;for(let a of i.blocks){let l=ie(a.padAfterDefault)??o;for(let c of a.children)r(c,l)}}return e}var gt=new WeakMap,ft=new WeakMap;function wr(n){let e=ft.get(n);return e||(e=Se(n),ft.set(n,e)),e}var ht=new WeakMap;function xr(n){let e=ht.get(n);return e||(e=ut(n),ht.set(n,e)),e}var mt=new WeakMap;function kr(n){let e=mt.get(n);if(e)return e;e=new Map;for(let t of Object.values(n.scenes))for(let r of t.blocks)G(r.children,s=>{if(s.type==="group"){s.prompt&&e.set(s.prompt.id,s.prompt);return}for(let i of s.beats??[])e.set(i.id,i)});return mt.set(n,e),e}function q(n,e){return n.tagIndex.get(e)?.slice()}var le="Patter",oe=n=>n.replace(/%/g,"%25").replace(/\//g,"%2F"),Er=n=>n.replace(/%2F/g,"/").replace(/%25/g,"%"),yt=Symbol("ownsRegistry"),O={stage:n=>`patter/scene/${oe(n)}`,flow:n=>`patter/flow/${oe(n)}/`,flowGlobals:n=>`patter/flow/${oe(n)}/patter`,flowScene:(n,e)=>`patter/flow/${oe(n)}/scene/${oe(e)}`},pe=class{constructor(e){this.journal=e}journal},ve=class n{host;defaultSeed;flowsById=new Map;allStrings;currentLocale;sourceDebug;sceneGameIdToId=new Map;blockGameIdToId=new Map;creationOptions;engineLog=[];engineSeq=0;engineTraceHandlers=new Set;constructor(e,t={}){this.creationOptions=t;let r=t.locale??e.locales.default,s=e.strings;this.allStrings=s,this.currentLocale=r;let i=s[r]??{},o=s[e.locales.default]??{},a=e.localisation,l=a?.mode==="ids"&&!a.sourceDebug;this.sourceDebug=a?.mode==="ids"&&!!a.sourceDebug,this.sourceDebug&&typeof console<"u"&&console.warn("[Patterplay] source-only DEBUG build: strings are the source language for debugging, not a shippable localised build.");let c=new Map;for(let m of e.cast??[])m.displayName&&c.set(m.name,m.displayName);let u=new Map;for(let m of e.qualifiers??[])m?.gameId&&u.set(m.gameId,m.name);let p=new Map;for(let m of e.cast??[])for(let[v,R]of Object.entries(m.qualifierLabels??{}))typeof R=="string"&&p.set(`${m.name}\0${v}`,R);let g=e.speakerPattern??lt;this.defaultSeed=(t.seed??2654435769)>>>0;let f=new Map,y=new Map,d=new Map;for(let[m,v]of Object.entries(e.scenes)){this.sceneGameIdToId.set(P(v),m);let R=new Map;for(let C of v.blocks)y.set(C.id,{sceneId:m}),d.set(C.id,C),R.set(P(C),C.id),G(C.children,de=>f.set(de.id,de));this.blockGameIdToId.set(m,R)}let x=e.properties??[],I=x.filter(m=>m.shared??!0).map(wt),D=x.filter(m=>!(m.shared??!0)).map(wt),L=new Set(I.map(m=>m.name.toLowerCase())),k=t.registry??new fe,A=!t.registry||t[yt]===!0,M=new T(I,{pathPrefix:"@patter."}),F=[],h=[];try{k.mountOwned("patter",M,{owner:le}),h.push("patter");let m=new Set;for(let[v,R]of Object.entries(xt(t))){let C=e.scopeRegistry?.scopes.find(rr=>rr.token===v),de=(C?.declarations??[]).map(Dt);k.defineForeign(v,R,de,{writable:C?.writable??!0,owner:le}),h.push(v),m.add(v)}for(let v of A?e.scopeRegistry?.scopes??[]:[]){if(m.has(v.token)||k.has(v.token))continue;let R=(v.declarations??[]).map(C=>Ir(C,v.writable));k.defineOwned(v.token,R,{owner:le}),h.push(v.token),F.push(v.token)}}catch(m){for(let v of h)k.remove(v,{keep:!0});throw m}let E=new Map;for(let[m,v]of Object.entries(e.scenes)){let R=new Set((v.sceneProps??[]).filter(C=>C.shared??!1).map(C=>C.name.toLowerCase()));E.set(m,R)}this.host={logEnabled:t.log??!1,tracing:t.log??!1,emitEngine:(m,v,R)=>this.emitEngine(m,v,R),bundle:e,emitIds:l,strings:i,defaultStrings:o,castDisplay:c,qualifierDisplay:u,speakerLabels:p,speakerPattern:g,nodeIndex:f,blockIndex:y,blockById:d,sceneGameIdToId:this.sceneGameIdToId,blockGameIdToId:this.blockGameIdToId,tagIndex:wr(e),padIndex:xr(e),registry:k,ownsRegistry:A,patterBag:M,hostScopes:F,patterSharedDecls:I,patterLocalDecls:D,patterSharedNames:L,sceneSharedNames:E,sharedVisits:new Map,qualityLadders:new Map,sharedSelectors:new Map,stageBags:new Map,journal:null,customRng:t.rng,onDryChoice:t.onDryChoice,onError:t.onError??(m=>console.warn(`Patterplay: ${m.kind} on ${m.node} in flow '${m.flow}' failed, played through: ${m.message}`)),reportRefits:()=>{let m=k.takeMisfits(v=>v==="patter"||v.startsWith("patter/")||F.includes(v));if(m.length!==0)if(t.onRefit)t.onRefit(m);else for(let v of m)console.warn(`Patterplay: the save's ${v.scope}.${v.name} was ${JSON.stringify(v.value)}, which no longer fits its declaration; it is back at its default`)},replayPromptOnChoose:t.replayPromptOnChoose??!1,captionsOn:t.closedCaptions??!0,captionOpen:(e.closedCaptions??Ne).open,captionClose:(e.closedCaptions??Ne).close,captionCharacter:e.closedCaptions?.character||pt,refSplitCache:new Map,refSplitRevision:k.revision},this.host.reportRefits()}get locale(){return this.currentLocale}get isSourceDebug(){return this.sourceDebug}get buildId(){return this.host.bundle.content?.hash??""}setLocale(e){this.currentLocale=e,this.host.strings=this.allStrings[e]??{}}replaceStrings(e){this.allStrings=e.strings,this.host.strings=this.allStrings[this.currentLocale]??{},this.host.defaultStrings=this.allStrings[this.host.bundle.locales.default]??{}}hotSwap(e){this.refuseInCheckpoint("hotSwap");let t=this.saveGame(),r=l=>(l.setLocale(this.currentLocale),l.setClosedCaptions(this.host.captionsOn),l),s=()=>new n(e,{...this.creationOptions,registry:this.host.registry,[yt]:this.host.ownsRegistry}),i=new Set(["patter",...this.host.hostScopes]),o=this.host.ownsRegistry?void 0:Object.fromEntries(Object.entries(this.host.registry.save()).filter(([l])=>i.has(l)||l.startsWith("patter/")));this.release(!0),o&&this.host.registry.load(o,{keepParked:!0,refit:!0});let a=s();try{return a.loadGame(t),r(a)}catch{a.release(!0);let l=this.host.ownsRegistry?t.registry:o;l&&this.host.registry.load(l,{keepParked:!0,refit:!0});let c=s();for(let[u,p]of Object.entries(t.flows)){let g=p.cursor.currentSceneId;try{c.openFlow(u,g!==null?{scene:g}:{})}catch{}}return r(c)}}get closedCaptions(){return this.host.captionsOn}setClosedCaptions(e){this.host.captionsOn=e}openFlow(e,t={}){this.assertExternalScopes();let{sceneId:r,blockId:s}=this.resolveOpenAddress(t.scene,t.block),i=this.flowsById.get(e),o=this.host.journal;if(o&&i&&!i.isClosed)throw new Error(`openFlow would replace the open flow '${e}', which can't be undone while a checkpoint is open`);i?.close();let a=new H(e,this.host,t.seed??this.defaultSeed);return o&&(o.flows.add(a),o.opened.add(a),o.undo.push(()=>{a.close(),i?this.flowsById.set(e,i):this.flowsById.delete(e)})),this.flowsById.set(e,a),a.begin(r,s),a}runFlow(e,t,r){let s=this.flowsById.get(e);if(!s)return this.openFlow(e,{scene:t,block:r}).advanceToStop().played;if(!s.goto(t,r))throw new Error(`runFlow: address not found: ${t}${r===void 0?"":` / ${r}`}`);return s.advanceToStop().played}assertExternalScopes(){for(let e of this.host.bundle.externalScopes??[])if(!this.host.registry.has(e))throw new Error(`this content names @${e}, which no engine on this registry registered: give every engine the game's one registry`)}resolveOpenAddress(e,t){if(e!==void 0){let r=Me(this.host,e);if(r===void 0)throw new Error(`unknown scene: ${e}`);if(t===void 0)return{sceneId:r};let s=Fe(this.host,r,t);if(s===void 0)throw new Error(`unknown block: ${t}`);return{sceneId:r,blockId:s}}if(t!==void 0){if(!this.host.blockIndex.has(t))throw new Error(`unknown block: ${t}`);return{blockId:t}}if(Object.keys(this.host.bundle.scenes).length===0)throw new Error("no scenes in bundle");return{}}resolveSceneRef(e){if(e!=null)return Me(this.host,e)??e}resolveBlockRef(e,t){if(t!=null)return e==null?t:Fe(this.host,e,t)}sceneAddress(e){let t=this.host.bundle.scenes[e];return t?P(t):void 0}blockAddress(e){let t=this.host.blockById.get(e);return t?P(t):void 0}tagsForBeat(e){return q(this.host,e)??[]}tagsForScene(e){let t=this.resolveSceneRef(e);return(t!=null?q(this.host,t):void 0)??[]}tagsForBlock(e,t){let r=this.resolveSceneRef(e),s=this.resolveBlockRef(r,t);return(s!=null?q(this.host,s):void 0)??[]}gameDataForScene(e){let t=this.resolveSceneRef(e);return{...(t!=null?this.host.bundle.scenes[t]:void 0)?.gameData}}gameDataForBlock(e,t){let r=this.resolveBlockRef(this.resolveSceneRef(e),t);return{...(r!=null?this.host.blockById.get(r):void 0)?.gameData}}getCast(){let e=[];for(let t of this.host.bundle.cast??[])t?.name&&e.push(t.name);return e}castForScene(e){let t=this.resolveSceneRef(e),r=t!=null?this.host.bundle.scenes[t]:void 0;if(!r)return[];let s=new Set;for(let i of r.blocks)bt(i.children,s);return[...s]}castForBlock(e,t){let r=this.resolveSceneRef(e),s=this.resolveBlockRef(r,t),i=s!=null?this.host.blockById.get(s):void 0;if(!i)return[];let o=new Set;return bt(i.children,o),[...o]}getOutline(){return Object.values(this.host.bundle.scenes).map(e=>({id:e.id,...P(e)?{gameId:P(e)}:{},name:e.name,...St(e.gameData),...this.tagsField(e.id),blocks:e.blocks.map(t=>({id:t.id,...P(t)?{gameId:P(t)}:{},name:t.name,...St(t.gameData),...this.tagsField(t.id),children:t.children.map(r=>this.outlineNode(r))}))}))}getBeatSequence(){let e=[];for(let t of Object.values(this.host.bundle.scenes))for(let r of t.blocks)G(r.children,s=>{if(s.type==="snippet")for(let i of s.beats??[])e.push({sceneId:t.id,blockId:r.id,snippetId:s.id,beat:this.beatInfo(i)})});return e}outlineNode(e){return e.type==="group"?{type:"group",id:e.id,...this.tagsField(e.id),...e.selector?{selector:e.selector}:{},...e.prompt?{prompt:this.beatInfo(e.prompt)}:{},children:e.children.map(t=>this.outlineNode(t))}:{type:"snippet",id:e.id,...this.tagsField(e.id),beats:(e.beats??[]).map(t=>this.beatInfo(t)),...e.jump?{jumpTo:e.jump.to,...e.jump.mode?{jumpMode:e.jump.mode}:{}}:{}}}beatInfo(e){let t=q(this.host,e.id),r={id:e.id,kind:e.kind};if(e.kind==="line"){if(e.character!==void 0){r.character=e.character;let i=this.host.defaultStrings[ye(e.character)]??this.host.castDisplay.get(e.character);i!==void 0&&(r.characterName=i)}if(e.direction!==void 0&&(r.direction=e.direction),e.qualifier!==void 0){r.qualifier=e.qualifier;let i=this.host.defaultStrings[be(e.qualifier)]??this.host.qualifierDisplay.get(e.qualifier);i!==void 0&&(r.qualifierName=i)}let s=ae(this.host,e.character,e.qualifier,!0);s!==void 0&&(r.speakerLabel=s)}if(e.kind==="line"||e.kind==="text"){let s=this.host.padIndex.get(e.id);r.padAfter=s?.resolved??$,s?.own!==void 0&&(r.ownPadAfter=s.own);let i=this.host.defaultStrings[e.id];i!==void 0&&(r.text=i)}return e.gameData&&Object.keys(e.gameData).length&&(r.gameData=e.gameData),t&&t.length&&(r.tags=t),r}tagsField(e){let t=q(this.host,e);return t&&t.length?{tags:t}:{}}getFlow(e){return this.flowsById.get(e)}flows(){return[...this.flowsById.values()]}listBags(){let e=[{bag:this.host.patterBag}];for(let[t,r]of this.host.stageBags)e.push({bag:r,pathPrefix:`@scene:${t}.`});return e}checkpoint(){if(this.host.journal)throw new Error("a checkpoint is already open: roll it back or commit it first");let e={undo:[],flows:new Set,opened:new Set,selectors:new Set,flowSelectors:new Map};return this.host.journal=e,new pe(e)}rollback(e){this.endCheckpoint(e);let t=e.journal.undo;for(let r=t.length-1;r>=0;r--)t[r]();n.forget(e.journal)}commit(e){this.endCheckpoint(e),n.forget(e.journal)}get inCheckpoint(){return this.host.journal!==null}endCheckpoint(e){if(this.host.journal!==e.journal)throw new Error("that checkpoint is not the open one");this.host.journal=null}static forget(e){e.undo=[],e.flows.clear(),e.opened.clear(),e.selectors.clear(),e.flowSelectors.clear()}refuseInCheckpoint(e){if(this.host.journal)throw new Error(`${e} can't be undone, so it isn't allowed while a checkpoint is open`)}captureFlow(e){let t=this.flowsById.get(e);if(!t)throw new Error(`no open flow '${e}' to capture`);return{version:ne,...t.snapshot(),...Or(e,this.host.registry.save())}}restoreFlow(e,t){this.refuseInCheckpoint("restoreFlow");let r=t.version;if(r!==2&&r!==ne)throw new Error(`unsupported flow state version: ${String(r)}`);let s=t.cursor;if(typeof s!="object"||s===null)throw new Error("malformed flow state: no cursor");if(this.flowsById.has(e))throw new Error(`a flow '${e}' is already open; close it before restoring another under that id`);this.assertExternalScopes();let i=O.flow(e);this.host.registry.discardParked(i),this.host.registry.load(Rt(e,t),{keepParked:!0,refit:!0});let o=new H(e,this.host,this.defaultSeed);try{o.restore(t)}catch(a){throw o.close(),this.host.registry.discardParked(i),a}return this.flowsById.set(e,o),this.host.reportRefits(),o}closeFlow(e){this.refuseInCheckpoint("closeFlow"),this.flowsById.get(e)?.close(),this.flowsById.delete(e)}reset(){this.refuseInCheckpoint("reset");for(let e of this.flowsById.values())e.close();this.flowsById.clear(),this.host.patterBag.reseed(this.host.patterSharedDecls),this.host.sharedVisits.clear(),this.host.sharedSelectors.clear();for(let e of this.host.stageBags.keys())this.host.registry.remove(O.stage(e));this.host.stageBags.clear(),this.host.registry.discardParked("patter/")}release(e){for(let r of this.flowsById.values())r.releaseBags(e),r.close();this.flowsById.clear();let t=this.host.registry;for(let r of this.host.stageBags.keys())t.remove(O.stage(r),{keep:e});this.host.stageBags.clear();for(let r of["patter",...this.host.hostScopes])t.has(r)&&t.remove(r,{keep:e});for(let r of Object.keys(xt(this.creationOptions)))t.has(r)&&t.remove(r)}getProperty(e){let{scope:t,name:r}=this.splitShared(e);return this.host.registry.get(t,r)}setProperty(e,t){let{scope:r,name:s}=this.splitShared(e),i=this.host.journal?this.host.registry.get(r,s):void 0;this.host.registry.set(r,s,t,{host:!0}),this.host.journal&&i!==void 0&&this.host.journal.undo.push(()=>this.host.registry.set(r,s,i,{host:!0}))}stageIndex(e,t){return _(this.ladderOf(e),t)}compareStages(e,t,r){return U(this.ladderOf(e),t,r)}nextStage(e,t){return W(this.ladderOf(e),t)}ladderOf(e){let{scope:t,name:r}=this.splitShared(e),s=Dr(this.host,t,r);if(!s)throw new Error(`'${e}' is not a quality`);return s}log(){return this.engineLog}clearLog(){this.engineLog.length=0}onTrace(e){return this.engineTraceHandlers.add(e),this.host.tracing=!0,()=>{this.engineTraceHandlers.delete(e),this.host.tracing=this.host.logEnabled||this.engineTraceHandlers.size>0}}emitEngine(e,t,r){for(let s of this.engineTraceHandlers)s(e,t);this.host.logEnabled&&this.engineLog.push({...t,flow:e,seq:this.engineSeq++,...r?{scene:r}:{}})}getVisitCounts(){return Object.fromEntries(this.host.sharedVisits)}listProperties(){return this.host.patterSharedDecls.map(e=>({name:e.name,path:`@patter.${e.name}`,type:e.type,values:e.values,stages:e.stages,value:this.getProperty(`@${e.name}`),default:J(e),writable:e.writable??!0}))}splitShared(e){let t=It(this.host,e);if(t.scope==="scene")throw new Error(`'${e}': @scene properties are scene-scoped - read/write them on a Flow, not the Engine`);return t}save(){return{patter:this.host.patterBag.save()}}load(e){e.patter&&this.host.patterBag.load(e.patter)}saveGame(){let e={};for(let[t,r]of this.flowsById)e[t]=r.snapshot();return{version:ne,...this.host.ownsRegistry?{registry:this.host.registry.save()}:{},sharedVisits:Object.fromEntries(this.host.sharedVisits),sharedSelectors:Et(this.host.sharedSelectors),flows:e}}loadGame(e){this.refuseInCheckpoint("loadGame");let t=e.version;if(t!==2&&t!==ne)throw new Error(`unsupported save version: ${String(t)}`);let r=e.flows;if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("malformed save: no flows");this.assertExternalScopes();let s=this.host.registry;for(let[o,a]of this.flowsById)a.releaseBags(o in e.flows),a.close();this.flowsById.clear();for(let o of this.host.stageBags.keys())s.remove(O.stage(o),{keep:!0});this.host.stageBags.clear();let i=e.version===2?Rr(e):e.registry;i&&(this.host.ownsRegistry?s.load(i,{refit:!0}):s.load(i,{keepParked:!0,refit:!0})),this.host.sharedVisits.clear();for(let[o,a]of Object.entries(e.sharedVisits??{}))this.host.sharedVisits.set(o,a);this.host.sharedSelectors.clear();for(let[o,a]of Ct(e.sharedSelectors))this.host.sharedSelectors.set(o,a);for(let[o,a]of Object.entries(e.flows)){let l=new H(o,this.host,this.defaultSeed);l.restore(a),this.flowsById.set(o,l)}this.host.reportRefits()}},H=class{id;host;local;registered=new Set;rngState;started=!1;flowEnded=!1;closed=!1;currentSceneId=null;stack=[];activeSnippet=null;beatIndex=0;pendingChoice=null;pendingPrompt=null;pendingPromptOwnerId=null;selectors=new Map;visitCounts=new Map;sceneBags=new Map;patterResolver={get:e=>this.host.patterSharedNames.has(e)?this.host.patterBag.get(e):this.local.get(e),set:(e,t)=>{this.host.patterSharedNames.has(e)?this.host.registry.set("patter",e,t):this.local.set(e,t)}};sceneResolver={get:e=>{let t=this.currentSceneId;if(t!==null)return this.sceneBagFor(t,e)?.get(e)},set:(e,t)=>{let r=this.currentSceneId;if(r===null)return;let s=this.sceneBagFor(r,e);s&&s.set(e,t)}};evalCtx;ctxRevision=-1;registryQualities;flowLog=[];flowSeq=0;constructor(e,t,r){this.id=e,this.host=t,this.rngState=ee(r),this.local=this.newLocal(),this.evalCtx={scopes:{},host:{nextRandom:this.rng,visits:s=>this.visitCounts.get(s)??0,patterVisits:s=>this.host.sharedVisits.get(s)??0},qualities:(s,i)=>this.stagesFor(s,i)}}context(){let e=this.host.registry;if(e.revision!==this.ctxRevision){let t=e.toEvalContext(),r=this.evalCtx.scopes;for(let s of Object.keys(r))delete r[s];Object.assign(r,t.scopes),r.patter=this.patterResolver,r.scene=this.sceneResolver,this.registryQualities=t.qualities,this.ctxRevision=e.revision}return this.evalCtx}stagesFor(e,t){let r=t.toLowerCase();if(e==="patter")return ce(this.host,"patter",()=>[...this.host.patterSharedDecls,...this.host.patterLocalDecls]).get(r);if(e==="scene"){let s=this.currentSceneId;return s==null?void 0:ce(this.host,`scene/${s}`,()=>this.host.bundle.scenes[s]?.sceneProps).get(r)}return this.registryQualities?.(e,t)??ce(this.host,`host/${e}`,()=>this.host.bundle.scopeRegistry?.scopes.find(s=>s.token===e)?.declarations).get(r)}begin(e,t){if(this.host.journal&&!this.host.journal.opened.has(this))throw new Error("a flow can't be started or reset while a checkpoint is open");if(this.releaseBags(!1),this.host.registry.discardParked(O.flow(this.id)),this.mountLocal(),this.selectors.clear(),this.visitCounts.clear(),this.stack=[],this.currentSceneId=null,this.flowEnded=!1,this.activeSnippet=null,this.beatIndex=0,this.clearPending(),this.started=!0,t){let r=this.host.blockIndex.get(t);if(!r)throw new Error(`unknown block: ${t}`);this.enterSceneSetup(r.sceneId),this.stack=[{sceneId:r.sceneId,containerId:t,index:0}],this.enter(t)}else{let r=e??Object.keys(this.host.bundle.scenes)[0],s=r?this.host.bundle.scenes[r]:void 0;if(!s)throw new Error(r?`unknown scene: ${r}`:"no scenes in bundle");this.enterSceneSetup(r);let i=s.blocks[0];i&&(this.stack=[{sceneId:r,containerId:i.id,index:0}],this.enter(i.id))}this.settle()}reset(e,t){this.begin(e,t)}start(e,t){this.reset(e,t)}goto(e,t){if(this.closed)return!1;if(this.touch(),e==="END")return this.started=!0,this.clearPending(),this.activeSnippet=null,this.beatIndex=0,this.flowEnded=!0,this.stack=[],!0;let r=Me(this.host,e);if(r===void 0)return!1;let s;return t!==void 0&&(s=Fe(this.host,r,t),s===void 0)?!1:this.started?(this.clearPending(),this.activeSnippet=null,this.beatIndex=0,this.flowEnded=!1,this.enterTarget(s??r,"jump"),this.settle(),!0):(this.begin(r,s),!0)}close(){this.releaseBags(!1),this.closed=!0,this.flowEnded=!0,this.stack=[],this.activeSnippet=null,this.beatIndex=0,this.clearPending()}clearPending(){this.pendingChoice=null,this.pendingPrompt=null,this.pendingPromptOwnerId=null}touch(){let e=this.host.journal;if(!e||e.flows.has(this))return;e.flows.add(this);let{rngState:t,started:r,flowEnded:s,currentSceneId:i,activeSnippet:o,beatIndex:a,pendingChoice:l,pendingPrompt:c,pendingPromptOwnerId:u}=this,p=this.stack.map(g=>({...g}));e.undo.push(()=>{Object.assign(this,{rngState:t,started:r,flowEnded:s,currentSceneId:i,activeSnippet:o,beatIndex:a,pendingChoice:l,pendingPrompt:c,pendingPromptOwnerId:u,stack:p})})}get isClosed(){return this.closed}get currentScene(){return this.currentSceneId}advance(){if(this.closed)return{type:"end"};if(!this.started)throw new Error("flow has not been started");if(this.touch(),this.pendingPrompt){let e=this.pendingPrompt;return this.pendingPrompt=null,this.pendingPromptOwnerId=null,e.shown?this.promptResult(e.beat,e.shown):this.beatResult(e.beat)}return this.settle(),this.flowEnded?{type:"end"}:this.pendingChoice?{type:"choice",groupId:this.pendingChoice.groupId,options:this.pendingChoice.options}:this.activeSnippet?this.beatResult(this.activeSnippet.beats[this.beatIndex++]):(this.flowEnded=!0,{type:"end"})}advanceToStop(){let e=[];for(;;){let t=this.advance();if(t.type==="choice"||t.type==="end")return{played:e,stop:t};e.push(t)}}settle(){let e=0;for(;;){if(++e>1e4)throw new Error("flow did not settle after 10000 transitions - likely a jump cycle with no deliverable content");if(this.flowEnded||this.pendingChoice)return;if(this.activeSnippet){if(this.beatIndex<(this.activeSnippet.beats?.length??0))return;this.runEffects(this.activeSnippet.onExit,this.activeSnippet.id);let i=this.activeSnippet.jump;this.activeSnippet=null,this.beatIndex=0,this.resolveJump(i);continue}let t=this.stack[this.stack.length-1];if(!t){this.flowEnded=!0;return}t.sceneId!==this.currentSceneId&&(this.currentSceneId=t.sceneId);let r=this.childrenOf(t.containerId);if(!r){this.stack.pop();continue}let s=t.index;for(;t.index<r.length&&!this.eligible(r[t.index]);)t.index++;if(this.host.tracing&&t.index!==s&&this.emit({type:"select",group:t.containerId,selector:"run",children:r.slice(s,t.index+1).map((i,o)=>({id:i.id,eligible:s+o===t.index})),picked:r[t.index]?.id??null}),t.index>=r.length){this.stack.pop();continue}this.enterChild(r[t.index++])}}listBags(){let e=[{bag:this.local,pathPrefix:`${this.id}/@patter.`}];for(let[t,r]of this.sceneBags)e.push({bag:r,pathPrefix:`${this.id}/@scene:${t}.`});return e}log(){return this.flowLog}clearLog(){this.flowLog.length=0}emit(e){let t=this.currentSceneId??void 0;this.host.emitEngine(this.id,e,t),this.host.logEnabled&&this.flowLog.push({...e,seq:this.flowSeq++,...t?{scene:t}:{}})}getVisitCounts(){return Object.fromEntries(this.visitCounts)}stepFor(e){let t=kr(this.host.bundle).get(e);return t?this.beatResult(t):void 0}getChoices(){return this.pendingChoice?.options??[]}choose(e){let t=this.pendingChoice;if(!t)throw new Error("no choice is pending");let r=t.options.find(o=>o.id===e);if(!r)throw new Error(`unknown choice option: ${e}`);if(!r.eligible)throw new Error(`choice option is not eligible: ${e}`);this.touch();let s=t.byId.get(e);this.host.tracing&&this.emit({type:"chose",group:t.groupId,option:e}),this.pendingChoice=null;let i=this.host.replayPromptOnChoose?this.authoredPromptOf(s):void 0;this.pendingPrompt=i&&r.prompt?{beat:i,shown:{...r.prompt}}:null,this.pendingPromptOwnerId=this.pendingPrompt?s.id:null,this.enterChild(s)}isEnded(){return this.flowEnded}getProperty(e){let{scope:t,name:r}=this.splitRef(e);return t==="patter"?this.patterResolver.get(r):t==="scene"?this.sceneResolver.get(r):this.host.registry.get(t,r)}setProperty(e,t){this.writeProperty(e,t,!0)}stageIndex(e,t){return _(this.ladderOf(e),t)}compareStages(e,t,r){return U(this.ladderOf(e),t,r)}nextStage(e,t){return W(this.ladderOf(e),t)}ladderOf(e){let{scope:t,name:r}=this.splitRef(e);this.context();let s=this.stagesFor(t,r);if(!s)throw new Error(`'${e}' is not a quality`);return s}writeProperty(e,t,r){let{scope:s,name:i}=this.splitRef(e),o=this.host.journal;if(s==="patter"){if(o){let a=this.host.patterSharedNames.has(i),l=a?this.host.patterBag.get(i):this.local.get(i),c=this.local;l!==void 0&&o.undo.push(a?()=>this.host.registry.set("patter",i,l):()=>c.set(i,l))}this.patterResolver.set(i,t)}else if(s==="scene"){if(this.currentSceneId===null)throw new Error(`'${e}': the flow has not entered a scene yet`);if(o){let a=this.sceneBagFor(this.currentSceneId,i),l=a?.get(i);a&&l!==void 0&&o.undo.push(()=>a.set(i,l))}this.sceneResolver.set(i,t)}else{let a=o?this.host.registry.get(s,i):void 0;this.host.registry.set(s,i,t,r?{host:!0}:void 0),o&&a!==void 0&&o.undo.push(()=>this.host.registry.set(s,i,a,{host:!0}))}}snapshot(){return{rngState:this.rngState,visits:Object.fromEntries(this.visitCounts),cursor:{flowEnded:this.flowEnded,currentSceneId:this.currentSceneId,stack:this.stack.map(e=>{let t=this.childrenOf(e.containerId)?.[e.index];return t?{...e,nextId:t.id}:{...e}}),activeSnippetId:this.activeSnippet?.id??null,beatIndex:this.beatIndex,pendingChoice:this.pendingChoice?{groupId:this.pendingChoice.groupId,options:this.pendingChoice.options.map(e=>({...e}))}:null,pendingPromptOwnerId:this.pendingPromptOwnerId,...this.pendingPrompt?.shown?{pendingPrompt:Cr(this.pendingPrompt.shown)}:{},selectors:Et(this.selectors)}}}restore(e){if(this.host.journal)throw new Error("a flow can't be restored while a checkpoint is open");this.restoreCursor(e),this.releaseBags(!0),this.mountLocal();for(let t of new Set([this.currentSceneId,...this.stack.map(r=>r.sceneId)]))t!==null&&this.host.bundle.scenes[t]&&this.ensureSceneBags(t)}restoreCursor(e){this.rngState=ee(e.rngState),this.visitCounts=new Map(Object.entries(e.visits??{}));let t=e.cursor;if(this.started=!0,this.flowEnded=t.flowEnded,this.beatIndex=t.beatIndex,this.currentSceneId=t.currentSceneId,this.stack=t.stack.map(r=>{let{nextId:s,...i}=r;if(s!==void 0){let o=this.childrenOf(i.containerId)?.findIndex(a=>a.id===s)??-1;if(o>=0)return{...i,index:o}}return{...i}}),this.activeSnippet=null,t.activeSnippetId!==null){let r=this.host.nodeIndex.get(t.activeSnippetId);r&&r.type==="snippet"&&(this.activeSnippet=r)}if(this.selectors=Ct(t.selectors),this.pendingChoice=null,t.pendingChoice!==null){let r=new Map,s=[];for(let i of t.pendingChoice.options){let o=this.host.nodeIndex.get(i.id);if(!o)continue;r.set(i.id,o);let{prompt:a,...l}=i,c=a?.kind==="line"&&a.speakerLabel===void 0?ae(this.host,a.character,a.qualifier):void 0;s.push({...l,...a?{prompt:{...a,padAfter:a.padAfter??this.promptPadOf(o),...c!==void 0?{speakerLabel:c}:{}}}:{}})}s.length>0&&(this.pendingChoice={groupId:t.pendingChoice.groupId,options:s,byId:r})}if(this.pendingPrompt=null,this.pendingPromptOwnerId=t.pendingPromptOwnerId??null,this.pendingPromptOwnerId){let r=this.host.nodeIndex.get(this.pendingPromptOwnerId),s=r?this.authoredPromptOf(r):void 0,i=t.pendingPrompt,o=i?.kind==="line"&&i.speakerLabel===void 0?ae(this.host,i.character,i.qualifier):void 0;s?this.pendingPrompt={beat:s,...i?{shown:{...i,padAfter:i.padAfter??this.padOf(s.id),...o!==void 0?{speakerLabel:o}:{}}}:{}}:this.pendingPromptOwnerId=null}}enterSceneSetup(e){let t=this.host.bundle.scenes[e];if(!t)throw new Error(`unknown scene: ${e}`);this.currentSceneId=e,this.enter(e),this.seedScene(t),this.runEffects(t.onEntry,t.id)}enterChild(e){if(this.enter(e.id),e.type==="snippet"){this.beginSnippet(e);return}let t=e.selector??"run";if(t==="run"){this.stack.push({sceneId:this.currentSceneId,containerId:e.id,index:0});return}if(t==="choice"){this.setupChoice(e);return}let r=this.selectChild(e);r&&this.enterChild(r)}childrenOf(e){let t=this.host.blockById.get(e);if(t)return t.children;let r=this.host.nodeIndex.get(e);if(r&&r.type==="group")return r.children}beginSnippet(e){this.runEffects(e.onEnter,e.id),this.activeSnippet=e,this.beatIndex=0}setupChoice(e){let t=[],r=new Map,s=[];for(let o of e.children){if(o.fallback===!0){s.push(o);continue}if(o.sticky!==!0&&(this.visitCounts.get(o.id)??0)>=1)continue;let a=this.eligible(o),l=o.secretUntilEligible===!0;!a&&l||(t.push({id:o.id,prompt:this.promptFor(o),eligible:a,gameData:o.gameData}),r.set(o.id,o))}if(t.some(o=>o.eligible)){this.host.tracing&&this.emit({type:"choice",group:e.id,options:t.map(o=>({id:o.id,eligible:o.eligible}))}),this.pendingChoice={groupId:e.id,options:t,byId:r};return}let i=s.find(o=>this.eligible(o));if(i){this.enterChild(i);return}this.host.tracing&&this.emit({type:"dry",group:e.id}),this.host.onDryChoice?.(e.id)}resolveJump(e){e&&this.enterTarget(e.to,e.mode==="call"?"call":"jump")}enterTarget(e,t){if(this.host.tracing&&this.emit({type:"jump",to:e,mode:t}),e==="END"){this.flowEnded=!0,this.stack=[];return}let r,s,i=this.host.bundle.scenes[e];if(i){this.enterSceneSetup(e);let a=i.blocks[0];if(!a){t==="jump"&&(this.stack=[]);return}r=e,s=a.id}else{let a=this.host.blockIndex.get(e);if(!a)throw new Error(`jump target not found: ${e}`);a.sceneId!==this.currentSceneId&&this.enterSceneSetup(a.sceneId),r=a.sceneId,s=e}this.enter(s);let o={sceneId:r,containerId:s,index:0};t==="call"?this.stack.push(o):this.stack=[o]}selectChild(e){let t=e.children.map(l=>({id:l.id,eligible:this.eligible(l)})),r=e.children.filter((l,c)=>t[c].eligible),s=e.options?.order??"sequential",i=e.options?.exhaust??"once",o=l=>(this.host.tracing&&this.emit({type:"select",group:e.id,selector:e.selector??"default",...e.selector==="sequence"?{order:s,exhaust:i}:{},children:t,picked:l?.id??null}),l);if(r.length===0)return o(null);let a=this.selectorState(e);switch(e.selector){case"branch":return o(r[0]);case"sequence":return o(s==="shuffle"?this.pickShuffle(r,i,a):s==="specificity"?this.pickSpecificity(r,i,a):this.pickSequential(r,i,a));default:return null}}pickSequential(e,t,r){let s=e.length,i=r.seq??0;return r.seq=i+1,t==="repeat"?e[i%s]:i<s?e[i]:t==="stick"?e[s-1]:null}pickShuffle(e,t,r){let s=e.length,i=t==="stick",o=()=>(i?e.slice(0,s-1):e).map(g=>g.id),a=new Set(e.map(g=>g.id));if(r.bag===void 0&&(r.bag=o()),!r.bag.some(g=>a.has(g))){if(t==="once")return null;if(i){let g=e[s-1];return r.last=g.id,g}if(r.bag=o(),r.bag.length===0)return null}let l=r.bag.filter(g=>a.has(g)),c=r.last!==void 0&&l.length>1?l.indexOf(r.last):-1,u=Math.floor(this.rng()*(c>=0?l.length-1:l.length));c>=0&&u>=c&&u++;let p=l[u];return r.bag.splice(r.bag.indexOf(p),1),r.last=p,e.find(g=>g.id===p)}pickSpecificity(e,t,r){let s=e;if(t!=="repeat"){r.bag===void 0&&(r.bag=e.map(u=>u.id));let c=new Set(r.bag);if(s=e.filter(u=>c.has(u.id)),s.length===0)return t==="stick"&&r.last!==void 0?e.find(u=>u.id===r.last)??null:null}let i=-1,a=s.map(c=>{let u=this.specScore(c);return u>i&&(i=u),{c,s:u}}).filter(c=>c.s===i).map(c=>c.c),l;if(a.length===1)l=a[0];else{let c=r.last!==void 0?a.findIndex(p=>p.id===r.last):-1,u=Math.floor(this.rng()*(c>=0?a.length-1:a.length));c>=0&&u>=c&&u++,l=a[u]}return t!=="repeat"&&(r.bag=r.bag.filter(c=>c!==l.id)),r.last=l.id,l}specScore(e){return e.condition?this.matchedSpec(this.conditionAst(e.condition),!0,e):0}matchedSpec(e,t,r){return ze(e,i=>{try{return kt(ue(i,this.context(),Ae))}catch(o){return this.reportError("best-match",r.id,r.condition,o),!1}},{want:t})}selectorState(e){let t=e.shared?this.host.sharedSelectors:this.selectors,r=this.host.journal,s;if(r&&(s=e.shared?r.selectors:r.flowSelectors.get(this),s||(s=new Set,r.flowSelectors.set(this,s))),r&&s&&!s.has(e.id)){s.add(e.id);let o=t.get(e.id),a=o?{...o,...o.bag?{bag:[...o.bag]}:{}}:void 0;r.undo.push(()=>{a?t.set(e.id,a):t.delete(e.id)})}let i=t.get(e.id);return i||(i={},t.set(e.id,i)),i}runEffects(e,t){for(let r of e??[]){let s;try{s=this.evalExpr(r.value);let i=this.host.tracing?this.getProperty(r.target):void 0;this.writeProperty(r.target,s,!1),this.host.tracing&&this.emit({type:"write",target:r.target,value:s,...i!==void 0?{prev:i}:{}})}catch(i){this.reportError("effect",t,r.value,i)}}}eligible(e){if(!e.condition)return!0;try{return kt(this.evalExpr(e.condition))}catch(t){return this.reportError("condition",e.id,e.condition,t),!1}}reportError(e,t,r,s){let i=s instanceof Error?s.message:String(s),o=r?.src;this.host.onError({flow:this.id,kind:e,node:t,...o?{source:o}:{},message:i}),this.host.tracing&&this.emit({type:"diagnostic",kind:e,node:t,...o?{source:o}:{},message:i})}evalExpr(e){return ue(this.conditionAst(e),this.context(),Ae)}conditionAst(e){let t=gt.get(e);return t||(t=V(e.ast),gt.set(e,t)),t}enter(e){let t=this.visitCounts,r=t.get(e);t.set(e,(r??0)+1);let s=this.host.sharedVisits,i=s.get(e);s.set(e,(i??0)+1),this.host.journal&&this.host.journal.undo.push(()=>{r===void 0?t.delete(e):t.set(e,r),i===void 0?s.delete(e):s.set(e,i)})}rng=()=>{if(this.host.customRng)return this.host.customRng();let e=Ie(this.rngState),t=e.next();return this.rngState=e.state(),t};beatResult(e){let t=q(this.host,e.id),r=t&&t.length?{tags:t}:{};switch(e.kind){case"gameEvent":return{type:"gameEvent",id:e.id,gameData:e.gameData,...r};case"text":return{type:"text",id:e.id,text:this.interpolate(this.resolveString(e.id)),padAfter:this.padOf(e.id),gameData:e.gameData,...r};case"line":{let s=this.resolveString(e.id),i=!this.host.captionsOn,a=i&&e.character===this.host.captionCharacter?"":this.captionLine(this.host.bundle.voiced?s:this.interpolate(s)),l=i&&a.length===0;return{type:"line",id:e.id,text:a,character:l?void 0:e.character,characterName:l?void 0:this.resolveCharacterName(e.character),direction:l?void 0:e.direction,qualifier:l?void 0:e.qualifier,qualifierName:l?void 0:this.resolveQualifierName(e.qualifier),speakerLabel:l?void 0:ae(this.host,e.character,e.qualifier),padAfter:this.padOf(e.id),gameData:e.gameData,...r}}}}interpolate(e){return it(e,t=>this.getProperty(t))}stripCaptions(e){return st(e,this.host.captionOpen,this.host.captionClose)}captionLine(e){return this.host.captionsOn?e:this.stripCaptions(e)}promptFor(e){let t=this.promptBeatOf(e);if(!t)return;let r=this.interpolate(this.resolveString(t.id)),s=this.padOf(t.id);return t.kind==="line"?{kind:"line",text:this.captionLine(r),character:t.character,characterName:this.resolveCharacterName(t.character),direction:t.direction,qualifier:t.qualifier,qualifierName:this.resolveQualifierName(t.qualifier),speakerLabel:ae(this.host,t.character,t.qualifier),padAfter:s}:{kind:"text",text:r,padAfter:s}}authoredPromptOf(e){return e.type==="group"?e.prompt:void 0}promptResult(e,t){let r=q(this.host,e.id),s=r&&r.length?{tags:r}:{};return t.kind==="text"?{type:"text",id:e.id,text:t.text,padAfter:this.padOf(e.id),gameData:e.gameData,...s}:{type:"line",id:e.id,text:t.text,character:t.character,characterName:t.characterName,direction:t.direction,qualifier:t.qualifier,qualifierName:t.qualifierName,speakerLabel:t.speakerLabel,padAfter:this.padOf(e.id),gameData:e.gameData,...s}}promptBeatOf(e){return e.type==="group"&&e.prompt?e.prompt:((e.type==="snippet"?e:this.firstTextSnippetIn(e.children))?.beats??[]).find(r=>r.kind==="line"||r.kind==="text")}firstTextSnippetIn(e){let t;return G(e,r=>{!t&&r.type==="snippet"&&(r.beats??[]).some(s=>s.kind==="line"||s.kind==="text")&&(t=r)}),t}resolveString(e){if(this.host.emitIds)return e;let t=this.host.strings[e];if(t!==void 0)return t;let r=this.host.defaultStrings[e];return r!==void 0?`<Untranslated: ${e}> ${r}`:e}resolveCharacterName(e){if(e===void 0||this.host.emitIds)return;let t=ye(e);return this.host.strings[t]??this.host.defaultStrings[t]??this.host.castDisplay.get(e)}promptPadOf(e){let t=this.promptBeatOf(e);return t?this.padOf(t.id):$}padOf(e){return this.host.padIndex.get(e)?.resolved??$}resolveQualifierName(e){if(e===void 0||this.host.emitIds)return;let t=be(e);return this.host.strings[t]??this.host.defaultStrings[t]??this.host.qualifierDisplay.get(e)}splitRef(e){return It(this.host,e)}newLocal(){return new T(this.host.patterLocalDecls,{pathPrefix:"@patter."})}mountLocal(){this.local=this.newLocal();let e=O.flowGlobals(this.id);this.host.registry.mountOwned(e,this.local,{owner:le}),this.registered.add(e),this.host.reportRefits()}releaseBags(e){for(let t of this.registered)this.host.registry.remove(t,{keep:e});this.registered.clear(),this.sceneBags.clear()}sceneBagFor(e,t){if(this.host.bundle.scenes[e])return this.ensureSceneBags(e),this.host.sceneSharedNames.get(e)?.has(t.toLowerCase())?this.host.stageBags.get(e):this.sceneBags.get(e)}ensureSceneBags(e){let t=this.host.sceneSharedNames.get(e)??new Set,r=this.host.bundle.scenes[e]?.sceneProps??[],s=this.host.journal,i=!this.sceneBags.has(e)||!this.host.stageBags.has(e);if(!this.sceneBags.has(e)){let o=new T(r.filter(c=>!t.has(c.name.toLowerCase())),{pathPrefix:"@scene."}),a=O.flowScene(this.id,e),l=vt(this.host.registry,a,o,s!==null);this.registered.add(a),this.sceneBags.set(e,o),s&&s.undo.push(()=>{this.sceneBags.get(e)===o&&(this.host.registry.remove(a,l?{keep:!0}:void 0),this.registered.delete(a),this.sceneBags.delete(e))})}if(!this.host.stageBags.has(e)){let o=new T(r.filter(l=>t.has(l.name.toLowerCase())),{pathPrefix:"@scene."}),a=vt(this.host.registry,O.stage(e),o,s!==null);this.host.stageBags.set(e,o),s&&s.undo.push(()=>{this.host.stageBags.get(e)===o&&(this.host.registry.remove(O.stage(e),a?{keep:!0}:void 0),this.host.stageBags.delete(e))})}i&&this.host.reportRefits()}seedScene(e){let t=this.host.sceneSharedNames.get(e.id)??new Set;this.ensureSceneBags(e.id);for(let r of e.sceneProps??[]){if(!r.temporary)continue;let s=r.name.toLowerCase(),i=t.has(s)?this.host.stageBags.get(e.id):this.sceneBags.get(e.id);if(!i)continue;let o=this.host.journal?i.get(s):void 0;o!==void 0&&this.host.journal.undo.push(()=>i.set(s,o)),i.set(s,J(r))}}};function bt(n,e){G(n,t=>{if(t.type==="group"){t.prompt?.kind==="line"&&t.prompt.character&&e.add(t.prompt.character);return}for(let r of t.beats??[])r.kind==="line"&&r.character&&e.add(r.character)})}function ae(n,e,t,r=!1){if(!e||n.emitIds)return;let s=l=>(r?void 0:n.strings[l])??n.defaultStrings[l],i=s(ye(e))??n.castDisplay.get(e)??e;if(t===void 0)return i;let o=n.speakerLabels.get(`${e}\0${t}`);if(o!==void 0)return s(ot(e,t))??o;let a=s(be(t))??n.qualifierDisplay.get(t)??t;return ct(s(at)??n.speakerPattern,i,a)}function St(n){return n&&Object.keys(n).length?{gameData:n}:{}}function Cr(n){let e={kind:n.kind,text:n.text};return n.character!==void 0&&(e.character=n.character),n.characterName!==void 0&&(e.characterName=n.characterName),n.direction!==void 0&&(e.direction=n.direction),n.qualifier!==void 0&&(e.qualifier=n.qualifier),n.qualifierName!==void 0&&(e.qualifierName=n.qualifierName),n.speakerLabel!==void 0&&(e.speakerLabel=n.speakerLabel),typeof n.padAfter=="number"&&(e.padAfter=n.padAfter),e}function Et(n){let e={};for(let[t,r]of n){let s={};r.seq!==void 0&&(s.seq=r.seq),r.bag&&(s.bag=[...r.bag]),r.last!==void 0&&(s.last=r.last),e[t]=s}return e}function Ct(n){let e=new Map;for(let[t,r]of Object.entries(n??{})){let s={};r.seq!==void 0&&(s.seq=r.seq),r.bag&&(s.bag=[...r.bag]),r.last!==void 0&&(s.last=r.last),e.set(t,s)}return e}function vt(n,e,t,r){let s=r?JSON.stringify(t.save()):"";return n.mountOwned(e,t,{owner:le}),r&&JSON.stringify(t.save())!==s}function wt(n){return{name:n.name,type:n.type,values:n.values,stages:n.stages,default:n.default}}function xt(n){return{...n.world?{world:n.world}:{},...n.hostScopes}}function ce(n,e,t){let r=n.qualityLadders.get(e);if(!r){r=new Map;for(let s of t()??[]){let i=s.name.toLowerCase();s.type==="quality"&&s.stages&&!r.has(i)&&r.set(i,s.stages)}n.qualityLadders.set(e,r)}return r}function Dr(n,e,t){let r=t.toLowerCase();return e==="patter"?ce(n,"patter",()=>[...n.patterSharedDecls,...n.patterLocalDecls]).get(r):n.registry.toEvalContext().qualities?.(e,t)??ce(n,`host/${e}`,()=>n.bundle.scopeRegistry?.scopes.find(s=>s.token===e)?.declarations).get(r)}function Dt(n){return{name:n.name,type:n.type,values:n.values,stages:n.stages,default:n.default,writable:n.writable}}function Ir(n,e){let t=Dt(n),r=n.writable??e;return r===void 0?t:{...t,writable:r}}function Me(n,e){return n.sceneGameIdToId.get(e)??(n.bundle.scenes[e]?e:void 0)}function Fe(n,e,t){return n.blockGameIdToId.get(e)?.get(t)??(n.blockIndex.get(t)?.sceneId===e?t:void 0)}function It(n,e){n.refSplitRevision!==n.registry.revision&&(n.refSplitCache.clear(),n.refSplitRevision=n.registry.revision);let t=n.refSplitCache.get(e);return t||(t=nt(e,r=>r==="scene"||n.registry.has(r)||(n.bundle.externalScopes?.includes(r)??!1)),n.refSplitCache.set(e,t)),t}function Rr(n){let e={};n.shared?.patter&&(e.patter=n.shared.patter);for(let[t,r]of Object.entries(n.stageBags??{}))e[O.stage(t)]=r;for(let[t,r]of Object.entries(n.flows??{}))Object.assign(e,Rt(t,r));return e}function Rt(n,e){let t={};e.scopes?.patter&&(t[O.flowGlobals(n)]=e.scopes.patter);for(let[r,s]of Object.entries(e.sceneBags??{}))t[O.flowScene(n,r)]=s;return t}function Or(n,e){let t={scopes:{},sceneBags:{}},r=O.flow(n);for(let[s,i]of Object.entries(e)){if(!s.startsWith(r))continue;let o=s.slice(r.length);o==="patter"?t.scopes.patter=i:o.startsWith("scene/")&&(t.sceneBags[Er(o.slice(6))]=i)}return t}function kt(n){return typeof n=="boolean"?n:typeof n=="number"?n!==0:typeof n=="string"?n!=="":n.length>0}var Pr=(n,e)=>n.shared??e;function Te(n,e){return{name:n.name,type:n.type,hasDefault:n.default!==void 0,...n.default!==void 0?{default:n.default}:{},shared:Pr(n,e)}}function Br(n){return{name:n.name,type:n.type,hasDefault:n.default!==void 0,...n.values?{values:[...n.values]}:{},...n.purpose?{purpose:n.purpose}:{}}}function Lr(n,e){e.blocks++;let t=[...n.children];for(;t.length;){let r=t.pop();if(r.type==="group"){e.groups++,r.prompt&&e.prompts++,t.push(...r.children);continue}e.snippets++;for(let s of r.beats??[])e.beats++,s.kind==="gameEvent"&&e.gameEvents++}}function we(n){let e={scenes:0,blocks:0,groups:0,snippets:0,beats:0,prompts:0,gameEvents:0,cast:n.cast?.length??0},t=[],r=[];for(let o of Object.values(n.scenes)){e.scenes++;let a=P(o);t.push({gameId:a,name:o.name,blocks:o.blocks.map(l=>({gameId:P(l),name:l.name}))});for(let l of o.blocks)Lr(l,e);o.sceneProps?.length&&r.push({gameId:a,properties:o.sceneProps.map(l=>Te(l,!1))})}let s=(n.scopeRegistry?.scopes??[]).map(o=>({token:o.token,writable:o.writable??!0,opaque:o.declarations===void 0,properties:(o.declarations??[]).map(a=>Te(a,!0))})),i=Object.entries(n.gameDataFields??{}).filter(([,o])=>(o?.length??0)>0).map(([o,a])=>({kind:o,fields:(a??[]).map(Br)}));return{identity:{schema:n.schema,project:n.content.project,...n.content.version!==void 0?{version:n.content.version}:{},...n.content.hash!==void 0?{hash:n.content.hash}:{},...n.content.structureHash!==void 0?{structureHash:n.content.structureHash}:{},voiced:n.voiced,defaultLocale:n.locales.default,locales:[...n.locales.included],localisation:n.localisation?.mode??"embedded",sourceDebug:n.localisation?.sourceDebug??!1},addresses:t,hostScopes:s,properties:{patter:(n.properties??[]).map(o=>Te(o,!0)),scene:r},gameData:i,counts:e}}function Ot(n,e){return n.gameDataFields?.[e]??[]}function $e(n,e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:n.find(r=>r.name===t)?.default}function Pt(n,e){let t={};for(let r of n){let s=$e(n,e,r.name);s!==void 0&&(t[r.name]=s)}for(let[r,s]of Object.entries(e??{}))r in t||(t[r]=s);return t}function Ve(n){return{schema:K,save:n.saveGame()}}function je(n,e){if(!e||e.schema!==K||!e.save)throw new Error(`loadState: not a ${K} envelope`);n.loadGame(e.save)}function xe(n){return JSON.stringify(Ve(n))}function ke(n,e){je(n,JSON.parse(e))}function Bt(n,e){return n.getProperty(e)}function Lt(n,e,t){n.setProperty(e,t)}function At(n,e){for(let[t,r]of Object.entries(e))n.setProperty(t,r)}function qe(n){let e={};for(let t of Nt(n)){let r=t.pathPrefix??t.bag.pathPrefix;for(let[s,i]of Object.entries(t.bag.save()))e[`${r}${s}`]=i}return Object.assign(e,Mt(n)),e}function Nt(n){return[...n.listBags(),...n.flows().flatMap(e=>e.listBags())]}function Ar(n){switch(n.type){case"line":return`line ${n.character??"?"}: ${JSON.stringify(n.text)}${Ge(n.gameData)}`;case"text":return`text: ${JSON.stringify(n.text)}${Ge(n.gameData)}`;case"gameEvent":return`game event ${n.id}${Ge(n.gameData)}`;case"choice":return`choice (${n.options.length} option${n.options.length===1?"":"s"})`;case"end":return"end"}}var Ge=n=>n?` gameData=${JSON.stringify(n)}`:"";function Mt(n){let e={};for(let[t,r]of Object.entries(n.getVisitCounts()))e[`visit:${t}`]=r;for(let t of n.flows())for(let[r,s]of Object.entries(t.getVisitCounts()))e[`${t.id}/visit:${r}`]=s;return e}function Ft(n,e={}){let t=e.label?`[${e.label}] `:"",r=Be({mounts:()=>Nt(n),extra:()=>Mt(n)},{sink:e.sink,label:t});return{snapshot:()=>qe(n),capture:()=>r.capture(),dispose:()=>r.dispose(),logStep(s){(e.sink??(i=>console.log(i)))(`${t}${Ar(s)}`)}}}function Tt(n){let e=n.url??"ws://127.0.0.1:4471",t=n.WebSocket??globalThis.WebSocket,r=new Set,s=[],i=null,o=!1,a=n.build,l=()=>{if(!(!i||i.readyState!==1)){for(let p of s)try{i.send(p)}catch{}s=[]}},c=p=>{o||!i||i.readyState>1||(s.push(JSON.stringify(p)),l())};if(!t)return{flowOpened(){},observe(){},flowClosed(){},setBuild(){},close(){o=!0},state:"closed",build:a,url:e};let u=()=>{let p=JSON.stringify({t:"hello",v:1,build:a,project:n.project,flows:[...r]});try{i?.send(p)}catch{}};try{i=new t(e),i.addEventListener("open",()=>{u(),l()}),i.addEventListener("message",p=>{if(!(!n.onBundle||typeof p.data!="string"))try{let g=JSON.parse(p.data);g.t==="bundle"&&typeof g.build=="string"&&typeof g.data=="string"&&n.onBundle({build:g.build,data:g.data})}catch{}}),i.addEventListener("error",()=>{}),i.addEventListener("close",()=>{i=null,s=[]})}catch{i=null}return{flowOpened(p){r.add(p),c({t:"flowOpen",flow:p})},flowClosed(p){r.delete(p),c({t:"flowClose",flow:p})},observe(p,g,f,y,d){r.has(p)||(r.add(p),c({t:"flowOpen",flow:p})),c({t:"frame",flow:p,sceneId:g,beatId:f,type:y,choiceId:d})},setBuild(p){o||p===a||(a=p,i&&i.readyState===1&&u())},close(){o=!0,s=[];try{i?.close()}catch{}i=null},get state(){return o||!i?"closed":i.readyState===1?"connected":"connecting"},get build(){return a},url:e}}function $t(n,e,t){let r=JSON.parse(t);return e.content.structureHash!==void 0&&e.content.structureHash===r.content.structureHash?(n.replaceStrings(r),{engine:n,bundle:r,kind:"text"}):{engine:n.hotSwap(r),bundle:r,kind:"structure"}}function Nr(n,e){n.textContent="";let t=/\u0002([^\u0003]*)\u0003/g,r=0,s;for(;(s=t.exec(e))!==null;){s.index>r&&n.append(e.slice(r,s.index));let i=document.createElement("strong");i.textContent=s[1]??"",n.append(i),r=s.index+s[0].length}r<e.length&&n.append(e.slice(r))}var Ue=!1,Vt=!1,_t,Mr=350,He=6,jt=7,Q=null,Y=0,Ee=null,Fr=null;function Ut(){if(Q)return Q;let n=document.createElement("div");return n.className="tooltip",n.setAttribute("role","tooltip"),n.hidden=!0,document.body.appendChild(n),Q=n,n}var Tr=n=>n instanceof HTMLElement?n.getBoundingClientRect():n;function $r(n){let e=Ut(),t=Tr(n),r=e.getBoundingClientRect(),s=t.top-r.height-jt;s<He&&(s=t.top+t.height+jt);let i=t.left+t.width/2-r.width/2;i=Math.max(He,Math.min(i,window.innerWidth-r.width-He)),e.style.left=`${Math.round(i)}px`,e.style.top=`${Math.round(s)}px`}function Vr(n){let e=n.dataset.tip;e&&jr(n,e)}function jr(n,e){if(_t?.())return;let t=Ut(),r=(n instanceof HTMLElement?n.closest("dialog[open]"):null)??document.body;t.parentElement!==r&&r.appendChild(t),Ee=n instanceof HTMLElement?n:null,Nr(t,e),t.hidden=!1,t.classList.remove("show"),t.offsetWidth,$r(n),t.classList.add("show")}function z(){Y&&(window.clearTimeout(Y),Y=0),Ee=null,Fr=null,Q&&(Q.hidden=!0,Q.classList.remove("show"))}function Gt(n){n!==Ee&&(Y&&window.clearTimeout(Y),Y=window.setTimeout(()=>Vr(n),Mr))}function Gr(){Hr()}function qr(){Vt||(Vt=!0,setTimeout(()=>{Ue||typeof document>"u"||document.querySelector("[data-tip]")&&console.warn("app-shell: something set `data-tip` but no tooltip host is mounted, so those rollovers will not draw. Call initTooltips() once per window.")},0))}var _e=n=>n instanceof Element?n.closest("[data-tip]"):null;function Hr(n={}){n.suppressed!==void 0&&(_t=n.suppressed),!Ue&&(Ue=!0,document.addEventListener("pointerover",e=>{let t=_e(e.target);t&&Gt(t)}),document.addEventListener("pointerout",e=>{let t=_e(e.target);if(!t)return;let r=e.relatedTarget;r instanceof Node&&t.contains(r)||z()}),document.addEventListener("focusin",e=>{let t=_e(e.target);t&&Gt(t)}),document.addEventListener("focusout",()=>z()),document.addEventListener("pointerdown",()=>z(),!0),document.addEventListener("scroll",()=>{Ee&&z()},!0),document.addEventListener("keydown",e=>{e.key==="Escape"&&z()}),window.addEventListener("blur",()=>z()))}var _r={close:"\u2715",more:"\u22EF",collapsed:"\u25B8",expanded:"\u25BE",dropdown:"\u25BE",back:"\u2039",forward:"\u203A",up:"\u2191",down:"\u2193",tick:"\u2713",locked:"\u2298",readOnly:"\u25CB",checkedOut:"\u270E",modified:"\u25CF",untracked:"+",warning:"\u203C",dot:"\u25CF",play:"\u25B6",restart:"\u27F2",viewCards:"\u25A6",viewTable:"\u2630",viewNode:"\u25C8",grip:"\u283F",add:"+",note:"\u270E",comment:"\u275D"},Ur='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.571" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">',Wr='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">',S=n=>`${Ur}${n}</svg>`,Wt=n=>`${Wr}${n}</svg>`,qt=Wt('<circle cx="12" cy="12" r="6"/>'),Jr=Wt('<circle cx="12" cy="12" r="9"/>'),Jt={close:S('<path d="M18 6 6 18"/><path d="m6 6 12 12"/>'),more:S('<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>'),collapsed:S('<path d="m9 18 6-6-6-6"/>'),expanded:S('<path d="m6 9 6 6 6-6"/>'),dropdown:S('<path d="m6 9 6 6 6-6"/>'),back:S('<path d="m15 18-6-6 6-6"/>'),forward:S('<path d="m9 18 6-6-6-6"/>'),up:S('<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>'),down:S('<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>'),arrowLeft:S('<path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>'),arrowRight:S('<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>'),tick:S('<path d="M20 6 9 17l-5-5"/>'),locked:S('<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>'),readOnly:S('<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/>'),checkedOut:S('<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/>'),modified:qt,untracked:S('<path d="M5 12h14"/><path d="M12 5v14"/>'),warning:S('<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>'),dot:qt,play:S('<path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"/>'),restart:S('<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'),viewCards:S('<rect width="7" height="7" x="3" y="3" rx="1"/><rect width="7" height="7" x="14" y="3" rx="1"/><rect width="7" height="7" x="14" y="14" rx="1"/><rect width="7" height="7" x="3" y="14" rx="1"/>'),viewTable:S('<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M21 9H3"/><path d="M21 15H3"/>'),viewNode:S('<path d="m10.586 5.414-5.172 5.172"/><path d="m18.586 13.414-5.172 5.172"/><path d="M6 12h12"/><circle cx="12" cy="20" r="2"/><circle cx="12" cy="4" r="2"/><circle cx="20" cy="12" r="2"/><circle cx="4" cy="12" r="2"/>'),record:Jr,speaker:S('<path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="M16 9a5 5 0 0 1 0 6"/><path d="M19.364 18.364a9 9 0 0 0 0-12.728"/>'),grip:S('<circle cx="9" cy="12" r="1"/><circle cx="9" cy="5" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="15" cy="19" r="1"/>'),add:S('<path d="M5 12h14"/><path d="M12 5v14"/>'),copy:S('<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>'),connect:S('<path d="M12 22v-5"/><path d="M15 8V2"/><path d="M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z"/><path d="M9 8V2"/>'),search:S('<path d="m21 21-4.34-4.34"/><circle cx="11" cy="11" r="8"/>'),pin:S('<path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"/>'),settings:S('<path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"/><circle cx="12" cy="12" r="3"/>'),note:S('<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>'),comment:S('<path d="M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"/>')},cs={...Jt,noteFilled:'<svg viewBox="0 0 16 16" width="13" height="13" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M3.4 1.4h5.3L12.6 5.3v8.1a1.2 1.2 0 0 1-1.2 1.2H3.4a1.2 1.2 0 0 1-1.2-1.2V2.6A1.2 1.2 0 0 1 3.4 1.4ZM4.9 6.8h6.2v1.1H4.9Zm0 2.1h6.2v1.1H4.9Zm0 2.1h3.7v1.1H4.9Z"/></svg>',noteOutline:'<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linejoin="round" stroke-linecap="round" aria-hidden="true"><path d="M3.4 2h4.9l3.9 3.9v7.5a1 1 0 0 1-1 1H3.4a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1Z"/><path d="M8.3 2.2v3.8h3.8"/><path d="M4.9 8h6.2M4.9 10h6.2M4.9 12h3.7" stroke-width="0.95"/></svg>'},ps=Object.keys(Jt);var Ht=new Map;for(let[n,e]of Object.entries(_r))Ht.has(e)||Ht.set(e,n);function Kt(n,e,...t){let r=document.createElement(n),s=typeof e=="string"?{className:e}:e??{};s.className&&(r.className=s.className),s.text!==void 0&&s.text!==null&&(r.textContent=s.text),s.title!==void 0&&(r.title=s.title),s.tip!==void 0&&(r.dataset.tip=s.tip,r.setAttribute("aria-label",s.tip),Gr()),s.onClick&&r.addEventListener("click",s.onClick);for(let i of t)i!=null&&r.append(i);return qr(),r}function zt(n){let e=n.default;if(e!=null)return typeof e=="boolean"?e?"True":"False":Array.isArray(e)?e.length===0?"none":e.join(", "):e===""?"none":String(e);switch(n.type){case"boolean":return"False";case"number":return"0";case"enum":return n.values?.[0]??"none";case"quality":return n.stages?.[0]??"first stage";case"flags":return"none";default:return"empty"}}var Qt=n=>`default (${zt(n)})`;function We(n){let e=n.doc===void 0?Kt:(a,l)=>{let c=n.doc.createElement(a);return c.className=l.className,l.text!==void 0&&(c.textContent=l.text),l.tip!==void 0&&(c.title=l.tip,c.setAttribute("aria-label",l.tip)),l.onClick&&c.addEventListener("click",l.onClick),a==="button"&&(c.type="button"),c},t=e("span",{className:"seg shell-rungs"}),r=n.decl??{type:"quality",stages:n.stages},s=n.value===void 0,i=typeof r.default=="string"&&n.stages.includes(r.default)?r.default:n.stages[0],o=n.onPick===void 0;n.onClear&&t.append(e("button",{className:`seg-opt shell-rung shell-rung-default${s?" on":""}`,text:Qt(r),tip:s?"Not set here: the declared default holds":"Clear the value, back to the default",onClick:()=>{s||n.onClear()}}));for(let a of n.stages){let l=n.value===a,c=s&&a===i,u=e(o?"span":"button",{className:`seg-opt shell-rung${l?" on":""}${c?" fallback":""}`,text:a,tip:l?"The current stage":c?"The stage it falls back to":o?a:n.pickTip?.(a)??`Set to "${a}"`,...o?{}:{onClick:()=>{l||n.onPick(a)}}});t.append(u)}return!s&&!n.stages.includes(n.value)&&t.append(e("span",{className:"seg-opt shell-rung stray on",text:n.value,tip:`"${n.value}" is not one of the stages: pick the one it belongs at now`})),t}var Yt="pp-inspector-style",Kr=`
1
+ "use strict";var Patterplay=(()=>{var Re=Object.defineProperty;var cn=Object.getOwnPropertyDescriptor;var dn=Object.getOwnPropertyNames;var pn=Object.prototype.hasOwnProperty;var un=(r,e)=>{for(var t in e)Re(r,t,{get:e[t],enumerable:!0})},fn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dn(e))!pn.call(r,s)&&s!==t&&Re(r,s,{get:()=>e[s],enumerable:!(n=cn(e,s))||n.enumerable});return r};var gn=r=>fn(Re({},"__esModule",{value:!0}),r);var ir={};un(ir,{Checkpoint:()=>ue,DEFAULT_PAD_AFTER:()=>j,Engine:()=>xe,Flow:()=>_,SAVE_SCHEMA:()=>z,applyLiveBundle:()=>Ht,buildTagIndex:()=>we,compareStages:()=>W,createAudioResolver:()=>an,createBundleInspector:()=>on,createDebugLink:()=>Gt,createPropertyInspector:()=>rn,createStateLogger:()=>qt,describeBundle:()=>ke,deserializeState:()=>Ce,diffState:()=>re,effectiveGameData:()=>At,extensionDecls:()=>Lt,extensionSettings:()=>Bt,extensionsOf:()=>Mt,gameDataFields:()=>Nt,gameDataValue:()=>Ve,getProperty:()=>Ft,loadState:()=>Ge,nextStage:()=>J,saveState:()=>qe,serializeState:()=>Ee,setProperties:()=>$t,setProperty:()=>Tt,snapshotState:()=>_e,stageIndex:()=>U});function te(r,e){return r!==void 0&&Object.prototype.hasOwnProperty.call(r,e)?r[e]:void 0}function V(r){switch(r[0]){case"b":return{kind:"bool",value:r[1]};case"n":return{kind:"number",value:r[1]};case"s":return{kind:"string",value:r[1]};case"sv":return{kind:"scopedvar",scope:r[1],name:r[2]};case"u":return{kind:"unary",op:r[1],operand:V(r[2])};case"bin":return{kind:"binary",op:r[1],left:V(r[2]),right:V(r[3])};case"call":{let e=r.slice(2).map(V);return{kind:"call",name:r[1],args:e}}case"fd":return{kind:"flagdelta",sign:r[1],name:r[2]}}}var b=class extends Error{constructor(e){super(e),this.name="EvalError"}};function ge(r,e,t){let n=new Map(t.scopes.map(i=>[i.token,i.missing??"false"])),s=i=>{switch(i.kind){case"bool":return i.value;case"number":return i.value;case"string":return i.value;case"scopedvar":{let o=te(e.scopes,i.scope);if(o===void 0)return!1;let a=typeof o.get=="function"?o.get(i.name):te(o,i.name);if(a===void 0){if(n.get(i.scope)==="throw")throw new b(`@${i.scope}.${i.name} is not declared on the current ${i.scope}.`);return!1}return a}case"call":{if(i.name==="advance"&&!te(t.functions,i.name)){let a=i.args[0];if(i.args.length!==1||a===void 0)throw new b(`advance() takes exactly 1 argument, got ${i.args.length}`);let l=Oe(a,e);if(l===void 0)throw new b("advance() needs a quality reference (@scope.name of a quality property)");let c=B(s(a),l,"advance");return l[Math.min(c+1,l.length-1)]}let o=te(t.functions,i.name);if(!o)throw new b(`unknown function '${i.name}'`);return o.eval(i.args,{evaluate:s,ctx:e})}case"flagdelta":throw new b("flagdelta node is only valid as an argument to a flag-delta function");case"unary":{if(i.op==="not"){let a=s(i.operand);if(typeof a!="boolean")throw new b(`'not' requires a boolean operand, got ${typeof a}`);return!a}let o=s(i.operand);if(typeof o!="number")throw new b(`unary '-' requires a numeric operand, got ${typeof o}`);return-o}case"binary":{if(i.op==="and"){let d=s(i.left);if(typeof d!="boolean")throw new b(`'and' requires boolean operands, left is ${typeof d}`);if(!d)return!1;let f=s(i.right);if(typeof f!="boolean")throw new b(`'and' requires boolean operands, right is ${typeof f}`);return f}if(i.op==="or"){let d=s(i.left);if(typeof d!="boolean")throw new b(`'or' requires boolean operands, left is ${typeof d}`);if(d)return!0;let f=s(i.right);if(typeof f!="boolean")throw new b(`'or' requires boolean operands, right is ${typeof f}`);return f}let o=s(i.left),a=s(i.right),l=Oe(i.left,e),c=Oe(i.right,e),p=l??c;if(p!==void 0){if(l&&c&&!hn(l,c)&&(i.op===">"||i.op===">="||i.op==="<"||i.op==="<="))throw new b(`'${i.op}' compares two different qualities, whose stage orders are unrelated`);switch(i.op){case">":return B(o,p,">")>B(a,p,">");case">=":return B(o,p,">=")>=B(a,p,">=");case"<":return B(o,p,"<")<B(a,p,"<");case"<=":return B(o,p,"<=")<=B(a,p,"<=");case"+":case"-":case"*":case"/":throw new b(`'${i.op}' cannot be applied to a quality - a stage is a position, not a number; use advance() to move it`);default:break}}switch(i.op){case"==":return Qe(o,a);case"!=":return!Qe(o,a);case">":return q(o,a,">"),o>a;case">=":return q(o,a,">="),o>=a;case"<":return q(o,a,"<"),o<a;case"<=":return q(o,a,"<="),o<=a;case"+":if(typeof o=="number"&&typeof a=="number"||typeof o=="string"&&typeof a=="string")return o+a;throw new b(`'+' requires two numbers or two strings, got ${typeof o} and ${typeof a}`);case"-":return q(o,a,"-"),o-a;case"*":return q(o,a,"*"),o*a;case"/":if(q(o,a,"/"),a===0)throw new b("division by zero");return o/a}}}};return s(r)}function Qe(r,e){if(Array.isArray(r)||Array.isArray(e)){if(!Array.isArray(r)||!Array.isArray(e)||r.length!==e.length)return!1;let t=[...r].sort(),n=[...e].sort();for(let s=0;s<t.length;s++)if(t[s]!==n[s])return!1;return!0}return r===e}function q(r,e,t){if(typeof r!="number"||typeof e!="number")throw new b(`'${t}' requires numeric operands, got ${typeof r} and ${typeof e}`)}function Oe(r,e){if(!(r.kind!=="scopedvar"||e.qualities===void 0))return e.qualities(r.scope,r.name)}function B(r,e,t){if(typeof r!="string")throw new b(`'${t}' on a quality compares stages, got ${typeof r}`);let n=e.indexOf(r);if(n<0)throw new b(`"${r}" is not a stage of this quality (stages: ${e.join(", ")})`);return n}var hn=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]);function ne(r){if(Number.isNaN(r)||!Number.isFinite(r))return 0;let e=Math.trunc(r)%4294967296;return e<0?e+4294967296:e}function Ie(r){let e=ne(r);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}}}var Ne=r=>Array.isArray(r)?r:r.stages??[],mn=r=>Array.isArray(r)?"flags":r==null?"nothing":typeof r;function U(r,e){return typeof e=="string"?Ne(r).indexOf(e):-1}function Pe(r,e){if(typeof e!="string")throw new b(`a stage is a name, got ${mn(e)}`);let t=r.indexOf(e);if(t<0)throw new b(`"${e}" is not a stage of this quality (stages: ${r.join(", ")})`);return t}function W(r,e,t){let n=Ne(r),s=Pe(n,e)-Pe(n,t);return s<0?-1:s>0?1:0}function J(r,e){let t=Ne(r);return t[Math.min(Pe(t,e)+1,t.length-1)]}function Ae(r,e,t){switch(r.type){case"boolean":return typeof e=="boolean";case"number":return typeof e=="number";case"string":case"text":case"multiline":return typeof e=="string";case"enum":return typeof e!="string"?!1:e===""&&t?.noneChosen?!0:!Array.isArray(r.values)||r.values.includes(e);case"flags":return Array.isArray(e)&&e.every(n=>typeof n=="string"&&(!Array.isArray(r.values)||r.values.includes(n)));case"quality":return typeof e=="string"&&(!Array.isArray(r.stages)||r.stages.includes(e));default:return!0}}var yn={name:"check_flags",count:r=>Math.max(1,r.args.length-1)},bn=[yn];function Ye(r,e,t){let n=t?.countingCalls??bn;return he(r,t?.want??!0,e,n)}function he(r,e,t,n){if(r.kind==="binary"&&(r.op==="and"||r.op==="or")){let s=he(r.left,e,t,n),i=he(r.right,e,t,n);return r.op==="and"===e?s>0&&i>0?s+i:0:Math.max(s,i)}if(r.kind==="unary"&&r.op==="not")return he(r.operand,!e,t,n);if(r.kind==="call"){let s=n.find(i=>i.name===r.name);if(s){let i=s.count(r),o=t(r);return e?o?i:0:o?0:1}}return t(r)===e?1:0}function re(r,e){let t=[],n=new Set([...Object.keys(r),...Object.keys(e)]);for(let s of[...n].sort()){let i=r[s],o=e[s];JSON.stringify(i)!==JSON.stringify(o)&&t.push({path:s,from:i,to:o})}return t}var Xe=r=>r===void 0?"<unset>":JSON.stringify(r),Ze=r=>r.pathPrefix??r.bag.pathPrefix;function Le(r,e={}){let t=e.sink??(d=>console.log(d)),n=e.label??"",s=d=>{t(`${n}${d.path}: ${Xe(d.from)} -> ${Xe(d.to)}`)},i=()=>{let d={};for(let f of r.mounts()){let g=Ze(f);for(let[y,u]of Object.entries(f.bag.values))d[g+y]=u}return Object.assign(d,r.extra?.()??{}),structuredClone(d)},o=i(),a=[],l=[],c=(d,f)=>f.onAudit(g=>{let y=structuredClone({path:d+g.name,from:g.prev,to:g.next});s(y),a.push(y),o[y.path]=structuredClone(g.next)}),p=()=>{let d=r.mounts();if(!(l.length===d.length&&d.every((g,y)=>l[y].bag===g.bag))){for(let g of l)g.off();l=d.map(g=>({bag:g.bag,off:c(Ze(g),g.bag)}))}};return p(),{snapshot:i,capture(){let d=i(),f=re(o,d);for(let y of f)s(y);let g=[...a,...f];return a=[],o=d,p(),g},dispose(){for(let d of l)d.off();l=[],a=[]}}}var $=class r{values=Object.create(null);decls=new Map;subscribers=new Set;auditors=new Set;norm;pathPrefix;constructor(e=[],t){this.norm=t?.normalise??(n=>n.toLowerCase()),this.pathPrefix=t?.pathPrefix??"",this.seed(e)}seed(e){for(let t of e){let n=this.norm(t.name);this.decls.set(n,t),this.values[n]=structuredClone(t.default??K(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,n){let s=this.norm(e);if(!n?.host&&!this.writable(s))throw new Error(`'${e}' is read-only`);let i={name:s,prev:this.values[s],next:t,silent:n?.silent??!1,reason:n?.reason};this.values[s]=t;for(let o of[...this.auditors])o(i);if(!i.silent)for(let o of[...this.subscribers])o(i);return i}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])=>tt(t,this.get(e),void 0,e,this.pathPrefix))}declarations(){return[...this.decls.values()]}clone(){let e=new r([],{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,t){let n=new Map;for(let[i,o]of Object.entries(e)){let a=this.norm(i);this.values[a]=structuredClone(o),n.set(a,o)}let s=[];if(!t?.refit)return s;for(let[i,o]of this.decls){if(!n.has(i))continue;let a=n.get(i);Ae(o,a)||(this.values[i]=structuredClone(K(o)),s.push({name:i,value:a}))}return s}};function tt(r,e,t,n,s=""){let i=n??r.name.toLowerCase();return{name:i,path:s+i,type:r.type,value:e,default:r.default??K(r),...r.values!==void 0?{values:r.values}:{},...r.stages!==void 0?{stages:r.stages}:{},writable:t??r.writable??!0}}var vn=r=>r.toLowerCase(),Be=1,me=class{scopes=new Map;parked=new Map;parkedRefit=new Set;misfits=[];rev=0;get revision(){return this.rev}defineOwned(e,t,n){let s=typeof n=="string"?{pathPrefix:n}:n??{},i=new $(t,{pathPrefix:s.pathPrefix??`${e}.`,...s.normalise?{normalise:s.normalise}:{}});return this.mountOwned(e,i,s.owner!==void 0?{owner:s.owner}:void 0)}mountOwned(e,t,n){this.assertFree(e,n?.owner),this.scopes.set(e,{kind:"owned",bag:t,...n?.owner!==void 0?{owner:n.owner}:{}}),this.rev++;let s=this.parked.get(e);return s&&(this.note(e,t.load(s,{refit:this.parkedRefit.has(e)})),this.parked.delete(e),this.parkedRefit.delete(e)),this}remove(e,t){let n=this.scopes.get(e);if(!n)throw new Error(`unknown scope '@${e}'`);return t?.keep&&n.kind==="owned"&&(this.parked.set(e,n.bag.save()),this.parkedRefit.delete(e)),this.scopes.delete(e),this.rev++,this}discardParked(e){if(e===void 0)this.parked.clear(),this.parkedRefit.clear();else for(let t of[...this.parked.keys()])t.startsWith(e)&&(this.parked.delete(t),this.parkedRefit.delete(t));return this}takeMisfits(e){if(!e){let n=this.misfits;return this.misfits=[],n}let t=this.misfits.filter(n=>e(n.scope));return this.misfits=this.misfits.filter(n=>!e(n.scope)),t}note(e,t){for(let n of t)this.misfits.push({scope:e,name:n.name,value:n.value})}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,n=[],s=!0){let i=typeof s=="boolean"?{writable:s}:s;this.assertFree(e,i.owner);let o=i.normalise??vn,a=new Map;for(let l of n)a.set(o(l.name),l);return this.scopes.set(e,{kind:"foreign",resolver:t,decls:a,scopeWritable:i.writable??!0,norm:o,...i.owner!==void 0?{owner:i.owner}:{}}),this.rev++,this}has(e){return this.scopes.has(e)}get(e,t){let n=this.scopes.get(e);if(n)return n.kind==="owned"?n.bag.get(t):n.resolver.get(n.norm(t))}set(e,t,n,s){let i=this.scopes.get(e);if(!i)throw new Error(`unknown scope '@${e}'`);if(i.kind==="owned"){if(!s?.host&&!i.bag.writable(t))throw new Error(`'@${e}.${t}' is read-only`);i.bag.set(t,n,s?.host?{host:!0}:void 0);return}let o=i.norm(t);if(!i.resolver.set)throw new Error(`'@${e}.${t}' is read-only`);if(!s?.host&&!this.foreignWritable(i,o))throw new Error(`'@${e}.${t}' is read-only`);i.resolver.set(o,n)}foreignWritable(e,t){return e.resolver.set?e.decls.get(t)?.writable??e.scopeWritable:!1}listProperties(){let e=[];for(let[t,n]of this.scopes){let s=n.owner!==void 0?{owner:n.owner}:{};if(n.kind==="owned")for(let i of n.bag.rows())e.push({scope:t,...s,...i});else for(let[i,o]of n.decls)e.push({scope:t,...s,...tt(o,n.resolver.get(i),this.foreignWritable(n,i),i,`${t}.`)})}return e}toEvalContext(e,t){let n=this.view(t?.aliases),s={};for(let[o,a]of n)s[o]=a.kind==="owned"?a.bag.values:a.resolver;let i=this.qualityLadders(n);return i.size===0?{scopes:s,host:e}:{scopes:s,host:e,qualities:(o,a)=>{let l=n.get(o);return l?i.get(o)?.get(Sn(l)(a)):void 0}}}view(e){let t=new Map(this.scopes);for(let[n,s]of Object.entries(e??{})){let i=this.scopes.get(s);if(!i)throw new Error(`alias '@${n}' names '${s}', which is not registered`);t.set(n,i)}return t}qualityLadders(e){let t=new Map;for(let[n,s]of e)for(let[i,o]of et(s)){if(o.type!=="quality"||o.stages===void 0)continue;let a=t.get(n);a||(a=new Map,t.set(n,a)),a.set(i,o.stages)}return t}toSchema(e){let t=new Map;for(let[n,s]of this.view(e?.aliases)){let i=et(s);if(i.length===0)continue;let o=new Map;for(let[a,l]of i)o.set(a,{type:l.type,enumValues:l.values,...l.stages!==void 0?{stages:l.stages}:{}});t.set(n,o)}return{properties:t}}save(){let e={};for(let[t,n]of this.scopes)n.kind==="owned"&&(e[t]=n.bag.save());for(let[t,n]of this.parked)e[t]=structuredClone(n);return e}load(e,t){t?.keepParked||(this.parked.clear(),this.parkedRefit.clear());let n=t?.refit===!0;for(let[s,i]of Object.entries(e)){let o=this.scopes.get(s);o?.kind==="owned"?this.note(s,o.bag.load(i,{refit:n})):o||(this.parked.set(s,structuredClone(i)),n?this.parkedRefit.add(s):this.parkedRefit.delete(s))}}saveFragment(){return{version:Be,scopes:this.save()}}loadFragment(e){if(e.version!==Be)throw new Error(`unsupported owned-state fragment version ${e.version} (supported: ${Be})`);this.load(e.scopes)}assertFree(e,t){let n=this.scopes.get(e);if(!n)return;let s=n.owner!==void 0?` by ${n.owner}`:"",i=t!==void 0?` (wanted by ${t})`:"";throw new Error(`scope '@${e}' is already registered${s}${i}`)}};function et(r){return r.kind==="foreign"?[...r.decls.entries()]:r.bag.declarations().map(e=>[r.bag.normalise(e.name),e])}function Sn(r){return r.kind==="foreign"?r.norm:e=>r.bag.normalise(e)}function K(r){if(r.default!==void 0)return r.default;switch(r.type){case"boolean":return!1;case"number":return 0;case"string":case"text":case"multiline":return"";case"enum":return r.values?.[0]??"";case"flags":return[];case"quality":return r.stages?.[0]??"";default:return!1}}var nt=[{token:"patter",engine:"Patterplay",means:"Patter's shared globals"},{token:"story",engine:"Storylet Engine",means:"the Storylet Engine's shared @story properties"}];function se(r){return r.ctx.host??{}}var Me={defaultScope:"patter",scopes:[{token:"patter"},{token:"scene"}],functions:{random:{minArgs:2,maxArgs:2,returnType:"number",eval(r,e){if(r.length!==2)throw new b("random(a, b) requires exactly 2 arguments");let t=se(e).nextRandom;if(!t)throw new b("random() called without a PRNG in context");let n=e.evaluate(r[0]),s=e.evaluate(r[1]);if(typeof n!="number"||typeof s!="number")throw new b("random(a, b) arguments must be numbers");if(!Number.isInteger(n)||!Number.isInteger(s))throw new b("random(a, b) arguments must be integers");let i=Math.min(n,s),o=Math.max(n,s);return Math.floor(t()*(o-i+1))+i}},check_flags:{minArgs:1,returnType:"boolean",flagDeltaArgs:!0,validate:st("check_flags"),eval(r,e){let t=rt(r[0],e,"check_flags");for(let n=1;n<r.length;n++){let s=r[n];if(s.kind!=="flagdelta")throw new b("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,validate:st("set_flags"),eval(r,e){let t=[...rt(r[0],e,"set_flags")];for(let n=1;n<r.length;n++){let s=r[n];if(s.kind!=="flagdelta")throw new b("set_flags() flag args must be +flagName or -flagName");if(s.sign==="+")t.includes(s.name)||t.push(s.name);else{let i=t.indexOf(s.name);i>=0&&t.splice(i,1)}}return t}},visits:{minArgs:1,maxArgs:1,returnType:"number",validate:be("visits"),eval:(r,e)=>se(e).visits?.(ye(r,e,"visits"))??0},seen:{minArgs:1,maxArgs:1,returnType:"boolean",validate:be("seen"),eval:(r,e)=>(se(e).visits?.(ye(r,e,"seen"))??0)>0},patter_visits:{minArgs:1,maxArgs:1,returnType:"number",validate:be("patter_visits"),eval:(r,e)=>se(e).patterVisits?.(ye(r,e,"patter_visits"))??0},patter_seen:{minArgs:1,maxArgs:1,returnType:"boolean",validate:be("patter_seen"),eval:(r,e)=>(se(e).patterVisits?.(ye(r,e,"patter_seen"))??0)>0}}},Mr=nt.map(r=>r.token).filter(r=>r!=="patter"&&r!=="scene");function it(r,e){let t=r.replace(/^@/,"").split(".");return t.length===2&&e(t[0])?{scope:t[0],name:t[1].toLowerCase()}:{scope:"patter",name:t.join(".").toLowerCase()}}function ye(r,e,t){let n=e.evaluate(r[0]);if(typeof n!="string")throw new b(`${t}(id) requires a string node id`);return n}function be(r){return(e,t)=>{let n=e[0];n&&n.kind!=="string"&&t.report({path:[...t.path,"args",0],kind:"wrong-arg-type",severity:"error",message:`${r}(id): the argument must be a string id literal (a scene / block / node id)`})}}function rt(r,e,t){if(!r)throw new b(`${t}() requires at least one argument (the flags variable)`);let n=e.evaluate(r);if(Array.isArray(n))return n;if(n===!1||n===null||n===void 0)return[];throw new b(`${t}() first argument must be a flags property`)}function st(r){return(e,t)=>{if(e.length===0)return;let n=e[0];if(n.kind!=="scopedvar"){t.report({path:[...t.path,"args",0],kind:"wrong-arg-type",severity:"error",message:`${r}(): first argument must be a flags property reference (@name or @scope.name)`});return}let s=t.schema.properties.get(n.scope)?.get(n.name);if(s&&s.type!=="flags"){let i=n.scope===t.defaultScope?n.name:`${n.scope}.${n.name}`;t.report({path:[...t.path,"args",0],kind:"wrong-arg-type",severity:"error",message:`${r}(): '@${i}' is not a flags property (got ${s.type})`});return}for(let i=1;i<e.length;i++){let o=e[i];o.kind!=="flagdelta"?t.report({path:[...t.path,"args",i],kind:"wrong-arg-type",severity:"error",message:`${r}(): argument ${i+1} must be +flagName or -flagName`}):s?.type==="flags"&&s.enumValues&&!s.enumValues.includes(o.name)&&t.report({path:[...t.path,"args",i],kind:"unknown-flag-name",severity:"error",message:`${r}(): unknown flag '${o.name}'`,reference:o.name})}}}var wn=/^@[A-Za-z0-9_.]+$/;function*xn(r){let e="",t=0;for(;t<r.length;){let n=r[t];if(n==="{"&&r[t+1]==="{"){e+="{",t+=2;continue}if(n==="}"&&r[t+1]==="}"){e+="}",t+=2;continue}if(n==="{"){let s=r.indexOf("}",t+1);if(s!==-1){let i=r.slice(t,s+1),o=r.slice(t+1,s).trim();if(o.startsWith("@")){e&&(yield{kind:"text",value:e},e=""),yield{kind:"slot",raw:i,inner:o,ref:wn.test(o)?o:void 0},t=s+1;continue}e+=i,t=s+1;continue}}e+=n,t+=1}e&&(yield{kind:"text",value:e})}function kn(r){return Array.isArray(r)?r.join(", "):typeof r=="boolean"?r?"true":"false":String(r)}function En(r){return r===" "||r===" "||r===`
2
+ `||r==="\r"||r==="\f"||r==="\v"}function Cn(r){let e="",t=!1;for(let n of r){if(En(n)){t=!0;continue}t&&e.length>0&&(e+=" "),t=!1,e+=n}return e}function ot(r,e,t){if(e.length===0||r.indexOf(e)<0)return r;let n="",s=0,i=!1;for(;s<r.length;){if(r.startsWith(e,s)){let o=r.indexOf(t,s+e.length);if(o>=0){s=o+t.length,i=!0;continue}n+=r.slice(s);break}n+=r[s],s+=1}return i?Cn(n):r}function at(r,e){if(r.indexOf("{")<0)return r;let t="";for(let n of xn(r)){if(n.kind==="text"){t+=n.value;continue}if(!n.ref){t+=n.raw;continue}let s=e(n.ref);t+=s===void 0?"":kn(s)}return t}function G(r,e){for(let t of r){e(t);let n=t.children;n&&G(n,e)}}function Dn(r){return r.toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function D(r){let e=r.gameId?.trim();return e||Dn(r.name)}var j=.6;function ve(r){return`cast:${r}`}function Se(r){return`qualifier:${r}`}function lt(r,e){return`speaker:${r}:${e}`}var ct="speaker:pattern",dt="{name} ({qualifier})";function pt(r,e,t){return r.split("{name}").map(n=>n.split("{qualifier}").join(t)).join(e)}var Fe={open:"[",close:"]"},ut="SFX",z="patter/save@0",ie=3;function oe(r){let e=new Set,t=[];for(let n of r)e.has(n)||(e.add(n),t.push(n));return t}function we(r){let e=new Map,t=(n,s)=>{let i=oe([...s,...n.tags??[]]);if(e.set(n.id,i),n.type==="group"&&n.prompt&&e.set(n.prompt.id,oe([...i,...n.prompt.tags??[]])),n.type==="group")for(let o of n.children)t(o,i);else for(let o of n.beats??[])e.set(o.id,oe([...i,...o.tags??[]]))};for(let n of Object.values(r.scenes)){let s=oe(n.tags??[]);e.set(n.id,s);for(let i of n.blocks){let o=oe([...s,...i.tags??[]]);e.set(i.id,o);for(let a of i.children)t(a,o)}}return e}var ft=r=>r.kind==="line"||r.kind==="text",ae=r=>typeof r=="number"&&Number.isFinite(r)?r:void 0;function gt(r){let e=new Map,t=(i,o,a)=>{let l=i.kind==="gameEvent"?void 0:ae(i.padAfter),c=l??o;a&&c<0&&(c=0),e.set(i.id,l!==void 0?{own:l,resolved:c}:{resolved:c})},n=(i,o)=>{let a=ae(i.padAfterDefault)??o;if(i.type==="group"){i.prompt&&t(i.prompt,a,!1);for(let p of i.children)n(p,a);return}let l=i.beats??[],c=-1;l.forEach((p,d)=>{ft(p)&&(c=d)}),l.forEach((p,d)=>{ft(p)&&t(p,a,d===c)})},s=ae(r.padAfterDefault)??j;for(let i of Object.values(r.scenes)){let o=ae(i.padAfterDefault)??s;for(let a of i.blocks){let l=ae(a.padAfterDefault)??o;for(let c of a.children)n(c,l)}}return e}var ht=new WeakMap,mt=new WeakMap;function Rn(r){let e=mt.get(r);return e||(e=we(r),mt.set(r,e)),e}var yt=new WeakMap;function On(r){let e=yt.get(r);return e||(e=gt(r),yt.set(r,e)),e}var bt=new WeakMap;function In(r){let e=bt.get(r);if(e)return e;e=new Map;for(let t of Object.values(r.scenes))for(let n of t.blocks)G(n.children,s=>{if(s.type==="group"){s.prompt&&e.set(s.prompt.id,s.prompt);return}for(let i of s.beats??[])e.set(i.id,i)});return bt.set(r,e),e}function H(r,e){return r.tagIndex.get(e)?.slice()}var de="Patter",le=r=>r.replace(/%/g,"%25").replace(/\//g,"%2F"),Pn=r=>r.replace(/%2F/g,"/").replace(/%25/g,"%"),vt=Symbol("ownsRegistry"),P={stage:r=>`patter/scene/${le(r)}`,flow:r=>`patter/flow/${le(r)}/`,flowGlobals:r=>`patter/flow/${le(r)}/patter`,flowScene:(r,e)=>`patter/flow/${le(r)}/scene/${le(e)}`},ue=class{constructor(e){this.journal=e}journal},xe=class r{host;defaultSeed;flowsById=new Map;allStrings;currentLocale;sourceDebug;sceneGameIdToId=new Map;blockGameIdToId=new Map;creationOptions;engineLog=[];engineSeq=0;engineTraceHandlers=new Set;constructor(e,t={}){this.creationOptions=t;let n=t.locale??e.locales.default,s=e.strings;this.allStrings=s,this.currentLocale=n;let i=s[n]??{},o=s[e.locales.default]??{},a=e.localisation,l=a?.mode==="ids"&&!a.sourceDebug;this.sourceDebug=a?.mode==="ids"&&!!a.sourceDebug,this.sourceDebug&&typeof console<"u"&&console.warn("[Patterplay] source-only DEBUG build: strings are the source language for debugging, not a shippable localised build.");let c=new Map;for(let m of e.cast??[])m.displayName&&c.set(m.name,m.displayName);let p=new Map;for(let m of e.qualifiers??[])m?.gameId&&p.set(m.gameId,m.name);let d=new Map;for(let m of e.cast??[])for(let[S,I]of Object.entries(m.qualifierLabels??{}))typeof I=="string"&&d.set(`${m.name}\0${S}`,I);let f=e.speakerPattern??dt;this.defaultSeed=(t.seed??2654435769)>>>0;let g=new Map,y=new Map,u=new Map;for(let[m,S]of Object.entries(e.scenes)){this.sceneGameIdToId.set(D(S),m);let I=new Map;for(let C of S.blocks)y.set(C.id,{sceneId:m}),u.set(C.id,C),I.set(D(C),C.id),G(C.children,fe=>g.set(fe.id,fe));this.blockGameIdToId.set(m,I)}let x=e.properties??[],O=x.filter(m=>m.shared??!0).map(kt),R=x.filter(m=>!(m.shared??!0)).map(kt),A=new Set(O.map(m=>m.name.toLowerCase())),k=t.registry??new me,L=!t.registry||t[vt]===!0,F=new $(O,{pathPrefix:"@patter."}),T=[],h=[];try{k.mountOwned("patter",F,{owner:de}),h.push("patter");let m=new Set;for(let[S,I]of Object.entries(Et(t))){let C=e.scopeRegistry?.scopes.find(ln=>ln.token===S),fe=(C?.declarations??[]).map(Ot);k.defineForeign(S,I,fe,{writable:C?.writable??!0,owner:de}),h.push(S),m.add(S)}for(let S of L?e.scopeRegistry?.scopes??[]:[]){if(m.has(S.token)||k.has(S.token))continue;let I=(S.declarations??[]).map(C=>Ln(C,S.writable));k.defineOwned(S.token,I,{owner:de}),h.push(S.token),T.push(S.token)}}catch(m){for(let S of h)k.remove(S,{keep:!0});throw m}let E=new Map;for(let[m,S]of Object.entries(e.scenes)){let I=new Set((S.sceneProps??[]).filter(C=>C.shared??!1).map(C=>C.name.toLowerCase()));E.set(m,I)}this.host={logEnabled:t.log??!1,tracing:t.log??!1,emitEngine:(m,S,I)=>this.emitEngine(m,S,I),bundle:e,emitIds:l,strings:i,defaultStrings:o,castDisplay:c,qualifierDisplay:p,speakerLabels:d,speakerPattern:f,nodeIndex:g,blockIndex:y,blockById:u,sceneGameIdToId:this.sceneGameIdToId,blockGameIdToId:this.blockGameIdToId,tagIndex:Rn(e),padIndex:On(e),registry:k,ownsRegistry:L,patterBag:F,hostScopes:T,patterSharedDecls:O,patterLocalDecls:R,patterSharedNames:A,sceneSharedNames:E,sharedVisits:new Map,qualityLadders:new Map,sharedSelectors:new Map,stageBags:new Map,journal:null,customRng:t.rng,onDryChoice:t.onDryChoice,onError:t.onError??(m=>console.warn(`Patterplay: ${m.kind} on ${m.node} in flow '${m.flow}' failed, played through: ${m.message}`)),reportRefits:()=>{let m=k.takeMisfits(S=>S==="patter"||S.startsWith("patter/")||T.includes(S));if(m.length!==0)if(t.onRefit)t.onRefit(m);else for(let S of m)console.warn(`Patterplay: the save's ${S.scope}.${S.name} was ${JSON.stringify(S.value)}, which no longer fits its declaration; it is back at its default`)},replayPromptOnChoose:t.replayPromptOnChoose??!1,captionsOn:t.closedCaptions??!0,captionOpen:(e.closedCaptions??Fe).open,captionClose:(e.closedCaptions??Fe).close,captionCharacter:e.closedCaptions?.character||ut,refSplitCache:new Map,refSplitRevision:k.revision},this.host.reportRefits()}get locale(){return this.currentLocale}get isSourceDebug(){return this.sourceDebug}get buildId(){return this.host.bundle.content?.hash??""}setLocale(e){this.currentLocale=e,this.host.strings=this.allStrings[e]??{}}replaceStrings(e){this.allStrings=e.strings,this.host.strings=this.allStrings[this.currentLocale]??{},this.host.defaultStrings=this.allStrings[this.host.bundle.locales.default]??{}}hotSwap(e){this.refuseInCheckpoint("hotSwap");let t=this.saveGame(),n=l=>(l.setLocale(this.currentLocale),l.setClosedCaptions(this.host.captionsOn),l),s=()=>new r(e,{...this.creationOptions,registry:this.host.registry,[vt]:this.host.ownsRegistry}),i=new Set(["patter",...this.host.hostScopes]),o=this.host.ownsRegistry?void 0:Object.fromEntries(Object.entries(this.host.registry.save()).filter(([l])=>i.has(l)||l.startsWith("patter/")));this.release(!0),o&&this.host.registry.load(o,{keepParked:!0,refit:!0});let a=s();try{return a.loadGame(t),n(a)}catch{a.release(!0);let l=this.host.ownsRegistry?t.registry:o;l&&this.host.registry.load(l,{keepParked:!0,refit:!0});let c=s();for(let[p,d]of Object.entries(t.flows)){let f=d.cursor.currentSceneId;try{c.openFlow(p,f!==null?{scene:f}:{})}catch{}}return n(c)}}get closedCaptions(){return this.host.captionsOn}setClosedCaptions(e){this.host.captionsOn=e}openFlow(e,t={}){this.assertExternalScopes();let{sceneId:n,blockId:s}=this.resolveOpenAddress(t.scene,t.block),i=this.flowsById.get(e),o=this.host.journal;if(o&&i&&!i.isClosed)throw new Error(`openFlow would replace the open flow '${e}', which can't be undone while a checkpoint is open`);i?.close();let a=new _(e,this.host,t.seed??this.defaultSeed);return o&&(o.flows.add(a),o.opened.add(a),o.undo.push(()=>{a.close(),i?this.flowsById.set(e,i):this.flowsById.delete(e)})),this.flowsById.set(e,a),a.begin(n,s),a}runFlow(e,t,n){let s=this.flowsById.get(e);if(!s)return this.openFlow(e,{scene:t,block:n}).advanceToStop().played;if(!s.goto(t,n))throw new Error(`runFlow: address not found: ${t}${n===void 0?"":` / ${n}`}`);return s.advanceToStop().played}assertExternalScopes(){for(let e of this.host.bundle.externalScopes??[])if(!this.host.registry.has(e))throw new Error(`this content names @${e}, which no engine on this registry registered: give every engine the game's one registry`)}resolveOpenAddress(e,t){if(e!==void 0){let n=Te(this.host,e);if(n===void 0)throw new Error(`unknown scene: ${e}`);if(t===void 0)return{sceneId:n};let s=$e(this.host,n,t);if(s===void 0)throw new Error(`unknown block: ${t}`);return{sceneId:n,blockId:s}}if(t!==void 0){if(!this.host.blockIndex.has(t))throw new Error(`unknown block: ${t}`);return{blockId:t}}if(Object.keys(this.host.bundle.scenes).length===0)throw new Error("no scenes in bundle");return{}}resolveSceneRef(e){if(e!=null)return Te(this.host,e)??e}resolveBlockRef(e,t){if(t!=null)return e==null?t:$e(this.host,e,t)}sceneAddress(e){let t=this.host.bundle.scenes[e];return t?D(t):void 0}blockAddress(e){let t=this.host.blockById.get(e);return t?D(t):void 0}tagsForBeat(e){return H(this.host,e)??[]}tagsForScene(e){let t=this.resolveSceneRef(e);return(t!=null?H(this.host,t):void 0)??[]}tagsForBlock(e,t){let n=this.resolveSceneRef(e),s=this.resolveBlockRef(n,t);return(s!=null?H(this.host,s):void 0)??[]}gameDataForScene(e){let t=this.resolveSceneRef(e);return{...(t!=null?this.host.bundle.scenes[t]:void 0)?.gameData}}gameDataForBlock(e,t){let n=this.resolveBlockRef(this.resolveSceneRef(e),t);return{...(n!=null?this.host.blockById.get(n):void 0)?.gameData}}extensionsForScene(e){let t=this.resolveSceneRef(e);return{...(t!=null?this.host.bundle.scenes[t]:void 0)?.extensions}}extensionsForBlock(e,t){let n=this.resolveBlockRef(this.resolveSceneRef(e),t);return{...(n!=null?this.host.blockById.get(n):void 0)?.extensions}}getCast(){let e=[];for(let t of this.host.bundle.cast??[])t?.name&&e.push(t.name);return e}castForScene(e){let t=this.resolveSceneRef(e),n=t!=null?this.host.bundle.scenes[t]:void 0;if(!n)return[];let s=new Set;for(let i of n.blocks)St(i.children,s);return[...s]}castForBlock(e,t){let n=this.resolveSceneRef(e),s=this.resolveBlockRef(n,t),i=s!=null?this.host.blockById.get(s):void 0;if(!i)return[];let o=new Set;return St(i.children,o),[...o]}getOutline(){return Object.values(this.host.bundle.scenes).map(e=>({id:e.id,...D(e)?{gameId:D(e)}:{},name:e.name,...wt(e.gameData),...M(e.extensions),...this.tagsField(e.id),blocks:e.blocks.map(t=>({id:t.id,...D(t)?{gameId:D(t)}:{},name:t.name,...wt(t.gameData),...M(t.extensions),...this.tagsField(t.id),children:t.children.map(n=>this.outlineNode(n))}))}))}getBeatSequence(){let e=[];for(let t of Object.values(this.host.bundle.scenes))for(let n of t.blocks)G(n.children,s=>{if(s.type==="snippet")for(let i of s.beats??[])e.push({sceneId:t.id,blockId:n.id,snippetId:s.id,beat:this.beatInfo(i)})});return e}outlineNode(e){return e.type==="group"?{type:"group",id:e.id,...this.tagsField(e.id),...e.selector?{selector:e.selector}:{},...e.prompt?{prompt:this.beatInfo(e.prompt)}:{},children:e.children.map(t=>this.outlineNode(t))}:{type:"snippet",id:e.id,...this.tagsField(e.id),beats:(e.beats??[]).map(t=>this.beatInfo(t)),...e.jump?{jumpTo:e.jump.to,...e.jump.mode?{jumpMode:e.jump.mode}:{}}:{}}}beatInfo(e){let t=H(this.host,e.id),n={id:e.id,kind:e.kind};if(e.kind==="line"){if(e.character!==void 0){n.character=e.character;let i=this.host.defaultStrings[ve(e.character)]??this.host.castDisplay.get(e.character);i!==void 0&&(n.characterName=i)}if(e.direction!==void 0&&(n.direction=e.direction),e.qualifier!==void 0){n.qualifier=e.qualifier;let i=this.host.defaultStrings[Se(e.qualifier)]??this.host.qualifierDisplay.get(e.qualifier);i!==void 0&&(n.qualifierName=i)}let s=ce(this.host,e.character,e.qualifier,!0);s!==void 0&&(n.speakerLabel=s)}if(e.kind==="line"||e.kind==="text"){let s=this.host.padIndex.get(e.id);n.padAfter=s?.resolved??j,s?.own!==void 0&&(n.ownPadAfter=s.own);let i=this.host.defaultStrings[e.id];i!==void 0&&(n.text=i)}return e.gameData&&Object.keys(e.gameData).length&&(n.gameData=e.gameData),e.extensions&&Object.keys(e.extensions).length&&(n.extensions=e.extensions),t&&t.length&&(n.tags=t),n}tagsField(e){let t=H(this.host,e);return t&&t.length?{tags:t}:{}}getFlow(e){return this.flowsById.get(e)}flows(){return[...this.flowsById.values()]}listBags(){let e=[{bag:this.host.patterBag}];for(let[t,n]of this.host.stageBags)e.push({bag:n,pathPrefix:`@scene:${t}.`});return e}checkpoint(){if(this.host.journal)throw new Error("a checkpoint is already open: roll it back or commit it first");let e={undo:[],flows:new Set,opened:new Set,selectors:new Set,flowSelectors:new Map};return this.host.journal=e,new ue(e)}rollback(e){this.endCheckpoint(e);let t=e.journal.undo;for(let n=t.length-1;n>=0;n--)t[n]();r.forget(e.journal)}commit(e){this.endCheckpoint(e),r.forget(e.journal)}get inCheckpoint(){return this.host.journal!==null}endCheckpoint(e){if(this.host.journal!==e.journal)throw new Error("that checkpoint is not the open one");this.host.journal=null}static forget(e){e.undo=[],e.flows.clear(),e.opened.clear(),e.selectors.clear(),e.flowSelectors.clear()}refuseInCheckpoint(e){if(this.host.journal)throw new Error(`${e} can't be undone, so it isn't allowed while a checkpoint is open`)}captureFlow(e){let t=this.flowsById.get(e);if(!t)throw new Error(`no open flow '${e}' to capture`);return{version:ie,...t.snapshot(),...Mn(e,this.host.registry.save())}}restoreFlow(e,t){this.refuseInCheckpoint("restoreFlow");let n=t.version;if(n!==2&&n!==ie)throw new Error(`unsupported flow state version: ${String(n)}`);let s=t.cursor;if(typeof s!="object"||s===null)throw new Error("malformed flow state: no cursor");if(this.flowsById.has(e))throw new Error(`a flow '${e}' is already open; close it before restoring another under that id`);this.assertExternalScopes();let i=P.flow(e);this.host.registry.discardParked(i),this.host.registry.load(Pt(e,t),{keepParked:!0,refit:!0});let o=new _(e,this.host,this.defaultSeed);try{o.restore(t)}catch(a){throw o.close(),this.host.registry.discardParked(i),a}return this.flowsById.set(e,o),this.host.reportRefits(),o}closeFlow(e){this.refuseInCheckpoint("closeFlow"),this.flowsById.get(e)?.close(),this.flowsById.delete(e)}reset(){this.refuseInCheckpoint("reset");for(let e of this.flowsById.values())e.close();this.flowsById.clear(),this.host.patterBag.reseed(this.host.patterSharedDecls),this.host.sharedVisits.clear(),this.host.sharedSelectors.clear();for(let e of this.host.stageBags.keys())this.host.registry.remove(P.stage(e));this.host.stageBags.clear(),this.host.registry.discardParked("patter/")}release(e){for(let n of this.flowsById.values())n.releaseBags(e),n.close();this.flowsById.clear();let t=this.host.registry;for(let n of this.host.stageBags.keys())t.remove(P.stage(n),{keep:e});this.host.stageBags.clear();for(let n of["patter",...this.host.hostScopes])t.has(n)&&t.remove(n,{keep:e});for(let n of Object.keys(Et(this.creationOptions)))t.has(n)&&t.remove(n)}getProperty(e){let{scope:t,name:n}=this.splitShared(e);return this.host.registry.get(t,n)}setProperty(e,t){let{scope:n,name:s}=this.splitShared(e),i=this.host.journal?this.host.registry.get(n,s):void 0;this.host.registry.set(n,s,t,{host:!0}),this.host.journal&&i!==void 0&&this.host.journal.undo.push(()=>this.host.registry.set(n,s,i,{host:!0}))}stageIndex(e,t){return U(this.ladderOf(e),t)}compareStages(e,t,n){return W(this.ladderOf(e),t,n)}nextStage(e,t){return J(this.ladderOf(e),t)}ladderOf(e){let{scope:t,name:n}=this.splitShared(e),s=An(this.host,t,n);if(!s)throw new Error(`'${e}' is not a quality`);return s}log(){return this.engineLog}clearLog(){this.engineLog.length=0}onTrace(e){return this.engineTraceHandlers.add(e),this.host.tracing=!0,()=>{this.engineTraceHandlers.delete(e),this.host.tracing=this.host.logEnabled||this.engineTraceHandlers.size>0}}emitEngine(e,t,n){for(let s of this.engineTraceHandlers)s(e,t);this.host.logEnabled&&this.engineLog.push({...t,flow:e,seq:this.engineSeq++,...n?{scene:n}:{}})}getVisitCounts(){return Object.fromEntries(this.host.sharedVisits)}listProperties(){return this.host.patterSharedDecls.map(e=>({name:e.name,path:`@patter.${e.name}`,type:e.type,values:e.values,stages:e.stages,value:this.getProperty(`@${e.name}`),default:K(e),writable:e.writable??!0}))}splitShared(e){let t=It(this.host,e);if(t.scope==="scene")throw new Error(`'${e}': @scene properties are scene-scoped - read/write them on a Flow, not the Engine`);return t}save(){return{patter:this.host.patterBag.save()}}load(e){e.patter&&this.host.patterBag.load(e.patter)}saveGame(){let e={};for(let[t,n]of this.flowsById)e[t]=n.snapshot();return{version:ie,...this.host.ownsRegistry?{registry:this.host.registry.save()}:{},sharedVisits:Object.fromEntries(this.host.sharedVisits),sharedSelectors:Dt(this.host.sharedSelectors),flows:e}}loadGame(e){this.refuseInCheckpoint("loadGame");let t=e.version;if(t!==2&&t!==ie)throw new Error(`unsupported save version: ${String(t)}`);let n=e.flows;if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("malformed save: no flows");this.assertExternalScopes();let s=this.host.registry;for(let[o,a]of this.flowsById)a.releaseBags(o in e.flows),a.close();this.flowsById.clear();for(let o of this.host.stageBags.keys())s.remove(P.stage(o),{keep:!0});this.host.stageBags.clear();let i=e.version===2?Bn(e):e.registry;i&&(this.host.ownsRegistry?s.load(i,{refit:!0}):s.load(i,{keepParked:!0,refit:!0})),this.host.sharedVisits.clear();for(let[o,a]of Object.entries(e.sharedVisits??{}))this.host.sharedVisits.set(o,a);this.host.sharedSelectors.clear();for(let[o,a]of Rt(e.sharedSelectors))this.host.sharedSelectors.set(o,a);for(let[o,a]of Object.entries(e.flows)){let l=new _(o,this.host,this.defaultSeed);l.restore(a),this.flowsById.set(o,l)}this.host.reportRefits()}},_=class{id;host;local;registered=new Set;rngState;started=!1;flowEnded=!1;closed=!1;currentSceneId=null;stack=[];activeSnippet=null;beatIndex=0;pendingChoice=null;pendingPrompt=null;pendingPromptOwnerId=null;selectors=new Map;visitCounts=new Map;sceneBags=new Map;patterResolver={get:e=>this.host.patterSharedNames.has(e)?this.host.patterBag.get(e):this.local.get(e),set:(e,t)=>{this.host.patterSharedNames.has(e)?this.host.registry.set("patter",e,t):this.local.set(e,t)}};sceneResolver={get:e=>{let t=this.currentSceneId;if(t!==null)return this.sceneBagFor(t,e)?.get(e)},set:(e,t)=>{let n=this.currentSceneId;if(n===null)return;let s=this.sceneBagFor(n,e);s&&s.set(e,t)}};evalCtx;ctxRevision=-1;registryQualities;flowLog=[];flowSeq=0;constructor(e,t,n){this.id=e,this.host=t,this.rngState=ne(n),this.local=this.newLocal(),this.evalCtx={scopes:{},host:{nextRandom:this.rng,visits:s=>this.visitCounts.get(s)??0,patterVisits:s=>this.host.sharedVisits.get(s)??0},qualities:(s,i)=>this.stagesFor(s,i)}}context(){let e=this.host.registry;if(e.revision!==this.ctxRevision){let t=e.toEvalContext(),n=this.evalCtx.scopes;for(let s of Object.keys(n))delete n[s];Object.assign(n,t.scopes),n.patter=this.patterResolver,n.scene=this.sceneResolver,this.registryQualities=t.qualities,this.ctxRevision=e.revision}return this.evalCtx}stagesFor(e,t){let n=t.toLowerCase();if(e==="patter")return pe(this.host,"patter",()=>[...this.host.patterSharedDecls,...this.host.patterLocalDecls]).get(n);if(e==="scene"){let s=this.currentSceneId;return s==null?void 0:pe(this.host,`scene/${s}`,()=>this.host.bundle.scenes[s]?.sceneProps).get(n)}return this.registryQualities?.(e,t)??pe(this.host,`host/${e}`,()=>this.host.bundle.scopeRegistry?.scopes.find(s=>s.token===e)?.declarations).get(n)}begin(e,t){if(this.host.journal&&!this.host.journal.opened.has(this))throw new Error("a flow can't be started or reset while a checkpoint is open");if(this.releaseBags(!1),this.host.registry.discardParked(P.flow(this.id)),this.mountLocal(),this.selectors.clear(),this.visitCounts.clear(),this.stack=[],this.currentSceneId=null,this.flowEnded=!1,this.activeSnippet=null,this.beatIndex=0,this.clearPending(),this.started=!0,t){let n=this.host.blockIndex.get(t);if(!n)throw new Error(`unknown block: ${t}`);this.enterSceneSetup(n.sceneId),this.stack=[{sceneId:n.sceneId,containerId:t,index:0}],this.enter(t)}else{let n=e??Object.keys(this.host.bundle.scenes)[0],s=n?this.host.bundle.scenes[n]:void 0;if(!s)throw new Error(n?`unknown scene: ${n}`:"no scenes in bundle");this.enterSceneSetup(n);let i=s.blocks[0];i&&(this.stack=[{sceneId:n,containerId:i.id,index:0}],this.enter(i.id))}this.settle()}reset(e,t){this.begin(e,t)}start(e,t){this.reset(e,t)}goto(e,t){if(this.closed)return!1;if(this.touch(),e==="END")return this.started=!0,this.clearPending(),this.activeSnippet=null,this.beatIndex=0,this.flowEnded=!0,this.stack=[],!0;let n=Te(this.host,e);if(n===void 0)return!1;let s;return t!==void 0&&(s=$e(this.host,n,t),s===void 0)?!1:this.started?(this.clearPending(),this.activeSnippet=null,this.beatIndex=0,this.flowEnded=!1,this.enterTarget(s??n,"jump"),this.settle(),!0):(this.begin(n,s),!0)}close(){this.releaseBags(!1),this.closed=!0,this.flowEnded=!0,this.stack=[],this.activeSnippet=null,this.beatIndex=0,this.clearPending()}clearPending(){this.pendingChoice=null,this.pendingPrompt=null,this.pendingPromptOwnerId=null}touch(){let e=this.host.journal;if(!e||e.flows.has(this))return;e.flows.add(this);let{rngState:t,started:n,flowEnded:s,currentSceneId:i,activeSnippet:o,beatIndex:a,pendingChoice:l,pendingPrompt:c,pendingPromptOwnerId:p}=this,d=this.stack.map(f=>({...f}));e.undo.push(()=>{Object.assign(this,{rngState:t,started:n,flowEnded:s,currentSceneId:i,activeSnippet:o,beatIndex:a,pendingChoice:l,pendingPrompt:c,pendingPromptOwnerId:p,stack:d})})}get isClosed(){return this.closed}get currentScene(){return this.currentSceneId}advance(){if(this.closed)return{type:"end"};if(!this.started)throw new Error("flow has not been started");if(this.touch(),this.pendingPrompt){let e=this.pendingPrompt;return this.pendingPrompt=null,this.pendingPromptOwnerId=null,e.shown?this.promptResult(e.beat,e.shown):this.beatResult(e.beat)}return this.settle(),this.flowEnded?{type:"end"}:this.pendingChoice?{type:"choice",groupId:this.pendingChoice.groupId,options:this.pendingChoice.options}:this.activeSnippet?this.beatResult(this.activeSnippet.beats[this.beatIndex++]):(this.flowEnded=!0,{type:"end"})}advanceToStop(){let e=[];for(;;){let t=this.advance();if(t.type==="choice"||t.type==="end")return{played:e,stop:t};e.push(t)}}settle(){let e=0;for(;;){if(++e>1e4)throw new Error("flow did not settle after 10000 transitions - likely a jump cycle with no deliverable content");if(this.flowEnded||this.pendingChoice)return;if(this.activeSnippet){if(this.beatIndex<(this.activeSnippet.beats?.length??0))return;this.runEffects(this.activeSnippet.onExit,this.activeSnippet.id);let i=this.activeSnippet.jump;this.activeSnippet=null,this.beatIndex=0,this.resolveJump(i);continue}let t=this.stack[this.stack.length-1];if(!t){this.flowEnded=!0;return}t.sceneId!==this.currentSceneId&&(this.currentSceneId=t.sceneId);let n=this.childrenOf(t.containerId);if(!n){this.stack.pop();continue}let s=t.index;for(;t.index<n.length&&!this.eligible(n[t.index]);)t.index++;if(this.host.tracing&&t.index!==s&&this.emit({type:"select",group:t.containerId,selector:"run",children:n.slice(s,t.index+1).map((i,o)=>({id:i.id,eligible:s+o===t.index})),picked:n[t.index]?.id??null}),t.index>=n.length){this.stack.pop();continue}this.enterChild(n[t.index++])}}listBags(){let e=[{bag:this.local,pathPrefix:`${this.id}/@patter.`}];for(let[t,n]of this.sceneBags)e.push({bag:n,pathPrefix:`${this.id}/@scene:${t}.`});return e}log(){return this.flowLog}clearLog(){this.flowLog.length=0}emit(e){let t=this.currentSceneId??void 0;this.host.emitEngine(this.id,e,t),this.host.logEnabled&&this.flowLog.push({...e,seq:this.flowSeq++,...t?{scene:t}:{}})}getVisitCounts(){return Object.fromEntries(this.visitCounts)}stepFor(e){let t=In(this.host.bundle).get(e);return t?this.beatResult(t):void 0}getChoices(){return this.pendingChoice?.options??[]}choose(e){let t=this.pendingChoice;if(!t)throw new Error("no choice is pending");let n=t.options.find(o=>o.id===e);if(!n)throw new Error(`unknown choice option: ${e}`);if(!n.eligible)throw new Error(`choice option is not eligible: ${e}`);this.touch();let s=t.byId.get(e);this.host.tracing&&this.emit({type:"chose",group:t.groupId,option:e}),this.pendingChoice=null;let i=this.host.replayPromptOnChoose?this.authoredPromptOf(s):void 0;this.pendingPrompt=i&&n.prompt?{beat:i,shown:{...n.prompt}}:null,this.pendingPromptOwnerId=this.pendingPrompt?s.id:null,this.enterChild(s)}isEnded(){return this.flowEnded}getProperty(e){let{scope:t,name:n}=this.splitRef(e);return t==="patter"?this.patterResolver.get(n):t==="scene"?this.sceneResolver.get(n):this.host.registry.get(t,n)}setProperty(e,t){this.writeProperty(e,t,!0)}stageIndex(e,t){return U(this.ladderOf(e),t)}compareStages(e,t,n){return W(this.ladderOf(e),t,n)}nextStage(e,t){return J(this.ladderOf(e),t)}ladderOf(e){let{scope:t,name:n}=this.splitRef(e);this.context();let s=this.stagesFor(t,n);if(!s)throw new Error(`'${e}' is not a quality`);return s}writeProperty(e,t,n){let{scope:s,name:i}=this.splitRef(e),o=this.host.journal;if(s==="patter"){if(o){let a=this.host.patterSharedNames.has(i),l=a?this.host.patterBag.get(i):this.local.get(i),c=this.local;l!==void 0&&o.undo.push(a?()=>this.host.registry.set("patter",i,l):()=>c.set(i,l))}this.patterResolver.set(i,t)}else if(s==="scene"){if(this.currentSceneId===null)throw new Error(`'${e}': the flow has not entered a scene yet`);if(o){let a=this.sceneBagFor(this.currentSceneId,i),l=a?.get(i);a&&l!==void 0&&o.undo.push(()=>a.set(i,l))}this.sceneResolver.set(i,t)}else{let a=o?this.host.registry.get(s,i):void 0;this.host.registry.set(s,i,t,n?{host:!0}:void 0),o&&a!==void 0&&o.undo.push(()=>this.host.registry.set(s,i,a,{host:!0}))}}snapshot(){return{rngState:this.rngState,visits:Object.fromEntries(this.visitCounts),cursor:{flowEnded:this.flowEnded,currentSceneId:this.currentSceneId,stack:this.stack.map(e=>{let t=this.childrenOf(e.containerId)?.[e.index];return t?{...e,nextId:t.id}:{...e}}),activeSnippetId:this.activeSnippet?.id??null,beatIndex:this.beatIndex,pendingChoice:this.pendingChoice?{groupId:this.pendingChoice.groupId,options:this.pendingChoice.options.map(({extensions:e,...t})=>({...t}))}:null,pendingPromptOwnerId:this.pendingPromptOwnerId,...this.pendingPrompt?.shown?{pendingPrompt:Nn(this.pendingPrompt.shown)}:{},selectors:Dt(this.selectors)}}}restore(e){if(this.host.journal)throw new Error("a flow can't be restored while a checkpoint is open");this.restoreCursor(e),this.releaseBags(!0),this.mountLocal();for(let t of new Set([this.currentSceneId,...this.stack.map(n=>n.sceneId)]))t!==null&&this.host.bundle.scenes[t]&&this.ensureSceneBags(t)}restoreCursor(e){this.rngState=ne(e.rngState),this.visitCounts=new Map(Object.entries(e.visits??{}));let t=e.cursor;if(this.started=!0,this.flowEnded=t.flowEnded,this.beatIndex=t.beatIndex,this.currentSceneId=t.currentSceneId,this.stack=t.stack.map(n=>{let{nextId:s,...i}=n;if(s!==void 0){let o=this.childrenOf(i.containerId)?.findIndex(a=>a.id===s)??-1;if(o>=0)return{...i,index:o}}return{...i}}),this.activeSnippet=null,t.activeSnippetId!==null){let n=this.host.nodeIndex.get(t.activeSnippetId);n&&n.type==="snippet"&&(this.activeSnippet=n)}if(this.selectors=Rt(t.selectors),this.pendingChoice=null,t.pendingChoice!==null){let n=new Map,s=[];for(let i of t.pendingChoice.options){let o=this.host.nodeIndex.get(i.id);if(!o)continue;n.set(i.id,o);let{prompt:a,extensions:l,...c}=i,p=a?.kind==="line"&&a.speakerLabel===void 0?ce(this.host,a.character,a.qualifier):void 0;s.push({...c,...a?{prompt:{...a,padAfter:a.padAfter??this.promptPadOf(o),...p!==void 0?{speakerLabel:p}:{}}}:{},...M(o.extensions)})}s.length>0&&(this.pendingChoice={groupId:t.pendingChoice.groupId,options:s,byId:n})}if(this.pendingPrompt=null,this.pendingPromptOwnerId=t.pendingPromptOwnerId??null,this.pendingPromptOwnerId){let n=this.host.nodeIndex.get(this.pendingPromptOwnerId),s=n?this.authoredPromptOf(n):void 0,i=t.pendingPrompt,o=i?.kind==="line"&&i.speakerLabel===void 0?ce(this.host,i.character,i.qualifier):void 0;s?this.pendingPrompt={beat:s,...i?{shown:{...i,padAfter:i.padAfter??this.padOf(s.id),...o!==void 0?{speakerLabel:o}:{}}}:{}}:this.pendingPromptOwnerId=null}}enterSceneSetup(e){let t=this.host.bundle.scenes[e];if(!t)throw new Error(`unknown scene: ${e}`);this.currentSceneId=e,this.enter(e),this.seedScene(t),this.runEffects(t.onEntry,t.id)}enterChild(e){if(this.enter(e.id),e.type==="snippet"){this.beginSnippet(e);return}let t=e.selector??"run";if(t==="run"){this.stack.push({sceneId:this.currentSceneId,containerId:e.id,index:0});return}if(t==="choice"){this.setupChoice(e);return}let n=this.selectChild(e);n&&this.enterChild(n)}childrenOf(e){let t=this.host.blockById.get(e);if(t)return t.children;let n=this.host.nodeIndex.get(e);if(n&&n.type==="group")return n.children}beginSnippet(e){this.runEffects(e.onEnter,e.id),this.activeSnippet=e,this.beatIndex=0}setupChoice(e){let t=[],n=new Map,s=[];for(let o of e.children){if(o.fallback===!0){s.push(o);continue}if(o.sticky!==!0&&(this.visitCounts.get(o.id)??0)>=1)continue;let a=this.eligible(o),l=o.secretUntilEligible===!0;!a&&l||(t.push({id:o.id,prompt:this.promptFor(o),eligible:a,gameData:o.gameData,...M(o.extensions)}),n.set(o.id,o))}if(t.some(o=>o.eligible)){this.host.tracing&&this.emit({type:"choice",group:e.id,options:t.map(o=>({id:o.id,eligible:o.eligible}))}),this.pendingChoice={groupId:e.id,options:t,byId:n};return}let i=s.find(o=>this.eligible(o));if(i){this.enterChild(i);return}this.host.tracing&&this.emit({type:"dry",group:e.id}),this.host.onDryChoice?.(e.id)}resolveJump(e){e&&this.enterTarget(e.to,e.mode==="call"?"call":"jump")}enterTarget(e,t){if(this.host.tracing&&this.emit({type:"jump",to:e,mode:t}),e==="END"){this.flowEnded=!0,this.stack=[];return}let n,s,i=this.host.bundle.scenes[e];if(i){this.enterSceneSetup(e);let a=i.blocks[0];if(!a){t==="jump"&&(this.stack=[]);return}n=e,s=a.id}else{let a=this.host.blockIndex.get(e);if(!a)throw new Error(`jump target not found: ${e}`);a.sceneId!==this.currentSceneId&&this.enterSceneSetup(a.sceneId),n=a.sceneId,s=e}this.enter(s);let o={sceneId:n,containerId:s,index:0};t==="call"?this.stack.push(o):this.stack=[o]}selectChild(e){let t=e.children.map(l=>({id:l.id,eligible:this.eligible(l)})),n=e.children.filter((l,c)=>t[c].eligible),s=e.options?.order??"sequential",i=e.options?.exhaust??"once",o=l=>(this.host.tracing&&this.emit({type:"select",group:e.id,selector:e.selector??"default",...e.selector==="sequence"?{order:s,exhaust:i}:{},children:t,picked:l?.id??null}),l);if(n.length===0)return o(null);let a=this.selectorState(e);switch(e.selector){case"branch":return o(n[0]);case"sequence":return o(s==="shuffle"?this.pickShuffle(n,i,a):s==="specificity"?this.pickSpecificity(n,i,a):this.pickSequential(n,i,a));default:return null}}pickSequential(e,t,n){let s=e.length,i=n.seq??0;return n.seq=i+1,t==="repeat"?e[i%s]:i<s?e[i]:t==="stick"?e[s-1]:null}pickShuffle(e,t,n){let s=e.length,i=t==="stick",o=()=>(i?e.slice(0,s-1):e).map(f=>f.id),a=new Set(e.map(f=>f.id));if(n.bag===void 0&&(n.bag=o()),!n.bag.some(f=>a.has(f))){if(t==="once")return null;if(i){let f=e[s-1];return n.last=f.id,f}if(n.bag=o(),n.bag.length===0)return null}let l=n.bag.filter(f=>a.has(f)),c=n.last!==void 0&&l.length>1?l.indexOf(n.last):-1,p=Math.floor(this.rng()*(c>=0?l.length-1:l.length));c>=0&&p>=c&&p++;let d=l[p];return n.bag.splice(n.bag.indexOf(d),1),n.last=d,e.find(f=>f.id===d)}pickSpecificity(e,t,n){let s=e;if(t!=="repeat"){n.bag===void 0&&(n.bag=e.map(p=>p.id));let c=new Set(n.bag);if(s=e.filter(p=>c.has(p.id)),s.length===0)return t==="stick"&&n.last!==void 0?e.find(p=>p.id===n.last)??null:null}let i=-1,a=s.map(c=>{let p=this.specScore(c);return p>i&&(i=p),{c,s:p}}).filter(c=>c.s===i).map(c=>c.c),l;if(a.length===1)l=a[0];else{let c=n.last!==void 0?a.findIndex(d=>d.id===n.last):-1,p=Math.floor(this.rng()*(c>=0?a.length-1:a.length));c>=0&&p>=c&&p++,l=a[p]}return t!=="repeat"&&(n.bag=n.bag.filter(c=>c!==l.id)),n.last=l.id,l}specScore(e){return e.condition?this.matchedSpec(this.conditionAst(e.condition),!0,e):0}matchedSpec(e,t,n){return Ye(e,i=>{try{return Ct(ge(i,this.context(),Me))}catch(o){return this.reportError("best-match",n.id,n.condition,o),!1}},{want:t})}selectorState(e){let t=e.shared?this.host.sharedSelectors:this.selectors,n=this.host.journal,s;if(n&&(s=e.shared?n.selectors:n.flowSelectors.get(this),s||(s=new Set,n.flowSelectors.set(this,s))),n&&s&&!s.has(e.id)){s.add(e.id);let o=t.get(e.id),a=o?{...o,...o.bag?{bag:[...o.bag]}:{}}:void 0;n.undo.push(()=>{a?t.set(e.id,a):t.delete(e.id)})}let i=t.get(e.id);return i||(i={},t.set(e.id,i)),i}runEffects(e,t){for(let n of e??[]){let s;try{s=this.evalExpr(n.value);let i=this.host.tracing?this.getProperty(n.target):void 0;this.writeProperty(n.target,s,!1),this.host.tracing&&this.emit({type:"write",target:n.target,value:s,...i!==void 0?{prev:i}:{}})}catch(i){this.reportError("effect",t,n.value,i)}}}eligible(e){if(!e.condition)return!0;try{return Ct(this.evalExpr(e.condition))}catch(t){return this.reportError("condition",e.id,e.condition,t),!1}}reportError(e,t,n,s){let i=s instanceof Error?s.message:String(s),o=n?.src;this.host.onError({flow:this.id,kind:e,node:t,...o?{source:o}:{},message:i}),this.host.tracing&&this.emit({type:"diagnostic",kind:e,node:t,...o?{source:o}:{},message:i})}evalExpr(e){return ge(this.conditionAst(e),this.context(),Me)}conditionAst(e){let t=ht.get(e);return t||(t=V(e.ast),ht.set(e,t)),t}enter(e){let t=this.visitCounts,n=t.get(e);t.set(e,(n??0)+1);let s=this.host.sharedVisits,i=s.get(e);s.set(e,(i??0)+1),this.host.journal&&this.host.journal.undo.push(()=>{n===void 0?t.delete(e):t.set(e,n),i===void 0?s.delete(e):s.set(e,i)})}rng=()=>{if(this.host.customRng)return this.host.customRng();let e=Ie(this.rngState),t=e.next();return this.rngState=e.state(),t};beatResult(e){let t=H(this.host,e.id),n=t&&t.length?{tags:t}:{};switch(e.kind){case"gameEvent":return{type:"gameEvent",id:e.id,gameData:e.gameData,...M(e.extensions),...n};case"text":return{type:"text",id:e.id,text:this.interpolate(this.resolveString(e.id)),padAfter:this.padOf(e.id),gameData:e.gameData,...M(e.extensions),...n};case"line":{let s=this.resolveString(e.id),i=!this.host.captionsOn,a=i&&e.character===this.host.captionCharacter?"":this.captionLine(this.host.bundle.voiced?s:this.interpolate(s)),l=i&&a.length===0;return{type:"line",id:e.id,text:a,character:l?void 0:e.character,characterName:l?void 0:this.resolveCharacterName(e.character),direction:l?void 0:e.direction,qualifier:l?void 0:e.qualifier,qualifierName:l?void 0:this.resolveQualifierName(e.qualifier),speakerLabel:l?void 0:ce(this.host,e.character,e.qualifier),padAfter:this.padOf(e.id),gameData:e.gameData,...M(e.extensions),...n}}}}interpolate(e){return at(e,t=>this.getProperty(t))}stripCaptions(e){return ot(e,this.host.captionOpen,this.host.captionClose)}captionLine(e){return this.host.captionsOn?e:this.stripCaptions(e)}promptFor(e){let t=this.promptBeatOf(e);if(!t)return;let n=this.interpolate(this.resolveString(t.id)),s=this.padOf(t.id);return t.kind==="line"?{kind:"line",text:this.captionLine(n),character:t.character,characterName:this.resolveCharacterName(t.character),direction:t.direction,qualifier:t.qualifier,qualifierName:this.resolveQualifierName(t.qualifier),speakerLabel:ce(this.host,t.character,t.qualifier),padAfter:s}:{kind:"text",text:n,padAfter:s}}authoredPromptOf(e){return e.type==="group"?e.prompt:void 0}promptResult(e,t){let n=H(this.host,e.id),s=n&&n.length?{tags:n}:{};return t.kind==="text"?{type:"text",id:e.id,text:t.text,padAfter:this.padOf(e.id),gameData:e.gameData,...M(e.extensions),...s}:{type:"line",id:e.id,text:t.text,character:t.character,characterName:t.characterName,direction:t.direction,qualifier:t.qualifier,qualifierName:t.qualifierName,speakerLabel:t.speakerLabel,padAfter:this.padOf(e.id),gameData:e.gameData,...M(e.extensions),...s}}promptBeatOf(e){return e.type==="group"&&e.prompt?e.prompt:((e.type==="snippet"?e:this.firstTextSnippetIn(e.children))?.beats??[]).find(n=>n.kind==="line"||n.kind==="text")}firstTextSnippetIn(e){let t;return G(e,n=>{!t&&n.type==="snippet"&&(n.beats??[]).some(s=>s.kind==="line"||s.kind==="text")&&(t=n)}),t}resolveString(e){if(this.host.emitIds)return e;let t=this.host.strings[e];if(t!==void 0)return t;let n=this.host.defaultStrings[e];return n!==void 0?`<Untranslated: ${e}> ${n}`:e}resolveCharacterName(e){if(e===void 0||this.host.emitIds)return;let t=ve(e);return this.host.strings[t]??this.host.defaultStrings[t]??this.host.castDisplay.get(e)}promptPadOf(e){let t=this.promptBeatOf(e);return t?this.padOf(t.id):j}padOf(e){return this.host.padIndex.get(e)?.resolved??j}resolveQualifierName(e){if(e===void 0||this.host.emitIds)return;let t=Se(e);return this.host.strings[t]??this.host.defaultStrings[t]??this.host.qualifierDisplay.get(e)}splitRef(e){return It(this.host,e)}newLocal(){return new $(this.host.patterLocalDecls,{pathPrefix:"@patter."})}mountLocal(){this.local=this.newLocal();let e=P.flowGlobals(this.id);this.host.registry.mountOwned(e,this.local,{owner:de}),this.registered.add(e),this.host.reportRefits()}releaseBags(e){for(let t of this.registered)this.host.registry.remove(t,{keep:e});this.registered.clear(),this.sceneBags.clear()}sceneBagFor(e,t){if(this.host.bundle.scenes[e])return this.ensureSceneBags(e),this.host.sceneSharedNames.get(e)?.has(t.toLowerCase())?this.host.stageBags.get(e):this.sceneBags.get(e)}ensureSceneBags(e){let t=this.host.sceneSharedNames.get(e)??new Set,n=this.host.bundle.scenes[e]?.sceneProps??[],s=this.host.journal,i=!this.sceneBags.has(e)||!this.host.stageBags.has(e);if(!this.sceneBags.has(e)){let o=new $(n.filter(c=>!t.has(c.name.toLowerCase())),{pathPrefix:"@scene."}),a=P.flowScene(this.id,e),l=xt(this.host.registry,a,o,s!==null);this.registered.add(a),this.sceneBags.set(e,o),s&&s.undo.push(()=>{this.sceneBags.get(e)===o&&(this.host.registry.remove(a,l?{keep:!0}:void 0),this.registered.delete(a),this.sceneBags.delete(e))})}if(!this.host.stageBags.has(e)){let o=new $(n.filter(l=>t.has(l.name.toLowerCase())),{pathPrefix:"@scene."}),a=xt(this.host.registry,P.stage(e),o,s!==null);this.host.stageBags.set(e,o),s&&s.undo.push(()=>{this.host.stageBags.get(e)===o&&(this.host.registry.remove(P.stage(e),a?{keep:!0}:void 0),this.host.stageBags.delete(e))})}i&&this.host.reportRefits()}seedScene(e){let t=this.host.sceneSharedNames.get(e.id)??new Set;this.ensureSceneBags(e.id);for(let n of e.sceneProps??[]){if(!n.temporary)continue;let s=n.name.toLowerCase(),i=t.has(s)?this.host.stageBags.get(e.id):this.sceneBags.get(e.id);if(!i)continue;let o=this.host.journal?i.get(s):void 0;o!==void 0&&this.host.journal.undo.push(()=>i.set(s,o)),i.set(s,K(n))}}};function St(r,e){G(r,t=>{if(t.type==="group"){t.prompt?.kind==="line"&&t.prompt.character&&e.add(t.prompt.character);return}for(let n of t.beats??[])n.kind==="line"&&n.character&&e.add(n.character)})}function ce(r,e,t,n=!1){if(!e||r.emitIds)return;let s=l=>(n?void 0:r.strings[l])??r.defaultStrings[l],i=s(ve(e))??r.castDisplay.get(e)??e;if(t===void 0)return i;let o=r.speakerLabels.get(`${e}\0${t}`);if(o!==void 0)return s(lt(e,t))??o;let a=s(Se(t))??r.qualifierDisplay.get(t)??t;return pt(s(ct)??r.speakerPattern,i,a)}function wt(r){return r&&Object.keys(r).length?{gameData:r}:{}}function M(r){return r&&Object.keys(r).length?{extensions:r}:{}}function Nn(r){let e={kind:r.kind,text:r.text};return r.character!==void 0&&(e.character=r.character),r.characterName!==void 0&&(e.characterName=r.characterName),r.direction!==void 0&&(e.direction=r.direction),r.qualifier!==void 0&&(e.qualifier=r.qualifier),r.qualifierName!==void 0&&(e.qualifierName=r.qualifierName),r.speakerLabel!==void 0&&(e.speakerLabel=r.speakerLabel),typeof r.padAfter=="number"&&(e.padAfter=r.padAfter),e}function Dt(r){let e={};for(let[t,n]of r){let s={};n.seq!==void 0&&(s.seq=n.seq),n.bag&&(s.bag=[...n.bag]),n.last!==void 0&&(s.last=n.last),e[t]=s}return e}function Rt(r){let e=new Map;for(let[t,n]of Object.entries(r??{})){let s={};n.seq!==void 0&&(s.seq=n.seq),n.bag&&(s.bag=[...n.bag]),n.last!==void 0&&(s.last=n.last),e.set(t,s)}return e}function xt(r,e,t,n){let s=n?JSON.stringify(t.save()):"";return r.mountOwned(e,t,{owner:de}),n&&JSON.stringify(t.save())!==s}function kt(r){return{name:r.name,type:r.type,values:r.values,stages:r.stages,default:r.default}}function Et(r){return{...r.world?{world:r.world}:{},...r.hostScopes}}function pe(r,e,t){let n=r.qualityLadders.get(e);if(!n){n=new Map;for(let s of t()??[]){let i=s.name.toLowerCase();s.type==="quality"&&s.stages&&!n.has(i)&&n.set(i,s.stages)}r.qualityLadders.set(e,n)}return n}function An(r,e,t){let n=t.toLowerCase();return e==="patter"?pe(r,"patter",()=>[...r.patterSharedDecls,...r.patterLocalDecls]).get(n):r.registry.toEvalContext().qualities?.(e,t)??pe(r,`host/${e}`,()=>r.bundle.scopeRegistry?.scopes.find(s=>s.token===e)?.declarations).get(n)}function Ot(r){return{name:r.name,type:r.type,values:r.values,stages:r.stages,default:r.default,writable:r.writable}}function Ln(r,e){let t=Ot(r),n=r.writable??e;return n===void 0?t:{...t,writable:n}}function Te(r,e){return r.sceneGameIdToId.get(e)??(r.bundle.scenes[e]?e:void 0)}function $e(r,e,t){return r.blockGameIdToId.get(e)?.get(t)??(r.blockIndex.get(t)?.sceneId===e?t:void 0)}function It(r,e){r.refSplitRevision!==r.registry.revision&&(r.refSplitCache.clear(),r.refSplitRevision=r.registry.revision);let t=r.refSplitCache.get(e);return t||(t=it(e,n=>n==="scene"||r.registry.has(n)||(r.bundle.externalScopes?.includes(n)??!1)),r.refSplitCache.set(e,t)),t}function Bn(r){let e={};r.shared?.patter&&(e.patter=r.shared.patter);for(let[t,n]of Object.entries(r.stageBags??{}))e[P.stage(t)]=n;for(let[t,n]of Object.entries(r.flows??{}))Object.assign(e,Pt(t,n));return e}function Pt(r,e){let t={};e.scopes?.patter&&(t[P.flowGlobals(r)]=e.scopes.patter);for(let[n,s]of Object.entries(e.sceneBags??{}))t[P.flowScene(r,n)]=s;return t}function Mn(r,e){let t={scopes:{},sceneBags:{}},n=P.flow(r);for(let[s,i]of Object.entries(e)){if(!s.startsWith(n))continue;let o=s.slice(n.length);o==="patter"?t.scopes.patter=i:o.startsWith("scene/")&&(t.sceneBags[Pn(o.slice(6))]=i)}return t}function Ct(r){return typeof r=="boolean"?r:typeof r=="number"?r!==0:typeof r=="string"?r!=="":r.length>0}var Fn=(r,e)=>r.shared??e;function je(r,e){return{name:r.name,type:r.type,hasDefault:r.default!==void 0,...r.default!==void 0?{default:r.default}:{},shared:Fn(r,e)}}function Tn(r){return{name:r.name,type:r.type,hasDefault:r.default!==void 0,...r.values?{values:[...r.values]}:{},...r.purpose?{purpose:r.purpose}:{}}}function $n(r,e){e.blocks++;let t=[...r.children];for(;t.length;){let n=t.pop();if(n.type==="group"){e.groups++,n.prompt&&e.prompts++,t.push(...n.children);continue}e.snippets++;for(let s of n.beats??[])e.beats++,s.kind==="gameEvent"&&e.gameEvents++}}function ke(r){let e={scenes:0,blocks:0,groups:0,snippets:0,beats:0,prompts:0,gameEvents:0,cast:r.cast?.length??0},t=[],n=[];for(let o of Object.values(r.scenes)){e.scenes++;let a=D(o);t.push({gameId:a,name:o.name,blocks:o.blocks.map(l=>({gameId:D(l),name:l.name}))});for(let l of o.blocks)$n(l,e);o.sceneProps?.length&&n.push({gameId:a,properties:o.sceneProps.map(l=>je(l,!1))})}let s=(r.scopeRegistry?.scopes??[]).map(o=>({token:o.token,writable:o.writable??!0,opaque:o.declarations===void 0,properties:(o.declarations??[]).map(a=>je(a,!0))})),i=Object.entries(r.gameDataFields??{}).filter(([,o])=>(o?.length??0)>0).map(([o,a])=>({kind:o,fields:(a??[]).map(Tn)}));return{identity:{schema:r.schema,project:r.content.project,...r.content.version!==void 0?{version:r.content.version}:{},...r.content.hash!==void 0?{hash:r.content.hash}:{},...r.content.structureHash!==void 0?{structureHash:r.content.structureHash}:{},voiced:r.voiced,defaultLocale:r.locales.default,locales:[...r.locales.included],localisation:r.localisation?.mode??"embedded",sourceDebug:r.localisation?.sourceDebug??!1},addresses:t,hostScopes:s,properties:{patter:(r.properties??[]).map(o=>je(o,!0)),scene:n},gameData:i,counts:e}}var Q=(r,e)=>Object.prototype.hasOwnProperty.call(r,e);function Nt(r,e){return r.gameDataFields?.[e]??[]}function Ve(r,e,t){return e&&Q(e,t)?e[t]:r.find(n=>n.name===t)?.default}function At(r,e){let t={};for(let n of r){let s=Ve(r,e,n.name);s!==void 0&&(t[n.name]=s)}for(let[n,s]of Object.entries(e??{}))Q(t,n)||(t[n]=s);return t}function Lt(r,e,t){let n=r.extensions!==void 0&&Q(r.extensions,e)?r.extensions[e]:void 0;return n!==void 0&&Q(n.fields,t)?n.fields[t]??[]:[]}function Bt(r,e){return{...(r.extensions!==void 0&&Q(r.extensions,e)?r.extensions[e]:void 0)?.settings??{}}}function Mt(r,e,t=""){let n=o=>({...o?.extensions??{}}),s=Object.values(r.scenes??{}),i=o=>(Q(r.scenes??{},o)?r.scenes[o]:void 0)??s.find(a=>D(a)===o);switch(e){case"project":{let o={};for(let[a,l]of Object.entries(r.extensions??{}))l.project!==void 0&&(o[a]=l.project);return o}case"scene":return n(i(t));case"block":{let o=t.indexOf("/");if(o<0)return{};let a=i(t.slice(0,o))?.blocks??[],l=t.slice(o+1);return n(a.find(c=>c.id===l)??a.find(c=>D(c)===l))}case"snippet":case"option":case"line":case"text":case"gameEvent":{let o,a=(l,c)=>{for(let p of l??[]){if(o!==void 0)return;if(p.type==="group"){if(c&&p.id===t&&e==="option"){o=p;return}if(c&&p.prompt?.id===t&&p.prompt.kind===e){o=p.prompt;return}a(p.children??[],p.selector==="choice");continue}if(p.id===t&&e==="snippet"){o=p;return}let d=(p.beats??[]).find(f=>f.id===t);if(d!==void 0){d.kind===e&&(o=d);return}}};for(let l of s)for(let c of l.blocks??[])o===void 0&&a(c.children??[],!1);return n(o)}default:return{}}}function qe(r){return{schema:z,save:r.saveGame()}}function Ge(r,e){if(!e||e.schema!==z||!e.save)throw new Error(`loadState: not a ${z} envelope`);r.loadGame(e.save)}function Ee(r){return JSON.stringify(qe(r))}function Ce(r,e){Ge(r,JSON.parse(e))}function Ft(r,e){return r.getProperty(e)}function Tt(r,e,t){r.setProperty(e,t)}function $t(r,e){for(let[t,n]of Object.entries(e))r.setProperty(t,n)}function _e(r){let e={};for(let t of jt(r)){let n=t.pathPrefix??t.bag.pathPrefix;for(let[s,i]of Object.entries(t.bag.save()))e[`${n}${s}`]=i}return Object.assign(e,Vt(r)),e}function jt(r){return[...r.listBags(),...r.flows().flatMap(e=>e.listBags())]}function jn(r){switch(r.type){case"line":return`line ${r.character??"?"}: ${JSON.stringify(r.text)}${He(r.gameData)}`;case"text":return`text: ${JSON.stringify(r.text)}${He(r.gameData)}`;case"gameEvent":return`game event ${r.id}${He(r.gameData)}`;case"choice":return`choice (${r.options.length} option${r.options.length===1?"":"s"})`;case"end":return"end"}}var He=r=>r?` gameData=${JSON.stringify(r)}`:"";function Vt(r){let e={};for(let[t,n]of Object.entries(r.getVisitCounts()))e[`visit:${t}`]=n;for(let t of r.flows())for(let[n,s]of Object.entries(t.getVisitCounts()))e[`${t.id}/visit:${n}`]=s;return e}function qt(r,e={}){let t=e.label?`[${e.label}] `:"",n=Le({mounts:()=>jt(r),extra:()=>Vt(r)},{sink:e.sink,label:t});return{snapshot:()=>_e(r),capture:()=>n.capture(),dispose:()=>n.dispose(),logStep(s){(e.sink??(i=>console.log(i)))(`${t}${jn(s)}`)}}}function Gt(r){let e=r.url??"ws://127.0.0.1:4471",t=r.WebSocket??globalThis.WebSocket,n=new Set,s=[],i=null,o=!1,a=r.build,l=()=>{if(!(!i||i.readyState!==1)){for(let d of s)try{i.send(d)}catch{}s=[]}},c=d=>{o||!i||i.readyState>1||(s.push(JSON.stringify(d)),l())};if(!t)return{flowOpened(){},observe(){},flowClosed(){},setBuild(){},close(){o=!0},state:"closed",build:a,url:e};let p=()=>{let d=JSON.stringify({t:"hello",v:1,build:a,project:r.project,flows:[...n]});try{i?.send(d)}catch{}};try{i=new t(e),i.addEventListener("open",()=>{p(),l()}),i.addEventListener("message",d=>{if(!(!r.onBundle||typeof d.data!="string"))try{let f=JSON.parse(d.data);f.t==="bundle"&&typeof f.build=="string"&&typeof f.data=="string"&&r.onBundle({build:f.build,data:f.data})}catch{}}),i.addEventListener("error",()=>{}),i.addEventListener("close",()=>{i=null,s=[]})}catch{i=null}return{flowOpened(d){n.add(d),c({t:"flowOpen",flow:d})},flowClosed(d){n.delete(d),c({t:"flowClose",flow:d})},observe(d,f,g,y,u){n.has(d)||(n.add(d),c({t:"flowOpen",flow:d})),c({t:"frame",flow:d,sceneId:f,beatId:g,type:y,choiceId:u})},setBuild(d){o||d===a||(a=d,i&&i.readyState===1&&p())},close(){o=!0,s=[];try{i?.close()}catch{}i=null},get state(){return o||!i?"closed":i.readyState===1?"connected":"connecting"},get build(){return a},url:e}}function Ht(r,e,t){let n=JSON.parse(t);return e.content.structureHash!==void 0&&e.content.structureHash===n.content.structureHash?(r.replaceStrings(n),{engine:r,bundle:n,kind:"text"}):{engine:r.hotSwap(n),bundle:n,kind:"structure"}}function Vn(r,e){r.textContent="";let t=/\u0002([^\u0003]*)\u0003/g,n=0,s;for(;(s=t.exec(e))!==null;){s.index>n&&r.append(e.slice(n,s.index));let i=document.createElement("strong");i.textContent=s[1]??"",r.append(i),n=s.index+s[0].length}n<e.length&&r.append(e.slice(n))}var Je=!1,_t=!1,zt,qn=350,Ue=6,Ut=7,X=null,Z=0,De=null,Gn=null;function Qt(){if(X)return X;let r=document.createElement("div");return r.className="tooltip",r.setAttribute("role","tooltip"),r.hidden=!0,document.body.appendChild(r),X=r,r}var Hn=r=>r instanceof HTMLElement?r.getBoundingClientRect():r;function _n(r){let e=Qt(),t=Hn(r),n=e.getBoundingClientRect(),s=t.top-n.height-Ut;s<Ue&&(s=t.top+t.height+Ut);let i=t.left+t.width/2-n.width/2;i=Math.max(Ue,Math.min(i,window.innerWidth-n.width-Ue)),e.style.left=`${Math.round(i)}px`,e.style.top=`${Math.round(s)}px`}function Un(r){let e=r.dataset.tip;e&&Wn(r,e)}function Wn(r,e){if(zt?.())return;let t=Qt(),n=(r instanceof HTMLElement?r.closest("dialog[open]"):null)??document.body;t.parentElement!==n&&n.appendChild(t),De=r instanceof HTMLElement?r:null,Vn(t,e),t.hidden=!1,t.classList.remove("show"),t.offsetWidth,_n(r),t.classList.add("show")}function Y(){Z&&(window.clearTimeout(Z),Z=0),De=null,Gn=null,X&&(X.hidden=!0,X.classList.remove("show"))}function Wt(r){r!==De&&(Z&&window.clearTimeout(Z),Z=window.setTimeout(()=>Un(r),qn))}function Jn(){zn()}function Kn(){_t||(_t=!0,setTimeout(()=>{Je||typeof document>"u"||document.querySelector("[data-tip]")&&console.warn("app-shell: something set `data-tip` but no tooltip host is mounted, so those rollovers will not draw. Call initTooltips() once per window.")},0))}var We=r=>r instanceof Element?r.closest("[data-tip]"):null;function zn(r={}){r.suppressed!==void 0&&(zt=r.suppressed),!Je&&(Je=!0,document.addEventListener("pointerover",e=>{let t=We(e.target);t&&Wt(t)}),document.addEventListener("pointerout",e=>{let t=We(e.target);if(!t)return;let n=e.relatedTarget;n instanceof Node&&t.contains(n)||Y()}),document.addEventListener("focusin",e=>{let t=We(e.target);t&&Wt(t)}),document.addEventListener("focusout",()=>Y()),document.addEventListener("pointerdown",()=>Y(),!0),document.addEventListener("scroll",()=>{De&&Y()},!0),document.addEventListener("keydown",e=>{e.key==="Escape"&&Y()}),window.addEventListener("blur",()=>Y()))}var Qn={close:"\u2715",more:"\u22EF",collapsed:"\u25B8",expanded:"\u25BE",dropdown:"\u25BE",back:"\u2039",forward:"\u203A",up:"\u2191",down:"\u2193",tick:"\u2713",locked:"\u2298",readOnly:"\u25CB",checkedOut:"\u270E",modified:"\u25CF",untracked:"+",warning:"\u203C",dot:"\u25CF",play:"\u25B6",restart:"\u27F2",viewCards:"\u25A6",viewTable:"\u2630",viewNode:"\u25C8",grip:"\u283F",add:"+",note:"\u270E",comment:"\u275D"},Yn='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.571" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">',Xn='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">',v=r=>`${Yn}${r}</svg>`,Yt=r=>`${Xn}${r}</svg>`,Jt=Yt('<circle cx="12" cy="12" r="6"/>'),Zn=Yt('<circle cx="12" cy="12" r="9"/>'),Xt={close:v('<path d="M18 6 6 18"/><path d="m6 6 12 12"/>'),more:v('<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>'),collapsed:v('<path d="m9 18 6-6-6-6"/>'),expanded:v('<path d="m6 9 6 6 6-6"/>'),dropdown:v('<path d="m6 9 6 6 6-6"/>'),back:v('<path d="m15 18-6-6 6-6"/>'),forward:v('<path d="m9 18 6-6-6-6"/>'),up:v('<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>'),down:v('<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>'),arrowLeft:v('<path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>'),arrowRight:v('<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>'),tick:v('<path d="M20 6 9 17l-5-5"/>'),locked:v('<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>'),readOnly:v('<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/>'),checkedOut:v('<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/>'),modified:Jt,untracked:v('<path d="M5 12h14"/><path d="M12 5v14"/>'),warning:v('<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>'),dot:Jt,play:v('<path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"/>'),restart:v('<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'),viewCards:v('<rect width="7" height="7" x="3" y="3" rx="1"/><rect width="7" height="7" x="14" y="3" rx="1"/><rect width="7" height="7" x="14" y="14" rx="1"/><rect width="7" height="7" x="3" y="14" rx="1"/>'),viewTable:v('<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M21 9H3"/><path d="M21 15H3"/>'),viewNode:v('<path d="m10.586 5.414-5.172 5.172"/><path d="m18.586 13.414-5.172 5.172"/><path d="M6 12h12"/><circle cx="12" cy="20" r="2"/><circle cx="12" cy="4" r="2"/><circle cx="20" cy="12" r="2"/><circle cx="4" cy="12" r="2"/>'),record:Zn,speaker:v('<path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="M16 9a5 5 0 0 1 0 6"/><path d="M19.364 18.364a9 9 0 0 0 0-12.728"/>'),grip:v('<circle cx="9" cy="12" r="1"/><circle cx="9" cy="5" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="15" cy="19" r="1"/>'),add:v('<path d="M5 12h14"/><path d="M12 5v14"/>'),copy:v('<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>'),connect:v('<path d="M12 22v-5"/><path d="M15 8V2"/><path d="M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z"/><path d="M9 8V2"/>'),search:v('<path d="m21 21-4.34-4.34"/><circle cx="11" cy="11" r="8"/>'),pin:v('<path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"/>'),settings:v('<path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"/><circle cx="12" cy="12" r="3"/>'),note:v('<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>'),comment:v('<path d="M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"/>')},hs={...Xt,noteFilled:'<svg viewBox="0 0 16 16" width="13" height="13" fill="currentColor" fill-rule="evenodd" aria-hidden="true"><path d="M3.4 1.4h5.3L12.6 5.3v8.1a1.2 1.2 0 0 1-1.2 1.2H3.4a1.2 1.2 0 0 1-1.2-1.2V2.6A1.2 1.2 0 0 1 3.4 1.4ZM4.9 6.8h6.2v1.1H4.9Zm0 2.1h6.2v1.1H4.9Zm0 2.1h3.7v1.1H4.9Z"/></svg>',noteOutline:'<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linejoin="round" stroke-linecap="round" aria-hidden="true"><path d="M3.4 2h4.9l3.9 3.9v7.5a1 1 0 0 1-1 1H3.4a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1Z"/><path d="M8.3 2.2v3.8h3.8"/><path d="M4.9 8h6.2M4.9 10h6.2M4.9 12h3.7" stroke-width="0.95"/></svg>'},ms=Object.keys(Xt);var Kt=new Map;for(let[r,e]of Object.entries(Qn))Kt.has(e)||Kt.set(e,r);function Zt(r,e,...t){let n=document.createElement(r),s=typeof e=="string"?{className:e}:e??{};s.className&&(n.className=s.className),s.text!==void 0&&s.text!==null&&(n.textContent=s.text),s.title!==void 0&&(n.title=s.title),s.tip!==void 0&&(n.dataset.tip=s.tip,n.setAttribute("aria-label",s.tip),Jn()),s.onClick&&n.addEventListener("click",s.onClick);for(let i of t)i!=null&&n.append(i);return Kn(),n}function en(r){let e=r.default;if(e!=null)return typeof e=="boolean"?e?"True":"False":Array.isArray(e)?e.length===0?"none":e.join(", "):e===""?"none":String(e);switch(r.type){case"boolean":return"False";case"number":return"0";case"enum":return r.values?.[0]??"none";case"quality":return r.stages?.[0]??"first stage";case"flags":return"none";default:return"empty"}}var tn=r=>`default (${en(r)})`;function Ke(r){let e=r.doc===void 0?Zt:(a,l)=>{let c=r.doc.createElement(a);return c.className=l.className,l.text!==void 0&&(c.textContent=l.text),l.tip!==void 0&&(c.title=l.tip,c.setAttribute("aria-label",l.tip)),l.onClick&&c.addEventListener("click",l.onClick),a==="button"&&(c.type="button"),c},t=e("span",{className:"seg shell-rungs"}),n=r.decl??{type:"quality",stages:r.stages},s=r.value===void 0,i=typeof n.default=="string"&&r.stages.includes(n.default)?n.default:r.stages[0],o=r.onPick===void 0;r.onClear&&t.append(e("button",{className:`seg-opt shell-rung shell-rung-default${s?" on":""}`,text:tn(n),tip:s?"Not set here: the declared default holds":"Clear the value, back to the default",onClick:()=>{s||r.onClear()}}));for(let a of r.stages){let l=r.value===a,c=s&&a===i,p=e(o?"span":"button",{className:`seg-opt shell-rung${l?" on":""}${c?" fallback":""}`,text:a,tip:l?"The current stage":c?"The stage it falls back to":o?a:r.pickTip?.(a)??`Set to "${a}"`,...o?{}:{onClick:()=>{l||r.onPick(a)}}});t.append(p)}return!s&&!r.stages.includes(r.value)&&t.append(e("span",{className:"seg-opt shell-rung stray on",text:r.value,tip:`"${r.value}" is not one of the stages: pick the one it belongs at now`})),t}var nn="pp-inspector-style",er=`
3
3
  .pp-insp{font:13px/1.4 ui-sans-serif,system-ui,sans-serif;color:#15201e;background:#f4efe6;border:1px solid #cfc7b8;border-radius:10px;padding:.6rem .7rem;max-width:22rem;box-shadow:0 6px 20px rgba(21,32,30,.12)}
4
4
  .pp-insp h4{margin:0 0 .4rem;font:600 .72rem/1 ui-sans-serif,system-ui,sans-serif;letter-spacing:.08em;text-transform:uppercase;color:#5c6b62}
5
5
  .pp-insp-empty{color:#8a9691;font-style:italic}
@@ -16,7 +16,7 @@
16
16
  .pp-insp-ctl .seg-opt+.seg-opt{border-left:1px solid #cfc7b8}
17
17
  .pp-insp-ctl .seg-opt.on{color:#214f4b;background:#dbe8e4;font-weight:600;cursor:default}
18
18
  .pp-insp-ctl .shell-rung.stray{color:#9a3b2e;text-decoration:line-through}
19
- `;function zr(n){if(n.getElementById(Yt))return;let e=n.createElement("style");e.id=Yt,e.textContent=Kr,(n.head??n.documentElement).appendChild(e)}function Qr(n,e){return Array.isArray(n)&&Array.isArray(e)?n.length===e.length&&n.every((t,r)=>t===e[r]):n===e}function Zt(n,e={}){let t=e.container?.ownerDocument??document;zr(t);let r=t.createElement("div");r.className="pp-insp";let s=t.createElement("h4");s.textContent=e.title??"Runtime state";let i=t.createElement("div"),o=t.createElement("div");o.className="pp-insp-io";let a=t.createElement("button");a.type="button",a.textContent="Save state\u2026",a.addEventListener("click",()=>{let d=new Blob([xe(n)],{type:"application/json"}),x=t.createElement("a");x.href=URL.createObjectURL(d),x.download="save.patterstate",x.click(),URL.revokeObjectURL(x.href)});let l=t.createElement("button");l.type="button",l.textContent="Load state\u2026",l.addEventListener("click",()=>{let d=t.createElement("input");d.type="file",d.accept=".patterstate,application/json",d.addEventListener("change",()=>{let x=d.files?.[0];x&&x.text().then(I=>{try{ke(n,I),g()}catch(D){console.error("Load state failed:",D instanceof Error?D.message:D)}})}),d.click()}),o.append(a,l),r.append(s,o,i);let c=[],u=d=>{let x=t.createElement("div");x.className="pp-insp-row";let I=t.createElement("span");I.className="pp-insp-ref",I.textContent=d.path,I.title=d.path;let D=t.createElement("div");D.className="pp-insp-ctl";let L=t.createElement("button");L.className="pp-insp-reset",L.type="button",L.textContent="\u21BA",L.title="Reset to default",x.append(I,D,L),i.appendChild(x);let k,A=h=>{n.setProperty(d.path,h),F()},M=h=>t.activeElement===h;function F(){L.disabled=Qr(n.getProperty(d.path),d.default)}if(L.addEventListener("click",()=>{n.setProperty(d.path,d.default),k(),F()}),d.type==="boolean"){let h=t.createElement("input");h.type="checkbox",h.addEventListener("change",()=>A(h.checked)),D.appendChild(h),k=()=>{M(h)||(h.checked=n.getProperty(d.path)===!0)}}else if(d.type==="number"){let h=t.createElement("input");h.type="number",h.addEventListener("change",()=>A(Number(h.value))),D.appendChild(h),k=()=>{M(h)||(h.value=String(n.getProperty(d.path)??""))}}else if(d.type==="quality"){let h=()=>{let E=n.getProperty(d.path);D.replaceChildren(We({stages:d.stages??[],value:typeof E=="string"?E:void 0,decl:d,onPick:m=>{A(m),h()},doc:t}))};k=h}else if(d.type==="enum"){let h=t.createElement("select");for(let E of d.values??[]){let m=t.createElement("option");m.value=E,m.textContent=E,h.appendChild(m)}h.addEventListener("change",()=>A(h.value)),D.appendChild(h),k=()=>{M(h)||(h.value=String(n.getProperty(d.path)??""))}}else if(d.type==="flags"){let h=t.createElement("input");h.type="text",h.placeholder="comma, separated, flags",h.addEventListener("change",()=>A(h.value.split(",").map(E=>E.trim()).filter(E=>E.length>0))),D.appendChild(h),k=()=>{if(!M(h)){let E=n.getProperty(d.path);h.value=Array.isArray(E)?E.join(", "):""}}}else{let h=t.createElement("input");h.type="text",h.addEventListener("change",()=>A(h.value)),D.appendChild(h),k=()=>{M(h)||(h.value=String(n.getProperty(d.path)??""))}}k(),F(),c.push(()=>{k(),F()})},p=n.listProperties();if(p.length===0){let d=t.createElement("div");d.className="pp-insp-empty",d.textContent="No @patter properties.",i.appendChild(d)}else for(let d of p)u(d);let g=()=>{for(let d of c)d()};e.container?.appendChild(r);let f=e.pollMs??250,y;return f>0&&(y=setInterval(g,f)),{el:r,refresh:g,destroy(){y!==void 0&&clearInterval(y),r.remove()}}}var Xt="pp-bundle-style",Yr=`
19
+ `;function tr(r){if(r.getElementById(nn))return;let e=r.createElement("style");e.id=nn,e.textContent=er,(r.head??r.documentElement).appendChild(e)}function nr(r,e){return Array.isArray(r)&&Array.isArray(e)?r.length===e.length&&r.every((t,n)=>t===e[n]):r===e}function rn(r,e={}){let t=e.container?.ownerDocument??document;tr(t);let n=t.createElement("div");n.className="pp-insp";let s=t.createElement("h4");s.textContent=e.title??"Runtime state";let i=t.createElement("div"),o=t.createElement("div");o.className="pp-insp-io";let a=t.createElement("button");a.type="button",a.textContent="Save state\u2026",a.addEventListener("click",()=>{let u=new Blob([Ee(r)],{type:"application/json"}),x=t.createElement("a");x.href=URL.createObjectURL(u),x.download="save.patterstate",x.click(),URL.revokeObjectURL(x.href)});let l=t.createElement("button");l.type="button",l.textContent="Load state\u2026",l.addEventListener("click",()=>{let u=t.createElement("input");u.type="file",u.accept=".patterstate,application/json",u.addEventListener("change",()=>{let x=u.files?.[0];x&&x.text().then(O=>{try{Ce(r,O),f()}catch(R){console.error("Load state failed:",R instanceof Error?R.message:R)}})}),u.click()}),o.append(a,l),n.append(s,o,i);let c=[],p=u=>{let x=t.createElement("div");x.className="pp-insp-row";let O=t.createElement("span");O.className="pp-insp-ref",O.textContent=u.path,O.title=u.path;let R=t.createElement("div");R.className="pp-insp-ctl";let A=t.createElement("button");A.className="pp-insp-reset",A.type="button",A.textContent="\u21BA",A.title="Reset to default",x.append(O,R,A),i.appendChild(x);let k,L=h=>{r.setProperty(u.path,h),T()},F=h=>t.activeElement===h;function T(){A.disabled=nr(r.getProperty(u.path),u.default)}if(A.addEventListener("click",()=>{r.setProperty(u.path,u.default),k(),T()}),u.type==="boolean"){let h=t.createElement("input");h.type="checkbox",h.addEventListener("change",()=>L(h.checked)),R.appendChild(h),k=()=>{F(h)||(h.checked=r.getProperty(u.path)===!0)}}else if(u.type==="number"){let h=t.createElement("input");h.type="number",h.addEventListener("change",()=>L(Number(h.value))),R.appendChild(h),k=()=>{F(h)||(h.value=String(r.getProperty(u.path)??""))}}else if(u.type==="quality"){let h=()=>{let E=r.getProperty(u.path);R.replaceChildren(Ke({stages:u.stages??[],value:typeof E=="string"?E:void 0,decl:u,onPick:m=>{L(m),h()},doc:t}))};k=h}else if(u.type==="enum"){let h=t.createElement("select");for(let E of u.values??[]){let m=t.createElement("option");m.value=E,m.textContent=E,h.appendChild(m)}h.addEventListener("change",()=>L(h.value)),R.appendChild(h),k=()=>{F(h)||(h.value=String(r.getProperty(u.path)??""))}}else if(u.type==="flags"){let h=t.createElement("input");h.type="text",h.placeholder="comma, separated, flags",h.addEventListener("change",()=>L(h.value.split(",").map(E=>E.trim()).filter(E=>E.length>0))),R.appendChild(h),k=()=>{if(!F(h)){let E=r.getProperty(u.path);h.value=Array.isArray(E)?E.join(", "):""}}}else{let h=t.createElement("input");h.type="text",h.addEventListener("change",()=>L(h.value)),R.appendChild(h),k=()=>{F(h)||(h.value=String(r.getProperty(u.path)??""))}}k(),T(),c.push(()=>{k(),T()})},d=r.listProperties();if(d.length===0){let u=t.createElement("div");u.className="pp-insp-empty",u.textContent="No @patter properties.",i.appendChild(u)}else for(let u of d)p(u);let f=()=>{for(let u of c)u()};e.container?.appendChild(n);let g=e.pollMs??250,y;return g>0&&(y=setInterval(f,g)),{el:n,refresh:f,destroy(){y!==void 0&&clearInterval(y),n.remove()}}}var sn="pp-bundle-style",rr=`
20
20
  .pp-bundle{font:13px/1.4 ui-sans-serif,system-ui,sans-serif;color:#15201e;background:#f4efe6;border:1px solid #cfc7b8;border-radius:10px;padding:.6rem .7rem;max-width:26rem;box-shadow:0 6px 20px rgba(21,32,30,.12)}
21
21
  .pp-bundle h4{margin:0 0 .4rem;font:600 .72rem/1 ui-sans-serif,system-ui,sans-serif;letter-spacing:.08em;text-transform:uppercase;color:#5c6b62}
22
22
  .pp-bundle details{border-top:1px solid #e3dccf;padding:.3rem 0}
@@ -33,5 +33,5 @@
33
33
  .pp-bundle-empty{color:#8a9691;font-style:italic;margin-left:1rem}
34
34
  .pp-bundle-warn{color:#8a3a2f;font-weight:600}
35
35
  .pp-bundle-tag{font-size:.7rem;color:#5c6b62;border:1px solid #cfc7b8;border-radius:5px;padding:0 .25rem;margin-left:.3rem}
36
- `;function Zr(n){if(n.getElementById(Xt))return;let e=n.createElement("style");e.id=Xt,e.textContent=Yr,(n.head??n.documentElement).appendChild(e)}var w=(n,e,t,r)=>{let s=n.createElement(e);return t&&(s.className=t),r!==void 0&&(s.textContent=r),s};function B(n,e,t,r="pp-bundle-val"){let s=w(n,"div","pp-bundle-row");return s.append(w(n,"span","pp-bundle-key",e),w(n,"span",r,t)),s}function Je(n,e){let t=w(n,"div","pp-bundle-row");t.append(w(n,"span","pp-bundle-key pp-bundle-addr",e.name));let r=w(n,"span","pp-bundle-val",e.type);return e.hasDefault||r.append(w(n,"span","pp-bundle-tag","no default")),t.append(r),t}function Z(n,e,t,r,s){let i=n.createElement("details");i.dataset.section=e,i.open=s;let o=n.createElement("summary");return o.textContent=t,r!==null&&o.append(w(n,"span","pp-bundle-count",` ${r}`)),i.append(o),i}function er(n,e={}){let t=e.container?.ownerDocument??document;Zr(t);let r=we(n),s=new Set(e.open??["identity","addresses"]),i=w(t,"div","pp-bundle");i.append(w(t,"h4",void 0,e.title??"Bundle"));let o=Z(t,"identity",r.identity.project||"(unnamed project)",null,s.has("identity"));r.identity.version&&o.append(B(t,"version",r.identity.version)),o.append(B(t,"schema",r.identity.schema)),o.append(B(t,"locales",`${r.identity.defaultLocale}${r.identity.locales.length>1?` (+${r.identity.locales.length-1})`:""}`)),o.append(B(t,"strings",r.identity.localisation)),r.identity.voiced&&o.append(B(t,"voiced","yes")),r.identity.hash&&o.append(B(t,"hash",r.identity.hash)),r.identity.structureHash&&o.append(B(t,"structure",r.identity.structureHash)),r.identity.sourceDebug&&o.append(B(t,"build","SOURCE DEBUG - not shippable","pp-bundle-val pp-bundle-warn")),i.append(o);let a=Z(t,"addresses","Addresses",r.addresses.length,s.has("addresses"));r.addresses.length||a.append(w(t,"div","pp-bundle-empty","no scenes"));for(let f of r.addresses){let y=w(t,"div","pp-bundle-row");y.append(w(t,"span","pp-bundle-key pp-bundle-addr",f.gameId),w(t,"span","pp-bundle-val",f.name)),a.append(y);for(let d of f.blocks){let x=w(t,"div","pp-bundle-row pp-bundle-sub");x.append(w(t,"span","pp-bundle-key pp-bundle-addr",d.gameId),w(t,"span","pp-bundle-val",d.name)),a.append(x)}}i.append(a);let l=r.hostScopes.reduce((f,y)=>f+y.properties.length,0),c=Z(t,"hostScopes","Host properties",l,s.has("hostScopes"));r.hostScopes.length||c.append(w(t,"div","pp-bundle-empty","the game supplies nothing"));for(let f of r.hostScopes){let y=w(t,"div","pp-bundle-row");y.append(w(t,"span","pp-bundle-key pp-bundle-addr",`@${f.token}`));let d=w(t,"span","pp-bundle-val",f.opaque?"any name, unchecked":`${f.properties.length} declared`);f.writable||d.append(w(t,"span","pp-bundle-tag","read-only")),y.append(d),c.append(y);for(let x of f.properties){let I=Je(t,x);I.classList.add("pp-bundle-sub"),c.append(I)}}i.append(c);let u=r.properties.patter.length+r.properties.scene.reduce((f,y)=>f+y.properties.length,0),p=Z(t,"properties","Story properties",u,s.has("properties"));u||p.append(w(t,"div","pp-bundle-empty","none declared"));for(let f of r.properties.patter)p.append(Je(t,f));for(let f of r.properties.scene){p.append(B(t,"@scene",f.gameId,"pp-bundle-val pp-bundle-addr"));for(let y of f.properties){let d=Je(t,y);d.classList.add("pp-bundle-sub"),p.append(d)}}if(i.append(p),r.gameData.length){let f=Z(t,"gameData","Game data",r.gameData.reduce((y,d)=>y+d.fields.length,0),s.has("gameData"));for(let y of r.gameData){f.append(B(t,"on",y.kind));for(let d of y.fields){let x=w(t,"div","pp-bundle-row pp-bundle-sub");x.append(w(t,"span","pp-bundle-key pp-bundle-addr",d.name),w(t,"span","pp-bundle-val",d.type)),f.append(x)}}i.append(f)}let g=Z(t,"counts","Counts",null,s.has("counts"));for(let[f,y]of Object.entries(r.counts))g.append(B(t,f,String(y)));return i.append(g),e.container?.append(i),{el:i,description:r,destroy(){i.remove()}}}function tr(n,e){let r=JSON.parse(n).clips??{},s=e===""||/[/\\]$/.test(e)?"":"/";return{resolve(i){let o=r[i];return!o||!o.file?null:`${e}${s}${o.file}`}}}return lr(Xr);})();
36
+ `;function sr(r){if(r.getElementById(sn))return;let e=r.createElement("style");e.id=sn,e.textContent=rr,(r.head??r.documentElement).appendChild(e)}var w=(r,e,t,n)=>{let s=r.createElement(e);return t&&(s.className=t),n!==void 0&&(s.textContent=n),s};function N(r,e,t,n="pp-bundle-val"){let s=w(r,"div","pp-bundle-row");return s.append(w(r,"span","pp-bundle-key",e),w(r,"span",n,t)),s}function ze(r,e){let t=w(r,"div","pp-bundle-row");t.append(w(r,"span","pp-bundle-key pp-bundle-addr",e.name));let n=w(r,"span","pp-bundle-val",e.type);return e.hasDefault||n.append(w(r,"span","pp-bundle-tag","no default")),t.append(n),t}function ee(r,e,t,n,s){let i=r.createElement("details");i.dataset.section=e,i.open=s;let o=r.createElement("summary");return o.textContent=t,n!==null&&o.append(w(r,"span","pp-bundle-count",` ${n}`)),i.append(o),i}function on(r,e={}){let t=e.container?.ownerDocument??document;sr(t);let n=ke(r),s=new Set(e.open??["identity","addresses"]),i=w(t,"div","pp-bundle");i.append(w(t,"h4",void 0,e.title??"Bundle"));let o=ee(t,"identity",n.identity.project||"(unnamed project)",null,s.has("identity"));n.identity.version&&o.append(N(t,"version",n.identity.version)),o.append(N(t,"schema",n.identity.schema)),o.append(N(t,"locales",`${n.identity.defaultLocale}${n.identity.locales.length>1?` (+${n.identity.locales.length-1})`:""}`)),o.append(N(t,"strings",n.identity.localisation)),n.identity.voiced&&o.append(N(t,"voiced","yes")),n.identity.hash&&o.append(N(t,"hash",n.identity.hash)),n.identity.structureHash&&o.append(N(t,"structure",n.identity.structureHash)),n.identity.sourceDebug&&o.append(N(t,"build","SOURCE DEBUG - not shippable","pp-bundle-val pp-bundle-warn")),i.append(o);let a=ee(t,"addresses","Addresses",n.addresses.length,s.has("addresses"));n.addresses.length||a.append(w(t,"div","pp-bundle-empty","no scenes"));for(let g of n.addresses){let y=w(t,"div","pp-bundle-row");y.append(w(t,"span","pp-bundle-key pp-bundle-addr",g.gameId),w(t,"span","pp-bundle-val",g.name)),a.append(y);for(let u of g.blocks){let x=w(t,"div","pp-bundle-row pp-bundle-sub");x.append(w(t,"span","pp-bundle-key pp-bundle-addr",u.gameId),w(t,"span","pp-bundle-val",u.name)),a.append(x)}}i.append(a);let l=n.hostScopes.reduce((g,y)=>g+y.properties.length,0),c=ee(t,"hostScopes","Host properties",l,s.has("hostScopes"));n.hostScopes.length||c.append(w(t,"div","pp-bundle-empty","the game supplies nothing"));for(let g of n.hostScopes){let y=w(t,"div","pp-bundle-row");y.append(w(t,"span","pp-bundle-key pp-bundle-addr",`@${g.token}`));let u=w(t,"span","pp-bundle-val",g.opaque?"any name, unchecked":`${g.properties.length} declared`);g.writable||u.append(w(t,"span","pp-bundle-tag","read-only")),y.append(u),c.append(y);for(let x of g.properties){let O=ze(t,x);O.classList.add("pp-bundle-sub"),c.append(O)}}i.append(c);let p=n.properties.patter.length+n.properties.scene.reduce((g,y)=>g+y.properties.length,0),d=ee(t,"properties","Story properties",p,s.has("properties"));p||d.append(w(t,"div","pp-bundle-empty","none declared"));for(let g of n.properties.patter)d.append(ze(t,g));for(let g of n.properties.scene){d.append(N(t,"@scene",g.gameId,"pp-bundle-val pp-bundle-addr"));for(let y of g.properties){let u=ze(t,y);u.classList.add("pp-bundle-sub"),d.append(u)}}if(i.append(d),n.gameData.length){let g=ee(t,"gameData","Game data",n.gameData.reduce((y,u)=>y+u.fields.length,0),s.has("gameData"));for(let y of n.gameData){g.append(N(t,"on",y.kind));for(let u of y.fields){let x=w(t,"div","pp-bundle-row pp-bundle-sub");x.append(w(t,"span","pp-bundle-key pp-bundle-addr",u.name),w(t,"span","pp-bundle-val",u.type)),g.append(x)}}i.append(g)}let f=ee(t,"counts","Counts",null,s.has("counts"));for(let[g,y]of Object.entries(n.counts))f.append(N(t,g,String(y)));return i.append(f),e.container?.append(i),{el:i,description:n,destroy(){i.remove()}}}function an(r,e){let n=JSON.parse(r).clips??{},s=e===""||/[/\\]$/.test(e)?"":"/";return{resolve(i){let o=n[i];return!o||!o.file?null:`${e}${s}${o.file}`}}}return gn(ir);})();
37
37
  //# sourceMappingURL=patterplay.min.js.map