@statedelta-actions/actions 0.7.0 → 0.9.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,28 @@
1
1
  # @statedelta-actions/actions
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Remove JIT genérico (`buildDirectiveExecutor`) — interpreter assume como `_directiveExecutor` em todos os modos.
8
+
9
+ **Bug fix:** `engine.runDirectives` em mode `"jit"` ou após auto-promote em `"auto"` deixava de tratar diretivas reservadas (`const`/`let`/`return`/`throw`/`if`), `as`, `halt`, `catch`, e chamava `resolve(ctx)` sem `scope`. Sub-blocos de handlers com `subDirectives` (ex: `simulate`) perdiam `data`, bindings e refs léxicas silenciosamente. Interpreter passa a cobrir todos os caminhos com SSOT.
10
+
11
+ **Breaking de surface (actions, sdk):** exports públicos `buildDirectiveExecutor` e `GeneratedDirectiveExecutor` removidos.
12
+
13
+ **Decisão arquitetural:** ADR-031 documenta o JIT genérico como `Deferred` — reabrir só com benchmark mostrando gargalo real no `_directiveExecutor`.
14
+
15
+ ## 0.8.0
16
+
17
+ ### Minor Changes
18
+
19
+ - update
20
+
21
+ ### Patch Changes
22
+
23
+ - Updated dependencies
24
+ - @statedelta-actions/core@0.6.0
25
+
3
26
  ## 0.7.0
4
27
 
5
28
  ### Minor Changes
