@wireweave/core 4.0.0-beta.15 → 4.0.0-beta.16

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
- import { linkAppV4, renderSite, getLinkedAppData, failed, diagnostic, freeze, jcs, asObjects, textValue, validateAppAssets, object } from './chunk-24W2GEKO.js';
2
- import { digestV4 } from './chunk-UGMDBW46.js';
1
+ import { linkAppV4, renderSite, getLinkedAppData, failed, diagnostic, freeze, jcs, asObjects, textValue, validateAppAssets, object } from './chunk-6EMG345O.js';
2
+ import { digestV4 } from './chunk-YAANMWP2.js';
3
3
  import { __publicField } from './chunk-PKBMQBKP.js';
4
4
 
5
5
  // src/ast/component-parameters.ts
@@ -62,8 +62,8 @@ function definitionKey(namespace, kind, id) {
62
62
  function nodeSource(module) {
63
63
  return module.source;
64
64
  }
65
- function manifestSource(manifest, location2) {
66
- return { sourceId: manifest.sourceId, location: location2 };
65
+ function manifestSource(manifest, location) {
66
+ return { sourceId: manifest.sourceId, location };
67
67
  }
68
68
  function componentUses(node) {
69
69
  const uses = [];
@@ -578,7 +578,7 @@ function linkLegacyApp(manifest, modules) {
578
578
  source: node.source
579
579
  }))
580
580
  );
