aktion-runtime 0.5.4 → 0.5.6

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 (82) hide show
  1. package/README.md +206 -125
  2. package/dist/aktion.iife.js +106 -460
  3. package/dist/aktion.iife.js.map +1 -1
  4. package/dist/aktion.js +13612 -12644
  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/{node/index-8OvnOYPI.js → language.js} +14789 -12298
  11. package/dist/language.js.map +1 -0
  12. package/dist/plugin.cjs +2660 -0
  13. package/dist/plugin.cjs.map +1 -0
  14. package/dist/plugin.js +2660 -0
  15. package/dist/plugin.js.map +1 -0
  16. package/dist/system_prompt.txt +200 -451
  17. package/dist/system_prompt_chat.txt +35 -85
  18. package/dist/testing.js +30190 -0
  19. package/dist/testing.js.map +1 -0
  20. package/dist/types/aktion-modules.d.ts +6 -10
  21. package/dist/types/compiler/index.d.ts +9 -11
  22. package/dist/types/compiler/linker.d.ts +11 -11
  23. package/dist/types/compiler/project.d.ts +45 -0
  24. package/dist/types/compiler/runtime.d.ts +22 -26
  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 +56 -25
  31. package/dist/types/index.d.ts +1 -1
  32. package/dist/types/language/builtins.d.ts +52 -0
  33. package/dist/types/language/index.d.ts +5 -2
  34. package/dist/types/language-api.d.ts +12 -8
  35. package/dist/types/library/components/helpers.d.ts +0 -5
  36. package/dist/types/library/components/wrappers.d.ts +1 -0
  37. package/dist/types/parser/types.d.ts +8 -9
  38. package/dist/types/plugin/index.d.ts +13 -6
  39. package/dist/types/renderer/renderer.d.ts +28 -0
  40. package/dist/types/runtime/builtins.d.ts +5 -11
  41. package/dist/types/runtime/effects.d.ts +16 -18
  42. package/dist/types/runtime/evaluator.d.ts +46 -5
  43. package/dist/types/runtime/http.d.ts +41 -1
  44. package/dist/types/runtime/index.d.ts +2 -1
  45. package/dist/types/runtime/router.d.ts +28 -2
  46. package/dist/types/runtime/toast.d.ts +45 -0
  47. package/dist/types/runtime/util.d.ts +11 -1
  48. package/dist/types/testing/index.d.ts +201 -0
  49. package/dist/types/theme/index.d.ts +3 -3
  50. package/dist/types/theme/styles.d.ts +1 -1
  51. package/dist/types/tooling/formatter.d.ts +7 -1
  52. package/dist/types/tooling/index.d.ts +6 -3
  53. package/dist/types/tooling/language-service.d.ts +10 -5
  54. package/dist/types/tooling/navigation.d.ts +91 -0
  55. package/dist/types/tooling/semantic-tokens.d.ts +24 -0
  56. package/dist/types/tooling/signature-help.d.ts +21 -0
  57. package/package.json +21 -19
  58. package/dist/node/compile-BUw0GAvN.cjs +0 -491
  59. package/dist/node/compile-BUw0GAvN.cjs.map +0 -1
  60. package/dist/node/compile-DxttTzo8.js +0 -492
  61. package/dist/node/compile-DxttTzo8.js.map +0 -1
  62. package/dist/node/compiler.cjs +0 -11
  63. package/dist/node/compiler.cjs.map +0 -1
  64. package/dist/node/compiler.js +0 -11
  65. package/dist/node/compiler.js.map +0 -1
  66. package/dist/node/index-8OvnOYPI.js.map +0 -1
  67. package/dist/node/index-DBgA3bHQ.cjs +0 -14069
  68. package/dist/node/index-DBgA3bHQ.cjs.map +0 -1
  69. package/dist/node/language.cjs +0 -1244
  70. package/dist/node/language.cjs.map +0 -1
  71. package/dist/node/language.js +0 -1244
  72. package/dist/node/language.js.map +0 -1
  73. package/dist/node/vite.cjs +0 -65
  74. package/dist/node/vite.cjs.map +0 -1
  75. package/dist/node/vite.js +0 -65
  76. package/dist/node/vite.js.map +0 -1
  77. package/dist/types/compiler/compile.d.ts +0 -54
  78. package/dist/types/compiler/emit.d.ts +0 -15
  79. package/dist/types/compiler/sourcemap.d.ts +0 -40
  80. package/dist/types/library/components/theme.d.ts +0 -2
  81. package/dist/types/plugin/vite.d.ts +0 -21
  82. package/dist/types/tooling/codemod.d.ts +0 -36
package/README.md CHANGED
@@ -13,10 +13,10 @@ renderer for an LLM's response.
13
13
  ```html
14
14
  <script type="module" src="https://asfand-dev.github.io/aktion/dist/aktion.js"></script>
15
15
  <aktion-app theme="light">
16
- aktion = Card([
16
+ $app(Card([
17
17
  CardHeader("Hello", { subtitle: "Generative UI in plain HTML" }),
18
18
  Markdown("This card was streamed in as **plain text**.")
19
- ])
19
+ ]))
20
20
  </aktion-app>
21
21
  ```
22
22
 
@@ -82,8 +82,9 @@ Everything you need at runtime ships in a single bundle:
82
82
  `value: $form.email`), and a **`$util` runtime namespace** of pure
83
83
  helpers (`$util.filter`, `$util.sort`, `$util.find`, `$util.groupBy`,
84
84
  `$util.format`, `$util.formatDate`, `$util.plural`, `$util.case`,
85
- `$util.range`, `$util.pick`, …) callable from Aktion expressions and
86
- ordinary JavaScript alike.
85
+ `$util.range`, `$util.pick`, `$util.omit`, `$util.merge`,
86
+ `$util.cloneDeep`, `$util.chunk`, `$util.partition`, `$util.keyBy`, …)
87
+ callable from Aktion expressions and ordinary JavaScript alike.
87
88
  - **One component-call shape.** Every call follows the trailing-object
