aktion-runtime 0.5.5 → 0.5.7

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 (37) hide show
  1. package/README.md +120 -15
  2. package/dist/aktion.iife.js +42 -42
  3. package/dist/aktion.iife.js.map +1 -1
  4. package/dist/aktion.js +12655 -12123
  5. package/dist/aktion.js.map +1 -1
  6. package/dist/aktion.umd.cjs +42 -42
  7. package/dist/aktion.umd.cjs.map +1 -1
  8. package/dist/language.js +1348 -98
  9. package/dist/language.js.map +1 -1
  10. package/dist/plugin.cjs +12 -2
  11. package/dist/plugin.cjs.map +1 -1
  12. package/dist/plugin.js +12 -2
  13. package/dist/plugin.js.map +1 -1
  14. package/dist/system_prompt.txt +40 -8
  15. package/dist/system_prompt_chat.txt +2 -1
  16. package/dist/testing.js +15415 -14698
  17. package/dist/testing.js.map +1 -1
  18. package/dist/types/element.d.ts +0 -1
  19. package/dist/types/language/builtins.d.ts +52 -0
  20. package/dist/types/language/index.d.ts +5 -2
  21. package/dist/types/language-api.d.ts +5 -1
  22. package/dist/types/library/components/helpers.d.ts +0 -5
  23. package/dist/types/library/components/wrappers.d.ts +1 -0
  24. package/dist/types/parser/types.d.ts +0 -1
  25. package/dist/types/runtime/effects.d.ts +1 -18
  26. package/dist/types/runtime/evaluator.d.ts +46 -5
  27. package/dist/types/runtime/http.d.ts +41 -0
  28. package/dist/types/runtime/index.d.ts +2 -1
  29. package/dist/types/runtime/router.d.ts +28 -2
  30. package/dist/types/runtime/toast.d.ts +45 -0
  31. package/dist/types/runtime/util.d.ts +11 -1
  32. package/dist/types/tooling/index.d.ts +6 -0
  33. package/dist/types/tooling/language-service.d.ts +10 -5
  34. package/dist/types/tooling/navigation.d.ts +91 -0
  35. package/dist/types/tooling/semantic-tokens.d.ts +24 -0
  36. package/dist/types/tooling/signature-help.d.ts +21 -0
  37. package/package.json +1 -1
package/README.md CHANGED
@@ -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
@@ -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
@@ -441,7 +452,11 @@ $app(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 @@ $app(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,8 +557,9 @@ $app(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
@@ -549,6 +576,7 @@ $app(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`. |
@@ -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
@@ -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() {
@@ -745,6 +796,17 @@ $app(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
 
@@ -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` |
@@ -1115,6 +1178,16 @@ stay in sync with the URL (`#/dashboard`, `#/users/42`). Browser
1115
1178
  back/forward, bookmarks, and deep links all work — and the host page
1116
1179
  never reloads.
1117
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
+
1118
1191
  ```js
1119
1192
  pages = $router({
1120
1193
  "/": homePage,
@@ -1302,7 +1375,9 @@ import {
1302
1375
  - `getDiagnostics`, `getCompletions`, and `getHoverInfo` are the data
1303
1376
  layer a real LSP server would wrap. The
1304
1377
  [playground](https://asfand-dev.github.io/aktion/playground.html)
1305
- 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.
1306
1381
 
1307
1382
  ---
1308
1383
 
@@ -1350,6 +1425,11 @@ import aktion from "aktion-runtime/vite";
1350
1425
  export default { plugins: [aktion()] };
1351
1426
  ```
1352
1427
 
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.
1432
+
1353
1433
  ```jsonc
1354
1434
  // tsconfig.json — resolve `import app from "./app.aktion"`
1355
1435
  { "compilerOptions": { "types": ["aktion-runtime/aktion-modules"] } }
@@ -1382,9 +1462,15 @@ el.mountCompiled(defineCompiledProgram({ __aktionCompiled: 1, program, source, p
1382
1462
  ### Editor support
1383
1463
 
1384
1464
  The [Aktion VS Code extension](./editors/vscode/) treats `.aktion` as
1385
- TypeScript (highlighting) and adds inline diagnostics, hover, completions, and
1386
- snippets via the DOM-free `aktion-runtime/language` API. Its README covers local
1387
- F5 debugging **and** publishing to the VS Code Marketplace + Open VSX.
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.
1388
1474
 
1389
1475
  ### Package entry points
1390
1476
 
@@ -1392,7 +1478,7 @@ F5 debugging **and** publishing to the VS Code Marketplace + Open VSX.
1392
1478
  | ------------------------------- | ------- | --------------------------------------------------------------------------- |
1393
1479
  | `aktion-runtime` | browser | `<aktion-app>` + `mountCompiled` + the browser-safe linker (`linkProject`) |
1394
1480
  | `aktion-runtime/vite` | Node | the Vite/Rollup plugin (`aktion()`) |
1395
- | `aktion-runtime/language` | Node | DOM-free diagnostics / hover / completions / snippets (editors, LSP) |
1481
+ | `aktion-runtime/language` | Node | DOM-free diagnostics / hover / completions / signature help / definition / references / rename / document symbols / semantic tokens / formatting / snippets (editors, LSP) |
1396
1482
  | `aktion-runtime/aktion-modules` | types | ambient `*.aktion` module declarations |
1397
1483
 
1398
1484
  The plugin + language service ship as separate entries and never enter the
@@ -1419,6 +1505,15 @@ consumes from the CDN.
1419
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. |
1420
1506
  | `javascript-interactions.html` | Effect + action bodies — the JavaScript execution surface. |
1421
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. |
1422
1517
  | `themes.html` | Built-in themes gallery, live picker, side-by-side compare, and the token customization studio. |
1423
1518
  | `examples.html` | Curated showcase of real-world block UIs (auth, products, FAQ, cart, todos, …). |
1424
1519
  | `playground.html` | CodeMirror 6 editor with custom highlighting / autocomplete, live preview, share links, hover-over component info, and an inspection mode. |
@@ -1622,6 +1717,16 @@ builds, tests, and publishes.
1622
1717
 
1623
1718
  ---
1624
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
+
1625
1730
  ## Contributing
1626
1731
 
1627
1732
  Contributions are very welcome. The fastest path is: