@slim-lang/core 1.2.12 → 1.2.13

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 (48) hide show
  1. package/README.md +522 -14
  2. package/package.json +2 -6
  3. package/packages/slim/server/main.slim +433 -422
  4. package/run-dev-slim.js +10 -5
  5. package/run-slim.js +10 -20
  6. package/src/bin/api/github_get.js +7 -12
  7. package/src/bin/api/github_req.js +54 -241
  8. package/src/bin/api/lock.js +2 -1
  9. package/src/bin/api/spm.js +20 -91
  10. package/src/bin/cli.js +73 -102
  11. package/src/bin/config.default.json +11 -11
  12. package/src/bin/helpers.js +2 -7
  13. package/src/bin/spm.js +3 -7
  14. package/src/checker.js +1705 -388
  15. package/src/compile.js +131 -100
  16. package/src/external/classErrors.js +5 -6
  17. package/src/external/client.js +0 -2
  18. package/src/external/core.js +355 -237
  19. package/src/external/defaults.js +12 -4
  20. package/src/external/dom.js +663 -0
  21. package/src/external/helpers.js +87 -58
  22. package/src/external/reactive.js +601 -0
  23. package/src/external/router.js +117 -0
  24. package/src/external/slim-globals.d.ts +43 -4
  25. package/src/external/typeSyntax.js +258 -0
  26. package/src/external/types.js +1 -1
  27. package/src/format.js +183 -12
  28. package/src/handlers/errorHandler.js +9 -36
  29. package/src/jsdoc.js +36 -16
  30. package/src/modulePaths.js +15 -5
  31. package/src/reactivity.js +774 -0
  32. package/src/repl.js +1 -1
  33. package/src/suggest.js +60 -0
  34. package/src/syntax/babel.js +46 -0
  35. package/src/syntax/index.js +39 -0
  36. package/src/syntax/lower.js +666 -0
  37. package/src/syntax/markup.js +195 -0
  38. package/src/syntax/plugin.js +903 -0
  39. package/src/syntax/types.js +106 -0
  40. package/src/test-runner.js +5 -5
  41. package/src/transform.js +209 -244
  42. package/packages/slim/helpers/string.js +0 -43
  43. package/packages/slim/types/hash.js +0 -11
  44. package/src/handlers/parser/components.js +0 -316
  45. package/src/handlers/parserHandler.js +0 -789
  46. package/src/lexer.js +0 -174
  47. package/src/parser.js +0 -803
  48. package/src/sourcemap.js +0 -0
package/README.md CHANGED
@@ -25,7 +25,7 @@ Slim is for projects where data validation needs to stay in the running program.
25
25
  | Runtime validation | Manual | Manual or libraries | Built in for typed values and structs |
26
26
  | Data modelling | Objects and classes | Interfaces and types | Structs, enums, defaults, inheritance, validators |
27
27
  | API and external data | Trust it or validate manually | Types are erased at runtime | Validate at the boundary with a `struct` or `type` |
28
- | Components | Native APIs or a framework | Native APIs or a framework | Components and custom elements |
28
+ | Components | Native APIs or a framework | Native APIs or a framework | Reactive components and custom elements, no virtual DOM |
29
29
  | Tooling | Depends on the project | Depends on the project | Compiler, formatter, test runner, REPL, dev server, and package manager |
30
30
 
31
31
  Slim does not aim to replace TypeScript everywhere. It is useful when runtime guarantees and built-in language tools matter.
