@statedelta-actions/actions 0.8.0 → 0.10.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 +18 -0
- package/README.md +109 -5
- package/dist/index.cjs +5 -9
- package/dist/index.d.cts +41 -18
- package/dist/index.d.ts +41 -18
- package/dist/index.js +5 -9
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @statedelta-actions/actions
|
|
2
2
|
|
|
3
|
+
## 0.10.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 1d4571b: Add `interactive.autoStepDirectives` opt-in flag — interpreter generator emits `PauseEvent { source: "step" }` before each directive during interactive invocations. Enables universal pause-points for debuggers, profilers, time-travel UIs and dry-run without instrumenting definitions. Drive values via `session.next(cmd?)`: `{ skip: true }`, `{ replaceWith: directive }`, `{ abort: true }`. Interpret-only by design — JIT remains atomic; `mode: "jit"` with the flag forces fallback to interpreter generator during interactive invocations of transitively-marked actions. `PauseEvent.source` union additively gains `"step"`. Zero impact on consumers without the flag. See ADR-032 and README §Modo Interactive → Auto-step directives.
|
|
8
|
+
|
|
9
|
+
## 0.9.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- Remove JIT genérico (`buildDirectiveExecutor`) — interpreter assume como `_directiveExecutor` em todos os modos.
|
|
14
|
+
|
|
15
|
+
**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.
|
|
16
|
+
|
|
17
|
+
**Breaking de surface (actions, sdk):** exports públicos `buildDirectiveExecutor` e `GeneratedDirectiveExecutor` removidos.
|
|
18
|
+
|
|
19
|
+
**Decisão arquitetural:** ADR-031 documenta o JIT genérico como `Deferred` — reabrir só com benchmark mostrando gargalo real no `_directiveExecutor`.
|
|
20
|
+
|
|
3
21
|
## 0.8.0
|
|
4
22
|
|
|
5
23
|
### 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 |
|
|
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";
|
|
@@ -963,6 +1021,52 @@ Engine híbrido (handler async + actions sync isoladas) permite `invoke()` regul
|
|
|
963
1021
|
|
|
964
1022
|
Diretivas dentro de `catch` executam **atomicamente** (ADR-023) via `engine.runDirectives` — sem yield. Caminho de erro não pausa. Diretivas `type: "pause"` ou handler interactive dentro de catch geram warning em register-time.
|
|
965
1023
|
|
|
1024
|
+
### Auto-step directives (debug mode)
|
|
1025
|
+
|
|
1026
|
+
Pra debuggers, profilers, time-travel UIs ou dry-run que precisam pause-point **universal** sem instrumentar definitions, habilite `autoStepDirectives` no config interactive:
|
|
1027
|
+
|
|
1028
|
+
```typescript
|
|
1029
|
+
const engine = createActionEngine({
|
|
1030
|
+
handlers,
|
|
1031
|
+
interactive: { autoStepDirectives: true },
|
|
1032
|
+
});
|
|
1033
|
+
```
|
|
1034
|
+
|
|
1035
|
+
O **interpreter generator** passa a emitir `PauseEvent { source: "step" }` antes de cada directive durante uma invocação interactive. Consumer drena via `session.next(cmd?)` e pode:
|
|
1036
|
+
|
|
1037
|
+
| `next(cmd)` | Efeito |
|
|
1038
|
+
|-------------|--------|
|
|
1039
|
+
| omitido | continua — executa a directive normalmente |
|
|
1040
|
+
| `{ skip: true }` | pula a directive (incrementa `skippedCount`) |
|
|
1041
|
+
| `{ replaceWith: directive }` | substitui antes de executar |
|
|
1042
|
+
| `{ abort: true }` | aborta com `abortedBy: "step"` |
|
|
1043
|
+
|
|
1044
|
+
Coexiste com `pause` directive e handlers interactive — em uma action que mistura tudo, a ordem de yields é: `step` (engine antes de processar) → yield natural (`pause` payload, ou handler `yield*`).
|
|
1045
|
+
|
|
1046
|
+
```typescript
|
|
1047
|
+
const session = engine.invokeInteractive("checkout", undefined, ctx);
|
|
1048
|
+
let r = session.next();
|
|
1049
|
+
while (!r.done) {
|
|
1050
|
+
const ev = r.value as PauseEvent;
|
|
1051
|
+
if (ev.source === "step") {
|
|
1052
|
+
console.log("next:", ev.directive.type, "at", ev.frame.path);
|
|
1053
|
+
r = session.next(); // continua
|
|
1054
|
+
} else if (ev.source === "pause") {
|
|
1055
|
+
r = session.next("ok"); // responde pause
|
|
1056
|
+
} else {
|
|
1057
|
+
r = session.next(responses[ev.payload?.prompt]); // handler
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
```
|
|
1061
|
+
|
|
1062
|
+
**Interpret-only.** JIT permanece atômico por design — pause-points em código compilado violariam o propósito do JIT. Engine em `mode: "jit"` com `autoStepDirectives: true` faz **fallback pro interpreter generator** durante invocações interactive das actions transitivamente marcadas. Invocações regulares (`invoke`/`invokeAsync`) e actions não-interactive continuam usando JIT normalmente — autoStep só desvia o caminho interactive.
|
|
1063
|
+
|
|
1064
|
+
**Propagação transitiva grátis.** Step yields propagam automaticamente via `yield*` em sub-actions interactive (sem código adicional) e em sub-blocos de wrapper handlers que delegam via `engine.runDirectivesInteractive`. Catch permanece atômico — `engine.runDirectives` (interpreter regular, não-generator) não emite step yields, preservando ADR-023.
|
|
1065
|
+
|
|
1066
|
+
**`replayResponder` e step events.** Em play mode, `replayResponder` ignora step events sem consumir a queue de respostas — pré-programados continuam alinhados aos yields semânticos (`pause` / `handler`).
|
|
1067
|
+
|
|
1068
|
+
**Custos.** Sem a flag: zero overhead. Com a flag: 1 yield + 1 `PauseEvent` alloc por directive executada (proporcional ao tamanho da action — desprezível em debug humano). Fallback JIT→interpreter custa ~10× mais lento que JIT compilado (aceitável — debug é interação humana, não hot path).
|
|
1069
|
+
|
|
966
1070
|
---
|
|
967
1071
|
|
|
968
1072
|
## Analyzer
|
package/dist/index.cjs
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
'use strict';var core=require('@statedelta-actions/core');function We(i,e){let t;for(;;){let r=i.next(t);if(r.done)return r.value;t=e?e(r.value):void 0;}}async function Je(i,e){let t;for(;;){let r=await i.next(t);if(r.done)return r.value;t=e?await e(r.value):void 0;}}function Ye(i){let e=0;return ()=>{if(!(e>=i.length))return i[e++]}}var X=class{_listeners=new Map;on(e,t){let r=this._listeners.get(e);r||(r=new Set,this._listeners.set(e,r)),r.add(t);let o=false;return ()=>{o||(o=true,r.delete(t),r.size===0&&this._listeners.delete(e));}}once(e,t){let r=this.on(e,o=>{r(),t(o);});return r}emit(e,t){let r=this._listeners.get(e);if(!r||r.size===0)return;let o=[...r];for(let n=0;n<o.length;n++)try{o[n](t);}catch(s){console.error(`[SimpleEmitter] Listener error on "${e}":`,s);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let t=this._listeners.get(e);return t!==void 0&&t.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var N=new Set(["const","let","return","throw","pause","if"]);function ke(i,e,t,r){let o=[];return se(i.directives,e,t,r,"directive",o,i.id),o}function se(i,e,t,r,o,n,s){for(let a=0;a<i.length;a++){let c=i[a],u=c[r],d=`${o}[${a}]`;if(!u){n.push(`${d}: missing type field "${r}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&n.push(`${d}: "if" requires cond as function or boolean`);let A=c.then;Array.isArray(A)?se(A,e,t,r,`${d}.then`,n,s):n.push(`${d}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?se(D,e,t,r,`${d}.else`,n,s):n.push(`${d}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${s}" ${d}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let h=t.get(u);if(h?.validate)try{let g=h.validate(c);g&&!g.valid&&n.push(`${d}: ${g.error??"validation failed"}`);}catch(g){n.push(`${d}: validate threw: ${g}`);}let f=c.catch;if(f&&Array.isArray(f))for(let g=0;g<f.length;g++){let D=f[g][r];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${s}" ${d}.catch[${g}]: no handler registered for type "${D}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let p=h?.subDirectives;if(p===void 0)continue;let l=Object.keys(p);for(let g=0;g<l.length;g++){let A=l[g];if(A==="catch")continue;let D=c[A];if(D===void 0){if(p[A].required)throw new Error(`Action "${s}" ${d}: handler "${u}" requires sub-directives field "${A}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${s}" ${d}.${A}: must be an array of directives`);se(D,e,t,r,`${d}.${A}`,n,s);}}}var Qe=new Map;function B(i,e,t=Qe){let r=i.length,o=new Array(r);for(let n=0;n<r;n++){let s=i[n],a=s[e],c=s,u=false,d=s.catch;if(Array.isArray(d)&&d.length>0&&(c={...c,catch:B(d,e,t)},u=true),a==="if"){let h=s.then;Array.isArray(h)&&h.length>0&&(c={...c,then:B(h,e,t)},u=true);let f=s.else;Array.isArray(f)&&f.length>0&&(c={...c,else:B(f,e,t)},u=true);}else if(a!==void 0){let h=t.get(a);if(h!==void 0)for(let f=0;f<h.length;f++){let p=h[f],l=s[p];!Array.isArray(l)||l.length===0||(c={...c,[p]:B(l,e,t)},u=true);}}o[n]=u?c:s;}return o}function Ee(i,e,t,r,o,n,s){let a=new Set;return Z(i,e,t,r,o,n,s,a),a}function Z(i,e,t,r,o,n,s,a){for(let c of i){let u=c[e];if(u!==void 0){let f=t.get(u);if(f!==void 0&&f.subDirectives!==void 0){let p=r.get(u);if(p!==void 0){let l=false;for(let g=0;g<p.length;g++){let A=c[p[g]];if(!(!Array.isArray(A)||A.length===0)&&ee(A,e,r,o,n)){l=true;break}}l&&(f.executeInteractive!==void 0||f.interactive===true||s(f.execute)||a.add(u));}}}let d=c.catch;if(Array.isArray(d)&&d.length>0&&Z(d,e,t,r,o,n,s,a),u==="if"){let f=c.then;Array.isArray(f)&&f.length>0&&Z(f,e,t,r,o,n,s,a);let p=c.else;Array.isArray(p)&&p.length>0&&Z(p,e,t,r,o,n,s,a);continue}if(u===void 0)continue;let h=r.get(u);if(h!==void 0)for(let f=0;f<h.length;f++){let p=c[h[f]];!Array.isArray(p)||p.length===0||Z(p,e,t,r,o,n,s,a);}}}function ee(i,e,t,r,o){for(let n of i){let s=n[e];if(s==="pause"||s!==void 0&&r.has(s)||s==="action"&&typeof n.id=="string"&&o(n.id))return true;let a=n.catch;if(Array.isArray(a)&&a.length>0&&ee(a,e,t,r,o))return true;if(s==="if"){let u=n.then;if(Array.isArray(u)&&u.length>0&&ee(u,e,t,r,o))return true;let d=n.else;if(Array.isArray(d)&&d.length>0&&ee(d,e,t,r,o))return true;continue}if(s===void 0)continue;let c=t.get(s);if(c!==void 0)for(let u=0;u<c.length;u++){let d=n[c[u]];if(!(!Array.isArray(d)||d.length===0)&&ee(d,e,t,r,o))return true}}return false}function j(i,e,t,r,o,n){let s=i.name;if(typeof i.resolve=="function")try{t[s]=i.resolve(e,t).value;}catch(a){r.push({directiveIndex:o,error:`Binding resolve: ${a}`}),n.errors++;}else t[s]=i.value;}function L(i,e,t,r,o,n){let s=i.value;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="value"in a?a.value:"return"in a?a.return:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function O(i,e,t,r,o,n){let s=i.message;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="message"in a?a.message:"throw"in a?a.throw:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function V(i,e,t,r,o,n,s,a,c,u,d){let h;try{let p=i.cond;h=typeof p=="function"?!!p(e,t):!!p;}catch(p){c.push({directiveIndex:u,error:`if cond: ${p}`}),d.errors++;return}let f=h?i.then:i.else;if(Array.isArray(f)&&f.length>0){let p=Math.min(f.length,a),l=o?n:s;r.push({dirs:f,i:0,len:p,topLevelIfIndex:l});}}function z(i,e,t){let r=core.processIntercept(i,"beforeDirective");if(r.action===core.Intercept.SKIP)return {action:"skip"};if(r.action===core.Intercept.ABORT)return {action:"abort",reason:r.abortReason};let o=t,n=e;return r.ctx!==void 0&&(o=t.withCtx(r.ctx)),r.directive!==void 0&&(n=r.directive),{action:"continue",directive:n,dFrame:o}}function G(i,e,t,r,o){i.push({directiveIndex:t,error:`Hook ${r}: ${o}`}),e.errors++;}function S(i,e,t,r,o){return {success:false,aborted:true,abortedBy:i,appliedCount:e.appliedCount,skippedCount:e.skippedCount,errors:e.errors,processedCount:t,totalCount:r,counters:e.counters,data:o}}function K(i,e,t,r){return {success:true,aborted:true,abortedBy:"halt",appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function U(i,e,t,r){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function q(i,e){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:e,counters:i.counters}}function W(i,e,t,r){return {success:r.success,aborted:true,abortedBy:r.abortedBy,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r.data}}function J(i,e,t,r,o){if(typeof i.resolve!="function")return i;try{let n=i.resolve(e.ctx,e.scope);return {...i,...n}}catch(n){return t.push({directiveIndex:r,error:`Directive resolve: ${n}`}),o.errors++,null}}function Y(i,e){return [{dirs:i,i:0,len:e,topLevelIfIndex:-1}]}function Ze(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function et(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=await F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function oe(i,e){return e?et(i):Ze(i)}function de(i){if(i===null||typeof i!="object")return null;if(typeof i.next=="function")return i;let e=i.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function fe(i,e,t){return {source:"pause",directive:i,frame:e,index:t,payload:{message:i.message}}}function pe(i){return i===false||i==="abort"||i==="cancel"}function ve(i,e,t,r){r.directivesApplied++,typeof i.as=="string"&&e!==void 0&&(t[i.as]=e);}function tt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function rt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=await F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function he(i,e){return e?rt(i):tt(i)}function ye(i,e=i.hasAnyAsync){let{filledNames:t}=i,r=d=>t.has(d),o=d=>i.asyncNames.has(d)?"await ":"",n=e?"await ":"",s=[];for(let d of t)s.push(`const ${d} = directiveHooks.${d};`);s.push("const len = Math.min(directives.length, maxDirectives);"),s.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),s.push("const counters = frame.counters;"),s.push("for (let i = 0; i < len; i++) {"),s.push(" let directive = directives[i];"),r("beforeDirective")?(s.push(" let _df = frame;"),s.push(" try {"),s.push(` const _bd = ${o("beforeDirective")}beforeDirective(directive, frame);`),s.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),s.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if (typeof _bd === "object" && _bd !== null) {'),s.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),s.push(' if ("directive" in _bd) directive = _bd.directive;'),s.push(" }"),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):s.push(" const _df = frame;"),s.push(' if (typeof directive.resolve === "function") {'),s.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),s.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),s.push(" }"),s.push(" const _type = directive[typeField];"),s.push(" const _handler = _type ? handlers[_type] : undefined;"),s.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),s.push(" let _result;"),s.push(` try { _result = ${n}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),s.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),s.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),r("afterDirective")&&(s.push(" try {"),s.push(` const _ad = ${o("afterDirective")}afterDirective(directive, _result, _df);`),s.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),s.push("}"),s.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),r("onDirectivesComplete")&&s.push(`try { ${o("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),s.push("return _finalResult;");let a=s.join(`
|
|
2
|
-
|
|
3
|
-
return (${
|
|
4
|
-
$
|
|
5
|
-
})();`),isAsync:e}}function ge(i,e,t){return `return{success:false,aborted:true,abortedBy:${i},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${t},counters};`}function nt(i,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function it(i,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function st(i,e,t,r){i.push("const counters=frame.counters;"),i.push("const ctx=frame.ctx;"),i.push("const errors=[];"),i.push("let appliedCount=0;"),i.push("let skippedCount=0;");for(let[o,n]of e)i.push(`const ${n}=$.h[${JSON.stringify(o)}];`);t&&i.push("const _hookBefore=$.hooks.beforeDirective;"),r&&i.push("const _hookAfter=$.hooks.afterDirective;");}function ot(i,e,t,r){i.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${e},totalCount:${e},counters};`),t&&i.push(`try{${r}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),i.push("return _finalResult;");}function ct(i,e,t){let r=`{
|
|
6
|
-
${i}
|
|
7
|
-
}`;return t?`(${e?"async function*()":"function*()"}${r})()`:`(${e?"async ()=>":"()=>"}${r})()`}function at(i,e,t,r){let o=JSON.stringify(e.name);typeof e.resolve=="function"?(i.push("try{"),i.push(`scope[${o}]=${t}.resolve(ctx,scope).value;`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Binding resolve: "+_e});counters.errors++;}`)):i.push(`scope[${o}]=${t}.value;`);}function ut(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${t}.value};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.value};`);}function lt(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${t}.message};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.message};`);}function dt(i,e,t,r,o,n){let s=typeof e.as=="string",a=s?JSON.stringify(e.as):"";i.push(`{const _ack=yield{source:"pause",directive:${t},frame,index:${r},payload:{message:${t}.message}};`),i.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:_ack};`),i.push("appliedCount++;counters.directivesApplied++;"),s&&i.push(`if(_ack!==undefined)scope[${a}]=_ack;`),i.push("}");}function ft(i,e,t,r,o){let{L:n,total:s,typeField:a,handlerVars:c,hasBefore:u,hasAfter:d,awBefore:h,awAfter:f,awHandler:p,actionIsAsync:l,actionIsInteractive:g,interactiveHandlerSet:A}=o,D=i[a],R=c.get(D),P=typeof i.resolve=="function",b=typeof i.as=="string",I=Array.isArray(i.catch)&&i.catch.length>0,T=b?JSON.stringify(i.as):"",_=g&&A.has(D),C=o.blockCounter.n++;n.push(`_b${C}:{`);let k=u||P,x=u;k&&n.push(`let _dir=${e};`),x&&n.push("let _df=frame;"),u&&(n.push("try{"),n.push(`const _bd=${h}_hookBefore(${e},frame);`),n.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${C};}`),n.push(`if(_bd==="abort")${ge('"beforeDirective"',r-1,s)}`),n.push('if(typeof _bd==="object"&&_bd!==null){'),n.push(`if("abort" in _bd)${ge("_bd.abort",r-1,s)}`),n.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),n.push('if("directive" in _bd)_dir=_bd.directive;'),n.push("}"),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(n.push('if(typeof _dir.resolve==="function"){'),n.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}}`)):P&&(n.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}`));let E=k?"_dir":e,H=x?"_df":"frame";if(n.push("let _result;"),_?(n.push(`try{_result=yield* ${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(n.push(`try{_result=${p}${R}(${E},${H},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):(n.push(`try{_result=${p}${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")),n.push("if(_result.ok){"),n.push("appliedCount++;counters.directivesApplied++;"),b&&n.push(`scope[${T}]=_result.data;`),n.push(`if(_result.halt)${nt(r,s)}`),n.push("}else{"),n.push(`if(_result.halt)${it(r,s)}`),I){n.push('scope.$exception=_result.error||"handler failed";');let M=l?"$.runner":"$.runnerSync";n.push(`const _cr=${p}${M}(${e}.catch,${H});`),n.push("appliedCount+=_cr.appliedCount;"),n.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),n.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${r},totalCount:${s},counters,data:_cr.data};`);}else n.push(`errors.push({directiveIndex:${t},error:_result.error||"handler failed"});counters.errors++;`);n.push("}"),d&&(n.push("try{"),n.push(`const _ad=${f}_hookAfter(${E},_result,${H});`),n.push(`if(_ad==="abort")${ge('"afterDirective"',r,s)}`),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook afterDirective: "+_e});counters.errors++;}`)),n.push("}");}function pt(i,e,t,r,o,n){let{L:s}=n,a=i.cond,c=typeof a=="boolean";s.push("{"),c?s.push(`if(${a?"true":"false"}){`):(s.push("let _cond=false,_condOk=true;"),s.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),s.push(`catch(_e){errors.push({directiveIndex:${t},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),s.push("if(_condOk){"),s.push("if(_cond){"));let u=i.then;Array.isArray(u)&&u.length>0&&xe(u,`${e}.then`,r,o,n),s.push("}");let d=i.else;Array.isArray(d)&&d.length>0&&(s.push("else{"),xe(d,`${e}.else`,r,o,n),s.push("}")),c||s.push("}"),s.push("}");}function xe(i,e,t,r,o){let n=t!==-1;for(let s=0;s<i.length;s++){let a=i[s],c=`${e}[${s}]`,u=n?t:s,d=n?r:s+1;switch(a[o.typeField]){case "const":case "let":at(o.L,a,c,u);break;case "return":ut(o.L,a,c,u,d,o.total);break;case "throw":lt(o.L,a,c,u,d,o.total);break;case "pause":dt(o.L,a,c,u,d,o.total);break;case "if":{let f=n?t:s,p=n?r:s+1;pt(a,c,u,f,p,o);break}default:ft(a,c,u,d,o);break}}}function me(i,e,t){for(let r of i){let o=r[e];if(o&&!N.has(o)&&t.add(o),o==="if"){let n=r.then;Array.isArray(n)&&n.length>0&&me(n,e,t);let s=r.else;Array.isArray(s)&&s.length>0&&me(s,e,t);}}}var we=new Set;function _e(i,e,t,r=we,o,n=false,s=we){let a=[],c=i.length,{filledNames:u,hasAnyAsync:d,asyncNames:h}=e,f=u.has("beforeDirective"),p=u.has("afterDirective"),l=u.has("onDirectivesComplete"),g=o!==void 0?o:ce(i,r,t),A=d||g,D=A?"await ":"",R=h.has("beforeDirective")?"await ":"",P=h.has("afterDirective")?"await ":"",b=h.has("onDirectivesComplete")?"await ":"",I=new Set;me(i,t,I);let T=new Map,_=0;for(let E of I)T.set(E,`_h${_++}`);st(a,T,f,p),xe(i,"$.d",-1,0,{L:a,total:c,typeField:t,handlerVars:T,hasBefore:f,hasAfter:p,awBefore:R,awAfter:P,awHandler:D,actionIsAsync:A,actionIsInteractive:n,interactiveHandlerSet:s,blockCounter:{n:0}}),ot(a,c,l,b);let k=ct(a.join(`
|
|
8
|
-
`),A,n);return {fn:new Function("frame","scope","$",`"use strict";
|
|
9
|
-
return ${k};`),isAsync:A,isInteractive:n}}function ce(i,e,t){for(let r of i){let o=r[t];if(o&&e.has(o))return true;if(o==="if"){let s=r.then;if(Array.isArray(s)&&s.length>0&&ce(s,e,t))return true;let a=r.else;if(Array.isArray(a)&&a.length>0&&ce(a,e,t))return true}let n=r.catch;if(Array.isArray(n)&&n.length>0&&ce(n,e,t))return true}return false}function De(i,e,t){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:i,...t}}function Te(i,e){return De(e,`Action not found: "${i}"`,{aborted:true,abortedBy:"action-not-found"})}function Se(i,e,t){return De(t,`Max depth ${e} exceeded invoking "${i}"`,{aborted:true,abortedBy:"maxDepth"})}function $e(i,e){return De(e,`Action "${i}" is private (sub-action). Can only be invoked from within its parent scope.`)}function ae(i,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:i,counters:e}}function vt(i){return typeof i=="object"&&i!==null&&"execute"in i}function He(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&o[c].graph!==false&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Me(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Pe(i,e,t){if(!e)return t;let r=new Set(t);for(let[o,n]of i)n.executeInteractive!==void 0&&r.add(o);return r}function te(i,e,t){let r=Object.create(null);for(let[o,n]of i){let s;t&&n.executeInteractive!==void 0?s=n.executeInteractive:e&&n.executeAsync!==void 0?s=n.executeAsync:s=n.execute,r[o]=s;}return r}function Fe(i){let e=Object.create(null),t=new Map;for(let r of Object.keys(i)){let o=i[r];vt(o)?(e[r]=o.execute,t.set(r,o)):(e[r]=o,t.set(r,{execute:o}));}return {handlers:e,definitions:t}}function Ge(i,e){if(i==="*")return true;if(!i.includes("*"))return i===e;let t=i.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}function Be(i){return typeof i=="string"?{pattern:i}:i}function Ne(i,e,t){let r=new Map;if(!e&&!t){for(let o of i)r.set(o,{status:"available"});return r}if(e){let o=e.map(Be);for(let n of i){let s=o.some(a=>Ge(a.pattern,n));r.set(n,{status:s?"available":"denied"});}}else {let o=t.map(Be);for(let n of i){let s=o.find(a=>Ge(a.pattern,n));s?r.set(n,{status:"denied",reason:s.reason,source:s.source}):r.set(n,{status:"available"});}}return r}function Le(i){let{typeField:e,asyncHandlerSet:t,interactiveHandlerSet:r,subDirectiveFieldsForGraph:o}=i,n=new Map,s=new Set,a=new Set,c=new Set,u=new Set;return {upsert(d,h,f){n.set(d,ht(h,e,o)),ne(h,t,e,o)?s.add(d):s.delete(d),f||ie(h,r,e,o)?a.add(d):a.delete(d);},remove(d){n.delete(d),s.delete(d),a.delete(d);},recompute(){c=je(n,s),u=je(n,a);},isAsync(d){return c.has(d)},isInteractive(d){return u.has(d)},has(d){return n.has(d)}}}var ue=new Map;function ht(i,e,t=ue){let r=new Set;return re(i,e,t,r),r}function re(i,e,t,r){for(let o of i){let n=o[e];n==="action"&&typeof o.id=="string"&&r.add(o.id);let s=o.catch;if(Array.isArray(s)&&s.length>0&&re(s,e,t,r),n==="if"){let c=o.then;Array.isArray(c)&&c.length>0&&re(c,e,t,r);let u=o.else;Array.isArray(u)&&u.length>0&&re(u,e,t,r);continue}if(n===void 0)continue;let a=t.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];!Array.isArray(u)||u.length===0||re(u,e,t,r);}}}function ne(i,e,t,r=ue){for(let o of i){let n=o[t];if(n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ne(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ne(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ne(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ne(u,e,t,r))return true}}return false}function ie(i,e,t,r=ue){for(let o of i){let n=o[t];if(n==="pause"||n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ie(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ie(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ie(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ie(u,e,t,r))return true}}return false}function Q(i,e,t=ue){for(let r of i){let o=r[e];if(o==="pause")return true;let n=r.catch;if(Array.isArray(n)&&n.length>0&&Q(n,e,t))return true;if(o==="if"){let a=r.then;if(Array.isArray(a)&&a.length>0&&Q(a,e,t))return true;let c=r.else;if(Array.isArray(c)&&c.length>0&&Q(c,e,t))return true;continue}if(o===void 0)continue;let s=t.get(o);if(s!==void 0)for(let a=0;a<s.length;a++){let c=r[s[a]];if(!(!Array.isArray(c)||c.length===0)&&Q(c,e,t))return true}}return false}function je(i,e){let t=new Set(e),r=true;for(;r;){r=false;for(let[o,n]of i)if(!t.has(o)){for(let s of n)if(t.has(s)){t.add(o),r=true;break}}}return t}var le=class{depth=0;errors=[];warnings=[];actions=[];registered=[];begin(){this.depth++,this.depth===1&&(this.errors=[],this.warnings=[],this.actions=[],this.registered=[]);}endDepth(){if(this.depth<=0)throw new Error("endBatch() called without matching beginBatch()");return this.depth--,this.depth===0}isActive(){return this.depth>0}accumulate(e,t,r,o){this.errors.push(...e),this.warnings.push(...t);for(let n of r)this.actions.push(n);this.registered.push(...o);}};function Oe(i){for(let e of i)if(N.has(e))throw new Error(`Handler type "${e}" is reserved for engine-internal directives`)}function Ve(i,e){if(i&&e)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.")}function ze(i,e,t){if(i)return;if(e.size>0){let o=Array.from(e).join(", ");throw new Error(`Handler(s) [${o}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}let r=[];for(let[o,n]of t)n.executeInteractive!==void 0&&r.push(o);if(r.length>0)throw new Error(`Handler(s) [${r.join(", ")}] declare \`executeInteractive\` variant but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}function Ke(i){let e=new Set,t=new Set;for(let[r,o]of i)(o.async===true||core.isAsyncFunction(o.execute))&&e.add(r),(o.interactive===true||core.isGeneratorFunction(o.execute))&&t.add(r);return {asyncHandlerSet:e,interactiveHandlerSet:t}}function Ue(i,e,t,r){let o=t?te(i,true,false):e,n=r?te(i,t,true):null;return {handlersAsync:o,handlersInteractive:n}}function Ae(i,e){return e?{next:()=>Promise.resolve({value:i,done:true}),return:()=>Promise.resolve({value:i,done:true}),throw:o=>Promise.reject(o),[Symbol.asyncIterator](){return this}}:{next:()=>({value:i,done:true}),return:()=>({value:i,done:true}),throw:r=>{throw r},[Symbol.iterator](){return this}}}function qe(i,e,t,r,o,n){if(n){let c=i;return {async next(d){let h=await c.next(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},async return(){let d=await c.return(void 0),h=d.value;if(d.done&&o!==null){let f=o(e,t,h,r);f!==void 0&&(h=f);}return {value:h,done:true}},async throw(d){let h=await c.throw(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},[Symbol.asyncIterator](){return this}}}let s=i;return {next(c){let u=s.next(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},return(){let c=s.return(void 0),u=c.value;if(c.done&&o!==null){let d=o(e,t,u,r);d!==void 0&&(u=d);}return {value:u,done:true}},throw(c){let u=s.throw(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}var Dt=8,At="type",be={maxDepth:10,maxRules:1e4,maxDirectives:1e5},Re=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_handlersAsync;_handlersInteractive;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new X;_batch=new le;_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Dt,this._typeField=e.typeField??At,this._limits={maxDepth:e.limits?.maxDepth??be.maxDepth,maxRules:e.limits?.maxRules??be.maxRules,maxDirectives:e.limits?.maxDirectives??be.maxDirectives};let{handlers:t,definitions:r}=Fe(e.handlers);Oe(Object.keys(e.handlers)),Ve(e.allowedDirectives,e.blockedDirectives),this._handlers=t,this._definitions=r,this._directivePermissions=Ne(Object.keys(t),e.allowedDirectives,e.blockedDirectives),this._directiveHooks=e.directiveHooks??{},this._beforeAction=e.actionHooks?.beforeAction??null,this._afterAction=e.actionHooks?.afterAction??null,this._directiveAnalysis=core.analyzeSlots(this._directiveHooks,core.DIRECTIVE_SLOT_NAMES);let{asyncHandlerSet:o,interactiveHandlerSet:n}=Ke(this._definitions);this._asyncHandlerSet=o,this._interactiveHandlerSet=n,this._isInteractive=e.interactive!==void 0,ze(this._isInteractive,n,this._definitions),this._isAsync=this._directiveAnalysis.hasAnyAsync||o.size>0;let{handlersAsync:s,handlersInteractive:a}=Ue(this._definitions,this._handlers,this._isAsync,this._isInteractive);this._handlersAsync=s,this._handlersInteractive=a;let c=He(this._definitions);this._subDirectiveFieldsForGraph=c,this._subDirectiveFieldsAll=Me(this._definitions),this._miniGraph=Le({typeField:this._typeField,asyncHandlerSet:o,interactiveHandlerSet:n,subDirectiveFieldsForGraph:c}),this._engineRef=this._buildEngineRef();let u=oe(this._directiveAnalysis,false);this._directiveRunner=this._buildDirectiveRunner(),this._directiveRunnerSync=this._buildDirectiveRunnerSync(u);let d=this._buildExecutors(u);this._directiveExecutor=d.directiveExecutor,this._mode=d.mode,this._interactiveExecutor=d.interactiveExecutor;}_buildEngineRef(){return {runDirectives:(e,t)=>this._executeDirectives(e,t),runDirectivesAsync:(e,t)=>this._executeDirectivesAsync(e,t),invoke:(e,t,r)=>this._invokeInternal(e,t,r),invokeAsync:(e,t,r)=>this._invokeInternalAsync(e,t,r),isActionAsync:e=>this._miniGraph.has(e)?this._miniGraph.isAsync(e):void 0,isActionInteractive:e=>this._miniGraph.has(e)?this._miniGraph.isInteractive(e):void 0,invokeInteractive:(e,t,r)=>this._invokeInteractiveInternal(e,t,r),runDirectivesInteractive:(e,t)=>this._executeDirectivesInteractive(e,t),evaluateRules:()=>{throw new Error("evaluateRules() not available in ActionEngine context. Use createRuleEngine().")},evaluateRulesAsync:()=>{throw new Error("evaluateRulesAsync() not available in ActionEngine context. Use createRuleEngine().")}}}_buildDirectiveRunner(){let e=this._isAsync?this._handlersAsync:this._handlers;return (t,r)=>this._directiveExecutor(t,r,e,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildDirectiveRunnerSync(e){return (t,r)=>e(t,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildExecutors(e){let t,r;this._requestedMode==="jit"?(t=this._buildJitDirectiveExecutor(),r="jit"):this._isAsync?(t=oe(this._directiveAnalysis,true),r="interpret"):(t=e,r="interpret");let o=this._isInteractive?this._isAsync?he(this._directiveAnalysis,true):he(this._directiveAnalysis,false):null;return {directiveExecutor:t,mode:r,interactiveExecutor:o}}register(e){let t=[],r=[],o=[],n=[];for(let c of e){if(!c.id){r.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&Q(c.directives,this._typeField,this._subDirectiveFieldsForGraph)){r.push({actionId:c.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let u=ke(c,this._handlers,this._definitions,this._typeField);if(u.length>0){for(let d of u)r.push({actionId:c.id,error:d});continue}n.push(c);}for(let c of n){let u=B(c.directives,this._typeField,this._subDirectiveFieldsAll),d={definition:c,directives:u,compiled:null,invokeCount:0};this._registry.set(c.id,d),this._registeredIds.add(c.id),this._miniGraph.upsert(c.id,u,c.interactive===true),t.push(c.id);}if(this._batch.isActive())return this._batch.accumulate(r,o,n,t),{registered:t,errors:r,warnings:o};let s=t;if(n.length>0){this._miniGraph.recompute();let c=this._validateInteractiveVariants(t);c.errors.length>0&&r.push(...c.errors),c.warnings.length>0&&o.push(...c.warnings),s=c.validRegistered,this._invalidateAndMaybeRecompile();}let a={registered:s,errors:r,warnings:o};if(s.length>0){let c=new Set(s),u=n.filter(d=>c.has(d.id));this._emitter.emit("register",{actions:u,result:a,registered:s});}return a}unregister(e){let t=this._registry.delete(e);t&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let r=e+"/",o=[];for(let n of this._registry.keys())n.startsWith(r)&&(this._registry.delete(n),this._registeredIds.delete(n),this._miniGraph.remove(n),o.push(n));return t&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:o})),t}invoke(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);if(this._miniGraph.isAsync(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is async (transitively). Use invokeAsync() instead.`);if(this._directiveAnalysis.hasAnyAsync)throw new Error(`Cannot call invoke("${e}") \u2014 engine has async directive hooks. Use invokeAsync() instead.`);let o=r!==void 0?r:this._requireCtx(),n=core.createRootFrame(o,this._limits);return this._invokeInternal(e,t,n)}async invokeAsync(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let o=r!==void 0?r:this._requireCtx(),n=core.createRootFrame(o,this._limits);return this._invokeInternalAsync(e,t,n)}setContext(e){this._ctx=e;}context(e,t){let r=this._ctx;this._ctx=e;try{return t()}finally{this._ctx=r;}}beginBatch(){this._batch.begin();}endBatch(){if(!this._batch.endDepth())return {registered:[],errors:[],warnings:[]};let t=this._batch.registered;if(this._batch.registered.length>0){this._miniGraph.recompute();let o=this._validateInteractiveVariants(this._batch.registered);this._batch.errors.push(...o.errors),this._batch.warnings.push(...o.warnings),t=o.validRegistered,this._invalidateAndMaybeRecompile();}let r={registered:t,errors:this._batch.errors,warnings:this._batch.warnings};if(t.length>0){let o=new Set(t),n=this._batch.actions.filter(s=>o.has(s.id));this._emitter.emit("register",{actions:n,result:r,registered:t});}return r}on(e,t){return this._emitter.on(e,t)}get handlerDefinitions(){return this._definitions}get registeredIds(){return this._registeredIds}getActionDefinition(e){return this._registry.get(e)?.definition}get typeField(){return this._typeField}get subDirectiveFieldsForGraph(){return this._subDirectiveFieldsForGraph}get directivePermissions(){return this._directivePermissions}get isAsync(){return this._isAsync}get isInteractive(){return this._isInteractive}isActionAsync(e){if(this._miniGraph.has(e))return this._miniGraph.isAsync(e)}isActionInteractive(e){if(this._miniGraph.has(e))return this._miniGraph.isInteractive(e)}invokeInteractive(e,t,r){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let o=r!==void 0?r:this._requireCtx(),n=core.createRootFrame(o,this._limits);return this._invokeInteractiveInternal(e,t,n)}_invokeInteractiveInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return Ae(o,this._isAsync);let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return Ae(ae(u.data,s.counters),this._isAsync)}let c;if(n.compiled&&n.compiled.isInteractive)c=n.compiled.fn(s,s.scope,n.compiled.$);else {let u=this._interactiveExecutor;c=u(n.directives,s,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return qe(c,e,t,s,this._afterAction,this._isAsync)}_executeDirectivesInteractive(e,t){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("runDirectivesInteractive: engine has no `interactive` config");return this._interactiveExecutor(e,t,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}get compilationMode(){return this._mode}get directiveHookSlots(){return this._directiveAnalysis.filledNames}get asyncSlots(){return this._directiveAnalysis.asyncNames}compile(){if(this._requestedMode!=="interpret"){this._mode!=="jit"&&this._promote();for(let[e,t]of this._registry)t.compiled||(t.compiled=this._compileAction(e,t.directives));}}_invokeInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=n.compiled.fn(s,a,n.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(n.compiled=this._compileAction(e,n.directives),c=n.compiled.fn(s,a,n.compiled.$)):(c=this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=await n.compiled.fn(s,a,n.compiled.$):(c=await this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}_prepareInvoke(e,t,r){let o=this._registry.get(e);if(!o)return Te(e,r.counters);if(e.includes("/")&&!this._isAccessible(e,r))return $e(e,r.counters);if(r.depth>=r.limits.maxDepth)return Se(e,r.limits.maxDepth,r.counters);let n=Object.create(r.scope);t&&Object.assign(n,t);let s=r.child("action:"+e,0,e).withScope(n);return {stored:o,childFrame:s,childScope:n}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&this._promote());}_executeDirectives(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,t){let r=this._miniGraph.isAsync(e),o=this._miniGraph.isInteractive(e),n=Pe(this._definitions,o,this._interactiveHandlerSet),{fn:s,isAsync:a,isInteractive:c}=_e(t,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,r,o,n),u=te(this._definitions,a,c),d={d:t,h:u,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:s,$:d,isAsync:a,isInteractive:c}}_isAccessible(e,t){let o="action:"+e.slice(0,e.lastIndexOf("/"));return t.path.includes(o)}_requireCtx(){if(this._ctx===void 0)throw new Error("No context set. Pass ctx to invoke(id, params, ctx), call setContext(ctx), or use context(ctx, fn).");return this._ctx}_promote(){this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit";}_buildJitDirectiveExecutor(){let{fn:e}=ye(this._directiveAnalysis,this._isAsync);return e}_validateInteractiveVariants(e){let t=[],r=[],o=new Set(e),n=new Set;for(let a of this._registeredIds){if(!this._miniGraph.isInteractive(a))continue;let c=this._registry.get(a);if(c===void 0)continue;let u=Ee(c.directives,this._typeField,this._definitions,this._subDirectiveFieldsForGraph,this._interactiveHandlerSet,h=>this._miniGraph.isInteractive(h),core.isGeneratorFunction);if(u.size===0)continue;let d=o.has(a);for(let h of u){let f=`Action "${a}" is transitively interactive but handler "${h}" has no executeInteractive variant (and execute is not a generator function, and interactive flag is not set)`;d?(t.push({actionId:a,error:f,code:"MISSING_INTERACTIVE_VARIANT"}),n.add(a)):r.push({actionId:a,code:"MISSING_INTERACTIVE_VARIANT",message:f});}}if(n.size>0){for(let a of n)this._registry.delete(a),this._registeredIds.delete(a),this._miniGraph.remove(a);this._miniGraph.recompute();}return {validRegistered:e.filter(a=>!n.has(a)),errors:t,warnings:r}}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,t]of this._registry)t.compiled=this._compileAction(e,t.directives);}};function Ct(i){return new Re(i)}exports.RESERVED_TYPES=N;exports.SimpleEmitter=X;exports.buildActionExecutor=_e;exports.buildDirectiveExecutor=ye;exports.createActionEngine=Ct;exports.createDirectiveInterpreter=oe;exports.drainAsync=Je;exports.drainSync=We;exports.normalizeDirectives=B;exports.replayResponder=Ye;
|
|
1
|
+
'use strict';var core=require('@statedelta-actions/core');function Qe(r,e){let t;for(;;){let n=r.next(t);if(n.done)return n.value;t=e?e(n.value):void 0;}}async function Xe(r,e){let t;for(;;){let n=await r.next(t);if(n.done)return n.value;t=e?await e(n.value):void 0;}}function Ze(r){let e=0;return t=>{if(t?.source!=="step"&&!(e>=r.length))return r[e++]}}var Z=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 i=0;i<s.length;i++)try{s[i](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 j=new Set(["const","let","return","throw","pause","if"]);function Ie(r,e,t,n){let s=[];return oe(r.directives,e,t,n,"directive",s,r.id),s}function oe(r,e,t,n,s,i,o){for(let a=0;a<r.length;a++){let c=r[a],u=c[n],l=`${s}[${a}]`;if(!u){i.push(`${l}: missing type field "${n}"`);continue}if(u==="if"){let d=c.cond;typeof d!="function"&&typeof d!="boolean"&&i.push(`${l}: "if" requires cond as function or boolean`);let x=c.then;Array.isArray(x)?oe(x,e,t,n,`${l}.then`,i,o):i.push(`${l}: "if" requires then as array`);let C=c.else;C!==void 0&&(Array.isArray(C)?oe(C,e,t,n,`${l}.else`,i,o):i.push(`${l}.else: must be array`));continue}if(j.has(u))continue;if(!e[u])throw new Error(`Action "${o}" ${l}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let y=t.get(u);if(y?.validate)try{let d=y.validate(c);d&&!d.valid&&i.push(`${l}: ${d.error??"validation failed"}`);}catch(d){i.push(`${l}: validate threw: ${d}`);}let v=c.catch;if(v&&Array.isArray(v))for(let d=0;d<v.length;d++){let C=v[d][n];if(!(C&&j.has(C))&&C&&!e[C])throw new Error(`Action "${o}" ${l}.catch[${d}]: no handler registered for type "${C}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let f=y?.subDirectives;if(f===void 0)continue;let p=Object.keys(f);for(let d=0;d<p.length;d++){let x=p[d];if(x==="catch")continue;let C=c[x];if(C===void 0){if(f[x].required)throw new Error(`Action "${o}" ${l}: handler "${u}" requires sub-directives field "${x}"`);continue}if(!Array.isArray(C))throw new Error(`Action "${o}" ${l}.${x}: must be an array of directives`);oe(C,e,t,n,`${l}.${x}`,i,o);}}}var et=new Map;function N(r,e,t=et){let n=r.length,s=new Array(n);for(let i=0;i<n;i++){let o=r[i],a=o[e],c=o,u=false,l=o.catch;if(Array.isArray(l)&&l.length>0&&(c={...c,catch:N(l,e,t)},u=true),a==="if"){let y=o.then;Array.isArray(y)&&y.length>0&&(c={...c,then:N(y,e,t)},u=true);let v=o.else;Array.isArray(v)&&v.length>0&&(c={...c,else:N(v,e,t)},u=true);}else if(a!==void 0){let y=t.get(a);if(y!==void 0)for(let v=0;v<y.length;v++){let f=y[v],p=o[f];!Array.isArray(p)||p.length===0||(c={...c,[f]:N(p,e,t)},u=true);}}s[i]=u?c:o;}return s}function we(r,e,t,n,s,i,o){let a=new Set;return ee(r,e,t,n,s,i,o,a),a}function ee(r,e,t,n,s,i,o,a){for(let c of r){let u=c[e];if(u!==void 0){let v=t.get(u);if(v!==void 0&&v.subDirectives!==void 0){let f=n.get(u);if(f!==void 0){let p=false;for(let d=0;d<f.length;d++){let x=c[f[d]];if(!(!Array.isArray(x)||x.length===0)&&te(x,e,n,s,i)){p=true;break}}p&&(v.executeInteractive!==void 0||v.interactive===true||o(v.execute)||a.add(u));}}}let l=c.catch;if(Array.isArray(l)&&l.length>0&&ee(l,e,t,n,s,i,o,a),u==="if"){let v=c.then;Array.isArray(v)&&v.length>0&&ee(v,e,t,n,s,i,o,a);let f=c.else;Array.isArray(f)&&f.length>0&&ee(f,e,t,n,s,i,o,a);continue}if(u===void 0)continue;let y=n.get(u);if(y!==void 0)for(let v=0;v<y.length;v++){let f=c[y[v]];!Array.isArray(f)||f.length===0||ee(f,e,t,n,s,i,o,a);}}}function te(r,e,t,n,s){for(let i of r){let o=i[e];if(o==="pause"||o!==void 0&&n.has(o)||o==="action"&&typeof i.id=="string"&&s(i.id))return true;let a=i.catch;if(Array.isArray(a)&&a.length>0&&te(a,e,t,n,s))return true;if(o==="if"){let u=i.then;if(Array.isArray(u)&&u.length>0&&te(u,e,t,n,s))return true;let l=i.else;if(Array.isArray(l)&&l.length>0&&te(l,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 l=i[c[u]];if(!(!Array.isArray(l)||l.length===0)&&te(l,e,t,n,s))return true}}return false}function O(r,e,t,n,s,i){let o=r.name;if(typeof r.resolve=="function")try{t[o]=r.resolve(e,t).value;}catch(a){n.push({directiveIndex:s,error:`Binding resolve: ${a}`}),i.errors++;}else t[o]=r.value;}function L(r,e,t,n,s,i){let o=r.value;if(typeof r.resolve=="function")try{let a=r.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}`}),i.errors++,{ok:false}}return {ok:true,data:o}}function V(r,e,t,n,s,i){let o=r.message;if(typeof r.resolve=="function")try{let a=r.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}`}),i.errors++,{ok:false}}return {ok:true,data:o}}function z(r,e,t,n,s,i,o,a,c,u,l){let y;try{let f=r.cond;y=typeof f=="function"?!!f(e,t):!!f;}catch(f){c.push({directiveIndex:u,error:`if cond: ${f}`}),l.errors++;return}let v=y?r.then:r.else;if(Array.isArray(v)&&v.length>0){let f=Math.min(v.length,a),p=s?i:o;n.push({dirs:v,i:0,len:f,topLevelIfIndex:p});}}function K(r,e,t){let n=core.processIntercept(r,"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,i=e;return n.ctx!==void 0&&(s=t.withCtx(n.ctx)),n.directive!==void 0&&(i=n.directive),{action:"continue",directive:i,dFrame:s}}function B(r,e,t,n,s){r.push({directiveIndex:t,error:`Hook ${n}: ${s}`}),e.errors++;}function H(r,e,t,n,s){return {success:false,aborted:true,abortedBy:r,appliedCount:e.appliedCount,skippedCount:e.skippedCount,errors:e.errors,processedCount:t,totalCount:n,counters:e.counters,data:s}}function U(r,e,t,n){return {success:true,aborted:true,abortedBy:"halt",appliedCount:r.appliedCount,skippedCount:r.skippedCount,errors:r.errors,processedCount:e,totalCount:t,counters:r.counters,data:n}}function q(r,e,t,n){return {success:true,aborted:false,appliedCount:r.appliedCount,skippedCount:r.skippedCount,errors:r.errors,processedCount:e,totalCount:t,counters:r.counters,data:n}}function W(r,e){return {success:true,aborted:false,appliedCount:r.appliedCount,skippedCount:r.skippedCount,errors:r.errors,processedCount:e,totalCount:e,counters:r.counters}}function Y(r,e,t,n){return {success:n.success,aborted:true,abortedBy:n.abortedBy,appliedCount:r.appliedCount,skippedCount:r.skippedCount,errors:r.errors,processedCount:e,totalCount:t,counters:r.counters,data:n.data}}function J(r,e,t,n,s){if(typeof r.resolve!="function")return r;try{let i=r.resolve(e.ctx,e.scope);return {...r,...i}}catch(i){return t.push({directiveIndex:n,error:`Directive resolve: ${i}`}),s.errors++,null}}function Q(r,e){return [{dirs:r,i:0,len:e,topLevelIfIndex:-1}]}function nt(r){let e=r.filledNames.has("beforeDirective"),t=r.filledNames.has("afterDirective"),n=r.filledNames.has("onDirectivesComplete");return function(i,o,a,c,u,l,y){let v=Math.min(i.length,y),f=[],p={appliedCount:0,skippedCount:0,errors:f,counters:o.counters},{scope:d}=o,x=o.ctx,C=Q(i,v),E=0;for(;C.length>0;){let $=C[C.length-1];if($.i>=$.len){C.pop();continue}let k=$.i++,S=$.topLevelIfIndex!==-1,I=S?$.topLevelIfIndex:k;S||(E=k+1);let _=$.dirs[k],R=_[u];if(R==="const"||R==="let"){O(_,x,d,f,I,p.counters);continue}if(R==="return"){let m=L(_,x,d,f,I,p.counters);if(!m.ok)continue;return q(p,E,v,m.data)}if(R==="throw"){let m=V(_,x,d,f,I,p.counters);if(!m.ok)continue;return H("throw",p,E,v,m.data)}if(R==="if"){z(_,x,d,C,S,$.topLevelIfIndex,k,y,f,I,p.counters);continue}let A=_,D=o;if(e)try{let m=c.beforeDirective(A,o),h=K(m,A,o);if(h.action==="skip"){p.skippedCount++,p.counters.directivesSkipped++;continue}if(h.action==="abort"){let g=E===0?k:E-1;return H(h.reason,p,g,v)}A=h.directive,D=h.dFrame;}catch(m){B(f,p.counters,I,"beforeDirective",m);}let M=J(A,D,f,I,p.counters);if(M===null)continue;A=M;let P=A[u],G=P?a[P]:void 0;if(!G){f.push({directiveIndex:I,error:`No handler for directive type: ${P??"undefined"}`}),p.counters.errors++;continue}let T;try{T=G(A,D,l);}catch(m){T={ok:false,error:String(m)};}let b=E;if(T.ok){if(p.appliedCount++,p.counters.directivesApplied++,typeof A.as=="string"&&(d[A.as]=T.data),T.halt)return U(p,b,v,T.data)}else {if(T.halt)return H("halt",p,b,v,T.data);let m=A.catch;if(Array.isArray(m)&&m.length>0){d.$exception=T.error??"handler failed";let h=l.runDirectives(m,D);p.appliedCount+=h.appliedCount;for(let g=0;g<h.errors.length;g++)f.push(h.errors[g]);if(h.aborted)return Y(p,b,v,h)}else f.push({directiveIndex:I,error:T.error??"handler failed"}),p.counters.errors++;}if(t)try{if(c.afterDirective(A,T,D)==="abort")return H("afterDirective",p,b,v)}catch(m){B(f,p.counters,I,"afterDirective",m);}}let w=W(p,v);if(n)try{c.onDirectivesComplete(w);}catch{}return w}}function rt(r){let e=r.filledNames.has("beforeDirective"),t=r.filledNames.has("afterDirective"),n=r.filledNames.has("onDirectivesComplete");return async function(i,o,a,c,u,l,y){let v=Math.min(i.length,y),f=[],p={appliedCount:0,skippedCount:0,errors:f,counters:o.counters},{scope:d}=o,x=o.ctx,C=Q(i,v),E=0;for(;C.length>0;){let $=C[C.length-1];if($.i>=$.len){C.pop();continue}let k=$.i++,S=$.topLevelIfIndex!==-1,I=S?$.topLevelIfIndex:k;S||(E=k+1);let _=$.dirs[k],R=_[u];if(R==="const"||R==="let"){O(_,x,d,f,I,p.counters);continue}if(R==="return"){let m=L(_,x,d,f,I,p.counters);if(!m.ok)continue;return q(p,E,v,m.data)}if(R==="throw"){let m=V(_,x,d,f,I,p.counters);if(!m.ok)continue;return H("throw",p,E,v,m.data)}if(R==="if"){z(_,x,d,C,S,$.topLevelIfIndex,k,y,f,I,p.counters);continue}let A=_,D=o;if(e)try{let m=await c.beforeDirective(A,o),h=K(m,A,o);if(h.action==="skip"){p.skippedCount++,p.counters.directivesSkipped++;continue}if(h.action==="abort"){let g=E===0?k:E-1;return H(h.reason,p,g,v)}A=h.directive,D=h.dFrame;}catch(m){B(f,p.counters,I,"beforeDirective",m);}let M=J(A,D,f,I,p.counters);if(M===null)continue;A=M;let P=A[u],G=P?a[P]:void 0;if(!G){f.push({directiveIndex:I,error:`No handler for directive type: ${P??"undefined"}`}),p.counters.errors++;continue}let T;try{T=await G(A,D,l);}catch(m){T={ok:false,error:String(m)};}let b=E;if(T.ok){if(p.appliedCount++,p.counters.directivesApplied++,typeof A.as=="string"&&(d[A.as]=T.data),T.halt)return U(p,b,v,T.data)}else {if(T.halt)return H("halt",p,b,v,T.data);let m=A.catch;if(Array.isArray(m)&&m.length>0){d.$exception=T.error??"handler failed";let h=await l.runDirectivesAsync(m,D);p.appliedCount+=h.appliedCount;for(let g=0;g<h.errors.length;g++)f.push(h.errors[g]);if(h.aborted)return Y(p,b,v,h)}else f.push({directiveIndex:I,error:T.error??"handler failed"}),p.counters.errors++;}if(t)try{if(await c.afterDirective(A,T,D)==="abort")return H("afterDirective",p,b,v)}catch(m){B(f,p.counters,I,"afterDirective",m);}}let w=W(p,v);if(n)try{await c.onDirectivesComplete(w);}catch{}return w}}function ce(r,e){return e?rt(r):nt(r)}function fe(r){if(r===null||typeof r!="object")return null;if(typeof r.next=="function")return r;let e=r.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function pe(r,e,t){return {source:"pause",directive:r,frame:e,index:t,payload:{message:r.message}}}function ve(r){return r===false||r==="abort"||r==="cancel"}function he(r,e,t,n){n.directivesApplied++,typeof r.as=="string"&&e!==void 0&&(t[r.as]=e);}function ye(r,e,t){return {source:"step",directive:r,frame:e,index:t}}var Se=Object.freeze({kind:"continue"}),it=Object.freeze({kind:"skip"}),st=Object.freeze({kind:"abort"});function ge(r){if(r==null||typeof r!="object")return Se;let e=r;if(e.abort===true)return st;if(e.skip===true)return it;if(e.replaceWith!==void 0){let t=e.replaceWith;if(typeof t=="object"&&t!==null&&!Array.isArray(t))return {kind:"replace",directive:t}}return Se}function ot(r){let e=r.filledNames.has("beforeDirective"),t=r.filledNames.has("afterDirective"),n=r.filledNames.has("onDirectivesComplete");return function*(i,o,a,c,u,l,y,v){let f=Math.min(i.length,y),p=[],d={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:x}=o,C=o.ctx,E=Q(i,f),w=0;for(;E.length>0;){let k=E[E.length-1];if(k.i>=k.len){E.pop();continue}let S=k.i++,I=k.topLevelIfIndex!==-1,_=I?k.topLevelIfIndex:S;I||(w=S+1);let R=k.dirs[S];if(v){let h=yield ye(R,o,_),g=ge(h);if(g.kind==="skip"){d.skippedCount++,d.counters.directivesSkipped++;continue}if(g.kind==="abort"){let F=w===0?S:w-1;return H("step",d,F,f)}g.kind==="replace"&&(R=g.directive);}let A=R[u];if(A==="const"||A==="let"){O(R,C,x,p,_,d.counters);continue}if(A==="return"){let h=L(R,C,x,p,_,d.counters);if(!h.ok)continue;return q(d,w,f,h.data)}if(A==="throw"){let h=V(R,C,x,p,_,d.counters);if(!h.ok)continue;return H("throw",d,w,f,h.data)}if(A==="pause"){let h=w,g=yield pe(R,o,_);if(ve(g))return H("pause",d,h,f,g);d.appliedCount++,he(R,g,x,d.counters);continue}if(A==="if"){z(R,C,x,E,I,k.topLevelIfIndex,S,y,p,_,d.counters);continue}let D=R,M=o;if(e)try{let h=c.beforeDirective(D,o),g=K(h,D,o);if(g.action==="skip"){d.skippedCount++,d.counters.directivesSkipped++;continue}if(g.action==="abort"){let F=w===0?S:w-1;return H(g.reason,d,F,f)}D=g.directive,M=g.dFrame;}catch(h){B(p,d.counters,_,"beforeDirective",h);}let P=J(D,M,p,_,d.counters);if(P===null)continue;D=P;let G=D[u],T=G?a[G]:void 0;if(!T){p.push({directiveIndex:_,error:`No handler for directive type: ${G??"undefined"}`}),d.counters.errors++;continue}let b;try{let h=T(D,M,l),g=fe(h);g!==null?b=yield*g:b=h;}catch(h){b={ok:false,error:String(h)};}let m=w;if(b.ok){if(d.appliedCount++,d.counters.directivesApplied++,typeof D.as=="string"&&(x[D.as]=b.data),b.halt)return U(d,m,f,b.data)}else {if(b.halt)return H("halt",d,m,f,b.data);let h=D.catch;if(Array.isArray(h)&&h.length>0){x.$exception=b.error??"handler failed";let g=l.runDirectives(h,M);d.appliedCount+=g.appliedCount;for(let F=0;F<g.errors.length;F++)p.push(g.errors[F]);if(g.aborted)return Y(d,m,f,g)}else p.push({directiveIndex:_,error:b.error??"handler failed"}),d.counters.errors++;}if(t)try{if(c.afterDirective(D,b,M)==="abort")return H("afterDirective",d,m,f)}catch(h){B(p,d.counters,_,"afterDirective",h);}}let $=W(d,f);if(n)try{c.onDirectivesComplete($);}catch{}return $}}function ct(r){let e=r.filledNames.has("beforeDirective"),t=r.filledNames.has("afterDirective"),n=r.filledNames.has("onDirectivesComplete");return async function*(i,o,a,c,u,l,y,v){let f=Math.min(i.length,y),p=[],d={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:x}=o,C=o.ctx,E=Q(i,f),w=0;for(;E.length>0;){let k=E[E.length-1];if(k.i>=k.len){E.pop();continue}let S=k.i++,I=k.topLevelIfIndex!==-1,_=I?k.topLevelIfIndex:S;I||(w=S+1);let R=k.dirs[S];if(v){let h=yield ye(R,o,_),g=ge(h);if(g.kind==="skip"){d.skippedCount++,d.counters.directivesSkipped++;continue}if(g.kind==="abort"){let F=w===0?S:w-1;return H("step",d,F,f)}g.kind==="replace"&&(R=g.directive);}let A=R[u];if(A==="const"||A==="let"){O(R,C,x,p,_,d.counters);continue}if(A==="return"){let h=L(R,C,x,p,_,d.counters);if(!h.ok)continue;return q(d,w,f,h.data)}if(A==="throw"){let h=V(R,C,x,p,_,d.counters);if(!h.ok)continue;return H("throw",d,w,f,h.data)}if(A==="pause"){let h=w,g=yield pe(R,o,_);if(ve(g))return H("pause",d,h,f,g);d.appliedCount++,he(R,g,x,d.counters);continue}if(A==="if"){z(R,C,x,E,I,k.topLevelIfIndex,S,y,p,_,d.counters);continue}let D=R,M=o;if(e)try{let h=await c.beforeDirective(D,o),g=K(h,D,o);if(g.action==="skip"){d.skippedCount++,d.counters.directivesSkipped++;continue}if(g.action==="abort"){let F=w===0?S:w-1;return H(g.reason,d,F,f)}D=g.directive,M=g.dFrame;}catch(h){B(p,d.counters,_,"beforeDirective",h);}let P=J(D,M,p,_,d.counters);if(P===null)continue;D=P;let G=D[u],T=G?a[G]:void 0;if(!T){p.push({directiveIndex:_,error:`No handler for directive type: ${G??"undefined"}`}),d.counters.errors++;continue}let b;try{let h=await T(D,M,l),g=fe(h);g!==null?b=yield*g:b=h;}catch(h){b={ok:false,error:String(h)};}let m=w;if(b.ok){if(d.appliedCount++,d.counters.directivesApplied++,typeof D.as=="string"&&(x[D.as]=b.data),b.halt)return U(d,m,f,b.data)}else {if(b.halt)return H("halt",d,m,f,b.data);let h=D.catch;if(Array.isArray(h)&&h.length>0){x.$exception=b.error??"handler failed";let g=await l.runDirectivesAsync(h,M);d.appliedCount+=g.appliedCount;for(let F=0;F<g.errors.length;F++)p.push(g.errors[F]);if(g.aborted)return Y(d,m,f,g)}else p.push({directiveIndex:_,error:b.error??"handler failed"}),d.counters.errors++;}if(t)try{if(await c.afterDirective(D,b,M)==="abort")return H("afterDirective",d,m,f)}catch(h){B(p,d.counters,_,"afterDirective",h);}}let $=W(d,f);if(n)try{await c.onDirectivesComplete($);}catch{}return $}}function xe(r,e){return e?ct(r):ot(r)}function me(r,e,t){return `return{success:false,aborted:true,abortedBy:${r},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${t},counters};`}function at(r,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${r},totalCount:${e},counters,data:_result.data};`}function ut(r,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${r},totalCount:${e},counters,data:_result.data};`}function lt(r,e,t,n){r.push("const counters=frame.counters;"),r.push("const ctx=frame.ctx;"),r.push("const errors=[];"),r.push("let appliedCount=0;"),r.push("let skippedCount=0;");for(let[s,i]of e)r.push(`const ${i}=$.h[${JSON.stringify(s)}];`);t&&r.push("const _hookBefore=$.hooks.beforeDirective;"),n&&r.push("const _hookAfter=$.hooks.afterDirective;");}function dt(r,e,t,n){r.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${e},totalCount:${e},counters};`),t&&r.push(`try{${n}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),r.push("return _finalResult;");}function ft(r,e,t){let n=`{
|
|
2
|
+
${r}
|
|
3
|
+
}`;return t?`(${e?"async function*()":"function*()"}${n})()`:`(${e?"async ()=>":"()=>"}${n})()`}function pt(r,e,t,n){let s=JSON.stringify(e.name);typeof e.resolve=="function"?(r.push("try{"),r.push(`scope[${s}]=${t}.resolve(ctx,scope).value;`),r.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Binding resolve: "+_e});counters.errors++;}`)):r.push(`scope[${s}]=${t}.value;`);}function vt(r,e,t,n,s,i){typeof e.resolve=="function"?(r.push("try{"),r.push(`const _rv=${t}.resolve(ctx,scope);`),r.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${t}.value};`),r.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Control resolve: "+_e});counters.errors++;}`)):r.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:${t}.value};`);}function ht(r,e,t,n,s,i){typeof e.resolve=="function"?(r.push("try{"),r.push(`const _rv=${t}.resolve(ctx,scope);`),r.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${t}.message};`),r.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Control resolve: "+_e});counters.errors++;}`)):r.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:${t}.message};`);}function yt(r,e,t,n,s,i){let o=typeof e.as=="string",a=o?JSON.stringify(e.as):"";r.push(`{const _ack=yield{source:"pause",directive:${t},frame,index:${n},payload:{message:${t}.message}};`),r.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:_ack};`),r.push("appliedCount++;counters.directivesApplied++;"),o&&r.push(`if(_ack!==undefined)scope[${a}]=_ack;`),r.push("}");}function gt(r,e,t,n,s){let{L:i,total:o,typeField:a,handlerVars:c,hasBefore:u,hasAfter:l,awBefore:y,awAfter:v,awHandler:f,actionIsAsync:p,actionIsInteractive:d,interactiveHandlerSet:x}=s,C=r[a],E=c.get(C),w=typeof r.resolve=="function",$=typeof r.as=="string",k=Array.isArray(r.catch)&&r.catch.length>0,S=$?JSON.stringify(r.as):"",I=d&&x.has(C),_=s.blockCounter.n++;i.push(`_b${_}:{`);let R=u||w,A=u;R&&i.push(`let _dir=${e};`),A&&i.push("let _df=frame;"),u&&(i.push("try{"),i.push(`const _bd=${y}_hookBefore(${e},frame);`),i.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${_};}`),i.push(`if(_bd==="abort")${me('"beforeDirective"',n-1,o)}`),i.push('if(typeof _bd==="object"&&_bd!==null){'),i.push(`if("abort" in _bd)${me("_bd.abort",n-1,o)}`),i.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),i.push('if("directive" in _bd)_dir=_bd.directive;'),i.push("}"),i.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(i.push('if(typeof _dir.resolve==="function"){'),i.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),i.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${_};}}`)):w&&(i.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),i.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${_};}`));let D=R?"_dir":e,M=A?"_df":"frame";if(i.push("let _result;"),I?(i.push(`try{_result=yield* ${E}(${D},${M},$.engine);}`),i.push("catch(_e){_result={ok:false,error:String(_e)};}")):d?(i.push(`try{_result=${f}${E}(${D},${M},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),i.push("catch(_e){_result={ok:false,error:String(_e)};}")):(i.push(`try{_result=${f}${E}(${D},${M},$.engine);}`),i.push("catch(_e){_result={ok:false,error:String(_e)};}")),i.push("if(_result.ok){"),i.push("appliedCount++;counters.directivesApplied++;"),$&&i.push(`scope[${S}]=_result.data;`),i.push(`if(_result.halt)${at(n,o)}`),i.push("}else{"),i.push(`if(_result.halt)${ut(n,o)}`),k){i.push('scope.$exception=_result.error||"handler failed";');let P=p?"$.runner":"$.runnerSync";i.push(`const _cr=${f}${P}(${e}.catch,${M});`),i.push("appliedCount+=_cr.appliedCount;"),i.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),i.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 i.push(`errors.push({directiveIndex:${t},error:_result.error||"handler failed"});counters.errors++;`);i.push("}"),l&&(i.push("try{"),i.push(`const _ad=${v}_hookAfter(${D},_result,${M});`),i.push(`if(_ad==="abort")${me('"afterDirective"',n,o)}`),i.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook afterDirective: "+_e});counters.errors++;}`)),i.push("}");}function xt(r,e,t,n,s,i){let{L:o}=i,a=r.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=r.then;Array.isArray(u)&&u.length>0&&_e(u,`${e}.then`,n,s,i),o.push("}");let l=r.else;Array.isArray(l)&&l.length>0&&(o.push("else{"),_e(l,`${e}.else`,n,s,i),o.push("}")),c||o.push("}"),o.push("}");}function _e(r,e,t,n,s){let i=t!==-1;for(let o=0;o<r.length;o++){let a=r[o],c=`${e}[${o}]`,u=i?t:o,l=i?n:o+1;switch(a[s.typeField]){case "const":case "let":pt(s.L,a,c,u);break;case "return":vt(s.L,a,c,u,l,s.total);break;case "throw":ht(s.L,a,c,u,l,s.total);break;case "pause":yt(s.L,a,c,u,l,s.total);break;case "if":{let v=i?t:o,f=i?n:o+1;xt(a,c,u,v,f,s);break}default:gt(a,c,u,l,s);break}}}function De(r,e,t){for(let n of r){let s=n[e];if(s&&!j.has(s)&&t.add(s),s==="if"){let i=n.then;Array.isArray(i)&&i.length>0&&De(i,e,t);let o=n.else;Array.isArray(o)&&o.length>0&&De(o,e,t);}}}var $e=new Set;function Ae(r,e,t,n=$e,s,i=false,o=$e){let a=[],c=r.length,{filledNames:u,hasAnyAsync:l,asyncNames:y}=e,v=u.has("beforeDirective"),f=u.has("afterDirective"),p=u.has("onDirectivesComplete"),d=s!==void 0?s:ae(r,n,t),x=l||d,C=x?"await ":"",E=y.has("beforeDirective")?"await ":"",w=y.has("afterDirective")?"await ":"",$=y.has("onDirectivesComplete")?"await ":"",k=new Set;De(r,t,k);let S=new Map,I=0;for(let D of k)S.set(D,`_h${I++}`);lt(a,S,v,f),_e(r,"$.d",-1,0,{L:a,total:c,typeField:t,handlerVars:S,hasBefore:v,hasAfter:f,awBefore:E,awAfter:w,awHandler:C,actionIsAsync:x,actionIsInteractive:i,interactiveHandlerSet:o,blockCounter:{n:0}}),dt(a,c,p,$);let R=ft(a.join(`
|
|
4
|
+
`),x,i);return {fn:new Function("frame","scope","$",`"use strict";
|
|
5
|
+
return ${R};`),isAsync:x,isInteractive:i}}function ae(r,e,t){for(let n of r){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&&ae(o,e,t))return true;let a=n.else;if(Array.isArray(a)&&a.length>0&&ae(a,e,t))return true}let i=n.catch;if(Array.isArray(i)&&i.length>0&&ae(i,e,t))return true}return false}function Ce(r,e,t){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:r,...t}}function Me(r,e){return Ce(e,`Action not found: "${r}"`,{aborted:true,abortedBy:"action-not-found"})}function He(r,e,t){return Ce(t,`Max depth ${e} exceeded invoking "${r}"`,{aborted:true,abortedBy:"maxDepth"})}function Pe(r,e){return Ce(e,`Action "${r}" is private (sub-action). Can only be invoked from within its parent scope.`)}function ue(r,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:r,counters:e}}function mt(r){return typeof r=="object"&&r!==null&&"execute"in r}function Fe(r){let e=new Map;for(let[t,n]of r){let s=n.subDirectives;if(!s)continue;let i=Object.keys(s);if(i.length===0)continue;let o=null;for(let a=0;a<i.length;a++){let c=i[a];c!=="catch"&&s[c].graph!==false&&(o===null&&(o=[]),o.push(c));}o!==null&&e.set(t,o);}return e}function Ge(r){let e=new Map;for(let[t,n]of r){let s=n.subDirectives;if(!s)continue;let i=Object.keys(s);if(i.length===0)continue;let o=null;for(let a=0;a<i.length;a++){let c=i[a];c!=="catch"&&(o===null&&(o=[]),o.push(c));}o!==null&&e.set(t,o);}return e}function Be(r,e,t){if(!e)return t;let n=new Set(t);for(let[s,i]of r)i.executeInteractive!==void 0&&n.add(s);return n}function ne(r,e,t){let n=Object.create(null);for(let[s,i]of r){let o;t&&i.executeInteractive!==void 0?o=i.executeInteractive:e&&i.executeAsync!==void 0?o=i.executeAsync:o=i.execute,n[s]=o;}return n}function Ne(r){let e=Object.create(null),t=new Map;for(let n of Object.keys(r)){let s=r[n];mt(s)?(e[n]=s.execute,t.set(n,s)):(e[n]=s,t.set(n,{execute:s}));}return {handlers:e,definitions:t}}function je(r,e){if(r==="*")return true;if(!r.includes("*"))return r===e;let t=r.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}function Oe(r){return typeof r=="string"?{pattern:r}:r}function Le(r,e,t){let n=new Map;if(!e&&!t){for(let s of r)n.set(s,{status:"available"});return n}if(e){let s=e.map(Oe);for(let i of r){let o=s.some(a=>je(a.pattern,i));n.set(i,{status:o?"available":"denied"});}}else {let s=t.map(Oe);for(let i of r){let o=s.find(a=>je(a.pattern,i));o?n.set(i,{status:"denied",reason:o.reason,source:o.source}):n.set(i,{status:"available"});}}return n}function ze(r){let{typeField:e,asyncHandlerSet:t,interactiveHandlerSet:n,subDirectiveFieldsForGraph:s}=r,i=new Map,o=new Set,a=new Set,c=new Set,u=new Set;return {upsert(l,y,v){i.set(l,_t(y,e,s)),ie(y,t,e,s)?o.add(l):o.delete(l),v||se(y,n,e,s)?a.add(l):a.delete(l);},remove(l){i.delete(l),o.delete(l),a.delete(l);},recompute(){c=Ve(i,o),u=Ve(i,a);},isAsync(l){return c.has(l)},isInteractive(l){return u.has(l)},has(l){return i.has(l)}}}var le=new Map;function _t(r,e,t=le){let n=new Set;return re(r,e,t,n),n}function re(r,e,t,n){for(let s of r){let i=s[e];i==="action"&&typeof s.id=="string"&&n.add(s.id);let o=s.catch;if(Array.isArray(o)&&o.length>0&&re(o,e,t,n),i==="if"){let c=s.then;Array.isArray(c)&&c.length>0&&re(c,e,t,n);let u=s.else;Array.isArray(u)&&u.length>0&&re(u,e,t,n);continue}if(i===void 0)continue;let a=t.get(i);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];!Array.isArray(u)||u.length===0||re(u,e,t,n);}}}function ie(r,e,t,n=le){for(let s of r){let i=s[t];if(i!==void 0&&e.has(i))return true;let o=s.catch;if(Array.isArray(o)&&o.length>0&&ie(o,e,t,n))return true;if(i==="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(i===void 0)continue;let a=n.get(i);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 se(r,e,t,n=le){for(let s of r){let i=s[t];if(i==="pause"||i!==void 0&&e.has(i))return true;let o=s.catch;if(Array.isArray(o)&&o.length>0&&se(o,e,t,n))return true;if(i==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&se(c,e,t,n))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&se(u,e,t,n))return true;continue}if(i===void 0)continue;let a=n.get(i);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];if(!(!Array.isArray(u)||u.length===0)&&se(u,e,t,n))return true}}return false}function X(r,e,t=le){for(let n of r){let s=n[e];if(s==="pause")return true;let i=n.catch;if(Array.isArray(i)&&i.length>0&&X(i,e,t))return true;if(s==="if"){let a=n.then;if(Array.isArray(a)&&a.length>0&&X(a,e,t))return true;let c=n.else;if(Array.isArray(c)&&c.length>0&&X(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)&&X(c,e,t))return true}}return false}function Ve(r,e){let t=new Set(e),n=true;for(;n;){n=false;for(let[s,i]of r)if(!t.has(s)){for(let o of i)if(t.has(o)){t.add(s),n=true;break}}}return t}var de=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 i of n)this.actions.push(i);this.registered.push(...s);}};function Ke(r){for(let e of r)if(j.has(e))throw new Error(`Handler type "${e}" is reserved for engine-internal directives`)}function Ue(r,e){if(r&&e)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.")}function qe(r,e,t){if(r)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,i]of t)i.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 We(r){let e=new Set,t=new Set;for(let[n,s]of r)(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 Ye(r,e,t,n){let s=t?ne(r,true,false):e,i=n?ne(r,t,true):null;return {handlersAsync:s,handlersInteractive:i}}function Re(r,e){return e?{next:()=>Promise.resolve({value:r,done:true}),return:()=>Promise.resolve({value:r,done:true}),throw:s=>Promise.reject(s),[Symbol.asyncIterator](){return this}}:{next:()=>({value:r,done:true}),return:()=>({value:r,done:true}),throw:n=>{throw n},[Symbol.iterator](){return this}}}function Je(r,e,t,n,s,i){if(i){let c=r;return {async next(l){let y=await c.next(l);if(y.done){let v=y.value;if(s!==null){let f=s(e,t,v,n);f!==void 0&&(v=f);}return {value:v,done:true}}return {value:y.value,done:false}},async return(){let l=await c.return(void 0),y=l.value;if(l.done&&s!==null){let v=s(e,t,y,n);v!==void 0&&(y=v);}return {value:y,done:true}},async throw(l){let y=await c.throw(l);if(y.done){let v=y.value;if(s!==null){let f=s(e,t,v,n);f!==void 0&&(v=f);}return {value:v,done:true}}return {value:y.value,done:false}},[Symbol.asyncIterator](){return this}}}let o=r;return {next(c){let u=o.next(c);if(u.done){let l=u.value;if(s!==null){let y=s(e,t,l,n);y!==void 0&&(l=y);}return {value:l,done:true}}return {value:u.value,done:false}},return(){let c=o.return(void 0),u=c.value;if(c.done&&s!==null){let l=s(e,t,u,n);l!==void 0&&(u=l);}return {value:u,done:true}},throw(c){let u=o.throw(c);if(u.done){let l=u.value;if(s!==null){let y=s(e,t,l,n);y!==void 0&&(l=y);}return {value:l,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}var kt=8,Et="type",ke={maxDepth:10,maxRules:1e4,maxDirectives:1e5},Ee=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_handlersAsync;_handlersInteractive;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_autoStepDirectives;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new Z;_batch=new de;_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??kt,this._typeField=e.typeField??Et,this._limits={maxDepth:e.limits?.maxDepth??ke.maxDepth,maxRules:e.limits?.maxRules??ke.maxRules,maxDirectives:e.limits?.maxDirectives??ke.maxDirectives};let{handlers:t,definitions:n}=Ne(e.handlers);Ke(Object.keys(e.handlers)),Ue(e.allowedDirectives,e.blockedDirectives),this._handlers=t,this._definitions=n,this._directivePermissions=Le(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:i}=We(this._definitions);this._asyncHandlerSet=s,this._interactiveHandlerSet=i,this._isInteractive=e.interactive!==void 0,this._autoStepDirectives=this._isInteractive&&e.interactive?.autoStepDirectives===true,qe(this._isInteractive,i,this._definitions),this._isAsync=this._directiveAnalysis.hasAnyAsync||s.size>0;let{handlersAsync:o,handlersInteractive:a}=Ye(this._definitions,this._handlers,this._isAsync,this._isInteractive);this._handlersAsync=o,this._handlersInteractive=a;let c=Fe(this._definitions);this._subDirectiveFieldsForGraph=c,this._subDirectiveFieldsAll=Ge(this._definitions),this._miniGraph=ze({typeField:this._typeField,asyncHandlerSet:s,interactiveHandlerSet:i,subDirectiveFieldsForGraph:c}),this._engineRef=this._buildEngineRef();let u=ce(this._directiveAnalysis,false);this._directiveRunner=this._buildDirectiveRunner(),this._directiveRunnerSync=this._buildDirectiveRunnerSync(u);let l=this._buildExecutors(u);this._directiveExecutor=l.directiveExecutor,this._mode=l.mode,this._interactiveExecutor=l.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?ce(this._directiveAnalysis,true):e,n=this._requestedMode==="jit"?"jit":"interpret",s=this._isInteractive?this._isAsync?xe(this._directiveAnalysis,true):xe(this._directiveAnalysis,false):null;return {directiveExecutor:t,mode:n,interactiveExecutor:s}}register(e){let t=[],n=[],s=[],i=[];for(let c of e){if(!c.id){n.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&X(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=Ie(c,this._handlers,this._definitions,this._typeField);if(u.length>0){for(let l of u)n.push({actionId:c.id,error:l});continue}i.push(c);}for(let c of i){let u=N(c.directives,this._typeField,this._subDirectiveFieldsAll),l={definition:c,directives:u,compiled:null,invokeCount:0};this._registry.set(c.id,l),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,i,t),{registered:t,errors:n,warnings:s};let o=t;if(i.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=i.filter(l=>c.has(l.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 i of this._registry.keys())i.startsWith(n)&&(this._registry.delete(i),this._registeredIds.delete(i),this._miniGraph.remove(i),s.push(i));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(),i=core.createRootFrame(s,this._limits);return this._invokeInternal(e,t,i)}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(),i=core.createRootFrame(s,this._limits);return this._invokeInternalAsync(e,t,i)}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),i=this._batch.actions.filter(o=>s.has(o.id));this._emitter.emit("register",{actions:i,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(),i=core.createRootFrame(s,this._limits);return this._invokeInteractiveInternal(e,t,i)}_invokeInteractiveInternal(e,t,n){let s=this._prepareInvoke(e,t,n);if("success"in s)return Re(s,this._isAsync);let{stored:i,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return Re(ue(u.data,o.counters),this._isAsync)}let c;if(i.compiled&&i.compiled.isInteractive&&!this._autoStepDirectives)c=i.compiled.fn(o,o.scope,i.compiled.$);else {let u=this._interactiveExecutor;c=u(i.directives,o,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives,this._autoStepDirectives);}return Je(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,this._autoStepDirectives)}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:i,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return ue(u.data,o.counters)}let c;if(i.compiled?c=i.compiled.fn(o,a,i.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(i.compiled=this._compileAction(e,i.directives),c=i.compiled.fn(o,a,i.compiled.$)):(c=this._directiveRunner(i.directives,o),this._maybeAutoPromote(i)),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:i,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return ue(u.data,o.counters)}let c;if(i.compiled?c=await i.compiled.fn(o,a,i.compiled.$):(c=await this._directiveRunner(i.directives,o),this._maybeAutoPromote(i)),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 Me(e,n.counters);if(e.includes("/")&&!this._isAccessible(e,n))return Pe(e,n.counters);if(n.depth>=n.limits.maxDepth)return He(e,n.limits.maxDepth,n.counters);let i=Object.create(n.scope);t&&Object.assign(i,t);let o=n.child("action:"+e,0,e).withScope(i);return {stored:s,childFrame:o,childScope:i}}_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),i=Be(this._definitions,s,this._interactiveHandlerSet),{fn:o,isAsync:a,isInteractive:c}=Ae(t,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,n,s,i),u=ne(this._definitions,a,c),l={d:t,h:u,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:o,$:l,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),i=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=we(c.directives,this._typeField,this._definitions,this._subDirectiveFieldsForGraph,this._interactiveHandlerSet,y=>this._miniGraph.isInteractive(y),core.isGeneratorFunction);if(u.size===0)continue;let l=s.has(a);for(let y of u){let v=`Action "${a}" is transitively interactive but handler "${y}" has no executeInteractive variant (and execute is not a generator function, and interactive flag is not set)`;l?(t.push({actionId:a,error:v,code:"MISSING_INTERACTIVE_VARIANT"}),i.add(a)):n.push({actionId:a,code:"MISSING_INTERACTIVE_VARIANT",message:v});}}if(i.size>0){for(let a of i)this._registry.delete(a),this._registeredIds.delete(a),this._miniGraph.remove(a);this._miniGraph.recompute();}return {validRegistered:e.filter(a=>!i.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 It(r){return new Ee(r)}exports.RESERVED_TYPES=j;exports.SimpleEmitter=Z;exports.buildActionExecutor=Ae;exports.createActionEngine=It;exports.createDirectiveInterpreter=ce;exports.drainAsync=Xe;exports.drainSync=Qe;exports.normalizeDirectives=N;exports.replayResponder=Ze;
|
package/dist/index.d.cts
CHANGED
|
@@ -330,6 +330,35 @@ type DirectivePermissionEntry = string | DirectivePermissionConfig;
|
|
|
330
330
|
* - diretiva `type: "pause"` → erro no register
|
|
331
331
|
*/
|
|
332
332
|
interface InteractiveConfig {
|
|
333
|
+
/**
|
|
334
|
+
* Quando true, o interpreter generator emite `PauseEvent { source: "step" }`
|
|
335
|
+
* antes de cada directive durante uma invocação interactive
|
|
336
|
+
* (`engine.invokeInteractive`). Habilita pause-point universal para
|
|
337
|
+
* debuggers, profilers, time-travel UIs e dry-run — sem precisar
|
|
338
|
+
* instrumentar definitions com `{ type: "pause" }`.
|
|
339
|
+
*
|
|
340
|
+
* **Interpret-only.** JIT permanece atômico por design. Engine em
|
|
341
|
+
* `mode: "jit"` com `autoStepDirectives: true` faz fallback pro
|
|
342
|
+
* interpreter generator durante invocações interactive das actions
|
|
343
|
+
* transitivamente marcadas. Invocações regulares (`invoke`/`invokeAsync`)
|
|
344
|
+
* e actions não-interactive continuam usando JIT normalmente.
|
|
345
|
+
*
|
|
346
|
+
* **Drive value de `session.next(value)` em step events:**
|
|
347
|
+
* - omitido → continua, executa a directive normalmente
|
|
348
|
+
* - `{ skip: true }` → pula a directive (incrementa skippedCount)
|
|
349
|
+
* - `{ replaceWith: directive }` → substitui antes de executar
|
|
350
|
+
* - `{ abort: true }` → aborta com `abortedBy: "step"`
|
|
351
|
+
*
|
|
352
|
+
* **Custos:**
|
|
353
|
+
* - Sem flag: zero impacto.
|
|
354
|
+
* - Com flag: 1 yield + 1 PauseEvent alloc por directive executada
|
|
355
|
+
* (proporcional ao tamanho da action — aceitável em debug).
|
|
356
|
+
* - Fallback JIT→interpreter: ~10× mais lento que JIT compilado
|
|
357
|
+
* (aceitável — debug é interação humana).
|
|
358
|
+
*
|
|
359
|
+
* Default: false.
|
|
360
|
+
*/
|
|
361
|
+
readonly autoStepDirectives?: boolean;
|
|
333
362
|
readonly [key: string]: unknown;
|
|
334
363
|
}
|
|
335
364
|
/**
|
|
@@ -339,9 +368,13 @@ interface InteractiveConfig {
|
|
|
339
368
|
* opaco (handler controla o protocol).
|
|
340
369
|
* - `source: "pause"` — diretiva `type:"pause"` engine-level. `payload`
|
|
341
370
|
* contém `{ message?: unknown }` extraído da diretiva.
|
|
371
|
+
* - `source: "step"` — yield automático antes de cada directive
|
|
372
|
+
* (`interactive.autoStepDirectives: true`). `payload` é `undefined`
|
|
373
|
+
* (sinalização passiva). Consumer drena via `session.next(cmd?)` com
|
|
374
|
+
* `{ skip }`, `{ replaceWith }`, `{ abort }` ou nada (continua).
|
|
342
375
|
*/
|
|
343
376
|
interface PauseEvent {
|
|
344
|
-
readonly source: "handler" | "pause";
|
|
377
|
+
readonly source: "handler" | "pause" | "step";
|
|
345
378
|
readonly directive: Directive;
|
|
346
379
|
readonly frame: ExecutionFrame<unknown>;
|
|
347
380
|
readonly index: number;
|
|
@@ -604,6 +637,12 @@ declare function drainAsync(session: AsyncInteractiveSession, responder?: Respon
|
|
|
604
637
|
*
|
|
605
638
|
* Se o iterator pausar mais vezes que a lista tem respostas, retorna
|
|
606
639
|
* `undefined` pras pausas extras (sem erro).
|
|
640
|
+
*
|
|
641
|
+
* **Step events não consomem a queue.** Quando `interactive.autoStepDirectives`
|
|
642
|
+
* está ativo, o engine emite `PauseEvent { source: "step" }` antes de cada
|
|
643
|
+
* directive. Esses yields são silenciosos em play mode — `replayResponder`
|
|
644
|
+
* retorna `undefined` sem avançar a fila, preservando a ordem das respostas
|
|
645
|
+
* pré-programadas pros yields semânticos (`pause` / `handler`).
|
|
607
646
|
*/
|
|
608
647
|
declare function replayResponder(responses: readonly unknown[]): Responder;
|
|
609
648
|
|
|
@@ -658,22 +697,6 @@ declare function createDirectiveInterpreter<TCtx>(analysis: SlotAnalysis, isAsyn
|
|
|
658
697
|
|
|
659
698
|
declare function createActionEngine<TCtx>(config: IActionEngineConfig<TCtx>): IActionEngine<TCtx>;
|
|
660
699
|
|
|
661
|
-
type RuntimeDirectiveExecutorFn = (directives: readonly unknown[], frame: unknown, handlers: unknown, directiveHooks: unknown, typeField: string, engine: unknown, maxDirectives: number) => unknown;
|
|
662
|
-
interface GeneratedDirectiveExecutor {
|
|
663
|
-
fn: RuntimeDirectiveExecutorFn;
|
|
664
|
-
isAsync: boolean;
|
|
665
|
-
}
|
|
666
|
-
/**
|
|
667
|
-
* Compila um executor genérico de diretivas via `new Function`.
|
|
668
|
-
*
|
|
669
|
-
* @param analysis — slot analysis dos directive hooks (filled/async).
|
|
670
|
-
* @param isAsync — se true, gera função `async ()` e prefixa `await` na chamada
|
|
671
|
-
* do handler. Default: `analysis.hasAnyAsync` (preserva o comportamento legado
|
|
672
|
-
* pra callers que não conhecem handler async). O engine sempre passa explícito,
|
|
673
|
-
* computado a partir de `directiveAnalysis.hasAnyAsync || asyncHandlerSet.size > 0`.
|
|
674
|
-
*/
|
|
675
|
-
declare function buildDirectiveExecutor(analysis: SlotAnalysis, isAsync?: boolean): GeneratedDirectiveExecutor;
|
|
676
|
-
|
|
677
700
|
/**
|
|
678
701
|
* Assinatura da função compilada pelo JIT per-action.
|
|
679
702
|
*
|
|
@@ -725,4 +748,4 @@ interface GeneratedActionExecutor {
|
|
|
725
748
|
*/
|
|
726
749
|
declare function buildActionExecutor(directives: readonly Directive[], analysis: SlotAnalysis, typeField: string, asyncHandlerSet?: ReadonlySet<string>, actionUsesAsyncOverride?: boolean, actionIsInteractive?: boolean, interactiveHandlerSet?: ReadonlySet<string>): GeneratedActionExecutor;
|
|
727
750
|
|
|
728
|
-
export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedActionExecutorFn, type
|
|
751
|
+
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
|
@@ -330,6 +330,35 @@ type DirectivePermissionEntry = string | DirectivePermissionConfig;
|
|
|
330
330
|
* - diretiva `type: "pause"` → erro no register
|
|
331
331
|
*/
|
|
332
332
|
interface InteractiveConfig {
|
|
333
|
+
/**
|
|
334
|
+
* Quando true, o interpreter generator emite `PauseEvent { source: "step" }`
|
|
335
|
+
* antes de cada directive durante uma invocação interactive
|
|
336
|
+
* (`engine.invokeInteractive`). Habilita pause-point universal para
|
|
337
|
+
* debuggers, profilers, time-travel UIs e dry-run — sem precisar
|
|
338
|
+
* instrumentar definitions com `{ type: "pause" }`.
|
|
339
|
+
*
|
|
340
|
+
* **Interpret-only.** JIT permanece atômico por design. Engine em
|
|
341
|
+
* `mode: "jit"` com `autoStepDirectives: true` faz fallback pro
|
|
342
|
+
* interpreter generator durante invocações interactive das actions
|
|
343
|
+
* transitivamente marcadas. Invocações regulares (`invoke`/`invokeAsync`)
|
|
344
|
+
* e actions não-interactive continuam usando JIT normalmente.
|
|
345
|
+
*
|
|
346
|
+
* **Drive value de `session.next(value)` em step events:**
|
|
347
|
+
* - omitido → continua, executa a directive normalmente
|
|
348
|
+
* - `{ skip: true }` → pula a directive (incrementa skippedCount)
|
|
349
|
+
* - `{ replaceWith: directive }` → substitui antes de executar
|
|
350
|
+
* - `{ abort: true }` → aborta com `abortedBy: "step"`
|
|
351
|
+
*
|
|
352
|
+
* **Custos:**
|
|
353
|
+
* - Sem flag: zero impacto.
|
|
354
|
+
* - Com flag: 1 yield + 1 PauseEvent alloc por directive executada
|
|
355
|
+
* (proporcional ao tamanho da action — aceitável em debug).
|
|
356
|
+
* - Fallback JIT→interpreter: ~10× mais lento que JIT compilado
|
|
357
|
+
* (aceitável — debug é interação humana).
|
|
358
|
+
*
|
|
359
|
+
* Default: false.
|
|
360
|
+
*/
|
|
361
|
+
readonly autoStepDirectives?: boolean;
|
|
333
362
|
readonly [key: string]: unknown;
|
|
334
363
|
}
|
|
335
364
|
/**
|
|
@@ -339,9 +368,13 @@ interface InteractiveConfig {
|
|
|
339
368
|
* opaco (handler controla o protocol).
|
|
340
369
|
* - `source: "pause"` — diretiva `type:"pause"` engine-level. `payload`
|
|
341
370
|
* contém `{ message?: unknown }` extraído da diretiva.
|
|
371
|
+
* - `source: "step"` — yield automático antes de cada directive
|
|
372
|
+
* (`interactive.autoStepDirectives: true`). `payload` é `undefined`
|
|
373
|
+
* (sinalização passiva). Consumer drena via `session.next(cmd?)` com
|
|
374
|
+
* `{ skip }`, `{ replaceWith }`, `{ abort }` ou nada (continua).
|
|
342
375
|
*/
|
|
343
376
|
interface PauseEvent {
|
|
344
|
-
readonly source: "handler" | "pause";
|
|
377
|
+
readonly source: "handler" | "pause" | "step";
|
|
345
378
|
readonly directive: Directive;
|
|
346
379
|
readonly frame: ExecutionFrame<unknown>;
|
|
347
380
|
readonly index: number;
|
|
@@ -604,6 +637,12 @@ declare function drainAsync(session: AsyncInteractiveSession, responder?: Respon
|
|
|
604
637
|
*
|
|
605
638
|
* Se o iterator pausar mais vezes que a lista tem respostas, retorna
|
|
606
639
|
* `undefined` pras pausas extras (sem erro).
|
|
640
|
+
*
|
|
641
|
+
* **Step events não consomem a queue.** Quando `interactive.autoStepDirectives`
|
|
642
|
+
* está ativo, o engine emite `PauseEvent { source: "step" }` antes de cada
|
|
643
|
+
* directive. Esses yields são silenciosos em play mode — `replayResponder`
|
|
644
|
+
* retorna `undefined` sem avançar a fila, preservando a ordem das respostas
|
|
645
|
+
* pré-programadas pros yields semânticos (`pause` / `handler`).
|
|
607
646
|
*/
|
|
608
647
|
declare function replayResponder(responses: readonly unknown[]): Responder;
|
|
609
648
|
|
|
@@ -658,22 +697,6 @@ declare function createDirectiveInterpreter<TCtx>(analysis: SlotAnalysis, isAsyn
|
|
|
658
697
|
|
|
659
698
|
declare function createActionEngine<TCtx>(config: IActionEngineConfig<TCtx>): IActionEngine<TCtx>;
|
|
660
699
|
|
|
661
|
-
type RuntimeDirectiveExecutorFn = (directives: readonly unknown[], frame: unknown, handlers: unknown, directiveHooks: unknown, typeField: string, engine: unknown, maxDirectives: number) => unknown;
|
|
662
|
-
interface GeneratedDirectiveExecutor {
|
|
663
|
-
fn: RuntimeDirectiveExecutorFn;
|
|
664
|
-
isAsync: boolean;
|
|
665
|
-
}
|
|
666
|
-
/**
|
|
667
|
-
* Compila um executor genérico de diretivas via `new Function`.
|
|
668
|
-
*
|
|
669
|
-
* @param analysis — slot analysis dos directive hooks (filled/async).
|
|
670
|
-
* @param isAsync — se true, gera função `async ()` e prefixa `await` na chamada
|
|
671
|
-
* do handler. Default: `analysis.hasAnyAsync` (preserva o comportamento legado
|
|
672
|
-
* pra callers que não conhecem handler async). O engine sempre passa explícito,
|
|
673
|
-
* computado a partir de `directiveAnalysis.hasAnyAsync || asyncHandlerSet.size > 0`.
|
|
674
|
-
*/
|
|
675
|
-
declare function buildDirectiveExecutor(analysis: SlotAnalysis, isAsync?: boolean): GeneratedDirectiveExecutor;
|
|
676
|
-
|
|
677
700
|
/**
|
|
678
701
|
* Assinatura da função compilada pelo JIT per-action.
|
|
679
702
|
*
|
|
@@ -725,4 +748,4 @@ interface GeneratedActionExecutor {
|
|
|
725
748
|
*/
|
|
726
749
|
declare function buildActionExecutor(directives: readonly Directive[], analysis: SlotAnalysis, typeField: string, asyncHandlerSet?: ReadonlySet<string>, actionUsesAsyncOverride?: boolean, actionIsInteractive?: boolean, interactiveHandlerSet?: ReadonlySet<string>): GeneratedActionExecutor;
|
|
727
750
|
|
|
728
|
-
export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedActionExecutorFn, type
|
|
751
|
+
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 {analyzeSlots,DIRECTIVE_SLOT_NAMES,createRootFrame,processIntercept,Intercept,isAsyncFunction,isGeneratorFunction}from'@statedelta-actions/core';function We(i,e){let t;for(;;){let r=i.next(t);if(r.done)return r.value;t=e?e(r.value):void 0;}}async function Je(i,e){let t;for(;;){let r=await i.next(t);if(r.done)return r.value;t=e?await e(r.value):void 0;}}function Ye(i){let e=0;return ()=>{if(!(e>=i.length))return i[e++]}}var X=class{_listeners=new Map;on(e,t){let r=this._listeners.get(e);r||(r=new Set,this._listeners.set(e,r)),r.add(t);let o=false;return ()=>{o||(o=true,r.delete(t),r.size===0&&this._listeners.delete(e));}}once(e,t){let r=this.on(e,o=>{r(),t(o);});return r}emit(e,t){let r=this._listeners.get(e);if(!r||r.size===0)return;let o=[...r];for(let n=0;n<o.length;n++)try{o[n](t);}catch(s){console.error(`[SimpleEmitter] Listener error on "${e}":`,s);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let t=this._listeners.get(e);return t!==void 0&&t.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var N=new Set(["const","let","return","throw","pause","if"]);function ke(i,e,t,r){let o=[];return se(i.directives,e,t,r,"directive",o,i.id),o}function se(i,e,t,r,o,n,s){for(let a=0;a<i.length;a++){let c=i[a],u=c[r],d=`${o}[${a}]`;if(!u){n.push(`${d}: missing type field "${r}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&n.push(`${d}: "if" requires cond as function or boolean`);let A=c.then;Array.isArray(A)?se(A,e,t,r,`${d}.then`,n,s):n.push(`${d}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?se(D,e,t,r,`${d}.else`,n,s):n.push(`${d}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${s}" ${d}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let h=t.get(u);if(h?.validate)try{let g=h.validate(c);g&&!g.valid&&n.push(`${d}: ${g.error??"validation failed"}`);}catch(g){n.push(`${d}: validate threw: ${g}`);}let f=c.catch;if(f&&Array.isArray(f))for(let g=0;g<f.length;g++){let D=f[g][r];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${s}" ${d}.catch[${g}]: no handler registered for type "${D}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let p=h?.subDirectives;if(p===void 0)continue;let l=Object.keys(p);for(let g=0;g<l.length;g++){let A=l[g];if(A==="catch")continue;let D=c[A];if(D===void 0){if(p[A].required)throw new Error(`Action "${s}" ${d}: handler "${u}" requires sub-directives field "${A}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${s}" ${d}.${A}: must be an array of directives`);se(D,e,t,r,`${d}.${A}`,n,s);}}}var Qe=new Map;function B(i,e,t=Qe){let r=i.length,o=new Array(r);for(let n=0;n<r;n++){let s=i[n],a=s[e],c=s,u=false,d=s.catch;if(Array.isArray(d)&&d.length>0&&(c={...c,catch:B(d,e,t)},u=true),a==="if"){let h=s.then;Array.isArray(h)&&h.length>0&&(c={...c,then:B(h,e,t)},u=true);let f=s.else;Array.isArray(f)&&f.length>0&&(c={...c,else:B(f,e,t)},u=true);}else if(a!==void 0){let h=t.get(a);if(h!==void 0)for(let f=0;f<h.length;f++){let p=h[f],l=s[p];!Array.isArray(l)||l.length===0||(c={...c,[p]:B(l,e,t)},u=true);}}o[n]=u?c:s;}return o}function Ee(i,e,t,r,o,n,s){let a=new Set;return Z(i,e,t,r,o,n,s,a),a}function Z(i,e,t,r,o,n,s,a){for(let c of i){let u=c[e];if(u!==void 0){let f=t.get(u);if(f!==void 0&&f.subDirectives!==void 0){let p=r.get(u);if(p!==void 0){let l=false;for(let g=0;g<p.length;g++){let A=c[p[g]];if(!(!Array.isArray(A)||A.length===0)&&ee(A,e,r,o,n)){l=true;break}}l&&(f.executeInteractive!==void 0||f.interactive===true||s(f.execute)||a.add(u));}}}let d=c.catch;if(Array.isArray(d)&&d.length>0&&Z(d,e,t,r,o,n,s,a),u==="if"){let f=c.then;Array.isArray(f)&&f.length>0&&Z(f,e,t,r,o,n,s,a);let p=c.else;Array.isArray(p)&&p.length>0&&Z(p,e,t,r,o,n,s,a);continue}if(u===void 0)continue;let h=r.get(u);if(h!==void 0)for(let f=0;f<h.length;f++){let p=c[h[f]];!Array.isArray(p)||p.length===0||Z(p,e,t,r,o,n,s,a);}}}function ee(i,e,t,r,o){for(let n of i){let s=n[e];if(s==="pause"||s!==void 0&&r.has(s)||s==="action"&&typeof n.id=="string"&&o(n.id))return true;let a=n.catch;if(Array.isArray(a)&&a.length>0&&ee(a,e,t,r,o))return true;if(s==="if"){let u=n.then;if(Array.isArray(u)&&u.length>0&&ee(u,e,t,r,o))return true;let d=n.else;if(Array.isArray(d)&&d.length>0&&ee(d,e,t,r,o))return true;continue}if(s===void 0)continue;let c=t.get(s);if(c!==void 0)for(let u=0;u<c.length;u++){let d=n[c[u]];if(!(!Array.isArray(d)||d.length===0)&&ee(d,e,t,r,o))return true}}return false}function j(i,e,t,r,o,n){let s=i.name;if(typeof i.resolve=="function")try{t[s]=i.resolve(e,t).value;}catch(a){r.push({directiveIndex:o,error:`Binding resolve: ${a}`}),n.errors++;}else t[s]=i.value;}function L(i,e,t,r,o,n){let s=i.value;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="value"in a?a.value:"return"in a?a.return:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function O(i,e,t,r,o,n){let s=i.message;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="message"in a?a.message:"throw"in a?a.throw:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function V(i,e,t,r,o,n,s,a,c,u,d){let h;try{let p=i.cond;h=typeof p=="function"?!!p(e,t):!!p;}catch(p){c.push({directiveIndex:u,error:`if cond: ${p}`}),d.errors++;return}let f=h?i.then:i.else;if(Array.isArray(f)&&f.length>0){let p=Math.min(f.length,a),l=o?n:s;r.push({dirs:f,i:0,len:p,topLevelIfIndex:l});}}function z(i,e,t){let r=processIntercept(i,"beforeDirective");if(r.action===Intercept.SKIP)return {action:"skip"};if(r.action===Intercept.ABORT)return {action:"abort",reason:r.abortReason};let o=t,n=e;return r.ctx!==void 0&&(o=t.withCtx(r.ctx)),r.directive!==void 0&&(n=r.directive),{action:"continue",directive:n,dFrame:o}}function G(i,e,t,r,o){i.push({directiveIndex:t,error:`Hook ${r}: ${o}`}),e.errors++;}function S(i,e,t,r,o){return {success:false,aborted:true,abortedBy:i,appliedCount:e.appliedCount,skippedCount:e.skippedCount,errors:e.errors,processedCount:t,totalCount:r,counters:e.counters,data:o}}function K(i,e,t,r){return {success:true,aborted:true,abortedBy:"halt",appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function U(i,e,t,r){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function q(i,e){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:e,counters:i.counters}}function W(i,e,t,r){return {success:r.success,aborted:true,abortedBy:r.abortedBy,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r.data}}function J(i,e,t,r,o){if(typeof i.resolve!="function")return i;try{let n=i.resolve(e.ctx,e.scope);return {...i,...n}}catch(n){return t.push({directiveIndex:r,error:`Directive resolve: ${n}`}),o.errors++,null}}function Y(i,e){return [{dirs:i,i:0,len:e,topLevelIfIndex:-1}]}function Ze(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function et(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=await F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function oe(i,e){return e?et(i):Ze(i)}function de(i){if(i===null||typeof i!="object")return null;if(typeof i.next=="function")return i;let e=i.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function fe(i,e,t){return {source:"pause",directive:i,frame:e,index:t,payload:{message:i.message}}}function pe(i){return i===false||i==="abort"||i==="cancel"}function ve(i,e,t,r){r.directivesApplied++,typeof i.as=="string"&&e!==void 0&&(t[i.as]=e);}function tt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function rt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=await F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function he(i,e){return e?rt(i):tt(i)}function ye(i,e=i.hasAnyAsync){let{filledNames:t}=i,r=d=>t.has(d),o=d=>i.asyncNames.has(d)?"await ":"",n=e?"await ":"",s=[];for(let d of t)s.push(`const ${d} = directiveHooks.${d};`);s.push("const len = Math.min(directives.length, maxDirectives);"),s.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),s.push("const counters = frame.counters;"),s.push("for (let i = 0; i < len; i++) {"),s.push(" let directive = directives[i];"),r("beforeDirective")?(s.push(" let _df = frame;"),s.push(" try {"),s.push(` const _bd = ${o("beforeDirective")}beforeDirective(directive, frame);`),s.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),s.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if (typeof _bd === "object" && _bd !== null) {'),s.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),s.push(' if ("directive" in _bd) directive = _bd.directive;'),s.push(" }"),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):s.push(" const _df = frame;"),s.push(' if (typeof directive.resolve === "function") {'),s.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),s.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),s.push(" }"),s.push(" const _type = directive[typeField];"),s.push(" const _handler = _type ? handlers[_type] : undefined;"),s.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),s.push(" let _result;"),s.push(` try { _result = ${n}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),s.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),s.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),r("afterDirective")&&(s.push(" try {"),s.push(` const _ad = ${o("afterDirective")}afterDirective(directive, _result, _df);`),s.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),s.push("}"),s.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),r("onDirectivesComplete")&&s.push(`try { ${o("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),s.push("return _finalResult;");let a=s.join(`
|
|
2
|
-
|
|
3
|
-
return (${
|
|
4
|
-
$
|
|
5
|
-
})();`),isAsync:e}}function ge(i,e,t){return `return{success:false,aborted:true,abortedBy:${i},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${t},counters};`}function nt(i,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function it(i,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function st(i,e,t,r){i.push("const counters=frame.counters;"),i.push("const ctx=frame.ctx;"),i.push("const errors=[];"),i.push("let appliedCount=0;"),i.push("let skippedCount=0;");for(let[o,n]of e)i.push(`const ${n}=$.h[${JSON.stringify(o)}];`);t&&i.push("const _hookBefore=$.hooks.beforeDirective;"),r&&i.push("const _hookAfter=$.hooks.afterDirective;");}function ot(i,e,t,r){i.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${e},totalCount:${e},counters};`),t&&i.push(`try{${r}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),i.push("return _finalResult;");}function ct(i,e,t){let r=`{
|
|
6
|
-
${i}
|
|
7
|
-
}`;return t?`(${e?"async function*()":"function*()"}${r})()`:`(${e?"async ()=>":"()=>"}${r})()`}function at(i,e,t,r){let o=JSON.stringify(e.name);typeof e.resolve=="function"?(i.push("try{"),i.push(`scope[${o}]=${t}.resolve(ctx,scope).value;`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Binding resolve: "+_e});counters.errors++;}`)):i.push(`scope[${o}]=${t}.value;`);}function ut(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${t}.value};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.value};`);}function lt(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${t}.message};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.message};`);}function dt(i,e,t,r,o,n){let s=typeof e.as=="string",a=s?JSON.stringify(e.as):"";i.push(`{const _ack=yield{source:"pause",directive:${t},frame,index:${r},payload:{message:${t}.message}};`),i.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:_ack};`),i.push("appliedCount++;counters.directivesApplied++;"),s&&i.push(`if(_ack!==undefined)scope[${a}]=_ack;`),i.push("}");}function ft(i,e,t,r,o){let{L:n,total:s,typeField:a,handlerVars:c,hasBefore:u,hasAfter:d,awBefore:h,awAfter:f,awHandler:p,actionIsAsync:l,actionIsInteractive:g,interactiveHandlerSet:A}=o,D=i[a],R=c.get(D),P=typeof i.resolve=="function",b=typeof i.as=="string",I=Array.isArray(i.catch)&&i.catch.length>0,T=b?JSON.stringify(i.as):"",_=g&&A.has(D),C=o.blockCounter.n++;n.push(`_b${C}:{`);let k=u||P,x=u;k&&n.push(`let _dir=${e};`),x&&n.push("let _df=frame;"),u&&(n.push("try{"),n.push(`const _bd=${h}_hookBefore(${e},frame);`),n.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${C};}`),n.push(`if(_bd==="abort")${ge('"beforeDirective"',r-1,s)}`),n.push('if(typeof _bd==="object"&&_bd!==null){'),n.push(`if("abort" in _bd)${ge("_bd.abort",r-1,s)}`),n.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),n.push('if("directive" in _bd)_dir=_bd.directive;'),n.push("}"),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(n.push('if(typeof _dir.resolve==="function"){'),n.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}}`)):P&&(n.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}`));let E=k?"_dir":e,H=x?"_df":"frame";if(n.push("let _result;"),_?(n.push(`try{_result=yield* ${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(n.push(`try{_result=${p}${R}(${E},${H},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):(n.push(`try{_result=${p}${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")),n.push("if(_result.ok){"),n.push("appliedCount++;counters.directivesApplied++;"),b&&n.push(`scope[${T}]=_result.data;`),n.push(`if(_result.halt)${nt(r,s)}`),n.push("}else{"),n.push(`if(_result.halt)${it(r,s)}`),I){n.push('scope.$exception=_result.error||"handler failed";');let M=l?"$.runner":"$.runnerSync";n.push(`const _cr=${p}${M}(${e}.catch,${H});`),n.push("appliedCount+=_cr.appliedCount;"),n.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),n.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${r},totalCount:${s},counters,data:_cr.data};`);}else n.push(`errors.push({directiveIndex:${t},error:_result.error||"handler failed"});counters.errors++;`);n.push("}"),d&&(n.push("try{"),n.push(`const _ad=${f}_hookAfter(${E},_result,${H});`),n.push(`if(_ad==="abort")${ge('"afterDirective"',r,s)}`),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook afterDirective: "+_e});counters.errors++;}`)),n.push("}");}function pt(i,e,t,r,o,n){let{L:s}=n,a=i.cond,c=typeof a=="boolean";s.push("{"),c?s.push(`if(${a?"true":"false"}){`):(s.push("let _cond=false,_condOk=true;"),s.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),s.push(`catch(_e){errors.push({directiveIndex:${t},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),s.push("if(_condOk){"),s.push("if(_cond){"));let u=i.then;Array.isArray(u)&&u.length>0&&xe(u,`${e}.then`,r,o,n),s.push("}");let d=i.else;Array.isArray(d)&&d.length>0&&(s.push("else{"),xe(d,`${e}.else`,r,o,n),s.push("}")),c||s.push("}"),s.push("}");}function xe(i,e,t,r,o){let n=t!==-1;for(let s=0;s<i.length;s++){let a=i[s],c=`${e}[${s}]`,u=n?t:s,d=n?r:s+1;switch(a[o.typeField]){case "const":case "let":at(o.L,a,c,u);break;case "return":ut(o.L,a,c,u,d,o.total);break;case "throw":lt(o.L,a,c,u,d,o.total);break;case "pause":dt(o.L,a,c,u,d,o.total);break;case "if":{let f=n?t:s,p=n?r:s+1;pt(a,c,u,f,p,o);break}default:ft(a,c,u,d,o);break}}}function me(i,e,t){for(let r of i){let o=r[e];if(o&&!N.has(o)&&t.add(o),o==="if"){let n=r.then;Array.isArray(n)&&n.length>0&&me(n,e,t);let s=r.else;Array.isArray(s)&&s.length>0&&me(s,e,t);}}}var we=new Set;function _e(i,e,t,r=we,o,n=false,s=we){let a=[],c=i.length,{filledNames:u,hasAnyAsync:d,asyncNames:h}=e,f=u.has("beforeDirective"),p=u.has("afterDirective"),l=u.has("onDirectivesComplete"),g=o!==void 0?o:ce(i,r,t),A=d||g,D=A?"await ":"",R=h.has("beforeDirective")?"await ":"",P=h.has("afterDirective")?"await ":"",b=h.has("onDirectivesComplete")?"await ":"",I=new Set;me(i,t,I);let T=new Map,_=0;for(let E of I)T.set(E,`_h${_++}`);st(a,T,f,p),xe(i,"$.d",-1,0,{L:a,total:c,typeField:t,handlerVars:T,hasBefore:f,hasAfter:p,awBefore:R,awAfter:P,awHandler:D,actionIsAsync:A,actionIsInteractive:n,interactiveHandlerSet:s,blockCounter:{n:0}}),ot(a,c,l,b);let k=ct(a.join(`
|
|
8
|
-
`),A,n);return {fn:new Function("frame","scope","$",`"use strict";
|
|
9
|
-
return ${k};`),isAsync:A,isInteractive:n}}function ce(i,e,t){for(let r of i){let o=r[t];if(o&&e.has(o))return true;if(o==="if"){let s=r.then;if(Array.isArray(s)&&s.length>0&&ce(s,e,t))return true;let a=r.else;if(Array.isArray(a)&&a.length>0&&ce(a,e,t))return true}let n=r.catch;if(Array.isArray(n)&&n.length>0&&ce(n,e,t))return true}return false}function De(i,e,t){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:i,...t}}function Te(i,e){return De(e,`Action not found: "${i}"`,{aborted:true,abortedBy:"action-not-found"})}function Se(i,e,t){return De(t,`Max depth ${e} exceeded invoking "${i}"`,{aborted:true,abortedBy:"maxDepth"})}function $e(i,e){return De(e,`Action "${i}" is private (sub-action). Can only be invoked from within its parent scope.`)}function ae(i,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:i,counters:e}}function vt(i){return typeof i=="object"&&i!==null&&"execute"in i}function He(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&o[c].graph!==false&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Me(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Pe(i,e,t){if(!e)return t;let r=new Set(t);for(let[o,n]of i)n.executeInteractive!==void 0&&r.add(o);return r}function te(i,e,t){let r=Object.create(null);for(let[o,n]of i){let s;t&&n.executeInteractive!==void 0?s=n.executeInteractive:e&&n.executeAsync!==void 0?s=n.executeAsync:s=n.execute,r[o]=s;}return r}function Fe(i){let e=Object.create(null),t=new Map;for(let r of Object.keys(i)){let o=i[r];vt(o)?(e[r]=o.execute,t.set(r,o)):(e[r]=o,t.set(r,{execute:o}));}return {handlers:e,definitions:t}}function Ge(i,e){if(i==="*")return true;if(!i.includes("*"))return i===e;let t=i.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}function Be(i){return typeof i=="string"?{pattern:i}:i}function Ne(i,e,t){let r=new Map;if(!e&&!t){for(let o of i)r.set(o,{status:"available"});return r}if(e){let o=e.map(Be);for(let n of i){let s=o.some(a=>Ge(a.pattern,n));r.set(n,{status:s?"available":"denied"});}}else {let o=t.map(Be);for(let n of i){let s=o.find(a=>Ge(a.pattern,n));s?r.set(n,{status:"denied",reason:s.reason,source:s.source}):r.set(n,{status:"available"});}}return r}function Le(i){let{typeField:e,asyncHandlerSet:t,interactiveHandlerSet:r,subDirectiveFieldsForGraph:o}=i,n=new Map,s=new Set,a=new Set,c=new Set,u=new Set;return {upsert(d,h,f){n.set(d,ht(h,e,o)),ne(h,t,e,o)?s.add(d):s.delete(d),f||ie(h,r,e,o)?a.add(d):a.delete(d);},remove(d){n.delete(d),s.delete(d),a.delete(d);},recompute(){c=je(n,s),u=je(n,a);},isAsync(d){return c.has(d)},isInteractive(d){return u.has(d)},has(d){return n.has(d)}}}var ue=new Map;function ht(i,e,t=ue){let r=new Set;return re(i,e,t,r),r}function re(i,e,t,r){for(let o of i){let n=o[e];n==="action"&&typeof o.id=="string"&&r.add(o.id);let s=o.catch;if(Array.isArray(s)&&s.length>0&&re(s,e,t,r),n==="if"){let c=o.then;Array.isArray(c)&&c.length>0&&re(c,e,t,r);let u=o.else;Array.isArray(u)&&u.length>0&&re(u,e,t,r);continue}if(n===void 0)continue;let a=t.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];!Array.isArray(u)||u.length===0||re(u,e,t,r);}}}function ne(i,e,t,r=ue){for(let o of i){let n=o[t];if(n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ne(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ne(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ne(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ne(u,e,t,r))return true}}return false}function ie(i,e,t,r=ue){for(let o of i){let n=o[t];if(n==="pause"||n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ie(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ie(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ie(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ie(u,e,t,r))return true}}return false}function Q(i,e,t=ue){for(let r of i){let o=r[e];if(o==="pause")return true;let n=r.catch;if(Array.isArray(n)&&n.length>0&&Q(n,e,t))return true;if(o==="if"){let a=r.then;if(Array.isArray(a)&&a.length>0&&Q(a,e,t))return true;let c=r.else;if(Array.isArray(c)&&c.length>0&&Q(c,e,t))return true;continue}if(o===void 0)continue;let s=t.get(o);if(s!==void 0)for(let a=0;a<s.length;a++){let c=r[s[a]];if(!(!Array.isArray(c)||c.length===0)&&Q(c,e,t))return true}}return false}function je(i,e){let t=new Set(e),r=true;for(;r;){r=false;for(let[o,n]of i)if(!t.has(o)){for(let s of n)if(t.has(s)){t.add(o),r=true;break}}}return t}var le=class{depth=0;errors=[];warnings=[];actions=[];registered=[];begin(){this.depth++,this.depth===1&&(this.errors=[],this.warnings=[],this.actions=[],this.registered=[]);}endDepth(){if(this.depth<=0)throw new Error("endBatch() called without matching beginBatch()");return this.depth--,this.depth===0}isActive(){return this.depth>0}accumulate(e,t,r,o){this.errors.push(...e),this.warnings.push(...t);for(let n of r)this.actions.push(n);this.registered.push(...o);}};function Oe(i){for(let e of i)if(N.has(e))throw new Error(`Handler type "${e}" is reserved for engine-internal directives`)}function Ve(i,e){if(i&&e)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.")}function ze(i,e,t){if(i)return;if(e.size>0){let o=Array.from(e).join(", ");throw new Error(`Handler(s) [${o}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}let r=[];for(let[o,n]of t)n.executeInteractive!==void 0&&r.push(o);if(r.length>0)throw new Error(`Handler(s) [${r.join(", ")}] declare \`executeInteractive\` variant but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}function Ke(i){let e=new Set,t=new Set;for(let[r,o]of i)(o.async===true||isAsyncFunction(o.execute))&&e.add(r),(o.interactive===true||isGeneratorFunction(o.execute))&&t.add(r);return {asyncHandlerSet:e,interactiveHandlerSet:t}}function Ue(i,e,t,r){let o=t?te(i,true,false):e,n=r?te(i,t,true):null;return {handlersAsync:o,handlersInteractive:n}}function Ae(i,e){return e?{next:()=>Promise.resolve({value:i,done:true}),return:()=>Promise.resolve({value:i,done:true}),throw:o=>Promise.reject(o),[Symbol.asyncIterator](){return this}}:{next:()=>({value:i,done:true}),return:()=>({value:i,done:true}),throw:r=>{throw r},[Symbol.iterator](){return this}}}function qe(i,e,t,r,o,n){if(n){let c=i;return {async next(d){let h=await c.next(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},async return(){let d=await c.return(void 0),h=d.value;if(d.done&&o!==null){let f=o(e,t,h,r);f!==void 0&&(h=f);}return {value:h,done:true}},async throw(d){let h=await c.throw(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},[Symbol.asyncIterator](){return this}}}let s=i;return {next(c){let u=s.next(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},return(){let c=s.return(void 0),u=c.value;if(c.done&&o!==null){let d=o(e,t,u,r);d!==void 0&&(u=d);}return {value:u,done:true}},throw(c){let u=s.throw(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}var Dt=8,At="type",be={maxDepth:10,maxRules:1e4,maxDirectives:1e5},Re=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_handlersAsync;_handlersInteractive;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new X;_batch=new le;_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Dt,this._typeField=e.typeField??At,this._limits={maxDepth:e.limits?.maxDepth??be.maxDepth,maxRules:e.limits?.maxRules??be.maxRules,maxDirectives:e.limits?.maxDirectives??be.maxDirectives};let{handlers:t,definitions:r}=Fe(e.handlers);Oe(Object.keys(e.handlers)),Ve(e.allowedDirectives,e.blockedDirectives),this._handlers=t,this._definitions=r,this._directivePermissions=Ne(Object.keys(t),e.allowedDirectives,e.blockedDirectives),this._directiveHooks=e.directiveHooks??{},this._beforeAction=e.actionHooks?.beforeAction??null,this._afterAction=e.actionHooks?.afterAction??null,this._directiveAnalysis=analyzeSlots(this._directiveHooks,DIRECTIVE_SLOT_NAMES);let{asyncHandlerSet:o,interactiveHandlerSet:n}=Ke(this._definitions);this._asyncHandlerSet=o,this._interactiveHandlerSet=n,this._isInteractive=e.interactive!==void 0,ze(this._isInteractive,n,this._definitions),this._isAsync=this._directiveAnalysis.hasAnyAsync||o.size>0;let{handlersAsync:s,handlersInteractive:a}=Ue(this._definitions,this._handlers,this._isAsync,this._isInteractive);this._handlersAsync=s,this._handlersInteractive=a;let c=He(this._definitions);this._subDirectiveFieldsForGraph=c,this._subDirectiveFieldsAll=Me(this._definitions),this._miniGraph=Le({typeField:this._typeField,asyncHandlerSet:o,interactiveHandlerSet:n,subDirectiveFieldsForGraph:c}),this._engineRef=this._buildEngineRef();let u=oe(this._directiveAnalysis,false);this._directiveRunner=this._buildDirectiveRunner(),this._directiveRunnerSync=this._buildDirectiveRunnerSync(u);let d=this._buildExecutors(u);this._directiveExecutor=d.directiveExecutor,this._mode=d.mode,this._interactiveExecutor=d.interactiveExecutor;}_buildEngineRef(){return {runDirectives:(e,t)=>this._executeDirectives(e,t),runDirectivesAsync:(e,t)=>this._executeDirectivesAsync(e,t),invoke:(e,t,r)=>this._invokeInternal(e,t,r),invokeAsync:(e,t,r)=>this._invokeInternalAsync(e,t,r),isActionAsync:e=>this._miniGraph.has(e)?this._miniGraph.isAsync(e):void 0,isActionInteractive:e=>this._miniGraph.has(e)?this._miniGraph.isInteractive(e):void 0,invokeInteractive:(e,t,r)=>this._invokeInteractiveInternal(e,t,r),runDirectivesInteractive:(e,t)=>this._executeDirectivesInteractive(e,t),evaluateRules:()=>{throw new Error("evaluateRules() not available in ActionEngine context. Use createRuleEngine().")},evaluateRulesAsync:()=>{throw new Error("evaluateRulesAsync() not available in ActionEngine context. Use createRuleEngine().")}}}_buildDirectiveRunner(){let e=this._isAsync?this._handlersAsync:this._handlers;return (t,r)=>this._directiveExecutor(t,r,e,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildDirectiveRunnerSync(e){return (t,r)=>e(t,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildExecutors(e){let t,r;this._requestedMode==="jit"?(t=this._buildJitDirectiveExecutor(),r="jit"):this._isAsync?(t=oe(this._directiveAnalysis,true),r="interpret"):(t=e,r="interpret");let o=this._isInteractive?this._isAsync?he(this._directiveAnalysis,true):he(this._directiveAnalysis,false):null;return {directiveExecutor:t,mode:r,interactiveExecutor:o}}register(e){let t=[],r=[],o=[],n=[];for(let c of e){if(!c.id){r.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&Q(c.directives,this._typeField,this._subDirectiveFieldsForGraph)){r.push({actionId:c.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let u=ke(c,this._handlers,this._definitions,this._typeField);if(u.length>0){for(let d of u)r.push({actionId:c.id,error:d});continue}n.push(c);}for(let c of n){let u=B(c.directives,this._typeField,this._subDirectiveFieldsAll),d={definition:c,directives:u,compiled:null,invokeCount:0};this._registry.set(c.id,d),this._registeredIds.add(c.id),this._miniGraph.upsert(c.id,u,c.interactive===true),t.push(c.id);}if(this._batch.isActive())return this._batch.accumulate(r,o,n,t),{registered:t,errors:r,warnings:o};let s=t;if(n.length>0){this._miniGraph.recompute();let c=this._validateInteractiveVariants(t);c.errors.length>0&&r.push(...c.errors),c.warnings.length>0&&o.push(...c.warnings),s=c.validRegistered,this._invalidateAndMaybeRecompile();}let a={registered:s,errors:r,warnings:o};if(s.length>0){let c=new Set(s),u=n.filter(d=>c.has(d.id));this._emitter.emit("register",{actions:u,result:a,registered:s});}return a}unregister(e){let t=this._registry.delete(e);t&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let r=e+"/",o=[];for(let n of this._registry.keys())n.startsWith(r)&&(this._registry.delete(n),this._registeredIds.delete(n),this._miniGraph.remove(n),o.push(n));return t&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:o})),t}invoke(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);if(this._miniGraph.isAsync(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is async (transitively). Use invokeAsync() instead.`);if(this._directiveAnalysis.hasAnyAsync)throw new Error(`Cannot call invoke("${e}") \u2014 engine has async directive hooks. Use invokeAsync() instead.`);let o=r!==void 0?r:this._requireCtx(),n=createRootFrame(o,this._limits);return this._invokeInternal(e,t,n)}async invokeAsync(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let o=r!==void 0?r:this._requireCtx(),n=createRootFrame(o,this._limits);return this._invokeInternalAsync(e,t,n)}setContext(e){this._ctx=e;}context(e,t){let r=this._ctx;this._ctx=e;try{return t()}finally{this._ctx=r;}}beginBatch(){this._batch.begin();}endBatch(){if(!this._batch.endDepth())return {registered:[],errors:[],warnings:[]};let t=this._batch.registered;if(this._batch.registered.length>0){this._miniGraph.recompute();let o=this._validateInteractiveVariants(this._batch.registered);this._batch.errors.push(...o.errors),this._batch.warnings.push(...o.warnings),t=o.validRegistered,this._invalidateAndMaybeRecompile();}let r={registered:t,errors:this._batch.errors,warnings:this._batch.warnings};if(t.length>0){let o=new Set(t),n=this._batch.actions.filter(s=>o.has(s.id));this._emitter.emit("register",{actions:n,result:r,registered:t});}return r}on(e,t){return this._emitter.on(e,t)}get handlerDefinitions(){return this._definitions}get registeredIds(){return this._registeredIds}getActionDefinition(e){return this._registry.get(e)?.definition}get typeField(){return this._typeField}get subDirectiveFieldsForGraph(){return this._subDirectiveFieldsForGraph}get directivePermissions(){return this._directivePermissions}get isAsync(){return this._isAsync}get isInteractive(){return this._isInteractive}isActionAsync(e){if(this._miniGraph.has(e))return this._miniGraph.isAsync(e)}isActionInteractive(e){if(this._miniGraph.has(e))return this._miniGraph.isInteractive(e)}invokeInteractive(e,t,r){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let o=r!==void 0?r:this._requireCtx(),n=createRootFrame(o,this._limits);return this._invokeInteractiveInternal(e,t,n)}_invokeInteractiveInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return Ae(o,this._isAsync);let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return Ae(ae(u.data,s.counters),this._isAsync)}let c;if(n.compiled&&n.compiled.isInteractive)c=n.compiled.fn(s,s.scope,n.compiled.$);else {let u=this._interactiveExecutor;c=u(n.directives,s,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return qe(c,e,t,s,this._afterAction,this._isAsync)}_executeDirectivesInteractive(e,t){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("runDirectivesInteractive: engine has no `interactive` config");return this._interactiveExecutor(e,t,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}get compilationMode(){return this._mode}get directiveHookSlots(){return this._directiveAnalysis.filledNames}get asyncSlots(){return this._directiveAnalysis.asyncNames}compile(){if(this._requestedMode!=="interpret"){this._mode!=="jit"&&this._promote();for(let[e,t]of this._registry)t.compiled||(t.compiled=this._compileAction(e,t.directives));}}_invokeInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=n.compiled.fn(s,a,n.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(n.compiled=this._compileAction(e,n.directives),c=n.compiled.fn(s,a,n.compiled.$)):(c=this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=await n.compiled.fn(s,a,n.compiled.$):(c=await this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}_prepareInvoke(e,t,r){let o=this._registry.get(e);if(!o)return Te(e,r.counters);if(e.includes("/")&&!this._isAccessible(e,r))return $e(e,r.counters);if(r.depth>=r.limits.maxDepth)return Se(e,r.limits.maxDepth,r.counters);let n=Object.create(r.scope);t&&Object.assign(n,t);let s=r.child("action:"+e,0,e).withScope(n);return {stored:o,childFrame:s,childScope:n}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&this._promote());}_executeDirectives(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,t){let r=this._miniGraph.isAsync(e),o=this._miniGraph.isInteractive(e),n=Pe(this._definitions,o,this._interactiveHandlerSet),{fn:s,isAsync:a,isInteractive:c}=_e(t,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,r,o,n),u=te(this._definitions,a,c),d={d:t,h:u,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:s,$:d,isAsync:a,isInteractive:c}}_isAccessible(e,t){let o="action:"+e.slice(0,e.lastIndexOf("/"));return t.path.includes(o)}_requireCtx(){if(this._ctx===void 0)throw new Error("No context set. Pass ctx to invoke(id, params, ctx), call setContext(ctx), or use context(ctx, fn).");return this._ctx}_promote(){this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit";}_buildJitDirectiveExecutor(){let{fn:e}=ye(this._directiveAnalysis,this._isAsync);return e}_validateInteractiveVariants(e){let t=[],r=[],o=new Set(e),n=new Set;for(let a of this._registeredIds){if(!this._miniGraph.isInteractive(a))continue;let c=this._registry.get(a);if(c===void 0)continue;let u=Ee(c.directives,this._typeField,this._definitions,this._subDirectiveFieldsForGraph,this._interactiveHandlerSet,h=>this._miniGraph.isInteractive(h),isGeneratorFunction);if(u.size===0)continue;let d=o.has(a);for(let h of u){let f=`Action "${a}" is transitively interactive but handler "${h}" has no executeInteractive variant (and execute is not a generator function, and interactive flag is not set)`;d?(t.push({actionId:a,error:f,code:"MISSING_INTERACTIVE_VARIANT"}),n.add(a)):r.push({actionId:a,code:"MISSING_INTERACTIVE_VARIANT",message:f});}}if(n.size>0){for(let a of n)this._registry.delete(a),this._registeredIds.delete(a),this._miniGraph.remove(a);this._miniGraph.recompute();}return {validRegistered:e.filter(a=>!n.has(a)),errors:t,warnings:r}}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,t]of this._registry)t.compiled=this._compileAction(e,t.directives);}};function Ct(i){return new Re(i)}export{N as RESERVED_TYPES,X as SimpleEmitter,_e as buildActionExecutor,ye as buildDirectiveExecutor,Ct as createActionEngine,oe as createDirectiveInterpreter,Je as drainAsync,We as drainSync,B as normalizeDirectives,Ye as replayResponder};
|
|
1
|
+
import {analyzeSlots,DIRECTIVE_SLOT_NAMES,createRootFrame,processIntercept,Intercept,isAsyncFunction,isGeneratorFunction}from'@statedelta-actions/core';function Qe(r,e){let t;for(;;){let n=r.next(t);if(n.done)return n.value;t=e?e(n.value):void 0;}}async function Xe(r,e){let t;for(;;){let n=await r.next(t);if(n.done)return n.value;t=e?await e(n.value):void 0;}}function Ze(r){let e=0;return t=>{if(t?.source!=="step"&&!(e>=r.length))return r[e++]}}var Z=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 i=0;i<s.length;i++)try{s[i](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 j=new Set(["const","let","return","throw","pause","if"]);function Ie(r,e,t,n){let s=[];return oe(r.directives,e,t,n,"directive",s,r.id),s}function oe(r,e,t,n,s,i,o){for(let a=0;a<r.length;a++){let c=r[a],u=c[n],l=`${s}[${a}]`;if(!u){i.push(`${l}: missing type field "${n}"`);continue}if(u==="if"){let d=c.cond;typeof d!="function"&&typeof d!="boolean"&&i.push(`${l}: "if" requires cond as function or boolean`);let x=c.then;Array.isArray(x)?oe(x,e,t,n,`${l}.then`,i,o):i.push(`${l}: "if" requires then as array`);let C=c.else;C!==void 0&&(Array.isArray(C)?oe(C,e,t,n,`${l}.else`,i,o):i.push(`${l}.else: must be array`));continue}if(j.has(u))continue;if(!e[u])throw new Error(`Action "${o}" ${l}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let y=t.get(u);if(y?.validate)try{let d=y.validate(c);d&&!d.valid&&i.push(`${l}: ${d.error??"validation failed"}`);}catch(d){i.push(`${l}: validate threw: ${d}`);}let v=c.catch;if(v&&Array.isArray(v))for(let d=0;d<v.length;d++){let C=v[d][n];if(!(C&&j.has(C))&&C&&!e[C])throw new Error(`Action "${o}" ${l}.catch[${d}]: no handler registered for type "${C}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let f=y?.subDirectives;if(f===void 0)continue;let p=Object.keys(f);for(let d=0;d<p.length;d++){let x=p[d];if(x==="catch")continue;let C=c[x];if(C===void 0){if(f[x].required)throw new Error(`Action "${o}" ${l}: handler "${u}" requires sub-directives field "${x}"`);continue}if(!Array.isArray(C))throw new Error(`Action "${o}" ${l}.${x}: must be an array of directives`);oe(C,e,t,n,`${l}.${x}`,i,o);}}}var et=new Map;function N(r,e,t=et){let n=r.length,s=new Array(n);for(let i=0;i<n;i++){let o=r[i],a=o[e],c=o,u=false,l=o.catch;if(Array.isArray(l)&&l.length>0&&(c={...c,catch:N(l,e,t)},u=true),a==="if"){let y=o.then;Array.isArray(y)&&y.length>0&&(c={...c,then:N(y,e,t)},u=true);let v=o.else;Array.isArray(v)&&v.length>0&&(c={...c,else:N(v,e,t)},u=true);}else if(a!==void 0){let y=t.get(a);if(y!==void 0)for(let v=0;v<y.length;v++){let f=y[v],p=o[f];!Array.isArray(p)||p.length===0||(c={...c,[f]:N(p,e,t)},u=true);}}s[i]=u?c:o;}return s}function we(r,e,t,n,s,i,o){let a=new Set;return ee(r,e,t,n,s,i,o,a),a}function ee(r,e,t,n,s,i,o,a){for(let c of r){let u=c[e];if(u!==void 0){let v=t.get(u);if(v!==void 0&&v.subDirectives!==void 0){let f=n.get(u);if(f!==void 0){let p=false;for(let d=0;d<f.length;d++){let x=c[f[d]];if(!(!Array.isArray(x)||x.length===0)&&te(x,e,n,s,i)){p=true;break}}p&&(v.executeInteractive!==void 0||v.interactive===true||o(v.execute)||a.add(u));}}}let l=c.catch;if(Array.isArray(l)&&l.length>0&&ee(l,e,t,n,s,i,o,a),u==="if"){let v=c.then;Array.isArray(v)&&v.length>0&&ee(v,e,t,n,s,i,o,a);let f=c.else;Array.isArray(f)&&f.length>0&&ee(f,e,t,n,s,i,o,a);continue}if(u===void 0)continue;let y=n.get(u);if(y!==void 0)for(let v=0;v<y.length;v++){let f=c[y[v]];!Array.isArray(f)||f.length===0||ee(f,e,t,n,s,i,o,a);}}}function te(r,e,t,n,s){for(let i of r){let o=i[e];if(o==="pause"||o!==void 0&&n.has(o)||o==="action"&&typeof i.id=="string"&&s(i.id))return true;let a=i.catch;if(Array.isArray(a)&&a.length>0&&te(a,e,t,n,s))return true;if(o==="if"){let u=i.then;if(Array.isArray(u)&&u.length>0&&te(u,e,t,n,s))return true;let l=i.else;if(Array.isArray(l)&&l.length>0&&te(l,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 l=i[c[u]];if(!(!Array.isArray(l)||l.length===0)&&te(l,e,t,n,s))return true}}return false}function O(r,e,t,n,s,i){let o=r.name;if(typeof r.resolve=="function")try{t[o]=r.resolve(e,t).value;}catch(a){n.push({directiveIndex:s,error:`Binding resolve: ${a}`}),i.errors++;}else t[o]=r.value;}function L(r,e,t,n,s,i){let o=r.value;if(typeof r.resolve=="function")try{let a=r.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}`}),i.errors++,{ok:false}}return {ok:true,data:o}}function V(r,e,t,n,s,i){let o=r.message;if(typeof r.resolve=="function")try{let a=r.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}`}),i.errors++,{ok:false}}return {ok:true,data:o}}function z(r,e,t,n,s,i,o,a,c,u,l){let y;try{let f=r.cond;y=typeof f=="function"?!!f(e,t):!!f;}catch(f){c.push({directiveIndex:u,error:`if cond: ${f}`}),l.errors++;return}let v=y?r.then:r.else;if(Array.isArray(v)&&v.length>0){let f=Math.min(v.length,a),p=s?i:o;n.push({dirs:v,i:0,len:f,topLevelIfIndex:p});}}function K(r,e,t){let n=processIntercept(r,"beforeDirective");if(n.action===Intercept.SKIP)return {action:"skip"};if(n.action===Intercept.ABORT)return {action:"abort",reason:n.abortReason};let s=t,i=e;return n.ctx!==void 0&&(s=t.withCtx(n.ctx)),n.directive!==void 0&&(i=n.directive),{action:"continue",directive:i,dFrame:s}}function B(r,e,t,n,s){r.push({directiveIndex:t,error:`Hook ${n}: ${s}`}),e.errors++;}function H(r,e,t,n,s){return {success:false,aborted:true,abortedBy:r,appliedCount:e.appliedCount,skippedCount:e.skippedCount,errors:e.errors,processedCount:t,totalCount:n,counters:e.counters,data:s}}function U(r,e,t,n){return {success:true,aborted:true,abortedBy:"halt",appliedCount:r.appliedCount,skippedCount:r.skippedCount,errors:r.errors,processedCount:e,totalCount:t,counters:r.counters,data:n}}function q(r,e,t,n){return {success:true,aborted:false,appliedCount:r.appliedCount,skippedCount:r.skippedCount,errors:r.errors,processedCount:e,totalCount:t,counters:r.counters,data:n}}function W(r,e){return {success:true,aborted:false,appliedCount:r.appliedCount,skippedCount:r.skippedCount,errors:r.errors,processedCount:e,totalCount:e,counters:r.counters}}function Y(r,e,t,n){return {success:n.success,aborted:true,abortedBy:n.abortedBy,appliedCount:r.appliedCount,skippedCount:r.skippedCount,errors:r.errors,processedCount:e,totalCount:t,counters:r.counters,data:n.data}}function J(r,e,t,n,s){if(typeof r.resolve!="function")return r;try{let i=r.resolve(e.ctx,e.scope);return {...r,...i}}catch(i){return t.push({directiveIndex:n,error:`Directive resolve: ${i}`}),s.errors++,null}}function Q(r,e){return [{dirs:r,i:0,len:e,topLevelIfIndex:-1}]}function nt(r){let e=r.filledNames.has("beforeDirective"),t=r.filledNames.has("afterDirective"),n=r.filledNames.has("onDirectivesComplete");return function(i,o,a,c,u,l,y){let v=Math.min(i.length,y),f=[],p={appliedCount:0,skippedCount:0,errors:f,counters:o.counters},{scope:d}=o,x=o.ctx,C=Q(i,v),E=0;for(;C.length>0;){let $=C[C.length-1];if($.i>=$.len){C.pop();continue}let k=$.i++,S=$.topLevelIfIndex!==-1,I=S?$.topLevelIfIndex:k;S||(E=k+1);let _=$.dirs[k],R=_[u];if(R==="const"||R==="let"){O(_,x,d,f,I,p.counters);continue}if(R==="return"){let m=L(_,x,d,f,I,p.counters);if(!m.ok)continue;return q(p,E,v,m.data)}if(R==="throw"){let m=V(_,x,d,f,I,p.counters);if(!m.ok)continue;return H("throw",p,E,v,m.data)}if(R==="if"){z(_,x,d,C,S,$.topLevelIfIndex,k,y,f,I,p.counters);continue}let A=_,D=o;if(e)try{let m=c.beforeDirective(A,o),h=K(m,A,o);if(h.action==="skip"){p.skippedCount++,p.counters.directivesSkipped++;continue}if(h.action==="abort"){let g=E===0?k:E-1;return H(h.reason,p,g,v)}A=h.directive,D=h.dFrame;}catch(m){B(f,p.counters,I,"beforeDirective",m);}let M=J(A,D,f,I,p.counters);if(M===null)continue;A=M;let P=A[u],G=P?a[P]:void 0;if(!G){f.push({directiveIndex:I,error:`No handler for directive type: ${P??"undefined"}`}),p.counters.errors++;continue}let T;try{T=G(A,D,l);}catch(m){T={ok:false,error:String(m)};}let b=E;if(T.ok){if(p.appliedCount++,p.counters.directivesApplied++,typeof A.as=="string"&&(d[A.as]=T.data),T.halt)return U(p,b,v,T.data)}else {if(T.halt)return H("halt",p,b,v,T.data);let m=A.catch;if(Array.isArray(m)&&m.length>0){d.$exception=T.error??"handler failed";let h=l.runDirectives(m,D);p.appliedCount+=h.appliedCount;for(let g=0;g<h.errors.length;g++)f.push(h.errors[g]);if(h.aborted)return Y(p,b,v,h)}else f.push({directiveIndex:I,error:T.error??"handler failed"}),p.counters.errors++;}if(t)try{if(c.afterDirective(A,T,D)==="abort")return H("afterDirective",p,b,v)}catch(m){B(f,p.counters,I,"afterDirective",m);}}let w=W(p,v);if(n)try{c.onDirectivesComplete(w);}catch{}return w}}function rt(r){let e=r.filledNames.has("beforeDirective"),t=r.filledNames.has("afterDirective"),n=r.filledNames.has("onDirectivesComplete");return async function(i,o,a,c,u,l,y){let v=Math.min(i.length,y),f=[],p={appliedCount:0,skippedCount:0,errors:f,counters:o.counters},{scope:d}=o,x=o.ctx,C=Q(i,v),E=0;for(;C.length>0;){let $=C[C.length-1];if($.i>=$.len){C.pop();continue}let k=$.i++,S=$.topLevelIfIndex!==-1,I=S?$.topLevelIfIndex:k;S||(E=k+1);let _=$.dirs[k],R=_[u];if(R==="const"||R==="let"){O(_,x,d,f,I,p.counters);continue}if(R==="return"){let m=L(_,x,d,f,I,p.counters);if(!m.ok)continue;return q(p,E,v,m.data)}if(R==="throw"){let m=V(_,x,d,f,I,p.counters);if(!m.ok)continue;return H("throw",p,E,v,m.data)}if(R==="if"){z(_,x,d,C,S,$.topLevelIfIndex,k,y,f,I,p.counters);continue}let A=_,D=o;if(e)try{let m=await c.beforeDirective(A,o),h=K(m,A,o);if(h.action==="skip"){p.skippedCount++,p.counters.directivesSkipped++;continue}if(h.action==="abort"){let g=E===0?k:E-1;return H(h.reason,p,g,v)}A=h.directive,D=h.dFrame;}catch(m){B(f,p.counters,I,"beforeDirective",m);}let M=J(A,D,f,I,p.counters);if(M===null)continue;A=M;let P=A[u],G=P?a[P]:void 0;if(!G){f.push({directiveIndex:I,error:`No handler for directive type: ${P??"undefined"}`}),p.counters.errors++;continue}let T;try{T=await G(A,D,l);}catch(m){T={ok:false,error:String(m)};}let b=E;if(T.ok){if(p.appliedCount++,p.counters.directivesApplied++,typeof A.as=="string"&&(d[A.as]=T.data),T.halt)return U(p,b,v,T.data)}else {if(T.halt)return H("halt",p,b,v,T.data);let m=A.catch;if(Array.isArray(m)&&m.length>0){d.$exception=T.error??"handler failed";let h=await l.runDirectivesAsync(m,D);p.appliedCount+=h.appliedCount;for(let g=0;g<h.errors.length;g++)f.push(h.errors[g]);if(h.aborted)return Y(p,b,v,h)}else f.push({directiveIndex:I,error:T.error??"handler failed"}),p.counters.errors++;}if(t)try{if(await c.afterDirective(A,T,D)==="abort")return H("afterDirective",p,b,v)}catch(m){B(f,p.counters,I,"afterDirective",m);}}let w=W(p,v);if(n)try{await c.onDirectivesComplete(w);}catch{}return w}}function ce(r,e){return e?rt(r):nt(r)}function fe(r){if(r===null||typeof r!="object")return null;if(typeof r.next=="function")return r;let e=r.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function pe(r,e,t){return {source:"pause",directive:r,frame:e,index:t,payload:{message:r.message}}}function ve(r){return r===false||r==="abort"||r==="cancel"}function he(r,e,t,n){n.directivesApplied++,typeof r.as=="string"&&e!==void 0&&(t[r.as]=e);}function ye(r,e,t){return {source:"step",directive:r,frame:e,index:t}}var Se=Object.freeze({kind:"continue"}),it=Object.freeze({kind:"skip"}),st=Object.freeze({kind:"abort"});function ge(r){if(r==null||typeof r!="object")return Se;let e=r;if(e.abort===true)return st;if(e.skip===true)return it;if(e.replaceWith!==void 0){let t=e.replaceWith;if(typeof t=="object"&&t!==null&&!Array.isArray(t))return {kind:"replace",directive:t}}return Se}function ot(r){let e=r.filledNames.has("beforeDirective"),t=r.filledNames.has("afterDirective"),n=r.filledNames.has("onDirectivesComplete");return function*(i,o,a,c,u,l,y,v){let f=Math.min(i.length,y),p=[],d={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:x}=o,C=o.ctx,E=Q(i,f),w=0;for(;E.length>0;){let k=E[E.length-1];if(k.i>=k.len){E.pop();continue}let S=k.i++,I=k.topLevelIfIndex!==-1,_=I?k.topLevelIfIndex:S;I||(w=S+1);let R=k.dirs[S];if(v){let h=yield ye(R,o,_),g=ge(h);if(g.kind==="skip"){d.skippedCount++,d.counters.directivesSkipped++;continue}if(g.kind==="abort"){let F=w===0?S:w-1;return H("step",d,F,f)}g.kind==="replace"&&(R=g.directive);}let A=R[u];if(A==="const"||A==="let"){O(R,C,x,p,_,d.counters);continue}if(A==="return"){let h=L(R,C,x,p,_,d.counters);if(!h.ok)continue;return q(d,w,f,h.data)}if(A==="throw"){let h=V(R,C,x,p,_,d.counters);if(!h.ok)continue;return H("throw",d,w,f,h.data)}if(A==="pause"){let h=w,g=yield pe(R,o,_);if(ve(g))return H("pause",d,h,f,g);d.appliedCount++,he(R,g,x,d.counters);continue}if(A==="if"){z(R,C,x,E,I,k.topLevelIfIndex,S,y,p,_,d.counters);continue}let D=R,M=o;if(e)try{let h=c.beforeDirective(D,o),g=K(h,D,o);if(g.action==="skip"){d.skippedCount++,d.counters.directivesSkipped++;continue}if(g.action==="abort"){let F=w===0?S:w-1;return H(g.reason,d,F,f)}D=g.directive,M=g.dFrame;}catch(h){B(p,d.counters,_,"beforeDirective",h);}let P=J(D,M,p,_,d.counters);if(P===null)continue;D=P;let G=D[u],T=G?a[G]:void 0;if(!T){p.push({directiveIndex:_,error:`No handler for directive type: ${G??"undefined"}`}),d.counters.errors++;continue}let b;try{let h=T(D,M,l),g=fe(h);g!==null?b=yield*g:b=h;}catch(h){b={ok:false,error:String(h)};}let m=w;if(b.ok){if(d.appliedCount++,d.counters.directivesApplied++,typeof D.as=="string"&&(x[D.as]=b.data),b.halt)return U(d,m,f,b.data)}else {if(b.halt)return H("halt",d,m,f,b.data);let h=D.catch;if(Array.isArray(h)&&h.length>0){x.$exception=b.error??"handler failed";let g=l.runDirectives(h,M);d.appliedCount+=g.appliedCount;for(let F=0;F<g.errors.length;F++)p.push(g.errors[F]);if(g.aborted)return Y(d,m,f,g)}else p.push({directiveIndex:_,error:b.error??"handler failed"}),d.counters.errors++;}if(t)try{if(c.afterDirective(D,b,M)==="abort")return H("afterDirective",d,m,f)}catch(h){B(p,d.counters,_,"afterDirective",h);}}let $=W(d,f);if(n)try{c.onDirectivesComplete($);}catch{}return $}}function ct(r){let e=r.filledNames.has("beforeDirective"),t=r.filledNames.has("afterDirective"),n=r.filledNames.has("onDirectivesComplete");return async function*(i,o,a,c,u,l,y,v){let f=Math.min(i.length,y),p=[],d={appliedCount:0,skippedCount:0,errors:p,counters:o.counters},{scope:x}=o,C=o.ctx,E=Q(i,f),w=0;for(;E.length>0;){let k=E[E.length-1];if(k.i>=k.len){E.pop();continue}let S=k.i++,I=k.topLevelIfIndex!==-1,_=I?k.topLevelIfIndex:S;I||(w=S+1);let R=k.dirs[S];if(v){let h=yield ye(R,o,_),g=ge(h);if(g.kind==="skip"){d.skippedCount++,d.counters.directivesSkipped++;continue}if(g.kind==="abort"){let F=w===0?S:w-1;return H("step",d,F,f)}g.kind==="replace"&&(R=g.directive);}let A=R[u];if(A==="const"||A==="let"){O(R,C,x,p,_,d.counters);continue}if(A==="return"){let h=L(R,C,x,p,_,d.counters);if(!h.ok)continue;return q(d,w,f,h.data)}if(A==="throw"){let h=V(R,C,x,p,_,d.counters);if(!h.ok)continue;return H("throw",d,w,f,h.data)}if(A==="pause"){let h=w,g=yield pe(R,o,_);if(ve(g))return H("pause",d,h,f,g);d.appliedCount++,he(R,g,x,d.counters);continue}if(A==="if"){z(R,C,x,E,I,k.topLevelIfIndex,S,y,p,_,d.counters);continue}let D=R,M=o;if(e)try{let h=await c.beforeDirective(D,o),g=K(h,D,o);if(g.action==="skip"){d.skippedCount++,d.counters.directivesSkipped++;continue}if(g.action==="abort"){let F=w===0?S:w-1;return H(g.reason,d,F,f)}D=g.directive,M=g.dFrame;}catch(h){B(p,d.counters,_,"beforeDirective",h);}let P=J(D,M,p,_,d.counters);if(P===null)continue;D=P;let G=D[u],T=G?a[G]:void 0;if(!T){p.push({directiveIndex:_,error:`No handler for directive type: ${G??"undefined"}`}),d.counters.errors++;continue}let b;try{let h=await T(D,M,l),g=fe(h);g!==null?b=yield*g:b=h;}catch(h){b={ok:false,error:String(h)};}let m=w;if(b.ok){if(d.appliedCount++,d.counters.directivesApplied++,typeof D.as=="string"&&(x[D.as]=b.data),b.halt)return U(d,m,f,b.data)}else {if(b.halt)return H("halt",d,m,f,b.data);let h=D.catch;if(Array.isArray(h)&&h.length>0){x.$exception=b.error??"handler failed";let g=await l.runDirectivesAsync(h,M);d.appliedCount+=g.appliedCount;for(let F=0;F<g.errors.length;F++)p.push(g.errors[F]);if(g.aborted)return Y(d,m,f,g)}else p.push({directiveIndex:_,error:b.error??"handler failed"}),d.counters.errors++;}if(t)try{if(await c.afterDirective(D,b,M)==="abort")return H("afterDirective",d,m,f)}catch(h){B(p,d.counters,_,"afterDirective",h);}}let $=W(d,f);if(n)try{await c.onDirectivesComplete($);}catch{}return $}}function xe(r,e){return e?ct(r):ot(r)}function me(r,e,t){return `return{success:false,aborted:true,abortedBy:${r},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${t},counters};`}function at(r,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${r},totalCount:${e},counters,data:_result.data};`}function ut(r,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${r},totalCount:${e},counters,data:_result.data};`}function lt(r,e,t,n){r.push("const counters=frame.counters;"),r.push("const ctx=frame.ctx;"),r.push("const errors=[];"),r.push("let appliedCount=0;"),r.push("let skippedCount=0;");for(let[s,i]of e)r.push(`const ${i}=$.h[${JSON.stringify(s)}];`);t&&r.push("const _hookBefore=$.hooks.beforeDirective;"),n&&r.push("const _hookAfter=$.hooks.afterDirective;");}function dt(r,e,t,n){r.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${e},totalCount:${e},counters};`),t&&r.push(`try{${n}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),r.push("return _finalResult;");}function ft(r,e,t){let n=`{
|
|
2
|
+
${r}
|
|
3
|
+
}`;return t?`(${e?"async function*()":"function*()"}${n})()`:`(${e?"async ()=>":"()=>"}${n})()`}function pt(r,e,t,n){let s=JSON.stringify(e.name);typeof e.resolve=="function"?(r.push("try{"),r.push(`scope[${s}]=${t}.resolve(ctx,scope).value;`),r.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Binding resolve: "+_e});counters.errors++;}`)):r.push(`scope[${s}]=${t}.value;`);}function vt(r,e,t,n,s,i){typeof e.resolve=="function"?(r.push("try{"),r.push(`const _rv=${t}.resolve(ctx,scope);`),r.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${t}.value};`),r.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Control resolve: "+_e});counters.errors++;}`)):r.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:${t}.value};`);}function ht(r,e,t,n,s,i){typeof e.resolve=="function"?(r.push("try{"),r.push(`const _rv=${t}.resolve(ctx,scope);`),r.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${t}.message};`),r.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Control resolve: "+_e});counters.errors++;}`)):r.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:${t}.message};`);}function yt(r,e,t,n,s,i){let o=typeof e.as=="string",a=o?JSON.stringify(e.as):"";r.push(`{const _ack=yield{source:"pause",directive:${t},frame,index:${n},payload:{message:${t}.message}};`),r.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${i},counters,data:_ack};`),r.push("appliedCount++;counters.directivesApplied++;"),o&&r.push(`if(_ack!==undefined)scope[${a}]=_ack;`),r.push("}");}function gt(r,e,t,n,s){let{L:i,total:o,typeField:a,handlerVars:c,hasBefore:u,hasAfter:l,awBefore:y,awAfter:v,awHandler:f,actionIsAsync:p,actionIsInteractive:d,interactiveHandlerSet:x}=s,C=r[a],E=c.get(C),w=typeof r.resolve=="function",$=typeof r.as=="string",k=Array.isArray(r.catch)&&r.catch.length>0,S=$?JSON.stringify(r.as):"",I=d&&x.has(C),_=s.blockCounter.n++;i.push(`_b${_}:{`);let R=u||w,A=u;R&&i.push(`let _dir=${e};`),A&&i.push("let _df=frame;"),u&&(i.push("try{"),i.push(`const _bd=${y}_hookBefore(${e},frame);`),i.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${_};}`),i.push(`if(_bd==="abort")${me('"beforeDirective"',n-1,o)}`),i.push('if(typeof _bd==="object"&&_bd!==null){'),i.push(`if("abort" in _bd)${me("_bd.abort",n-1,o)}`),i.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),i.push('if("directive" in _bd)_dir=_bd.directive;'),i.push("}"),i.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(i.push('if(typeof _dir.resolve==="function"){'),i.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),i.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${_};}}`)):w&&(i.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),i.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${_};}`));let D=R?"_dir":e,M=A?"_df":"frame";if(i.push("let _result;"),I?(i.push(`try{_result=yield* ${E}(${D},${M},$.engine);}`),i.push("catch(_e){_result={ok:false,error:String(_e)};}")):d?(i.push(`try{_result=${f}${E}(${D},${M},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),i.push("catch(_e){_result={ok:false,error:String(_e)};}")):(i.push(`try{_result=${f}${E}(${D},${M},$.engine);}`),i.push("catch(_e){_result={ok:false,error:String(_e)};}")),i.push("if(_result.ok){"),i.push("appliedCount++;counters.directivesApplied++;"),$&&i.push(`scope[${S}]=_result.data;`),i.push(`if(_result.halt)${at(n,o)}`),i.push("}else{"),i.push(`if(_result.halt)${ut(n,o)}`),k){i.push('scope.$exception=_result.error||"handler failed";');let P=p?"$.runner":"$.runnerSync";i.push(`const _cr=${f}${P}(${e}.catch,${M});`),i.push("appliedCount+=_cr.appliedCount;"),i.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),i.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 i.push(`errors.push({directiveIndex:${t},error:_result.error||"handler failed"});counters.errors++;`);i.push("}"),l&&(i.push("try{"),i.push(`const _ad=${v}_hookAfter(${D},_result,${M});`),i.push(`if(_ad==="abort")${me('"afterDirective"',n,o)}`),i.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook afterDirective: "+_e});counters.errors++;}`)),i.push("}");}function xt(r,e,t,n,s,i){let{L:o}=i,a=r.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=r.then;Array.isArray(u)&&u.length>0&&_e(u,`${e}.then`,n,s,i),o.push("}");let l=r.else;Array.isArray(l)&&l.length>0&&(o.push("else{"),_e(l,`${e}.else`,n,s,i),o.push("}")),c||o.push("}"),o.push("}");}function _e(r,e,t,n,s){let i=t!==-1;for(let o=0;o<r.length;o++){let a=r[o],c=`${e}[${o}]`,u=i?t:o,l=i?n:o+1;switch(a[s.typeField]){case "const":case "let":pt(s.L,a,c,u);break;case "return":vt(s.L,a,c,u,l,s.total);break;case "throw":ht(s.L,a,c,u,l,s.total);break;case "pause":yt(s.L,a,c,u,l,s.total);break;case "if":{let v=i?t:o,f=i?n:o+1;xt(a,c,u,v,f,s);break}default:gt(a,c,u,l,s);break}}}function De(r,e,t){for(let n of r){let s=n[e];if(s&&!j.has(s)&&t.add(s),s==="if"){let i=n.then;Array.isArray(i)&&i.length>0&&De(i,e,t);let o=n.else;Array.isArray(o)&&o.length>0&&De(o,e,t);}}}var $e=new Set;function Ae(r,e,t,n=$e,s,i=false,o=$e){let a=[],c=r.length,{filledNames:u,hasAnyAsync:l,asyncNames:y}=e,v=u.has("beforeDirective"),f=u.has("afterDirective"),p=u.has("onDirectivesComplete"),d=s!==void 0?s:ae(r,n,t),x=l||d,C=x?"await ":"",E=y.has("beforeDirective")?"await ":"",w=y.has("afterDirective")?"await ":"",$=y.has("onDirectivesComplete")?"await ":"",k=new Set;De(r,t,k);let S=new Map,I=0;for(let D of k)S.set(D,`_h${I++}`);lt(a,S,v,f),_e(r,"$.d",-1,0,{L:a,total:c,typeField:t,handlerVars:S,hasBefore:v,hasAfter:f,awBefore:E,awAfter:w,awHandler:C,actionIsAsync:x,actionIsInteractive:i,interactiveHandlerSet:o,blockCounter:{n:0}}),dt(a,c,p,$);let R=ft(a.join(`
|
|
4
|
+
`),x,i);return {fn:new Function("frame","scope","$",`"use strict";
|
|
5
|
+
return ${R};`),isAsync:x,isInteractive:i}}function ae(r,e,t){for(let n of r){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&&ae(o,e,t))return true;let a=n.else;if(Array.isArray(a)&&a.length>0&&ae(a,e,t))return true}let i=n.catch;if(Array.isArray(i)&&i.length>0&&ae(i,e,t))return true}return false}function Ce(r,e,t){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:r,...t}}function Me(r,e){return Ce(e,`Action not found: "${r}"`,{aborted:true,abortedBy:"action-not-found"})}function He(r,e,t){return Ce(t,`Max depth ${e} exceeded invoking "${r}"`,{aborted:true,abortedBy:"maxDepth"})}function Pe(r,e){return Ce(e,`Action "${r}" is private (sub-action). Can only be invoked from within its parent scope.`)}function ue(r,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:r,counters:e}}function mt(r){return typeof r=="object"&&r!==null&&"execute"in r}function Fe(r){let e=new Map;for(let[t,n]of r){let s=n.subDirectives;if(!s)continue;let i=Object.keys(s);if(i.length===0)continue;let o=null;for(let a=0;a<i.length;a++){let c=i[a];c!=="catch"&&s[c].graph!==false&&(o===null&&(o=[]),o.push(c));}o!==null&&e.set(t,o);}return e}function Ge(r){let e=new Map;for(let[t,n]of r){let s=n.subDirectives;if(!s)continue;let i=Object.keys(s);if(i.length===0)continue;let o=null;for(let a=0;a<i.length;a++){let c=i[a];c!=="catch"&&(o===null&&(o=[]),o.push(c));}o!==null&&e.set(t,o);}return e}function Be(r,e,t){if(!e)return t;let n=new Set(t);for(let[s,i]of r)i.executeInteractive!==void 0&&n.add(s);return n}function ne(r,e,t){let n=Object.create(null);for(let[s,i]of r){let o;t&&i.executeInteractive!==void 0?o=i.executeInteractive:e&&i.executeAsync!==void 0?o=i.executeAsync:o=i.execute,n[s]=o;}return n}function Ne(r){let e=Object.create(null),t=new Map;for(let n of Object.keys(r)){let s=r[n];mt(s)?(e[n]=s.execute,t.set(n,s)):(e[n]=s,t.set(n,{execute:s}));}return {handlers:e,definitions:t}}function je(r,e){if(r==="*")return true;if(!r.includes("*"))return r===e;let t=r.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}function Oe(r){return typeof r=="string"?{pattern:r}:r}function Le(r,e,t){let n=new Map;if(!e&&!t){for(let s of r)n.set(s,{status:"available"});return n}if(e){let s=e.map(Oe);for(let i of r){let o=s.some(a=>je(a.pattern,i));n.set(i,{status:o?"available":"denied"});}}else {let s=t.map(Oe);for(let i of r){let o=s.find(a=>je(a.pattern,i));o?n.set(i,{status:"denied",reason:o.reason,source:o.source}):n.set(i,{status:"available"});}}return n}function ze(r){let{typeField:e,asyncHandlerSet:t,interactiveHandlerSet:n,subDirectiveFieldsForGraph:s}=r,i=new Map,o=new Set,a=new Set,c=new Set,u=new Set;return {upsert(l,y,v){i.set(l,_t(y,e,s)),ie(y,t,e,s)?o.add(l):o.delete(l),v||se(y,n,e,s)?a.add(l):a.delete(l);},remove(l){i.delete(l),o.delete(l),a.delete(l);},recompute(){c=Ve(i,o),u=Ve(i,a);},isAsync(l){return c.has(l)},isInteractive(l){return u.has(l)},has(l){return i.has(l)}}}var le=new Map;function _t(r,e,t=le){let n=new Set;return re(r,e,t,n),n}function re(r,e,t,n){for(let s of r){let i=s[e];i==="action"&&typeof s.id=="string"&&n.add(s.id);let o=s.catch;if(Array.isArray(o)&&o.length>0&&re(o,e,t,n),i==="if"){let c=s.then;Array.isArray(c)&&c.length>0&&re(c,e,t,n);let u=s.else;Array.isArray(u)&&u.length>0&&re(u,e,t,n);continue}if(i===void 0)continue;let a=t.get(i);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];!Array.isArray(u)||u.length===0||re(u,e,t,n);}}}function ie(r,e,t,n=le){for(let s of r){let i=s[t];if(i!==void 0&&e.has(i))return true;let o=s.catch;if(Array.isArray(o)&&o.length>0&&ie(o,e,t,n))return true;if(i==="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(i===void 0)continue;let a=n.get(i);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 se(r,e,t,n=le){for(let s of r){let i=s[t];if(i==="pause"||i!==void 0&&e.has(i))return true;let o=s.catch;if(Array.isArray(o)&&o.length>0&&se(o,e,t,n))return true;if(i==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&se(c,e,t,n))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&se(u,e,t,n))return true;continue}if(i===void 0)continue;let a=n.get(i);if(a!==void 0)for(let c=0;c<a.length;c++){let u=s[a[c]];if(!(!Array.isArray(u)||u.length===0)&&se(u,e,t,n))return true}}return false}function X(r,e,t=le){for(let n of r){let s=n[e];if(s==="pause")return true;let i=n.catch;if(Array.isArray(i)&&i.length>0&&X(i,e,t))return true;if(s==="if"){let a=n.then;if(Array.isArray(a)&&a.length>0&&X(a,e,t))return true;let c=n.else;if(Array.isArray(c)&&c.length>0&&X(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)&&X(c,e,t))return true}}return false}function Ve(r,e){let t=new Set(e),n=true;for(;n;){n=false;for(let[s,i]of r)if(!t.has(s)){for(let o of i)if(t.has(o)){t.add(s),n=true;break}}}return t}var de=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 i of n)this.actions.push(i);this.registered.push(...s);}};function Ke(r){for(let e of r)if(j.has(e))throw new Error(`Handler type "${e}" is reserved for engine-internal directives`)}function Ue(r,e){if(r&&e)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.")}function qe(r,e,t){if(r)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,i]of t)i.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 We(r){let e=new Set,t=new Set;for(let[n,s]of r)(s.async===true||isAsyncFunction(s.execute))&&e.add(n),(s.interactive===true||isGeneratorFunction(s.execute))&&t.add(n);return {asyncHandlerSet:e,interactiveHandlerSet:t}}function Ye(r,e,t,n){let s=t?ne(r,true,false):e,i=n?ne(r,t,true):null;return {handlersAsync:s,handlersInteractive:i}}function Re(r,e){return e?{next:()=>Promise.resolve({value:r,done:true}),return:()=>Promise.resolve({value:r,done:true}),throw:s=>Promise.reject(s),[Symbol.asyncIterator](){return this}}:{next:()=>({value:r,done:true}),return:()=>({value:r,done:true}),throw:n=>{throw n},[Symbol.iterator](){return this}}}function Je(r,e,t,n,s,i){if(i){let c=r;return {async next(l){let y=await c.next(l);if(y.done){let v=y.value;if(s!==null){let f=s(e,t,v,n);f!==void 0&&(v=f);}return {value:v,done:true}}return {value:y.value,done:false}},async return(){let l=await c.return(void 0),y=l.value;if(l.done&&s!==null){let v=s(e,t,y,n);v!==void 0&&(y=v);}return {value:y,done:true}},async throw(l){let y=await c.throw(l);if(y.done){let v=y.value;if(s!==null){let f=s(e,t,v,n);f!==void 0&&(v=f);}return {value:v,done:true}}return {value:y.value,done:false}},[Symbol.asyncIterator](){return this}}}let o=r;return {next(c){let u=o.next(c);if(u.done){let l=u.value;if(s!==null){let y=s(e,t,l,n);y!==void 0&&(l=y);}return {value:l,done:true}}return {value:u.value,done:false}},return(){let c=o.return(void 0),u=c.value;if(c.done&&s!==null){let l=s(e,t,u,n);l!==void 0&&(u=l);}return {value:u,done:true}},throw(c){let u=o.throw(c);if(u.done){let l=u.value;if(s!==null){let y=s(e,t,l,n);y!==void 0&&(l=y);}return {value:l,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}var kt=8,Et="type",ke={maxDepth:10,maxRules:1e4,maxDirectives:1e5},Ee=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_handlersAsync;_handlersInteractive;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_autoStepDirectives;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new Z;_batch=new de;_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??kt,this._typeField=e.typeField??Et,this._limits={maxDepth:e.limits?.maxDepth??ke.maxDepth,maxRules:e.limits?.maxRules??ke.maxRules,maxDirectives:e.limits?.maxDirectives??ke.maxDirectives};let{handlers:t,definitions:n}=Ne(e.handlers);Ke(Object.keys(e.handlers)),Ue(e.allowedDirectives,e.blockedDirectives),this._handlers=t,this._definitions=n,this._directivePermissions=Le(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:i}=We(this._definitions);this._asyncHandlerSet=s,this._interactiveHandlerSet=i,this._isInteractive=e.interactive!==void 0,this._autoStepDirectives=this._isInteractive&&e.interactive?.autoStepDirectives===true,qe(this._isInteractive,i,this._definitions),this._isAsync=this._directiveAnalysis.hasAnyAsync||s.size>0;let{handlersAsync:o,handlersInteractive:a}=Ye(this._definitions,this._handlers,this._isAsync,this._isInteractive);this._handlersAsync=o,this._handlersInteractive=a;let c=Fe(this._definitions);this._subDirectiveFieldsForGraph=c,this._subDirectiveFieldsAll=Ge(this._definitions),this._miniGraph=ze({typeField:this._typeField,asyncHandlerSet:s,interactiveHandlerSet:i,subDirectiveFieldsForGraph:c}),this._engineRef=this._buildEngineRef();let u=ce(this._directiveAnalysis,false);this._directiveRunner=this._buildDirectiveRunner(),this._directiveRunnerSync=this._buildDirectiveRunnerSync(u);let l=this._buildExecutors(u);this._directiveExecutor=l.directiveExecutor,this._mode=l.mode,this._interactiveExecutor=l.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?ce(this._directiveAnalysis,true):e,n=this._requestedMode==="jit"?"jit":"interpret",s=this._isInteractive?this._isAsync?xe(this._directiveAnalysis,true):xe(this._directiveAnalysis,false):null;return {directiveExecutor:t,mode:n,interactiveExecutor:s}}register(e){let t=[],n=[],s=[],i=[];for(let c of e){if(!c.id){n.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&X(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=Ie(c,this._handlers,this._definitions,this._typeField);if(u.length>0){for(let l of u)n.push({actionId:c.id,error:l});continue}i.push(c);}for(let c of i){let u=N(c.directives,this._typeField,this._subDirectiveFieldsAll),l={definition:c,directives:u,compiled:null,invokeCount:0};this._registry.set(c.id,l),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,i,t),{registered:t,errors:n,warnings:s};let o=t;if(i.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=i.filter(l=>c.has(l.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 i of this._registry.keys())i.startsWith(n)&&(this._registry.delete(i),this._registeredIds.delete(i),this._miniGraph.remove(i),s.push(i));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(),i=createRootFrame(s,this._limits);return this._invokeInternal(e,t,i)}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(),i=createRootFrame(s,this._limits);return this._invokeInternalAsync(e,t,i)}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),i=this._batch.actions.filter(o=>s.has(o.id));this._emitter.emit("register",{actions:i,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(),i=createRootFrame(s,this._limits);return this._invokeInteractiveInternal(e,t,i)}_invokeInteractiveInternal(e,t,n){let s=this._prepareInvoke(e,t,n);if("success"in s)return Re(s,this._isAsync);let{stored:i,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return Re(ue(u.data,o.counters),this._isAsync)}let c;if(i.compiled&&i.compiled.isInteractive&&!this._autoStepDirectives)c=i.compiled.fn(o,o.scope,i.compiled.$);else {let u=this._interactiveExecutor;c=u(i.directives,o,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives,this._autoStepDirectives);}return Je(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,this._autoStepDirectives)}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:i,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return ue(u.data,o.counters)}let c;if(i.compiled?c=i.compiled.fn(o,a,i.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(i.compiled=this._compileAction(e,i.directives),c=i.compiled.fn(o,a,i.compiled.$)):(c=this._directiveRunner(i.directives,o),this._maybeAutoPromote(i)),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:i,childFrame:o,childScope:a}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,t,o);if(u?.skip)return ue(u.data,o.counters)}let c;if(i.compiled?c=await i.compiled.fn(o,a,i.compiled.$):(c=await this._directiveRunner(i.directives,o),this._maybeAutoPromote(i)),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 Me(e,n.counters);if(e.includes("/")&&!this._isAccessible(e,n))return Pe(e,n.counters);if(n.depth>=n.limits.maxDepth)return He(e,n.limits.maxDepth,n.counters);let i=Object.create(n.scope);t&&Object.assign(i,t);let o=n.child("action:"+e,0,e).withScope(i);return {stored:s,childFrame:o,childScope:i}}_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),i=Be(this._definitions,s,this._interactiveHandlerSet),{fn:o,isAsync:a,isInteractive:c}=Ae(t,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,n,s,i),u=ne(this._definitions,a,c),l={d:t,h:u,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:o,$:l,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),i=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=we(c.directives,this._typeField,this._definitions,this._subDirectiveFieldsForGraph,this._interactiveHandlerSet,y=>this._miniGraph.isInteractive(y),isGeneratorFunction);if(u.size===0)continue;let l=s.has(a);for(let y of u){let v=`Action "${a}" is transitively interactive but handler "${y}" has no executeInteractive variant (and execute is not a generator function, and interactive flag is not set)`;l?(t.push({actionId:a,error:v,code:"MISSING_INTERACTIVE_VARIANT"}),i.add(a)):n.push({actionId:a,code:"MISSING_INTERACTIVE_VARIANT",message:v});}}if(i.size>0){for(let a of i)this._registry.delete(a),this._registeredIds.delete(a),this._miniGraph.remove(a);this._miniGraph.recompute();}return {validRegistered:e.filter(a=>!i.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 It(r){return new Ee(r)}export{j as RESERVED_TYPES,Z as SimpleEmitter,Ae as buildActionExecutor,It as createActionEngine,ce as createDirectiveInterpreter,Xe as drainAsync,Qe as drainSync,N as normalizeDirectives,Ze as replayResponder};
|