88
89
  rule — `Component(positionalArg, { prop: value, … })`. At most one
89
90
  positional argument; every other argument goes in a trailing
@@ -99,6 +100,13 @@ Everything you need at runtime ships in a single bundle:
99
100
  lowercase. `$storage.set/get` (localStorage by default),
100
101
  `$storage.session.*`, `$storage.cookies.*` with object-literal options,
101
102
  and `console.log/error/warn/info/debug`.
103
+ - **`$toast` — imperative notifications.** A reserved namespace that owns the
104
+ toast lifecycle so you never hand-manage a `$toasts = [...]` array.
105
+ `$toast.show(message, { tone?, title?, duration? })` (auto-dismisses after
106
+ `duration` ms, default `4000`; `0` keeps it), plus shortcuts
107
+ `$toast.success/.error/.info/.warning`, `$toast.dismiss(id)`,
108
+ `$toast.clear()`, and a reactive `$toast.items` list to render with
109
+ `Toasts`/`Toast`.
102
110
  - **A React-like DOM reconciler.** Diffs each re-render against the live
103
111
  DOM. Text-input value, selection, IME state, scroll positions,
104
112
  `<details>.open`, and stateful primitives like `Tabs` are all preserved
@@ -131,8 +139,8 @@ Everything you need at runtime ships in a single bundle:
131
139
  - **Seven built-in themes** (`light`, `dark`, `neon`, `pastel`, `glass`,
132
140
  `brutalist`, `skyline`) plus full custom-token support via CSS custom
133
141
  properties. **50+ design tokens** organised into `colors`, `radius`,
134
- `font`, `motion`, and `elevation` groups. Brand the UI from inside
135
- the script with `theme = $theme({...})`.
142
+ and `font` groups. Brand the UI from inside the script with
143
+ `$theme({...})` statement.
136
144
  - **`$i18n` factory.** `const { t, setCurrentLanguage, getCurrentLanguage } = $i18n({ defaultLanguage, currentLanguage, translations })` builds a translation bundle keyed by language, with `{name}` placeholder interpolation.
137
145
  - **Font Awesome 6.7.2** auto-loaded — every `icon` prop accepts a Free
138
146
  Font Awesome name (no `fa-` prefix). Use `Icon(name, { variant?, size? })`
@@ -212,18 +220,18 @@ Three equivalent ways:
212
220
 
213
221
  ```html
214
222
  <!-- as an attribute -->
215
- <aktion-app response='aktion = Card([CardHeader("Hi")])'></aktion-app>
223
+ <aktion-app response='$app(Card([CardHeader("Hi")]))'></aktion-app>
216
224
 
217
225
  <!-- as inner text (rendered on connect) -->
218
226
  <aktion-app>
219
- aktion = Card([CardHeader("Hi")])
227
+ $app(Card([CardHeader("Hi")]))
220
228
  </aktion-app>
221
229
 
222
230
  <!-- as a property/method -->
223
231
  <script>
224
232
  const el = document.querySelector("aktion-app");
225
233
  el.setResponse(`
226
- aktion = Column([greeting])
234
+ $app(Column([greeting]))
227
235
  greeting = Card([CardHeader("Hello", { subtitle: "Generative UI in plain HTML" })])
228
236
  `);
229
237
  </script>
@@ -298,6 +306,9 @@ All members live on the `<aktion-app>` element.
298
306
  | `streaming` | `true` / unset | Hint that text is still being appended. The error banner is suppressed while set. |
299
307
  | `response` | Aktion text | Sets the program declaratively. Re-renders whenever the attribute changes. |
300
308
  | `showerrors` | `true` / unset | If present and `true`, displays parse errors in the rendered UI. Defaults to off. |
309
+ | `strict` | `true` / unset | Dev/strict mode. Surfaces silent failures as `console.warn`s — unknown identifiers that would resolve to `null`, and trailing `{...}` objects passed to a user component whose keys match no parameter (the silent named→positional flip). Off by default; enable while developing. |
310
+ | `router-mode` | `hash` (default) / `history` | URL strategy. `history` uses the History API for clean `/about` URLs (needs an `index.html` fallback on the server); `hash` works on any static host. |
311
+ | `router-base` | path string (e.g. `/app`) | Sub-directory the SPA is served under, stripped from / prepended to URLs in `history` mode. |
301
312
 
302
313
  Routing and JavaScript execution inside `effect` / action bodies are
303
314
  always available — no host attribute, no allow-list. To omit those
@@ -329,7 +340,6 @@ surfaces from the *generated prompt*, build it via
329
340
  | `hydrateState(snapshot)` | Apply a snapshot to the live store and schedule a re-render. Atoms not in the snapshot are untouched. |
330
341
  | `loadSnapshot({ programText, state })` | Atomic program + state load. The next render plans the program with the hydrated state already in place. |
331
342
  | `applyDelta(ops)` | Apply a structured delta (`patch` / `replace` / `append` / `new` / `delete`). User `$state` is preserved across the diff. |
332
- | `mountCompiled(compiled, state?)` | Mount a build-time-compiled program (from the [Vite/Rollup plugin](#build-time-compiler--multi-file-modules) or `compile()`), skipping the runtime parser. Optional `state` seeds reactive values (SSR / HMR). |
333
343
 
334
344
  ### Events
335
345
 
@@ -408,13 +418,14 @@ pages = $router({
408
418
  default: NotFound()
409
419
  })
410
420
 
411
- aktion = pages
421
+ $app(pages)
412
422
  ```
413
423
 
