@statedelta-actions/actions 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @statedelta-actions/actions
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - update
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies
12
+ - @statedelta-actions/core@0.6.0
13
+
3
14
  ## 0.7.0
4
15
 
5
16
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- 'use strict';var core=require('@statedelta-actions/core');function Ie(o,e){let n;for(;;){let i=o.next(n);if(i.done)return i.value;n=e?e(i.value):void 0;}}async function Ee(o,e){let n;for(;;){let i=await o.next(n);if(i.done)return i.value;n=e?await e(i.value):void 0;}}function we(o){let e=0;return ()=>{if(!(e>=o.length))return o[e++]}}var O=class{_listeners=new Map;on(e,n){let i=this._listeners.get(e);i||(i=new Set,this._listeners.set(e,i)),i.add(n);let s=false;return ()=>{s||(s=true,i.delete(n),i.size===0&&this._listeners.delete(e));}}once(e,n){let i=this.on(e,s=>{i(),n(s);});return i}emit(e,n){let i=this._listeners.get(e);if(!i||i.size===0)return;let s=[...i];for(let t=0;t<s.length;t++)try{s[t](n);}catch(r){console.error(`[SimpleEmitter] Listener error on "${e}":`,r);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let n=this._listeners.get(e);return n!==void 0&&n.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var N=new Set(["const","let","return","throw","pause","if"]);function le(o,e,n,i){let s=[];return q(o.directives,e,n,i,"directive",s,o.id),s}function q(o,e,n,i,s,t,r){for(let d=0;d<o.length;d++){let c=o[d],u=c[i],h=`${s}[${d}]`;if(!u){t.push(`${h}: missing type field "${i}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&t.push(`${h}: "if" requires cond as function or boolean`);let f=c.then;Array.isArray(f)?q(f,e,n,i,`${h}.then`,t,r):t.push(`${h}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?q(D,e,n,i,`${h}.else`,t,r):t.push(`${h}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${r}" ${h}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let C=n.get(u);if(C?.validate)try{let g=C.validate(c);g&&!g.valid&&t.push(`${h}: ${g.error??"validation failed"}`);}catch(g){t.push(`${h}: validate threw: ${g}`);}let y=c.catch;if(y&&Array.isArray(y))for(let g=0;g<y.length;g++){let D=y[g][i];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${r}" ${h}.catch[${g}]: no handler registered for type "${D}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let p=C?.subDirectives;if(p===void 0)continue;let m=Object.keys(p);for(let g=0;g<m.length;g++){let f=m[g];if(f==="catch")continue;let D=c[f];if(D===void 0){if(p[f].required)throw new Error(`Action "${r}" ${h}: handler "${u}" requires sub-directives field "${f}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${r}" ${h}.${f}: must be an array of directives`);q(D,e,n,i,`${h}.${f}`,t,r);}}}var Te=new Map;function L(o,e,n=Te){let i=o.length,s=new Array(i);for(let t=0;t<i;t++){let r=o[t],d=r[e],c=r,u=false,h=r.catch;if(Array.isArray(h)&&h.length>0&&(c={...c,catch:L(h,e,n)},u=true),d==="if"){let C=r.then;Array.isArray(C)&&C.length>0&&(c={...c,then:L(C,e,n)},u=true);let y=r.else;Array.isArray(y)&&y.length>0&&(c={...c,else:L(y,e,n)},u=true);}else if(d!==void 0){let C=n.get(d);if(C!==void 0)for(let y=0;y<C.length;y++){let p=C[y],m=r[p];!Array.isArray(m)||m.length===0||(c={...c,[p]:L(m,e,n)},u=true);}}s[t]=u?c:r;}return s}function W(o,e,n,i,s,t,r){return {success:false,aborted:true,abortedBy:o,appliedCount:e,skippedCount:n,errors:i,processedCount:s,totalCount:t,counters:r}}function $e(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return function(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="value"in l?l.value:"return"in l?l.return:x.value;return {success:!0,aborted:!1,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.value};continue}if(E==="throw"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="message"in l?l.message:"throw"in l?l.throw:x.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.message};continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=core.processIntercept(c.beforeDirective(_,r),"beforeDirective");if(a.action===core.Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===core.Intercept.ABORT)return W(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{b=F(_,k,h);}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data};let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=h.runDirectives(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(c.afterDirective(_,b,k)==="abort")return W("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{c.onDirectivesComplete(P);}catch{}return P}}function Se(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return async function(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="value"in l?l.value:"return"in l?l.return:x.value;return {success:!0,aborted:!1,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.value};continue}if(E==="throw"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="message"in l?l.message:"throw"in l?l.throw:x.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.message};continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=core.processIntercept(await c.beforeDirective(_,r),"beforeDirective");if(a.action===core.Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===core.Intercept.ABORT)return W(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{b=await F(_,k,h);}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data};let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=await h.runDirectivesAsync(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(await c.afterDirective(_,b,k)==="abort")return W("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{await c.onDirectivesComplete(P);}catch{}return P}}function J(o,e){return e?Se(o):$e(o)}function B(o,e,n,i,s,t,r,d){return {success:false,aborted:true,abortedBy:o,appliedCount:e,skippedCount:n,errors:i,processedCount:s,totalCount:t,counters:r,data:d}}function pe(o){if(o===null||typeof o!="object")return null;if(typeof o.next=="function")return o;let e=o.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function He(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return function*(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I,l=x.value;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="value"in v?v.value:"return"in v?v.return:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:l}}if(E==="throw"){let a=I,l=x.message;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="message"in v?v.message:"throw"in v?v.throw:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return B("throw",m,g,p,a,y,f,l)}if(E==="pause"){let a=I,l=yield {source:"pause",directive:x,frame:r,index:A,payload:{message:x.message}};if(l===false||l==="abort"||l==="cancel")return B("pause",m,g,p,a,y,f,l);m++,f.directivesApplied++,typeof x.as=="string"&&l!==void 0&&(D[x.as]=l);continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=core.processIntercept(c.beforeDirective(_,r),"beforeDirective");if(a.action===core.Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===core.Intercept.ABORT)return B(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{let a=F(_,k,h),l=pe(a);l!==null?b=yield*l:b=a;}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return B("halt",m,g,p,H,y,f,b.data);let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=h.runDirectives(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(c.afterDirective(_,b,k)==="abort")return B("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{c.onDirectivesComplete(P);}catch{}return P}}function Me(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return async function*(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I,l=x.value;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="value"in v?v.value:"return"in v?v.return:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:l}}if(E==="throw"){let a=I,l=x.message;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="message"in v?v.message:"throw"in v?v.throw:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return B("throw",m,g,p,a,y,f,l)}if(E==="pause"){let a=I,l=yield {source:"pause",directive:x,frame:r,index:A,payload:{message:x.message}};if(l===false||l==="abort"||l==="cancel")return B("pause",m,g,p,a,y,f,l);m++,f.directivesApplied++,typeof x.as=="string"&&l!==void 0&&(D[x.as]=l);continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=core.processIntercept(await c.beforeDirective(_,r),"beforeDirective");if(a.action===core.Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===core.Intercept.ABORT)return B(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{let a=await F(_,k,h),l=pe(a);l!==null?b=yield*l:b=a;}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return B("halt",m,g,p,H,y,f,b.data);let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=await h.runDirectivesAsync(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(await c.afterDirective(_,b,k)==="abort")return B("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{await c.onDirectivesComplete(P);}catch{}return P}}function ee(o,e){return e?Me(o):He(o)}function te(o,e=o.hasAnyAsync){let{filledNames:n}=o,i=h=>n.has(h),s=h=>o.asyncNames.has(h)?"await ":"",t=e?"await ":"",r=[];for(let h of n)r.push(`const ${h} = directiveHooks.${h};`);r.push("const len = Math.min(directives.length, maxDirectives);"),r.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),r.push("const counters = frame.counters;"),r.push("for (let i = 0; i < len; i++) {"),r.push(" let directive = directives[i];"),i("beforeDirective")?(r.push(" let _df = frame;"),r.push(" try {"),r.push(` const _bd = ${s("beforeDirective")}beforeDirective(directive, frame);`),r.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),r.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),r.push(' if (typeof _bd === "object" && _bd !== null) {'),r.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),r.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),r.push(' if ("directive" in _bd) directive = _bd.directive;'),r.push(" }"),r.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):r.push(" const _df = frame;"),r.push(' if (typeof directive.resolve === "function") {'),r.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),r.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),r.push(" }"),r.push(" const _type = directive[typeField];"),r.push(" const _handler = _type ? handlers[_type] : undefined;"),r.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),r.push(" let _result;"),r.push(` try { _result = ${t}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),r.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),r.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),i("afterDirective")&&(r.push(" try {"),r.push(` const _ad = ${s("afterDirective")}afterDirective(directive, _result, _df);`),r.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),r.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),r.push("}"),r.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),i("onDirectivesComplete")&&r.push(`try { ${s("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),r.push("return _finalResult;");let d=r.join(`
1
+ 'use strict';var core=require('@statedelta-actions/core');function We(i,e){let t;for(;;){let r=i.next(t);if(r.done)return r.value;t=e?e(r.value):void 0;}}async function Je(i,e){let t;for(;;){let r=await i.next(t);if(r.done)return r.value;t=e?await e(r.value):void 0;}}function Ye(i){let e=0;return ()=>{if(!(e>=i.length))return i[e++]}}var X=class{_listeners=new Map;on(e,t){let r=this._listeners.get(e);r||(r=new Set,this._listeners.set(e,r)),r.add(t);let o=false;return ()=>{o||(o=true,r.delete(t),r.size===0&&this._listeners.delete(e));}}once(e,t){let r=this.on(e,o=>{r(),t(o);});return r}emit(e,t){let r=this._listeners.get(e);if(!r||r.size===0)return;let o=[...r];for(let n=0;n<o.length;n++)try{o[n](t);}catch(s){console.error(`[SimpleEmitter] Listener error on "${e}":`,s);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let t=this._listeners.get(e);return t!==void 0&&t.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var N=new Set(["const","let","return","throw","pause","if"]);function ke(i,e,t,r){let o=[];return se(i.directives,e,t,r,"directive",o,i.id),o}function se(i,e,t,r,o,n,s){for(let a=0;a<i.length;a++){let c=i[a],u=c[r],d=`${o}[${a}]`;if(!u){n.push(`${d}: missing type field "${r}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&n.push(`${d}: "if" requires cond as function or boolean`);let A=c.then;Array.isArray(A)?se(A,e,t,r,`${d}.then`,n,s):n.push(`${d}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?se(D,e,t,r,`${d}.else`,n,s):n.push(`${d}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${s}" ${d}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let h=t.get(u);if(h?.validate)try{let g=h.validate(c);g&&!g.valid&&n.push(`${d}: ${g.error??"validation failed"}`);}catch(g){n.push(`${d}: validate threw: ${g}`);}let f=c.catch;if(f&&Array.isArray(f))for(let g=0;g<f.length;g++){let D=f[g][r];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${s}" ${d}.catch[${g}]: no handler registered for type "${D}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let p=h?.subDirectives;if(p===void 0)continue;let l=Object.keys(p);for(let g=0;g<l.length;g++){let A=l[g];if(A==="catch")continue;let D=c[A];if(D===void 0){if(p[A].required)throw new Error(`Action "${s}" ${d}: handler "${u}" requires sub-directives field "${A}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${s}" ${d}.${A}: must be an array of directives`);se(D,e,t,r,`${d}.${A}`,n,s);}}}var Qe=new Map;function B(i,e,t=Qe){let r=i.length,o=new Array(r);for(let n=0;n<r;n++){let s=i[n],a=s[e],c=s,u=false,d=s.catch;if(Array.isArray(d)&&d.length>0&&(c={...c,catch:B(d,e,t)},u=true),a==="if"){let h=s.then;Array.isArray(h)&&h.length>0&&(c={...c,then:B(h,e,t)},u=true);let f=s.else;Array.isArray(f)&&f.length>0&&(c={...c,else:B(f,e,t)},u=true);}else if(a!==void 0){let h=t.get(a);if(h!==void 0)for(let f=0;f<h.length;f++){let p=h[f],l=s[p];!Array.isArray(l)||l.length===0||(c={...c,[p]:B(l,e,t)},u=true);}}o[n]=u?c:s;}return o}function Ee(i,e,t,r,o,n,s){let a=new Set;return Z(i,e,t,r,o,n,s,a),a}function Z(i,e,t,r,o,n,s,a){for(let c of i){let u=c[e];if(u!==void 0){let f=t.get(u);if(f!==void 0&&f.subDirectives!==void 0){let p=r.get(u);if(p!==void 0){let l=false;for(let g=0;g<p.length;g++){let A=c[p[g]];if(!(!Array.isArray(A)||A.length===0)&&ee(A,e,r,o,n)){l=true;break}}l&&(f.executeInteractive!==void 0||f.interactive===true||s(f.execute)||a.add(u));}}}let d=c.catch;if(Array.isArray(d)&&d.length>0&&Z(d,e,t,r,o,n,s,a),u==="if"){let f=c.then;Array.isArray(f)&&f.length>0&&Z(f,e,t,r,o,n,s,a);let p=c.else;Array.isArray(p)&&p.length>0&&Z(p,e,t,r,o,n,s,a);continue}if(u===void 0)continue;let h=r.get(u);if(h!==void 0)for(let f=0;f<h.length;f++){let p=c[h[f]];!Array.isArray(p)||p.length===0||Z(p,e,t,r,o,n,s,a);}}}function ee(i,e,t,r,o){for(let n of i){let s=n[e];if(s==="pause"||s!==void 0&&r.has(s)||s==="action"&&typeof n.id=="string"&&o(n.id))return true;let a=n.catch;if(Array.isArray(a)&&a.length>0&&ee(a,e,t,r,o))return true;if(s==="if"){let u=n.then;if(Array.isArray(u)&&u.length>0&&ee(u,e,t,r,o))return true;let d=n.else;if(Array.isArray(d)&&d.length>0&&ee(d,e,t,r,o))return true;continue}if(s===void 0)continue;let c=t.get(s);if(c!==void 0)for(let u=0;u<c.length;u++){let d=n[c[u]];if(!(!Array.isArray(d)||d.length===0)&&ee(d,e,t,r,o))return true}}return false}function j(i,e,t,r,o,n){let s=i.name;if(typeof i.resolve=="function")try{t[s]=i.resolve(e,t).value;}catch(a){r.push({directiveIndex:o,error:`Binding resolve: ${a}`}),n.errors++;}else t[s]=i.value;}function L(i,e,t,r,o,n){let s=i.value;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="value"in a?a.value:"return"in a?a.return:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function O(i,e,t,r,o,n){let s=i.message;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="message"in a?a.message:"throw"in a?a.throw:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function V(i,e,t,r,o,n,s,a,c,u,d){let h;try{let p=i.cond;h=typeof p=="function"?!!p(e,t):!!p;}catch(p){c.push({directiveIndex:u,error:`if cond: ${p}`}),d.errors++;return}let f=h?i.then:i.else;if(Array.isArray(f)&&f.length>0){let p=Math.min(f.length,a),l=o?n:s;r.push({dirs:f,i:0,len:p,topLevelIfIndex:l});}}function z(i,e,t){let r=core.processIntercept(i,"beforeDirective");if(r.action===core.Intercept.SKIP)return {action:"skip"};if(r.action===core.Intercept.ABORT)return {action:"abort",reason:r.abortReason};let o=t,n=e;return r.ctx!==void 0&&(o=t.withCtx(r.ctx)),r.directive!==void 0&&(n=r.directive),{action:"continue",directive:n,dFrame:o}}function G(i,e,t,r,o){i.push({directiveIndex:t,error:`Hook ${r}: ${o}`}),e.errors++;}function S(i,e,t,r,o){return {success:false,aborted:true,abortedBy:i,appliedCount:e.appliedCount,skippedCount:e.skippedCount,errors:e.errors,processedCount:t,totalCount:r,counters:e.counters,data:o}}function K(i,e,t,r){return {success:true,aborted:true,abortedBy:"halt",appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function U(i,e,t,r){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function q(i,e){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:e,counters:i.counters}}function W(i,e,t,r){return {success:r.success,aborted:true,abortedBy:r.abortedBy,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r.data}}function J(i,e,t,r,o){if(typeof i.resolve!="function")return i;try{let n=i.resolve(e.ctx,e.scope);return {...i,...n}}catch(n){return t.push({directiveIndex:r,error:`Directive resolve: ${n}`}),o.errors++,null}}function Y(i,e){return [{dirs:i,i:0,len:e,topLevelIfIndex:-1}]}function Ze(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function et(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=await F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function oe(i,e){return e?et(i):Ze(i)}function de(i){if(i===null||typeof i!="object")return null;if(typeof i.next=="function")return i;let e=i.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function fe(i,e,t){return {source:"pause",directive:i,frame:e,index:t,payload:{message:i.message}}}function pe(i){return i===false||i==="abort"||i==="cancel"}function ve(i,e,t,r){r.directivesApplied++,typeof i.as=="string"&&e!==void 0&&(t[i.as]=e);}function tt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function rt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=await F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function he(i,e){return e?rt(i):tt(i)}function ye(i,e=i.hasAnyAsync){let{filledNames:t}=i,r=d=>t.has(d),o=d=>i.asyncNames.has(d)?"await ":"",n=e?"await ":"",s=[];for(let d of t)s.push(`const ${d} = directiveHooks.${d};`);s.push("const len = Math.min(directives.length, maxDirectives);"),s.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),s.push("const counters = frame.counters;"),s.push("for (let i = 0; i < len; i++) {"),s.push(" let directive = directives[i];"),r("beforeDirective")?(s.push(" let _df = frame;"),s.push(" try {"),s.push(` const _bd = ${o("beforeDirective")}beforeDirective(directive, frame);`),s.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),s.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if (typeof _bd === "object" && _bd !== null) {'),s.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),s.push(' if ("directive" in _bd) directive = _bd.directive;'),s.push(" }"),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):s.push(" const _df = frame;"),s.push(' if (typeof directive.resolve === "function") {'),s.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),s.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),s.push(" }"),s.push(" const _type = directive[typeField];"),s.push(" const _handler = _type ? handlers[_type] : undefined;"),s.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),s.push(" let _result;"),s.push(` try { _result = ${n}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),s.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),s.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),r("afterDirective")&&(s.push(" try {"),s.push(` const _ad = ${o("afterDirective")}afterDirective(directive, _result, _df);`),s.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),s.push("}"),s.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),r("onDirectivesComplete")&&s.push(`try { ${o("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),s.push("return _finalResult;");let a=s.join(`
2
2
  `),c=e?"async ":"";return {fn:new Function("directives","frame","handlers","directiveHooks","typeField","engine","maxDirectives",`"use strict";
3
3
  return (${c}() => {
4
- ${d}
5
- })();`),isAsync:e}}function re(o,e,n){return `return{success:false,aborted:true,abortedBy:${o},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${n},counters};`}function Pe(o,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${e},counters,data:_result.data};`}function Fe(o,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${e},counters,data:_result.data};`}function Be(o,e,n,i){let s=JSON.stringify(e.name);typeof e.resolve=="function"?(o.push("try{"),o.push(`scope[${s}]=${n}.resolve(ctx,scope).value;`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Binding resolve: "+_e});counters.errors++;}`)):o.push(`scope[${s}]=${n}.value;`);}function Ge(o,e,n,i,s,t){typeof e.resolve=="function"?(o.push("try{"),o.push(`const _rv=${n}.resolve(ctx,scope);`),o.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${n}.value};`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):o.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:${n}.value};`);}function Le(o,e,n,i,s,t){typeof e.resolve=="function"?(o.push("try{"),o.push(`const _rv=${n}.resolve(ctx,scope);`),o.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${n}.message};`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):o.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:${n}.message};`);}function Ne(o,e,n,i,s,t){let r=typeof e.as=="string",d=r?JSON.stringify(e.as):"";o.push(`{const _ack=yield{source:"pause",directive:${n},frame,index:${i},payload:{message:${n}.message}};`),o.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:_ack};`),o.push("appliedCount++;counters.directivesApplied++;"),r&&o.push(`if(_ack!==undefined)scope[${d}]=_ack;`),o.push("}");}function je(o,e,n,i,s){let{L:t,total:r,typeField:d,handlerVars:c,hasBefore:u,hasAfter:h,awBefore:C,awAfter:y,awHandler:p,actionIsAsync:m,actionIsInteractive:g,interactiveHandlerSet:f}=s,D=o[d],$=c.get(D),w=typeof o.resolve=="function",I=typeof o.as=="string",P=Array.isArray(o.catch)&&o.catch.length>0,R=I?JSON.stringify(o.as):"",T=g&&f.has(D),S=s.blockCounter.n++;t.push(`_b${S}:{`);let A=u||w,x=u;A&&t.push(`let _dir=${e};`),x&&t.push("let _df=frame;"),u&&(t.push("try{"),t.push(`const _bd=${C}_hookBefore(${e},frame);`),t.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${S};}`),t.push(`if(_bd==="abort")${re('"beforeDirective"',i-1,r)}`),t.push('if(typeof _bd==="object"&&_bd!==null){'),t.push(`if("abort" in _bd)${re("_bd.abort",i-1,r)}`),t.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),t.push('if("directive" in _bd)_dir=_bd.directive;'),t.push("}"),t.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(t.push('if(typeof _dir.resolve==="function"){'),t.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),t.push(`catch(_e){errors.push({directiveIndex:${n},error:"Directive resolve: "+_e});counters.errors++;break _b${S};}}`)):w&&(t.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),t.push(`catch(_e){errors.push({directiveIndex:${n},error:"Directive resolve: "+_e});counters.errors++;break _b${S};}`));let E=A?"_dir":e,_=x?"_df":"frame";if(t.push("let _result;"),T?(t.push(`try{_result=yield* ${$}(${E},${_},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(t.push(`try{_result=${p}${$}(${E},${_},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):(t.push(`try{_result=${p}${$}(${E},${_},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")),t.push("if(_result.ok){"),t.push("appliedCount++;counters.directivesApplied++;"),I&&t.push(`scope[${R}]=_result.data;`),t.push(`if(_result.halt)${Pe(i,r)}`),t.push("}else{"),t.push(`if(_result.halt)${Fe(i,r)}`),P){t.push('scope.$exception=_result.error||"handler failed";');let k=m?"$.runner":"$.runnerSync";t.push(`const _cr=${p}${k}(${e}.catch,${_});`),t.push("appliedCount+=_cr.appliedCount;"),t.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),t.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${i},totalCount:${r},counters,data:_cr.data};`);}else t.push(`errors.push({directiveIndex:${n},error:_result.error||"handler failed"});counters.errors++;`);t.push("}"),h&&(t.push("try{"),t.push(`const _ad=${y}_hookAfter(${E},_result,${_});`),t.push(`if(_ad==="abort")${re('"afterDirective"',i,r)}`),t.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Hook afterDirective: "+_e});counters.errors++;}`)),t.push("}");}function Oe(o,e,n,i,s,t){let{L:r}=t,d=o.cond,c=typeof d=="boolean";r.push("{"),c?r.push(`if(${d?"true":"false"}){`):(r.push("let _cond=false,_condOk=true;"),r.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),r.push(`catch(_e){errors.push({directiveIndex:${n},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),r.push("if(_condOk){"),r.push("if(_cond){"));let u=o.then;Array.isArray(u)&&u.length>0&&ne(u,`${e}.then`,i,s,t),r.push("}");let h=o.else;Array.isArray(h)&&h.length>0&&(r.push("else{"),ne(h,`${e}.else`,i,s,t),r.push("}")),c||r.push("}"),r.push("}");}function ne(o,e,n,i,s){let t=n!==-1;for(let r=0;r<o.length;r++){let d=o[r],c=`${e}[${r}]`,u=t?n:r,h=t?i:r+1;switch(d[s.typeField]){case "const":case "let":Be(s.L,d,c,u);break;case "return":Ge(s.L,d,c,u,h,s.total);break;case "throw":Le(s.L,d,c,u,h,s.total);break;case "pause":Ne(s.L,d,c,u,h,s.total);break;case "if":{let y=t?n:r,p=t?i:r+1;Oe(d,c,u,y,p,s);break}default:je(d,c,u,h,s);break}}}function ie(o,e,n){for(let i of o){let s=i[e];if(s&&!N.has(s)&&n.add(s),s==="if"){let t=i.then;Array.isArray(t)&&t.length>0&&ie(t,e,n);let r=i.else;Array.isArray(r)&&r.length>0&&ie(r,e,n);}}}var he=new Set;function se(o,e,n,i=he,s,t=false,r=he){let d=[],c=o.length,{filledNames:u,hasAnyAsync:h,asyncNames:C}=e,y=u.has("beforeDirective"),p=u.has("afterDirective"),m=u.has("onDirectivesComplete"),g=s!==void 0?s:Q(o,i,n),f=h||g,D=f?"await ":"",$=C.has("beforeDirective")?"await ":"",w=C.has("afterDirective")?"await ":"",I=C.has("onDirectivesComplete")?"await ":"",P=new Set;ie(o,n,P);let R=new Map,T=0;for(let k of P)R.set(k,`_h${T++}`);d.push("const counters=frame.counters;"),d.push("const ctx=frame.ctx;"),d.push("const errors=[];"),d.push("let appliedCount=0;"),d.push("let skippedCount=0;");for(let[k,M]of R)d.push(`const ${M}=$.h[${JSON.stringify(k)}];`);y&&d.push("const _hookBefore=$.hooks.beforeDirective;"),p&&d.push("const _hookAfter=$.hooks.afterDirective;"),ne(o,"$.d",-1,0,{L:d,total:c,typeField:n,handlerVars:R,hasBefore:y,hasAfter:p,awBefore:$,awAfter:w,awHandler:D,actionIsAsync:f,actionIsInteractive:t,interactiveHandlerSet:r,blockCounter:{n:0}}),d.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${c},totalCount:${c},counters};`),m&&d.push(`try{${I}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),d.push("return _finalResult;");let x=`{
6
- ${d.join(`
7
- `)}
8
- }`,E;return t?E=`(${f?"async function*()":"function*()"}${x})()`:E=`(${f?"async ()=>":"()=>"}${x})()`,{fn:new Function("frame","scope","$",`"use strict";
9
- return ${E};`),isAsync:f,isInteractive:t}}function Q(o,e,n){for(let i of o){let s=i[n];if(s&&e.has(s))return true;if(s==="if"){let r=i.then;if(Array.isArray(r)&&r.length>0&&Q(r,e,n))return true;let d=i.else;if(Array.isArray(d)&&d.length>0&&Q(d,e,n))return true}let t=i.catch;if(Array.isArray(t)&&t.length>0&&Q(t,e,n))return true}return false}function oe(o,e,n){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:o,...n}}function ve(o,e){return oe(e,`Action not found: "${o}"`,{aborted:true,abortedBy:"action-not-found"})}function ye(o,e,n){return oe(n,`Max depth ${e} exceeded invoking "${o}"`,{aborted:true,abortedBy:"maxDepth"})}function xe(o,e){return oe(e,`Action "${o}" is private (sub-action). Can only be invoked from within its parent scope.`)}function X(o,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:o,counters:e}}function Ke(o){return typeof o=="object"&&o!==null&&"execute"in o}function ge(o){let e=new Map;for(let[n,i]of o){let s=i.subDirectives;if(!s)continue;let t=Object.keys(s);if(t.length===0)continue;let r=null;for(let d=0;d<t.length;d++){let c=t[d];c!=="catch"&&s[c].graph!==false&&(r===null&&(r=[]),r.push(c));}r!==null&&e.set(n,r);}return e}function me(o){let e=new Map;for(let[n,i]of o){let s=i.subDirectives;if(!s)continue;let t=Object.keys(s);if(t.length===0)continue;let r=null;for(let d=0;d<t.length;d++){let c=t[d];c!=="catch"&&(r===null&&(r=[]),r.push(c));}r!==null&&e.set(n,r);}return e}function _e(o){let e=Object.create(null),n=new Map;for(let i of Object.keys(o)){let s=o[i];Ke(s)?(e[i]=s.execute,n.set(i,s)):(e[i]=s,n.set(i,{execute:s}));}return {handlers:e,definitions:n}}function De(o,e){if(o==="*")return true;if(!o.includes("*"))return o===e;let n=o.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)}function Ce(o){return typeof o=="string"?{pattern:o}:o}function be(o,e,n){let i=new Map;if(!e&&!n){for(let s of o)i.set(s,{status:"available"});return i}if(e){let s=e.map(Ce);for(let t of o){let r=s.some(d=>De(d.pattern,t));i.set(t,{status:r?"available":"denied"});}}else {let s=n.map(Ce);for(let t of o){let r=s.find(d=>De(d.pattern,t));r?i.set(t,{status:"denied",reason:r.reason,source:r.source}):i.set(t,{status:"available"});}}return i}function Re(o){let{typeField:e,asyncHandlerSet:n,interactiveHandlerSet:i,subDirectiveFieldsForGraph:s}=o,t=new Map,r=new Set,d=new Set,c=new Set,u=new Set;return {upsert(h,C,y){t.set(h,Ue(C,e,s)),U(C,n,e,s)?r.add(h):r.delete(h),y||z(C,i,e,s)?d.add(h):d.delete(h);},remove(h){t.delete(h),r.delete(h),d.delete(h);},recompute(){c=Ae(t,r),u=Ae(t,d);},isAsync(h){return c.has(h)},isInteractive(h){return u.has(h)},has(h){return t.has(h)}}}var Z=new Map;function Ue(o,e,n=Z){let i=new Set;return K(o,e,n,i),i}function K(o,e,n,i){for(let s of o){let t=s[e];t==="action"&&typeof s.id=="string"&&i.add(s.id);let r=s.catch;if(Array.isArray(r)&&r.length>0&&K(r,e,n,i),t==="if"){let c=s.then;Array.isArray(c)&&c.length>0&&K(c,e,n,i);let u=s.else;Array.isArray(u)&&u.length>0&&K(u,e,n,i);continue}if(t===void 0)continue;let d=n.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];!Array.isArray(u)||u.length===0||K(u,e,n,i);}}}function U(o,e,n,i=Z){for(let s of o){let t=s[n];if(t!==void 0&&e.has(t))return true;let r=s.catch;if(Array.isArray(r)&&r.length>0&&U(r,e,n,i))return true;if(t==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&U(c,e,n,i))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&U(u,e,n,i))return true;continue}if(t===void 0)continue;let d=i.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];if(!(!Array.isArray(u)||u.length===0)&&U(u,e,n,i))return true}}return false}function z(o,e,n,i=Z){for(let s of o){let t=s[n];if(t==="pause"||t!==void 0&&e.has(t))return true;let r=s.catch;if(Array.isArray(r)&&r.length>0&&z(r,e,n,i))return true;if(t==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&z(c,e,n,i))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&z(u,e,n,i))return true;continue}if(t===void 0)continue;let d=i.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];if(!(!Array.isArray(u)||u.length===0)&&z(u,e,n,i))return true}}return false}function j(o,e,n=Z){for(let i of o){let s=i[e];if(s==="pause")return true;let t=i.catch;if(Array.isArray(t)&&t.length>0&&j(t,e,n))return true;if(s==="if"){let d=i.then;if(Array.isArray(d)&&d.length>0&&j(d,e,n))return true;let c=i.else;if(Array.isArray(c)&&c.length>0&&j(c,e,n))return true;continue}if(s===void 0)continue;let r=n.get(s);if(r!==void 0)for(let d=0;d<r.length;d++){let c=i[r[d]];if(!(!Array.isArray(c)||c.length===0)&&j(c,e,n))return true}}return false}function Ae(o,e){let n=new Set(e),i=true;for(;i;){i=false;for(let[s,t]of o)if(!n.has(s)){for(let r of t)if(n.has(r)){n.add(s),i=true;break}}}return n}var Je=8,Ye="type",ae={maxDepth:10,maxRules:1e4,maxDirectives:1e5},ue=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new O;_batchDepth=0;_batchErrors=[];_batchWarnings=[];_batchActions=[];_batchRegistered=[];_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Je,this._typeField=e.typeField??Ye,this._limits={maxDepth:e.limits?.maxDepth??ae.maxDepth,maxRules:e.limits?.maxRules??ae.maxRules,maxDirectives:e.limits?.maxDirectives??ae.maxDirectives};let{handlers:n,definitions:i}=_e(e.handlers);for(let c of Object.keys(e.handlers))if(N.has(c))throw new Error(`Handler type "${c}" is reserved for engine-internal directives`);if(e.allowedDirectives&&e.blockedDirectives)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.");this._handlers=n,this._definitions=i,this._directivePermissions=be(Object.keys(n),e.allowedDirectives,e.blockedDirectives),this._directiveHooks=e.directiveHooks??{},this._beforeAction=e.actionHooks?.beforeAction??null,this._afterAction=e.actionHooks?.afterAction??null,this._directiveAnalysis=core.analyzeSlots(this._directiveHooks,core.DIRECTIVE_SLOT_NAMES);let s=new Set,t=new Set;for(let[c,u]of this._definitions)(u.async===true||core.isAsyncFunction(u.execute))&&s.add(c),(u.interactive===true||core.isGeneratorFunction(u.execute))&&t.add(c);if(this._asyncHandlerSet=s,this._interactiveHandlerSet=t,this._isInteractive=e.interactive!==void 0,!this._isInteractive&&t.size>0){let c=Array.from(t).join(", ");throw new Error(`Handler(s) [${c}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}this._isAsync=this._directiveAnalysis.hasAnyAsync||s.size>0;let r=ge(this._definitions);this._subDirectiveFieldsForGraph=r,this._subDirectiveFieldsAll=me(this._definitions),this._miniGraph=Re({typeField:this._typeField,asyncHandlerSet:s,interactiveHandlerSet:t,subDirectiveFieldsForGraph:r}),this._engineRef={runDirectives:(c,u)=>this._executeDirectives(c,u),runDirectivesAsync:(c,u)=>this._executeDirectivesAsync(c,u),invoke:(c,u,h)=>this._invokeInternal(c,u,h),invokeAsync:(c,u,h)=>this._invokeInternalAsync(c,u,h),isActionAsync:c=>this._miniGraph.has(c)?this._miniGraph.isAsync(c):void 0,isActionInteractive:c=>this._miniGraph.has(c)?this._miniGraph.isInteractive(c):void 0,invokeInteractive:(c,u,h)=>this._invokeInteractiveInternal(c,u,h),evaluateRules:()=>{throw new Error("evaluateRules() not available in ActionEngine context. Use createRuleEngine().")},evaluateRulesAsync:()=>{throw new Error("evaluateRulesAsync() not available in ActionEngine context. Use createRuleEngine().")}},this._directiveRunner=(c,u)=>this._directiveExecutor(c,u,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);let d=J(this._directiveAnalysis,false);this._directiveRunnerSync=(c,u)=>d(c,u,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives),this._requestedMode==="jit"?(this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit"):this._isAsync?(this._directiveExecutor=J(this._directiveAnalysis,true),this._mode="interpret"):(this._directiveExecutor=d,this._mode="interpret"),this._interactiveExecutor=this._isInteractive?this._isAsync?ee(this._directiveAnalysis,true):ee(this._directiveAnalysis,false):null;}register(e){let n=[],i=[],s=[],t=[];for(let d of e){if(!d.id){i.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&j(d.directives,this._typeField,this._subDirectiveFieldsForGraph)){i.push({actionId:d.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let c=le(d,this._handlers,this._definitions,this._typeField);if(c.length>0){for(let u of c)i.push({actionId:d.id,error:u});continue}t.push(d);}for(let d of t){let c=L(d.directives,this._typeField,this._subDirectiveFieldsAll),u={definition:d,directives:c,compiled:null,invokeCount:0};this._registry.set(d.id,u),this._registeredIds.add(d.id),this._miniGraph.upsert(d.id,c,d.interactive===true),n.push(d.id);}if(this._batchDepth>0){this._batchErrors.push(...i),this._batchWarnings.push(...s);for(let d of t)this._batchActions.push(d);return this._batchRegistered.push(...n),{registered:n,errors:i,warnings:s}}t.length>0&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile());let r={registered:n,errors:i,warnings:s};return n.length>0&&this._emitter.emit("register",{actions:t,result:r,registered:n}),r}unregister(e){let n=this._registry.delete(e);n&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let i=e+"/",s=[];for(let t of this._registry.keys())t.startsWith(i)&&(this._registry.delete(t),this._registeredIds.delete(t),this._miniGraph.remove(t),s.push(t));return n&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:s})),n}invoke(e,n,i){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);if(this._miniGraph.isAsync(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is async (transitively). Use invokeAsync() instead.`);if(this._directiveAnalysis.hasAnyAsync)throw new Error(`Cannot call invoke("${e}") \u2014 engine has async directive hooks. Use invokeAsync() instead.`);let s=i!==void 0?i:this._requireCtx(),t=core.createRootFrame(s,this._limits);return this._invokeInternal(e,n,t)}async invokeAsync(e,n,i){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let s=i!==void 0?i:this._requireCtx(),t=core.createRootFrame(s,this._limits);return this._invokeInternalAsync(e,n,t)}setContext(e){this._ctx=e;}context(e,n){let i=this._ctx;this._ctx=e;try{return n()}finally{this._ctx=i;}}beginBatch(){this._batchDepth++,this._batchDepth===1&&(this._batchErrors=[],this._batchWarnings=[],this._batchActions=[],this._batchRegistered=[]);}endBatch(){if(this._batchDepth<=0)throw new Error("endBatch() called without matching beginBatch()");if(this._batchDepth--,this._batchDepth>0)return {registered:[],errors:[],warnings:[]};let e={registered:this._batchRegistered,errors:this._batchErrors,warnings:this._batchWarnings};return this._batchRegistered.length>0&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile()),this._batchRegistered.length>0&&this._emitter.emit("register",{actions:this._batchActions,result:e,registered:this._batchRegistered}),e}on(e,n){return this._emitter.on(e,n)}get handlerDefinitions(){return this._definitions}get registeredIds(){return this._registeredIds}getActionDefinition(e){return this._registry.get(e)?.definition}get typeField(){return this._typeField}get subDirectiveFieldsForGraph(){return this._subDirectiveFieldsForGraph}get directivePermissions(){return this._directivePermissions}get isAsync(){return this._isAsync}get isInteractive(){return this._isInteractive}isActionAsync(e){if(this._miniGraph.has(e))return this._miniGraph.isAsync(e)}isActionInteractive(e){if(this._miniGraph.has(e))return this._miniGraph.isInteractive(e)}invokeInteractive(e,n,i){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let s=i!==void 0?i:this._requireCtx(),t=core.createRootFrame(s,this._limits);return this._invokeInteractiveInternal(e,n,t)}_invokeInteractiveInternal(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return ke(s,this._isAsync);let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return ke(X(u.data,r.counters),this._isAsync)}let c;if(t.compiled&&t.compiled.isInteractive)c=t.compiled.fn(r,r.scope,t.compiled.$);else {let u=this._interactiveExecutor;c=u(t.directives,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return Qe(c,e,n,r,this._afterAction,this._isAsync)}get compilationMode(){return this._mode}get directiveHookSlots(){return this._directiveAnalysis.filledNames}get asyncSlots(){return this._directiveAnalysis.asyncNames}compile(){if(this._requestedMode!=="interpret"){this._mode!=="jit"&&this._promote();for(let[e,n]of this._registry)n.compiled||(n.compiled=this._compileAction(e,n.directives));}}_invokeInternal(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return s;let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return X(u.data,r.counters)}let c;if(t.compiled?c=t.compiled.fn(r,d,t.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(t.compiled=this._compileAction(e,t.directives),c=t.compiled.fn(r,d,t.compiled.$)):(c=this._directiveRunner(t.directives,r),this._maybeAutoPromote(t)),this._afterAction!==null){let u=this._afterAction(e,n,c,r);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return s;let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return X(u.data,r.counters)}let c;if(t.compiled?c=await t.compiled.fn(r,d,t.compiled.$):(c=await this._directiveRunner(t.directives,r),this._maybeAutoPromote(t)),this._afterAction!==null){let u=this._afterAction(e,n,c,r);u!==void 0&&(c=u);}return c}_prepareInvoke(e,n,i){let s=this._registry.get(e);if(!s)return ve(e,i.counters);if(e.includes("/")&&!this._isAccessible(e,i))return xe(e,i.counters);if(i.depth>=i.limits.maxDepth)return ye(e,i.limits.maxDepth,i.counters);let t=Object.create(i.scope);n&&Object.assign(t,n);let r=i.child("action:"+e,0,e).withScope(t);return {stored:s,childFrame:r,childScope:t}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&this._promote());}_executeDirectives(e,n){return this._directiveExecutor(e,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,n){return this._directiveExecutor(e,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,n){let i=this._miniGraph.isAsync(e),s=this._miniGraph.isInteractive(e),{fn:t,isAsync:r,isInteractive:d}=se(n,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,i,s,this._interactiveHandlerSet),c={d:n,h:this._handlers,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:t,$:c,isAsync:r,isInteractive:d}}_isAccessible(e,n){let s="action:"+e.slice(0,e.lastIndexOf("/"));return n.path.includes(s)}_requireCtx(){if(this._ctx===void 0)throw new Error("No context set. Pass ctx to invoke(id, params, ctx), call setContext(ctx), or use context(ctx, fn).");return this._ctx}_promote(){this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit";}_buildJitDirectiveExecutor(){let{fn:e}=te(this._directiveAnalysis,this._isAsync);return e}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,n]of this._registry)n.compiled=this._compileAction(e,n.directives);}};function ke(o,e){return e?{next:()=>Promise.resolve({value:o,done:true}),return:()=>Promise.resolve({value:o,done:true}),throw:s=>Promise.reject(s),[Symbol.asyncIterator](){return this}}:{next:()=>({value:o,done:true}),return:()=>({value:o,done:true}),throw:i=>{throw i},[Symbol.iterator](){return this}}}function Qe(o,e,n,i,s,t){if(t){let c=o;return {async next(h){let C=await c.next(h);if(C.done){let y=C.value;if(s!==null){let p=s(e,n,y,i);p!==void 0&&(y=p);}return {value:y,done:true}}return {value:C.value,done:false}},async return(){let h=await c.return(void 0),C=h.value;if(h.done&&s!==null){let y=s(e,n,C,i);y!==void 0&&(C=y);}return {value:C,done:true}},async throw(h){let C=await c.throw(h);if(C.done){let y=C.value;if(s!==null){let p=s(e,n,y,i);p!==void 0&&(y=p);}return {value:y,done:true}}return {value:C.value,done:false}},[Symbol.asyncIterator](){return this}}}let r=o;return {next(c){let u=r.next(c);if(u.done){let h=u.value;if(s!==null){let C=s(e,n,h,i);C!==void 0&&(h=C);}return {value:h,done:true}}return {value:u.value,done:false}},return(){let c=r.return(void 0),u=c.value;if(c.done&&s!==null){let h=s(e,n,u,i);h!==void 0&&(u=h);}return {value:u,done:true}},throw(c){let u=r.throw(c);if(u.done){let h=u.value;if(s!==null){let C=s(e,n,h,i);C!==void 0&&(h=C);}return {value:h,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}function Xe(o){return new ue(o)}exports.RESERVED_TYPES=N;exports.SimpleEmitter=O;exports.buildActionExecutor=se;exports.buildDirectiveExecutor=te;exports.createActionEngine=Xe;exports.createDirectiveInterpreter=J;exports.drainAsync=Ee;exports.drainSync=Ie;exports.normalizeDirectives=L;exports.replayResponder=we;
4
+ ${a}
5
+ })();`),isAsync:e}}function ge(i,e,t){return `return{success:false,aborted:true,abortedBy:${i},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${t},counters};`}function nt(i,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function it(i,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function st(i,e,t,r){i.push("const counters=frame.counters;"),i.push("const ctx=frame.ctx;"),i.push("const errors=[];"),i.push("let appliedCount=0;"),i.push("let skippedCount=0;");for(let[o,n]of e)i.push(`const ${n}=$.h[${JSON.stringify(o)}];`);t&&i.push("const _hookBefore=$.hooks.beforeDirective;"),r&&i.push("const _hookAfter=$.hooks.afterDirective;");}function ot(i,e,t,r){i.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${e},totalCount:${e},counters};`),t&&i.push(`try{${r}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),i.push("return _finalResult;");}function ct(i,e,t){let r=`{
6
+ ${i}
7
+ }`;return t?`(${e?"async function*()":"function*()"}${r})()`:`(${e?"async ()=>":"()=>"}${r})()`}function at(i,e,t,r){let o=JSON.stringify(e.name);typeof e.resolve=="function"?(i.push("try{"),i.push(`scope[${o}]=${t}.resolve(ctx,scope).value;`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Binding resolve: "+_e});counters.errors++;}`)):i.push(`scope[${o}]=${t}.value;`);}function ut(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${t}.value};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.value};`);}function lt(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${t}.message};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.message};`);}function dt(i,e,t,r,o,n){let s=typeof e.as=="string",a=s?JSON.stringify(e.as):"";i.push(`{const _ack=yield{source:"pause",directive:${t},frame,index:${r},payload:{message:${t}.message}};`),i.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:_ack};`),i.push("appliedCount++;counters.directivesApplied++;"),s&&i.push(`if(_ack!==undefined)scope[${a}]=_ack;`),i.push("}");}function ft(i,e,t,r,o){let{L:n,total:s,typeField:a,handlerVars:c,hasBefore:u,hasAfter:d,awBefore:h,awAfter:f,awHandler:p,actionIsAsync:l,actionIsInteractive:g,interactiveHandlerSet:A}=o,D=i[a],R=c.get(D),P=typeof i.resolve=="function",b=typeof i.as=="string",I=Array.isArray(i.catch)&&i.catch.length>0,T=b?JSON.stringify(i.as):"",_=g&&A.has(D),C=o.blockCounter.n++;n.push(`_b${C}:{`);let k=u||P,x=u;k&&n.push(`let _dir=${e};`),x&&n.push("let _df=frame;"),u&&(n.push("try{"),n.push(`const _bd=${h}_hookBefore(${e},frame);`),n.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${C};}`),n.push(`if(_bd==="abort")${ge('"beforeDirective"',r-1,s)}`),n.push('if(typeof _bd==="object"&&_bd!==null){'),n.push(`if("abort" in _bd)${ge("_bd.abort",r-1,s)}`),n.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),n.push('if("directive" in _bd)_dir=_bd.directive;'),n.push("}"),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(n.push('if(typeof _dir.resolve==="function"){'),n.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}}`)):P&&(n.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}`));let E=k?"_dir":e,H=x?"_df":"frame";if(n.push("let _result;"),_?(n.push(`try{_result=yield* ${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(n.push(`try{_result=${p}${R}(${E},${H},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):(n.push(`try{_result=${p}${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")),n.push("if(_result.ok){"),n.push("appliedCount++;counters.directivesApplied++;"),b&&n.push(`scope[${T}]=_result.data;`),n.push(`if(_result.halt)${nt(r,s)}`),n.push("}else{"),n.push(`if(_result.halt)${it(r,s)}`),I){n.push('scope.$exception=_result.error||"handler failed";');let M=l?"$.runner":"$.runnerSync";n.push(`const _cr=${p}${M}(${e}.catch,${H});`),n.push("appliedCount+=_cr.appliedCount;"),n.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),n.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${r},totalCount:${s},counters,data:_cr.data};`);}else n.push(`errors.push({directiveIndex:${t},error:_result.error||"handler failed"});counters.errors++;`);n.push("}"),d&&(n.push("try{"),n.push(`const _ad=${f}_hookAfter(${E},_result,${H});`),n.push(`if(_ad==="abort")${ge('"afterDirective"',r,s)}`),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook afterDirective: "+_e});counters.errors++;}`)),n.push("}");}function pt(i,e,t,r,o,n){let{L:s}=n,a=i.cond,c=typeof a=="boolean";s.push("{"),c?s.push(`if(${a?"true":"false"}){`):(s.push("let _cond=false,_condOk=true;"),s.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),s.push(`catch(_e){errors.push({directiveIndex:${t},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),s.push("if(_condOk){"),s.push("if(_cond){"));let u=i.then;Array.isArray(u)&&u.length>0&&xe(u,`${e}.then`,r,o,n),s.push("}");let d=i.else;Array.isArray(d)&&d.length>0&&(s.push("else{"),xe(d,`${e}.else`,r,o,n),s.push("}")),c||s.push("}"),s.push("}");}function xe(i,e,t,r,o){let n=t!==-1;for(let s=0;s<i.length;s++){let a=i[s],c=`${e}[${s}]`,u=n?t:s,d=n?r:s+1;switch(a[o.typeField]){case "const":case "let":at(o.L,a,c,u);break;case "return":ut(o.L,a,c,u,d,o.total);break;case "throw":lt(o.L,a,c,u,d,o.total);break;case "pause":dt(o.L,a,c,u,d,o.total);break;case "if":{let f=n?t:s,p=n?r:s+1;pt(a,c,u,f,p,o);break}default:ft(a,c,u,d,o);break}}}function me(i,e,t){for(let r of i){let o=r[e];if(o&&!N.has(o)&&t.add(o),o==="if"){let n=r.then;Array.isArray(n)&&n.length>0&&me(n,e,t);let s=r.else;Array.isArray(s)&&s.length>0&&me(s,e,t);}}}var we=new Set;function _e(i,e,t,r=we,o,n=false,s=we){let a=[],c=i.length,{filledNames:u,hasAnyAsync:d,asyncNames:h}=e,f=u.has("beforeDirective"),p=u.has("afterDirective"),l=u.has("onDirectivesComplete"),g=o!==void 0?o:ce(i,r,t),A=d||g,D=A?"await ":"",R=h.has("beforeDirective")?"await ":"",P=h.has("afterDirective")?"await ":"",b=h.has("onDirectivesComplete")?"await ":"",I=new Set;me(i,t,I);let T=new Map,_=0;for(let E of I)T.set(E,`_h${_++}`);st(a,T,f,p),xe(i,"$.d",-1,0,{L:a,total:c,typeField:t,handlerVars:T,hasBefore:f,hasAfter:p,awBefore:R,awAfter:P,awHandler:D,actionIsAsync:A,actionIsInteractive:n,interactiveHandlerSet:s,blockCounter:{n:0}}),ot(a,c,l,b);let k=ct(a.join(`
8
+ `),A,n);return {fn:new Function("frame","scope","$",`"use strict";
9
+ return ${k};`),isAsync:A,isInteractive:n}}function ce(i,e,t){for(let r of i){let o=r[t];if(o&&e.has(o))return true;if(o==="if"){let s=r.then;if(Array.isArray(s)&&s.length>0&&ce(s,e,t))return true;let a=r.else;if(Array.isArray(a)&&a.length>0&&ce(a,e,t))return true}let n=r.catch;if(Array.isArray(n)&&n.length>0&&ce(n,e,t))return true}return false}function De(i,e,t){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:i,...t}}function Te(i,e){return De(e,`Action not found: "${i}"`,{aborted:true,abortedBy:"action-not-found"})}function Se(i,e,t){return De(t,`Max depth ${e} exceeded invoking "${i}"`,{aborted:true,abortedBy:"maxDepth"})}function $e(i,e){return De(e,`Action "${i}" is private (sub-action). Can only be invoked from within its parent scope.`)}function ae(i,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:i,counters:e}}function vt(i){return typeof i=="object"&&i!==null&&"execute"in i}function He(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&o[c].graph!==false&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Me(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Pe(i,e,t){if(!e)return t;let r=new Set(t);for(let[o,n]of i)n.executeInteractive!==void 0&&r.add(o);return r}function te(i,e,t){let r=Object.create(null);for(let[o,n]of i){let s;t&&n.executeInteractive!==void 0?s=n.executeInteractive:e&&n.executeAsync!==void 0?s=n.executeAsync:s=n.execute,r[o]=s;}return r}function Fe(i){let e=Object.create(null),t=new Map;for(let r of Object.keys(i)){let o=i[r];vt(o)?(e[r]=o.execute,t.set(r,o)):(e[r]=o,t.set(r,{execute:o}));}return {handlers:e,definitions:t}}function Ge(i,e){if(i==="*")return true;if(!i.includes("*"))return i===e;let t=i.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}function Be(i){return typeof i=="string"?{pattern:i}:i}function Ne(i,e,t){let r=new Map;if(!e&&!t){for(let o of i)r.set(o,{status:"available"});return r}if(e){let o=e.map(Be);for(let n of i){let s=o.some(a=>Ge(a.pattern,n));r.set(n,{status:s?"available":"denied"});}}else {let o=t.map(Be);for(let n of i){let s=o.find(a=>Ge(a.pattern,n));s?r.set(n,{status:"denied",reason:s.reason,source:s.source}):r.set(n,{status:"available"});}}return r}function Le(i){let{typeField:e,asyncHandlerSet:t,interactiveHandlerSet:r,subDirectiveFieldsForGraph:o}=i,n=new Map,s=new Set,a=new Set,c=new Set,u=new Set;return {upsert(d,h,f){n.set(d,ht(h,e,o)),ne(h,t,e,o)?s.add(d):s.delete(d),f||ie(h,r,e,o)?a.add(d):a.delete(d);},remove(d){n.delete(d),s.delete(d),a.delete(d);},recompute(){c=je(n,s),u=je(n,a);},isAsync(d){return c.has(d)},isInteractive(d){return u.has(d)},has(d){return n.has(d)}}}var ue=new Map;function ht(i,e,t=ue){let r=new Set;return re(i,e,t,r),r}function re(i,e,t,r){for(let o of i){let n=o[e];n==="action"&&typeof o.id=="string"&&r.add(o.id);let s=o.catch;if(Array.isArray(s)&&s.length>0&&re(s,e,t,r),n==="if"){let c=o.then;Array.isArray(c)&&c.length>0&&re(c,e,t,r);let u=o.else;Array.isArray(u)&&u.length>0&&re(u,e,t,r);continue}if(n===void 0)continue;let a=t.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];!Array.isArray(u)||u.length===0||re(u,e,t,r);}}}function ne(i,e,t,r=ue){for(let o of i){let n=o[t];if(n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ne(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ne(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ne(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ne(u,e,t,r))return true}}return false}function ie(i,e,t,r=ue){for(let o of i){let n=o[t];if(n==="pause"||n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ie(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ie(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ie(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ie(u,e,t,r))return true}}return false}function Q(i,e,t=ue){for(let r of i){let o=r[e];if(o==="pause")return true;let n=r.catch;if(Array.isArray(n)&&n.length>0&&Q(n,e,t))return true;if(o==="if"){let a=r.then;if(Array.isArray(a)&&a.length>0&&Q(a,e,t))return true;let c=r.else;if(Array.isArray(c)&&c.length>0&&Q(c,e,t))return true;continue}if(o===void 0)continue;let s=t.get(o);if(s!==void 0)for(let a=0;a<s.length;a++){let c=r[s[a]];if(!(!Array.isArray(c)||c.length===0)&&Q(c,e,t))return true}}return false}function je(i,e){let t=new Set(e),r=true;for(;r;){r=false;for(let[o,n]of i)if(!t.has(o)){for(let s of n)if(t.has(s)){t.add(o),r=true;break}}}return t}var le=class{depth=0;errors=[];warnings=[];actions=[];registered=[];begin(){this.depth++,this.depth===1&&(this.errors=[],this.warnings=[],this.actions=[],this.registered=[]);}endDepth(){if(this.depth<=0)throw new Error("endBatch() called without matching beginBatch()");return this.depth--,this.depth===0}isActive(){return this.depth>0}accumulate(e,t,r,o){this.errors.push(...e),this.warnings.push(...t);for(let n of r)this.actions.push(n);this.registered.push(...o);}};function Oe(i){for(let e of i)if(N.has(e))throw new Error(`Handler type "${e}" is reserved for engine-internal directives`)}function Ve(i,e){if(i&&e)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.")}function ze(i,e,t){if(i)return;if(e.size>0){let o=Array.from(e).join(", ");throw new Error(`Handler(s) [${o}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}let r=[];for(let[o,n]of t)n.executeInteractive!==void 0&&r.push(o);if(r.length>0)throw new Error(`Handler(s) [${r.join(", ")}] declare \`executeInteractive\` variant but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}function Ke(i){let e=new Set,t=new Set;for(let[r,o]of i)(o.async===true||core.isAsyncFunction(o.execute))&&e.add(r),(o.interactive===true||core.isGeneratorFunction(o.execute))&&t.add(r);return {asyncHandlerSet:e,interactiveHandlerSet:t}}function Ue(i,e,t,r){let o=t?te(i,true,false):e,n=r?te(i,t,true):null;return {handlersAsync:o,handlersInteractive:n}}function Ae(i,e){return e?{next:()=>Promise.resolve({value:i,done:true}),return:()=>Promise.resolve({value:i,done:true}),throw:o=>Promise.reject(o),[Symbol.asyncIterator](){return this}}:{next:()=>({value:i,done:true}),return:()=>({value:i,done:true}),throw:r=>{throw r},[Symbol.iterator](){return this}}}function qe(i,e,t,r,o,n){if(n){let c=i;return {async next(d){let h=await c.next(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},async return(){let d=await c.return(void 0),h=d.value;if(d.done&&o!==null){let f=o(e,t,h,r);f!==void 0&&(h=f);}return {value:h,done:true}},async throw(d){let h=await c.throw(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},[Symbol.asyncIterator](){return this}}}let s=i;return {next(c){let u=s.next(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},return(){let c=s.return(void 0),u=c.value;if(c.done&&o!==null){let d=o(e,t,u,r);d!==void 0&&(u=d);}return {value:u,done:true}},throw(c){let u=s.throw(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}var Dt=8,At="type",be={maxDepth:10,maxRules:1e4,maxDirectives:1e5},Re=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_handlersAsync;_handlersInteractive;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new X;_batch=new le;_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Dt,this._typeField=e.typeField??At,this._limits={maxDepth:e.limits?.maxDepth??be.maxDepth,maxRules:e.limits?.maxRules??be.maxRules,maxDirectives:e.limits?.maxDirectives??be.maxDirectives};let{handlers:t,definitions:r}=Fe(e.handlers);Oe(Object.keys(e.handlers)),Ve(e.allowedDirectives,e.blockedDirectives),this._handlers=t,this._definitions=r,this._directivePermissions=Ne(Object.keys(t),e.allowedDirectives,e.blockedDirectives),this._directiveHooks=e.directiveHooks??{},this._beforeAction=e.actionHooks?.beforeAction??null,this._afterAction=e.actionHooks?.afterAction??null,this._directiveAnalysis=core.analyzeSlots(this._directiveHooks,core.DIRECTIVE_SLOT_NAMES);let{asyncHandlerSet:o,interactiveHandlerSet:n}=Ke(this._definitions);this._asyncHandlerSet=o,this._interactiveHandlerSet=n,this._isInteractive=e.interactive!==void 0,ze(this._isInteractive,n,this._definitions),this._isAsync=this._directiveAnalysis.hasAnyAsync||o.size>0;let{handlersAsync:s,handlersInteractive:a}=Ue(this._definitions,this._handlers,this._isAsync,this._isInteractive);this._handlersAsync=s,this._handlersInteractive=a;let c=He(this._definitions);this._subDirectiveFieldsForGraph=c,this._subDirectiveFieldsAll=Me(this._definitions),this._miniGraph=Le({typeField:this._typeField,asyncHandlerSet:o,interactiveHandlerSet:n,subDirectiveFieldsForGraph:c}),this._engineRef=this._buildEngineRef();let u=oe(this._directiveAnalysis,false);this._directiveRunner=this._buildDirectiveRunner(),this._directiveRunnerSync=this._buildDirectiveRunnerSync(u);let d=this._buildExecutors(u);this._directiveExecutor=d.directiveExecutor,this._mode=d.mode,this._interactiveExecutor=d.interactiveExecutor;}_buildEngineRef(){return {runDirectives:(e,t)=>this._executeDirectives(e,t),runDirectivesAsync:(e,t)=>this._executeDirectivesAsync(e,t),invoke:(e,t,r)=>this._invokeInternal(e,t,r),invokeAsync:(e,t,r)=>this._invokeInternalAsync(e,t,r),isActionAsync:e=>this._miniGraph.has(e)?this._miniGraph.isAsync(e):void 0,isActionInteractive:e=>this._miniGraph.has(e)?this._miniGraph.isInteractive(e):void 0,invokeInteractive:(e,t,r)=>this._invokeInteractiveInternal(e,t,r),runDirectivesInteractive:(e,t)=>this._executeDirectivesInteractive(e,t),evaluateRules:()=>{throw new Error("evaluateRules() not available in ActionEngine context. Use createRuleEngine().")},evaluateRulesAsync:()=>{throw new Error("evaluateRulesAsync() not available in ActionEngine context. Use createRuleEngine().")}}}_buildDirectiveRunner(){let e=this._isAsync?this._handlersAsync:this._handlers;return (t,r)=>this._directiveExecutor(t,r,e,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildDirectiveRunnerSync(e){return (t,r)=>e(t,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildExecutors(e){let t,r;this._requestedMode==="jit"?(t=this._buildJitDirectiveExecutor(),r="jit"):this._isAsync?(t=oe(this._directiveAnalysis,true),r="interpret"):(t=e,r="interpret");let o=this._isInteractive?this._isAsync?he(this._directiveAnalysis,true):he(this._directiveAnalysis,false):null;return {directiveExecutor:t,mode:r,interactiveExecutor:o}}register(e){let t=[],r=[],o=[],n=[];for(let c of e){if(!c.id){r.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&Q(c.directives,this._typeField,this._subDirectiveFieldsForGraph)){r.push({actionId:c.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let u=ke(c,this._handlers,this._definitions,this._typeField);if(u.length>0){for(let d of u)r.push({actionId:c.id,error:d});continue}n.push(c);}for(let c of n){let u=B(c.directives,this._typeField,this._subDirectiveFieldsAll),d={definition:c,directives:u,compiled:null,invokeCount:0};this._registry.set(c.id,d),this._registeredIds.add(c.id),this._miniGraph.upsert(c.id,u,c.interactive===true),t.push(c.id);}if(this._batch.isActive())return this._batch.accumulate(r,o,n,t),{registered:t,errors:r,warnings:o};let s=t;if(n.length>0){this._miniGraph.recompute();let c=this._validateInteractiveVariants(t);c.errors.length>0&&r.push(...c.errors),c.warnings.length>0&&o.push(...c.warnings),s=c.validRegistered,this._invalidateAndMaybeRecompile();}let a={registered:s,errors:r,warnings:o};if(s.length>0){let c=new Set(s),u=n.filter(d=>c.has(d.id));this._emitter.emit("register",{actions:u,result:a,registered:s});}return a}unregister(e){let t=this._registry.delete(e);t&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let r=e+"/",o=[];for(let n of this._registry.keys())n.startsWith(r)&&(this._registry.delete(n),this._registeredIds.delete(n),this._miniGraph.remove(n),o.push(n));return t&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:o})),t}invoke(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);if(this._miniGraph.isAsync(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is async (transitively). Use invokeAsync() instead.`);if(this._directiveAnalysis.hasAnyAsync)throw new Error(`Cannot call invoke("${e}") \u2014 engine has async directive hooks. Use invokeAsync() instead.`);let o=r!==void 0?r:this._requireCtx(),n=core.createRootFrame(o,this._limits);return this._invokeInternal(e,t,n)}async invokeAsync(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let o=r!==void 0?r:this._requireCtx(),n=core.createRootFrame(o,this._limits);return this._invokeInternalAsync(e,t,n)}setContext(e){this._ctx=e;}context(e,t){let r=this._ctx;this._ctx=e;try{return t()}finally{this._ctx=r;}}beginBatch(){this._batch.begin();}endBatch(){if(!this._batch.endDepth())return {registered:[],errors:[],warnings:[]};let t=this._batch.registered;if(this._batch.registered.length>0){this._miniGraph.recompute();let o=this._validateInteractiveVariants(this._batch.registered);this._batch.errors.push(...o.errors),this._batch.warnings.push(...o.warnings),t=o.validRegistered,this._invalidateAndMaybeRecompile();}let r={registered:t,errors:this._batch.errors,warnings:this._batch.warnings};if(t.length>0){let o=new Set(t),n=this._batch.actions.filter(s=>o.has(s.id));this._emitter.emit("register",{actions:n,result:r,registered:t});}return r}on(e,t){return this._emitter.on(e,t)}get handlerDefinitions(){return this._definitions}get registeredIds(){return this._registeredIds}getActionDefinition(e){return this._registry.get(e)?.definition}get typeField(){return this._typeField}get subDirectiveFieldsForGraph(){return this._subDirectiveFieldsForGraph}get directivePermissions(){return this._directivePermissions}get isAsync(){return this._isAsync}get isInteractive(){return this._isInteractive}isActionAsync(e){if(this._miniGraph.has(e))return this._miniGraph.isAsync(e)}isActionInteractive(e){if(this._miniGraph.has(e))return this._miniGraph.isInteractive(e)}invokeInteractive(e,t,r){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let o=r!==void 0?r:this._requireCtx(),n=core.createRootFrame(o,this._limits);return this._invokeInteractiveInternal(e,t,n)}_invokeInteractiveInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return Ae(o,this._isAsync);let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return Ae(ae(u.data,s.counters),this._isAsync)}let c;if(n.compiled&&n.compiled.isInteractive)c=n.compiled.fn(s,s.scope,n.compiled.$);else {let u=this._interactiveExecutor;c=u(n.directives,s,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return qe(c,e,t,s,this._afterAction,this._isAsync)}_executeDirectivesInteractive(e,t){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("runDirectivesInteractive: engine has no `interactive` config");return this._interactiveExecutor(e,t,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}get compilationMode(){return this._mode}get directiveHookSlots(){return this._directiveAnalysis.filledNames}get asyncSlots(){return this._directiveAnalysis.asyncNames}compile(){if(this._requestedMode!=="interpret"){this._mode!=="jit"&&this._promote();for(let[e,t]of this._registry)t.compiled||(t.compiled=this._compileAction(e,t.directives));}}_invokeInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=n.compiled.fn(s,a,n.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(n.compiled=this._compileAction(e,n.directives),c=n.compiled.fn(s,a,n.compiled.$)):(c=this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=await n.compiled.fn(s,a,n.compiled.$):(c=await this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}_prepareInvoke(e,t,r){let o=this._registry.get(e);if(!o)return Te(e,r.counters);if(e.includes("/")&&!this._isAccessible(e,r))return $e(e,r.counters);if(r.depth>=r.limits.maxDepth)return Se(e,r.limits.maxDepth,r.counters);let n=Object.create(r.scope);t&&Object.assign(n,t);let s=r.child("action:"+e,0,e).withScope(n);return {stored:o,childFrame:s,childScope:n}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&this._promote());}_executeDirectives(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,t){let r=this._miniGraph.isAsync(e),o=this._miniGraph.isInteractive(e),n=Pe(this._definitions,o,this._interactiveHandlerSet),{fn:s,isAsync:a,isInteractive:c}=_e(t,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,r,o,n),u=te(this._definitions,a,c),d={d:t,h:u,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:s,$:d,isAsync:a,isInteractive:c}}_isAccessible(e,t){let o="action:"+e.slice(0,e.lastIndexOf("/"));return t.path.includes(o)}_requireCtx(){if(this._ctx===void 0)throw new Error("No context set. Pass ctx to invoke(id, params, ctx), call setContext(ctx), or use context(ctx, fn).");return this._ctx}_promote(){this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit";}_buildJitDirectiveExecutor(){let{fn:e}=ye(this._directiveAnalysis,this._isAsync);return e}_validateInteractiveVariants(e){let t=[],r=[],o=new Set(e),n=new Set;for(let a of this._registeredIds){if(!this._miniGraph.isInteractive(a))continue;let c=this._registry.get(a);if(c===void 0)continue;let u=Ee(c.directives,this._typeField,this._definitions,this._subDirectiveFieldsForGraph,this._interactiveHandlerSet,h=>this._miniGraph.isInteractive(h),core.isGeneratorFunction);if(u.size===0)continue;let d=o.has(a);for(let h of u){let f=`Action "${a}" is transitively interactive but handler "${h}" has no executeInteractive variant (and execute is not a generator function, and interactive flag is not set)`;d?(t.push({actionId:a,error:f,code:"MISSING_INTERACTIVE_VARIANT"}),n.add(a)):r.push({actionId:a,code:"MISSING_INTERACTIVE_VARIANT",message:f});}}if(n.size>0){for(let a of n)this._registry.delete(a),this._registeredIds.delete(a),this._miniGraph.remove(a);this._miniGraph.recompute();}return {validRegistered:e.filter(a=>!n.has(a)),errors:t,warnings:r}}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,t]of this._registry)t.compiled=this._compileAction(e,t.directives);}};function Ct(i){return new Re(i)}exports.RESERVED_TYPES=N;exports.SimpleEmitter=X;exports.buildActionExecutor=_e;exports.buildDirectiveExecutor=ye;exports.createActionEngine=Ct;exports.createDirectiveInterpreter=oe;exports.drainAsync=Je;exports.drainSync=We;exports.normalizeDirectives=B;exports.replayResponder=Ye;
package/dist/index.d.cts CHANGED
@@ -134,57 +134,69 @@ type AsyncHandlerExecute<TCtx> = (directive: Directive, frame: ExecutionFrame<TC
134
134
  */
135
135
  type InteractiveHandlerExecute<TCtx> = (directive: Directive, frame: ExecutionFrame<TCtx>, engine: ActionEngineRef<TCtx>) => Generator<unknown, ApplyResult, unknown> | AsyncGenerator<unknown, ApplyResult, unknown>;
136
136
  /**
137
- * Handler sync `execute` retorna `ApplyResult` direto. É o modo default:
138
- * sem flag e sem `async function`/`function*`, o handler é tratado como sync.
139
- */
140
- interface SyncHandlerDefinition<TCtx> extends HandlerBaseDefinition {
141
- async?: false;
142
- interactive?: false;
143
- execute: SyncHandlerExecute<TCtx>;
144
- }
145
- /**
146
- * Handler async — `execute` retorna `Promise<ApplyResult>`. Marcado com
147
- * `async: true` ou detectado via `isAsyncFunction(execute)` (cobre
148
- * `async function`). Use a flag pra wrappers que retornam Promise sem serem
149
- * `async function` (ex: factory que delega via `.then`).
137
+ * Handler V2 (objeto com fases). Multi-variant: o handler declara `execute`
138
+ * como floor (sync, async ou generator) e opcionalmente `executeAsync` e
139
+ * `executeInteractive` como variantes especializadas pra quando a action
140
+ * que o usa é transitivamente async/interactive.
150
141
  *
151
- * Quando o engine um handler async: inclui no async handler set, força
152
- * `isAsync = true` no engine inteiro, e emite `await` ao invocá-lo no
153
- * interpreter async e nos JITs.
154
- */
155
- interface AsyncHandlerDefinition<TCtx> extends HandlerBaseDefinition {
156
- async: true;
157
- interactive?: false;
158
- execute: AsyncHandlerExecute<TCtx>;
159
- }
160
- /**
161
- * Handler interactive — `execute` é generator (sync ou async). Marcado com
162
- * `interactive: true` ou detectado via `isGeneratorFunction(execute)` (cobre
163
- * `function*` e `async function*`). Use a flag pra wrappers que retornam
164
- * iterator sem serem generator function. Pode também ser `async` (generator
165
- * async) — daí `async: true` junto.
142
+ * Seleção da variante (compile-time da action, via mini-graph):
143
+ * - Action transitivamente interactive `executeInteractive` (se presente),
144
+ * senão `execute` (deve ser generator function ou flag `interactive: true`,
145
+ * validado em register-time)
146
+ * - Action transitivamente async → `executeAsync` (se presente), senão
147
+ * `execute` (engine awaita — `await` em valor sync é no-op)
148
+ * - Action sync → `execute`
166
149
  *
167
- * Quando o engine um handler interactive: inclui no interactive handler set,
168
- * propaga `_interactiveActions` transitivamente no mini-graph, emite
169
- * `yield* handler(...)` ao invocá-lo nas actions interactive, e exige
170
- * `engine.invokeInteractive()` em actions cuja sub-árvore o use. Handler
171
- * `interactive: true` em engine sem `interactive` config → erro no constructor
172
- * (fail-fast).
150
+ * Auto-detect de modo do handler:
151
+ * - `executeAsync` presente OU `async: true` OU `isAsyncFunction(execute)`
152
+ * handler é async (adicionado ao `asyncHandlerSet`)
153
+ * - `executeInteractive` presente OU `interactive: true` OU
154
+ * `isGeneratorFunction(execute)` handler é interactive (adicionado ao
155
+ * `interactiveHandlerSet`)
156
+ *
157
+ * Custo runtime: zero. A seleção de variante acontece 1x em register/compile
158
+ * time da action — `$.h[type]` no JIT já vem pré-resolvido pra função certa.
159
+ *
160
+ * Backwards compat: handlers single-mode (só `execute`) continuam funcionando
161
+ * idênticos. As variantes opcionais são pra wrapper handlers (simulate, try_,
162
+ * transaction) que precisam adaptar à mode do sub-bloco.
173
163
  */
174
- interface InteractiveHandlerDefinition<TCtx> extends HandlerBaseDefinition {
175
- interactive: true;
164
+ interface HandlerDefinition<TCtx> extends HandlerBaseDefinition {
165
+ /**
166
+ * Floor execute. Pode ser sync, async, ou generator. O modo é
167
+ * auto-detectado via `isAsyncFunction`/`isGeneratorFunction`, ou
168
+ * declarado explícito via `async`/`interactive` flags.
169
+ */
170
+ execute: SyncHandlerExecute<TCtx> | AsyncHandlerExecute<TCtx> | InteractiveHandlerExecute<TCtx>;
171
+ /**
172
+ * Variante async opcional. Quando presente, engine usa esta no lugar de
173
+ * `execute` em actions transitivamente async. Sua presença marca o
174
+ * handler como async (entra no `asyncHandlerSet`).
175
+ */
176
+ executeAsync?: AsyncHandlerExecute<TCtx>;
177
+ /**
178
+ * Variante interactive opcional. Quando presente, engine usa esta no
179
+ * lugar de `execute` em actions transitivamente interactive. Sua
180
+ * presença marca o handler como interactive (entra no
181
+ * `interactiveHandlerSet`). Convenção: `async function*` (cobre tanto
182
+ * sync+interactive quanto async+interactive — o `await` interno em
183
+ * valor sync é no-op, V8 otimiza).
184
+ */
185
+ executeInteractive?: InteractiveHandlerExecute<TCtx>;
186
+ /**
187
+ * Flag explícita — handler é async (mesmo que `execute` não seja
188
+ * `async function`). Use pra wrappers que retornam Promise sem serem
189
+ * `async function`.
190
+ */
176
191
  async?: boolean;
177
- execute: InteractiveHandlerExecute<TCtx>;
192
+ /**
193
+ * Flag explícita — handler é interactive (mesmo que `execute` não seja
194
+ * generator). Use pra wrappers que retornam iterator sem serem
195
+ * generator function. Em engine sem `interactive` config → erro no
196
+ * constructor (fail-fast).
197
+ */
198
+ interactive?: boolean;
178
199
  }
179
- /**
180
- * Handler V2 (objeto com fases). Discriminated union pelo modo de execução —
181
- * `async` e `interactive` discriminam, `execute` refina seu retorno conforme
182
- * o modo. Tipar como `HandlerDefinition<TCtx>` continua válido (é o agregado);
183
- * narrowing pelos flags refina pro subtipo. Quem sabe o modo do seu handler
184
- * pode tipar diretamente como `SyncHandlerDefinition` etc. e chamar
185
- * `handler.execute(...)` sem `await`/narrowing.
186
- */
187
- type HandlerDefinition<TCtx> = SyncHandlerDefinition<TCtx> | AsyncHandlerDefinition<TCtx> | InteractiveHandlerDefinition<TCtx>;
188
200
  /**
189
201
  * Aceita handler V1 (função) ou V2 (objeto com fases).
190
202
  * Backwards compat: função simples é tratada como { execute: fn }.
@@ -713,4 +725,4 @@ interface GeneratedActionExecutor {
713
725
  */
714
726
  declare function buildActionExecutor(directives: readonly Directive[], analysis: SlotAnalysis, typeField: string, asyncHandlerSet?: ReadonlySet<string>, actionUsesAsyncOverride?: boolean, actionIsInteractive?: boolean, interactiveHandlerSet?: ReadonlySet<string>): GeneratedActionExecutor;
715
727
 
716
- export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerDefinition, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedActionExecutorFn, type GeneratedDirectiveExecutor, type HandlerAnalysis, type HandlerBaseDefinition, type HandlerDefinition, type HandlerInput, type HandlerInputMap, type IActionEngine, type IActionEngineConfig, type InteractiveApplyResult, type InteractiveConfig, type InteractiveHandlerDefinition, type InteractiveHandlerExecute, type InteractiveSession, type Listener, type PauseEvent, RESERVED_TYPES, type RegisterError, type RegisterEvent, type RegisterResult, type Responder, SimpleEmitter, type SubDirectiveFieldConfig, type SyncHandlerDefinition, type SyncHandlerExecute, type UnregisterEvent, type ValidationResult, buildActionExecutor, buildDirectiveExecutor, createActionEngine, createDirectiveInterpreter, drainAsync, drainSync, normalizeDirectives, replayResponder };
728
+ export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedActionExecutorFn, type GeneratedDirectiveExecutor, type HandlerAnalysis, type HandlerBaseDefinition, type HandlerDefinition, type HandlerInput, type HandlerInputMap, type IActionEngine, type IActionEngineConfig, type InteractiveApplyResult, type InteractiveConfig, type InteractiveHandlerExecute, type InteractiveSession, type Listener, type PauseEvent, RESERVED_TYPES, type RegisterError, type RegisterEvent, type RegisterResult, type Responder, SimpleEmitter, type SubDirectiveFieldConfig, type SyncHandlerExecute, type UnregisterEvent, type ValidationResult, buildActionExecutor, buildDirectiveExecutor, createActionEngine, createDirectiveInterpreter, drainAsync, drainSync, normalizeDirectives, replayResponder };
package/dist/index.d.ts CHANGED
@@ -134,57 +134,69 @@ type AsyncHandlerExecute<TCtx> = (directive: Directive, frame: ExecutionFrame<TC
134
134
  */
135
135
  type InteractiveHandlerExecute<TCtx> = (directive: Directive, frame: ExecutionFrame<TCtx>, engine: ActionEngineRef<TCtx>) => Generator<unknown, ApplyResult, unknown> | AsyncGenerator<unknown, ApplyResult, unknown>;
136
136
  /**
137
- * Handler sync `execute` retorna `ApplyResult` direto. É o modo default:
138
- * sem flag e sem `async function`/`function*`, o handler é tratado como sync.
139
- */
140
- interface SyncHandlerDefinition<TCtx> extends HandlerBaseDefinition {
141
- async?: false;
142
- interactive?: false;
143
- execute: SyncHandlerExecute<TCtx>;
144
- }
145
- /**
146
- * Handler async — `execute` retorna `Promise<ApplyResult>`. Marcado com
147
- * `async: true` ou detectado via `isAsyncFunction(execute)` (cobre
148
- * `async function`). Use a flag pra wrappers que retornam Promise sem serem
149
- * `async function` (ex: factory que delega via `.then`).
137
+ * Handler V2 (objeto com fases). Multi-variant: o handler declara `execute`
138
+ * como floor (sync, async ou generator) e opcionalmente `executeAsync` e
139
+ * `executeInteractive` como variantes especializadas pra quando a action
140
+ * que o usa é transitivamente async/interactive.
150
141
  *
151
- * Quando o engine um handler async: inclui no async handler set, força
152
- * `isAsync = true` no engine inteiro, e emite `await` ao invocá-lo no
153
- * interpreter async e nos JITs.
154
- */
155
- interface AsyncHandlerDefinition<TCtx> extends HandlerBaseDefinition {
156
- async: true;
157
- interactive?: false;
158
- execute: AsyncHandlerExecute<TCtx>;
159
- }
160
- /**
161
- * Handler interactive — `execute` é generator (sync ou async). Marcado com
162
- * `interactive: true` ou detectado via `isGeneratorFunction(execute)` (cobre
163
- * `function*` e `async function*`). Use a flag pra wrappers que retornam
164
- * iterator sem serem generator function. Pode também ser `async` (generator
165
- * async) — daí `async: true` junto.
142
+ * Seleção da variante (compile-time da action, via mini-graph):
143
+ * - Action transitivamente interactive `executeInteractive` (se presente),
144
+ * senão `execute` (deve ser generator function ou flag `interactive: true`,
145
+ * validado em register-time)
146
+ * - Action transitivamente async → `executeAsync` (se presente), senão
147
+ * `execute` (engine awaita — `await` em valor sync é no-op)
148
+ * - Action sync → `execute`
166
149
  *
167
- * Quando o engine um handler interactive: inclui no interactive handler set,
168
- * propaga `_interactiveActions` transitivamente no mini-graph, emite
169
- * `yield* handler(...)` ao invocá-lo nas actions interactive, e exige
170
- * `engine.invokeInteractive()` em actions cuja sub-árvore o use. Handler
171
- * `interactive: true` em engine sem `interactive` config → erro no constructor
172
- * (fail-fast).
150
+ * Auto-detect de modo do handler:
151
+ * - `executeAsync` presente OU `async: true` OU `isAsyncFunction(execute)`
152
+ * handler é async (adicionado ao `asyncHandlerSet`)
153
+ * - `executeInteractive` presente OU `interactive: true` OU
154
+ * `isGeneratorFunction(execute)` handler é interactive (adicionado ao
155
+ * `interactiveHandlerSet`)
156
+ *
157
+ * Custo runtime: zero. A seleção de variante acontece 1x em register/compile
158
+ * time da action — `$.h[type]` no JIT já vem pré-resolvido pra função certa.
159
+ *
160
+ * Backwards compat: handlers single-mode (só `execute`) continuam funcionando
161
+ * idênticos. As variantes opcionais são pra wrapper handlers (simulate, try_,
162
+ * transaction) que precisam adaptar à mode do sub-bloco.
173
163
  */
174
- interface InteractiveHandlerDefinition<TCtx> extends HandlerBaseDefinition {
175
- interactive: true;
164
+ interface HandlerDefinition<TCtx> extends HandlerBaseDefinition {
165
+ /**
166
+ * Floor execute. Pode ser sync, async, ou generator. O modo é
167
+ * auto-detectado via `isAsyncFunction`/`isGeneratorFunction`, ou
168
+ * declarado explícito via `async`/`interactive` flags.
169
+ */
170
+ execute: SyncHandlerExecute<TCtx> | AsyncHandlerExecute<TCtx> | InteractiveHandlerExecute<TCtx>;
171
+ /**
172
+ * Variante async opcional. Quando presente, engine usa esta no lugar de
173
+ * `execute` em actions transitivamente async. Sua presença marca o
174
+ * handler como async (entra no `asyncHandlerSet`).
175
+ */
176
+ executeAsync?: AsyncHandlerExecute<TCtx>;
177
+ /**
178
+ * Variante interactive opcional. Quando presente, engine usa esta no
179
+ * lugar de `execute` em actions transitivamente interactive. Sua
180
+ * presença marca o handler como interactive (entra no
181
+ * `interactiveHandlerSet`). Convenção: `async function*` (cobre tanto
182
+ * sync+interactive quanto async+interactive — o `await` interno em
183
+ * valor sync é no-op, V8 otimiza).
184
+ */
185
+ executeInteractive?: InteractiveHandlerExecute<TCtx>;
186
+ /**
187
+ * Flag explícita — handler é async (mesmo que `execute` não seja
188
+ * `async function`). Use pra wrappers que retornam Promise sem serem
189
+ * `async function`.
190
+ */
176
191
  async?: boolean;
177
- execute: InteractiveHandlerExecute<TCtx>;
192
+ /**
193
+ * Flag explícita — handler é interactive (mesmo que `execute` não seja
194
+ * generator). Use pra wrappers que retornam iterator sem serem
195
+ * generator function. Em engine sem `interactive` config → erro no
196
+ * constructor (fail-fast).
197
+ */
198
+ interactive?: boolean;
178
199
  }
179
- /**
180
- * Handler V2 (objeto com fases). Discriminated union pelo modo de execução —
181
- * `async` e `interactive` discriminam, `execute` refina seu retorno conforme
182
- * o modo. Tipar como `HandlerDefinition<TCtx>` continua válido (é o agregado);
183
- * narrowing pelos flags refina pro subtipo. Quem sabe o modo do seu handler
184
- * pode tipar diretamente como `SyncHandlerDefinition` etc. e chamar
185
- * `handler.execute(...)` sem `await`/narrowing.
186
- */
187
- type HandlerDefinition<TCtx> = SyncHandlerDefinition<TCtx> | AsyncHandlerDefinition<TCtx> | InteractiveHandlerDefinition<TCtx>;
188
200
  /**
189
201
  * Aceita handler V1 (função) ou V2 (objeto com fases).
190
202
  * Backwards compat: função simples é tratada como { execute: fn }.
@@ -713,4 +725,4 @@ interface GeneratedActionExecutor {
713
725
  */
714
726
  declare function buildActionExecutor(directives: readonly Directive[], analysis: SlotAnalysis, typeField: string, asyncHandlerSet?: ReadonlySet<string>, actionUsesAsyncOverride?: boolean, actionIsInteractive?: boolean, interactiveHandlerSet?: ReadonlySet<string>): GeneratedActionExecutor;
715
727
 
716
- export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerDefinition, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedActionExecutorFn, type GeneratedDirectiveExecutor, type HandlerAnalysis, type HandlerBaseDefinition, type HandlerDefinition, type HandlerInput, type HandlerInputMap, type IActionEngine, type IActionEngineConfig, type InteractiveApplyResult, type InteractiveConfig, type InteractiveHandlerDefinition, type InteractiveHandlerExecute, type InteractiveSession, type Listener, type PauseEvent, RESERVED_TYPES, type RegisterError, type RegisterEvent, type RegisterResult, type Responder, SimpleEmitter, type SubDirectiveFieldConfig, type SyncHandlerDefinition, type SyncHandlerExecute, type UnregisterEvent, type ValidationResult, buildActionExecutor, buildDirectiveExecutor, createActionEngine, createDirectiveInterpreter, drainAsync, drainSync, normalizeDirectives, replayResponder };
728
+ export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedActionExecutorFn, type GeneratedDirectiveExecutor, type HandlerAnalysis, type HandlerBaseDefinition, type HandlerDefinition, type HandlerInput, type HandlerInputMap, type IActionEngine, type IActionEngineConfig, type InteractiveApplyResult, type InteractiveConfig, type InteractiveHandlerExecute, type InteractiveSession, type Listener, type PauseEvent, RESERVED_TYPES, type RegisterError, type RegisterEvent, type RegisterResult, type Responder, SimpleEmitter, type SubDirectiveFieldConfig, type SyncHandlerExecute, type UnregisterEvent, type ValidationResult, buildActionExecutor, buildDirectiveExecutor, createActionEngine, createDirectiveInterpreter, drainAsync, drainSync, normalizeDirectives, replayResponder };
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import {processIntercept,Intercept,analyzeSlots,DIRECTIVE_SLOT_NAMES,isAsyncFunction,isGeneratorFunction,createRootFrame}from'@statedelta-actions/core';function Ie(o,e){let n;for(;;){let i=o.next(n);if(i.done)return i.value;n=e?e(i.value):void 0;}}async function Ee(o,e){let n;for(;;){let i=await o.next(n);if(i.done)return i.value;n=e?await e(i.value):void 0;}}function we(o){let e=0;return ()=>{if(!(e>=o.length))return o[e++]}}var O=class{_listeners=new Map;on(e,n){let i=this._listeners.get(e);i||(i=new Set,this._listeners.set(e,i)),i.add(n);let s=false;return ()=>{s||(s=true,i.delete(n),i.size===0&&this._listeners.delete(e));}}once(e,n){let i=this.on(e,s=>{i(),n(s);});return i}emit(e,n){let i=this._listeners.get(e);if(!i||i.size===0)return;let s=[...i];for(let t=0;t<s.length;t++)try{s[t](n);}catch(r){console.error(`[SimpleEmitter] Listener error on "${e}":`,r);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let n=this._listeners.get(e);return n!==void 0&&n.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var N=new Set(["const","let","return","throw","pause","if"]);function le(o,e,n,i){let s=[];return q(o.directives,e,n,i,"directive",s,o.id),s}function q(o,e,n,i,s,t,r){for(let d=0;d<o.length;d++){let c=o[d],u=c[i],h=`${s}[${d}]`;if(!u){t.push(`${h}: missing type field "${i}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&t.push(`${h}: "if" requires cond as function or boolean`);let f=c.then;Array.isArray(f)?q(f,e,n,i,`${h}.then`,t,r):t.push(`${h}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?q(D,e,n,i,`${h}.else`,t,r):t.push(`${h}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${r}" ${h}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let C=n.get(u);if(C?.validate)try{let g=C.validate(c);g&&!g.valid&&t.push(`${h}: ${g.error??"validation failed"}`);}catch(g){t.push(`${h}: validate threw: ${g}`);}let y=c.catch;if(y&&Array.isArray(y))for(let g=0;g<y.length;g++){let D=y[g][i];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${r}" ${h}.catch[${g}]: no handler registered for type "${D}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let p=C?.subDirectives;if(p===void 0)continue;let m=Object.keys(p);for(let g=0;g<m.length;g++){let f=m[g];if(f==="catch")continue;let D=c[f];if(D===void 0){if(p[f].required)throw new Error(`Action "${r}" ${h}: handler "${u}" requires sub-directives field "${f}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${r}" ${h}.${f}: must be an array of directives`);q(D,e,n,i,`${h}.${f}`,t,r);}}}var Te=new Map;function L(o,e,n=Te){let i=o.length,s=new Array(i);for(let t=0;t<i;t++){let r=o[t],d=r[e],c=r,u=false,h=r.catch;if(Array.isArray(h)&&h.length>0&&(c={...c,catch:L(h,e,n)},u=true),d==="if"){let C=r.then;Array.isArray(C)&&C.length>0&&(c={...c,then:L(C,e,n)},u=true);let y=r.else;Array.isArray(y)&&y.length>0&&(c={...c,else:L(y,e,n)},u=true);}else if(d!==void 0){let C=n.get(d);if(C!==void 0)for(let y=0;y<C.length;y++){let p=C[y],m=r[p];!Array.isArray(m)||m.length===0||(c={...c,[p]:L(m,e,n)},u=true);}}s[t]=u?c:r;}return s}function W(o,e,n,i,s,t,r){return {success:false,aborted:true,abortedBy:o,appliedCount:e,skippedCount:n,errors:i,processedCount:s,totalCount:t,counters:r}}function $e(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return function(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="value"in l?l.value:"return"in l?l.return:x.value;return {success:!0,aborted:!1,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.value};continue}if(E==="throw"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="message"in l?l.message:"throw"in l?l.throw:x.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.message};continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=processIntercept(c.beforeDirective(_,r),"beforeDirective");if(a.action===Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===Intercept.ABORT)return W(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{b=F(_,k,h);}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data};let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=h.runDirectives(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(c.afterDirective(_,b,k)==="abort")return W("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{c.onDirectivesComplete(P);}catch{}return P}}function Se(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return async function(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="value"in l?l.value:"return"in l?l.return:x.value;return {success:!0,aborted:!1,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.value};continue}if(E==="throw"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="message"in l?l.message:"throw"in l?l.throw:x.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.message};continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=processIntercept(await c.beforeDirective(_,r),"beforeDirective");if(a.action===Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===Intercept.ABORT)return W(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{b=await F(_,k,h);}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data};let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=await h.runDirectivesAsync(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(await c.afterDirective(_,b,k)==="abort")return W("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{await c.onDirectivesComplete(P);}catch{}return P}}function J(o,e){return e?Se(o):$e(o)}function B(o,e,n,i,s,t,r,d){return {success:false,aborted:true,abortedBy:o,appliedCount:e,skippedCount:n,errors:i,processedCount:s,totalCount:t,counters:r,data:d}}function pe(o){if(o===null||typeof o!="object")return null;if(typeof o.next=="function")return o;let e=o.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function He(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return function*(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I,l=x.value;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="value"in v?v.value:"return"in v?v.return:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:l}}if(E==="throw"){let a=I,l=x.message;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="message"in v?v.message:"throw"in v?v.throw:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return B("throw",m,g,p,a,y,f,l)}if(E==="pause"){let a=I,l=yield {source:"pause",directive:x,frame:r,index:A,payload:{message:x.message}};if(l===false||l==="abort"||l==="cancel")return B("pause",m,g,p,a,y,f,l);m++,f.directivesApplied++,typeof x.as=="string"&&l!==void 0&&(D[x.as]=l);continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=processIntercept(c.beforeDirective(_,r),"beforeDirective");if(a.action===Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===Intercept.ABORT)return B(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{let a=F(_,k,h),l=pe(a);l!==null?b=yield*l:b=a;}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return B("halt",m,g,p,H,y,f,b.data);let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=h.runDirectives(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(c.afterDirective(_,b,k)==="abort")return B("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{c.onDirectivesComplete(P);}catch{}return P}}function Me(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return async function*(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I,l=x.value;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="value"in v?v.value:"return"in v?v.return:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:l}}if(E==="throw"){let a=I,l=x.message;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="message"in v?v.message:"throw"in v?v.throw:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return B("throw",m,g,p,a,y,f,l)}if(E==="pause"){let a=I,l=yield {source:"pause",directive:x,frame:r,index:A,payload:{message:x.message}};if(l===false||l==="abort"||l==="cancel")return B("pause",m,g,p,a,y,f,l);m++,f.directivesApplied++,typeof x.as=="string"&&l!==void 0&&(D[x.as]=l);continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=processIntercept(await c.beforeDirective(_,r),"beforeDirective");if(a.action===Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===Intercept.ABORT)return B(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{let a=await F(_,k,h),l=pe(a);l!==null?b=yield*l:b=a;}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return B("halt",m,g,p,H,y,f,b.data);let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=await h.runDirectivesAsync(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(await c.afterDirective(_,b,k)==="abort")return B("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{await c.onDirectivesComplete(P);}catch{}return P}}function ee(o,e){return e?Me(o):He(o)}function te(o,e=o.hasAnyAsync){let{filledNames:n}=o,i=h=>n.has(h),s=h=>o.asyncNames.has(h)?"await ":"",t=e?"await ":"",r=[];for(let h of n)r.push(`const ${h} = directiveHooks.${h};`);r.push("const len = Math.min(directives.length, maxDirectives);"),r.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),r.push("const counters = frame.counters;"),r.push("for (let i = 0; i < len; i++) {"),r.push(" let directive = directives[i];"),i("beforeDirective")?(r.push(" let _df = frame;"),r.push(" try {"),r.push(` const _bd = ${s("beforeDirective")}beforeDirective(directive, frame);`),r.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),r.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),r.push(' if (typeof _bd === "object" && _bd !== null) {'),r.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),r.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),r.push(' if ("directive" in _bd) directive = _bd.directive;'),r.push(" }"),r.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):r.push(" const _df = frame;"),r.push(' if (typeof directive.resolve === "function") {'),r.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),r.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),r.push(" }"),r.push(" const _type = directive[typeField];"),r.push(" const _handler = _type ? handlers[_type] : undefined;"),r.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),r.push(" let _result;"),r.push(` try { _result = ${t}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),r.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),r.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),i("afterDirective")&&(r.push(" try {"),r.push(` const _ad = ${s("afterDirective")}afterDirective(directive, _result, _df);`),r.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),r.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),r.push("}"),r.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),i("onDirectivesComplete")&&r.push(`try { ${s("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),r.push("return _finalResult;");let d=r.join(`
1
+ import {analyzeSlots,DIRECTIVE_SLOT_NAMES,createRootFrame,processIntercept,Intercept,isAsyncFunction,isGeneratorFunction}from'@statedelta-actions/core';function We(i,e){let t;for(;;){let r=i.next(t);if(r.done)return r.value;t=e?e(r.value):void 0;}}async function Je(i,e){let t;for(;;){let r=await i.next(t);if(r.done)return r.value;t=e?await e(r.value):void 0;}}function Ye(i){let e=0;return ()=>{if(!(e>=i.length))return i[e++]}}var X=class{_listeners=new Map;on(e,t){let r=this._listeners.get(e);r||(r=new Set,this._listeners.set(e,r)),r.add(t);let o=false;return ()=>{o||(o=true,r.delete(t),r.size===0&&this._listeners.delete(e));}}once(e,t){let r=this.on(e,o=>{r(),t(o);});return r}emit(e,t){let r=this._listeners.get(e);if(!r||r.size===0)return;let o=[...r];for(let n=0;n<o.length;n++)try{o[n](t);}catch(s){console.error(`[SimpleEmitter] Listener error on "${e}":`,s);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let t=this._listeners.get(e);return t!==void 0&&t.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var N=new Set(["const","let","return","throw","pause","if"]);function ke(i,e,t,r){let o=[];return se(i.directives,e,t,r,"directive",o,i.id),o}function se(i,e,t,r,o,n,s){for(let a=0;a<i.length;a++){let c=i[a],u=c[r],d=`${o}[${a}]`;if(!u){n.push(`${d}: missing type field "${r}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&n.push(`${d}: "if" requires cond as function or boolean`);let A=c.then;Array.isArray(A)?se(A,e,t,r,`${d}.then`,n,s):n.push(`${d}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?se(D,e,t,r,`${d}.else`,n,s):n.push(`${d}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${s}" ${d}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let h=t.get(u);if(h?.validate)try{let g=h.validate(c);g&&!g.valid&&n.push(`${d}: ${g.error??"validation failed"}`);}catch(g){n.push(`${d}: validate threw: ${g}`);}let f=c.catch;if(f&&Array.isArray(f))for(let g=0;g<f.length;g++){let D=f[g][r];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${s}" ${d}.catch[${g}]: no handler registered for type "${D}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let p=h?.subDirectives;if(p===void 0)continue;let l=Object.keys(p);for(let g=0;g<l.length;g++){let A=l[g];if(A==="catch")continue;let D=c[A];if(D===void 0){if(p[A].required)throw new Error(`Action "${s}" ${d}: handler "${u}" requires sub-directives field "${A}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${s}" ${d}.${A}: must be an array of directives`);se(D,e,t,r,`${d}.${A}`,n,s);}}}var Qe=new Map;function B(i,e,t=Qe){let r=i.length,o=new Array(r);for(let n=0;n<r;n++){let s=i[n],a=s[e],c=s,u=false,d=s.catch;if(Array.isArray(d)&&d.length>0&&(c={...c,catch:B(d,e,t)},u=true),a==="if"){let h=s.then;Array.isArray(h)&&h.length>0&&(c={...c,then:B(h,e,t)},u=true);let f=s.else;Array.isArray(f)&&f.length>0&&(c={...c,else:B(f,e,t)},u=true);}else if(a!==void 0){let h=t.get(a);if(h!==void 0)for(let f=0;f<h.length;f++){let p=h[f],l=s[p];!Array.isArray(l)||l.length===0||(c={...c,[p]:B(l,e,t)},u=true);}}o[n]=u?c:s;}return o}function Ee(i,e,t,r,o,n,s){let a=new Set;return Z(i,e,t,r,o,n,s,a),a}function Z(i,e,t,r,o,n,s,a){for(let c of i){let u=c[e];if(u!==void 0){let f=t.get(u);if(f!==void 0&&f.subDirectives!==void 0){let p=r.get(u);if(p!==void 0){let l=false;for(let g=0;g<p.length;g++){let A=c[p[g]];if(!(!Array.isArray(A)||A.length===0)&&ee(A,e,r,o,n)){l=true;break}}l&&(f.executeInteractive!==void 0||f.interactive===true||s(f.execute)||a.add(u));}}}let d=c.catch;if(Array.isArray(d)&&d.length>0&&Z(d,e,t,r,o,n,s,a),u==="if"){let f=c.then;Array.isArray(f)&&f.length>0&&Z(f,e,t,r,o,n,s,a);let p=c.else;Array.isArray(p)&&p.length>0&&Z(p,e,t,r,o,n,s,a);continue}if(u===void 0)continue;let h=r.get(u);if(h!==void 0)for(let f=0;f<h.length;f++){let p=c[h[f]];!Array.isArray(p)||p.length===0||Z(p,e,t,r,o,n,s,a);}}}function ee(i,e,t,r,o){for(let n of i){let s=n[e];if(s==="pause"||s!==void 0&&r.has(s)||s==="action"&&typeof n.id=="string"&&o(n.id))return true;let a=n.catch;if(Array.isArray(a)&&a.length>0&&ee(a,e,t,r,o))return true;if(s==="if"){let u=n.then;if(Array.isArray(u)&&u.length>0&&ee(u,e,t,r,o))return true;let d=n.else;if(Array.isArray(d)&&d.length>0&&ee(d,e,t,r,o))return true;continue}if(s===void 0)continue;let c=t.get(s);if(c!==void 0)for(let u=0;u<c.length;u++){let d=n[c[u]];if(!(!Array.isArray(d)||d.length===0)&&ee(d,e,t,r,o))return true}}return false}function j(i,e,t,r,o,n){let s=i.name;if(typeof i.resolve=="function")try{t[s]=i.resolve(e,t).value;}catch(a){r.push({directiveIndex:o,error:`Binding resolve: ${a}`}),n.errors++;}else t[s]=i.value;}function L(i,e,t,r,o,n){let s=i.value;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="value"in a?a.value:"return"in a?a.return:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function O(i,e,t,r,o,n){let s=i.message;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="message"in a?a.message:"throw"in a?a.throw:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function V(i,e,t,r,o,n,s,a,c,u,d){let h;try{let p=i.cond;h=typeof p=="function"?!!p(e,t):!!p;}catch(p){c.push({directiveIndex:u,error:`if cond: ${p}`}),d.errors++;return}let f=h?i.then:i.else;if(Array.isArray(f)&&f.length>0){let p=Math.min(f.length,a),l=o?n:s;r.push({dirs:f,i:0,len:p,topLevelIfIndex:l});}}function z(i,e,t){let r=processIntercept(i,"beforeDirective");if(r.action===Intercept.SKIP)return {action:"skip"};if(r.action===Intercept.ABORT)return {action:"abort",reason:r.abortReason};let o=t,n=e;return r.ctx!==void 0&&(o=t.withCtx(r.ctx)),r.directive!==void 0&&(n=r.directive),{action:"continue",directive:n,dFrame:o}}function G(i,e,t,r,o){i.push({directiveIndex:t,error:`Hook ${r}: ${o}`}),e.errors++;}function S(i,e,t,r,o){return {success:false,aborted:true,abortedBy:i,appliedCount:e.appliedCount,skippedCount:e.skippedCount,errors:e.errors,processedCount:t,totalCount:r,counters:e.counters,data:o}}function K(i,e,t,r){return {success:true,aborted:true,abortedBy:"halt",appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function U(i,e,t,r){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function q(i,e){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:e,counters:i.counters}}function W(i,e,t,r){return {success:r.success,aborted:true,abortedBy:r.abortedBy,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r.data}}function J(i,e,t,r,o){if(typeof i.resolve!="function")return i;try{let n=i.resolve(e.ctx,e.scope);return {...i,...n}}catch(n){return t.push({directiveIndex:r,error:`Directive resolve: ${n}`}),o.errors++,null}}function Y(i,e){return [{dirs:i,i:0,len:e,topLevelIfIndex:-1}]}function Ze(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function et(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=await F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function oe(i,e){return e?et(i):Ze(i)}function de(i){if(i===null||typeof i!="object")return null;if(typeof i.next=="function")return i;let e=i.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function fe(i,e,t){return {source:"pause",directive:i,frame:e,index:t,payload:{message:i.message}}}function pe(i){return i===false||i==="abort"||i==="cancel"}function ve(i,e,t,r){r.directivesApplied++,typeof i.as=="string"&&e!==void 0&&(t[i.as]=e);}function tt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function rt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=await F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function he(i,e){return e?rt(i):tt(i)}function ye(i,e=i.hasAnyAsync){let{filledNames:t}=i,r=d=>t.has(d),o=d=>i.asyncNames.has(d)?"await ":"",n=e?"await ":"",s=[];for(let d of t)s.push(`const ${d} = directiveHooks.${d};`);s.push("const len = Math.min(directives.length, maxDirectives);"),s.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),s.push("const counters = frame.counters;"),s.push("for (let i = 0; i < len; i++) {"),s.push(" let directive = directives[i];"),r("beforeDirective")?(s.push(" let _df = frame;"),s.push(" try {"),s.push(` const _bd = ${o("beforeDirective")}beforeDirective(directive, frame);`),s.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),s.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if (typeof _bd === "object" && _bd !== null) {'),s.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),s.push(' if ("directive" in _bd) directive = _bd.directive;'),s.push(" }"),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):s.push(" const _df = frame;"),s.push(' if (typeof directive.resolve === "function") {'),s.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),s.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),s.push(" }"),s.push(" const _type = directive[typeField];"),s.push(" const _handler = _type ? handlers[_type] : undefined;"),s.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),s.push(" let _result;"),s.push(` try { _result = ${n}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),s.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),s.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),r("afterDirective")&&(s.push(" try {"),s.push(` const _ad = ${o("afterDirective")}afterDirective(directive, _result, _df);`),s.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),s.push("}"),s.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),r("onDirectivesComplete")&&s.push(`try { ${o("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),s.push("return _finalResult;");let a=s.join(`
2
2
  `),c=e?"async ":"";return {fn:new Function("directives","frame","handlers","directiveHooks","typeField","engine","maxDirectives",`"use strict";
3
3
  return (${c}() => {
4
- ${d}
5
- })();`),isAsync:e}}function re(o,e,n){return `return{success:false,aborted:true,abortedBy:${o},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${n},counters};`}function Pe(o,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${e},counters,data:_result.data};`}function Fe(o,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${e},counters,data:_result.data};`}function Be(o,e,n,i){let s=JSON.stringify(e.name);typeof e.resolve=="function"?(o.push("try{"),o.push(`scope[${s}]=${n}.resolve(ctx,scope).value;`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Binding resolve: "+_e});counters.errors++;}`)):o.push(`scope[${s}]=${n}.value;`);}function Ge(o,e,n,i,s,t){typeof e.resolve=="function"?(o.push("try{"),o.push(`const _rv=${n}.resolve(ctx,scope);`),o.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${n}.value};`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):o.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:${n}.value};`);}function Le(o,e,n,i,s,t){typeof e.resolve=="function"?(o.push("try{"),o.push(`const _rv=${n}.resolve(ctx,scope);`),o.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${n}.message};`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):o.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:${n}.message};`);}function Ne(o,e,n,i,s,t){let r=typeof e.as=="string",d=r?JSON.stringify(e.as):"";o.push(`{const _ack=yield{source:"pause",directive:${n},frame,index:${i},payload:{message:${n}.message}};`),o.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:_ack};`),o.push("appliedCount++;counters.directivesApplied++;"),r&&o.push(`if(_ack!==undefined)scope[${d}]=_ack;`),o.push("}");}function je(o,e,n,i,s){let{L:t,total:r,typeField:d,handlerVars:c,hasBefore:u,hasAfter:h,awBefore:C,awAfter:y,awHandler:p,actionIsAsync:m,actionIsInteractive:g,interactiveHandlerSet:f}=s,D=o[d],$=c.get(D),w=typeof o.resolve=="function",I=typeof o.as=="string",P=Array.isArray(o.catch)&&o.catch.length>0,R=I?JSON.stringify(o.as):"",T=g&&f.has(D),S=s.blockCounter.n++;t.push(`_b${S}:{`);let A=u||w,x=u;A&&t.push(`let _dir=${e};`),x&&t.push("let _df=frame;"),u&&(t.push("try{"),t.push(`const _bd=${C}_hookBefore(${e},frame);`),t.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${S};}`),t.push(`if(_bd==="abort")${re('"beforeDirective"',i-1,r)}`),t.push('if(typeof _bd==="object"&&_bd!==null){'),t.push(`if("abort" in _bd)${re("_bd.abort",i-1,r)}`),t.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),t.push('if("directive" in _bd)_dir=_bd.directive;'),t.push("}"),t.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(t.push('if(typeof _dir.resolve==="function"){'),t.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),t.push(`catch(_e){errors.push({directiveIndex:${n},error:"Directive resolve: "+_e});counters.errors++;break _b${S};}}`)):w&&(t.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),t.push(`catch(_e){errors.push({directiveIndex:${n},error:"Directive resolve: "+_e});counters.errors++;break _b${S};}`));let E=A?"_dir":e,_=x?"_df":"frame";if(t.push("let _result;"),T?(t.push(`try{_result=yield* ${$}(${E},${_},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(t.push(`try{_result=${p}${$}(${E},${_},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):(t.push(`try{_result=${p}${$}(${E},${_},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")),t.push("if(_result.ok){"),t.push("appliedCount++;counters.directivesApplied++;"),I&&t.push(`scope[${R}]=_result.data;`),t.push(`if(_result.halt)${Pe(i,r)}`),t.push("}else{"),t.push(`if(_result.halt)${Fe(i,r)}`),P){t.push('scope.$exception=_result.error||"handler failed";');let k=m?"$.runner":"$.runnerSync";t.push(`const _cr=${p}${k}(${e}.catch,${_});`),t.push("appliedCount+=_cr.appliedCount;"),t.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),t.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${i},totalCount:${r},counters,data:_cr.data};`);}else t.push(`errors.push({directiveIndex:${n},error:_result.error||"handler failed"});counters.errors++;`);t.push("}"),h&&(t.push("try{"),t.push(`const _ad=${y}_hookAfter(${E},_result,${_});`),t.push(`if(_ad==="abort")${re('"afterDirective"',i,r)}`),t.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Hook afterDirective: "+_e});counters.errors++;}`)),t.push("}");}function Oe(o,e,n,i,s,t){let{L:r}=t,d=o.cond,c=typeof d=="boolean";r.push("{"),c?r.push(`if(${d?"true":"false"}){`):(r.push("let _cond=false,_condOk=true;"),r.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),r.push(`catch(_e){errors.push({directiveIndex:${n},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),r.push("if(_condOk){"),r.push("if(_cond){"));let u=o.then;Array.isArray(u)&&u.length>0&&ne(u,`${e}.then`,i,s,t),r.push("}");let h=o.else;Array.isArray(h)&&h.length>0&&(r.push("else{"),ne(h,`${e}.else`,i,s,t),r.push("}")),c||r.push("}"),r.push("}");}function ne(o,e,n,i,s){let t=n!==-1;for(let r=0;r<o.length;r++){let d=o[r],c=`${e}[${r}]`,u=t?n:r,h=t?i:r+1;switch(d[s.typeField]){case "const":case "let":Be(s.L,d,c,u);break;case "return":Ge(s.L,d,c,u,h,s.total);break;case "throw":Le(s.L,d,c,u,h,s.total);break;case "pause":Ne(s.L,d,c,u,h,s.total);break;case "if":{let y=t?n:r,p=t?i:r+1;Oe(d,c,u,y,p,s);break}default:je(d,c,u,h,s);break}}}function ie(o,e,n){for(let i of o){let s=i[e];if(s&&!N.has(s)&&n.add(s),s==="if"){let t=i.then;Array.isArray(t)&&t.length>0&&ie(t,e,n);let r=i.else;Array.isArray(r)&&r.length>0&&ie(r,e,n);}}}var he=new Set;function se(o,e,n,i=he,s,t=false,r=he){let d=[],c=o.length,{filledNames:u,hasAnyAsync:h,asyncNames:C}=e,y=u.has("beforeDirective"),p=u.has("afterDirective"),m=u.has("onDirectivesComplete"),g=s!==void 0?s:Q(o,i,n),f=h||g,D=f?"await ":"",$=C.has("beforeDirective")?"await ":"",w=C.has("afterDirective")?"await ":"",I=C.has("onDirectivesComplete")?"await ":"",P=new Set;ie(o,n,P);let R=new Map,T=0;for(let k of P)R.set(k,`_h${T++}`);d.push("const counters=frame.counters;"),d.push("const ctx=frame.ctx;"),d.push("const errors=[];"),d.push("let appliedCount=0;"),d.push("let skippedCount=0;");for(let[k,M]of R)d.push(`const ${M}=$.h[${JSON.stringify(k)}];`);y&&d.push("const _hookBefore=$.hooks.beforeDirective;"),p&&d.push("const _hookAfter=$.hooks.afterDirective;"),ne(o,"$.d",-1,0,{L:d,total:c,typeField:n,handlerVars:R,hasBefore:y,hasAfter:p,awBefore:$,awAfter:w,awHandler:D,actionIsAsync:f,actionIsInteractive:t,interactiveHandlerSet:r,blockCounter:{n:0}}),d.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${c},totalCount:${c},counters};`),m&&d.push(`try{${I}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),d.push("return _finalResult;");let x=`{
6
- ${d.join(`
7
- `)}
8
- }`,E;return t?E=`(${f?"async function*()":"function*()"}${x})()`:E=`(${f?"async ()=>":"()=>"}${x})()`,{fn:new Function("frame","scope","$",`"use strict";
9
- return ${E};`),isAsync:f,isInteractive:t}}function Q(o,e,n){for(let i of o){let s=i[n];if(s&&e.has(s))return true;if(s==="if"){let r=i.then;if(Array.isArray(r)&&r.length>0&&Q(r,e,n))return true;let d=i.else;if(Array.isArray(d)&&d.length>0&&Q(d,e,n))return true}let t=i.catch;if(Array.isArray(t)&&t.length>0&&Q(t,e,n))return true}return false}function oe(o,e,n){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:o,...n}}function ve(o,e){return oe(e,`Action not found: "${o}"`,{aborted:true,abortedBy:"action-not-found"})}function ye(o,e,n){return oe(n,`Max depth ${e} exceeded invoking "${o}"`,{aborted:true,abortedBy:"maxDepth"})}function xe(o,e){return oe(e,`Action "${o}" is private (sub-action). Can only be invoked from within its parent scope.`)}function X(o,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:o,counters:e}}function Ke(o){return typeof o=="object"&&o!==null&&"execute"in o}function ge(o){let e=new Map;for(let[n,i]of o){let s=i.subDirectives;if(!s)continue;let t=Object.keys(s);if(t.length===0)continue;let r=null;for(let d=0;d<t.length;d++){let c=t[d];c!=="catch"&&s[c].graph!==false&&(r===null&&(r=[]),r.push(c));}r!==null&&e.set(n,r);}return e}function me(o){let e=new Map;for(let[n,i]of o){let s=i.subDirectives;if(!s)continue;let t=Object.keys(s);if(t.length===0)continue;let r=null;for(let d=0;d<t.length;d++){let c=t[d];c!=="catch"&&(r===null&&(r=[]),r.push(c));}r!==null&&e.set(n,r);}return e}function _e(o){let e=Object.create(null),n=new Map;for(let i of Object.keys(o)){let s=o[i];Ke(s)?(e[i]=s.execute,n.set(i,s)):(e[i]=s,n.set(i,{execute:s}));}return {handlers:e,definitions:n}}function De(o,e){if(o==="*")return true;if(!o.includes("*"))return o===e;let n=o.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)}function Ce(o){return typeof o=="string"?{pattern:o}:o}function be(o,e,n){let i=new Map;if(!e&&!n){for(let s of o)i.set(s,{status:"available"});return i}if(e){let s=e.map(Ce);for(let t of o){let r=s.some(d=>De(d.pattern,t));i.set(t,{status:r?"available":"denied"});}}else {let s=n.map(Ce);for(let t of o){let r=s.find(d=>De(d.pattern,t));r?i.set(t,{status:"denied",reason:r.reason,source:r.source}):i.set(t,{status:"available"});}}return i}function Re(o){let{typeField:e,asyncHandlerSet:n,interactiveHandlerSet:i,subDirectiveFieldsForGraph:s}=o,t=new Map,r=new Set,d=new Set,c=new Set,u=new Set;return {upsert(h,C,y){t.set(h,Ue(C,e,s)),U(C,n,e,s)?r.add(h):r.delete(h),y||z(C,i,e,s)?d.add(h):d.delete(h);},remove(h){t.delete(h),r.delete(h),d.delete(h);},recompute(){c=Ae(t,r),u=Ae(t,d);},isAsync(h){return c.has(h)},isInteractive(h){return u.has(h)},has(h){return t.has(h)}}}var Z=new Map;function Ue(o,e,n=Z){let i=new Set;return K(o,e,n,i),i}function K(o,e,n,i){for(let s of o){let t=s[e];t==="action"&&typeof s.id=="string"&&i.add(s.id);let r=s.catch;if(Array.isArray(r)&&r.length>0&&K(r,e,n,i),t==="if"){let c=s.then;Array.isArray(c)&&c.length>0&&K(c,e,n,i);let u=s.else;Array.isArray(u)&&u.length>0&&K(u,e,n,i);continue}if(t===void 0)continue;let d=n.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];!Array.isArray(u)||u.length===0||K(u,e,n,i);}}}function U(o,e,n,i=Z){for(let s of o){let t=s[n];if(t!==void 0&&e.has(t))return true;let r=s.catch;if(Array.isArray(r)&&r.length>0&&U(r,e,n,i))return true;if(t==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&U(c,e,n,i))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&U(u,e,n,i))return true;continue}if(t===void 0)continue;let d=i.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];if(!(!Array.isArray(u)||u.length===0)&&U(u,e,n,i))return true}}return false}function z(o,e,n,i=Z){for(let s of o){let t=s[n];if(t==="pause"||t!==void 0&&e.has(t))return true;let r=s.catch;if(Array.isArray(r)&&r.length>0&&z(r,e,n,i))return true;if(t==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&z(c,e,n,i))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&z(u,e,n,i))return true;continue}if(t===void 0)continue;let d=i.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];if(!(!Array.isArray(u)||u.length===0)&&z(u,e,n,i))return true}}return false}function j(o,e,n=Z){for(let i of o){let s=i[e];if(s==="pause")return true;let t=i.catch;if(Array.isArray(t)&&t.length>0&&j(t,e,n))return true;if(s==="if"){let d=i.then;if(Array.isArray(d)&&d.length>0&&j(d,e,n))return true;let c=i.else;if(Array.isArray(c)&&c.length>0&&j(c,e,n))return true;continue}if(s===void 0)continue;let r=n.get(s);if(r!==void 0)for(let d=0;d<r.length;d++){let c=i[r[d]];if(!(!Array.isArray(c)||c.length===0)&&j(c,e,n))return true}}return false}function Ae(o,e){let n=new Set(e),i=true;for(;i;){i=false;for(let[s,t]of o)if(!n.has(s)){for(let r of t)if(n.has(r)){n.add(s),i=true;break}}}return n}var Je=8,Ye="type",ae={maxDepth:10,maxRules:1e4,maxDirectives:1e5},ue=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new O;_batchDepth=0;_batchErrors=[];_batchWarnings=[];_batchActions=[];_batchRegistered=[];_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Je,this._typeField=e.typeField??Ye,this._limits={maxDepth:e.limits?.maxDepth??ae.maxDepth,maxRules:e.limits?.maxRules??ae.maxRules,maxDirectives:e.limits?.maxDirectives??ae.maxDirectives};let{handlers:n,definitions:i}=_e(e.handlers);for(let c of Object.keys(e.handlers))if(N.has(c))throw new Error(`Handler type "${c}" is reserved for engine-internal directives`);if(e.allowedDirectives&&e.blockedDirectives)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.");this._handlers=n,this._definitions=i,this._directivePermissions=be(Object.keys(n),e.allowedDirectives,e.blockedDirectives),this._directiveHooks=e.directiveHooks??{},this._beforeAction=e.actionHooks?.beforeAction??null,this._afterAction=e.actionHooks?.afterAction??null,this._directiveAnalysis=analyzeSlots(this._directiveHooks,DIRECTIVE_SLOT_NAMES);let s=new Set,t=new Set;for(let[c,u]of this._definitions)(u.async===true||isAsyncFunction(u.execute))&&s.add(c),(u.interactive===true||isGeneratorFunction(u.execute))&&t.add(c);if(this._asyncHandlerSet=s,this._interactiveHandlerSet=t,this._isInteractive=e.interactive!==void 0,!this._isInteractive&&t.size>0){let c=Array.from(t).join(", ");throw new Error(`Handler(s) [${c}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}this._isAsync=this._directiveAnalysis.hasAnyAsync||s.size>0;let r=ge(this._definitions);this._subDirectiveFieldsForGraph=r,this._subDirectiveFieldsAll=me(this._definitions),this._miniGraph=Re({typeField:this._typeField,asyncHandlerSet:s,interactiveHandlerSet:t,subDirectiveFieldsForGraph:r}),this._engineRef={runDirectives:(c,u)=>this._executeDirectives(c,u),runDirectivesAsync:(c,u)=>this._executeDirectivesAsync(c,u),invoke:(c,u,h)=>this._invokeInternal(c,u,h),invokeAsync:(c,u,h)=>this._invokeInternalAsync(c,u,h),isActionAsync:c=>this._miniGraph.has(c)?this._miniGraph.isAsync(c):void 0,isActionInteractive:c=>this._miniGraph.has(c)?this._miniGraph.isInteractive(c):void 0,invokeInteractive:(c,u,h)=>this._invokeInteractiveInternal(c,u,h),evaluateRules:()=>{throw new Error("evaluateRules() not available in ActionEngine context. Use createRuleEngine().")},evaluateRulesAsync:()=>{throw new Error("evaluateRulesAsync() not available in ActionEngine context. Use createRuleEngine().")}},this._directiveRunner=(c,u)=>this._directiveExecutor(c,u,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);let d=J(this._directiveAnalysis,false);this._directiveRunnerSync=(c,u)=>d(c,u,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives),this._requestedMode==="jit"?(this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit"):this._isAsync?(this._directiveExecutor=J(this._directiveAnalysis,true),this._mode="interpret"):(this._directiveExecutor=d,this._mode="interpret"),this._interactiveExecutor=this._isInteractive?this._isAsync?ee(this._directiveAnalysis,true):ee(this._directiveAnalysis,false):null;}register(e){let n=[],i=[],s=[],t=[];for(let d of e){if(!d.id){i.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&j(d.directives,this._typeField,this._subDirectiveFieldsForGraph)){i.push({actionId:d.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let c=le(d,this._handlers,this._definitions,this._typeField);if(c.length>0){for(let u of c)i.push({actionId:d.id,error:u});continue}t.push(d);}for(let d of t){let c=L(d.directives,this._typeField,this._subDirectiveFieldsAll),u={definition:d,directives:c,compiled:null,invokeCount:0};this._registry.set(d.id,u),this._registeredIds.add(d.id),this._miniGraph.upsert(d.id,c,d.interactive===true),n.push(d.id);}if(this._batchDepth>0){this._batchErrors.push(...i),this._batchWarnings.push(...s);for(let d of t)this._batchActions.push(d);return this._batchRegistered.push(...n),{registered:n,errors:i,warnings:s}}t.length>0&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile());let r={registered:n,errors:i,warnings:s};return n.length>0&&this._emitter.emit("register",{actions:t,result:r,registered:n}),r}unregister(e){let n=this._registry.delete(e);n&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let i=e+"/",s=[];for(let t of this._registry.keys())t.startsWith(i)&&(this._registry.delete(t),this._registeredIds.delete(t),this._miniGraph.remove(t),s.push(t));return n&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:s})),n}invoke(e,n,i){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);if(this._miniGraph.isAsync(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is async (transitively). Use invokeAsync() instead.`);if(this._directiveAnalysis.hasAnyAsync)throw new Error(`Cannot call invoke("${e}") \u2014 engine has async directive hooks. Use invokeAsync() instead.`);let s=i!==void 0?i:this._requireCtx(),t=createRootFrame(s,this._limits);return this._invokeInternal(e,n,t)}async invokeAsync(e,n,i){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let s=i!==void 0?i:this._requireCtx(),t=createRootFrame(s,this._limits);return this._invokeInternalAsync(e,n,t)}setContext(e){this._ctx=e;}context(e,n){let i=this._ctx;this._ctx=e;try{return n()}finally{this._ctx=i;}}beginBatch(){this._batchDepth++,this._batchDepth===1&&(this._batchErrors=[],this._batchWarnings=[],this._batchActions=[],this._batchRegistered=[]);}endBatch(){if(this._batchDepth<=0)throw new Error("endBatch() called without matching beginBatch()");if(this._batchDepth--,this._batchDepth>0)return {registered:[],errors:[],warnings:[]};let e={registered:this._batchRegistered,errors:this._batchErrors,warnings:this._batchWarnings};return this._batchRegistered.length>0&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile()),this._batchRegistered.length>0&&this._emitter.emit("register",{actions:this._batchActions,result:e,registered:this._batchRegistered}),e}on(e,n){return this._emitter.on(e,n)}get handlerDefinitions(){return this._definitions}get registeredIds(){return this._registeredIds}getActionDefinition(e){return this._registry.get(e)?.definition}get typeField(){return this._typeField}get subDirectiveFieldsForGraph(){return this._subDirectiveFieldsForGraph}get directivePermissions(){return this._directivePermissions}get isAsync(){return this._isAsync}get isInteractive(){return this._isInteractive}isActionAsync(e){if(this._miniGraph.has(e))return this._miniGraph.isAsync(e)}isActionInteractive(e){if(this._miniGraph.has(e))return this._miniGraph.isInteractive(e)}invokeInteractive(e,n,i){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let s=i!==void 0?i:this._requireCtx(),t=createRootFrame(s,this._limits);return this._invokeInteractiveInternal(e,n,t)}_invokeInteractiveInternal(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return ke(s,this._isAsync);let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return ke(X(u.data,r.counters),this._isAsync)}let c;if(t.compiled&&t.compiled.isInteractive)c=t.compiled.fn(r,r.scope,t.compiled.$);else {let u=this._interactiveExecutor;c=u(t.directives,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return Qe(c,e,n,r,this._afterAction,this._isAsync)}get compilationMode(){return this._mode}get directiveHookSlots(){return this._directiveAnalysis.filledNames}get asyncSlots(){return this._directiveAnalysis.asyncNames}compile(){if(this._requestedMode!=="interpret"){this._mode!=="jit"&&this._promote();for(let[e,n]of this._registry)n.compiled||(n.compiled=this._compileAction(e,n.directives));}}_invokeInternal(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return s;let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return X(u.data,r.counters)}let c;if(t.compiled?c=t.compiled.fn(r,d,t.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(t.compiled=this._compileAction(e,t.directives),c=t.compiled.fn(r,d,t.compiled.$)):(c=this._directiveRunner(t.directives,r),this._maybeAutoPromote(t)),this._afterAction!==null){let u=this._afterAction(e,n,c,r);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return s;let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return X(u.data,r.counters)}let c;if(t.compiled?c=await t.compiled.fn(r,d,t.compiled.$):(c=await this._directiveRunner(t.directives,r),this._maybeAutoPromote(t)),this._afterAction!==null){let u=this._afterAction(e,n,c,r);u!==void 0&&(c=u);}return c}_prepareInvoke(e,n,i){let s=this._registry.get(e);if(!s)return ve(e,i.counters);if(e.includes("/")&&!this._isAccessible(e,i))return xe(e,i.counters);if(i.depth>=i.limits.maxDepth)return ye(e,i.limits.maxDepth,i.counters);let t=Object.create(i.scope);n&&Object.assign(t,n);let r=i.child("action:"+e,0,e).withScope(t);return {stored:s,childFrame:r,childScope:t}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&this._promote());}_executeDirectives(e,n){return this._directiveExecutor(e,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,n){return this._directiveExecutor(e,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,n){let i=this._miniGraph.isAsync(e),s=this._miniGraph.isInteractive(e),{fn:t,isAsync:r,isInteractive:d}=se(n,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,i,s,this._interactiveHandlerSet),c={d:n,h:this._handlers,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:t,$:c,isAsync:r,isInteractive:d}}_isAccessible(e,n){let s="action:"+e.slice(0,e.lastIndexOf("/"));return n.path.includes(s)}_requireCtx(){if(this._ctx===void 0)throw new Error("No context set. Pass ctx to invoke(id, params, ctx), call setContext(ctx), or use context(ctx, fn).");return this._ctx}_promote(){this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit";}_buildJitDirectiveExecutor(){let{fn:e}=te(this._directiveAnalysis,this._isAsync);return e}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,n]of this._registry)n.compiled=this._compileAction(e,n.directives);}};function ke(o,e){return e?{next:()=>Promise.resolve({value:o,done:true}),return:()=>Promise.resolve({value:o,done:true}),throw:s=>Promise.reject(s),[Symbol.asyncIterator](){return this}}:{next:()=>({value:o,done:true}),return:()=>({value:o,done:true}),throw:i=>{throw i},[Symbol.iterator](){return this}}}function Qe(o,e,n,i,s,t){if(t){let c=o;return {async next(h){let C=await c.next(h);if(C.done){let y=C.value;if(s!==null){let p=s(e,n,y,i);p!==void 0&&(y=p);}return {value:y,done:true}}return {value:C.value,done:false}},async return(){let h=await c.return(void 0),C=h.value;if(h.done&&s!==null){let y=s(e,n,C,i);y!==void 0&&(C=y);}return {value:C,done:true}},async throw(h){let C=await c.throw(h);if(C.done){let y=C.value;if(s!==null){let p=s(e,n,y,i);p!==void 0&&(y=p);}return {value:y,done:true}}return {value:C.value,done:false}},[Symbol.asyncIterator](){return this}}}let r=o;return {next(c){let u=r.next(c);if(u.done){let h=u.value;if(s!==null){let C=s(e,n,h,i);C!==void 0&&(h=C);}return {value:h,done:true}}return {value:u.value,done:false}},return(){let c=r.return(void 0),u=c.value;if(c.done&&s!==null){let h=s(e,n,u,i);h!==void 0&&(u=h);}return {value:u,done:true}},throw(c){let u=r.throw(c);if(u.done){let h=u.value;if(s!==null){let C=s(e,n,h,i);C!==void 0&&(h=C);}return {value:h,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}function Xe(o){return new ue(o)}export{N as RESERVED_TYPES,O as SimpleEmitter,se as buildActionExecutor,te as buildDirectiveExecutor,Xe as createActionEngine,J as createDirectiveInterpreter,Ee as drainAsync,Ie as drainSync,L as normalizeDirectives,we as replayResponder};
4
+ ${a}
5
+ })();`),isAsync:e}}function ge(i,e,t){return `return{success:false,aborted:true,abortedBy:${i},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${t},counters};`}function nt(i,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function it(i,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function st(i,e,t,r){i.push("const counters=frame.counters;"),i.push("const ctx=frame.ctx;"),i.push("const errors=[];"),i.push("let appliedCount=0;"),i.push("let skippedCount=0;");for(let[o,n]of e)i.push(`const ${n}=$.h[${JSON.stringify(o)}];`);t&&i.push("const _hookBefore=$.hooks.beforeDirective;"),r&&i.push("const _hookAfter=$.hooks.afterDirective;");}function ot(i,e,t,r){i.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${e},totalCount:${e},counters};`),t&&i.push(`try{${r}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),i.push("return _finalResult;");}function ct(i,e,t){let r=`{
6
+ ${i}
7
+ }`;return t?`(${e?"async function*()":"function*()"}${r})()`:`(${e?"async ()=>":"()=>"}${r})()`}function at(i,e,t,r){let o=JSON.stringify(e.name);typeof e.resolve=="function"?(i.push("try{"),i.push(`scope[${o}]=${t}.resolve(ctx,scope).value;`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Binding resolve: "+_e});counters.errors++;}`)):i.push(`scope[${o}]=${t}.value;`);}function ut(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${t}.value};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.value};`);}function lt(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${t}.message};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.message};`);}function dt(i,e,t,r,o,n){let s=typeof e.as=="string",a=s?JSON.stringify(e.as):"";i.push(`{const _ack=yield{source:"pause",directive:${t},frame,index:${r},payload:{message:${t}.message}};`),i.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:_ack};`),i.push("appliedCount++;counters.directivesApplied++;"),s&&i.push(`if(_ack!==undefined)scope[${a}]=_ack;`),i.push("}");}function ft(i,e,t,r,o){let{L:n,total:s,typeField:a,handlerVars:c,hasBefore:u,hasAfter:d,awBefore:h,awAfter:f,awHandler:p,actionIsAsync:l,actionIsInteractive:g,interactiveHandlerSet:A}=o,D=i[a],R=c.get(D),P=typeof i.resolve=="function",b=typeof i.as=="string",I=Array.isArray(i.catch)&&i.catch.length>0,T=b?JSON.stringify(i.as):"",_=g&&A.has(D),C=o.blockCounter.n++;n.push(`_b${C}:{`);let k=u||P,x=u;k&&n.push(`let _dir=${e};`),x&&n.push("let _df=frame;"),u&&(n.push("try{"),n.push(`const _bd=${h}_hookBefore(${e},frame);`),n.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${C};}`),n.push(`if(_bd==="abort")${ge('"beforeDirective"',r-1,s)}`),n.push('if(typeof _bd==="object"&&_bd!==null){'),n.push(`if("abort" in _bd)${ge("_bd.abort",r-1,s)}`),n.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),n.push('if("directive" in _bd)_dir=_bd.directive;'),n.push("}"),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(n.push('if(typeof _dir.resolve==="function"){'),n.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}}`)):P&&(n.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}`));let E=k?"_dir":e,H=x?"_df":"frame";if(n.push("let _result;"),_?(n.push(`try{_result=yield* ${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(n.push(`try{_result=${p}${R}(${E},${H},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):(n.push(`try{_result=${p}${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")),n.push("if(_result.ok){"),n.push("appliedCount++;counters.directivesApplied++;"),b&&n.push(`scope[${T}]=_result.data;`),n.push(`if(_result.halt)${nt(r,s)}`),n.push("}else{"),n.push(`if(_result.halt)${it(r,s)}`),I){n.push('scope.$exception=_result.error||"handler failed";');let M=l?"$.runner":"$.runnerSync";n.push(`const _cr=${p}${M}(${e}.catch,${H});`),n.push("appliedCount+=_cr.appliedCount;"),n.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),n.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${r},totalCount:${s},counters,data:_cr.data};`);}else n.push(`errors.push({directiveIndex:${t},error:_result.error||"handler failed"});counters.errors++;`);n.push("}"),d&&(n.push("try{"),n.push(`const _ad=${f}_hookAfter(${E},_result,${H});`),n.push(`if(_ad==="abort")${ge('"afterDirective"',r,s)}`),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook afterDirective: "+_e});counters.errors++;}`)),n.push("}");}function pt(i,e,t,r,o,n){let{L:s}=n,a=i.cond,c=typeof a=="boolean";s.push("{"),c?s.push(`if(${a?"true":"false"}){`):(s.push("let _cond=false,_condOk=true;"),s.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),s.push(`catch(_e){errors.push({directiveIndex:${t},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),s.push("if(_condOk){"),s.push("if(_cond){"));let u=i.then;Array.isArray(u)&&u.length>0&&xe(u,`${e}.then`,r,o,n),s.push("}");let d=i.else;Array.isArray(d)&&d.length>0&&(s.push("else{"),xe(d,`${e}.else`,r,o,n),s.push("}")),c||s.push("}"),s.push("}");}function xe(i,e,t,r,o){let n=t!==-1;for(let s=0;s<i.length;s++){let a=i[s],c=`${e}[${s}]`,u=n?t:s,d=n?r:s+1;switch(a[o.typeField]){case "const":case "let":at(o.L,a,c,u);break;case "return":ut(o.L,a,c,u,d,o.total);break;case "throw":lt(o.L,a,c,u,d,o.total);break;case "pause":dt(o.L,a,c,u,d,o.total);break;case "if":{let f=n?t:s,p=n?r:s+1;pt(a,c,u,f,p,o);break}default:ft(a,c,u,d,o);break}}}function me(i,e,t){for(let r of i){let o=r[e];if(o&&!N.has(o)&&t.add(o),o==="if"){let n=r.then;Array.isArray(n)&&n.length>0&&me(n,e,t);let s=r.else;Array.isArray(s)&&s.length>0&&me(s,e,t);}}}var we=new Set;function _e(i,e,t,r=we,o,n=false,s=we){let a=[],c=i.length,{filledNames:u,hasAnyAsync:d,asyncNames:h}=e,f=u.has("beforeDirective"),p=u.has("afterDirective"),l=u.has("onDirectivesComplete"),g=o!==void 0?o:ce(i,r,t),A=d||g,D=A?"await ":"",R=h.has("beforeDirective")?"await ":"",P=h.has("afterDirective")?"await ":"",b=h.has("onDirectivesComplete")?"await ":"",I=new Set;me(i,t,I);let T=new Map,_=0;for(let E of I)T.set(E,`_h${_++}`);st(a,T,f,p),xe(i,"$.d",-1,0,{L:a,total:c,typeField:t,handlerVars:T,hasBefore:f,hasAfter:p,awBefore:R,awAfter:P,awHandler:D,actionIsAsync:A,actionIsInteractive:n,interactiveHandlerSet:s,blockCounter:{n:0}}),ot(a,c,l,b);let k=ct(a.join(`
8
+ `),A,n);return {fn:new Function("frame","scope","$",`"use strict";
9
+ return ${k};`),isAsync:A,isInteractive:n}}function ce(i,e,t){for(let r of i){let o=r[t];if(o&&e.has(o))return true;if(o==="if"){let s=r.then;if(Array.isArray(s)&&s.length>0&&ce(s,e,t))return true;let a=r.else;if(Array.isArray(a)&&a.length>0&&ce(a,e,t))return true}let n=r.catch;if(Array.isArray(n)&&n.length>0&&ce(n,e,t))return true}return false}function De(i,e,t){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:i,...t}}function Te(i,e){return De(e,`Action not found: "${i}"`,{aborted:true,abortedBy:"action-not-found"})}function Se(i,e,t){return De(t,`Max depth ${e} exceeded invoking "${i}"`,{aborted:true,abortedBy:"maxDepth"})}function $e(i,e){return De(e,`Action "${i}" is private (sub-action). Can only be invoked from within its parent scope.`)}function ae(i,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:i,counters:e}}function vt(i){return typeof i=="object"&&i!==null&&"execute"in i}function He(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&o[c].graph!==false&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Me(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Pe(i,e,t){if(!e)return t;let r=new Set(t);for(let[o,n]of i)n.executeInteractive!==void 0&&r.add(o);return r}function te(i,e,t){let r=Object.create(null);for(let[o,n]of i){let s;t&&n.executeInteractive!==void 0?s=n.executeInteractive:e&&n.executeAsync!==void 0?s=n.executeAsync:s=n.execute,r[o]=s;}return r}function Fe(i){let e=Object.create(null),t=new Map;for(let r of Object.keys(i)){let o=i[r];vt(o)?(e[r]=o.execute,t.set(r,o)):(e[r]=o,t.set(r,{execute:o}));}return {handlers:e,definitions:t}}function Ge(i,e){if(i==="*")return true;if(!i.includes("*"))return i===e;let t=i.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}function Be(i){return typeof i=="string"?{pattern:i}:i}function Ne(i,e,t){let r=new Map;if(!e&&!t){for(let o of i)r.set(o,{status:"available"});return r}if(e){let o=e.map(Be);for(let n of i){let s=o.some(a=>Ge(a.pattern,n));r.set(n,{status:s?"available":"denied"});}}else {let o=t.map(Be);for(let n of i){let s=o.find(a=>Ge(a.pattern,n));s?r.set(n,{status:"denied",reason:s.reason,source:s.source}):r.set(n,{status:"available"});}}return r}function Le(i){let{typeField:e,asyncHandlerSet:t,interactiveHandlerSet:r,subDirectiveFieldsForGraph:o}=i,n=new Map,s=new Set,a=new Set,c=new Set,u=new Set;return {upsert(d,h,f){n.set(d,ht(h,e,o)),ne(h,t,e,o)?s.add(d):s.delete(d),f||ie(h,r,e,o)?a.add(d):a.delete(d);},remove(d){n.delete(d),s.delete(d),a.delete(d);},recompute(){c=je(n,s),u=je(n,a);},isAsync(d){return c.has(d)},isInteractive(d){return u.has(d)},has(d){return n.has(d)}}}var ue=new Map;function ht(i,e,t=ue){let r=new Set;return re(i,e,t,r),r}function re(i,e,t,r){for(let o of i){let n=o[e];n==="action"&&typeof o.id=="string"&&r.add(o.id);let s=o.catch;if(Array.isArray(s)&&s.length>0&&re(s,e,t,r),n==="if"){let c=o.then;Array.isArray(c)&&c.length>0&&re(c,e,t,r);let u=o.else;Array.isArray(u)&&u.length>0&&re(u,e,t,r);continue}if(n===void 0)continue;let a=t.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];!Array.isArray(u)||u.length===0||re(u,e,t,r);}}}function ne(i,e,t,r=ue){for(let o of i){let n=o[t];if(n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ne(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ne(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ne(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ne(u,e,t,r))return true}}return false}function ie(i,e,t,r=ue){for(let o of i){let n=o[t];if(n==="pause"||n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ie(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ie(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ie(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ie(u,e,t,r))return true}}return false}function Q(i,e,t=ue){for(let r of i){let o=r[e];if(o==="pause")return true;let n=r.catch;if(Array.isArray(n)&&n.length>0&&Q(n,e,t))return true;if(o==="if"){let a=r.then;if(Array.isArray(a)&&a.length>0&&Q(a,e,t))return true;let c=r.else;if(Array.isArray(c)&&c.length>0&&Q(c,e,t))return true;continue}if(o===void 0)continue;let s=t.get(o);if(s!==void 0)for(let a=0;a<s.length;a++){let c=r[s[a]];if(!(!Array.isArray(c)||c.length===0)&&Q(c,e,t))return true}}return false}function je(i,e){let t=new Set(e),r=true;for(;r;){r=false;for(let[o,n]of i)if(!t.has(o)){for(let s of n)if(t.has(s)){t.add(o),r=true;break}}}return t}var le=class{depth=0;errors=[];warnings=[];actions=[];registered=[];begin(){this.depth++,this.depth===1&&(this.errors=[],this.warnings=[],this.actions=[],this.registered=[]);}endDepth(){if(this.depth<=0)throw new Error("endBatch() called without matching beginBatch()");return this.depth--,this.depth===0}isActive(){return this.depth>0}accumulate(e,t,r,o){this.errors.push(...e),this.warnings.push(...t);for(let n of r)this.actions.push(n);this.registered.push(...o);}};function Oe(i){for(let e of i)if(N.has(e))throw new Error(`Handler type "${e}" is reserved for engine-internal directives`)}function Ve(i,e){if(i&&e)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.")}function ze(i,e,t){if(i)return;if(e.size>0){let o=Array.from(e).join(", ");throw new Error(`Handler(s) [${o}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}let r=[];for(let[o,n]of t)n.executeInteractive!==void 0&&r.push(o);if(r.length>0)throw new Error(`Handler(s) [${r.join(", ")}] declare \`executeInteractive\` variant but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}function Ke(i){let e=new Set,t=new Set;for(let[r,o]of i)(o.async===true||isAsyncFunction(o.execute))&&e.add(r),(o.interactive===true||isGeneratorFunction(o.execute))&&t.add(r);return {asyncHandlerSet:e,interactiveHandlerSet:t}}function Ue(i,e,t,r){let o=t?te(i,true,false):e,n=r?te(i,t,true):null;return {handlersAsync:o,handlersInteractive:n}}function Ae(i,e){return e?{next:()=>Promise.resolve({value:i,done:true}),return:()=>Promise.resolve({value:i,done:true}),throw:o=>Promise.reject(o),[Symbol.asyncIterator](){return this}}:{next:()=>({value:i,done:true}),return:()=>({value:i,done:true}),throw:r=>{throw r},[Symbol.iterator](){return this}}}function qe(i,e,t,r,o,n){if(n){let c=i;return {async next(d){let h=await c.next(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},async return(){let d=await c.return(void 0),h=d.value;if(d.done&&o!==null){let f=o(e,t,h,r);f!==void 0&&(h=f);}return {value:h,done:true}},async throw(d){let h=await c.throw(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},[Symbol.asyncIterator](){return this}}}let s=i;return {next(c){let u=s.next(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},return(){let c=s.return(void 0),u=c.value;if(c.done&&o!==null){let d=o(e,t,u,r);d!==void 0&&(u=d);}return {value:u,done:true}},throw(c){let u=s.throw(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}var Dt=8,At="type",be={maxDepth:10,maxRules:1e4,maxDirectives:1e5},Re=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_handlersAsync;_handlersInteractive;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new X;_batch=new le;_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Dt,this._typeField=e.typeField??At,this._limits={maxDepth:e.limits?.maxDepth??be.maxDepth,maxRules:e.limits?.maxRules??be.maxRules,maxDirectives:e.limits?.maxDirectives??be.maxDirectives};let{handlers:t,definitions:r}=Fe(e.handlers);Oe(Object.keys(e.handlers)),Ve(e.allowedDirectives,e.blockedDirectives),this._handlers=t,this._definitions=r,this._directivePermissions=Ne(Object.keys(t),e.allowedDirectives,e.blockedDirectives),this._directiveHooks=e.directiveHooks??{},this._beforeAction=e.actionHooks?.beforeAction??null,this._afterAction=e.actionHooks?.afterAction??null,this._directiveAnalysis=analyzeSlots(this._directiveHooks,DIRECTIVE_SLOT_NAMES);let{asyncHandlerSet:o,interactiveHandlerSet:n}=Ke(this._definitions);this._asyncHandlerSet=o,this._interactiveHandlerSet=n,this._isInteractive=e.interactive!==void 0,ze(this._isInteractive,n,this._definitions),this._isAsync=this._directiveAnalysis.hasAnyAsync||o.size>0;let{handlersAsync:s,handlersInteractive:a}=Ue(this._definitions,this._handlers,this._isAsync,this._isInteractive);this._handlersAsync=s,this._handlersInteractive=a;let c=He(this._definitions);this._subDirectiveFieldsForGraph=c,this._subDirectiveFieldsAll=Me(this._definitions),this._miniGraph=Le({typeField:this._typeField,asyncHandlerSet:o,interactiveHandlerSet:n,subDirectiveFieldsForGraph:c}),this._engineRef=this._buildEngineRef();let u=oe(this._directiveAnalysis,false);this._directiveRunner=this._buildDirectiveRunner(),this._directiveRunnerSync=this._buildDirectiveRunnerSync(u);let d=this._buildExecutors(u);this._directiveExecutor=d.directiveExecutor,this._mode=d.mode,this._interactiveExecutor=d.interactiveExecutor;}_buildEngineRef(){return {runDirectives:(e,t)=>this._executeDirectives(e,t),runDirectivesAsync:(e,t)=>this._executeDirectivesAsync(e,t),invoke:(e,t,r)=>this._invokeInternal(e,t,r),invokeAsync:(e,t,r)=>this._invokeInternalAsync(e,t,r),isActionAsync:e=>this._miniGraph.has(e)?this._miniGraph.isAsync(e):void 0,isActionInteractive:e=>this._miniGraph.has(e)?this._miniGraph.isInteractive(e):void 0,invokeInteractive:(e,t,r)=>this._invokeInteractiveInternal(e,t,r),runDirectivesInteractive:(e,t)=>this._executeDirectivesInteractive(e,t),evaluateRules:()=>{throw new Error("evaluateRules() not available in ActionEngine context. Use createRuleEngine().")},evaluateRulesAsync:()=>{throw new Error("evaluateRulesAsync() not available in ActionEngine context. Use createRuleEngine().")}}}_buildDirectiveRunner(){let e=this._isAsync?this._handlersAsync:this._handlers;return (t,r)=>this._directiveExecutor(t,r,e,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildDirectiveRunnerSync(e){return (t,r)=>e(t,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildExecutors(e){let t,r;this._requestedMode==="jit"?(t=this._buildJitDirectiveExecutor(),r="jit"):this._isAsync?(t=oe(this._directiveAnalysis,true),r="interpret"):(t=e,r="interpret");let o=this._isInteractive?this._isAsync?he(this._directiveAnalysis,true):he(this._directiveAnalysis,false):null;return {directiveExecutor:t,mode:r,interactiveExecutor:o}}register(e){let t=[],r=[],o=[],n=[];for(let c of e){if(!c.id){r.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&Q(c.directives,this._typeField,this._subDirectiveFieldsForGraph)){r.push({actionId:c.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let u=ke(c,this._handlers,this._definitions,this._typeField);if(u.length>0){for(let d of u)r.push({actionId:c.id,error:d});continue}n.push(c);}for(let c of n){let u=B(c.directives,this._typeField,this._subDirectiveFieldsAll),d={definition:c,directives:u,compiled:null,invokeCount:0};this._registry.set(c.id,d),this._registeredIds.add(c.id),this._miniGraph.upsert(c.id,u,c.interactive===true),t.push(c.id);}if(this._batch.isActive())return this._batch.accumulate(r,o,n,t),{registered:t,errors:r,warnings:o};let s=t;if(n.length>0){this._miniGraph.recompute();let c=this._validateInteractiveVariants(t);c.errors.length>0&&r.push(...c.errors),c.warnings.length>0&&o.push(...c.warnings),s=c.validRegistered,this._invalidateAndMaybeRecompile();}let a={registered:s,errors:r,warnings:o};if(s.length>0){let c=new Set(s),u=n.filter(d=>c.has(d.id));this._emitter.emit("register",{actions:u,result:a,registered:s});}return a}unregister(e){let t=this._registry.delete(e);t&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let r=e+"/",o=[];for(let n of this._registry.keys())n.startsWith(r)&&(this._registry.delete(n),this._registeredIds.delete(n),this._miniGraph.remove(n),o.push(n));return t&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:o})),t}invoke(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);if(this._miniGraph.isAsync(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is async (transitively). Use invokeAsync() instead.`);if(this._directiveAnalysis.hasAnyAsync)throw new Error(`Cannot call invoke("${e}") \u2014 engine has async directive hooks. Use invokeAsync() instead.`);let o=r!==void 0?r:this._requireCtx(),n=createRootFrame(o,this._limits);return this._invokeInternal(e,t,n)}async invokeAsync(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let o=r!==void 0?r:this._requireCtx(),n=createRootFrame(o,this._limits);return this._invokeInternalAsync(e,t,n)}setContext(e){this._ctx=e;}context(e,t){let r=this._ctx;this._ctx=e;try{return t()}finally{this._ctx=r;}}beginBatch(){this._batch.begin();}endBatch(){if(!this._batch.endDepth())return {registered:[],errors:[],warnings:[]};let t=this._batch.registered;if(this._batch.registered.length>0){this._miniGraph.recompute();let o=this._validateInteractiveVariants(this._batch.registered);this._batch.errors.push(...o.errors),this._batch.warnings.push(...o.warnings),t=o.validRegistered,this._invalidateAndMaybeRecompile();}let r={registered:t,errors:this._batch.errors,warnings:this._batch.warnings};if(t.length>0){let o=new Set(t),n=this._batch.actions.filter(s=>o.has(s.id));this._emitter.emit("register",{actions:n,result:r,registered:t});}return r}on(e,t){return this._emitter.on(e,t)}get handlerDefinitions(){return this._definitions}get registeredIds(){return this._registeredIds}getActionDefinition(e){return this._registry.get(e)?.definition}get typeField(){return this._typeField}get subDirectiveFieldsForGraph(){return this._subDirectiveFieldsForGraph}get directivePermissions(){return this._directivePermissions}get isAsync(){return this._isAsync}get isInteractive(){return this._isInteractive}isActionAsync(e){if(this._miniGraph.has(e))return this._miniGraph.isAsync(e)}isActionInteractive(e){if(this._miniGraph.has(e))return this._miniGraph.isInteractive(e)}invokeInteractive(e,t,r){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let o=r!==void 0?r:this._requireCtx(),n=createRootFrame(o,this._limits);return this._invokeInteractiveInternal(e,t,n)}_invokeInteractiveInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return Ae(o,this._isAsync);let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return Ae(ae(u.data,s.counters),this._isAsync)}let c;if(n.compiled&&n.compiled.isInteractive)c=n.compiled.fn(s,s.scope,n.compiled.$);else {let u=this._interactiveExecutor;c=u(n.directives,s,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return qe(c,e,t,s,this._afterAction,this._isAsync)}_executeDirectivesInteractive(e,t){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("runDirectivesInteractive: engine has no `interactive` config");return this._interactiveExecutor(e,t,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}get compilationMode(){return this._mode}get directiveHookSlots(){return this._directiveAnalysis.filledNames}get asyncSlots(){return this._directiveAnalysis.asyncNames}compile(){if(this._requestedMode!=="interpret"){this._mode!=="jit"&&this._promote();for(let[e,t]of this._registry)t.compiled||(t.compiled=this._compileAction(e,t.directives));}}_invokeInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=n.compiled.fn(s,a,n.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(n.compiled=this._compileAction(e,n.directives),c=n.compiled.fn(s,a,n.compiled.$)):(c=this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=await n.compiled.fn(s,a,n.compiled.$):(c=await this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}_prepareInvoke(e,t,r){let o=this._registry.get(e);if(!o)return Te(e,r.counters);if(e.includes("/")&&!this._isAccessible(e,r))return $e(e,r.counters);if(r.depth>=r.limits.maxDepth)return Se(e,r.limits.maxDepth,r.counters);let n=Object.create(r.scope);t&&Object.assign(n,t);let s=r.child("action:"+e,0,e).withScope(n);return {stored:o,childFrame:s,childScope:n}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&this._promote());}_executeDirectives(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,t){let r=this._miniGraph.isAsync(e),o=this._miniGraph.isInteractive(e),n=Pe(this._definitions,o,this._interactiveHandlerSet),{fn:s,isAsync:a,isInteractive:c}=_e(t,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,r,o,n),u=te(this._definitions,a,c),d={d:t,h:u,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:s,$:d,isAsync:a,isInteractive:c}}_isAccessible(e,t){let o="action:"+e.slice(0,e.lastIndexOf("/"));return t.path.includes(o)}_requireCtx(){if(this._ctx===void 0)throw new Error("No context set. Pass ctx to invoke(id, params, ctx), call setContext(ctx), or use context(ctx, fn).");return this._ctx}_promote(){this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit";}_buildJitDirectiveExecutor(){let{fn:e}=ye(this._directiveAnalysis,this._isAsync);return e}_validateInteractiveVariants(e){let t=[],r=[],o=new Set(e),n=new Set;for(let a of this._registeredIds){if(!this._miniGraph.isInteractive(a))continue;let c=this._registry.get(a);if(c===void 0)continue;let u=Ee(c.directives,this._typeField,this._definitions,this._subDirectiveFieldsForGraph,this._interactiveHandlerSet,h=>this._miniGraph.isInteractive(h),isGeneratorFunction);if(u.size===0)continue;let d=o.has(a);for(let h of u){let f=`Action "${a}" is transitively interactive but handler "${h}" has no executeInteractive variant (and execute is not a generator function, and interactive flag is not set)`;d?(t.push({actionId:a,error:f,code:"MISSING_INTERACTIVE_VARIANT"}),n.add(a)):r.push({actionId:a,code:"MISSING_INTERACTIVE_VARIANT",message:f});}}if(n.size>0){for(let a of n)this._registry.delete(a),this._registeredIds.delete(a),this._miniGraph.remove(a);this._miniGraph.recompute();}return {validRegistered:e.filter(a=>!n.has(a)),errors:t,warnings:r}}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,t]of this._registry)t.compiled=this._compileAction(e,t.directives);}};function Ct(i){return new Re(i)}export{N as RESERVED_TYPES,X as SimpleEmitter,_e as buildActionExecutor,ye as buildDirectiveExecutor,Ct as createActionEngine,oe as createDirectiveInterpreter,Je as drainAsync,We as drainSync,B as normalizeDirectives,Ye as replayResponder};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statedelta-actions/actions",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Directive execution engine with JIT compilation and BailHook interception",
5
5
  "keywords": [
6
6
  "statedelta",
@@ -27,7 +27,7 @@
27
27
  "CHANGELOG.md"
28
28
  ],
29
29
  "dependencies": {
30
- "@statedelta-actions/core": "0.5.1"
30
+ "@statedelta-actions/core": "0.6.0"
31
31
  },
32
32
  "author": "Anderson D. Rosa <andersondrosa@outlook.com>",
33
33
  "license": "MIT",