@@ -119,12 +119,14 @@ struct User {
119
119
  const user = {
120
120
  name: "John",
121
121
  id: 3,
122
- roles: [] // null array (null[])
122
+ roles: [1, 2] // int array (int[])
123
123
  }
124
124
 
125
- User.verify(user) // ❌ StructError: "User.roles" expected string[], got null[]
125
+ User.verify(user) // ❌ StructError: "User.roles" expected string[], got int[]
126
126
  ```
127
127
 
128
+ An empty array `[]` fits any `T[]`.
129
+
128
130
  **Built-in Operators**:
129
131
 
130
132
  ```typescript
@@ -178,6 +180,13 @@ const user = {
178
180
  if(user.role == Role.Member) log(true) // true
179
181
  ```
180
182
 
183
+ `Role.from(value)` turns a raw value (from JSON, a form, a database) into an enum member and throws `EnumError` for unknown values:
184
+
185
+ ```cpp
186
+ const role = Role.from(payload.role) // Role.Admin for 2
187
+ Role.from(7) // ❌ EnumError: 7 is not a value of enum "Role"
188
+ ```
189
+
181
190
  Enum members can also be used in struct annotations:
182
191
 
183
192
  ```cpp
@@ -227,6 +236,18 @@ const { name, id }: User = payload // throws if payload is not a valid User
227
236
  const [x, y]: [int, int] = point
228
237
  ```
229
238
 
239
+ Literal types restrict a value to exact strings, numbers or booleans:
240
+
241
+ ```cpp
242
+ type Role = "admin" | "user"
243
+ type Id = int | string
244
+
245
+ func setRole(role: Role) { ... }
246
+
247
+ setRole("admin") // ok
248
+ setRole("guest") // ❌ static error: argument "role" of "setRole" expects Role, got "guest"
249
+ ```
250
+
230
251
  Types combine with `|` (union — matches any) and `&` (intersection — matches all):
231
252
 
232
253
  ```cpp
@@ -264,6 +285,15 @@ struct User {
264
285
  const u = User.new({ name: "Alice" }) // { name: "Alice", role: "member", active: true }
265
286
  ```
266
287
 
288
+ An object literal written where a struct type is declared is built the same way, with defaults, methods and readonly fields. That covers typed variables, `return` in a function with a struct return type, arrays of literals, and nested struct fields:
289
+
290
+ ```cpp
291
+ const u: User = { name: "Alice" } // same as User.new({ name: "Alice" })
292
+ const team: User[] = [{ name: "A" }, { name: "B" }]
293
+
294
+ func guest() -> User { return { name: "guest" } }
295
+ ```
296
+
267
297
  A struct can `extend` another, inheriting its fields and defaults:
268
298
 
269
299
  ```cpp
@@ -285,6 +315,33 @@ struct Greeter {
285
315
  Greeter.new({ name: "Ada" }).greet() // "Hi Ada"
286
316
  ```
287
317
 
318
+ Method calls on a struct are type-checked like function calls. A default may span several lines as long as it is inside brackets.
319
+
320
+ `readonly` fields can't be reassigned: the static checker reports it, and instances made with `Struct.new(...)` refuse the write at runtime:
321
+
322
+ ```cpp
323
+ struct Account {
324
+ readonly id: int
325
+ owner: string
326
+ }
327
+
328
+ const acc = Account.new({ id: 1, owner: "Ada" })
329
+ acc.owner = "Bob" // ok
330
+ acc.id = 2 // ❌ "Account.id" is readonly
331
+ ```
332
+
333
+ Structs can be generic. Type arguments are checked at runtime and by the static checker:
334
+
335
+ ```cpp
336
+ struct Page<T> {
337
+ items: T[]
338
+ total: int
339
+ }
340
+
341
+ const users: Page<User> = await api.users() // every item must be a valid User
342
+ Page.verify(payload, ["int"]) // same check without a typed variable
343
+ ```
344
+
288
345
  ## Return Types
289
346
 
290
347
  A function can declare its return type with `-> Type`. Slim checks each `return` and verifies the value at runtime:
@@ -362,7 +419,31 @@ match (role) {
362
419
  } // ❌ match on "Role" does not handle Role.Member — add the missing case or a "_" fallback
363
420
  ```
364
421
 
365
- Slim skips this check for guarded cases and non-enum subjects.
422
+ A case can also match by type and name the value for its branch. Over a union, every member has to be handled, the same way as an enum:
423
+
424
+ ```cpp
425
+ struct Circle { radius: float }
426
+ struct Square { side: float }
427
+ type Shape = Circle | Square
428
+
429
+ func area(s: Shape) -> float {
430
+ return match (s) {
431
+ Circle c => 3.14 * c.radius * c.radius,
432
+ Square q => q.side * q.side
433
+ }
434
+ }
435
+
436
+ func show(value: int | string | bool) {
437
+ return match (value) {
438
+ int n => "number",
439
+ string s => s
440
+ } // ❌ match on (int | string | bool) does not handle bool
441
+ }
442
+ ```
443
+
444
+ A type case may have a `when` guard too (`Square q when q.side > 10 => ...`); a guarded case doesn't count towards handling its type. A match over a union of literals (`"a" | "b"`) has to handle each value.
445
+
446
+ Slim skips the completeness check when guarded value cases are mixed in.
366
447
 
367
448
  ## Error Handling
368
449
 
@@ -384,6 +465,17 @@ test("addition works", () => {
384
465
  })
385
466
  ```
386
467
 
468
+ Tests run one after another; an `async` test is awaited before the next one starts. `describe` groups related tests:
469
+
470
+ ```cpp
471
+ describe("users", () => {
472
+ test("loads", async () => {
473
+ const user = await loadUser(1)
474
+ assertEqual(user.id, 1)
475
+ })
476
+ })
477
+ ```
478
+
387
479
  Run them all with:
388
480
 
389
481
  ```console
@@ -392,7 +484,7 @@ slmc test
392
484
 
393
485
  ## Formatting
394
486
 
395
- Reindent Slim source (strings, templates, and comments are left untouched):
487
+ Reindent Slim source by brackets and, inside components, by markup tags. Strings, template text, and comments are left untouched; method chains (`.map(...)` on the next line) are indented under their source:
396
488
 
397
489
  ```console
398
490
  slmc fmt index
@@ -440,18 +532,88 @@ greet(u) // ❌ expects 2 arguments, got 1
440
532
  log(u.nmae) // ❌ "User" has no field "nmae"
441
533
  ```
442
534
 
443
- Inference is intentionally conservative. Calls into npm packages, unknown imports, and custom `type` validators remain unknown and are checked at runtime. Slim reports only conflicts it can prove, so normal narrowing with unions remains valid:
535
+ A union only fits where every part of it fits, so an `int | string` is not an `int` and a `string?` is not a `string`. A check narrows the type for the code it guards: `if`, `? :`, `&&`, `||`, `??`, an early `return` or `throw`, `typeof`, `kindof`, `instanceof`, `== null` and `Array.isArray`:
536
+
537
+ ```cpp
538
+ func show(v: int | string, name: string?) {
539
+ let n: int = v // ❌ "n" expects int, got (int | string)
540
+
541
+ if (kindof v == "int") {
542
+ let m: int = v // ok: v is an int here
543
+ }
544
+
545
+ if (name == null) return
546
+ let s: string = name // ok: name can't be null past the return
547
+ }
548
+ ```
549
+
550
+ An optional struct field reads as `T | undefined`. Assigning a variable again after the check undoes the narrowing.
551
+
552
+ Types are inferred for unannotated constants, for `for...of` variables and for callback parameters of array methods, `Map` and `Set`. `map`, `filter`, `find`, `reduce`, string methods, `Map.get` and the like have result types, and a function without `-> T` returns what its `return` statements return:
444
553
 
445
554
  ```cpp
446
- let v: int | string = 1
555
+ func names(users: User[]) {
556
+ users.forEach(u => log(u.nmae)) // ❌ "User" has no field "nmae"
557
+ let ages: string[] = users.map(u => u.age) // ❌ expects string[], got int[]
558
+ let first: User = users.find(u => u.age > 18) // ❌ got (User | undefined)
559
+ }
560
+ ```
561
+
562
+ A `match` over a union of literals (`"a" | "b" | "c"`) has to handle each of them, just like a match over an enum.
447
563
 
448
- if (kindof v == "int") {
449
- let n: int = v // fine — the runtime confirms it
564
+ Generic functions get their type parameters from each call, and generic struct methods from the instance:
565
+
566
+ ```cpp
567
+ func first<T>(items: T[]) -> T? { return items[0] }
568
+
569
+ let n: int = first(["a"]) // ❌ "n" expects int, got string?
570
+
571
+ struct Box<T> {
572
+ value: T
573
+ set(value: T) { this.value = value }
450
574
  }
451
575
 
452
- let b: bool = v // ❌ no arm of int | string can ever be a bool
576
+ const box: Box<int> = { value: 1 }
577
+ box.set("text") // ❌ argument "value" of "Box<int>.set" expects int, got string
453
578
  ```
454
579
 
580
+ Function types keep their parameters and result. A callback passed to a typed parameter gets its parameter types from it:
581
+
582
+ ```cpp
583
+ func apply(cb: (n: int) => string, n: int) -> string { return cb(n) }
584
+
585
+ apply(n => `#${n}`, 1) // ok, n is an int
586
+ apply(n => n * 2, 1) // ❌ expects (n: int) => string, got (n: int) => int
587
+ ```
588
+
589
+ Typos get a suggestion: unknown struct fields, enum members, type names, string and array methods, and names that are not declared but look like one that is:
590
+
591
+ ```cpp
592
+ log(user.nmae) // ❌ "User" has no field "nmae" — did you mean "name"?
593
+ log(Role.Admn) // ❌ "Role" has no member "Admn" — did you mean "Admin"?
594
+ log(title.lenght) // ❌ string has no property "lenght" — did you mean "length"?
595
+ log(usres) // ❌ "usres" is not defined — did you mean "users"?
596
+ ```
597
+
598
+ A component call is checked against its props, and markup against known events and attributes:
599
+
600
+ ```cpp
601
+ component Badge({ count: int, label?: string }) {
602
+ return <span>${count} ${label ?? ""}</span>
603
+ }
604
+
605
+ Badge({ cont: 1 }) // ❌ "Badge" has no prop "cont" — did you mean "count"?
606
+ Badge({ count: "1" }) // ❌ prop "count" of "Badge" expects int, got string
607
+ Badge({ label: "a" }) // ❌ "Badge" is missing prop "count" of type int
608
+
609
+ <button onClik=${save}> // ❌ unknown event "onClik" — did you mean "onClick"?
610
+ <a herf="/"> // ❌ unknown attribute "herf" on <a> — did you mean "href"?
611
+ ```
612
+
613
+ Only names close to a known one are reported: `data-`, `aria-`, custom element and SVG attributes, and custom events like `onMyEvent` pass.
614
+
615
+ Calls into npm packages, unknown imports, and custom `type` validators stay unknown and are checked at runtime. Slim reports only conflicts it can prove.
616
+
455
617
  Checks follow `use` across files, so imported structs, enums, custom types, and function signatures are checked at their call sites:
456
618
 
457
619
  ```cpp
@@ -474,6 +636,25 @@ let n: int = greet(u) // ❌ "n" expects int, got string
474
636
 
475
637
  Inherited struct fields and types used only inside an imported module are also resolved. A local declaration takes precedence over an imported name.
476
638
 
639
+ The checker also follows `await` (calling an `async func` without it gives `Promise<T>`), checks assignments to struct fields, and checks arguments of struct methods. Circular `use` between files compiles with a warning: types from a module that is still being compiled are not known at that point.
640
+
641
+ Two common async mistakes are compile errors:
642
+
643
+ ```cpp
644
+ async func save(user: User) { ... }
645
+
646
+ async func main() {
647
+ save(user) // ❌ "save" is async and nothing awaits it
648
+ void save(user) // ok: runs in the background on purpose
649
+ users.forEach(async u => { await save(u) }) // ❌ forEach doesn't wait for async callbacks
650
+ await Promise.all(users.map(u => save(u))) // ok
651
+ }
652
+ ```
653
+
654
+ `filter`, `some`, `every` and `find` with an async callback are reported too: they get a promise, which is always truthy. Errors of async calls that nothing awaits (`main()` at the top level, `void save()`) still go through Slim's error output.
655
+
656
+ `slmc build` only compiles files that changed. A file is compiled again when its source changes or when the types of a file it uses change; changing `slimconfig.json` or updating Slim rebuilds everything. The cache lives in `slim-dist/.slim-cache.json`, and `slmc build --force` ignores it.
657
+
477
658
  Static checks run before runtime validation. Disable them with `slmc build --no-check` or in the config:
478
659
 
479
660
  ```json
@@ -485,13 +666,14 @@ Static checks run before runtime validation. Disable them with `slmc build --no-
485
666
 
486
667
  ## Release Mode
487
668
 
488
- Typed variables, parameters, and struct fields are validated at runtime by default. Production builds can remove those implicit checks while keeping explicit `struct.verify()` calls, operators, and `lock`:
669
+ Typed variables, parameters, and struct fields are validated at runtime by default. Release builds leave those implicit checks out of the generated code while keeping explicit `struct.verify()` calls, `Struct.new()`, operators, and `lock`:
489
670
 
490
671
  ```console
672
+ slmc build --release
491
673
  slmc run --release
492
674
  ```
493
675
 
494
- This sets `SLIM_RELEASE=1`. You can use the same variable when running compiled output directly:
676
+ The same can be set with `"release": true` in `slimconfig.json`. Static checks still run. Output built without release mode can skip the checks at startup instead:
495
677
 
496
678
  ```console
497
679
  SLIM_RELEASE=1 node dist/index.js
@@ -553,6 +735,289 @@ Point `package.json` at the generated entry declaration so consumers pick it up:
553
735
 
554
736
  A TypeScript project can then import `User` and `greet` from the package with type checking intact.
555
737
 
738
+ ## Components
739
+
740
+ A component returns markup. Values interpolated with `${...}` are escaped, so data from users can't inject HTML:
741
+
742
+ ```cpp
743
+ component Comment(props) {
744
+ return <p class="comment">${props.text}</p> // "<b>hi</b>" is shown as text
745
+ }
746
+ ```
747
+
748
+ Markup written in the component is markup, including markup in the body and inside interpolations. Already trusted HTML goes through `raw()`:
749
+
750
+ ```cpp
751
+ component List(props) {
752
+ const title = props.title ? <h2>${props.title}</h2> : ""
753
+ return <section>
754
+ ${title}
755
+ <ul>${props.items.map(item => <li>${item}</li>)}</ul>
756
+ <div>${raw(props.trustedHtml)}</div>
757
+ </section>
758
+ }
759
+ ```
760
+
761
+ Unquoted attribute values are quoted automatically: `<div title=${text}>`.
762
+
763
+ Text follows JSX: a line break with the indentation around it goes, lines of text are joined with a space, and text on one line keeps its spaces. `<pre>`, `<textarea>`, `<script>` and `<style>` keep everything.
764
+
765
+ A component is used as a tag, the markup inside it arrives as `children`. `<Card title="x">` is `Card({ title: "x" })`, and both forms work:
766
+
767
+ ```cpp
768
+ component Card({ title, children }) {
769
+ return <section class="card">
770
+ <h2>${title}</h2>
771
+ ${children}
772
+ </section>
773
+ }
774
+
775
+ component Page() {
776
+ return <Card title="Settings">
777
+ <p>Everything in one place.</p>
778
+ </Card>
779
+ }
780
+ ```
781
+
782
+ A capital letter makes a tag a component (`<Card>`, `<ui.Card>`). This works in component markup; markup outside components builds HTML strings, where `<Card>` is just a tag.
783
+
784
+ ## Reactivity
785
+
786
+ A `state` is a variable whose changes show up wherever it is read. The component runs once; Slim compiles its markup into a template that is cloned per use, and each `${...}` into a binding that updates only its own text node or attribute. There is no virtual DOM to build and compare:
787
+
788
+ ```cpp
789
+ component Counter() {
790
+ state count = 0
791
+ state items: string[] = []
792
+ const double = count * 2 // recomputed when count changes
793
+
794
+ effect(() => {
795
+ document.title = `Clicks: ${count}`
796
+ })
797
+
798
+ return <div>
799
+ <button onClick=${() => count++}>${count} × 2 = ${double}</button>
800
+ <button onClick=${() => items.push("item " + count)}>add</button>
801
+ ${count > 5 ? <p>That's a lot</p> : null}
802
+ <ul>${items.map(item => <li>${item}</li>)}</ul>
803
+ </div>
804
+ }
805
+ ```
806
+
807
+ - **`state name = value`** goes at the top of a component body. Assign it, increment it, or change it in place: `items.push(x)`, `items[i].done = true` and `user.name = "x"` all update what reads it. A typed state (`state count: int = 0`) is checked like a typed `let`.
808
+ - **A `const` that reads a state or props** is recomputed when they change, at most once per change and only while something reads it.
809
+ - **`effect(fn)`** runs after the component has its DOM, and again whenever what it read changes. A function it returns runs before the next run and when the component goes away.
810
+ - **`watch(() => source, (value, previous) => ...)`** reacts only to what `source` reads. `untrack(() => ...)` reads without subscribing, `batch(() => ...)` applies several changes as one.
811
+ - **Event handlers** are batched: two assignments in one click update the DOM once.
812
+ - **`cond ? <A/> : <B/>` and `cond && <A/>`** build a branch again only when the condition flips. When a branch is removed, its effects stop.
813
+ - **`items.map(item => <li>...</li>)`** keeps rows by item, or by a `key=${item.id}` on the row. Rows that stay are moved, not rebuilt; a row whose item changed in place updates only its own bindings.
814
+
815
+ Props stay live. `Badge({ count: items.length })` passes the current value on every read, so `Badge` updates its text without running again. This works for destructured props too; a default is made once per component:
816
+
817
+ ```cpp
818
+ component Badge({ count, label = "items" }) {
819
+ return <span title=${count}>${count} ${label}</span>
820
+ }
821
+ ```
822
+
823
+ Attributes follow their values. `disabled=${off}` is present or absent, `data-` and `aria-` attributes get `"true"`/`"false"`, and `value`, `checked` and `selected` also set the element property. `<input ${attrs}>` takes a string or an object of attributes. Markup inside `<svg>` is built in the SVG namespace.
824
+
825
+ ### Shared state
826
+
827
+ A `state` at the top of a module is shared by every component that reads it, in that module and in the modules that `use` it. Importers read and assign it like their own:
828
+
829
+ ```cpp
830
+ // cart.slim
831
+ export state items: Item[] = []
832
+ export const total = items.reduce((sum, item) => sum + item.price, 0)
833
+
834
+ // header.slim
835
+ use { items, total } from "./cart"
836
+
837
+ component CartBadge() {
838
+ return <span>${items.length} items, ${total} €</span>
839
+ }
840
+ ```
841
+
842
+ ### Forms
843
+
844
+ `bind:value` and `bind:checked` show a state or a field and write back what the user types. A number or range input writes a number:
845
+
846
+ ```cpp
847
+ component Signup() {
848
+ state form = { name: "", age: 18, terms: false }
849
+ return <form>
850
+ <input bind:value=${form.name}>
851
+ <input type="number" bind:value=${form.age}>
852
+ <input type="checkbox" bind:checked=${form.terms}>
853
+ </form>
854
+ }
855
+ ```
856
+
857
+ `createForm` builds a form from a struct. The struct's field types are the form's rules, the same ones its values are checked against everywhere else, on the server included:
858
+
859
+ ```cpp
860
+ type email(value: string) { return value.includes("@") }
861
+
862
+ struct Signup {
863
+ name: string
864
+ email: email
865
+ age: positive
866
+ nick?: string
867
+ }
868
+
869
+ component SignupForm() {
870
+ const form = createForm(Signup, { messages: { age: "Age must be above zero" } })
871
+ return <form onSubmit=${form.submit(save)}>
872
+ <input bind:value=${form.name}>
873
+ <input bind:value=${form.email}>
874
+ <p class="error">${form.errors.email}</p> // "expected email" once the field was changed
875
+ <input bind:value=${form.age}> // "30" typed here is the number 30
876
+ <button disabled=${!form.valid || form.submitting}>Sign up</button>
877
+ </form>
878
+ }
879
+
880
+ func save(data: Signup) { ... }
881
+ ```
882
+
883
+ A field's error shows once the field was changed or a submit was tried; an empty required field is `"required"`. `form.submit(save)` calls `save` only with valid data, as a `Signup` built like `Signup.new`, and `form.submitting` is true while a promise it returns is pending. `form.reset()` starts over, `form.values` is what was typed. The compiler knows a form has its struct's fields: `form.nmae` and `form.errors.nmae` get a did-you-mean.
884
+
885
+ ### Loading data
886
+
887
+ `resource(loader)` loads, and loads again when what the loader read before its first `await` changes. A slower, older answer never replaces a newer one:
888
+
889
+ ```cpp
890
+ component Profile({ id }) {
891
+ const user = resource(() => api.user(id))
892
+ return <section>
893
+ ${user.loading ? <p>Loading…</p> : user.error ? <p>${user.error.message}</p> : <h2>${user.value.name}</h2>}
894
+ </section>
895
+ }
896
+ ```
897
+
898
+ `user.reload()` loads again on demand, and assigning `user.value` shows a value right away (an optimistic update).
899
+
900
+ With a source, only the source is tracked and the loader is called with its value. This is the form to use with server rendering, where the data comes with the page and nothing is loaded twice:
901
+
902
+ ```cpp
903
+ const user = resource(() => id, id => api.user(id))
904
+ ```
905
+
906
+ ### Large lists
907
+
908
+ A comparison with a state in a row, like `class=${selected == row.id ? "active" : ""}`, only runs again in the two rows whose answer changes, so selecting in a list of 10,000 rows touches two of them. A row that shows its own key (`${row.id}` in a row keyed by `row.id`) shows it once, without a binding. In the browser, `onClick`, `onInput` and other bubbling events are handled by one listener on the document per event type, so rows add no listeners; a tree that is not in the document yet gets the same handling on its root.
909
+
910
+ ### Context
911
+
912
+ `provide` makes a value available to everything a component renders, however deep; `inject` reads it. A provided state stays live:
913
+
914
+ ```cpp
915
+ const Theme = createContext("light")
916
+
917
+ component App() {
918
+ state theme = "dark"
919
+ provide(Theme, theme)
920
+ return <main><Toolbar /></main>
921
+ }
922
+
923
+ component Button({ children }) {
924
+ const theme = inject(Theme) // "dark", and follows App's state
925
+ return <button class=${theme}>${children}</button>
926
+ }
927
+ ```
928
+
929
+ Without a `provide` above, `inject` gives the context's default.
930
+
931
+ ### Errors
932
+
933
+ `catchError` shows a fallback when its content throws, while it is built or later, in one of its updates. The fallback gets the error and a `reset` that tries again:
934
+
935
+ ```cpp
936
+ ${catchError(() => <Chart data=${data} />, (error, reset) =>
937
+ <p>Chart failed: ${error.message} <button onClick=${reset}>retry</button></p>)}
938
+ ```
939
+
940
+ ### Animations
941
+
942
+ `enter="name"` puts a class on an element while it appears and takes it off when its animation ends. `leave="name"` puts a class on when it is removed and removes it once its animations finish:
943
+
944
+ ```cpp
945
+ ${open && <div class="panel" enter="fade-in" leave="fade-out">...</div>}
946
+ ```
947
+
948
+ ```css
949
+ .fade-in { animation: fade 150ms reverse }
950
+ .fade-out { animation: fade 150ms forwards }
951
+ @keyframes fade { to { opacity: 0 } }
952
+ ```
953
+
954
+ `move` (or `move="300"`, in ms) makes a row slide to its new place when its list is reordered:
955
+
956
+ ```cpp
957
+ <ul>${items.map(item => <li key=${item.id} move>${item.name}</li>)}</ul>
958
+ ```
959
+
960
+ ### Routing
961
+
962
+ `<Router>` shows the page for the current path; `<Link>` and `navigate()` change it without a reload, and the back button works:
963
+
964
+ ```cpp
965
+ const routes = {
966
+ "/": Home,
967
+ "/users/:id": User, // User({ params: { id: "7" } })
968
+ "/admin": () => import("./admin.js"), // loaded the first time it is opened
969
+ "*": NotFound
970
+ }
971
+
972
+ component App() {
973
+ return <main>
974
+ <nav><Link href="/users/7" active="current">Ann</Link></nav>
975
+ <Router routes=${routes} />
976
+ </main>
977
+ }
978
+ ```
979
+
980
+ A page gets `params`, `query` and `path`. Moving between paths of the same route (`/users/7` to `/users/8`) keeps the page and updates its params. `route()` reads the current path, query and params anywhere; `active` names a class a link has while it points at the current path. On the server, pass the request's path: `<Router routes=${routes} url=${url} />`.
981
+
982
+ ### Portals
983
+
984
+ `<Portal>` shows its children somewhere else in the page, a modal in `document.body` for example. They still belong to the component that wrote them and go away with it:
985
+
986
+ ```cpp
987
+ ${open && <Portal to="#modals"><Dialog onClose=${() => { open = false }} /></Portal>}
988
+ ```
989
+
990
+ `to` is a selector or an element; without it the children go to `document.body`. A portal renders nothing on the server.
991
+
992
+ ### What the compiler checks
993
+
994
+ An event handler knows its event: `onInput=${e => age = e.target.value}` with `state age: int` is an error, `e.target.value` is a string. A change through a copy of a state is an error too, since it would not update the page:
995
+
996
+ ```cpp
997
+ const list = items
998
+ list.push(x) // ❌ "list" holds the state "items": a change through "list" doesn't update the page
999
+ ```
1000
+
1001
+ Changing a derived `const` in place is reported the same way: it is recomputed, so the change would be lost. An async effect only tracks what it reads before its first `await`.
1002
+
1003
+ Keyed tables from [bench/](bench/) against React 18.3.1 and 19.1.0 with `React.memo` rows, on one page in Chromium, taking turns sample by sample. Median in ms, lower is better; *script* is the framework's own work, *total* adds style and layout:
1004
+
1005
+ | | Slim script | React 18 script | React 19 script | Slim total | React 19 total |
1006
+ |---|---|---|---|---|---|
1007
+ | create 1,000 rows | 6.3 | 11.5 | 10.0 | 56.1 | 57.5 |
1008
+ | replace 1,000 rows | 10.8 | 22.1 | 20.3 | 64.0 | 66.3 |
1009
+ | update every 10th row | 1.0 | 1.2 | 1.4 | 9.7 | 10.2 |
1010
+ | select row | 0.1 | 0.7 | 1.0 | 0.1 | 1.0 |
1011
+ | swap rows | 0.5 | 9.2 | 9.4 | 8.8 | 58.8 |
1012
+ | remove row | 0.4 | 1.1 | 1.6 | 8.1 | 10.0 |
1013
+ | create 10,000 rows | 54.1 | 334.2 | 243.1 | 551.5 | 720.2 |
1014
+ | append 1,000 rows | 8.1 | 12.0 | 11.6 | 70.4 | 77.8 |
1015
+ | clear 1,000 rows | 4.8 | 10.5 | 10.0 | 5.0 | 10.1 |
1016
+
1017
+ Most of *total* is the browser's style and layout, which costs the same for the same rows whichever framework made them; that is why it moves less than *script*.
1018
+
1019
+ Run it with `node bench/build.mjs` and `node bench/serve.mjs`, then open `http://localhost:5178/bench/`.
1020
+
556
1021
  ## Custom Elements
557
1022
 
558
1023
  Mark a component as `element` to compile it as both a custom element and a function. `Tab` becomes `slim-tab`, `TabBar` becomes `slim-tab-bar`, and the tag is available as `Tab.tag`:
@@ -609,7 +1074,50 @@ tab.props = { label: "Overview", items: [1, 2, 3] }
609
1074
  document.body.append(tab)
610
1075
  ```
611
1076
 
612
- A tag renders on connection and when `props` changes. There is no hydration; server output is markup, not state. On the server or in an embedded engine, registration is skipped and the component remains a function.
1077
+ A tag renders once, on connection. Reassigning `props` or changing an attribute updates the bindings that read them; state inside the tag is kept. See [Server Rendering](#server-rendering) for rendering on the server and taking over in the browser. On the server or in an embedded engine, registration is skipped and the component remains a function.
1078
+
1079
+ ## Server Rendering
1080
+
1081
+ `renderToString` renders a component to HTML on the server, with markers around each `${...}`. `hydrate` runs the same component in the browser and takes over the nodes that are already there instead of building new ones, so the page is live without being drawn twice:
1082
+
1083
+ ```cpp
1084
+ // server
1085
+ const html = renderToString(() => App(props))
1086
+
1087
+ // browser, with the same props
1088
+ hydrate(() => App(props), document.getElementById("root"))
1089
+ ```
1090
+
1091
+ `renderToStringAsync` waits for the page's resources: it renders, waits for what they started loading, and renders again with the results until nothing new is loading. It gives the HTML and a `<script>` with the data, and `hydrate` starts from that data, so the page doesn't show a loading state or load anything again:
1092
+
1093
+ ```cpp
1094
+ const { html, script } = await renderToStringAsync(() => App(props))
1095
+ const page = `<div id="root">${html}</div>${script}`
1096
+ ```
1097
+
1098
+ Effects don't run on the server; they start in the browser after `hydrate`. Event handlers are ordinary closures and keep everything they capture. The nodes stay where they are while the page is taken over, so focus, scroll positions and iframes are kept.
1099
+
1100
+ A custom element takes over what was rendered inside it when it has the `hydrate` attribute:
1101
+
1102
+ ```cpp
1103
+ const html = `<x-counter hydrate>${renderToString(() => XCounter({ start: 5 }))}</x-counter>`
1104
+ ```
1105
+
1106
+ The server from `@slim/server` does both when a page names its browser module:
1107
+
1108
+ ```cpp
1109
+ server.page("/", ({ params }) => App({ params }), { hydrate: "/client.js" })
1110
+ ```
1111
+
1112
+ The page is rendered with `renderToStringAsync` inside `<div id="slim-root">`, the props (with the request's `url`) go to `window.__slimProps`, and `client.js` takes it over:
1113
+
1114
+ ```cpp
1115
+ use { App } from "./app"
1116
+
1117
+ hydrate(() => App(window.__slimProps), document.getElementById("slim-root"))
1118
+ ```
1119
+
1120
+ The compiled output runs in the browser as is: the runtime loads linkedom and `fs` only where there is no DOM.
613
1121
 
614
1122
  ## Embedding Slim in a Host Engine
615
1123
 
@@ -620,7 +1128,7 @@ Slim uses one of two runtimes per file:
620
1128
  DOM. Every `process` reference is guarded, so the module loads where `process`
621
1129
  does not exist at all.
622
1130
  - `external/defaults.js` — the core plus the DOM layer components render through
623
- (linkedom on the server) and the file reading that puts a source line in an error.
1131
+ (linkedom on the server, loaded only there) and the file reading that puts a source line in an error.
624
1132
 
625
1133
  Files without components use `core.js`, which also works in hosts such as QuickJS:
626
1134
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slim-lang/core",
3
- "version": "1.2.12",
3
+ "version": "1.2.13",
4
4
  "description": "Slim extends JavaScript with runtime types, structs, operators, and components, compiling to plain Javascript",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -33,19 +33,15 @@
33
33
  "license": "ISC",
34
34
  "dependencies": {
35
35
  "@babel/generator": "^7.29.7",
36
- "@babel/parser": "^7.29.7",
36
+ "@babel/parser": "7.29.7",
37
37
  "@babel/traverse": "^7.29.7",
38
38
  "@babel/types": "^7.29.7",
39
- "@jridgewell/gen-mapping": "^0.3.13",
40
- "@jridgewell/remapping": "^2.3.5",
41
39
  "chalk": "^6.0.0",
42
40
  "chokidar": "^5.0.0",
43
41
  "commander": "^15.0.0",
44
42
  "keytar": "^7.9.0",
45
43
  "linkedom": "^0.18.13",
46
- "magic-string": "^0.30.21",
47
44
  "open": "^11.0.1",
48
- "source-map": "^0.7.6",
49
45
  "tar": "^7.5.22"
50
46
  },
51
47
  "devDependencies": {