414
424
  ### Key constructs
415
425
 
416
- - `aktion = …` — the reserved entry point. Every program renders from
417
- it.
426
+ - `$app(…)` — the reserved entry point. Every program renders from
427
+ it. It accepts a single root node, an array of nodes (rendered as
428
+ siblings), or variadic nodes.
418
429
  - `$name = value` — reactive state. One kind. Read or write with the
419
430
  same sigil. Inside action / effect / lambda bodies, assignment
420
431
  operators (`= += -= *= /= ??= ++ --`) are all allowed.
@@ -441,7 +452,11 @@ aktion = pages
441
452
  `props` object — every parameter is a real JS parameter.
442
453
  - `function name(args) { body }` — camelCase name means it's an action.
443
454
  Callable effects with optional `return`. Used as event handlers
444
- (`onClick: save`) or as expressions (`$result = greet("Ada")`).
455
+ (`onClick: save`) or as expressions (`$result = greet("Ada")`). Wrap
456
+ optimistic writes in `$optimistic(() => { … })` — it snapshots reactive
457
+ state, runs the callback, and automatically rolls back if the callback
458
+ throws (or the promise it returns rejects). An ordinary `$`-prefixed
459
+ builtin call, so it works anywhere an expression does.
445
460
  - `$effect(() => { body }, [...deps])` — declarative, anonymous side
446
461
  effects. The dependency array mixes state triggers (`$atom`),
447
462
  lifecycle / interval triggers (`"mount"`, `"unmount"`, `"every(N)"`),
@@ -495,6 +510,17 @@ aktion = pages
495
510
  `.status`, `.loading`, `.headers`, `.lastUpdated`, `.refetch()`,
496
511
  `.cancel()`, and a settable `.onDone` callback that fires each time the
497
512
  request settles (handy for `$todos.refetch()` after a write).
513
+ - `$query({ url, key?, ttl? })` — a **cached, deduplicated** read built on
514
+ `$http`. Identical queries (same `key`, or same method + url + query +
515
+ body) share one in-flight request and one cached bag, so the same data
516
+ fetched from several components hits the network once. Optional `ttl` (ms)
517
+ auto-refetches stale data. Same reactive bag as `$http`.
518
+ - `$mutation({ url, method? })` — a **deferred** write that fires only when
519
+ you call `.mutate(overrides?)` (not on render; `method` defaults to
520
+ `POST`). The bag exposes `.loading` / `.error` / `.data`, plus `.reset()`
521
+ and a settable `.onDone`. `.mutate()` resolves with the response body.
522
+ Assign it to an atom and trigger it from a handler:
523
+ `$save = $mutation({ url }); Button("Save", { onClick: () => $save.mutate({ body: $form }) })`.
498
524
  - `pages = $router({ "/path": Component(), default: NotFound() })` —
499
525
  function-call router. The reserved `route` handle exposes the
500
526
  reactive surface (`route.path`, `route.params`, `route.query`,
@@ -531,14 +557,15 @@ aktion = pages
531
557
  - **`$util` runtime namespace** — pure, side-effect-free helpers for data
532
558
  shaping, formatting, dates, math, and strings (`$util.filter`, `$util.sort`,
533
559
  `$util.groupBy`, `$util.format`, `$util.formatDate`, `$util.plural`, `$util.range`,
534
- `$util.addDays`, `$util.pick`, `$util.count`, …). Never carry hidden state —
535
- safe to call anywhere.
560
+ `$util.addDays`, `$util.pick`, `$util.omit`, `$util.merge`, `$util.cloneDeep`,
561
+ `$util.chunk`, `$util.partition`, `$util.keyBy`, `$util.zip`, `$util.flatten`,
562
+ `$util.count`, …). Never carry hidden state — safe to call anywhere.
536
563
  - **Escape hatches** — `HTMLTag(tag, { attributes?, children? })` for
537
564
  raw HTML elements and `Styles(css)` for raw CSS injected into the
538
565
  shadow root. Use only when the standard component library cannot
539
566
  express the design.
540
567
  - **Hoisting & streaming** — references resolve from the entire
541
- top-level scope, not source order. Always emit `aktion = …` first
568
+ top-level scope, not source order. Always call `$app(…)` first
542
569
  so the reconciler has the page shell to attach streamed leaves to.
543
570
  - Comments: `//` line comments and `/* block */` comments — standard
544
571
  JS style.
@@ -549,6 +576,7 @@ aktion = pages
549
576
  | --------- | -------------------------------------------------------------------- |
550
577
  | `$storage` | Browser persistence — `$storage.set/get`, `$storage.session.*`, `$storage.cookies.*`. |
551
578
  | `$console` | Forwards to the host console — `log` / `error` / `warn` / `info` / `debug`. |
579
+ | `$toast` | Imperative notifications — `$toast.show/.success/.error/.info/.warning`, `.dismiss(id)`, `.clear()`, reactive `.items`. |
552
580
  | `route` | Reactive router handle — `path`, `params`, `query`, `pattern`, `navigate(path)`. |
553
581
  | JS stdlib | The JS standard library — `Math`, `JSON`, `Object`, `Array`, `Number`, `String`, `Boolean`, `Date`, `Map`, `Set`, `RegExp`, `Promise`, plus `parseInt` / `parseFloat` / `isNaN` / `isFinite` / `encodeURIComponent` / … Use directly (`Math.max(a, b)`, `JSON.stringify(x)`, `Object.keys(o)`) or with `new` (`new Date()`, `new Map()`). |
554
582
  | timers | `setTimeout` / `setInterval` / `clearTimeout` / `clearInterval` — like their JS counterparts, but tracked by the runtime and cleared automatically on re-plan/disconnect. Use inside an `effect` and clear in `cleanup`. |
