aktion-runtime 0.5.3 → 0.5.5

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.
Files changed (46) hide show
  1. package/README.md +126 -31
  2. package/dist/aktion.iife.js +106 -460
  3. package/dist/aktion.iife.js.map +1 -1
  4. package/dist/aktion.js +5688 -5055
  5. package/dist/aktion.js.map +1 -1
  6. package/dist/aktion.umd.cjs +106 -460
  7. package/dist/aktion.umd.cjs.map +1 -1
  8. package/dist/devtools.js +1367 -0
  9. package/dist/devtools.js.map +1 -0
  10. package/dist/language.js +15311 -0
  11. package/dist/language.js.map +1 -0
  12. package/dist/plugin.cjs +2650 -0
  13. package/dist/plugin.cjs.map +1 -0
  14. package/dist/plugin.js +2650 -0
  15. package/dist/plugin.js.map +1 -0
  16. package/dist/system_prompt.txt +164 -447
  17. package/dist/system_prompt_chat.txt +33 -84
  18. package/dist/testing.js +29496 -0
  19. package/dist/testing.js.map +1 -0
  20. package/dist/types/aktion-modules.d.ts +18 -0
  21. package/dist/types/compiler/index.d.ts +12 -0
  22. package/dist/types/compiler/linker.d.ts +27 -0
  23. package/dist/types/compiler/project.d.ts +45 -0
  24. package/dist/types/compiler/runtime.d.ts +59 -0
  25. package/dist/types/devtools/hook.d.ts +88 -0
  26. package/dist/types/devtools/index.d.ts +35 -0
  27. package/dist/types/devtools/panel.d.ts +109 -0
  28. package/dist/types/devtools/protocol.d.ts +130 -0
  29. package/dist/types/devtools/styles.d.ts +7 -0
  30. package/dist/types/element.d.ts +76 -8
  31. package/dist/types/index.d.ts +1 -0
  32. package/dist/types/language-api.d.ts +15 -0
  33. package/dist/types/parser/types.d.ts +38 -1
  34. package/dist/types/plugin/index.d.ts +17 -0
  35. package/dist/types/renderer/renderer.d.ts +28 -0
  36. package/dist/types/runtime/builtins.d.ts +5 -11
  37. package/dist/types/runtime/effects.d.ts +15 -0
  38. package/dist/types/runtime/http.d.ts +0 -1
  39. package/dist/types/testing/index.d.ts +201 -0
  40. package/dist/types/theme/index.d.ts +3 -3
  41. package/dist/types/theme/styles.d.ts +1 -1
  42. package/dist/types/tooling/formatter.d.ts +7 -1
  43. package/dist/types/tooling/index.d.ts +0 -3
  44. package/package.json +35 -2
  45. package/dist/types/library/components/theme.d.ts +0 -2
  46. package/dist/types/tooling/codemod.d.ts +0 -36
@@ -1,3 +1,4 @@
1
+ import { CompiledProgram } from './compiler/runtime.js';
1
2
  import { DeltaOp } from './tooling/index.js';
2
3
  import { ComponentSpec } from './library/types.js';
3
4
  import { PromptOptions } from './prompt/generator.js';