package/README.md CHANGED
@@ -128,9 +128,12 @@ const handlers = {
128
128
  | Fase | Quando | Propósito |
129
129
  |------|--------|-----------|
130
130
  | `validate` | Register | Validação estrutural (rejeita diretivas malformadas) |
131
- | `execute` | Runtime | Processa a diretiva e retorna resultado |
131
+ | `execute` | Runtime | Floor — processa a diretiva e retorna resultado |
132
+ | `executeAsync` | Runtime | Variante opcional — usada em actions transitivamente async (ver [Handler Multi-Variant](#handler-multi-variant)) |
133
+ | `executeInteractive` | Runtime | Variante opcional — usada em actions transitivamente interactive |
132
134
  | `analyze` | — | Consumido pelo `ActionAnalyzer` externo, não pelo engine |
133
135
  | `async` (flag) | Construct | Marca handler como assíncrono (opt-in explícito) |
136
+ | `interactive` (flag) | Construct | Marca handler como interactive (opt-in explícito) |
134
137
  | `subDirectives` | Register | Declara campos com sub-arrays que entram no grafo |
135
138
 
136
139
  ### Sub-Directives — handlers com filhos no grafo
@@ -289,6 +292,65 @@ engine.invoke("anything"); // throws — use invokeAsync
289
292
  // action que usa `fetchDB` → wrapper async, await no handler
290
293
  ```
291
294
 
295
+ ### Handler Multi-Variant
296
+
297
+ Para **wrapper handlers** (`simulate`, `try_`, `transaction`) que delegam execução do sub-bloco, o modo correto depende do **conteúdo concreto do sub-bloco**, não de algo intrínseco ao handler. Em JS, uma função tem shape fixo na definição (`function` / `async function` / `function*` / `async function*`), então um único `execute` não consegue ser polimórfico.
298
+
299
+ Solução: o handler declara **3 variantes opcionais**. O engine escolhe a certa em compile-time da action via mini-graph:
300
+
301
+ ```typescript
302
+ const simulate = {
303
+ subDirectives: { directives: { required: true } },
304
+
305
+ // Floor — usado em actions sync transitivas
306
+ execute(d, frame, engine) {
307
+ beginTx(frame.ctx);
308
+ const r = engine.runDirectives(d.directives, frame);
309
+ if (!r.success) rollback(frame.ctx); else commit(frame.ctx);
310
+ return { ok: r.success, data: r.data };
311
+ },
312
+
313
+ // Opcional — usado em actions async transitivas
314
+ async executeAsync(d, frame, engine) {
315
+ beginTx(frame.ctx);
316
+ const r = await engine.runDirectivesAsync(d.directives, frame);
317
+ if (!r.success) rollback(frame.ctx); else commit(frame.ctx);
318
+ return { ok: r.success, data: r.data };
319
+ },
320
+
321
+ // Opcional — usado em actions interactive transitivas (propaga pauses)
322
+ async *executeInteractive(d, frame, engine) {
323
+ beginTx(frame.ctx);
324
+ const session = engine.runDirectivesInteractive(d.directives, frame);
325
+ const r = yield* session;
326
+ if (!r.success) rollback(frame.ctx); else commit(frame.ctx);
327
+ return { ok: r.success, data: r.data };
328
+ },
329
+ };
330
+ ```
331
+
332
+ **Regras de seleção** (compile-time da action, via mini-graph):
333
+
334
+ | Action transitivamente | Variante chamada |
335
+ |------------------------|------------------|
336
+ | sync | `execute` (floor) |
337
+ | async | `executeAsync` se presente, senão `execute` (engine awaita — `await` em sync é no-op) |
338
+ | interactive | `executeInteractive` se presente, senão `execute` (deve ser generator ou flag `interactive: true`) |
339
+
340
+ **Custo runtime: zero.** A escolha de variante acontece 1x no compile da action. JIT consome `$.h[type]` direto — código gerado é idêntico ao single-mode. Benchmark confirma: multi-variant vs single-mode = **+1.23% (dentro do ruído)**.
341
+
342
+ **Convenção:** `executeInteractive` é sempre `async function*` (async generator) — cobre os 2 modos interactive (sync+interactive e async+interactive) com 1 implementação. `await` em valor sync é no-op (V8 otimiza).
343
+
344
+ **Capability vs Mode.** Variantes opcionais (`executeAsync`, `executeInteractive`) são **capabilities** — declaram "o handler pode ser chamado nesse modo se necessário". NÃO entram no `asyncHandlerSet`/`interactiveHandlerSet` do mini-graph. O **modo** do handler em si é determinado pelo floor `execute` + flags. Isso preserva o princípio "actions sync não pagam overhead async/interactive".
345
+
346
+ **Validação register-time.** Se uma action é transitivamente interactive (sub-bloco contém `pause`, handler interactive, ou call pra action interactive) e o wrapper handler usado **não tem suporte interactive** (`executeInteractive` ausente + `execute` não é generator + flag `interactive: true` não set), o register lança erro `MISSING_INTERACTIVE_VARIANT` e remove a action do registry (rollback). Leaf handlers (sem `subDirectives`) não precisam de variante interactive — JIT chama `execute` regular mesmo em action interactive.
347
+
348
+ **Quem precisa de variantes?** Wrapper handlers que delegam o sub-bloco. Leaf handlers (`state`, `emit`, `log`, `fetchUser`) continuam single-mode normal.
349
+
350
+ **Inversão do "function coloring problem".** Em JS, uma função declarada async contamina toda a cadeia de callers. Aqui o engine resolve a contaminação automaticamente — o customer escreve `simulate` 1x com variantes, e o engine decide qual chamar baseado em quem usa. Mesmo nome, múltiplos modos.
351
+
352
+ Ver [ADR-030](./docs/DECISIONS.md#adr-030-handler-multi-variant--execute--executeasync--executeinteractive) para detalhes da decisão.
353
+
292
354
  ## Ações
293
355
 
294
356
  Uma ação é um ID mais diretivas:
@@ -778,10 +840,6 @@ import type { Listener } from "@statedelta-actions/actions";
778
840
  // Interpreter
779
841
  import { createDirectiveInterpreter } from "@statedelta-actions/actions";
780
842
 
781
- // JIT (generic)
782
- import { buildDirectiveExecutor } from "@statedelta-actions/actions";
783
- import type { GeneratedDirectiveExecutor } from "@statedelta-actions/actions";
784
-
785
843
  // JIT (per-action)
786
844
  import { buildActionExecutor } from "@statedelta-actions/actions";
787
845
  import type { GeneratedActionExecutor } from "@statedelta-actions/actions";
package/dist/index.cjs CHANGED
@@ -1,9 +1,5 @@
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(`
2
- `),c=e?"async ":"";return {fn:new Function("directives","frame","handlers","directiveHooks","typeField","engine","maxDirectives",`"use strict";
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;
1
+ 'use strict';var core=require('@statedelta-actions/core');function qe(i,e){let t;for(;;){let n=i.next(t);if(n.done)return n.value;t=e?e(n.value):void 0;}}async function We(i,e){let t;for(;;){let n=await i.next(t);if(n.done)return n.value;t=e?await e(n.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 n=this._listeners.get(e);n||(n=new Set,this._listeners.set(e,n)),n.add(t);let s=false;return ()=>{s||(s=true,n.delete(t),n.size===0&&this._listeners.delete(e));}}once(e,t){let n=this.on(e,s=>{n(),t(s);});return n}emit(e,t){let n=this._listeners.get(e);if(!n||n.size===0)return;let s=[...n];for(let r=0;r<s.length;r++)try{s[r](t);}catch(o){console.error(`[SimpleEmitter] Listener error on "${e}":`,o);}}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 be(i,e,t,n){let s=[];return se(i.directives,e,t,n,"directive",s,i.id),s}function se(i,e,t,n,s,r,o){for(let a=0;a<i.length;a++){let c=i[a],u=c[n],d=`${s}[${a}]`;if(!u){r.push(`${d}: missing type field "${n}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&r.push(`${d}: "if" requires cond as function or boolean`);let A=c.then;Array.isArray(A)?se(A,e,t,n,`${d}.then`,r,o):r.push(`${d}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?se(D,e,t,n,`${d}.else`,r,o):r.push(`${d}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${o}" ${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&&r.push(`${d}: ${g.error??"validation failed"}`);}catch(g){r.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][n];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${o}" ${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 "${o}" ${d}: handler "${u}" requires sub-directives field "${A}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${o}" ${d}.${A}: must be an array of directives`);se(D,e,t,n,`${d}.${A}`,r,o);}}}var Je=new Map;function B(i,e,t=Je){let n=i.length,s=new Array(n);for(let r=0;r<n;r++){let o=i[r],a=o[e],c=o,u=false,d=o.catch;if(Array.isArray(d)&&d.length>0&&(c={...c,catch:B(d,e,t)},u=true),a==="if"){let h=o.then;Array.isArray(h)&&h.length>0&&(c={...c,then:B(h,e,t)},u=true);let f=o.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=o[p];!Array.isArray(l)||l.length===0||(c={...c,[p]:B(l,e,t)},u=true);}}s[r]=u?c:o;}return s}function ke(i,e,t,n,s,r,o){let a=new Set;return Z(i,e,t,n,s,r,o,a),a}function Z(i,e,t,n,s,r,o,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=n.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,n,s,r)){l=true;break}}l&&(f.executeInteractive!==void 0||f.interactive===true||o(f.execute)||a.add(u));}}}let d=c.catch;if(Array.isArray(d)&&d.length>0&&Z(d,e,t,n,s,r,o,a),u==="if"){let f=c.then;Array.isArray(f)&&f.length>0&&Z(f,e,t,n,s,r,o,a);let p=c.else;Array.isArray(p)&&p.length>0&&Z(p,e,t,n,s,r,o,a);continue}if(u===void 0)continue;let h=n.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,n,s,r,o,a);}}}function ee(i,e,t,n,s){for(let r of i){let o=r[e];if(o==="pause"||o!==void 0&&n.has(o)||o==="action"&&typeof r.id=="string"&&s(r.id))return true;let a=r.catch;if(Array.isArray(a)&&a.length>0&&ee(a,e,t,n,s))return true;if(o==="if"){let u=r.then;if(Array.isArray(u)&&u.length>0&&ee(u,e,t,n,s))return true;let d=r.else;if(Array.isArray(d)&&d.length>0&&ee(d,e,t,n,s))return true;continue}if(o===void 0)continue;let c=t.get(o);if(c!==void 0)for(let u=0;u<c.length;u++){let d=r[c[u]];if(!(!Array.isArray(d)||d.length===0)&&ee(d,e,t,n,s))return true}}return false}function j(i,e,t,n,s,r){let o=i.name;if(typeof i.resolve=="function")try{t[o]=i.resolve(e,t).value;}catch(a){n.push({directiveIndex:s,error:`Binding resolve: ${a}`}),r.errors++;}else t[o]=i.value;}function L(i,e,t,n,s,r){let o=i.value;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);o="value"in a?a.value:"return"in a?a.return:o;}catch(a){return n.push({directiveIndex:s,error:`Control resolve: ${a}`}),r.errors++,{ok:false}}return {ok:true,data:o}}function O(i,e,t,n,s,r){let o=i.message;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);o="message"in a?a.message:"throw"in a?a.throw:o;}catch(a){return n.push({directiveIndex:s,error:`Control resolve: ${a}`}),r.errors++,{ok:false}}return {ok:true,data:o}}function V(i,e,t,n,s,r,o,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=s?r:o;n.push({dirs:f,i:0,len:p,topLevelIfIndex:l});}}function z(i,e,t){let n=core.processIntercept(i,"beforeDirective");if(n.action===core.Intercept.SKIP)return {action:"skip"};if(n.action===core.Intercept.ABORT)return {action:"abort",reason:n.abortReason};let s=t,r=e;return n.ctx!==void 0&&(s=t.withCtx(n.ctx)),n.directive!==void 0&&(r=n.directive),{action:"continue",directive:r,dFrame:s}}function G(i,e,t,n,s){i.push({directiveIndex:t,error:`Hook ${n}: ${s}`}),e.errors++;}function S(i,e,t,n,s){return {success:false,aborted:true,abortedBy:i,appliedCount:e.appliedCount,skippedCount:e.skippedCount,errors:e.errors,processedCount:t,totalCount:n,counters:e.counters,data:s}}function K(i,e,t,n){return {success:true,aborted:true,abortedBy:"halt",appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:n}}function U(i,e,t,n){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:n}}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,n){return {success:n.success,aborted:true,abortedBy:n.abortedBy,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:n.data}}function Y(i,e,t,n,s){if(typeof i.resolve!="function")return i;try{let r=i.resolve(e.ctx,e.scope);return {...i,...r}}catch(r){return t.push({directiveIndex:n,error:`Directive resolve: ${r}`}),s.errors++,null}}function J(i,e){return [{dirs:i,i:0,len:e,topLevelIfIndex:-1}]}function Xe(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),n=i.filledNames.has("onDirectivesComplete");return function(r,o,a,c,u,d,h){let f=Math.min(r.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:g}=o,A=o.ctx,D=J(r,f),b=0;for(;D.length>0;){let R=D[D.length-1];if(R.i>=R.len){D.pop();continue}let I=R.i++,T=R.topLevelIfIndex!==-1,_=T?R.topLevelIfIndex:I;T||(b=I+1);let C=R.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,b,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,b,f,v.data)}if(k==="if"){V(C,A,g,D,T,R.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=o;if(e)try{let v=c.beforeDirective(x,o),y=z(v,x,o);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=b===0?I:b-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let M=Y(x,E,p,_,l.counters);if(M===null)continue;x=M;let H=x[u],F=H?a[H]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${H??"undefined"}`}),l.counters.errors++;continue}let m;try{m=F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=b;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(n)try{c.onDirectivesComplete(P);}catch{}return P}}function Ze(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),n=i.filledNames.has("onDirectivesComplete");return async function(r,o,a,c,u,d,h){let f=Math.min(r.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:g}=o,A=o.ctx,D=J(r,f),b=0;for(;D.length>0;){let R=D[D.length-1];if(R.i>=R.len){D.pop();continue}let I=R.i++,T=R.topLevelIfIndex!==-1,_=T?R.topLevelIfIndex:I;T||(b=I+1);let C=R.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,b,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,b,f,v.data)}if(k==="if"){V(C,A,g,D,T,R.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=o;if(e)try{let v=await c.beforeDirective(x,o),y=z(v,x,o);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=b===0?I:b-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let M=Y(x,E,p,_,l.counters);if(M===null)continue;x=M;let H=x[u],F=H?a[H]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${H??"undefined"}`}),l.counters.errors++;continue}let m;try{m=await F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=b;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(n)try{await c.onDirectivesComplete(P);}catch{}return P}}function oe(i,e){return e?Ze(i):Xe(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,n){n.directivesApplied++,typeof i.as=="string"&&e!==void 0&&(t[i.as]=e);}function et(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),n=i.filledNames.has("onDirectivesComplete");return function*(r,o,a,c,u,d,h){let f=Math.min(r.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:g}=o,A=o.ctx,D=J(r,f),b=0;for(;D.length>0;){let R=D[D.length-1];if(R.i>=R.len){D.pop();continue}let I=R.i++,T=R.topLevelIfIndex!==-1,_=T?R.topLevelIfIndex:I;T||(b=I+1);let C=R.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,b,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,b,f,v.data)}if(k==="pause"){let v=b,y=yield fe(C,o,_);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,R.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=o;if(e)try{let v=c.beforeDirective(x,o),y=z(v,x,o);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=b===0?I:b-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let M=Y(x,E,p,_,l.counters);if(M===null)continue;x=M;let H=x[u],F=H?a[H]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${H??"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 $=b;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(n)try{c.onDirectivesComplete(P);}catch{}return P}}function tt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),n=i.filledNames.has("onDirectivesComplete");return async function*(r,o,a,c,u,d,h){let f=Math.min(r.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:g}=o,A=o.ctx,D=J(r,f),b=0;for(;D.length>0;){let R=D[D.length-1];if(R.i>=R.len){D.pop();continue}let I=R.i++,T=R.topLevelIfIndex!==-1,_=T?R.topLevelIfIndex:I;T||(b=I+1);let C=R.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,b,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,b,f,v.data)}if(k==="pause"){let v=b,y=yield fe(C,o,_);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,R.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=o;if(e)try{let v=await c.beforeDirective(x,o),y=z(v,x,o);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=b===0?I:b-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let M=Y(x,E,p,_,l.counters);if(M===null)continue;x=M;let H=x[u],F=H?a[H]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${H??"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 $=b;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(n)try{await c.onDirectivesComplete(P);}catch{}return P}}function he(i,e){return e?tt(i):et(i)}function ye(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 rt(i,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function it(i,e,t,n){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[s,r]of e)i.push(`const ${r}=$.h[${JSON.stringify(s)}];`);t&&i.push("const _hookBefore=$.hooks.beforeDirective;"),n&&i.push("const _hookAfter=$.hooks.afterDirective;");}function st(i,e,t,n){i.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${e},totalCount:${e},counters};`),t&&i.push(`try{${n}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),i.push("return _finalResult;");}function ot(i,e,t){let n=`{
2
+ ${i}
3
+ }`;return t?`(${e?"async function*()":"function*()"}${n})()`:`(${e?"async ()=>":"()=>"}${n})()`}function ct(i,e,t,n){let s=JSON.stringify(e.name);typeof e.resolve=="function"?(i.push("try{"),i.push(`scope[${s}]=${t}.resolve(ctx,scope).value;`),i.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Binding resolve: "+_e});counters.errors++;}`)):i.push(`scope[${s}]=${t}.value;`);}function at(i,e,t,n,s,r){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:${s},totalCount:${r},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${t}.value};`),i.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${r},counters,data:${t}.value};`);}function ut(i,e,t,n,s,r){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:${s},totalCount:${r},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${t}.message};`),i.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${r},counters,data:${t}.message};`);}function lt(i,e,t,n,s,r){let o=typeof e.as=="string",a=o?JSON.stringify(e.as):"";i.push(`{const _ack=yield{source:"pause",directive:${t},frame,index:${n},payload:{message:${t}.message}};`),i.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${r},counters,data:_ack};`),i.push("appliedCount++;counters.directivesApplied++;"),o&&i.push(`if(_ack!==undefined)scope[${a}]=_ack;`),i.push("}");}function dt(i,e,t,n,s){let{L:r,total:o,typeField:a,handlerVars:c,hasBefore:u,hasAfter:d,awBefore:h,awAfter:f,awHandler:p,actionIsAsync:l,actionIsInteractive:g,interactiveHandlerSet:A}=s,D=i[a],b=c.get(D),P=typeof i.resolve=="function",R=typeof i.as=="string",I=Array.isArray(i.catch)&&i.catch.length>0,T=R?JSON.stringify(i.as):"",_=g&&A.has(D),C=s.blockCounter.n++;r.push(`_b${C}:{`);let k=u||P,x=u;k&&r.push(`let _dir=${e};`),x&&r.push("let _df=frame;"),u&&(r.push("try{"),r.push(`const _bd=${h}_hookBefore(${e},frame);`),r.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${C};}`),r.push(`if(_bd==="abort")${ye('"beforeDirective"',n-1,o)}`),r.push('if(typeof _bd==="object"&&_bd!==null){'),r.push(`if("abort" in _bd)${ye("_bd.abort",n-1,o)}`),r.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),r.push('if("directive" in _bd)_dir=_bd.directive;'),r.push("}"),r.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(r.push('if(typeof _dir.resolve==="function"){'),r.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),r.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}}`)):P&&(r.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),r.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}`));let E=k?"_dir":e,M=x?"_df":"frame";if(r.push("let _result;"),_?(r.push(`try{_result=yield* ${b}(${E},${M},$.engine);}`),r.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(r.push(`try{_result=${p}${b}(${E},${M},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),r.push("catch(_e){_result={ok:false,error:String(_e)};}")):(r.push(`try{_result=${p}${b}(${E},${M},$.engine);}`),r.push("catch(_e){_result={ok:false,error:String(_e)};}")),r.push("if(_result.ok){"),r.push("appliedCount++;counters.directivesApplied++;"),R&&r.push(`scope[${T}]=_result.data;`),r.push(`if(_result.halt)${nt(n,o)}`),r.push("}else{"),r.push(`if(_result.halt)${rt(n,o)}`),I){r.push('scope.$exception=_result.error||"handler failed";');let H=l?"$.runner":"$.runnerSync";r.push(`const _cr=${p}${H}(${e}.catch,${M});`),r.push("appliedCount+=_cr.appliedCount;"),r.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),r.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${n},totalCount:${o},counters,data:_cr.data};`);}else r.push(`errors.push({directiveIndex:${t},error:_result.error||"handler failed"});counters.errors++;`);r.push("}"),d&&(r.push("try{"),r.push(`const _ad=${f}_hookAfter(${E},_result,${M});`),r.push(`if(_ad==="abort")${ye('"afterDirective"',n,o)}`),r.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook afterDirective: "+_e});counters.errors++;}`)),r.push("}");}function ft(i,e,t,n,s,r){let{L:o}=r,a=i.cond,c=typeof a=="boolean";o.push("{"),c?o.push(`if(${a?"true":"false"}){`):(o.push("let _cond=false,_condOk=true;"),o.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),o.push(`catch(_e){errors.push({directiveIndex:${t},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),o.push("if(_condOk){"),o.push("if(_cond){"));let u=i.then;Array.isArray(u)&&u.length>0&&ge(u,`${e}.then`,n,s,r),o.push("}");let d=i.else;Array.isArray(d)&&d.length>0&&(o.push("else{"),ge(d,`${e}.else`,n,s,r),o.push("}")),c||o.push("}"),o.push("}");}function ge(i,e,t,n,s){let r=t!==-1;for(let o=0;o<i.length;o++){let a=i[o],c=`${e}[${o}]`,u=r?t:o,d=r?n:o+1;switch(a[s.typeField]){case "const":case "let":ct(s.L,a,c,u);break;case "return":at(s.L,a,c,u,d,s.total);break;case "throw":ut(s.L,a,c,u,d,s.total);break;case "pause":lt(s.L,a,c,u,d,s.total);break;case "if":{let f=r?t:o,p=r?n:o+1;ft(a,c,u,f,p,s);break}default:dt(a,c,u,d,s);break}}}function xe(i,e,t){for(let n of i){let s=n[e];if(s&&!N.has(s)&&t.add(s),s==="if"){let r=n.then;Array.isArray(r)&&r.length>0&&xe(r,e,t);let o=n.else;Array.isArray(o)&&o.length>0&&xe(o,e,t);}}}var Ie=new Set;function me(i,e,t,n=Ie,s,r=false,o=Ie){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=s!==void 0?s:ce(i,n,t),A=d||g,D=A?"await ":"",b=h.has("beforeDirective")?"await ":"",P=h.has("afterDirective")?"await ":"",R=h.has("onDirectivesComplete")?"await ":"",I=new Set;xe(i,t,I);let T=new Map,_=0;for(let E of I)T.set(E,`_h${_++}`);it(a,T,f,p),ge(i,"$.d",-1,0,{L:a,total:c,typeField:t,handlerVars:T,hasBefore:f,hasAfter:p,awBefore:b,awAfter:P,awHandler:D,actionIsAsync:A,actionIsInteractive:r,interactiveHandlerSet:o,blockCounter:{n:0}}),st(a,c,l,R);let k=ot(a.join(`
4
+ `),A,r);return {fn:new Function("frame","scope","$",`"use strict";
5
+ return ${k};`),isAsync:A,isInteractive:r}}function ce(i,e,t){for(let n of i){let s=n[t];if(s&&e.has(s))return true;if(s==="if"){let o=n.then;if(Array.isArray(o)&&o.length>0&&ce(o,e,t))return true;let a=n.else;if(Array.isArray(a)&&a.length>0&&ce(a,e,t))return true}let r=n.catch;if(Array.isArray(r)&&r.length>0&&ce(r,e,t))return true}return false}function _e(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 we(i,e){return _e(e,`Action not found: "${i}"`,{aborted:true,abortedBy:"action-not-found"})}function Te(i,e,t){return _e(t,`Max depth ${e} exceeded invoking "${i}"`,{aborted:true,abortedBy:"maxDepth"})}function Se(i,e){return _e(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 pt(i){return typeof i=="object"&&i!==null&&"execute"in i}function $e(i){let e=new Map;for(let[t,n]of i){let s=n.subDirectives;if(!s)continue;let r=Object.keys(s);if(r.length===0)continue;let o=null;for(let a=0;a<r.length;a++){let c=r[a];c!=="catch"&&s[c].graph!==false&&(o===null&&(o=[]),o.push(c));}o!==null&&e.set(t,o);}return e}function Me(i){let e=new Map;for(let[t,n]of i){let s=n.subDirectives;if(!s)continue;let r=Object.keys(s);if(r.length===0)continue;let o=null;for(let a=0;a<r.length;a++){let c=r[a];c!=="catch"&&(o===null&&(o=[]),o.push(c));}o!==null&&e.set(t,o);}return e}function He(i,e,t){if(!e)return t;let n=new Set(t);for(let[s,r]of i)r.executeInteractive!==void 0&&n.add(s);return n}function te(i,e,t){let n=Object.create(null);for(let[s,r]of i){let o;t&&r.executeInteractive!==void 0?o=r.executeInteractive:e&&r.executeAsync!==void 0?o=r.executeAsync:o=r.execute,n[s]=o;}return n}function Pe(i){let e=Object.create(null),t=new Map;for(let n of Object.keys(i)){let s=i[n];pt(s)?(e[n]=s.execute,t.set(n,s)):(e[n]=s,t.set(n,{execute:s}));}return {handlers:e,definitions:t}}function Fe(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 Ge(i){return typeof i=="string"?{pattern:i}:i}function Be(i,e,t){let n=new Map;if(!e&&!t){for(let s of i)n.set(s,{status:"available"});return n}if(e){let s=e.map(Ge);for(let r of i){let o=s.some(a=>Fe(a.pattern,r));n.set(r,{status:o?"available":"denied"});}}else {let s=t.map(Ge);for(let r of i){let o=s.find(a=>Fe(a.pattern,r));o?n.set(r,{status:"denied",reason:o.reason,source:o.source}):n.set(r,{status:"available"});}}return n}function je(i){let{typeField:e,asyncHandlerSet:t,interactiveHandlerSet:n,subDirectiveFieldsForGraph:s}=i,r=new Map,o=new Set,a=new Set,c=new Set,u=new Set;return {upsert(d,h,f){r.set(d,vt(h,e,s)),re(h,t,e,s)?o.add(d):o.delete(d),f||ie(h,n,e,s)?a.add(d):a.delete(d);},remove(d){r.delete(d),o.delete(d),a.delete(d);},recompute(){c=Ne(r,o),u=Ne(r,a);},isAsync(d){return c.has(d)},isInteractive(d){return u.has(d)},has(d){return r.has(d)}}}var ue=new Map;function vt(i,e,t=ue){let n=new Set;return ne(i,e,t,n),n}function ne(i,e,t,n){for(let s of i){let r=s[e];r==="action"&&typeof s.id=="string"&&n.add(s.id);let o=s.catch;if(Array.isArray(o)&&o.length>0&&ne(o,e,t,n),r==="if"){let c=s.then;Array.isArray(c)&&c.length>0&&ne(c,e,t,n);let u=s.else;Array.isArray(u)&&u.length>0&&ne(u,e,t,n);continue}if(r===void 0)continue;let a=t.get(r);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];!Array.isArray(u)||u.length===0||ne(u,e,t,n);}}}function re(i,e,t,n=ue){for(let s of i){let r=s[t];if(r!==void 0&&e.has(r))return true;let o=s.catch;if(Array.isArray(o)&&o.length>0&&re(o,e,t,n))return true;if(r==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&re(c,e,t,n))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&re(u,e,t,n))return true;continue}if(r===void 0)continue;let a=n.get(r);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];if(!(!Array.isArray(u)||u.length===0)&&re(u,e,t,n))return true}}return false}function ie(i,e,t,n=ue){for(let s of i){let r=s[t];if(r==="pause"||r!==void 0&&e.has(r))return true;let o=s.catch;if(Array.isArray(o)&&o.length>0&&ie(o,e,t,n))return true;if(r==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&ie(c,e,t,n))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&ie(u,e,t,n))return true;continue}if(r===void 0)continue;let a=n.get(r);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ie(u,e,t,n))return true}}return false}function Q(i,e,t=ue){for(let n of i){let s=n[e];if(s==="pause")return true;let r=n.catch;if(Array.isArray(r)&&r.length>0&&Q(r,e,t))return true;if(s==="if"){let a=n.then;if(Array.isArray(a)&&a.length>0&&Q(a,e,t))return true;let c=n.else;if(Array.isArray(c)&&c.length>0&&Q(c,e,t))return true;continue}if(s===void 0)continue;let o=t.get(s);if(o!==void 0)for(let a=0;a<o.length;a++){let c=n[o[a]];if(!(!Array.isArray(c)||c.length===0)&&Q(c,e,t))return true}}return false}function Ne(i,e){let t=new Set(e),n=true;for(;n;){n=false;for(let[s,r]of i)if(!t.has(s)){for(let o of r)if(t.has(o)){t.add(s),n=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,n,s){this.errors.push(...e),this.warnings.push(...t);for(let r of n)this.actions.push(r);this.registered.push(...s);}};function Le(i){for(let e of i)if(N.has(e))throw new Error(`Handler type "${e}" is reserved for engine-internal directives`)}function Oe(i,e){if(i&&e)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.")}function Ve(i,e,t){if(i)return;if(e.size>0){let s=Array.from(e).join(", ");throw new Error(`Handler(s) [${s}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}let n=[];for(let[s,r]of t)r.executeInteractive!==void 0&&n.push(s);if(n.length>0)throw new Error(`Handler(s) [${n.join(", ")}] declare \`executeInteractive\` variant but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}function ze(i){let e=new Set,t=new Set;for(let[n,s]of i)(s.async===true||core.isAsyncFunction(s.execute))&&e.add(n),(s.interactive===true||core.isGeneratorFunction(s.execute))&&t.add(n);return {asyncHandlerSet:e,interactiveHandlerSet:t}}function Ke(i,e,t,n){let s=t?te(i,true,false):e,r=n?te(i,t,true):null;return {handlersAsync:s,handlersInteractive:r}}function De(i,e){return e?{next:()=>Promise.resolve({value:i,done:true}),return:()=>Promise.resolve({value:i,done:true}),throw:s=>Promise.reject(s),[Symbol.asyncIterator](){return this}}:{next:()=>({value:i,done:true}),return:()=>({value:i,done:true}),throw:n=>{throw n},[Symbol.iterator](){return this}}}function Ue(i,e,t,n,s,r){if(r){let c=i;return {async next(d){let h=await c.next(d);if(h.done){let f=h.value;if(s!==null){let p=s(e,t,f,n);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&&s!==null){let f=s(e,t,h,n);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(s!==null){let p=s(e,t,f,n);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},[Symbol.asyncIterator](){return this}}}let o=i;return {next(c){let u=o.next(c);if(u.done){let d=u.value;if(s!==null){let h=s(e,t,d,n);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},return(){let c=o.return(void 0),u=c.value;if(c.done&&s!==null){let d=s(e,t,u,n);d!==void 0&&(u=d);}return {value:u,done:true}},throw(c){let u=o.throw(c);if(u.done){let d=u.value;if(s!==null){let h=s(e,t,d,n);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}var _t=8,Dt="type",Ce={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??_t,this._typeField=e.typeField??Dt,this._limits={maxDepth:e.limits?.maxDepth??Ce.maxDepth,maxRules:e.limits?.maxRules??Ce.maxRules,maxDirectives:e.limits?.maxDirectives??Ce.maxDirectives};let{handlers:t,definitions:n}=Pe(e.handlers);Le(Object.keys(e.handlers)),Oe(e.allowedDirectives,e.blockedDirectives),this._handlers=t,this._definitions=n,this._directivePermissions=Be(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:s,interactiveHandlerSet:r}=ze(this._definitions);this._asyncHandlerSet=s,this._interactiveHandlerSet=r,this._isInteractive=e.interactive!==void 0,Ve(this._isInteractive,r,this._definitions),this._isAsync=this._directiveAnalysis.hasAnyAsync||s.size>0;let{handlersAsync:o,handlersInteractive:a}=Ke(this._definitions,this._handlers,this._isAsync,this._isInteractive);this._handlersAsync=o,this._handlersInteractive=a;let c=$e(this._definitions);this._subDirectiveFieldsForGraph=c,this._subDirectiveFieldsAll=Me(this._definitions),this._miniGraph=je({typeField:this._typeField,asyncHandlerSet:s,interactiveHandlerSet:r,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,n)=>this._invokeInternal(e,t,n),invokeAsync:(e,t,n)=>this._invokeInternalAsync(e,t,n),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,n)=>this._invokeInteractiveInternal(e,t,n),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,n)=>this._directiveExecutor(t,n,e,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildDirectiveRunnerSync(e){return (t,n)=>e(t,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildExecutors(e){let t=this._isAsync?oe(this._directiveAnalysis,true):e,n=this._requestedMode==="jit"?"jit":"interpret",s=this._isInteractive?this._isAsync?he(this._directiveAnalysis,true):he(this._directiveAnalysis,false):null;return {directiveExecutor:t,mode:n,interactiveExecutor:s}}register(e){let t=[],n=[],s=[],r=[];for(let c of e){if(!c.id){n.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&Q(c.directives,this._typeField,this._subDirectiveFieldsForGraph)){n.push({actionId:c.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let u=be(c,this._handlers,this._definitions,this._typeField);if(u.length>0){for(let d of u)n.push({actionId:c.id,error:d});continue}r.push(c);}for(let c of r){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(n,s,r,t),{registered:t,errors:n,warnings:s};let o=t;if(r.length>0){this._miniGraph.recompute();let c=this._validateInteractiveVariants(t);c.errors.length>0&&n.push(...c.errors),c.warnings.length>0&&s.push(...c.warnings),o=c.validRegistered,this._invalidateAndMaybeRecompile();}let a={registered:o,errors:n,warnings:s};if(o.length>0){let c=new Set(o),u=r.filter(d=>c.has(d.id));this._emitter.emit("register",{actions:u,result:a,registered:o});}return a}unregister(e){let t=this._registry.delete(e);t&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let n=e+"/",s=[];for(let r of this._registry.keys())r.startsWith(n)&&(this._registry.delete(r),this._registeredIds.delete(r),this._miniGraph.remove(r),s.push(r));return t&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:s})),t}invoke(e,t,n){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=n!==void 0?n:this._requireCtx(),r=core.createRootFrame(s,this._limits);return this._invokeInternal(e,t,r)}async invokeAsync(e,t,n){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let s=n!==void 0?n:this._requireCtx(),r=core.createRootFrame(s,this._limits);return this._invokeInternalAsync(e,t,r)}setContext(e){this._ctx=e;}context(e,t){let n=this._ctx;this._ctx=e;try{return t()}finally{this._ctx=n;}}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 s=this._validateInteractiveVariants(this._batch.registered);this._batch.errors.push(...s.errors),this._batch.warnings.push(...s.warnings),t=s.validRegistered,this._invalidateAndMaybeRecompile();}let n={registered:t,errors:this._batch.errors,warnings:this._batch.warnings};if(t.length>0){let s=new Set(t),r=this._batch.actions.filter(o=>s.has(o.id));this._emitter.emit("register",{actions:r,result:n,registered:t});}return n}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,n){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let s=n!==void 0?n:this._requireCtx(),r=core.createRootFrame(s,this._limits);return this._invokeInteractiveInternal(e,t,r)}_invokeInteractiveInternal(e,t,n){let s=this._prepareInvoke(e,t,n);if("success"in s)return De(s,this._isAsync);let{stored:r,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return De(ae(u.data,o.counters),this._isAsync)}let c;if(r.compiled&&r.compiled.isInteractive)c=r.compiled.fn(o,o.scope,r.compiled.$);else {let u=this._interactiveExecutor;c=u(r.directives,o,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return Ue(c,e,t,o,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._mode="jit");for(let[e,t]of this._registry)t.compiled||(t.compiled=this._compileAction(e,t.directives));}}_invokeInternal(e,t,n){let s=this._prepareInvoke(e,t,n);if("success"in s)return s;let{stored:r,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return ae(u.data,o.counters)}let c;if(r.compiled?c=r.compiled.fn(o,a,r.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(r.compiled=this._compileAction(e,r.directives),c=r.compiled.fn(o,a,r.compiled.$)):(c=this._directiveRunner(r.directives,o),this._maybeAutoPromote(r)),this._afterAction!==null){let u=this._afterAction(e,t,c,o);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,t,n){let s=this._prepareInvoke(e,t,n);if("success"in s)return s;let{stored:r,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return ae(u.data,o.counters)}let c;if(r.compiled?c=await r.compiled.fn(o,a,r.compiled.$):(c=await this._directiveRunner(r.directives,o),this._maybeAutoPromote(r)),this._afterAction!==null){let u=this._afterAction(e,t,c,o);u!==void 0&&(c=u);}return c}_prepareInvoke(e,t,n){let s=this._registry.get(e);if(!s)return we(e,n.counters);if(e.includes("/")&&!this._isAccessible(e,n))return Se(e,n.counters);if(n.depth>=n.limits.maxDepth)return Te(e,n.limits.maxDepth,n.counters);let r=Object.create(n.scope);t&&Object.assign(r,t);let o=n.child("action:"+e,0,e).withScope(r);return {stored:s,childFrame:o,childScope:r}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&(this._mode="jit"));}_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 n=this._miniGraph.isAsync(e),s=this._miniGraph.isInteractive(e),r=He(this._definitions,s,this._interactiveHandlerSet),{fn:o,isAsync:a,isInteractive:c}=me(t,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,n,s,r),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:o,$:d,isAsync:a,isInteractive:c}}_isAccessible(e,t){let s="action:"+e.slice(0,e.lastIndexOf("/"));return t.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}_validateInteractiveVariants(e){let t=[],n=[],s=new Set(e),r=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=ke(c.directives,this._typeField,this._definitions,this._subDirectiveFieldsForGraph,this._interactiveHandlerSet,h=>this._miniGraph.isInteractive(h),core.isGeneratorFunction);if(u.size===0)continue;let d=s.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"}),r.add(a)):n.push({actionId:a,code:"MISSING_INTERACTIVE_VARIANT",message:f});}}if(r.size>0){for(let a of r)this._registry.delete(a),this._registeredIds.delete(a),this._miniGraph.remove(a);this._miniGraph.recompute();}return {validRegistered:e.filter(a=>!r.has(a)),errors:t,warnings:n}}_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 At(i){return new Re(i)}exports.RESERVED_TYPES=N;exports.SimpleEmitter=X;exports.buildActionExecutor=me;exports.createActionEngine=At;exports.createDirectiveInterpreter=oe;exports.drainAsync=We;exports.drainSync=qe;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`
149
+ *
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`)
166
156
  *
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).
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 }.
@@ -646,22 +658,6 @@ declare function createDirectiveInterpreter<TCtx>(analysis: SlotAnalysis, isAsyn
646
658
 
647
659
  declare function createActionEngine<TCtx>(config: IActionEngineConfig<TCtx>): IActionEngine<TCtx>;
648
660
 
649
- type RuntimeDirectiveExecutorFn = (directives: readonly unknown[], frame: unknown, handlers: unknown, directiveHooks: unknown, typeField: string, engine: unknown, maxDirectives: number) => unknown;
650
- interface GeneratedDirectiveExecutor {
651
- fn: RuntimeDirectiveExecutorFn;
652
- isAsync: boolean;
653
- }
654
- /**
655
- * Compila um executor genérico de diretivas via `new Function`.
656
- *
657
- * @param analysis — slot analysis dos directive hooks (filled/async).
658
- * @param isAsync — se true, gera função `async ()` e prefixa `await` na chamada
659
- * do handler. Default: `analysis.hasAnyAsync` (preserva o comportamento legado
660
- * pra callers que não conhecem handler async). O engine sempre passa explícito,
661
- * computado a partir de `directiveAnalysis.hasAnyAsync || asyncHandlerSet.size > 0`.
662
- */
663
- declare function buildDirectiveExecutor(analysis: SlotAnalysis, isAsync?: boolean): GeneratedDirectiveExecutor;
664
-
665
661
  /**
666
662
  * Assinatura da função compilada pelo JIT per-action.
667
663
  *
@@ -713,4 +709,4 @@ interface GeneratedActionExecutor {
713
709
  */
714
710
  declare function buildActionExecutor(directives: readonly Directive[], analysis: SlotAnalysis, typeField: string, asyncHandlerSet?: ReadonlySet<string>, actionUsesAsyncOverride?: boolean, actionIsInteractive?: boolean, interactiveHandlerSet?: ReadonlySet<string>): GeneratedActionExecutor;
715
711
 
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 };
712
+ 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 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, 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`
149
+ *
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`)
166
156
  *
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).
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 }.
@@ -646,22 +658,6 @@ declare function createDirectiveInterpreter<TCtx>(analysis: SlotAnalysis, isAsyn
646
658
 
647
659
  declare function createActionEngine<TCtx>(config: IActionEngineConfig<TCtx>): IActionEngine<TCtx>;
648
660
 
649
- type RuntimeDirectiveExecutorFn = (directives: readonly unknown[], frame: unknown, handlers: unknown, directiveHooks: unknown, typeField: string, engine: unknown, maxDirectives: number) => unknown;
650
- interface GeneratedDirectiveExecutor {
651
- fn: RuntimeDirectiveExecutorFn;
652
- isAsync: boolean;
653
- }
654
- /**
655
- * Compila um executor genérico de diretivas via `new Function`.
656
- *
657
- * @param analysis — slot analysis dos directive hooks (filled/async).
658
- * @param isAsync — se true, gera função `async ()` e prefixa `await` na chamada
659
- * do handler. Default: `analysis.hasAnyAsync` (preserva o comportamento legado
660
- * pra callers que não conhecem handler async). O engine sempre passa explícito,
661
- * computado a partir de `directiveAnalysis.hasAnyAsync || asyncHandlerSet.size > 0`.
662
- */
663
- declare function buildDirectiveExecutor(analysis: SlotAnalysis, isAsync?: boolean): GeneratedDirectiveExecutor;
664
-
665
661
  /**
666
662
  * Assinatura da função compilada pelo JIT per-action.
667
663
  *
@@ -713,4 +709,4 @@ interface GeneratedActionExecutor {
713
709
  */
714
710
  declare function buildActionExecutor(directives: readonly Directive[], analysis: SlotAnalysis, typeField: string, asyncHandlerSet?: ReadonlySet<string>, actionUsesAsyncOverride?: boolean, actionIsInteractive?: boolean, interactiveHandlerSet?: ReadonlySet<string>): GeneratedActionExecutor;
715
711
 
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 };
712
+ 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 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, createActionEngine, createDirectiveInterpreter, drainAsync, drainSync, normalizeDirectives, replayResponder };
package/dist/index.js CHANGED
@@ -1,9 +1,5 @@
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(`
2
- `),c=e?"async ":"";return {fn:new Function("directives","frame","handlers","directiveHooks","typeField","engine","maxDirectives",`"use strict";
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};
1
+ import {analyzeSlots,DIRECTIVE_SLOT_NAMES,createRootFrame,processIntercept,Intercept,isAsyncFunction,isGeneratorFunction}from'@statedelta-actions/core';function qe(i,e){let t;for(;;){let n=i.next(t);if(n.done)return n.value;t=e?e(n.value):void 0;}}async function We(i,e){let t;for(;;){let n=await i.next(t);if(n.done)return n.value;t=e?await e(n.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 n=this._listeners.get(e);n||(n=new Set,this._listeners.set(e,n)),n.add(t);let s=false;return ()=>{s||(s=true,n.delete(t),n.size===0&&this._listeners.delete(e));}}once(e,t){let n=this.on(e,s=>{n(),t(s);});return n}emit(e,t){let n=this._listeners.get(e);if(!n||n.size===0)return;let s=[...n];for(let r=0;r<s.length;r++)try{s[r](t);}catch(o){console.error(`[SimpleEmitter] Listener error on "${e}":`,o);}}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 be(i,e,t,n){let s=[];return se(i.directives,e,t,n,"directive",s,i.id),s}function se(i,e,t,n,s,r,o){for(let a=0;a<i.length;a++){let c=i[a],u=c[n],d=`${s}[${a}]`;if(!u){r.push(`${d}: missing type field "${n}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&r.push(`${d}: "if" requires cond as function or boolean`);let A=c.then;Array.isArray(A)?se(A,e,t,n,`${d}.then`,r,o):r.push(`${d}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?se(D,e,t,n,`${d}.else`,r,o):r.push(`${d}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${o}" ${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&&r.push(`${d}: ${g.error??"validation failed"}`);}catch(g){r.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][n];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${o}" ${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 "${o}" ${d}: handler "${u}" requires sub-directives field "${A}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${o}" ${d}.${A}: must be an array of directives`);se(D,e,t,n,`${d}.${A}`,r,o);}}}var Je=new Map;function B(i,e,t=Je){let n=i.length,s=new Array(n);for(let r=0;r<n;r++){let o=i[r],a=o[e],c=o,u=false,d=o.catch;if(Array.isArray(d)&&d.length>0&&(c={...c,catch:B(d,e,t)},u=true),a==="if"){let h=o.then;Array.isArray(h)&&h.length>0&&(c={...c,then:B(h,e,t)},u=true);let f=o.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=o[p];!Array.isArray(l)||l.length===0||(c={...c,[p]:B(l,e,t)},u=true);}}s[r]=u?c:o;}return s}function ke(i,e,t,n,s,r,o){let a=new Set;return Z(i,e,t,n,s,r,o,a),a}function Z(i,e,t,n,s,r,o,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=n.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,n,s,r)){l=true;break}}l&&(f.executeInteractive!==void 0||f.interactive===true||o(f.execute)||a.add(u));}}}let d=c.catch;if(Array.isArray(d)&&d.length>0&&Z(d,e,t,n,s,r,o,a),u==="if"){let f=c.then;Array.isArray(f)&&f.length>0&&Z(f,e,t,n,s,r,o,a);let p=c.else;Array.isArray(p)&&p.length>0&&Z(p,e,t,n,s,r,o,a);continue}if(u===void 0)continue;let h=n.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,n,s,r,o,a);}}}function ee(i,e,t,n,s){for(let r of i){let o=r[e];if(o==="pause"||o!==void 0&&n.has(o)||o==="action"&&typeof r.id=="string"&&s(r.id))return true;let a=r.catch;if(Array.isArray(a)&&a.length>0&&ee(a,e,t,n,s))return true;if(o==="if"){let u=r.then;if(Array.isArray(u)&&u.length>0&&ee(u,e,t,n,s))return true;let d=r.else;if(Array.isArray(d)&&d.length>0&&ee(d,e,t,n,s))return true;continue}if(o===void 0)continue;let c=t.get(o);if(c!==void 0)for(let u=0;u<c.length;u++){let d=r[c[u]];if(!(!Array.isArray(d)||d.length===0)&&ee(d,e,t,n,s))return true}}return false}function j(i,e,t,n,s,r){let o=i.name;if(typeof i.resolve=="function")try{t[o]=i.resolve(e,t).value;}catch(a){n.push({directiveIndex:s,error:`Binding resolve: ${a}`}),r.errors++;}else t[o]=i.value;}function L(i,e,t,n,s,r){let o=i.value;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);o="value"in a?a.value:"return"in a?a.return:o;}catch(a){return n.push({directiveIndex:s,error:`Control resolve: ${a}`}),r.errors++,{ok:false}}return {ok:true,data:o}}function O(i,e,t,n,s,r){let o=i.message;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);o="message"in a?a.message:"throw"in a?a.throw:o;}catch(a){return n.push({directiveIndex:s,error:`Control resolve: ${a}`}),r.errors++,{ok:false}}return {ok:true,data:o}}function V(i,e,t,n,s,r,o,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=s?r:o;n.push({dirs:f,i:0,len:p,topLevelIfIndex:l});}}function z(i,e,t){let n=processIntercept(i,"beforeDirective");if(n.action===Intercept.SKIP)return {action:"skip"};if(n.action===Intercept.ABORT)return {action:"abort",reason:n.abortReason};let s=t,r=e;return n.ctx!==void 0&&(s=t.withCtx(n.ctx)),n.directive!==void 0&&(r=n.directive),{action:"continue",directive:r,dFrame:s}}function G(i,e,t,n,s){i.push({directiveIndex:t,error:`Hook ${n}: ${s}`}),e.errors++;}function S(i,e,t,n,s){return {success:false,aborted:true,abortedBy:i,appliedCount:e.appliedCount,skippedCount:e.skippedCount,errors:e.errors,processedCount:t,totalCount:n,counters:e.counters,data:s}}function K(i,e,t,n){return {success:true,aborted:true,abortedBy:"halt",appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:n}}function U(i,e,t,n){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:n}}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,n){return {success:n.success,aborted:true,abortedBy:n.abortedBy,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:n.data}}function Y(i,e,t,n,s){if(typeof i.resolve!="function")return i;try{let r=i.resolve(e.ctx,e.scope);return {...i,...r}}catch(r){return t.push({directiveIndex:n,error:`Directive resolve: ${r}`}),s.errors++,null}}function J(i,e){return [{dirs:i,i:0,len:e,topLevelIfIndex:-1}]}function Xe(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),n=i.filledNames.has("onDirectivesComplete");return function(r,o,a,c,u,d,h){let f=Math.min(r.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:g}=o,A=o.ctx,D=J(r,f),b=0;for(;D.length>0;){let R=D[D.length-1];if(R.i>=R.len){D.pop();continue}let I=R.i++,T=R.topLevelIfIndex!==-1,_=T?R.topLevelIfIndex:I;T||(b=I+1);let C=R.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,b,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,b,f,v.data)}if(k==="if"){V(C,A,g,D,T,R.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=o;if(e)try{let v=c.beforeDirective(x,o),y=z(v,x,o);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=b===0?I:b-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let M=Y(x,E,p,_,l.counters);if(M===null)continue;x=M;let H=x[u],F=H?a[H]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${H??"undefined"}`}),l.counters.errors++;continue}let m;try{m=F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=b;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(n)try{c.onDirectivesComplete(P);}catch{}return P}}function Ze(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),n=i.filledNames.has("onDirectivesComplete");return async function(r,o,a,c,u,d,h){let f=Math.min(r.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:g}=o,A=o.ctx,D=J(r,f),b=0;for(;D.length>0;){let R=D[D.length-1];if(R.i>=R.len){D.pop();continue}let I=R.i++,T=R.topLevelIfIndex!==-1,_=T?R.topLevelIfIndex:I;T||(b=I+1);let C=R.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,b,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,b,f,v.data)}if(k==="if"){V(C,A,g,D,T,R.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=o;if(e)try{let v=await c.beforeDirective(x,o),y=z(v,x,o);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=b===0?I:b-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let M=Y(x,E,p,_,l.counters);if(M===null)continue;x=M;let H=x[u],F=H?a[H]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${H??"undefined"}`}),l.counters.errors++;continue}let m;try{m=await F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=b;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(n)try{await c.onDirectivesComplete(P);}catch{}return P}}function oe(i,e){return e?Ze(i):Xe(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,n){n.directivesApplied++,typeof i.as=="string"&&e!==void 0&&(t[i.as]=e);}function et(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),n=i.filledNames.has("onDirectivesComplete");return function*(r,o,a,c,u,d,h){let f=Math.min(r.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:g}=o,A=o.ctx,D=J(r,f),b=0;for(;D.length>0;){let R=D[D.length-1];if(R.i>=R.len){D.pop();continue}let I=R.i++,T=R.topLevelIfIndex!==-1,_=T?R.topLevelIfIndex:I;T||(b=I+1);let C=R.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,b,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,b,f,v.data)}if(k==="pause"){let v=b,y=yield fe(C,o,_);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,R.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=o;if(e)try{let v=c.beforeDirective(x,o),y=z(v,x,o);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=b===0?I:b-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let M=Y(x,E,p,_,l.counters);if(M===null)continue;x=M;let H=x[u],F=H?a[H]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${H??"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 $=b;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(n)try{c.onDirectivesComplete(P);}catch{}return P}}function tt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),n=i.filledNames.has("onDirectivesComplete");return async function*(r,o,a,c,u,d,h){let f=Math.min(r.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:g}=o,A=o.ctx,D=J(r,f),b=0;for(;D.length>0;){let R=D[D.length-1];if(R.i>=R.len){D.pop();continue}let I=R.i++,T=R.topLevelIfIndex!==-1,_=T?R.topLevelIfIndex:I;T||(b=I+1);let C=R.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,b,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,b,f,v.data)}if(k==="pause"){let v=b,y=yield fe(C,o,_);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,R.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=o;if(e)try{let v=await c.beforeDirective(x,o),y=z(v,x,o);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=b===0?I:b-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let M=Y(x,E,p,_,l.counters);if(M===null)continue;x=M;let H=x[u],F=H?a[H]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${H??"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 $=b;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(n)try{await c.onDirectivesComplete(P);}catch{}return P}}function he(i,e){return e?tt(i):et(i)}function ye(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 rt(i,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function it(i,e,t,n){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[s,r]of e)i.push(`const ${r}=$.h[${JSON.stringify(s)}];`);t&&i.push("const _hookBefore=$.hooks.beforeDirective;"),n&&i.push("const _hookAfter=$.hooks.afterDirective;");}function st(i,e,t,n){i.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${e},totalCount:${e},counters};`),t&&i.push(`try{${n}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),i.push("return _finalResult;");}function ot(i,e,t){let n=`{
2
+ ${i}
3
+ }`;return t?`(${e?"async function*()":"function*()"}${n})()`:`(${e?"async ()=>":"()=>"}${n})()`}function ct(i,e,t,n){let s=JSON.stringify(e.name);typeof e.resolve=="function"?(i.push("try{"),i.push(`scope[${s}]=${t}.resolve(ctx,scope).value;`),i.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Binding resolve: "+_e});counters.errors++;}`)):i.push(`scope[${s}]=${t}.value;`);}function at(i,e,t,n,s,r){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:${s},totalCount:${r},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${t}.value};`),i.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${r},counters,data:${t}.value};`);}function ut(i,e,t,n,s,r){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:${s},totalCount:${r},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${t}.message};`),i.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${r},counters,data:${t}.message};`);}function lt(i,e,t,n,s,r){let o=typeof e.as=="string",a=o?JSON.stringify(e.as):"";i.push(`{const _ack=yield{source:"pause",directive:${t},frame,index:${n},payload:{message:${t}.message}};`),i.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${r},counters,data:_ack};`),i.push("appliedCount++;counters.directivesApplied++;"),o&&i.push(`if(_ack!==undefined)scope[${a}]=_ack;`),i.push("}");}function dt(i,e,t,n,s){let{L:r,total:o,typeField:a,handlerVars:c,hasBefore:u,hasAfter:d,awBefore:h,awAfter:f,awHandler:p,actionIsAsync:l,actionIsInteractive:g,interactiveHandlerSet:A}=s,D=i[a],b=c.get(D),P=typeof i.resolve=="function",R=typeof i.as=="string",I=Array.isArray(i.catch)&&i.catch.length>0,T=R?JSON.stringify(i.as):"",_=g&&A.has(D),C=s.blockCounter.n++;r.push(`_b${C}:{`);let k=u||P,x=u;k&&r.push(`let _dir=${e};`),x&&r.push("let _df=frame;"),u&&(r.push("try{"),r.push(`const _bd=${h}_hookBefore(${e},frame);`),r.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${C};}`),r.push(`if(_bd==="abort")${ye('"beforeDirective"',n-1,o)}`),r.push('if(typeof _bd==="object"&&_bd!==null){'),r.push(`if("abort" in _bd)${ye("_bd.abort",n-1,o)}`),r.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),r.push('if("directive" in _bd)_dir=_bd.directive;'),r.push("}"),r.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(r.push('if(typeof _dir.resolve==="function"){'),r.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),r.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}}`)):P&&(r.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),r.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}`));let E=k?"_dir":e,M=x?"_df":"frame";if(r.push("let _result;"),_?(r.push(`try{_result=yield* ${b}(${E},${M},$.engine);}`),r.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(r.push(`try{_result=${p}${b}(${E},${M},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),r.push("catch(_e){_result={ok:false,error:String(_e)};}")):(r.push(`try{_result=${p}${b}(${E},${M},$.engine);}`),r.push("catch(_e){_result={ok:false,error:String(_e)};}")),r.push("if(_result.ok){"),r.push("appliedCount++;counters.directivesApplied++;"),R&&r.push(`scope[${T}]=_result.data;`),r.push(`if(_result.halt)${nt(n,o)}`),r.push("}else{"),r.push(`if(_result.halt)${rt(n,o)}`),I){r.push('scope.$exception=_result.error||"handler failed";');let H=l?"$.runner":"$.runnerSync";r.push(`const _cr=${p}${H}(${e}.catch,${M});`),r.push("appliedCount+=_cr.appliedCount;"),r.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),r.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${n},totalCount:${o},counters,data:_cr.data};`);}else r.push(`errors.push({directiveIndex:${t},error:_result.error||"handler failed"});counters.errors++;`);r.push("}"),d&&(r.push("try{"),r.push(`const _ad=${f}_hookAfter(${E},_result,${M});`),r.push(`if(_ad==="abort")${ye('"afterDirective"',n,o)}`),r.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook afterDirective: "+_e});counters.errors++;}`)),r.push("}");}function ft(i,e,t,n,s,r){let{L:o}=r,a=i.cond,c=typeof a=="boolean";o.push("{"),c?o.push(`if(${a?"true":"false"}){`):(o.push("let _cond=false,_condOk=true;"),o.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),o.push(`catch(_e){errors.push({directiveIndex:${t},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),o.push("if(_condOk){"),o.push("if(_cond){"));let u=i.then;Array.isArray(u)&&u.length>0&&ge(u,`${e}.then`,n,s,r),o.push("}");let d=i.else;Array.isArray(d)&&d.length>0&&(o.push("else{"),ge(d,`${e}.else`,n,s,r),o.push("}")),c||o.push("}"),o.push("}");}function ge(i,e,t,n,s){let r=t!==-1;for(let o=0;o<i.length;o++){let a=i[o],c=`${e}[${o}]`,u=r?t:o,d=r?n:o+1;switch(a[s.typeField]){case "const":case "let":ct(s.L,a,c,u);break;case "return":at(s.L,a,c,u,d,s.total);break;case "throw":ut(s.L,a,c,u,d,s.total);break;case "pause":lt(s.L,a,c,u,d,s.total);break;case "if":{let f=r?t:o,p=r?n:o+1;ft(a,c,u,f,p,s);break}default:dt(a,c,u,d,s);break}}}function xe(i,e,t){for(let n of i){let s=n[e];if(s&&!N.has(s)&&t.add(s),s==="if"){let r=n.then;Array.isArray(r)&&r.length>0&&xe(r,e,t);let o=n.else;Array.isArray(o)&&o.length>0&&xe(o,e,t);}}}var Ie=new Set;function me(i,e,t,n=Ie,s,r=false,o=Ie){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=s!==void 0?s:ce(i,n,t),A=d||g,D=A?"await ":"",b=h.has("beforeDirective")?"await ":"",P=h.has("afterDirective")?"await ":"",R=h.has("onDirectivesComplete")?"await ":"",I=new Set;xe(i,t,I);let T=new Map,_=0;for(let E of I)T.set(E,`_h${_++}`);it(a,T,f,p),ge(i,"$.d",-1,0,{L:a,total:c,typeField:t,handlerVars:T,hasBefore:f,hasAfter:p,awBefore:b,awAfter:P,awHandler:D,actionIsAsync:A,actionIsInteractive:r,interactiveHandlerSet:o,blockCounter:{n:0}}),st(a,c,l,R);let k=ot(a.join(`
4
+ `),A,r);return {fn:new Function("frame","scope","$",`"use strict";
5
+ return ${k};`),isAsync:A,isInteractive:r}}function ce(i,e,t){for(let n of i){let s=n[t];if(s&&e.has(s))return true;if(s==="if"){let o=n.then;if(Array.isArray(o)&&o.length>0&&ce(o,e,t))return true;let a=n.else;if(Array.isArray(a)&&a.length>0&&ce(a,e,t))return true}let r=n.catch;if(Array.isArray(r)&&r.length>0&&ce(r,e,t))return true}return false}function _e(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 we(i,e){return _e(e,`Action not found: "${i}"`,{aborted:true,abortedBy:"action-not-found"})}function Te(i,e,t){return _e(t,`Max depth ${e} exceeded invoking "${i}"`,{aborted:true,abortedBy:"maxDepth"})}function Se(i,e){return _e(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 pt(i){return typeof i=="object"&&i!==null&&"execute"in i}function $e(i){let e=new Map;for(let[t,n]of i){let s=n.subDirectives;if(!s)continue;let r=Object.keys(s);if(r.length===0)continue;let o=null;for(let a=0;a<r.length;a++){let c=r[a];c!=="catch"&&s[c].graph!==false&&(o===null&&(o=[]),o.push(c));}o!==null&&e.set(t,o);}return e}function Me(i){let e=new Map;for(let[t,n]of i){let s=n.subDirectives;if(!s)continue;let r=Object.keys(s);if(r.length===0)continue;let o=null;for(let a=0;a<r.length;a++){let c=r[a];c!=="catch"&&(o===null&&(o=[]),o.push(c));}o!==null&&e.set(t,o);}return e}function He(i,e,t){if(!e)return t;let n=new Set(t);for(let[s,r]of i)r.executeInteractive!==void 0&&n.add(s);return n}function te(i,e,t){let n=Object.create(null);for(let[s,r]of i){let o;t&&r.executeInteractive!==void 0?o=r.executeInteractive:e&&r.executeAsync!==void 0?o=r.executeAsync:o=r.execute,n[s]=o;}return n}function Pe(i){let e=Object.create(null),t=new Map;for(let n of Object.keys(i)){let s=i[n];pt(s)?(e[n]=s.execute,t.set(n,s)):(e[n]=s,t.set(n,{execute:s}));}return {handlers:e,definitions:t}}function Fe(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 Ge(i){return typeof i=="string"?{pattern:i}:i}function Be(i,e,t){let n=new Map;if(!e&&!t){for(let s of i)n.set(s,{status:"available"});return n}if(e){let s=e.map(Ge);for(let r of i){let o=s.some(a=>Fe(a.pattern,r));n.set(r,{status:o?"available":"denied"});}}else {let s=t.map(Ge);for(let r of i){let o=s.find(a=>Fe(a.pattern,r));o?n.set(r,{status:"denied",reason:o.reason,source:o.source}):n.set(r,{status:"available"});}}return n}function je(i){let{typeField:e,asyncHandlerSet:t,interactiveHandlerSet:n,subDirectiveFieldsForGraph:s}=i,r=new Map,o=new Set,a=new Set,c=new Set,u=new Set;return {upsert(d,h,f){r.set(d,vt(h,e,s)),re(h,t,e,s)?o.add(d):o.delete(d),f||ie(h,n,e,s)?a.add(d):a.delete(d);},remove(d){r.delete(d),o.delete(d),a.delete(d);},recompute(){c=Ne(r,o),u=Ne(r,a);},isAsync(d){return c.has(d)},isInteractive(d){return u.has(d)},has(d){return r.has(d)}}}var ue=new Map;function vt(i,e,t=ue){let n=new Set;return ne(i,e,t,n),n}function ne(i,e,t,n){for(let s of i){let r=s[e];r==="action"&&typeof s.id=="string"&&n.add(s.id);let o=s.catch;if(Array.isArray(o)&&o.length>0&&ne(o,e,t,n),r==="if"){let c=s.then;Array.isArray(c)&&c.length>0&&ne(c,e,t,n);let u=s.else;Array.isArray(u)&&u.length>0&&ne(u,e,t,n);continue}if(r===void 0)continue;let a=t.get(r);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];!Array.isArray(u)||u.length===0||ne(u,e,t,n);}}}function re(i,e,t,n=ue){for(let s of i){let r=s[t];if(r!==void 0&&e.has(r))return true;let o=s.catch;if(Array.isArray(o)&&o.length>0&&re(o,e,t,n))return true;if(r==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&re(c,e,t,n))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&re(u,e,t,n))return true;continue}if(r===void 0)continue;let a=n.get(r);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];if(!(!Array.isArray(u)||u.length===0)&&re(u,e,t,n))return true}}return false}function ie(i,e,t,n=ue){for(let s of i){let r=s[t];if(r==="pause"||r!==void 0&&e.has(r))return true;let o=s.catch;if(Array.isArray(o)&&o.length>0&&ie(o,e,t,n))return true;if(r==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&ie(c,e,t,n))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&ie(u,e,t,n))return true;continue}if(r===void 0)continue;let a=n.get(r);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ie(u,e,t,n))return true}}return false}function Q(i,e,t=ue){for(let n of i){let s=n[e];if(s==="pause")return true;let r=n.catch;if(Array.isArray(r)&&r.length>0&&Q(r,e,t))return true;if(s==="if"){let a=n.then;if(Array.isArray(a)&&a.length>0&&Q(a,e,t))return true;let c=n.else;if(Array.isArray(c)&&c.length>0&&Q(c,e,t))return true;continue}if(s===void 0)continue;let o=t.get(s);if(o!==void 0)for(let a=0;a<o.length;a++){let c=n[o[a]];if(!(!Array.isArray(c)||c.length===0)&&Q(c,e,t))return true}}return false}function Ne(i,e){let t=new Set(e),n=true;for(;n;){n=false;for(let[s,r]of i)if(!t.has(s)){for(let o of r)if(t.has(o)){t.add(s),n=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,n,s){this.errors.push(...e),this.warnings.push(...t);for(let r of n)this.actions.push(r);this.registered.push(...s);}};function Le(i){for(let e of i)if(N.has(e))throw new Error(`Handler type "${e}" is reserved for engine-internal directives`)}function Oe(i,e){if(i&&e)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.")}function Ve(i,e,t){if(i)return;if(e.size>0){let s=Array.from(e).join(", ");throw new Error(`Handler(s) [${s}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}let n=[];for(let[s,r]of t)r.executeInteractive!==void 0&&n.push(s);if(n.length>0)throw new Error(`Handler(s) [${n.join(", ")}] declare \`executeInteractive\` variant but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}function ze(i){let e=new Set,t=new Set;for(let[n,s]of i)(s.async===true||isAsyncFunction(s.execute))&&e.add(n),(s.interactive===true||isGeneratorFunction(s.execute))&&t.add(n);return {asyncHandlerSet:e,interactiveHandlerSet:t}}function Ke(i,e,t,n){let s=t?te(i,true,false):e,r=n?te(i,t,true):null;return {handlersAsync:s,handlersInteractive:r}}function De(i,e){return e?{next:()=>Promise.resolve({value:i,done:true}),return:()=>Promise.resolve({value:i,done:true}),throw:s=>Promise.reject(s),[Symbol.asyncIterator](){return this}}:{next:()=>({value:i,done:true}),return:()=>({value:i,done:true}),throw:n=>{throw n},[Symbol.iterator](){return this}}}function Ue(i,e,t,n,s,r){if(r){let c=i;return {async next(d){let h=await c.next(d);if(h.done){let f=h.value;if(s!==null){let p=s(e,t,f,n);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&&s!==null){let f=s(e,t,h,n);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(s!==null){let p=s(e,t,f,n);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},[Symbol.asyncIterator](){return this}}}let o=i;return {next(c){let u=o.next(c);if(u.done){let d=u.value;if(s!==null){let h=s(e,t,d,n);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},return(){let c=o.return(void 0),u=c.value;if(c.done&&s!==null){let d=s(e,t,u,n);d!==void 0&&(u=d);}return {value:u,done:true}},throw(c){let u=o.throw(c);if(u.done){let d=u.value;if(s!==null){let h=s(e,t,d,n);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}var _t=8,Dt="type",Ce={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??_t,this._typeField=e.typeField??Dt,this._limits={maxDepth:e.limits?.maxDepth??Ce.maxDepth,maxRules:e.limits?.maxRules??Ce.maxRules,maxDirectives:e.limits?.maxDirectives??Ce.maxDirectives};let{handlers:t,definitions:n}=Pe(e.handlers);Le(Object.keys(e.handlers)),Oe(e.allowedDirectives,e.blockedDirectives),this._handlers=t,this._definitions=n,this._directivePermissions=Be(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:s,interactiveHandlerSet:r}=ze(this._definitions);this._asyncHandlerSet=s,this._interactiveHandlerSet=r,this._isInteractive=e.interactive!==void 0,Ve(this._isInteractive,r,this._definitions),this._isAsync=this._directiveAnalysis.hasAnyAsync||s.size>0;let{handlersAsync:o,handlersInteractive:a}=Ke(this._definitions,this._handlers,this._isAsync,this._isInteractive);this._handlersAsync=o,this._handlersInteractive=a;let c=$e(this._definitions);this._subDirectiveFieldsForGraph=c,this._subDirectiveFieldsAll=Me(this._definitions),this._miniGraph=je({typeField:this._typeField,asyncHandlerSet:s,interactiveHandlerSet:r,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,n)=>this._invokeInternal(e,t,n),invokeAsync:(e,t,n)=>this._invokeInternalAsync(e,t,n),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,n)=>this._invokeInteractiveInternal(e,t,n),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,n)=>this._directiveExecutor(t,n,e,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildDirectiveRunnerSync(e){return (t,n)=>e(t,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildExecutors(e){let t=this._isAsync?oe(this._directiveAnalysis,true):e,n=this._requestedMode==="jit"?"jit":"interpret",s=this._isInteractive?this._isAsync?he(this._directiveAnalysis,true):he(this._directiveAnalysis,false):null;return {directiveExecutor:t,mode:n,interactiveExecutor:s}}register(e){let t=[],n=[],s=[],r=[];for(let c of e){if(!c.id){n.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&Q(c.directives,this._typeField,this._subDirectiveFieldsForGraph)){n.push({actionId:c.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let u=be(c,this._handlers,this._definitions,this._typeField);if(u.length>0){for(let d of u)n.push({actionId:c.id,error:d});continue}r.push(c);}for(let c of r){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(n,s,r,t),{registered:t,errors:n,warnings:s};let o=t;if(r.length>0){this._miniGraph.recompute();let c=this._validateInteractiveVariants(t);c.errors.length>0&&n.push(...c.errors),c.warnings.length>0&&s.push(...c.warnings),o=c.validRegistered,this._invalidateAndMaybeRecompile();}let a={registered:o,errors:n,warnings:s};if(o.length>0){let c=new Set(o),u=r.filter(d=>c.has(d.id));this._emitter.emit("register",{actions:u,result:a,registered:o});}return a}unregister(e){let t=this._registry.delete(e);t&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let n=e+"/",s=[];for(let r of this._registry.keys())r.startsWith(n)&&(this._registry.delete(r),this._registeredIds.delete(r),this._miniGraph.remove(r),s.push(r));return t&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:s})),t}invoke(e,t,n){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=n!==void 0?n:this._requireCtx(),r=createRootFrame(s,this._limits);return this._invokeInternal(e,t,r)}async invokeAsync(e,t,n){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let s=n!==void 0?n:this._requireCtx(),r=createRootFrame(s,this._limits);return this._invokeInternalAsync(e,t,r)}setContext(e){this._ctx=e;}context(e,t){let n=this._ctx;this._ctx=e;try{return t()}finally{this._ctx=n;}}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 s=this._validateInteractiveVariants(this._batch.registered);this._batch.errors.push(...s.errors),this._batch.warnings.push(...s.warnings),t=s.validRegistered,this._invalidateAndMaybeRecompile();}let n={registered:t,errors:this._batch.errors,warnings:this._batch.warnings};if(t.length>0){let s=new Set(t),r=this._batch.actions.filter(o=>s.has(o.id));this._emitter.emit("register",{actions:r,result:n,registered:t});}return n}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,n){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let s=n!==void 0?n:this._requireCtx(),r=createRootFrame(s,this._limits);return this._invokeInteractiveInternal(e,t,r)}_invokeInteractiveInternal(e,t,n){let s=this._prepareInvoke(e,t,n);if("success"in s)return De(s,this._isAsync);let{stored:r,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return De(ae(u.data,o.counters),this._isAsync)}let c;if(r.compiled&&r.compiled.isInteractive)c=r.compiled.fn(o,o.scope,r.compiled.$);else {let u=this._interactiveExecutor;c=u(r.directives,o,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return Ue(c,e,t,o,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._mode="jit");for(let[e,t]of this._registry)t.compiled||(t.compiled=this._compileAction(e,t.directives));}}_invokeInternal(e,t,n){let s=this._prepareInvoke(e,t,n);if("success"in s)return s;let{stored:r,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return ae(u.data,o.counters)}let c;if(r.compiled?c=r.compiled.fn(o,a,r.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(r.compiled=this._compileAction(e,r.directives),c=r.compiled.fn(o,a,r.compiled.$)):(c=this._directiveRunner(r.directives,o),this._maybeAutoPromote(r)),this._afterAction!==null){let u=this._afterAction(e,t,c,o);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,t,n){let s=this._prepareInvoke(e,t,n);if("success"in s)return s;let{stored:r,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return ae(u.data,o.counters)}let c;if(r.compiled?c=await r.compiled.fn(o,a,r.compiled.$):(c=await this._directiveRunner(r.directives,o),this._maybeAutoPromote(r)),this._afterAction!==null){let u=this._afterAction(e,t,c,o);u!==void 0&&(c=u);}return c}_prepareInvoke(e,t,n){let s=this._registry.get(e);if(!s)return we(e,n.counters);if(e.includes("/")&&!this._isAccessible(e,n))return Se(e,n.counters);if(n.depth>=n.limits.maxDepth)return Te(e,n.limits.maxDepth,n.counters);let r=Object.create(n.scope);t&&Object.assign(r,t);let o=n.child("action:"+e,0,e).withScope(r);return {stored:s,childFrame:o,childScope:r}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&(this._mode="jit"));}_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 n=this._miniGraph.isAsync(e),s=this._miniGraph.isInteractive(e),r=He(this._definitions,s,this._interactiveHandlerSet),{fn:o,isAsync:a,isInteractive:c}=me(t,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,n,s,r),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:o,$:d,isAsync:a,isInteractive:c}}_isAccessible(e,t){let s="action:"+e.slice(0,e.lastIndexOf("/"));return t.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}_validateInteractiveVariants(e){let t=[],n=[],s=new Set(e),r=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=ke(c.directives,this._typeField,this._definitions,this._subDirectiveFieldsForGraph,this._interactiveHandlerSet,h=>this._miniGraph.isInteractive(h),isGeneratorFunction);if(u.size===0)continue;let d=s.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"}),r.add(a)):n.push({actionId:a,code:"MISSING_INTERACTIVE_VARIANT",message:f});}}if(r.size>0){for(let a of r)this._registry.delete(a),this._registeredIds.delete(a),this._miniGraph.remove(a);this._miniGraph.recompute();}return {validRegistered:e.filter(a=>!r.has(a)),errors:t,warnings:n}}_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 At(i){return new Re(i)}export{N as RESERVED_TYPES,X as SimpleEmitter,me as buildActionExecutor,At as createActionEngine,oe as createDirectiveInterpreter,We as drainAsync,qe 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.9.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",