@@ -578,7 +606,7 @@ chart = LineChart({
578
606
  series: [Series("Events", $data.data?.daily?.events ?? [])]
579
607
  })
580
608
 
581
- aktion = Column([CardHeader("Analytics"), filter, kpi, chart])
609
+ $app(Column([CardHeader("Analytics"), filter, kpi, chart]))
582
610
  ```
583
611
 
584
612
  Highlights:
@@ -593,7 +621,7 @@ Highlights:
593
621
  plus pluck (`$rows.title` → `[title1, title2, …]`).
594
622
  - Responsive prop maps on layout components:
595
623
  `Grid(items, { columns: { sm: 1, md: 2, lg: 4 }, gap: "l" })`.
596
- - Forward references are allowed — list `aktion = Column([...])` first
624
+ - Forward references are allowed — call `$app(Column([...]))` first
597
625
  and let the children stream in beneath it.
598
626
 
599
627
  ### Declarative todo app
@@ -617,11 +645,11 @@ row = t => Card([Stack([
617
645
  ])])
618
646
 
619
647
  list = $todos.map(t => row(t))
620
- aktion = Stack([
648
+ $app(Stack([
621
649
  Input("draft-input", { placeholder: "What needs doing?", value: $draft }),
622
650
  Button("Add", { onClick: add, variant: "primary" }),
623
651
  list
624
- ])
652
+ ]))
625
653
  ```
626
654
 
627
655
  ### Fine-grained reactivity
@@ -694,6 +722,20 @@ binding if you want it skipped. State changes the path-tracker can't see
694
722
  > component does re-execute, Aktion rebuilds its render tree and the morph
695
723
  > reconciler patches only the DOM that actually differs.
696
724
 
725
+ > [!IMPORTANT]
726
+ > **Path-tracking applies to `$name = value` atoms only.** The other state
727
+ > sources — the `$state` / `$memo` / `$ref` / `$reducer` hook setters, `$http`
728
+ > / `$query` / `$mutation` lifecycle changes, `setTimeout` / `setInterval`
729
+ > ticks, `$effect` writes, and `$emit` — cannot be path-tracked, so each of
730
+ > them triggers a **full re-render** (the morph reconciler still patches only
731
+ > the changed DOM, but every component body re-executes). This is the single
732
+ > most important performance characteristic to internalise: a hook-heavy
733
+ > component tree loses the fine-grained skipping you get from plain atoms.
734
+ > Prefer top-level `$name = value` atoms for app state on the hot path, and
735
+ > reach for hooks when you specifically need per-instance isolation, accepting
736
+ > the full-re-render cost. See the "Reactivity" section of
737
+ > [`coding-gen-skill.md`](./coding-gen-skill.md) for the full model.
738
+
697
739
  ### Per-instance state & content-addressed identity
698
740
 
699
741
  ```js
@@ -706,7 +748,7 @@ function Counter(label) {
706
748
  }
707
749
 
708
750
  // Two independent counters — each holds its own atom.
709
- aktion = Stack([Counter("A"), Counter("B")])
751
+ $app(Stack([Counter("A"), Counter("B")]))
710
752
  ```
711
753
 
712
754
  Every call site accepts a universal `key` named argument. The renderer
@@ -719,12 +761,21 @@ function TaskRow(task) {
719
761
  }
720
762
  ```
721
763
 
722
- ### Hooks — `$state`, `$memo`, and custom `$name`
764
+ ### Hooks — `$state`, `$memo`, `$ref`, `$reducer`, `$id`, and custom `$name`
723
765
 
724
766
  A function whose name starts with `$` is a **hook**, mirroring React's
725
767
  `use*` convention. Hooks are the composable way to manage per-instance
726
- state. Built-in `$state` and `$memo` mirror React's `useState` and
727
- `useMemo`:
768
+ state. The built-in hooks mirror their React counterparts one-to-one:
769
+
770
+ | Hook | React equivalent | Returns |
771
+ | --- | --- | --- |
772
+ | `$state(initial)` | `useState` | `[value, setValue]` |
773
+ | `$memo(() => v, [deps])` | `useMemo` | cached value |
774
+ | `$ref(initial)` | `useRef` | stable `{ current }` box (writes don't re-render) |
775
+ | `$reducer((state, action) => next, initial)` | `useReducer` | `[state, dispatch]` |
776
+ | `$id(prefix?)` | `useId` | stable unique id per instance |
777
+
778
+ `$state` and `$memo` are the everyday pair:
728
779
 
729
780
  ```js
730
781
  function Counter() {
@@ -736,7 +787,7 @@ function Counter() {
736
787
  ])
737
788
  }
738
789
 