581
- const document2 = {
581
+ const document = {
582
582
  type: "AppDocument",
583
583
  id: manifest.id,
584
584
  modules: resolvedModules,
@@ -587,9 +587,12 @@ function linkLegacyApp(manifest, modules) {
587
587
  screens: linkedScreens,
588
588
  sourceMap
589
589
  };
590
- return { ok: true, document: document2, diagnostics: [] };
590
+ return { ok: true, document, diagnostics: [] };
591
591
  }
592
592
 
593
+ // src/app/native-runtime.generated.ts
594
+ var NATIVE_RUNTIME = '(()=>{function runtimeEngine(program2){const nodes=new Map(program2.nodes.map(node=>[node.id,node]));const byIdentity=new Map(program2.nodes.map(node=>[canonical(node.identity),node]));const fixtures=new Map(program2.fixtures.map(fixture=>[fixture.id,fixture]));const clone=value=>JSON.parse(JSON.stringify(value));const record=value=>value!==null&&typeof value==="object"&&!Array.isArray(value)?value:{};const scalar=value=>{if(value==null)return"";if(typeof value==="string")return value;if(typeof value==="number"||typeof value==="boolean")return String(value);if(typeof value==="object")return canonical(value);throw Error("scalar-type")};function canonical(value){if(Array.isArray(value))return"["+value.map(canonical).join(",")+"]";if(value!==null&&typeof value==="object")return"{"+Object.keys(value).sort().map(key=>JSON.stringify(key)+":"+canonical(value[key])).join(",")+"}";return JSON.stringify(value)}function bounded(value){const stack=[{value,depth:0}];let count=0;while(stack.length){const entry=stack.pop();if(++count>25e4||entry.depth>128)throw Error("limit-json");const item=entry.value;if(typeof item==="string"){for(const character of item){const code=character.codePointAt(0);if(code>=55296&&code<=57343)throw Error("invalid-unicode")}}else if(typeof item==="number"){if(!Number.isFinite(item))throw Error("non-finite-number")}else if(Array.isArray(item)){if(item.length>1e4)throw Error("limit-list");for(const child of item)stack.push({value:child,depth:entry.depth+1})}else if(item!==null&&typeof item==="object"){const entries=Object.entries(item);if(entries.length>1e3)throw Error("limit-record");for(const[key,child]of entries){bounded(key);stack.push({value:child,depth:entry.depth+1})}}else if(item!==null&&typeof item!=="boolean")throw Error("invalid-json")}}function hash(source){var _a,_b,_c,_d,_e,_f,_g;const k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];const bytes=new TextEncoder().encode(source),padded=new Uint8Array(Math.ceil((bytes.length+9)/64)*64);padded.set(bytes);padded[bytes.length]=128;const view2=new DataView(padded.buffer);view2.setUint32(padded.length-8,Math.floor(bytes.length/536870912));view2.setUint32(padded.length-4,bytes.length*8>>>0);const h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],words=new Uint32Array(64);const rotate=(value,shift)=>value>>>shift|value<<32-shift;for(let block=0;block<padded.length;block+=64){for(let index=0;index<16;index++)words[index]=view2.getUint32(block+index*4);for(let index=16;index<64;index++){const x=(_a=words[index-15])!=null?_a:0,y=(_b=words[index-2])!=null?_b:0;words[index]=((_c=words[index-16])!=null?_c:0)+(rotate(x,7)^rotate(x,18)^x>>>3)+((_d=words[index-7])!=null?_d:0)+(rotate(y,17)^rotate(y,19)^y>>>10)>>>0}let[a=0,b=0,c=0,d=0,e=0,f=0,g=0,v=0]=h;for(let index=0;index<64;index++){const first=v+(rotate(e,6)^rotate(e,11)^rotate(e,25))+(e&f^~e&g)+((_e=k[index])!=null?_e:0)+((_f=words[index])!=null?_f:0)>>>0,second=(rotate(a,2)^rotate(a,13)^rotate(a,22))+(a&b^a&c^b&c)>>>0;v=g;g=f;f=e;e=d+first>>>0;d=c;c=b;b=a;a=first+second>>>0}for(const[index,value]of[a,b,c,d,e,f,g,v].entries())h[index]=((_g=h[index])!=null?_g:0)+value>>>0}return"sha256:"+h.map(value=>value.toString(16).padStart(8,"0")).join("")}function range(code,ranges){let low=0,high=ranges.length-1;while(low<=high){const middle=low+high>>>1,pair=ranges[middle];if(code<pair[0])high=middle-1;else if(code>pair[1])low=middle+1;else return true}return false}function convert(value,mode){if(typeof value!=="string")throw Error("value-type");const chars=Array.from(value);if(mode==="trim"){let start=0,end=chars.length;while(start<end&&range(chars[start].codePointAt(0),program2.unicode.whitespace))start++;while(end>start&&range(chars[end-1].codePointAt(0),program2.unicode.whitespace))end--;return chars.slice(start,end).join("")}return chars.map((character,index)=>{var _a;if(mode==="lower"&&character==="\\u03A3"){let before=index-1,after=index+1;while(before>=0&&range(chars[before].codePointAt(0),program2.unicode.ignorable))before--;while(after<chars.length&&range(chars[after].codePointAt(0),program2.unicode.ignorable))after++;if(before>=0&&range(chars[before].codePointAt(0),program2.unicode.cased)&&!(after<chars.length&&range(chars[after].codePointAt(0),program2.unicode.cased)))return"\\u03C2"}return(_a=(mode==="upper"?program2.unicode.upper:program2.unicode.lower)[String(character.codePointAt(0))])!=null?_a:character}).join("")}function expression(raw,node,state,event={},depth=0){var _a;if(depth>128)throw Error("limit-expression");const value=record(raw);if(Object.hasOwn(value,"literal"))return value.literal;if(typeof value.state==="string"){const binding=node.bindings[value.state];if(!binding)throw Error("missing-state");return state.states[binding.key]}if(typeof value.event==="string"){if(!Object.hasOwn(event,value.event))throw Error("event-value-unavailable");return event[value.event]}if(value.read){const read=record(value.read);let result=expression(read.source,node,state,event,depth+1);for(const key of read.path){if(["__proto__","constructor","prototype"].includes(String(key))||result===null||typeof result!=="object"||!Object.hasOwn(result,key))throw Error("missing-read-path");result=result[key]}return result}if(typeof value.call==="string"){const args=value.args.map(arg=>expression(arg,node,state,event,depth+1));if(value.call==="length"&&args.length===1&&(typeof args[0]==="string"||Array.isArray(args[0])))return Array.from(args[0]).length;if(["lower","upper","trim"].includes(value.call)&&args.length===1)return convert(args[0],value.call);if(value.call==="concat"&&args.length>=2&&args.length<=16&&args.every(arg=>typeof arg==="string"))return args.join("");if(value.call==="coalesce"&&args.length>=2&&args.length<=16)return(_a=args.find(arg=>arg!==null))!=null?_a:null;if(["add","subtract","multiply","divide"].includes(value.call)&&args.length===2&&args.every(arg=>typeof arg==="number")){const a=args[0],b=args[1];if(value.call==="divide"&&b===0)throw Error("division-by-zero");const result=value.call==="add"?a+b:value.call==="subtract"?a-b:value.call==="multiply"?a*b:a/b;if(!Number.isFinite(result))throw Error("non-finite-number");return result}}throw Error("expression-type")}function compare(a,b){if(typeof a!==typeof b||!["number","string"].includes(typeof a))throw Error("comparison-type");if(typeof a==="number"&&typeof b==="number")return a===b?0:a<b?-1:1;const left=Array.from(a),right=Array.from(b);for(let index=0;index<Math.min(left.length,right.length);index++)if(left[index]!==right[index])return left[index].codePointAt(0)<right[index].codePointAt(0)?-1:1;return left.length-right.length}function guard(raw,node,state,event={}){if(raw===void 0)return true;const value=record(raw);if(value.op==="all")return value.guards.every(item=>guard(item,node,state,event));if(value.op==="any")return value.guards.some(item=>guard(item,node,state,event));if(value.op==="not")return!guard(value.guard,node,state,event);const left=expression(value.left,node,state,event),right=expression(value.right,node,state,event);if(value.op==="eq")return canonical(left)===canonical(right);if(value.op==="ne")return canonical(left)!==canonical(right);if(value.op==="in"&&Array.isArray(right))return right.some(item=>canonical(item)===canonical(left));if(["contains","startsWith"].includes(scalar(value.op))&&typeof left==="string"&&typeof right==="string")return value.op==="contains"?left.includes(right):left.startsWith(right);const order=compare(left,right);if(value.op==="lt")return order<0;if(value.op==="lte")return order<=0;if(value.op==="gt")return order>0;if(value.op==="gte")return order>=0;throw Error("guard-type")}function routeAddress(route){return"#wf/"+encodeURIComponent(route.namespace)+"/"+encodeURIComponent(route.id)+(route.variant===void 0?"":"?variant="+encodeURIComponent(route.variant))}function parseAddress(fragment){if(fragment==="")return clone(program2.entry);try{const match=/^#wf\\/([^/?]+)\\/([^/?]+)(?:\\?variant=([^&]*))?$/.exec(fragment);if(!match)return null;const result={namespace:decodeURIComponent(match[1]),id:decodeURIComponent(match[2])};if(match[3]!==void 0)result.variant=decodeURIComponent(match[3]);const screen=program2.screens.find(screen2=>screen2.route.namespace===result.namespace&&screen2.route.id===result.id);return screen&&(result.variant===void 0||screen.variants.includes(result.variant))?result:null}catch(error){void error;return null}}function screenOf(state){return program2.screens.find(screen=>{var _a,_b;return screen.route.namespace===((_a=state.route)==null?void 0:_a.namespace)&&screen.route.id===((_b=state.route)==null?void 0:_b.id)})}function roots(state){const screen=screenOf(state);return screen?["app","screen/"+screen.route.namespace+"/"+screen.route.id,...screen.shell?[program2.shells.find(shell=>shell.id===screen.shell).root]:[]]:["app"]}function descendant(id,ancestor){let node=nodes.get(id);while(node){if(node.id===ancestor)return true;node=node.parent?nodes.get(node.parent):void 0}return false}function visible(node,state){var _a,_b,_c;const mounted=roots(state);let current=node;while(current){if(!mounted.includes(current.root)||!guard(current.attributes.visibleWhen,current,state))return false;if((["modal","drawer","popover"].includes(current.kind)||current.kind==="dropdown"&&current.id!==node.id)&&!state.overlays.some(overlay=>overlay.id===current.id))return false;if(current.kind==="tab"&&current.parent&&current.id!==node.id){const owner=nodes.get(current.parent);if((owner==null?void 0:owner.kind)==="tabs"&&owner.children.filter(id=>{var _a2;return((_a2=nodes.get(id))==null?void 0:_a2.kind)==="tab"})[(_a=state.selection[owner.id])!=null?_a:0]!==current.id)return false}const when=current.attributes.when;if(when!==void 0){const screen=screenOf(state);const variant=(_c=(_b=state.route)==null?void 0:_b.variant)!=null?_c:screen==null?void 0:screen.variants[0];if(!(Array.isArray(when)?when.includes(variant!=null?variant:""):when===variant))return false}current=current.parent?nodes.get(current.parent):void 0}return true}function enabled(node,state){let current=node;while(current){if(current.attributes.disabled===true||current.attributes.loading===true||!guard(current.attributes.enabledWhen,current,state))return false;current=current.parent?nodes.get(current.parent):void 0}return true}function active(node,state){if(!visible(node,state)||!enabled(node,state))return false;const modal=state.overlays.filter(overlay=>overlay.modal).at(-1);return!modal||descendant(node.id,modal.id)}function focusable(node,state){return active(node,state)&&(["input","textarea","select","checkbox","radio","switch","slider","button","link","nav-item","dropdown-item","page","modal","drawer","popover","dropdown","tabs","tab","accordion"].includes(node.kind)||node.attributes.scroll===true)}function controlValue(node,state){var _a,_b,_c,_d;const raw=(_a=state.controls[node.id])!=null?_a:{value:"",checked:false},bind=record(node.attributes.bind),binding=node.bindings[scalar(bind.state)];if(!binding||state.invalid[node.id]||raw.pending)return raw;const value=state.states[binding.key];if(node.kind==="radio")return{value:(_b=node.attributes.value)!=null?_b:"",checked:canonical(value)===canonical((_c=node.attributes.value)!=null?_c:"")};return bind.property==="checked"?{value:(_d=node.attributes.value)!=null?_d:"",checked:value===true}:{value,checked:raw.checked}}function view(state){const result={visible:{},enabled:{},controls:{},states:state.states,data:{}};for(const node of program2.nodes){result.visible[node.id]=visible(node,state);result.enabled[node.id]=enabled(node,state);result.controls[node.id]=controlValue(node,state);if(node.attributes.data)result.data[node.id]=expression(node.attributes.data,node,state)}return result}function append(state,node,handler,operation,event,result,diagnostic=null,before=state.states){var _a,_b,_c,_d,_e,_f;const delta={};for(const[key,value]of Object.entries(state.states))if(canonical(before[key])!==canonical(value))delta[key]=((_a=program2.states[key])==null?void 0:_a.sensitive)?"[redacted]":value;const normalized=clone(event),binding=node==null?void 0:node.bindings[scalar(record(node==null?void 0:node.attributes.bind).state)];if((binding==null?void 0:binding.sensitive)||(node==null?void 0:node.attributes.inputType)==="password"){if("value"in normalized)normalized.value="[redacted]";if("checked"in normalized)normalized.checked="[redacted]"}state.trace.push({schemaVersion:"1.0.0",appId:program2.appId,modelDigest:program2.modelDigest,profileDigest:program2.profileDigest,sequence:++state.sequence,resetGeneration:state.resetGeneration,virtualTime:state.virtualTime,route:clone(state.route),source:(_b=node==null?void 0:node.identity)!=null?_b:null,renderedId:(_c=node==null?void 0:node.id)!=null?_c:null,handlerId:(_d=handler==null?void 0:handler.id)!=null?_d:null,operationId:(_e=operation==null?void 0:operation.id)!=null?_e:null,executionClass:(_f=operation==null?void 0:operation.executionClass)!=null?_f:"runtime",event:normalized,stateDeltaDigest:hash(canonical(delta)),result,diagnostic});if(diagnostic)state.diagnostic=diagnostic}function write(state,binding,value,requestId){if(!binding)throw Error("missing-state");const held=state.reservations[binding.key];if(held&&held!==requestId)throw Error("state-busy");bounded(value);const valid=binding.type==="list"?Array.isArray(value):binding.type==="record"?value!==null&&typeof value==="object"&&!Array.isArray(value):typeof value===binding.type;if(!valid)throw Error("state-type");state.states[binding.key]=clone(value)}let microsteps=0;function tick(){if(++microsteps>256)throw Error("limit-microsteps")}function enqueue(state,item){if(state.queue.length>=4096)throw Error("limit-queue");state.queue.push(item)}function fieldError(node,state){var _a,_b;const attrs=node.attributes,control=controlValue(node,state);if(!visible(node,state)||!enabled(node,state)||attrs.readonly===true)return null;const value=control.value,text=scalar(value),type=node.kind==="input"?scalar((_a=attrs.inputType)!=null?_a:"text"):node.kind;if(attrs.required===true&&(["checkbox","switch"].includes(type)&&!control.checked||type==="radio"&&!program2.nodes.some(other=>other.kind==="radio"&&other.form===node.form&&other.attributes.name===attrs.name&&controlValue(other,state).checked)||!["checkbox","switch","radio"].includes(type)&&text===""))return"required";if(text==="")return null;if(typeof attrs.minLength==="number"&&Array.from(text).length<attrs.minLength)return"too-short";if(typeof attrs.maxLength==="number"&&Array.from(text).length>attrs.maxLength)return"too-long";if(type==="email"&&!/^[a-zA-Z0-9.!#$%&\'*+\\-/=?^_`{|}~]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*$/.test(text))return"email";if(type==="url"){try{const url=new URL(text);if(!url.protocol)return"url"}catch(error){void error;return"url"}}if(type==="date"){const match=/^(\\d{4,})-(\\d\\d)-(\\d\\d)$/.exec(text);if(!match)return"date";const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),days=[31,year%4===0&&(year%100!==0||year%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(year<1||month<1||month>12||day<1||day>((_b=days[month-1])!=null?_b:0))return"date"}if(type==="number"||type==="slider"){const number=typeof value==="number"?value:Number(text);if(!Number.isFinite(number))return"number";const min=typeof attrs.min==="number"?attrs.min:type==="slider"?0:void 0,max=typeof attrs.max==="number"?attrs.max:type==="slider"?100:void 0,step=typeof attrs.step==="number"?attrs.step:1;if(min!==void 0&&number<min)return"range-underflow";if(max!==void 0&&number>max)return"range-overflow";const remainder=(number-(min!=null?min:0))/step;if(Math.abs(remainder-Math.round(remainder))>1e-9)return"step-mismatch"}if(node.kind==="select"&&!attrs.options.some(option=>option.disabled!==true&&canonical(option.value)===canonical(value)))return"option";return null}function validateForm(state,form){let first;for(const control of program2.nodes.filter(node=>node.form===form.id&&["input","textarea","select","checkbox","radio","switch","slider"].includes(node.kind))){const error=fieldError(control,state);if(error){state.invalid[control.id]=error;first!=null?first:first=control}else delete state.invalid[control.id]}if(first){state.invalid[form.id]="form-invalid";state.focus=first.id;return false}delete state.invalid[form.id];return true}function normalizeControl(state,node,event){var _a,_b;const bind=record(node.attributes.bind),target=node.bindings[scalar(bind.state)],previous=(_a=state.controls[node.id])!=null?_a:{value:"",checked:false};const raw={value:Object.hasOwn(event,"value")?event.value:previous.value,checked:typeof event.checked==="boolean"?event.checked:previous.checked,pending:!!target&&bind.update!==event.type};if(node.attributes.readonly===true)throw Error("readonly-control");state.controls[node.id]=raw;if(!target||bind.update!==event.type)return;if(node.kind==="radio"&&!raw.checked)return;let value=bind.property==="checked"?raw.checked:raw.value;if(node.kind==="radio")value=(_b=node.attributes.value)!=null?_b:"";else if(node.kind==="select"){const option=node.attributes.options.find(option2=>option2.disabled!==true&&scalar(option2.value)===scalar(raw.value));if(!option)throw Error("option");value=option.value}else if(target.type==="number"){if(value===""){state.invalid[node.id]="number";throw Error("invalid-edit")}value=typeof value==="number"?value:Number(value);if(!Number.isFinite(value)){state.invalid[node.id]="number";throw Error("invalid-edit")}}else if(target.type==="boolean"&&bind.property!=="checked"){if(![true,false,"true","false"].includes(value))throw Error("state-type");value=value===true||value==="true"}const check=clone(state);delete check.invalid[node.id];check.controls[node.id]={...raw,value};if(target)check.states[target.key]=value;const error=fieldError(node,check);if(error&&["too-short","too-long","range-underflow","range-overflow","step-mismatch","number","option"].includes(error)){state.invalid[node.id]=error;throw Error("invalid-edit")}write(state,target,value);raw.pending=false;delete state.invalid[node.id]}function resolveTarget(node,effect){const target=record(effect.target),id=node.targets[scalar(target.scope)+":"+scalar(target.id)],resolved=nodes.get(id!=null?id:"");if(!resolved)throw Error("missing-target");return resolved}function openOverlay(state,target,opener){var _a,_b;if(state.overlays.some(overlay=>overlay.id===target.id))return;if(!roots(state).includes(target.root)||!guard(target.attributes.visibleWhen,target,state)||target.parent&&!visible(nodes.get(target.parent),state))throw Error("inactive-target");const modal=target.kind==="modal"||target.kind==="drawer"&&target.attributes.modal!==false;state.overlays.push({id:target.id,opener:opener.id,modal});if(target.kind==="tooltip")return;const initial2=nodes.get((_a=target.targets.initialFocus)!=null?_a:"");const first=initial2!=null?initial2:program2.nodes.find(node=>node.id!==target.id&&descendant(node.id,target.id)&&focusable(node,state));if(initial2&&!focusable(initial2,state))throw Error("invalid-focus");state.focus=(_b=first==null?void 0:first.id)!=null?_b:target.id}function closeOverlay(state,target){var _a,_b;const index=state.overlays.findIndex(overlay=>overlay.id===target.id);if(index<0)return;const opener=state.overlays[index].opener;if(target.kind==="tooltip"){state.overlays.splice(index,1);return}state.overlays.splice(index);const candidate=opener?nodes.get(opener):void 0;state.focus=candidate&&focusable(candidate,state)?candidate.id:(_b=(_a=screenOf(state))==null?void 0:_a.id)!=null?_b:null}function schedule(state,node,activation,operation){var _a,_b,_c,_d,_e;const effect=operation.effect,fixture=fixtures.get(scalar(effect.fixtureRef));if(!fixture)throw Error("missing-fixture");if(Object.keys(state.requests).length>=128)throw Error("limit-requests");const output=[scalar(effect.resultState),scalar(effect.statusState),scalar(effect.errorState)].map(ref=>node.bindings[ref]);if(output.some(item=>!item)||new Set(output.map(item=>item.key)).size!==3)throw Error("fixture-output-alias");for(const item of output)if(state.reservations[item.key])throw Error("state-busy");const cursor=(_a=state.fixtureCursors[fixture.id])!=null?_a:0,step=(_b=fixture.steps[cursor])!=null?_b:fixture.exhaustion==="repeat-last"?fixture.steps.at(-1):void 0;state.fixtureCursors[fixture.id]=cursor+1;const sequence=++state.requestSequence,id=state.resetGeneration+":"+sequence,timeout=Number(effect.timeoutMs);const deadline=state.virtualTime+timeout,responseAt=state.virtualTime+((_c=step==null?void 0:step.delayMs)!=null?_c:0);if(!Number.isSafeInteger(deadline)||!Number.isSafeInteger(responseAt))throw Error("limit-clock");const request={id,generation:state.resetGeneration,sequence,activation:activation.id,owner:node.id,operation:clone(operation),resultKey:output[0].key,statusKey:output[1].key,errorKey:output[2].key,deadline,responseAt,outcome:(_d=step==null?void 0:step.outcome)!=null?_d:"exhausted",value:clone((_e=step==null?void 0:step.value)!=null?_e:null)};for(const item of output)state.reservations[item.key]=id;write(state,output[1],"pending",id);write(state,output[2],{},id);state.requests[id]=request;state.scheduled.push({time:deadline,priority:0,sequence,requestId:id,generation:state.resetGeneration,owner:node.id,operationId:operation.id});if(request.outcome!=="timeout")state.scheduled.push({time:responseAt,priority:1,sequence,requestId:id,generation:state.resetGeneration,owner:node.id,operationId:operation.id});if(state.scheduled.length>4096)throw Error("limit-queue");state.activations[String(activation.id)]=clone(activation)}function applyOperation(state,node,activation,operation,segment){var _a;tick();const effect=operation.effect,kind=scalar(effect.kind),event=activation.event;if(kind==="specify")return"specified-unexecuted";if(kind==="simulate"){schedule(state,node,activation,operation);return"pending"}if(kind==="set"){write(state,node.bindings[scalar(effect.state)],expression(effect.value,node,state,event));return"succeeded"}if(kind==="reset"){const binding=node.bindings[scalar(effect.state)];write(state,binding,binding.initial);for(const child of program2.nodes)if(((_a=child.bindings[scalar(record(child.attributes.bind).state)])==null?void 0:_a.key)===binding.key)delete state.invalid[child.id];return"succeeded"}if(kind==="toggle"){const binding=node.bindings[scalar(effect.state)],value=state.states[binding.key];if(typeof value!=="boolean")throw Error("state-type");write(state,binding,!value);return"succeeded"}if(kind==="filter"||kind==="sort"){const source=state.states[node.bindings[scalar(effect.source)].key];if(!Array.isArray(source))throw Error("list-type");const field=scalar(effect.field);let result;if(kind==="filter"){const query=convert(expression(effect.query,node,state,event),"lower");for(const item of source)if(!Object.hasOwn(record(item),field)||typeof record(item)[field]!=="string")throw Error("filter-field-type");result=source.filter(item=>convert(record(item)[field],"lower").includes(query))}else{let type;for(const item of source){const value=record(item)[field];if(!Object.hasOwn(record(item),field)||!["number","string"].includes(typeof value)||type&&type!==typeof value)throw Error("sort-field-type");type=typeof value}result=source.map((value,index)=>({value,index})).sort((a,b)=>compare(record(a.value)[field],record(b.value)[field])*(effect.direction==="descending"?-1:1)||a.index-b.index).map(item=>item.value)}write(state,node.bindings[scalar(effect.target)],result);return"succeeded"}if(["open","close","toggleOverlay","focus","validate"].includes(kind)){const target=resolveTarget(node,effect);if(kind==="validate"){if(!active(target,state))throw Error("inactive-target");if(!validateForm(state,target))throw Error("form-invalid")}else if(kind==="focus"){if(!focusable(target,state))throw Error("invalid-focus");state.focus=target.id}else if(kind==="close"||kind==="toggleOverlay"&&state.overlays.some(item=>item.id===target.id))closeOverlay(state,target);else openOverlay(state,target,node);return"succeeded"}if(kind==="navigate"){const target=record(effect.target);if(target.kind==="url"){state.effects.push({kind:"external",fragment:scalar(target.url),sequence:0,delta:0});return"succeeded"}const route=target.screen;const fragment=routeAddress(route);if(!parseAddress(fragment))throw Error("missing-route");segment.route={fragment,mode:effect.history==="replace"?"replace":"push",index:null,browserSequence:null};return"succeeded"}if(kind==="navigateBack"||kind==="navigateForward"){const index=state.historyIndex+(kind==="navigateBack"?-1:1);if(index<0||index>=state.history.length)return"history-boundary";segment.route={fragment:state.history[index].fragment,mode:"traverse",index,browserSequence:null};return"succeeded"}if(kind==="resetScenario"){segment.reset=true;return"succeeded"}throw Error("unsupported-operation")}function cancelRequest(state,request,surviving,reset2=false){var _a,_b;for(const key of[request.resultKey,request.statusKey,request.errorKey])delete state.reservations[key];if(!reset2){for(const[key,value]of[[request.statusKey,"cancelled"],[request.errorKey,{code:"cancelled",value:null,operationId:request.operation.id}]]){const binding=program2.states[key];if(binding&&(binding.lifetime==="session"||surviving.includes(binding.root)))write(state,binding,value)}}const node=nodes.get(request.owner),activation=state.activations[String(request.activation)],handler=(_a=node.handlers.find(handler2=>handler2.id===(activation==null?void 0:activation.handlerId)))!=null?_a:null;delete state.requests[request.id];state.scheduled=state.scheduled.filter(item=>item.requestId!==request.id||item.priority===1);delete state.activations[String(request.activation)];state.queue=state.queue.filter(item=>item.source!==request.owner);append(state,node,handler,request.operation,(_b=activation==null?void 0:activation.event)!=null?_b:{},"cancelled")}function ensureFocus(state,previous,observed){var _a,_b,_c;for(const overlay of[...state.overlays]){const node=nodes.get(overlay.id);if(node&&!visible(node,state))closeOverlay(state,node)}let target=state.focus?nodes.get(state.focus):void 0;if(target&&!focusable(target,state)){while(target==null?void 0:target.parent){target=nodes.get(target.parent);if(target&&focusable(target,state))break}state.focus=target&&focusable(target,state)?target.id:(_b=(_a=screenOf(state))==null?void 0:_a.id)!=null?_b:null}if(state.focus!==previous.focus){for(const[source,type]of[[previous.focus,"blur"],[state.focus,"focus"]]){if(!source||(observed==null?void 0:observed.source)===source&&observed.type===type||!((_c=nodes.get(source))==null?void 0:_c.handlers.some(handler=>handler.event===type))||state.queue.some(item=>item.source===source&&item.event.type===type&&item.handlerId===null))continue;enqueue(state,{source,event:{type},handlerId:null})}}}function lifecycle(state,ids,event){for(const id of ids){const node=nodes.get(id!=null?id:"");if(!node)continue;const handler=node.handlers.find(handler2=>handler2.event===event);if(!handler)continue;tick();if(!guard(handler.guard,node,state))continue;const activation={id:++state.activationSequence,owner:node.id,handlerId:handler.id,event:{type:event},index:0,statuses:{}},segment={route:null,reset:false};for(const operation of handler.operations){const before=clone(state.states);if(operation.after.some(id2=>activation.statuses[id2]!=="succeeded")){activation.statuses[operation.id]="skipped-dependency";append(state,node,handler,operation,activation.event,"skipped-dependency");continue}try{const result=applyOperation(state,node,activation,operation,segment);activation.statuses[operation.id]=result;append(state,node,handler,operation,activation.event,result,null,before)}catch(error){activation.statuses[operation.id]="failed";append(state,node,handler,operation,activation.event,"failed",error.message);if(operation.onFailure==="stop")throw error}}if(segment.route||segment.reset)throw Error("exit-effect")}}function changeRoute(state,request){var _a;const route=parseAddress(request.fragment),current=screenOf(state),next=program2.screens.find(screen=>screen.route.namespace===(route==null?void 0:route.namespace)&&screen.route.id===(route==null?void 0:route.id));const identical=canonical(state.route)===canonical(route)&&state.address===(request.fragment||routeAddress(program2.entry));if(identical&&request.mode==="push")return;const departed=(current==null?void 0:current.id)!==(next==null?void 0:next.id),oldRoots=roots(state),nextRoots=next?["app","screen/"+next.route.namespace+"/"+next.route.id,...next.shell?[program2.shells.find(shell=>shell.id===next.shell).root]:[]]:["app"];if(departed){for(const pending of Object.values(state.requests))if(!nextRoots.includes(nodes.get(pending.owner).root))cancelRequest(state,pending,nextRoots);lifecycle(state,[current==null?void 0:current.id,(current==null?void 0:current.shell)!==(next==null?void 0:next.shell)?current==null?void 0:current.shell:null],"exit");state.overlays=state.overlays.filter(overlay=>nextRoots.includes(nodes.get(overlay.id).root));for(const binding of Object.values(program2.states))if(binding.lifetime==="mount"&&oldRoots.includes(binding.root)&&!nextRoots.includes(binding.root))state.states[binding.key]=clone(binding.initial);for(const node of program2.nodes)if(oldRoots.includes(node.root)&&!nextRoots.includes(node.root)){delete state.invalid[node.id];state.controls[node.id]=initialControl(node)}state.queue=state.queue.filter(item=>{var _a2,_b;return nextRoots.includes((_b=(_a2=nodes.get(item.source))==null?void 0:_a2.root)!=null?_b:"")})}state.route=route;state.address=request.fragment||routeAddress(program2.entry);if(request.mode==="push"){state.history=state.history.slice(0,state.historyIndex+1);const sequence=state.nextHistorySequence++;state.history.push({fragment:state.address,sequence});state.historyIndex=state.history.length-1;state.effects.push({kind:"push",fragment:state.address,sequence,delta:0})}else if(request.mode==="replace"){const sequence=state.history[state.historyIndex].sequence;state.history[state.historyIndex]={fragment:state.address,sequence};state.effects.push({kind:"replace",fragment:state.address,sequence,delta:0})}else if(request.index!==null){const delta=request.index-state.historyIndex;state.historyIndex=request.index;if(request.mode==="traverse")state.effects.push({kind:"traverse",fragment:state.address,sequence:state.history[request.index].sequence,delta})}else{const sequence=state.nextHistorySequence++;state.history=[{fragment:state.address,sequence}];state.historyIndex=0;state.effects.push({kind:"replace",fragment:state.address,sequence,delta:0})}if(departed&&next){if((current==null?void 0:current.shell)!==next.shell&&next.shell)enqueue(state,{source:next.shell,event:{type:"enter"},handlerId:null});enqueue(state,{source:next.id,event:{type:"enter"},handlerId:null})}if(departed)state.focus=(_a=next==null?void 0:next.id)!=null?_a:null}function initialControl(node){var _a,_b,_c,_d;return{value:(_d=node.attributes.value)!=null?_d:node.kind==="select"?Array.isArray(node.attributes.options)?(_b=(_a=node.attributes.options.map(record).find(option=>option.disabled!==true))==null?void 0:_a.value)!=null?_b:"":"":["slider","progress"].includes(node.kind)?(_c=node.attributes.min)!=null?_c:0:"",checked:node.attributes.checked===true}}function fresh(fragment=routeAddress(program2.entry)){var _a,_b;const route=parseAddress(fragment),state={modelDigest:program2.modelDigest,profileDigest:program2.profileDigest,resetGeneration:0,virtualTime:Number(program2.profile.clockStartMs),sequence:0,requestSequence:0,activationSequence:0,states:{},controls:{},invalid:{},route,address:fragment||routeAddress(program2.entry),history:[{fragment:fragment||routeAddress(program2.entry),sequence:0}],historyIndex:0,nextHistorySequence:1,overlays:[],focus:null,selection:{},expanded:{},viewMode:"fixed",fixtureCursors:{},requests:{},reservations:{},activations:{},queue:[],scheduled:[],trace:[],effects:[],diagnostic:null,suspended:false};for(const[key,binding]of Object.entries(program2.states))state.states[key]=clone(binding.initial);for(const node of program2.nodes){state.controls[node.id]=initialControl(node);if(node.kind==="tabs")state.selection[node.id]=Number((_a=node.attributes.active)!=null?_a:0);state.expanded[node.id]=node.attributes.expanded===true||node.attributes.dismissible===true}const screen=screenOf(state);state.focus=(_b=screen==null?void 0:screen.id)!=null?_b:null;if(screen==null?void 0:screen.shell)enqueue(state,{source:screen.shell,event:{type:"enter"},handlerId:null});if(screen)enqueue(state,{source:screen.id,event:{type:"enter"},handlerId:null});return state}function reset(state){const next=fresh(),previousTrace=state.trace;next.resetGeneration=state.resetGeneration+1;next.sequence=state.sequence;next.trace=previousTrace;next.nextHistorySequence=state.nextHistorySequence+1;next.history[0].sequence=state.nextHistorySequence;next.effects=[{kind:"replace",fragment:next.address,sequence:next.history[0].sequence,delta:0}];Object.assign(state,next);append(state,null,null,null,{type:"reset"},"succeeded")}function runHandler(state,node,handler,event,resumed){var _a;tick();if(!resumed&&!["input","change"].includes(scalar(event.type))&&Object.values(state.requests).some(request=>{var _a2;return request.owner===node.id&&((_a2=state.activations[String(request.activation)])==null?void 0:_a2.handlerId)===handler.id})){if(handler.concurrency==="queue")enqueue(state,{source:node.id,event:clone(event),handlerId:handler.id});else append(state,node,handler,null,event,"busy","busy");return}const before=clone(state),draft=clone(state),segment={route:null,reset:false},records=[];const activation=resumed?clone(resumed):{id:++draft.activationSequence,owner:node.id,handlerId:handler.id,event:clone(event),index:0,statuses:{}};let pending=false;try{if(!resumed&&["input","change"].includes(scalar(event.type)))normalizeControl(draft,node,event);const busy=Object.values(draft.requests).some(request=>{var _a2;return request.owner===node.id&&((_a2=draft.activations[String(request.activation)])==null?void 0:_a2.handlerId)===handler.id});if(!resumed&&busy){if(handler.concurrency==="queue"){enqueue(draft,{source:node.id,event:clone(event),handlerId:handler.id});Object.assign(state,draft);return}Object.assign(state,draft);append(state,node,handler,null,event,"busy","busy",before.states);return}if(!resumed&&!guard(handler.guard,node,draft,event)){Object.assign(state,draft);for(const operation of handler.operations)append(state,node,handler,operation,event,"guard-false",null,before.states);return}for(let index=activation.index;index<handler.operations.length;index++){const operation=handler.operations[index];activation.index=index+1;if(operation.after.some(id=>activation.statuses[id]!=="succeeded")){activation.statuses[operation.id]="skipped-dependency";records.push({operation,result:"skipped-dependency",code:null});continue}const prior=clone(draft),priorSegment=clone(segment);try{const result=applyOperation(draft,node,activation,operation,segment);activation.statuses[operation.id]=result;records.push({operation,result,code:result==="history-boundary"?"history-boundary":null});if(result==="pending"){pending=true;draft.activations[String(activation.id)]=clone(activation);break}if(segment.reset||(result==="specified-unexecuted"||result==="history-boundary")&&operation.onFailure==="stop")break}catch(error){const validation=clone(draft.invalid),focus=draft.focus;Object.assign(draft,prior);Object.assign(segment,priorSegment);if(error.message==="form-invalid"){draft.invalid=validation;draft.focus=focus}activation.statuses[operation.id]="failed";records.push({operation,result:"failed",code:error.message});if(operation.onFailure==="stop")throw error}}if(segment.route)changeRoute(draft,segment.route);view(draft);ensureFocus(draft,before,{source:node.id,type:scalar(event.type)});if(!pending)delete draft.activations[String(activation.id)];Object.assign(state,draft);for(const item of records)append(state,node,handler,item.operation,event,item.result,item.code,before.states);if(segment.reset)reset(state)}catch(error){const code=error.message;if(code==="invalid-edit"){state.controls[node.id]=draft.controls[node.id];state.invalid[node.id]=draft.invalid[node.id];append(state,node,handler,null,event,"failed","invalid-edit");return}if(code==="form-invalid"){state.invalid=clone(draft.invalid);state.focus=draft.focus}if(resumed)delete state.activations[String(activation.id)];if(!records.length)append(state,node,handler,null,event,"failed",code);for(const item of records)append(state,node,handler,item.operation,event,item.result==="succeeded"||item.result==="pending"?"cancelled":item.result,(_a=item.code)!=null?_a:item.result==="succeeded"?null:code);if(!records.some(item=>item.code===code))append(state,node,handler,null,event,"failed",code);if(code.startsWith("limit-"))throw error}}function composite(state,node,event){const type=event.type,key=event.key;if(node.kind==="accordion"&&type==="click")state.expanded[node.id]=!state.expanded[node.id];if(["alert","toast"].includes(node.kind)&&node.attributes.dismissible===true&&type==="click")state.expanded[node.id]=false;const tabs=node.kind==="tab"&&node.parent?nodes.get(node.parent):node.kind==="tabs"?node:void 0;if((tabs==null?void 0:tabs.kind)==="tabs"){const list=tabs.children.map(id=>nodes.get(id)).filter(child=>child.kind==="tab"&&enabled(child,state));const selected=list.findIndex(child=>child.id===node.id),current=selected<0?0:selected;const backwards=tabs.attributes.vertical===true?"ArrowUp":"ArrowLeft",forwards=tabs.attributes.vertical===true?"ArrowDown":"ArrowRight";let next=current;if(type==="keydown"&&key===backwards)next=(current-1+list.length)%list.length;else if(type==="keydown"&&key===forwards)next=(current+1)%list.length;else if(type==="keydown"&&key==="Home")next=0;else if(type==="keydown"&&key==="End")next=list.length-1;if(type==="click"||type==="keydown"&&["Enter"," "].includes(scalar(key)))state.selection[tabs.id]=tabs.children.filter(id=>{var _a;return((_a=nodes.get(id))==null?void 0:_a.kind)==="tab"}).indexOf(node.id);if(list[next])state.focus=list[next].id}if(node.kind==="dropdown"&&(type==="click"||type==="keydown"&&["Enter"," ","ArrowDown","ArrowUp"].includes(scalar(key)))){if(state.overlays.some(overlay=>overlay.id===node.id)&&type==="click")closeOverlay(state,node);else openOverlay(state,node,node)}let menu=node;while(menu&&menu.kind!=="dropdown")menu=menu.parent?nodes.get(menu.parent):void 0;if(menu&&node.kind==="dropdown-item"&&type==="click")closeOverlay(state,menu);if(menu&&state.overlays.some(overlay=>overlay.id===menu.id)&&type==="keydown"){const list=program2.nodes.filter(candidate=>candidate.kind==="dropdown-item"&&descendant(candidate.id,menu.id)&&enabled(candidate,state));let index=list.findIndex(candidate=>candidate.id===node.id);if(key==="ArrowDown")index=(index+1)%list.length;else if(key==="ArrowUp")index=(index-1+list.length)%list.length;else if(key==="Home")index=0;else if(key==="End")index=list.length-1;else index=-1;if(list[index])state.focus=list[index].id}if(type==="keydown"&&key==="Escape"){const top=state.overlays.at(-1),target=top?nodes.get(top.id):void 0;if(target&&target.attributes.dismissible!==false)closeOverlay(state,target)}const tooltip=node.parent?nodes.get(node.parent):void 0;if((tooltip==null?void 0:tooltip.kind)==="tooltip"){if(type==="focus")openOverlay(state,tooltip,node);else if(type==="blur")closeOverlay(state,tooltip)}if(type==="focus")state.focus=node.id;else if(type==="blur"&&state.focus===node.id)state.focus=null}function dispatch(state,node,event,handlerId=null){var _a;tick();const internal=["enter","exit"].includes(scalar(event.type));if(!internal&&!active(node,state)){append(state,node,null,null,event,"failed","inactive-owner");return}if(internal&&!roots(state).includes(node.root))return;const handlers=node.handlers.filter(handler=>handlerId?handler.id===handlerId:handler.event===event.type&&(handler.event!=="keydown"||handler.key===event.key));if(event.type==="submit"){const validated=clone(state);if(!validateForm(validated,node)){state.invalid=validated.invalid;state.focus=validated.focus;append(state,node,null,null,event,"failed","form-invalid");return}state.invalid=validated.invalid;if(state.diagnostic==="form-invalid")state.diagnostic=null}const previous={...state,states:{...state.states}};composite(state,node,event);if(!handlers.length&&["input","change"].includes(scalar(event.type))){const draft=clone(state);try{normalizeControl(draft,node,event);view(draft);Object.assign(state,draft);append(state,node,null,null,event,"succeeded",null,previous.states)}catch(error){const code=error.message;if(code==="invalid-edit"){state.controls[node.id]=draft.controls[node.id];state.invalid[node.id]=draft.invalid[node.id]}append(state,node,null,null,event,"failed",code)}}for(const handler of handlers)runHandler(state,node,handler,event);if(event.type==="keydown"&&node.kind==="dropdown-item"&&["Enter"," "].includes(scalar(event.key)))enqueue(state,{source:node.id,event:{type:"click"},handlerId:null});if(event.type==="click"&&node.kind==="button"&&(node.attributes.buttonType==="submit"||node.attributes.action==="submit")&&!handlers.some(handler=>handler.event==="click")){const form=nodes.get((_a=node.form)!=null?_a:"");if(form)enqueue(state,{source:form.id,event:{type:"submit"},handlerId:null})}if(event.type==="click"&&node.kind==="button"&&node.attributes.buttonType==="reset"){for(const child of program2.nodes.filter(child2=>child2.form===node.form)){const target=child.bindings[scalar(record(child.attributes.bind).state)];if(target)write(state,target,target.initial);state.controls[child.id]=initialControl(child);delete state.invalid[child.id]}}ensureFocus(state,previous,{source:node.id,type:scalar(event.type)})}function drain(state){let blocked=0;while(state.queue.length){if(blocked>=state.queue.length)break;const next=state.queue.shift(),node=nodes.get(next.source);if(!node)continue;if(next.handlerId&&Object.values(state.requests).some(request=>{var _a;return request.owner===node.id&&((_a=state.activations[String(request.activation)])==null?void 0:_a.handlerId)===next.handlerId})){state.queue.push(next);blocked++;continue}blocked=0;dispatch(state,node,next.event,next.handlerId)}}function completion(state,due){var _a,_b,_c;const request=state.requests[due.requestId],node=(_a=nodes.get(due.owner))!=null?_a:null;if(!request||request.generation!==state.resetGeneration){const handler2=(_b=node==null?void 0:node.handlers.find(handler3=>handler3.operations.some(operation=>operation.id===due.operationId)))!=null?_b:null;if(due.priority===1)append(state,node,handler2,(_c=handler2==null?void 0:handler2.operations.find(operation=>operation.id===due.operationId))!=null?_c:null,{type:"fixture-response",requestId:due.requestId},"stale-response","stale-response");return}const activation=state.activations[String(request.activation)],owner=nodes.get(request.owner),handler=owner.handlers.find(handler2=>handler2.id===(activation==null?void 0:activation.handlerId));if(!activation||!handler||!roots(state).includes(owner.root)){cancelRequest(state,request,roots(state));append(state,owner,handler!=null?handler:null,request.operation,{type:"fixture-response"},"stale-response","stale-response");return}const before=clone(state.states),timedOut=due.priority===0,success=!timedOut&&request.outcome==="success";for(const key of[request.resultKey,request.statusKey,request.errorKey])delete state.reservations[key];delete state.requests[request.id];state.scheduled=state.scheduled.filter(item=>item.requestId!==request.id||timedOut&&item.priority===1);const code=success?null:timedOut?"timeout":request.outcome==="exhausted"?"fixture-exhausted":"fixture-error";if(success)write(state,program2.states[request.resultKey],request.value);write(state,program2.states[request.statusKey],success?"succeeded":"failed");write(state,program2.states[request.errorKey],success?{}:{code,value:timedOut||request.outcome==="exhausted"?null:request.value,operationId:request.operation.id});activation.statuses[request.operation.id]=success?"succeeded":"failed";append(state,owner,handler,request.operation,activation.event,success?"succeeded":"failed",code,before);if(!success&&request.operation.onFailure==="stop")delete state.activations[String(activation.id)];else runHandler(state,owner,handler,activation.event,activation);drain(state)}function initial(fragment){microsteps=0;const state=fresh(fragment);try{drain(state)}catch(error){state.queue=[];append(state,null,null,null,{type:"initial"},"failed",error.message)}state.effects=[];return state}function reduce(previous,input,browserSequence=null){const state=clone(previous);state.effects=[];microsteps=0;try{if(!input||typeof input!=="object"||Array.isArray(input))throw Error("input-shape");const keys=input.kind==="reset"?["kind"]:input.kind==="advanceClock"?["kind","deltaMs"]:input.kind==="address"?["kind","fragment"]:input.kind==="event"?["kind","source","event","key","value","checked"]:[];if(!keys.length||Object.keys(input).some(key=>!keys.includes(key)))throw Error("input-shape");if(state.suspended&&input.kind!=="address"&&input.kind!=="reset"){append(state,null,null,null,{type:input.kind},"busy","history-compensation");return state}state.diagnostic=null;if(input.kind==="reset"){reset(state);drain(state);return state}if(input.kind==="advanceClock"){if(!Number.isInteger(input.deltaMs)||input.deltaMs<0||input.deltaMs>6e5||!Number.isSafeInteger(state.virtualTime+input.deltaMs))throw Error("limit-clock");const target=state.virtualTime+input.deltaMs;for(;;){state.scheduled.sort((a,b)=>a.time-b.time||a.priority-b.priority||a.sequence-b.sequence);const due=state.scheduled[0];if(!due||due.time>target)break;state.scheduled.shift();state.virtualTime=due.time;microsteps=0;completion(state,due)}state.virtualTime=target;return state}if(input.kind==="address"){if(typeof input.fragment!=="string")throw Error("input-shape");bounded(input.fragment);const fragment=input.fragment||routeAddress(program2.entry);if(state.suspended&&fragment===state.address&&browserSequence===state.history[state.historyIndex].sequence){state.suspended=false;return state}const index=browserSequence===null?-1:state.history.findIndex(entry=>entry.sequence===browserSequence&&entry.fragment===fragment);try{changeRoute(state,{fragment:input.fragment,mode:"address",index:index<0?null:index,browserSequence});ensureFocus(state,previous);drain(state);return state}catch(error){const restored=clone(previous);restored.effects=[];const code=error.message;append(restored,null,null,null,{type:"address",fragment:input.fragment},"failed",code);if(index>=0){restored.suspended=true;restored.effects.push({kind:"compensate",fragment:restored.address,sequence:restored.history[restored.historyIndex].sequence,delta:restored.historyIndex-index})}else{const sequence=restored.nextHistorySequence++;restored.history=[{fragment:restored.address,sequence}];restored.historyIndex=0;restored.effects.push({kind:"replace",fragment:restored.address,sequence,delta:0})}return restored}}const node=byIdentity.get(canonical(input.source));if(!node)throw Error("unknown-source");if(!["click","input","change","submit","keydown","focus","blur"].includes(input.event))throw Error("event-type");if("value"in input){if(input.value===void 0)throw Error("event-payload");bounded(input.value)}if("checked"in input&&typeof input.checked!=="boolean")throw Error("event-payload");if("key"in input&&typeof input.key!=="string")throw Error("event-payload");if(input.event==="keydown"&&(typeof input.key!=="string"||"value"in input||"checked"in input))throw Error("event-payload");if(!["input","change","keydown"].includes(input.event)&&("value"in input||"checked"in input||"key"in input))throw Error("event-payload");if(["input","change"].includes(input.event)&&!["input","textarea","select","checkbox","radio","switch","slider"].includes(node.kind))throw Error("event-owner");if(["input","change"].includes(input.event)){const booleanControl=["checkbox","radio","switch"].includes(node.kind);if("key"in input)throw Error("event-payload");if(booleanControl&&"value"in input)throw Error("event-payload");if(!booleanControl&&"checked"in input)throw Error("event-payload")}if(input.event==="submit"&&node.kind!=="form")throw Error("event-owner");const event={type:input.event};if(input.value!==void 0){event.value=input.value}if(input.checked!==void 0)event.checked=input.checked;if(input.key!==void 0)event.key=input.key;dispatch(state,node,event);drain(state);view(state);return state}catch(error){const restored=clone(previous);restored.effects=[];append(restored,null,null,null,{type:scalar(record(input).kind)||"invalid"},"failed",error.message);return restored}}function hover(previous,id,open){const state=clone(previous),node=nodes.get(id);state.effects=[];if((node==null?void 0:node.kind)==="tooltip"&&active(node,state)){if(open)openOverlay(state,node,node);else closeOverlay(state,node)}return state}return{initial,reduce,view,parseAddress,routeAddress,hover}}function browserAdapter(engine,program2){const root=document.getElementById("wireweave-app"),storage=root.querySelector("[data-wf-screen-storage]");const nodes=new Map(program2.nodes.map(node=>[node.id,node]));let state=engine.initial(location.hash),projecting=false,processing=false,paused=false,last=performance.now(),timer;let projectedFocus;let projectionTimer;const queue=[];let composition=null;const present=value=>value==null?"":typeof value==="object"?JSON.stringify(value):String(value);function element(id){return document.getElementById(id)}function focusElement(id){const node=nodes.get(id);if((node==null?void 0:node.kind)==="tab")return document.getElementById(id+"-tab");if((node==null?void 0:node.kind)==="dropdown")return document.getElementById(id+"-trigger");return element(id)}function pendingFor(id){for(const request of Object.values(state.requests)){let owner2=nodes.get(request.owner);while(owner2){if(owner2.id===id)return true;owner2=owner2.parent?nodes.get(owner2.parent):void 0}}return false}function metadata(sequence){return{wireweave:{modelDigest:program2.modelDigest,sequence}}}function browserSequence(){const outer=history.state;const value=outer&&typeof outer==="object"?outer.wireweave:void 0;if(!value||typeof value!=="object")return null;const entry=value;return entry.modelDigest===program2.modelDigest&&typeof entry.sequence==="number"&&Number.isInteger(entry.sequence)?entry.sequence:null}function effectCommands(){for(const effect of state.effects){if(effect.kind==="push")history.pushState(metadata(effect.sequence),"",effect.fragment);else if(effect.kind==="replace")history.replaceState(metadata(effect.sequence),"",effect.fragment);else if(effect.kind==="traverse"||effect.kind==="compensate"){if(effect.delta!==0)history.go(effect.delta);else history.replaceState(metadata(effect.sequence),"",effect.fragment)}else location.assign(effect.fragment)}}function render(){var _a,_b,_c,_d,_e,_f,_g,_h;if(projectionTimer!==void 0){clearTimeout(projectionTimer);projectionTimer=void 0}projecting=true;try{const view=engine.view(state),active=program2.screens.find(screen=>{var _a2,_b2;return screen.route.namespace===((_a2=state.route)==null?void 0:_a2.namespace)&&screen.route.id===((_b2=state.route)==null?void 0:_b2.id)});for(const wrapper of root.querySelectorAll("[data-wf-screen]")){const visible=wrapper.contains(element((_a=active==null?void 0:active.id)!=null?_a:""));wrapper.hidden=!visible;wrapper.inert=!visible;if(!visible&&wrapper.parentElement!==storage)storage.append(wrapper)}for(const wrapper of root.querySelectorAll("[data-wf-shell]")){const visible=!!(active==null?void 0:active.shell)&&wrapper.contains(element(active.shell));wrapper.hidden=!visible;wrapper.inert=!visible}if(active){const screen=element(active.id).closest("[data-wf-screen]");if(active.shell){const shell=program2.shells.find(shell2=>shell2.id===active.shell);const slot=element(shell.slot);if(screen.parentElement!==slot)slot.append(screen)}else if(screen.parentElement!==storage)storage.append(screen);screen.hidden=false;screen.inert=false}const routeError=root.querySelector("[data-wf-route-error]");routeError.hidden=state.route!==null;root.querySelector("[data-wf-invalid-address]").textContent=state.address;root.setAttribute("data-wf-route",state.route?state.address:"error");root.setAttribute("data-wf-view",state.viewMode);root.setAttribute("aria-busy",String(state.suspended||Object.keys(state.requests).length>0));for(const node of program2.nodes){const el=element(node.id);if(!el)continue;el.hidden=view.visible[node.id]!==true;const pending=pendingFor(node.id);if(pending||node.attributes.loading===true){el.setAttribute("aria-busy","true");if(pending)el.setAttribute("data-wf-pending","true");else el.removeAttribute("data-wf-pending")}else{el.removeAttribute("aria-busy");el.removeAttribute("data-wf-pending")}const field=el.closest("[data-wf-field]");if(field)field.hidden=el.hidden;if(node.kind==="tab"){const owner2=nodes.get((_b=node.parent)!=null?_b:""),tabs=(_c=owner2==null?void 0:owner2.children.filter(id=>{var _a2;return((_a2=nodes.get(id))==null?void 0:_a2.kind)==="tab"}))!=null?_c:[],selected=tabs[(_e=state.selection[(_d=owner2==null?void 0:owner2.id)!=null?_d:""])!=null?_e:0]===node.id;el.hidden=!view.visible[node.id]||!selected;const button=document.getElementById(node.id+"-tab");if(button){button.setAttribute("aria-selected",String(selected));button.tabIndex=state.focus===node.id?0:tabs.includes((_f=state.focus)!=null?_f:"")?-1:selected?0:-1;button.disabled=!view.enabled[node.id]}}if("disabled"in el)el.disabled=view.enabled[node.id]!==true;const control=view.controls[node.id];if(["input","textarea","select","checkbox","radio","switch","slider"].includes(node.kind)){const input=el;if(["checkbox","radio","switch"].includes(node.kind))input.checked=control.checked;else if(!composition||composition.id!==node.id)input.value=present(control.value)}if(state.invalid[node.id]){el.setAttribute("aria-invalid","true");const message=element(node.id+"-error");if(message){message.textContent=state.invalid[node.id];message.hidden=false;el.setAttribute("aria-describedby",message.id)}}else{el.removeAttribute("aria-invalid");const message=element(node.id+"-error");if(message)message.hidden=true;el.removeAttribute("aria-describedby")}if(node.kind==="form"){const error=el.querySelector("[data-wf-form-error]");if(error){error.textContent=state.invalid[node.id]?"Check the required input values.":"";error.hidden=!state.invalid[node.id]}el.setAttribute("aria-busy",String(pending||node.attributes.loading===true))}if(node.kind==="accordion")el.open=state.expanded[node.id]===true;if(["modal","drawer","popover"].includes(node.kind)){const overlay=state.overlays.find(overlay2=>overlay2.id===node.id),dialog=el;if(overlay){dialog.hidden=false;if(!dialog.open){if(overlay.modal)dialog.showModal();else dialog.show()}dialog.setAttribute("aria-modal",String(overlay.modal))}else if(dialog.open)dialog.close()}if(node.kind==="dropdown"){const open=state.overlays.some(overlay=>overlay.id===node.id);const body=el.querySelector("[data-wf-overlay-body]");if(body)body.hidden=!open;const button=document.getElementById(node.id+"-trigger");button==null?void 0:button.setAttribute("aria-expanded",String(open))}if(node.kind==="tooltip"){const tooltip=el.querySelector("[role=tooltip]");if(tooltip)tooltip.hidden=!state.overlays.some(overlay=>overlay.id===node.id);const trigger=node.children[0]?element(node.children[0]):null;if(trigger&&tooltip)trigger.setAttribute("aria-describedby",tooltip.id)}if(node.attributes.dismissible===true&&["toast","alert"].includes(node.kind))el.hidden=el.hidden||state.expanded[node.id]===false;if(el instanceof HTMLAnchorElement){if(el.getAttribute("href")===state.address)el.setAttribute("aria-current","page");else el.removeAttribute("aria-current")}if(node.attributes.data){const value=view.data[node.id];if(node.kind==="table"&&Array.isArray(value)){const body=el.querySelector("tbody"),fragment=document.createDocumentFragment();for(const row of value){const tr=document.createElement("tr");for(const key of node.attributes.columns){const td=document.createElement("td");td.textContent=present(row[key]);tr.append(td)}fragment.append(tr)}body.replaceChildren(fragment)}else if(node.kind==="list"&&Array.isArray(value)){const fragment=document.createDocumentFragment();for(const item of value){const li=document.createElement("li");li.textContent=present(item);fragment.append(li)}el.replaceChildren(fragment)}else if(node.kind==="text"&&value!==void 0)el.textContent=present(value)}}for(const screen of program2.screens)(_g=element(screen.id))==null?void 0:_g.removeAttribute("role");if(active&&![...root.querySelectorAll("main")].some(main=>!main.closest("[hidden]")))(_h=element(active.id))==null?void 0:_h.setAttribute("role","main");const status=root.querySelector("[data-wf-runtime-status]");status.textContent=state.diagnostic?"The action could not complete: "+state.diagnostic:"";if(state.diagnostic)root.setAttribute("data-wf-runtime-diagnostic",state.diagnostic);else root.removeAttribute("data-wf-runtime-diagnostic");const lastTrace=state.trace.at(-1);if(lastTrace)root.setAttribute("data-wf-operation-result",lastTrace.result);document.getElementById("wf-runtime-trace").textContent=JSON.stringify(state.trace);if(state.focus&&state.focus!==projectedFocus){const focus=focusElement(state.focus);if(focus&&focus!==document.activeElement&&!focus.closest("[hidden],[inert]"))focus.focus()}else if(!state.route&&projectedFocus!==null){const heading=routeError.querySelector("h1");heading==null?void 0:heading.focus()}projectedFocus=state.focus}finally{projecting=false}}function apply(input,sequence=null,deferProjection=false){if(queue.length>=4096)throw Error("limit-queue");queue.push({input,sequence,deferProjection});if(processing)return;processing=true;try{while(queue.length){const item=queue.shift();state=engine.reduce(state,item.input,item.sequence);effectCommands();if(item.deferProjection){if(projectionTimer===void 0)projectionTimer=setTimeout(render,0)}else render()}}finally{processing=false}}function owner(target){var _a,_b;if(!(target instanceof Element))return void 0;const el=target.closest("[data-wf-event-owner], [data-wf-kind]");return nodes.get((_b=(_a=el==null?void 0:el.getAttribute("data-wf-event-owner"))!=null?_a:el==null?void 0:el.id)!=null?_b:"")}function nativeEvent(event){if(projecting)return;const node=owner(event.target);if(!node)return;const kind=event.type;const input={kind:"event",source:node.identity,event:kind};if(kind==="input"||kind==="change"){const control=event.target;if(event.isComposing)return;if((composition==null?void 0:composition.id)===node.id){if(composition.value===control.value){composition=null;return}composition=null}if(["checkbox","radio","switch"].includes(node.kind))input.checked=control.checked;else input.value=control.value}apply(input)}root.addEventListener("input",nativeEvent);root.addEventListener("change",nativeEvent);root.addEventListener("focus",nativeEvent,true);root.addEventListener("blur",nativeEvent,true);root.addEventListener("compositionstart",event=>{const node=owner(event.target);if(node)composition={id:node.id,value:event.target.value}});root.addEventListener("compositionend",event=>{const node=owner(event.target);if(!node)return;const value=event.target.value;composition=null;apply({kind:"event",source:node.identity,event:"input",value});composition={id:node.id,value}});root.addEventListener("submit",event=>{event.preventDefault();if(projecting)return;const node=owner(event.target);if(node)apply({kind:"event",source:node.identity,event:"submit"})});root.addEventListener("click",event=>{if(projecting)return;const target=event.target,tool=target.closest("[data-wf-tooling]");if(tool){event.preventDefault();projectedFocus=void 0;if(tool.getAttribute("data-wf-tooling")==="view"){state={...state,viewMode:state.viewMode==="fixed"?"accessible":"fixed"};render()}else if(tool.getAttribute("data-wf-tooling")==="reset")apply({kind:"reset"});return}const node=owner(event.target);if(!node)return;if(event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;const anchor=target.closest("a");if(["input","textarea","select","checkbox","radio","switch","slider"].includes(node.kind)){if(node.handlers.some(handler=>handler.event==="click"))apply({kind:"event",source:node.identity,event:"click"},null,true);return}if(anchor&&node.attributes.href!==void 0&&!node.handlers.some(handler=>handler.event==="click"))return;event.preventDefault();apply({kind:"event",source:node.identity,event:"click"})});root.addEventListener("keydown",event=>{if(projecting)return;const node=owner(event.target);if(!node)return;const explicit=node.handlers.some(handler=>handler.event==="keydown"&&handler.key===event.key),widget=["tab","tabs","dropdown","dropdown-item"].includes(node.kind)&&["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","Enter"," "].includes(event.key);if(explicit||widget||event.key==="Escape"){event.preventDefault();apply({kind:"event",source:node.identity,event:"keydown",key:event.key})}else if(event.key==="Enter"&&["input","select"].includes(node.kind)&&node.form){event.preventDefault();const form=nodes.get(node.form);apply({kind:"event",source:form.identity,event:"submit"})}});root.addEventListener("cancel",event=>{event.preventDefault();const node=owner(event.target);if(node)apply({kind:"event",source:node.identity,event:"keydown",key:"Escape"})},true);function addressChanged(){const sequence=browserSequence(),fragment=location.hash,canonical=fragment||engine.routeAddress(program2.entry);if(!state.suspended&&canonical===state.address&&sequence===state.history[state.historyIndex].sequence)return;apply({kind:"address",fragment},sequence)}addEventListener("hashchange",addressChanged);addEventListener("popstate",addressChanged);for(const type of["pointerover","pointerout"])root.addEventListener(type,event=>{const target=event.target instanceof Element?event.target.closest("[data-wf-kind=tooltip]"):null;if(!target||target.contains(event.relatedTarget))return;if(type==="pointerout"&&target.contains(document.activeElement))return;state=engine.hover(state,target.id,type==="pointerover");render()});function schedule(){timer=setTimeout(()=>{const now=performance.now();if(!paused&&!state.suspended){let delta=Math.max(0,Math.floor(now-last));while(delta>0){const part=Math.min(delta,6e5);const next=engine.reduce(state,{kind:"advanceClock",deltaMs:part});const changed=next.sequence!==state.sequence;state=next;if(changed){effectCommands();render()}delta-=part}}last=now;schedule()},16)}history.replaceState(metadata(state.history[state.historyIndex].sequence),"",location.href);render();schedule();Object.defineProperty(window,"wireweaveRuntime",{value:Object.freeze({pause(){paused=true;last=performance.now()},resume(){paused=false;last=performance.now()},dispatch(input){apply(input)},advanceClock(deltaMs){paused=true;apply({kind:"advanceClock",deltaMs})},reset(){apply({kind:"reset"})},snapshot(){return JSON.parse(JSON.stringify(state))}}),enumerable:false,writable:false,configurable:false});addEventListener("pagehide",()=>{if(timer!==void 0)clearTimeout(timer)})}const program=JSON.parse(document.getElementById("wf-runtime-data").textContent);browserAdapter(runtimeEngine(program),program)})();';
595
+
593
596
  // src/app/compiler.ts
594
597
  function layoutName(layout) {
595
598
  return layout.nodeId;
@@ -609,11 +612,11 @@ function projectScreen(screen) {
609
612
  uses: target === void 0 ? screen.node.uses : target.targetId
610
613
  };
611
614
  }
612
- function compileApp(document2, options = {}) {
613
- if (!("screens" in document2)) return compileAppV4(document2);
615
+ function compileApp(document, options = {}) {
616
+ if (!("screens" in document)) return compileAppV4(document);
614
617
  const projected = {
615
618
  type: "Document",
616
- children: [...document2.layouts.map(projectLayout), ...document2.screens.map(projectScreen)]
619
+ children: [...document.layouts.map(projectLayout), ...document.screens.map(projectScreen)]
617
620
  };
618
621
  return renderSite(projected, { ...options, annotationStyle: "neutral" });
619
622
  }
@@ -652,6 +655,10 @@ function hashBase64(value) {
652
655
  }
653
656
  return output;
654
657
  }
658
+ function isPrimaryAction(entry) {
659
+ const { kind, attributes } = entry.node;
660
+ return attributes.primary === true && (kind === "button" || kind === "link" && (entry.route !== void 0 || attributes.href !== void 0));
661
+ }
655
662
  var HtmlArtifact = class {
656
663
  constructor(data, program) {
657
664
  __publicField(this, "data", data);
@@ -667,7 +674,10 @@ var HtmlArtifact = class {
667
674
  const attrs = node.attributes;
668
675
  const label = (_b = node.label) != null ? _b : textValue((_a = attrs.label) != null ? _a : "");
669
676
  const children = () => entry.children.map((child) => this.node(child)).join("");
670
- let common = attribute("id", renderedId) + attribute("class", `wf-node wf-${node.kind} ${renderedId}`) + attribute("data-wf-kind", node.kind) + attribute("data-wf-source", entry.owner.module.id) + attribute("data-wf-identity", jcs(entry.identity)) + attribute(
677
+ let common = attribute("id", renderedId) + attribute(
678
+ "class",
679
+ `wf-node wf-${node.kind} ${renderedId}${isPrimaryAction(entry) ? " wf-primary-action" : ""}`
680
+ ) + attribute("data-wf-kind", node.kind) + attribute("data-wf-source", entry.owner.module.id) + attribute("data-wf-identity", jcs(entry.identity)) + attribute(
671
681
  "data-wf-requirements",
672
682
  attrs.requirementRefs === void 0 ? void 0 : jcs(attrs.requirementRefs)
673
683
  ) + attribute(
@@ -874,11 +884,13 @@ var HtmlArtifact = class {
874
884
  }
875
885
  if (a.border === true || a.outline === true || a.bordered === true)
876
886
  styles.push("border:1px solid #71717a");
877
- if (a.ghost === true) styles.push("background:transparent", "border-color:transparent");
887
+ const primaryAction = isPrimaryAction(entry);
888
+ if (a.ghost === true && !primaryAction)
889
+ styles.push("background:transparent", "border-color:transparent");
878
890
  if (a.rounded === true || a.pill === true)
879
891
  styles.push(`border-radius:${a.pill === true ? "999px" : "4px"}`);
880
892
  if (a.muted === true) styles.push("color:#52525b");
881
- if (a.bg !== void 0 || a.primary === true || a.secondary === true)
893
+ if (!primaryAction && (a.bg !== void 0 || a.primary === true || a.secondary === true))
882
894
  styles.push("background:#f4f4f5");
883
895
  if (a.shadow !== void 0 && a.shadow !== "none")
884
896
  styles.push(
@@ -919,7 +931,8 @@ var HtmlArtifact = class {
919
931
  const font = typeof bundle.profile.fontAssetId === "string" ? this.assets.get(bundle.profile.fontAssetId) : void 0;
920
932
  const fontFace = font === void 0 ? "" : `@font-face{font-family:WireweaveProfile;src:url(data:${font.mediaType};base64,${font.base64}) format("woff2");font-display:swap}`;
921
933
  const fontFamily = font === void 0 ? "system-ui,sans-serif" : "WireweaveProfile,system-ui,sans-serif";
922
- const css = `${fontFace}#wireweave-app{font:16px/1.5 ${fontFamily};color:#18181b;background:white}#wireweave-app [hidden]{display:none!important}#wireweave-app *{box-sizing:border-box}#wireweave-app :focus-visible{outline:2px solid #18181b;outline-offset:2px}#wireweave-app button,#wireweave-app input,#wireweave-app select{min-height:24px;font:inherit}#wireweave-app .wf-row{display:flex;gap:0}#wireweave-app .wf-col{flex:1}#wireweave-app .wf-stack,#wireweave-app .wf-field{display:flex;flex-direction:column;gap:8px}#wireweave-app .wf-page,#wireweave-app [data-wf-shell]{width:${textValue(bundle.profile.width)}px;height:${textValue(bundle.profile.height)}px;overflow:auto}#wireweave-app .wf-card,#wireweave-app th,#wireweave-app td{border:1px solid #71717a;padding:8px}#wireweave-app .wf-relative{position:relative}#wireweave-app [data-wf-slot]{display:contents}${this.rules.join("")}#wireweave-app[data-wf-view=accessible] .wf-node,#wireweave-app[data-wf-view=accessible] [data-wf-shell]{position:static!important;transform:none!important;width:auto!important;height:auto!important;min-width:0!important;max-width:100%!important;min-height:0!important;overflow-wrap:anywhere;order:0!important}#wireweave-app[data-wf-view=accessible] .wf-row{flex-direction:column!important;flex-wrap:wrap!important}#wireweave-app[data-wf-view=accessible] .wf-col{flex-basis:auto!important}#wireweave-app .wf-field{min-width:0}#wireweave-app .wf-field input,#wireweave-app .wf-field textarea,#wireweave-app .wf-field select{max-width:100%}#wireweave-app [data-wf-field][hidden]{display:none!important}#wireweave-app [role=tablist]{display:flex;flex-wrap:wrap}#wireweave-app [role=tooltip]{background:#f4f4f5;border:1px solid #71717a}#wireweave-app dialog{color:#18181b;background:white;max-width:100%;max-height:100%;overflow:auto}`;
934
+ const primaryActionCss = "#wireweave-app .wf-primary-action{display:inline-flex;align-items:center;width:fit-content;max-width:100%;min-height:40px;padding:8px 14px;border:1px solid #18181b;border-radius:4px;background:#18181b;color:white;font-weight:600;text-decoration:none}#wireweave-app .wf-primary-action:not(:disabled,[aria-disabled=true]):hover{background:#3f3f46;cursor:pointer}#wireweave-app .wf-primary-action:is(:disabled,[aria-disabled=true]){background:#f4f4f5;border-color:#71717a;color:#52525b}";
935
+ const css = `${fontFace}body:has(> #wireweave-app){margin:0}#wireweave-app{font:16px/1.5 ${fontFamily};color:#18181b;background:white}#wireweave-app [hidden]{display:none!important}#wireweave-app *{box-sizing:border-box}#wireweave-app :focus-visible{outline:2px solid #18181b;outline-offset:2px}#wireweave-app button,#wireweave-app input,#wireweave-app select{min-height:24px;font:inherit}#wireweave-app .wf-row{display:flex;gap:0}${primaryActionCss}#wireweave-app .wf-col{flex:1}#wireweave-app .wf-field{display:flex;flex-direction:column;gap:8px}#wireweave-app .wf-page,#wireweave-app [data-wf-shell]{width:${textValue(bundle.profile.width)}px;height:${textValue(bundle.profile.height)}px;overflow:auto}#wireweave-app .wf-card,#wireweave-app th,#wireweave-app td{border:1px solid #71717a;padding:8px}#wireweave-app .wf-relative{position:relative}#wireweave-app [data-wf-slot]{display:contents}${this.rules.join("")}#wireweave-app[data-wf-view=accessible] .wf-node,#wireweave-app[data-wf-view=accessible] [data-wf-shell]{position:static!important;transform:none!important;width:auto!important;height:auto!important;min-width:0!important;max-width:100%!important;min-height:0!important;overflow-wrap:anywhere;order:0!important}#wireweave-app[data-wf-view=accessible] .wf-row{flex-direction:column!important;flex-wrap:wrap!important}#wireweave-app[data-wf-view=accessible] .wf-col{flex-basis:auto!important}#wireweave-app .wf-field{min-width:0}#wireweave-app .wf-field input,#wireweave-app .wf-field textarea,#wireweave-app .wf-field select{max-width:100%}#wireweave-app [data-wf-field][hidden]{display:none!important}#wireweave-app [role=tablist]{display:flex;flex-wrap:wrap}#wireweave-app [role=tooltip]{background:#f4f4f5;border:1px solid #71717a}#wireweave-app dialog{color:#18181b;background:white;max-width:100%;max-height:100%;overflow:auto}`;
923
936
  const runtimeData = this.program;
924
937
  const csp = `default-src 'none'; script-src 'sha256-${hashBase64(NATIVE_RUNTIME)}'; style-src 'sha256-${hashBase64(css)}'; img-src data:; font-src data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'`;
925
938
  return `<!DOCTYPE html>
@@ -2597,432 +2610,6 @@ function advanceClock(snapshot, deltaMs) {
2597
2610
  function resetRuntime(snapshot) {
2598
2611
  return reduceEvent(snapshot, { kind: "reset" });
2599
2612
  }
2600
- function browserAdapter(engine, program) {
2601
- const root = document.getElementById("wireweave-app"), storage = root.querySelector("[data-wf-screen-storage]");
2602
- const nodes = new Map(program.nodes.map((node) => [node.id, node]));
2603
- let state = engine.initial(location.hash), projecting = false, processing = false, paused = false, last = performance.now(), timer;
2604
- let projectedFocus;
2605
- let projectionTimer;
2606
- const queue = [];
2607
- let composition = null;
2608
- const present = (value) => value == null ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
2609
- function element(id) {
2610
- return document.getElementById(id);
2611
- }
2612
- function focusElement(id) {
2613
- const node = nodes.get(id);
2614
- if ((node == null ? void 0 : node.kind) === "tab") return document.getElementById(id + "-tab");
2615
- if ((node == null ? void 0 : node.kind) === "dropdown") return document.getElementById(id + "-trigger");
2616
- return element(id);
2617
- }
2618
- function pendingFor(id) {
2619
- for (const request of Object.values(state.requests)) {
2620
- let owner2 = nodes.get(request.owner);
2621
- while (owner2) {
2622
- if (owner2.id === id) return true;
2623
- owner2 = owner2.parent ? nodes.get(owner2.parent) : void 0;
2624
- }
2625
- }
2626
- return false;
2627
- }
2628
- function metadata(sequence) {
2629
- return { wireweave: { modelDigest: program.modelDigest, sequence } };
2630
- }
2631
- function browserSequence() {
2632
- const outer = history.state;
2633
- const value = outer && typeof outer === "object" ? outer.wireweave : void 0;
2634
- if (!value || typeof value !== "object") return null;
2635
- const entry = value;
2636
- return entry.modelDigest === program.modelDigest && typeof entry.sequence === "number" && Number.isInteger(entry.sequence) ? entry.sequence : null;
2637
- }
2638
- function effectCommands() {
2639
- for (const effect of state.effects) {
2640
- if (effect.kind === "push") history.pushState(metadata(effect.sequence), "", effect.fragment);
2641
- else if (effect.kind === "replace")
2642
- history.replaceState(metadata(effect.sequence), "", effect.fragment);
2643
- else if (effect.kind === "traverse" || effect.kind === "compensate") {
2644
- if (effect.delta !== 0) history.go(effect.delta);
2645
- else history.replaceState(metadata(effect.sequence), "", effect.fragment);
2646
- } else location.assign(effect.fragment);
2647
- }
2648
- }
2649
- function render() {
2650
- var _a, _b, _c, _d, _e, _f, _g, _h;
2651
- if (projectionTimer !== void 0) {
2652
- clearTimeout(projectionTimer);
2653
- projectionTimer = void 0;
2654
- }
2655
- projecting = true;
2656
- try {
2657
- const view = engine.view(state), active = program.screens.find(
2658
- (screen) => {
2659
- var _a2, _b2;
2660
- return screen.route.namespace === ((_a2 = state.route) == null ? void 0 : _a2.namespace) && screen.route.id === ((_b2 = state.route) == null ? void 0 : _b2.id);
2661
- }
2662
- );
2663
- for (const wrapper of root.querySelectorAll("[data-wf-screen]")) {
2664
- const visible = wrapper.contains(element((_a = active == null ? void 0 : active.id) != null ? _a : ""));
2665
- wrapper.hidden = !visible;
2666
- wrapper.inert = !visible;
2667
- if (!visible && wrapper.parentElement !== storage) storage.append(wrapper);
2668
- }
2669
- for (const wrapper of root.querySelectorAll("[data-wf-shell]")) {
2670
- const visible = !!(active == null ? void 0 : active.shell) && wrapper.contains(element(active.shell));
2671
- wrapper.hidden = !visible;
2672
- wrapper.inert = !visible;
2673
- }
2674
- if (active) {
2675
- const screen = element(active.id).closest("[data-wf-screen]");
2676
- if (active.shell) {
2677
- const shell = program.shells.find((shell2) => shell2.id === active.shell);
2678
- const slot = element(shell.slot);
2679
- if (screen.parentElement !== slot) slot.append(screen);
2680
- } else if (screen.parentElement !== storage) storage.append(screen);
2681
- screen.hidden = false;
2682
- screen.inert = false;
2683
- }
2684
- const routeError = root.querySelector("[data-wf-route-error]");
2685
- routeError.hidden = state.route !== null;
2686
- root.querySelector("[data-wf-invalid-address]").textContent = state.address;
2687
- root.setAttribute("data-wf-route", state.route ? state.address : "error");
2688
- root.setAttribute("data-wf-view", state.viewMode);
2689
- root.setAttribute(
2690
- "aria-busy",
2691
- String(state.suspended || Object.keys(state.requests).length > 0)
2692
- );
2693
- for (const node of program.nodes) {
2694
- const el = element(node.id);
2695
- if (!el) continue;
2696
- el.hidden = view.visible[node.id] !== true;
2697
- const pending = pendingFor(node.id);
2698
- if (pending || node.attributes.loading === true) {
2699
- el.setAttribute("aria-busy", "true");
2700
- if (pending) el.setAttribute("data-wf-pending", "true");
2701
- else el.removeAttribute("data-wf-pending");
2702
- } else {
2703
- el.removeAttribute("aria-busy");
2704
- el.removeAttribute("data-wf-pending");
2705
- }
2706
- const field = el.closest("[data-wf-field]");
2707
- if (field) field.hidden = el.hidden;
2708
- if (node.kind === "tab") {
2709
- const owner2 = nodes.get((_b = node.parent) != null ? _b : ""), tabs = (_c = owner2 == null ? void 0 : owner2.children.filter((id) => {
2710
- var _a2;
2711
- return ((_a2 = nodes.get(id)) == null ? void 0 : _a2.kind) === "tab";
2712
- })) != null ? _c : [], selected = tabs[(_e = state.selection[(_d = owner2 == null ? void 0 : owner2.id) != null ? _d : ""]) != null ? _e : 0] === node.id;
2713
- el.hidden = !view.visible[node.id] || !selected;
2714
- const button = document.getElementById(node.id + "-tab");
2715
- if (button) {
2716
- button.setAttribute("aria-selected", String(selected));
2717
- button.tabIndex = state.focus === node.id ? 0 : tabs.includes((_f = state.focus) != null ? _f : "") ? -1 : selected ? 0 : -1;
2718
- button.disabled = !view.enabled[node.id];
2719
- }
2720
- }
2721
- if ("disabled" in el) el.disabled = view.enabled[node.id] !== true;
2722
- const control = view.controls[node.id];
2723
- if (["input", "textarea", "select", "checkbox", "radio", "switch", "slider"].includes(
2724
- node.kind
2725
- )) {
2726
- const input = el;
2727
- if (["checkbox", "radio", "switch"].includes(node.kind)) input.checked = control.checked;
2728
- else if (!composition || composition.id !== node.id) input.value = present(control.value);
2729
- }
2730
- if (state.invalid[node.id]) {
2731
- el.setAttribute("aria-invalid", "true");
2732
- const message = element(node.id + "-error");
2733
- if (message) {
2734
- message.textContent = state.invalid[node.id];
2735
- message.hidden = false;
2736
- el.setAttribute("aria-describedby", message.id);
2737
- }
2738
- } else {
2739
- el.removeAttribute("aria-invalid");
2740
- const message = element(node.id + "-error");
2741
- if (message) message.hidden = true;
2742
- el.removeAttribute("aria-describedby");
2743
- }
2744
- if (node.kind === "form") {
2745
- const error = el.querySelector("[data-wf-form-error]");
2746
- if (error) {
2747
- error.textContent = state.invalid[node.id] ? "Check the required input values." : "";
2748
- error.hidden = !state.invalid[node.id];
2749
- }
2750
- el.setAttribute("aria-busy", String(pending || node.attributes.loading === true));
2751
- }
2752
- if (node.kind === "accordion")
2753
- el.open = state.expanded[node.id] === true;
2754
- if (["modal", "drawer", "popover"].includes(node.kind)) {
2755
- const overlay = state.overlays.find((overlay2) => overlay2.id === node.id), dialog = el;
2756
- if (overlay) {
2757
- dialog.hidden = false;
2758
- if (!dialog.open) {
2759
- if (overlay.modal) dialog.showModal();
2760
- else dialog.show();
2761
- }
2762
- dialog.setAttribute("aria-modal", String(overlay.modal));
2763
- } else if (dialog.open) dialog.close();
2764
- }
2765
- if (node.kind === "dropdown") {
2766
- const open = state.overlays.some((overlay) => overlay.id === node.id);
2767
- const body = el.querySelector("[data-wf-overlay-body]");
2768
- if (body) body.hidden = !open;
2769
- const button = document.getElementById(node.id + "-trigger");
2770
- button == null ? void 0 : button.setAttribute("aria-expanded", String(open));
2771
- }
2772
- if (node.kind === "tooltip") {
2773
- const tooltip = el.querySelector("[role=tooltip]");
2774
- if (tooltip) tooltip.hidden = !state.overlays.some((overlay) => overlay.id === node.id);
2775
- const trigger = node.children[0] ? element(node.children[0]) : null;
2776
- if (trigger && tooltip) trigger.setAttribute("aria-describedby", tooltip.id);
2777
- }
2778
- if (node.attributes.dismissible === true && ["toast", "alert"].includes(node.kind))
2779
- el.hidden = el.hidden || state.expanded[node.id] === false;
2780
- if (el instanceof HTMLAnchorElement) {
2781
- if (el.getAttribute("href") === state.address) el.setAttribute("aria-current", "page");
2782
- else el.removeAttribute("aria-current");
2783
- }
2784
- if (node.attributes.data) {
2785
- const value = view.data[node.id];
2786
- if (node.kind === "table" && Array.isArray(value)) {
2787
- const body = el.querySelector("tbody"), fragment = document.createDocumentFragment();
2788
- for (const row of value) {
2789
- const tr = document.createElement("tr");
2790
- for (const key of node.attributes.columns) {
2791
- const td = document.createElement("td");
2792
- td.textContent = present(row[key]);
2793
- tr.append(td);
2794
- }
2795
- fragment.append(tr);
2796
- }
2797
- body.replaceChildren(fragment);
2798
- } else if (node.kind === "list" && Array.isArray(value)) {
2799
- const fragment = document.createDocumentFragment();
2800
- for (const item of value) {
2801
- const li = document.createElement("li");
2802
- li.textContent = present(item);
2803
- fragment.append(li);
2804
- }
2805
- el.replaceChildren(fragment);
2806
- } else if (node.kind === "text" && value !== void 0) el.textContent = present(value);
2807
- }
2808
- }
2809
- for (const screen of program.screens) (_g = element(screen.id)) == null ? void 0 : _g.removeAttribute("role");
2810
- if (active && ![...root.querySelectorAll("main")].some((main) => !main.closest("[hidden]")))
2811
- (_h = element(active.id)) == null ? void 0 : _h.setAttribute("role", "main");
2812
- const status = root.querySelector("[data-wf-runtime-status]");
2813
- status.textContent = state.diagnostic ? "The action could not complete: " + state.diagnostic : "";
2814
- if (state.diagnostic) root.setAttribute("data-wf-runtime-diagnostic", state.diagnostic);
2815
- else root.removeAttribute("data-wf-runtime-diagnostic");
2816
- const lastTrace = state.trace.at(-1);
2817
- if (lastTrace) root.setAttribute("data-wf-operation-result", lastTrace.result);
2818
- document.getElementById("wf-runtime-trace").textContent = JSON.stringify(state.trace);
2819
- if (state.focus && state.focus !== projectedFocus) {
2820
- const focus = focusElement(state.focus);
2821
- if (focus && focus !== document.activeElement && !focus.closest("[hidden],[inert]"))
2822
- focus.focus();
2823
- } else if (!state.route && projectedFocus !== null) {
2824
- const heading = routeError.querySelector("h1");
2825
- heading == null ? void 0 : heading.focus();
2826
- }
2827
- projectedFocus = state.focus;
2828
- } finally {
2829
- projecting = false;
2830
- }
2831
- }
2832
- function apply(input, sequence = null, deferProjection = false) {
2833
- if (queue.length >= 4096) throw Error("limit-queue");
2834
- queue.push({ input, sequence, deferProjection });
2835
- if (processing) return;
2836
- processing = true;
2837
- try {
2838
- while (queue.length) {
2839
- const item = queue.shift();
2840
- state = engine.reduce(state, item.input, item.sequence);
2841
- effectCommands();
2842
- if (item.deferProjection) {
2843
- if (projectionTimer === void 0) projectionTimer = setTimeout(render, 0);
2844
- } else render();
2845
- }
2846
- } finally {
2847
- processing = false;
2848
- }
2849
- }
2850
- function owner(target) {
2851
- var _a, _b;
2852
- if (!(target instanceof Element)) return void 0;
2853
- const el = target.closest("[data-wf-event-owner], [data-wf-kind]");
2854
- return nodes.get((_b = (_a = el == null ? void 0 : el.getAttribute("data-wf-event-owner")) != null ? _a : el == null ? void 0 : el.id) != null ? _b : "");
2855
- }
2856
- function nativeEvent(event) {
2857
- if (projecting) return;
2858
- const node = owner(event.target);
2859
- if (!node) return;
2860
- const kind = event.type;
2861
- const input = { kind: "event", source: node.identity, event: kind };
2862
- if (kind === "input" || kind === "change") {
2863
- const control = event.target;
2864
- if (event.isComposing) return;
2865
- if ((composition == null ? void 0 : composition.id) === node.id) {
2866
- if (composition.value === control.value) {
2867
- composition = null;
2868
- return;
2869
- }
2870
- composition = null;
2871
- }
2872
- if (["checkbox", "radio", "switch"].includes(node.kind)) input.checked = control.checked;
2873
- else input.value = control.value;
2874
- }
2875
- apply(input);
2876
- }
2877
- root.addEventListener("input", nativeEvent);
2878
- root.addEventListener("change", nativeEvent);
2879
- root.addEventListener("focus", nativeEvent, true);
2880
- root.addEventListener("blur", nativeEvent, true);
2881
- root.addEventListener("compositionstart", (event) => {
2882
- const node = owner(event.target);
2883
- if (node) composition = { id: node.id, value: event.target.value };
2884
- });
2885
- root.addEventListener("compositionend", (event) => {
2886
- const node = owner(event.target);
2887
- if (!node) return;
2888
- const value = event.target.value;
2889
- composition = null;
2890
- apply({ kind: "event", source: node.identity, event: "input", value });
2891
- composition = { id: node.id, value };
2892
- });
2893
- root.addEventListener("submit", (event) => {
2894
- event.preventDefault();
2895
- if (projecting) return;
2896
- const node = owner(event.target);
2897
- if (node) apply({ kind: "event", source: node.identity, event: "submit" });
2898
- });
2899
- root.addEventListener("click", (event) => {
2900
- if (projecting) return;
2901
- const target = event.target, tool = target.closest("[data-wf-tooling]");
2902
- if (tool) {
2903
- event.preventDefault();
2904
- projectedFocus = void 0;
2905
- if (tool.getAttribute("data-wf-tooling") === "view") {
2906
- state = { ...state, viewMode: state.viewMode === "fixed" ? "accessible" : "fixed" };
2907
- render();
2908
- } else if (tool.getAttribute("data-wf-tooling") === "reset") apply({ kind: "reset" });
2909
- return;
2910
- }
2911
- const node = owner(event.target);
2912
- if (!node) return;
2913
- if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
2914
- return;
2915
- const anchor = target.closest("a");
2916
- if (["input", "textarea", "select", "checkbox", "radio", "switch", "slider"].includes(node.kind)) {
2917
- if (node.handlers.some((handler) => handler.event === "click"))
2918
- apply({ kind: "event", source: node.identity, event: "click" }, null, true);
2919
- return;
2920
- }
2921
- if (anchor && node.attributes.href !== void 0 && !node.handlers.some((handler) => handler.event === "click"))
2922
- return;
2923
- event.preventDefault();
2924
- apply({ kind: "event", source: node.identity, event: "click" });
2925
- });
2926
- root.addEventListener("keydown", (event) => {
2927
- if (projecting) return;
2928
- const node = owner(event.target);
2929
- if (!node) return;
2930
- const explicit = node.handlers.some(
2931
- (handler) => handler.event === "keydown" && handler.key === event.key
2932
- ), widget = ["tab", "tabs", "dropdown", "dropdown-item"].includes(node.kind) && ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", "Enter", " "].includes(
2933
- event.key
2934
- );
2935
- if (explicit || widget || event.key === "Escape") {
2936
- event.preventDefault();
2937
- apply({ kind: "event", source: node.identity, event: "keydown", key: event.key });
2938
- } else if (event.key === "Enter" && ["input", "select"].includes(node.kind) && node.form) {
2939
- event.preventDefault();
2940
- const form = nodes.get(node.form);
2941
- apply({ kind: "event", source: form.identity, event: "submit" });
2942
- }
2943
- });
2944
- root.addEventListener(
2945
- "cancel",
2946
- (event) => {
2947
- event.preventDefault();
2948
- const node = owner(event.target);
2949
- if (node) apply({ kind: "event", source: node.identity, event: "keydown", key: "Escape" });
2950
- },
2951
- true
2952
- );
2953
- function addressChanged() {
2954
- const sequence = browserSequence(), fragment = location.hash, canonical = fragment || engine.routeAddress(program.entry);
2955
- if (!state.suspended && canonical === state.address && sequence === state.history[state.historyIndex].sequence)
2956
- return;
2957
- apply({ kind: "address", fragment }, sequence);
2958
- }
2959
- addEventListener("hashchange", addressChanged);
2960
- addEventListener("popstate", addressChanged);
2961
- for (const type of ["pointerover", "pointerout"])
2962
- root.addEventListener(type, (event) => {
2963
- const target = event.target instanceof Element ? event.target.closest("[data-wf-kind=tooltip]") : null;
2964
- if (!target || target.contains(event.relatedTarget)) return;
2965
- if (type === "pointerout" && target.contains(document.activeElement)) return;
2966
- state = engine.hover(state, target.id, type === "pointerover");
2967
- render();
2968
- });
2969
- function schedule() {
2970
- timer = setTimeout(() => {
2971
- const now = performance.now();
2972
- if (!paused && !state.suspended) {
2973
- let delta = Math.max(0, Math.floor(now - last));
2974
- while (delta > 0) {
2975
- const part = Math.min(delta, 6e5);
2976
- const next = engine.reduce(state, { kind: "advanceClock", deltaMs: part });
2977
- const changed = next.sequence !== state.sequence;
2978
- state = next;
2979
- if (changed) {
2980
- effectCommands();
2981
- render();
2982
- }
2983
- delta -= part;
2984
- }
2985
- }
2986
- last = now;
2987
- schedule();
2988
- }, 16);
2989
- }
2990
- history.replaceState(metadata(state.history[state.historyIndex].sequence), "", location.href);
2991
- render();
2992
- schedule();
2993
- Object.defineProperty(window, "wireweaveRuntime", {
2994
- value: Object.freeze({
2995
- pause() {
2996
- paused = true;
2997
- last = performance.now();
2998
- },
2999
- resume() {
3000
- paused = false;
3001
- last = performance.now();
3002
- },
3003
- dispatch(input) {
3004
- apply(input);
3005
- },
3006
- advanceClock(deltaMs) {
3007
- paused = true;
3008
- apply({ kind: "advanceClock", deltaMs });
3009
- },
3010
- reset() {
3011
- apply({ kind: "reset" });
3012
- },
3013
- snapshot() {
3014
- return JSON.parse(JSON.stringify(state));
3015
- }
3016
- }),
3017
- enumerable: false,
3018
- writable: false,
3019
- configurable: false
3020
- });
3021
- addEventListener("pagehide", () => {
3022
- if (timer !== void 0) clearTimeout(timer);
3023
- });
3024
- }
3025
- var NATIVE_RUNTIME = `(()=>{const program=JSON.parse(document.getElementById("wf-runtime-data").textContent);(${browserAdapter.toString()})((${runtimeEngine.toString()})(program),program);})();`;
3026
2613
  function compileAppV4(linked) {
3027
2614
  const data = getLinkedAppData(linked);
3028
2615
  if (data === void 0)