@@ -19,6 +20,20 @@ export declare class AktionElement extends HTMLElement {
19
20
  private rootEl;
20
21
  private errorEl;
21
22
  private currentResponse;
23
+ /**
24
+ * Pre-parsed AST injected by `mountCompiled(...)` (the multi-file linker
25
+ * path). When set, `replan()` consumes it instead of calling
26
+ * `parse(currentResponse)`, then clears it so a later string update
27
+ * (`setResponse` / `appendChunk`) re-parses normally. `null` for the
28
+ * ordinary streamed-string path.
29
+ */
30
+ private pendingCompiled;
31
+ /**
32
+ * Module id of the compiled program currently mounted (from
33
+ * `CompiledProgram.path`), or `null` for the string path. Exposed via the
34
+ * `sourceId` getter so HMR / host tooling can target the right instances.
35
+ */
36
+ private compiledSourceId;
22
37
  private renderScheduled;
23
38
  /** True when the program text changed and the runtime needs a re-plan. */
24
39
  private programDirty;
@@ -47,12 +62,18 @@ export declare class AktionElement extends HTMLElement {
47
62
  private forceFullRender;
48
63
  private parseErrors;
49
64
  /**
50
- * Token keys most recently applied by an in-script `Theme({...})`
65
+ * Token keys most recently applied by an in-script `$theme({...})`
51
66
  * declaration. We remember them so the next render can clear stale
52
- * overrides — otherwise switching from a `Theme(...)` block to the
67
+ * overrides — otherwise switching from a `$theme(...)` block to the
53
68
  * base theme would leave the previous tokens stuck on the host.
54
69
  */
55
70
  private scriptThemeKeys;
71
+ /** Stable DevTools id for this element (`aktion-app-N`). */
72
+ private readonly devtoolsId;
73
+ /** Monotonic commit sequence for the render profiler (0 = initial mount). */
74
+ private devtoolsCommitId;
75
+ /** True once this element has been registered with the DevTools hook. */
76
+ private devtoolsRegistered;
56
77
  constructor();
57
78
  connectedCallback(): void;
58
79
  disconnectedCallback(): void;
@@ -115,6 +136,24 @@ export declare class AktionElement extends HTMLElement {
115
136
  programText: string;
116
137
  state: Record<string, unknown>;
117
138
  }): void;
139
+ /**
140
+ * Mount a linked / compiled program — the artefact produced by `linkProject`
141
+ * (multi-file modules) or `compileLite`. The pre-parsed AST is rendered
142
+ * directly, skipping the runtime parser; the runtime still re-validates
143
+ * against the active library on `replan()`, so a host that has called
144
+ * `registerComponents(...)` stays correct even if the program was linked
145
+ * against the default library.
146
+ *
147
+ * The string path (`setResponse`, `appendChunk`, `response`) is unaffected.
148
+ * Pass `state` to seed reactive values before the first render (SSR
149
+ * hydration; preserving live `$state` across a re-mount / hot edit).
150
+ */
151
+ mountCompiled(compiled: CompiledProgram, state?: Record<string, unknown>): void;
152
+ /**
153
+ * Module id of the compiled program currently mounted, or `null` when the
154
+ * element is driven by the streamed-string path.
155
+ */
156
+ get sourceId(): string | null;
118
157
  /** Append a streaming chunk and re-render. */
119
158
  appendChunk(chunk: string): void;
120
159
  setTheme(theme: ThemeInput): void;
@@ -138,6 +177,34 @@ export declare class AktionElement extends HTMLElement {
138
177
  set showErrors(value: boolean);
139
178
  /** Dispatch a custom event from `emit()` calls in effect/action bodies. */
140
179
  private emitCustomEvent;
180
+ /**
181
+ * Register this element with the global DevTools hook (idempotent). The
182
+ * exposed record only grants a debugger the operations it legitimately
183
+ * needs — read state, push an edit, read the program, force a render —
184
+ * never the raw runtime internals. A no-op when no hook is installed.
185
+ */
186
+ private registerWithDevtools;
187
+ /**
188
+ * Public DevTools entry point: attach to a hook that was installed *after*
189
+ * this element mounted. The in-page panel calls this on every
190
+ * `<aktion-app>` it finds when it opens, so late-attaching DevTools picks up
191
+ * already-running apps. Idempotent; safe to call repeatedly.
192
+ */
193
+ connectDevtools(): void;
194
+ /**
195
+ * Apply a DevTools-originated edit to a reactive atom. Dotted paths
196
+ * (`user.name`) write through `setPath` so the root is reconstructed
197
+ * immutably and dependents wake; bare names go through `set`. Either way the
198
+ * normal reactive flush → render pipeline runs, so the edit behaves exactly
199
+ * like one an event handler would make.
200
+ */
201
+ private applyDevtoolsStateEdit;
202
+ /**
203
+ * Stamp `appId` + `time` onto an effect-runner payload and forward it to the
204
+ * hook. The runner already gated on `isDevtoolsActive()` before calling, so
205
+ * by the time we're here a frontend is listening.
206
+ */
207
+ private emitDevtoolsEffect;
141
208
  private buildInlineStyle;
142
209
  /**
143
210
  * Start the router so the hash listener is attached and `route` is
@@ -159,12 +226,13 @@ export declare class AktionElement extends HTMLElement {
159
226
  private handleRouteChange;
160
227
  private applyThemeFromAttribute;
161
228
  /**
162
- * Look for a `theme = Theme({...})` (or any binding returning a
163
- * `ThemeNode`) in the active program. If found, write its tokens to the
164
- * host as CSS custom properties so the in-script declaration layers on
165
- * top of the attribute / `setTheme()` base. The previous render's keys
166
- * are cleared first so removing a `Theme(...)` line snaps the renderer
167
- * back to the underlying theme without a reload.
229
+ * Look for the reserved `theme` binding in the active program — set by a
230
+ * bare `$theme({...})` statement or an explicit `theme = $theme({...})`
231
+ * assignment (or any binding returning a `ThemeNode`). If found, write
232
+ * its tokens to the host as CSS custom properties so the in-script
233
+ * declaration layers on top of the attribute / `setTheme()` base. The
234
+ * previous render's keys are cleared first so removing a `$theme(...)`
235
+ * line snaps the renderer back to the underlying theme without a reload.
168
236
  */
169
237
  private applyScriptThemeOverrides;
170
238
  private scheduleRender;
@@ -7,6 +7,7 @@ export * from './renderer/index.js';
7
7
  export * from './prompt/index.js';
8
8
  export * from './theme/index.js';
9
9
  export * from './language/index.js';
10
+ export * from './compiler/index.js';
10
11
  declare global {
11
12
  interface HTMLElementTagNameMap {
12
13
  "aktion-app": AktionElement;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `aktion-runtime/language` — the DOM-free language + tooling surface.
3
+ *
4
+ * Editors (the VS Code extension, a future LSP), CLIs, and any Node host that
5
+ * needs diagnostics / completions / hover / snippets / grammar metadata import
6
+ * this instead of the package root. The root entry (`aktion-runtime`) defines
7
+ * the `<aktion-app>` custom element — `class AktionElement extends HTMLElement`
8
+ * plus a top-level `defineElement()` — which throws in a non-DOM runtime. This
9
+ * module pulls in NONE of that: everything re-exported here is pure and
10
+ * Node-safe (no DOM access at import time).
11
+ */
12
+ export { getDiagnostics, getCompletions, getHoverInfo, type Position, type Diagnostic, type CompletionItem, type HoverInfo, } from './tooling/language-service.js';
13
+ export { getLanguageSpec, grammarSpec, keywordDocs, getComponentCatalog, getSnippets, type LanguageSpec, type GrammarSpec, type ComponentEntry, type ComponentParam, type SnippetEntry, type KeywordDoc, } from './language/index.js';
14
+ export { defaultLibrary } from './library/index.js';
15
+ export type { ComponentLibrary } from './library/types.js';
@@ -201,6 +201,37 @@ export interface AssignmentStatement {
201
201
  identifier: string;
202
202
  isState: boolean;
203
203
  expression: Expression;
204
+ /**
205
+ * True when prefixed with `export` (multi-file modules). Used by the linker
206
+ * to decide importability; the streaming runtime ignores it.
207
+ */
208
+ exported?: boolean;
209
+ loc?: SourceLocation;
210
+ }
211
+ /**
212
+ * Single specifier in an `import { … } from "./mod.aktion"`. Names are stored
213
+ * WITHOUT the leading `$`; `isState` records that the surface syntax used `$`
214
+ * (so `import { $shared }` and `export $shared = …` line up by bare name).
215
+ */
216
+ export interface ImportSpecifier {
217
+ /** Name as exported by the source module (bare, no `$`). */
218
+ imported: string;
219
+ /** Local alias bound in this module (bare, no `$`). */
220
+ local: string;
221
+ /** True when the binding is a `$state` atom. */
222
+ isState?: boolean;
223
+ }
224
+ /**
225
+ * `import { A, B as C, $shared } from "./other.aktion"` — named imports for
226
+ * multi-file `.aktion` programs. Resolved + merged into a single program by the
227
+ * linker (`linkProgram` / `linkProject`); the streaming runtime treats `Import`
228
+ * as a no-op (it has no module map to resolve against).
229
+ */
230
+ export interface ImportStatement {
231
+ kind: "Import";
232
+ specifiers: ReadonlyArray<ImportSpecifier>;
233
+ /** Raw module specifier, e.g. "./components/counter.aktion". */
234
+ source: string;
204
235
  loc?: SourceLocation;
205
236
  }
206
237
  /**
@@ -215,6 +246,8 @@ export interface ComponentDeclaration {
215
246
  /** Names of the declared slots (from props object convention). */
216
247
  slots: ReadonlyArray<string>;
217
248
  body: BlockExpr;
249
+ /** True when prefixed with `export` (multi-file modules). */
250
+ exported?: boolean;
218
251
  loc?: SourceLocation;
219
252
  }
220
253
  /**
@@ -294,6 +327,8 @@ export interface ActionDeclaration {
294
327
  params: ReadonlyArray<DeclParam>;
295
328
  optimistic: boolean;
296
329
  body: BlockExpr;
330
+ /** True when prefixed with `export` (multi-file modules). */
331
+ exported?: boolean;
297
332
  loc?: SourceLocation;
298
333
  }
299
334
  /**
@@ -319,6 +354,8 @@ export interface HookDeclaration {
319
354
  name: string;
320
355
  params: ReadonlyArray<DeclParam>;
321
356
  body: BlockExpr;
357
+ /** True when prefixed with `export` (multi-file modules). */
358
+ exported?: boolean;
322
359
  loc?: SourceLocation;
323
360
  }
324
361
  /** `await expr` statement / expression — only valid inside `function`/`effect`. */
@@ -458,7 +495,7 @@ export interface TryStatement {
458
495
  finallyBlock?: BlockExpr;
459
496
  loc?: SourceLocation;
460
497
  }
461
- export type Statement = AssignmentStatement | ComponentDeclaration | EffectDeclaration | ActionDeclaration | HookDeclaration | AwaitStatement | ReturnStatement | ExpressionStatement | IfStatement | SwitchStatement | ForOfStatement | ForClassicStatement | ForInStatement | WhileStatement | DoWhileStatement | DestructureStatement | BreakStatement | ContinueStatement | ThrowStatement | TryStatement;
498
+ export type Statement = AssignmentStatement | ImportStatement | ComponentDeclaration | EffectDeclaration | ActionDeclaration | HookDeclaration | AwaitStatement | ReturnStatement | ExpressionStatement | IfStatement | SwitchStatement | ForOfStatement | ForClassicStatement | ForInStatement | WhileStatement | DoWhileStatement | DestructureStatement | BreakStatement | ContinueStatement | ThrowStatement | TryStatement;
462
499
  export interface Program {
463
500
  statements: Statement[];
464
501
  errors: ParseError[];
@@ -0,0 +1,17 @@
1
+ import { Plugin } from 'vite';
2
+ export interface AktionPluginOptions {
3
+ /** Treat linker warnings (e.g. a missing `aktion` entry) as build errors. Default: false. */
4
+ strict?: boolean;
5
+ /** Specifier the emitted module imports the runtime helper from. Default: `"aktion-runtime"`. */
6
+ runtimeModuleId?: string;
7
+ }
8
+ /**
9
+ * Add to `vite.config.ts`:
10
+ *
11
+ * import aktion from "aktion-runtime/vite";
12
+ * export default { plugins: [aktion()] };
13
+ */
14
+ export declare function aktionPlugin(options?: AktionPluginOptions): Plugin;
15
+ /** True for `*.aktion` ids (query/hash stripped). Exported for tests. */
16
+ export declare function isAktionId(id: string): boolean;
17
+ export { aktionPlugin as default };
@@ -2,6 +2,7 @@ import { EvaluationContext, ScopedEffectDecl } from '../runtime/evaluator.js';
2
2
  import { StateStore } from '../runtime/state.js';
3
3
  import { Router } from '../runtime/router.js';
4
4
  import { ComponentLibrary } from '../library/types.js';
5
+ import { ComponentRenderRecord } from '../devtools/protocol.js';
5
6
  export interface RenderOptions {
6
7
  library: ComponentLibrary;
7
8
  state: StateStore;
@@ -94,7 +95,32 @@ export declare class Renderer {
94
95
  private changedPaths;
95
96
  /** Whether memoization may apply this render (false on mount / replan / notify). */
96
97
  private memoEnabled;
98
+ /**
99
+ * When `true`, each render appends a {@link ComponentRenderRecord} per
100
+ * visited instance to {@link profilerRecords}. Toggled by the host element
101
+ * once a DevTools frontend is actually listening, so a closed inspector
102
+ * costs nothing. See `setProfiling`.
103
+ */
104
+ private profiling;
105
+ /** Per-commit profiler records, drained by the host after each render. */
106
+ private profilerRecords;
107
+ /**
108
+ * Every instance key seen in a *previous* render, so the profiler can label
109
+ * a record `mount` (first sighting) vs `update`. Pruned in `endRender` so it
110
+ * tracks exactly the live tree. Only maintained while profiling.
111
+ */
112
+ private profiledInstances;
97
113
  constructor(options: RenderOptions);
114
+ /**
115
+ * Enable/disable the render profiler. The host element flips this on when a
116
+ * DevTools frontend subscribes and off when it disconnects, so the common
117
+ * (no-DevTools) path never allocates a record or reads the clock.
118
+ */
119
+ setProfiling(enabled: boolean): void;
120
+ /** Hand the current commit's component records to the host, then clear. */
121
+ drainProfilerRecords(): ComponentRenderRecord[];
122
+ /** Tree depth for flamegraph indentation — one level per `#instance` segment. */
123
+ private depthOf;
98
124
  /**
99
125
  * Swap the component library backing this renderer. Used when the host
100
126
  * element calls `registerComponents(...)` after first paint — preserves
@@ -124,6 +150,8 @@ export declare class Renderer {
124
150
  * disappeared from the tree so the map doesn't grow unbounded.
125
151
  */
126
152
  endRender(): void;
153
+ /** Record one component instance's contribution to the current commit. */
154
+ private profile;
127
155
  private safeDispose;
128
156
  /**
129
157
  * Apply a state write addressed by either a plain atom name
@@ -5,24 +5,18 @@
5
5
  * has been removed. Programs now reach for equivalent native
6
6
  * JavaScript or the `Util` namespace (see `./util.ts`).
7
7
  */
8
- export type BuiltinFn = (args: unknown[]) => unknown;
9
- /**
10
- * Empty registry kept as a structural placeholder so the parser's
11
- * synthetic `BuiltinCall` nodes (`__rui_assign__`, `__rui_postfix__`,
12
- * `__rui_prefix__`, `__rui_await__`) flow through the evaluator without
13
- * a surprise lookup.
14
- */
15
- export declare const dataBuiltins: Record<string, BuiltinFn>;
16
8
  /**
17
9
  * Marker emitted by the `Theme({...})` construct. Carries an arbitrary token
18
10
  * map that the element applies on top of the base theme between render
19
11
  * cycles. Distinct from `ComponentNode` so the renderer can ignore it (it is
20
12
  * a side-effect, not a piece of UI to draw).
21
13
  *
22
- * Authors declare a theme like any other top-level binding:
14
+ * Authors apply a theme with a bare top-level `$theme({...})` statement
15
+ * (no binding needed); the equivalent `theme = $theme({...})` form also
16
+ * works and registers the same reserved `theme` binding:
23
17
  *
24
- * theme = Theme({ colors: { primary: "#0969da" }, radius: { button: "6px" } })
25
- * root = Stack([...])
18
+ * $theme({ colors: { primary: "#0969da" }, radius: { button: "6px" } })
19
+ * root = Stack([...])
26
20
  */
27
21
  export interface ThemeNode {
28
22
  kind: "Theme";
@@ -1,12 +1,21 @@
1
1
  import { ActionDeclaration, EffectDeclaration } from '../parser/types.js';
2
2
  import { EvaluationContext, ScopedEffectDecl } from './evaluator.js';
3
3
  import { StateStore } from './state.js';
4
+ import { EffectEventPayload } from '../devtools/protocol.js';
4
5
  export interface EffectRunnerOptions {
5
6
  state: StateStore;
6
7
  /** Called whenever an effect mutates state or completes — schedules render. */
7
8
  notify: () => void;
8
9
  /** Called when the effect/action body emits a CustomEvent via `emit()`. */
9
10
  onEmit?: (eventName: string, detail: unknown) => void;
11
+ /**
12
+ * DevTools instrumentation sink. Called on every effect lifecycle
13
+ * transition (mount / run / cleanup / unmount / error) with everything the
14
+ * runner can compute on its own; the host stamps on `appId` + `time`. Only
15
+ * invoked while a DevTools frontend is actually attached, so it costs
16
+ * nothing when the inspector is closed.
17
+ */
18
+ onEffectEvent?: (payload: EffectEventPayload) => void;
10
19
  }
11
20
  export declare class EffectRunner {
12
21
  private readonly options;
@@ -42,6 +51,12 @@ export declare class EffectRunner {
42
51
  unmountInstance(instanceKey: string): void;
43
52
  reset(): void;
44
53
  private mount;
54
+ /**
55
+ * Build and dispatch one DevTools effect event. Returns immediately when no
56
+ * frontend is attached, so the only cost on the hot path is a single
57
+ * global-property read.
58
+ */
59
+ private emitEffect;
45
60
  private unmount;
46
61
  }
47
62
  export interface ActionRunnerOptions {
@@ -70,7 +70,6 @@ export declare class HttpRuntime {
70
70
  /**
71
71
  * Issue a single HTTP request. Runs through `onRequest`/`onResponse`
72
72
  * interceptors and surfaces a `retry()` one-shot inside `onResponse`.
73
- * Honours `defaults.timeoutMs` via `AbortController`.
74
73
  */
75
74
  request(input: HttpRequest): Promise<HttpResponse>;
76
75
  }
@@ -0,0 +1,201 @@
1
+ import { ComponentSpec } from '../library/types.js';
2
+ import { ThemeInput } from '../theme/index.js';
3
+ /** The public surface of the `<aktion-app>` element this library drives. */
4
+ export type AktionApp = HTMLElement & {
5
+ setResponse(text: string): void;
6
+ appendChunk(chunk: string): void;
7
+ serializeState(): Record<string, unknown>;
8
+ hydrateState(snapshot: Record<string, unknown>): void;
9
+ setTheme(theme: ThemeInput): void;
10
+ registerComponents(components: ComponentSpec[], rootName?: string): void;
11
+ navigate(path: string): void;
12
+ clear(): void;
13
+ route: string;
14
+ streaming: boolean;
15
+ showErrors: boolean;
16
+ };
17
+ /** A value the fetch mock may return; normalised into a real `Response`. */
18
+ export type MockResult = Response | string | {
19
+ status?: number;
20
+ json?: unknown;
21
+ body?: BodyInit | null;
22
+ headers?: Record<string, string>;
23
+ };
24
+ /** The fetch mock handler — receives the resolved URL and the `fetch` init. */
25
+ export type FetchHandler = (url: string, init: RequestInit & {
26
+ method: string;
27
+ }) => MockResult | Promise<MockResult>;
28
+ /** A request the mock fetch observed, captured for assertions. */
29
+ export interface CapturedRequest {
30
+ url: string;
31
+ method: string;
32
+ headers: Record<string, string>;
33
+ body: unknown;
34
+ }
35
+ export interface RenderOptions {
36
+ /** Theme name (`"dark"`) or a token map applied before the first render. */
37
+ theme?: ThemeInput;
38
+ /** Seed reactive `$state` before the program plans (inject props / spies). */
39
+ state?: Record<string, unknown>;
40
+ /** Host-registered custom components (TypeScript `ComponentSpec`s). */
41
+ components?: ComponentSpec[];
42
+ /** Initial hash route, e.g. `"/orders/42"`. */
43
+ route?: string;
44
+ /** Mock the global `fetch` used by `$http(...)` for the lifetime of the test. */
45
+ fetch?: FetchHandler;
46
+ /**
47
+ * Custom `$emit("name", ...)` event names to capture from the first render.
48
+ * The built-ins (`assistant-message`, `route-change`, `error`) are always
49
+ * captured; custom events need their name listed here (or a `screen.listen`
50
+ * call) BEFORE they fire, since their names aren't known in advance.
51
+ */
52
+ captureEvents?: string[];
53
+ /** Mount in this element instead of `document.body`. */
54
+ container?: HTMLElement;
55
+ /** Render the in-shadow parse-error banner (off by default). */
56
+ showErrors?: boolean;
57
+ }
58
+ export interface ComponentRenderOptions extends RenderOptions {
59
+ /** DSL statements injected ABOVE the `$app(expression)` line (helpers, state). */
60
+ setup?: string;
61
+ }
62
+ export interface TextMatchOptions {
63
+ /** Exact normalised-text match (default `true`); `false` => substring. */
64
+ exact?: boolean;
65
+ }
66
+ export interface WaitForOptions {
67
+ /** Give up after this many ms (default 1000). */
68
+ timeout?: number;
69
+ /** Poll interval in ms (default 20). */
70
+ interval?: number;
71
+ }
72
+ /** A string, regex, or predicate used to match an element's accessible text. */
73
+ export type Matcher = string | RegExp | ((content: string, element: Element) => boolean);
74
+ /**
75
+ * Drain the microtask queue so Aktion's state-flush → render cascade settles.
76
+ * Aktion schedules both state notifications and renders with `queueMicrotask`,
77
+ * so a handful of turns is enough for any synchronous chain (a click that
78
+ * writes state, which re-derives a computed atom, which re-renders).
79
+ */
80
+ export declare function flush(times?: number): Promise<void>;
81
+ /**
82
+ * Run `fn` (which may trigger reactive writes / handlers) and then flush —
83
+ * the Aktion equivalent of React's `act(...)`. Returns whatever `fn` returns.
84
+ */
85
+ export declare function act<T>(fn: () => T | Promise<T>): Promise<T>;
86
+ /**
87
+ * Poll `fn` until it returns a truthy / non-empty value or `timeout` elapses.
88
+ * Use it (or the `findBy*` queries built on it) to await async work —
89
+ * `$http(...)` resolutions, `setTimeout`, debounced effects.
90
+ */
91
+ export declare function waitFor<T>(fn: () => T, opts?: WaitForOptions): Promise<T>;
92
+ /** A captured DOM/custom event with its `detail` payload. */
93
+ export interface CapturedEvent {
94
+ type: string;
95
+ detail: unknown;
96
+ event: Event;
97
+ }
98
+ export interface Screen {
99
+ /** The mounted `<aktion-app>` element. */
100
+ readonly container: AktionApp;
101
+ /** The element's shadow root (where the program renders). */
102
+ readonly shadowRoot: ShadowRoot;
103
+ /** Captured fetch requests (empty unless a `fetch` mock was supplied). */
104
+ readonly requests: ReadonlyArray<CapturedRequest>;
105
+ getByText(matcher: Matcher, options?: TextMatchOptions): HTMLElement;
106
+ queryByText(matcher: Matcher, options?: TextMatchOptions): HTMLElement | null;
107
+ getAllByText(matcher: Matcher, options?: TextMatchOptions): HTMLElement[];
108
+ queryAllByText(matcher: Matcher, options?: TextMatchOptions): HTMLElement[];
109
+ findByText(matcher: Matcher, options?: TextMatchOptions, wait?: WaitForOptions): Promise<HTMLElement>;
110
+ findAllByText(matcher: Matcher, options?: TextMatchOptions, wait?: WaitForOptions): Promise<HTMLElement[]>;
111
+ getByRole(role: string, options?: {
112
+ name?: Matcher;
113
+ }): HTMLElement;
114
+ queryByRole(role: string, options?: {
115
+ name?: Matcher;
116
+ }): HTMLElement | null;
117
+ getAllByRole(role: string, options?: {
118
+ name?: Matcher;
119
+ }): HTMLElement[];
120
+ findByRole(role: string, options?: {
121
+ name?: Matcher;
122
+ }, wait?: WaitForOptions): Promise<HTMLElement>;
123
+ getByLabelText(matcher: Matcher, options?: TextMatchOptions): HTMLElement;
124
+ queryByLabelText(matcher: Matcher, options?: TextMatchOptions): HTMLElement | null;
125
+ getByPlaceholderText(matcher: Matcher, options?: TextMatchOptions): HTMLElement;
126
+ queryByPlaceholderText(matcher: Matcher, options?: TextMatchOptions): HTMLElement | null;
127
+ getByTestId(id: string): HTMLElement;
128
+ queryByTestId(id: string): HTMLElement | null;
129
+ readonly user: UserEvent;
130
+ /** Click a button/link/[role=button] found by its text, or click an element. */
131
+ click(target: string | Element): Promise<void>;
132
+ /** Type into a field found by label/placeholder/role, or into an element. */
133
+ type(target: string | Element, text: string): Promise<void>;
134
+ fireEvent(el: Element, type: string, init?: EventInit): Promise<void>;
135
+ readonly state: StateProbe;
136
+ /** Await an atom until `predicate(value)` holds (or it becomes non-null). */
137
+ waitForState(name: string, predicate?: (value: unknown) => boolean, wait?: WaitForOptions): Promise<unknown>;
138
+ readonly events: ReadonlyArray<CapturedEvent>;
139
+ /** Start capturing a custom `$emit(...)` event type (call before the trigger). */
140
+ listen(type: string): void;
141
+ emitted(type?: string): unknown[];
142
+ lastEvent(type: string): unknown;
143
+ waitForEvent(type: string, wait?: WaitForOptions): Promise<unknown>;
144
+ navigate(path: string): Promise<void>;
145
+ readonly route: string;
146
+ rerender(program: string): Promise<void>;
147
+ appendChunk(chunk: string): Promise<void>;
148
+ stream(chunks: string[]): Promise<void>;
149
+ setStreaming(value: boolean): void;
150
+ setTheme(theme: ThemeInput): Promise<void>;
151
+ flush(times?: number): Promise<void>;
152
+ unmount(): void;
153
+ html(): string;
154
+ debug(el?: Element): void;
155
+ }
156
+ export interface UserEvent {
157
+ click(el: Element): Promise<void>;
158
+ type(el: Element, text: string): Promise<void>;
159
+ clear(el: Element): Promise<void>;
160
+ selectOption(select: Element, value: string): Promise<void>;
161
+ check(el: Element): Promise<void>;
162
+ uncheck(el: Element): Promise<void>;
163
+ keyboard(el: Element, key: string): Promise<void>;
164
+ hover(el: Element): Promise<void>;
165
+ unhover(el: Element): Promise<void>;
166
+ submit(form: Element): Promise<void>;
167
+ }
168
+ export interface StateProbe {
169
+ /** Read one atom from the live snapshot (`serializeState()[name]`). */
170
+ get(name: string): unknown;
171
+ /** Whether the atom currently exists. */
172
+ has(name: string): boolean;
173
+ /** The full reactive snapshot — ideal for `toMatchSnapshot()`. */
174
+ snapshot(): Record<string, unknown>;
175
+ /** Simulate a host-side write (`hydrateState`) and re-render. */
176
+ set(name: string, value: unknown): Promise<void>;
177
+ }
178
+ /**
179
+ * Mount an Aktion program in a real `<aktion-app>` and return a `Screen`
180
+ * scoped to its shadow root. Renders synchronously enough that the returned
181
+ * screen's `getBy*` queries see the first paint; use `findBy*` / `waitFor`
182
+ * for anything that resolves after an effect, timer, or `$http(...)` request.
183
+ */
184
+ export declare function render(program: string, options?: RenderOptions): Screen;
185
+ /**
186
+ * Render a single component expression in isolation — sugar over `render`
187
+ * that wraps the expression in `$app(...)` and lets you prepend `setup` DSL
188
+ * (helper functions, seed state). Capture interactions the idiomatic Aktion
189
+ * way (write a `$state` flag or `$emit(...)` inside an inline handler) and
190
+ * assert with `screen.state` / `screen.emitted`.
191
+ *
192
+ * renderComponent(`Button("Save", { onClick: () => $saved = true })`)
193
+ */
194
+ export declare function renderComponent(expression: string, options?: ComponentRenderOptions): Screen;
195
+ /**
196
+ * Unmount every screen created since the last cleanup and restore any mocked
197
+ * `fetch`. Call from your runner's `afterEach` for isolated tests.
198
+ */
199
+ export declare function cleanup(): void;
200
+ /** Convenience for building a JSON `MockResult` in a `fetch` handler. */
201
+ export declare function json(data: unknown, status?: number): MockResult;
@@ -11,8 +11,8 @@
11
11
  * - "skyline" (deep navy + cyan, crisp & calm)
12
12
  *
13
13
  * Consumers can also pass a JSON object via the `theme` attribute, call
14
- * `element.setTheme({...})`, or declare `theme = Theme({...})` inside a
15
- * Aktion program. All three paths flow through `mergeTheme`
14
+ * `element.setTheme({...})`, or write a bare `$theme({...})` statement
15
+ * inside a Aktion program. All three paths flow through `mergeTheme`
16
16
  * so partial token maps are layered on top of the `light` defaults.
17
17
  *
18
18
  * Token taxonomy:
@@ -168,7 +168,7 @@ export declare function clearTokenOverrides(host: HTMLElement, keys: ReadonlyArr
168
168
  /**
169
169
  * Filter an arbitrary object down to the keys recognised by `ThemeTokens`,
170
170
  * stringifying primitive values along the way. Used when an Aktion program
171
- * declares `theme = Theme({...})` — the evaluator hands us
171
+ * applies `$theme({...})` — the evaluator hands us
172
172
  * a plain JS object, and we want to ignore anything that isn't a real token
173
173
  * (LLM typo guard) before applying it.
174
174
  */