739
- aktion = Counter()
790
+ $app(Counter())
740
791
  ```
741
792
 
742
793
  - `$state(initial)` returns a `[value, setValue]` pair. `setValue(next)`
@@ -745,6 +796,17 @@ aktion = Counter()
745
796
  - `$memo(() => compute, [deps])` returns a cached value and recomputes
746
797
  only when a dependency changes (shallow `Object.is` compare). Omit the
747
798
  deps array to recompute every render.
799
+ - `$ref(initial)` returns a stable mutable `{ current }` box whose identity
800
+ persists across renders. Writing `ref.current = …` does **not** schedule
801
+ a re-render — the escape hatch for holding a DOM node, a timer id, or a
802
+ previous value. Pair it with `OnMount(child, { onMount: node => ref.current = node })`
803
+ to grab a rendered DOM node.
804
+ - `$reducer((state, action) => next, initial)` returns `[state, dispatch]`.
805
+ `dispatch(action)` runs the reducer and re-renders when the result
806
+ changes — the clean way to manage many related state transitions.
807
+ - `$id(prefix?)` returns a stable, unique string id for the instance's
808
+ lifetime — for wiring `for` / `id` / `aria-labelledby` pairs without
809
+ hard-coding ids that collide across multiple instances.
748
810
 
749
811
  Declare your own hooks with `function $name(...)`. A custom hook's
750
812
  body runs **inline in the calling component's hook scope**, so its
@@ -767,7 +829,8 @@ Two rules, both inherited from React: call hooks **unconditionally and in
767
829
  a stable order** at the top level of a component / hook body (slots are
768
830
  matched by call order across renders), and remember that hook state
769
831
  **resets when the instance leaves the tree** — a remounted component
770
- starts again from its initial value. `$state` and `$memo` are reserved
832
+ starts again from its initial value. `$state`, `$memo`, `$ref`,
833
+ `$reducer`, and `$id` are reserved
771
834
  names. The lighter `$name = value` per-instance form above remains
772
835
  available when an atom is written directly by the component's actions.
773
836
 
@@ -793,7 +856,7 @@ cart = $store({
793
856
  // Siblings with no relationship both talk to the same cart.
794
857
  function AddLatte() { return Button("Add", { onClick: () => cart.add({ price: 4.5 }) }) }
795
858
  function MiniCart() { return Text(`${cart.count()} items — ${$util.format(cart.total(), "currency")}`) }
796
- aktion = Column([AddLatte(), MiniCart()])
859
+ $app(Column([AddLatte(), MiniCart()]))
797
860
  ```
798
861
 
799
862
  Reads are fine-grained and per-component (changing `cart.items` re-renders
@@ -813,7 +876,7 @@ tree. Two `LiveClock()` calls produce two independent intervals — and
813
876
  removing one stops only that one:
814
877
 
815
878
  ```js
816
- aktion = Stack([LiveClock("UTC"), LiveClock("Local")])
879
+ $app(Stack([LiveClock("UTC"), LiveClock("Local")]))
817
880
 
818
881
  function LiveClock(label) {
819
882
  $now = $util.now()
@@ -880,7 +943,7 @@ production-quality SaaS UI in a single line.
880
943
  | **App shell** | `AppShell`, `Sidebar`, `SidebarSection`, `SidebarItem` (supports `to` for router navigation), `SplitView` |
881
944
  | **Advanced UI** | `IconButton`, `CommandPalette`, `FilterChips`, `FieldRepeater`, `VirtualList`, `QueryBuilder`, `DiffViewer`, `JsonTree`, `Gantt`, `Truncate`, `InlineEdit`, `NotificationBell` |
882
945
  | **Helpers** | `Async`, `Show`, `Portal`, `Redirect`, `Lazy`, `ErrorBoundary` |
883
- | **Behaviour wrappers** | `OnClick`, `OnMouse`, `OnKeyboard`, `OnFocus`, `OnIntersect`, `Css`, `Link` — attach click / mouse / keyboard / focus / intersection listeners or raw class / style to ANY component without it needing a dedicated prop. `Link(label_or_child, { to?, href?, external? })` wraps either a string or a component as a router-aware anchor. |
946
+ | **Behaviour wrappers** | `OnClick`, `OnMouse`, `OnKeyboard`, `OnFocus`, `OnIntersect`, `OnMount`, `Css`, `Link` — attach click / mouse / keyboard / focus / intersection / lifecycle listeners or raw class / style to ANY component without it needing a dedicated prop. `OnMount(child, { onMount, onUnmount })` is the DOM-ref escape hatch — `onMount(node)` fires once after attach so you can measure, focus, or hand the node to an imperative library. `Link(label_or_child, { to?, href?, external? })` wraps either a string or a component as a router-aware anchor. |
884
947
  | **Escape hatches** | `HTMLTag`, `Styles` (last-resort raw HTML / CSS — see [language.html](https://asfand-dev.github.io/aktion/language.html#escape-hatches)) |
885
948
  | **Theming** | `$theme` |
886
949
  | **Routing** | `$router({ … })`, `NavLink` |
@@ -954,7 +1017,7 @@ board = KanbanBoard([
954
1017
  ])
955
1018
  follow = FollowUpBlock(["Show at-risk projects", "Compare to Q2", "Who needs help?"])
956
1019
 
957
- aktion = Column([dashHeader, kpis, board, follow])
1020
+ $app(Column([dashHeader, kpis, board, follow]))
958
1021
  ```
959
1022
 
960
1023
  ### Adding your own components
@@ -1026,12 +1089,11 @@ el.setTheme({
1026
1089
 
1027
1090
  ### `$theme({...})` from inside a response
1028
1091
 
1029
- A response can brand itself by assigning a `$theme({...})` call to the
1030
- reserved top-level `theme` binding. The tokens land on the host as CSS
1031
- variables on top of the base theme.
1092
+ A response can brand itself with a `$theme({...})` statement. The tokens land on the host as CSS variables on top
1093
+ of the base theme.
1032
1094
 
1033
1095
  ```js
1034
- theme = $theme({
1096
+ $theme({
1035
1097
  colors: {
1036
1098
  primary: "#0969da",
1037
1099
  border: "#d0d7de",
@@ -1045,12 +1107,12 @@ theme = $theme({
1045
1107
  radius: { button: "6px", input: "6px" }
1046
1108
  })
1047
1109
 
1048
- aktion = Column([CardHeader("GitHub-style page"), Buttons([Button("New repository")])])
1110
+ $app(Column([CardHeader("GitHub-style page"), Buttons([Button("New repository")])]))
1049
1111
  ```
1050
1112
 
1051
1113
  `$theme` expects the **structured** form — top-level groups `colors` /
1052
- `radius` / `font` / `motion` / `elevation` (plus metadata keys `name`
1053
- and `direction`). Removing the `$theme(...)` line snaps the UI back to
1114
+ `radius` / `font` (plus metadata keys `name` and `direction`). Removing
1115
+ the `$theme(...)` line snaps the UI back to
1054
1116
  the base theme. Unknown keys are ignored silently, so typos in an
1055
1117
  LLM-emitted token map can never break the page.
1056
1118
 
@@ -1104,7 +1166,7 @@ kpis = Stats([
1104
1166
  StatCard("Orders", { value: "1,284", trend: "up", delta: "+8%", icon: "cart-shopping" }),
1105
1167
  StatCard("Refunds", { value: "12", trend: "down", delta: "-3", icon: "rotate-left" })
1106
1168
  ])
1107
- aktion = Stack([brandIcon, kpis, profileTab])
1169
+ $app(Stack([brandIcon, kpis, profileTab]))
1108
1170
  ```
1109
1171
 
1110
1172
  ---
@@ -1116,6 +1178,16 @@ stay in sync with the URL (`#/dashboard`, `#/users/42`). Browser
1116
1178
  back/forward, bookmarks, and deep links all work — and the host page
1117
1179
  never reloads.
1118
1180
 
1181
+ Routing defaults to **hash mode**, which works on any static host with no
1182
+ server configuration. To opt into clean History-API URLs (`/dashboard`
1183
+ instead of `#/dashboard`), set `router-mode="history"` on the element (and
1184
+ `router-base` if the app is served under a sub-directory). History mode
1185
+ requires the server to fall back to `index.html` for unknown paths:
1186
+
1187
+ ```html
1188
+ <aktion-app router-mode="history" router-base="/app"></aktion-app>
1189
+ ```
1190
+
1119
1191
  ```js
1120
1192
  pages = $router({
1121
1193
  "/": homePage,
@@ -1130,7 +1202,7 @@ nav = Row([
1130
1202
  NavLink("Users", { to: "/users" })
1131
1203
  ], { gap: "s" })
1132
1204
 
1133
- aktion = Stack([nav, pages])
1205
+ $app(Stack([nav, pages]))
1134
1206
 
1135
1207
  homePage = Card([CardHeader("Welcome")])
1136
1208
  dashboardPage = Card([CardHeader("Dashboard")])
@@ -1233,10 +1305,10 @@ const i18nInstance = $i18n({
1233
1305
  currentLanguage: $lang,
1234
1306
  translations: { hi: { en: "Hi", fr: "Salut", de: "Hallo" } }
1235
1307
  })
1236
- aktion = Column([
1308
+ $app(Column([
1237
1309
  Text(i18nInstance.t("hi")),
1238
1310
  Button("Deutsch", { onClick: () => { $lang = "de" } })
1239
- ])
1311
+ ]))
1240
1312
  ```
1241
1313
 
1242
1314
  ---
@@ -1303,7 +1375,9 @@ import {
1303
1375
  - `getDiagnostics`, `getCompletions`, and `getHoverInfo` are the data
1304
1376
  layer a real LSP server would wrap. The
1305
1377
  [playground](https://asfand-dev.github.io/aktion/playground.html)
1306
- uses them under the hood.
1378
+ uses them under the hood. `getCompletions` is **scope-aware**: alongside
1379
+ the library + reserved words it surfaces the symbols declared in the
1380
+ current document — your own reactive atoms, components, and actions.
1307
1381
 
1308
1382
  ---
1309
1383
 
@@ -1311,116 +1385,104 @@ import {
1311
1385
 
1312
1386
  > **Optional.** The CDN bundle and the streamed-string path
1313
1387
  > (`<aktion-app response="...">`, `setResponse`, `appendChunk`) work exactly as
1314
- > before. This is an opt-in enhancement for NPM consumers who author UI by hand
1315
- > and want multi-file modules, type-safety, source maps, and IDE integration.
1388
+ > before. This is an opt-in enhancement for NPM consumers who author UI by hand.
1316
1389
 
1317
- When you install `aktion-runtime` from NPM you can author UI in `.aktion` files
1318
- and let a Vite/Rollup plugin **compile them at build time** into the
1319
- already-parsed, schema-validated component tree. The browser then mounts that
1320
- pre-parsed AST without running the parser. The runtime stays fully reactive —
1321
- `$state`, `$http`, effects, and routing all run in the browser as usual; only
1322
- parsing, linking, and validation move to build time.
1390
+ Author UI in `.aktion` files that `import`/`export` from one another like JS/TS
1391
+ modules, then mount the pre-parsed, linked program with
1392
+ `el.mountCompiled(program)` — the runtime parser never runs in the browser. The
1393
+ runtime stays fully reactive (`$state`, `$http`, effects, routing run as usual);
1394
+ only parsing + linking move ahead of time.
1323
1395
 
1324
- **What you get:** multi-file `import`/`export`; parse + schema errors become
1325
- **build errors** (unknown component / prop / enum, surfaced in Vite's overlay
1326
- with a code frame); a typed `CompiledProgram` default export; **source maps**
1327
- back to your `.aktion` file; and editor diagnostics/hover/completions (see
1328
- [Editor support](#editor-support)). HMR is automatic and **preserves live
1329
- `$state`** across edits — even when you edit an imported module.
1396
+ ### Multi-file modules
1330
1397
 
1331
- ### Setup
1398
+ Named `import`/`export` with **true module scope** — a file's non-exported
1399
+ top-level names are private:
1332
1400
 
1333
- ```ts
1334
- // vite.config.ts
1335
- import { defineConfig } from "vite";
1336
- import aktion from "aktion-runtime/vite";
1401
+ ```js
1402
+ // src/components/counter.aktion
1403
+ export $count = 0
1404
+ export function Counter() { return Button(`Clicked ${$count}`, { action: bump }) }
1405
+ function bump() { $count = $count + 1 } // private to this module
1337
1406
 
1338
- export default defineConfig({ plugins: [aktion()] });
1407
+ // src/app.aktion (entry — must define `aktion`)
1408
+ import { Counter, $count } from "./components/counter.aktion"
1409
+ aktion = Column([Markdown(`Shared count: ${$count}`), Counter()])
1339
1410
  ```
1340
1411
 
1341
- ```jsonc
1342
- // tsconfig.json — make TypeScript resolve `import ui from "./app.aktion"`
1343
- { "compilerOptions": { "types": ["aktion-runtime/aktion-modules"] } }
1344
- ```
1412
+ The linker merges the graph into one program, renaming each module's private
1413
+ names so two files can reuse a name without clashing; the entry keeps its own
1414
+ names canonical (the `aktion` binding + the `$state` names that `serializeState`
1415
+ / `applyDelta` target).
1345
1416
 
1346
- ### Authoring
1417
+ ### Vite plugin
1347
1418
 
1348
- A `.aktion` file is pure DSL (identical grammar to a streamed response):
1419
+ The `aktion-runtime/vite` plugin compiles `.aktion` files at build time so you
1420
+ can import them directly, with HMR that preserves live `$state`:
1349
1421
 
1422
+ ```ts
1423
+ // vite.config.ts
1424
+ import aktion from "aktion-runtime/vite";
1425
+ export default { plugins: [aktion()] };
1350
1426
  ```
1351
- // src/dashboard.aktion
1352
- $count = 0
1353
- aktion = Card([
1354
- CardHeader("Counter"),
1355
- Button(`Clicked ${$count} times`, { action: increment })
1356
- ])
1357
- function increment() { $count = $count + 1 }
1358
- ```
1359
-
1360
- ### Multi-file modules
1361
1427
 
1362
- `.aktion` files `import`/`export` like JS/TS, with **true module scope** — a
1363
- file's non-exported top-level names (components, actions, `$state`, helpers) are
1364
- private to that file:
1428
+ The plugin emits a source map that carries the original `.aktion` path and its
1429
+ contents (`sourcesContent`), so the file shows up in the browser's Sources
1430
+ panel and runtime frames resolve to your `.aktion` module rather than the
1431
+ generated JSON blob.
1365
1432
 
1366
- ```
1367
- // src/components/counter.aktion
1368
- export $count = 0
1369
- export function Counter() {
1370
- return Button(`Clicked ${$count}`, { action: bump })
1371
- }
1372
- function bump() { $count = $count + 1 } // private to this module
1433
+ ```jsonc
1434
+ // tsconfig.json — resolve `import app from "./app.aktion"`
1435
+ { "compilerOptions": { "types": ["aktion-runtime/aktion-modules"] } }
1373
1436
  ```
1374
1437
 
1375
- ```
1376
- // src/app.aktion (entry — must define `aktion`)
1377
- import { Counter, $count } from "./components/counter.aktion"
1378
- aktion = Column([Markdown(`Shared count: ${$count}`), Counter()])
1438
+ ```ts
1439
+ import "aktion-runtime";
1440
+ import app from "./app.aktion"; // a typed CompiledProgram (the linked graph)
1441
+ document.querySelector("aktion-app").mountCompiled(app);
1379
1442
  ```
1380
1443
 
1381
- Named imports only (`import { A, B as C, $shared } from "./mod.aktion"`); a
1382
- `$state` import keeps its `$`. The compiler resolves the import graph at build
1383
- time and links it into one program, renaming each module's private names so two
1384
- files can reuse a name without clashing. The **entry** keeps its own names
1385
- canonical (the `aktion` binding and the `$state` names that `serializeState` /
1386
- `applyDelta` target). Importing is a build-time feature — the streaming runtime
1387
- path stays single-file.
1444
+ Scaffold a ready-made Vite + TypeScript project with **`npm create aktion@latest`**
1445
+ (see [`create-aktion`](./create-aktion/)). A runnable example lives in
1446
+ [`examples/vite-compiler/`](./examples/vite-compiler/).
1388
1447
 
1389
- ### Mounting
1448
+ ### Link in the browser (no bundler)
1390
1449
 
1391
- ```ts
1392
- import "aktion-runtime"; // registers <aktion-app>
1393
- import app from "./app.aktion"; // a typed CompiledProgram (the whole linked graph)
1450
+ The linker is browser-safe and re-exported from the package root, so a host (or
1451
+ the playground) can link a project in-page from raw sources:
1394
1452
 
1395
- document.querySelector("aktion-app").mountCompiled(app);
1453
+ ```ts
1454
+ import { linkProject, defineCompiledProgram } from "aktion-runtime";
1455
+ const { program, source } = await linkProject({
1456
+ entry: "app.aktion",
1457
+ files: { "app.aktion": "…", "components/counter.aktion": "…" },
1458
+ });
1459
+ el.mountCompiled(defineCompiledProgram({ __aktionCompiled: 1, program, source, path: "app.aktion" }));
1396
1460
  ```
1397
1461
 
1398
- Editing any file in the graph hot-reloads in place: the plugin recompiles
1399
- (imported files are registered as watched dependencies), and the self-accepting
1400
- module re-mounts the program while replaying the current `$state` via
1401
- `serializeState()`, so live state survives the edit.
1402
-
1403
1462
  ### Editor support
1404
1463
 
1405
1464
  The [Aktion VS Code extension](./editors/vscode/) treats `.aktion` as
1406
- TypeScript (highlighting) and adds inline diagnostics, hover, completions, and
1407
- snippets via the DOM-free `aktion-runtime/language` API — the same schema-aware
1408
- language service the docs playground uses.
1465
+ TypeScript (highlighting) and layers full language intelligence on top —
1466
+ semantic highlighting, inline diagnostics, hover, scope-aware completions,
1467
+ signature help, **cross-file** go-to-definition (jump to an imported binding's
1468
+ declaration or open the module specifier's file), find-all-references, rename,
1469
+ document outline, document highlights, document formatting (format-on-save), and
1470
+ snippets — all via the DOM-free `aktion-runtime/language` API. Its public
1471
+ [README](./editors/vscode/README.md) covers install / use / update; the
1472
+ [contributor guide](./editors/vscode/docs/README.md) covers local F5 debugging,
1473
+ architecture, **and** publishing to the VS Code Marketplace + Open VSX.
1409
1474
 
1410
1475
  ### Package entry points
1411
1476
 
1412
- | Import | Runs in | Purpose |
1413
- | ------------------------------- | ------- | ------------------------------------------------------------- |
1414
- | `aktion-runtime` | browser | the `<aktion-app>` element + `mountCompiled` |
1415
- | `aktion-runtime/vite` | Node | the Vite/Rollup plugin (`aktion()`) |
1416
- | `aktion-runtime/compiler` | Node | `compile(source, opts)` for programmatic/build use |
1417
- | `aktion-runtime/language` | Node | DOM-free diagnostics/hover/completions/snippets (editors/LSP) |
1418
- | `aktion-runtime/aktion-modules` | types | ambient `*.aktion` module declarations |
1419
-
1420
- The plugin, compiler, and language service ship as a **separate Node entry**
1421
- (`dist/node/`) and never enter the browser bundle, so `dist/aktion.js` is
1422
- unchanged. A runnable example lives in
1423
- [`examples/vite-compiler/`](./examples/vite-compiler/).
1477
+ | Import | Runs in | Purpose |
1478
+ | ------------------------------- | ------- | --------------------------------------------------------------------------- |
1479
+ | `aktion-runtime` | browser | `<aktion-app>` + `mountCompiled` + the browser-safe linker (`linkProject`) |
1480
+ | `aktion-runtime/vite` | Node | the Vite/Rollup plugin (`aktion()`) |
1481
+ | `aktion-runtime/language` | Node | DOM-free diagnostics / hover / completions / signature help / definition / references / rename / document symbols / semantic tokens / formatting / snippets (editors, LSP) |
1482
+ | `aktion-runtime/aktion-modules` | types | ambient `*.aktion` module declarations |
1483
+
1484
+ The plugin + language service ship as separate entries and never enter the
1485
+ browser bundle, so `dist/aktion.js` is unchanged.
1424
1486
 
1425
1487
  ---
1426
1488
 
@@ -1443,6 +1505,15 @@ consumes from the CDN.
1443
1505
  | `side-effects.html` | `$effect(() => { … }, [...deps])` guide — anonymous side effects, dependency entries (state, lifecycle, intervals, debounce/throttle), top-level vs. component-local scope, cleanup, and effect vs. action. |
1444
1506
  | `javascript-interactions.html` | Effect + action bodies — the JavaScript execution surface. |
1445
1507
  | `routing.html` | Hash-based routing guide — always available at runtime. |
1508
+ | `reactivity.html` | Reactivity & rendering deep-dive — path tracking, the two render gates, exactly what forces a full re-render, and how to stay fine-grained. |
1509
+ | `performance.html` | Performance & optimization — re-render avoidance, memoization rules, the safety budget, bundle size, and `setResponse` vs `appendChunk`. |
1510
+ | `troubleshooting.html` | Troubleshooting / FAQ — focus loss, effects not firing, memoized-away components, the `Map` component vs JS `Map`, dropped styles, missing i18n keys. |
1511
+ | `errors.html` | Error handling & debugging — reading parse/runtime errors, the render-loop and budget guards, the `error` event, and strict mode. |
1512
+ | `typescript.html` | TypeScript guide — public types, subpath entry points, typing custom components/helpers/interceptors, host event payloads, a typed host-wrapper recipe. |
1513
+ | `recipes.html` | Recipes, patterns & anti-patterns — the A–V application patterns by task, the JS-aligned do/don't table, and the pre-ship self-check. |
1514
+ | `accessibility.html` | Accessibility guide — conformance target, keyboard map, screen-reader/streaming behaviour, built-in ARIA, and theme contrast. |
1515
+ | `deployment.html` | Production & deployment — SSR/hydration via `serializeState`, CSP and `unsafe-eval`, integrity hashes, CDN caching, edge-function LLM streaming. |
1516
+ | `llm-integration.html` | LLM integration — wiring OpenAI/Anthropic/OpenRouter/Bedrock streams into `appendChunk`, prompt selection, interceptors, the `assistant-message` round-trip. |
1446
1517
  | `themes.html` | Built-in themes gallery, live picker, side-by-side compare, and the token customization studio. |
1447
1518
  | `examples.html` | Curated showcase of real-world block UIs (auth, products, FAQ, cart, todos, …). |
1448
1519
  | `playground.html` | CodeMirror 6 editor with custom highlighting / autocomplete, live preview, share links, hover-over component info, and an inspection mode. |
@@ -1646,6 +1717,16 @@ builds, tests, and publishes.
1646
1717
 
1647
1718
  ---
1648
1719
 
1720
+ ## Versioning & stability
1721
+
1722
+ See [`CHANGELOG.md`](./CHANGELOG.md) for what changed between versions and a
1723
+ **Stability & versioning** matrix (which APIs are stable vs experimental, the
1724
+ pre-1.0 SemVer policy, and how the generated `system_prompt.txt` is versioned).
1725
+ Aktion is pre-1.0: minor versions may include behavioural changes, always
1726
+ flagged in the changelog.
1727
+
1728
+ ---
1729
+
1649
1730
  ## Contributing
1650
1731
 
1651
1732
  Contributions are very welcome. The fastest path is: