tilia 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,354 @@
1
+ # Tilia LLM Guide (ReScript)
2
+
3
+ AI-focused ReScript documentation for the full Tilia API.
4
+
5
+ ## Install
6
+
7
+ npm install tilia @tilia/react
8
+
9
+ ## Primary Rule
10
+
11
+ - Use `carve` as the default for feature modules.
12
+ - `carve` must glue parts into one reactive object.
13
+ - Do not put business complexity inside `carve`.
14
+ - Put logic in standalone functions that take `self`.
15
+ - Bind with `field: derived(field)` when possible.
16
+
17
+ ## Canonical Carve Pattern
18
+
19
+ ```rescript
20
+ open Tilia
21
+
22
+ type feature = {
23
+ mutable count: int,
24
+ double: int,
25
+ add: int => unit,
26
+ }
27
+
28
+ type service = {
29
+ fetchCount: (int, int => unit) => unit,
30
+ updateCount: (int, unit => unit) => unit,
31
+ }
32
+
33
+ let double = (self: feature) => self.count * 2
34
+
35
+ let add = (service: service) => (self: feature) => (count: int) => {
36
+ let prevValue = self.count
37
+ self.count += count // optimistic write
38
+ service.updateCount(self.count, () => self.count = prevValue)
39
+ }
40
+
41
+ let makeFeature = service =>
42
+ carve(({derived}) => {
43
+ count: source(0, service.fetchCount),
44
+ double: derived(double),
45
+ add: derived(add(service)),
46
+ })
47
+
48
+ let feature = makeFeature(service)
49
+ feature.add(4)
50
+ ```
51
+
52
+ ## Anti-Pattern (Avoid)
53
+
54
+ ```rescript
55
+ open Tilia
56
+
57
+ // Avoid: logic-heavy body inside carve.
58
+ let cart = carve(({derived}) => {
59
+ items: [{price: 10.0, quantity: 1}],
60
+ total: derived(self => {
61
+ let mutable sum = 0.0
62
+ for i in 0 to Array.length(self.items) - 1 {
63
+ switch self.items[i] {
64
+ | Some(item) => sum = sum +. item.price *. Float.fromInt(item.quantity)
65
+ | None => ()
66
+ }
67
+ }
68
+ sum
69
+ }),
70
+ })
71
+ ```
72
+
73
+ ## Feature File Organization
74
+
75
+ Use this if the project does not provide other guidelines.
76
+
77
+ ```text
78
+ [feature-name]/
79
+ index.res // carve glue
80
+ type.res // type of the feature
81
+ computed.res // all computed/derived values
82
+ actions.res // all mutating functions
83
+ service.res // external dependencies (db fetch, etc)
84
+ ```
85
+
86
+ ## Full API Map (ReScript)
87
+
88
+ ### `tilia`
89
+
90
+ Wrap an object/array into a reactive proxy.
91
+
92
+ ```rescript
93
+ let state = tilia({count: 0})
94
+ state.count = 1
95
+ ```
96
+
97
+ ### `carve`
98
+
99
+ Create a reactive feature object with helper-function injection via `derived`.
100
+
101
+ ```rescript
102
+ type feature = {value: int, doubled: int}
103
+ let doubled = (self: feature) => self.value * 2
104
+
105
+ let feature = carve(({derived}) => {
106
+ value: 1,
107
+ doubled: derived(doubled),
108
+ })
109
+ ```
110
+
111
+ ### `observe`
112
+
113
+ Push reactivity. Callback re-runs when tracked reads change.
114
+
115
+ ```rescript
116
+ observe(() => Js.log(state.count))
117
+ ```
118
+
119
+ ### `watch`
120
+
121
+ Split tracking and effect.
122
+
123
+ ```rescript
124
+ watch(
125
+ () => state.count,
126
+ v => Js.log(v),
127
+ )
128
+ ```
129
+
130
+ ### `batch`
131
+
132
+ Group writes and flush once.
133
+
134
+ ```rescript
135
+ batch(() => {
136
+ state.a = 1
137
+ state.b = 2
138
+ })
139
+ ```
140
+
141
+ ### `signal`
142
+
143
+ Single mutable reactive value + setter.
144
+
145
+ ```rescript
146
+ let (count, setCount) = signal(0)
147
+ setCount(2)
148
+ ```
149
+
150
+ ### `derived` (signal API)
151
+
152
+ Create a derived signal from signals or reactive reads.
153
+
154
+ ```rescript
155
+ let (a, setA) = signal(1)
156
+ let b = derived(() => a.value * 2)
157
+ setA(2)
158
+ ```
159
+
160
+ ### `lift`
161
+
162
+ Insert signal value into a `tilia` object.
163
+
164
+ ```rescript
165
+ let (s, setS) = signal(0)
166
+ let state = tilia({count: lift(s), setS})
167
+ ```
168
+
169
+ ### `readonly`
170
+
171
+ Insert non-tracked immutable data wrapper.
172
+
173
+ ```rescript
174
+ let app = tilia({form: readonly(bigData)})
175
+ ```
176
+
177
+ ### `computed`
178
+
179
+ Pull reactivity. Re-computes on read after dependency invalidation.
180
+
181
+ ```rescript
182
+ let state = tilia({
183
+ count: 1,
184
+ double: computed(() => state.count * 2),
185
+ })
186
+ ```
187
+
188
+ ### `source` (async query and re-query)
189
+
190
+ Use `source(initial, setup)` for async loaders and re-loaders.
191
+
192
+ - **Tracking rule:** Never use `async` in the `setup` function. Tilia tracks reactive reads during synchronous execution of `setup` only. Tracking ONLY HAPPENS INSIDE A CALLBACK. Read dependencies synchronously, then delegate async work.
193
+ - `initial` is returned until `set` is called.
194
+ - `setup(previous, set)` runs on first read.
195
+ - `setup(previous, set)` runs again when tracked dependencies inside setup change.
196
+ - `set(next)` updates the source value imperatively.
197
+ - `previous` is the last emitted value, useful for incremental updates.
198
+ - `previous` also supports stale-while-revalidate UI (keep old data visible, e.g. greyed out, while reloading to avoid blinking).
199
+
200
+ ```rescript
201
+ open Tilia
202
+
203
+ let sleep: unit => promise<unit> = async () =>
204
+ %raw(`new Promise(resolve => setTimeout(resolve, 10))`)
205
+
206
+ let fetchName = self => (previous, set) => {
207
+ // 1. Synchronous read (tracked)
208
+ let q = self.query
209
+
210
+ // 2. Delegate async work
211
+ let _ = sleep()->Promise.thenResolve(() => {
212
+ switch q {
213
+ | "helena" => set("Helena")
214
+ | "bob" => set("William")
215
+ | _ => set(previous ++ "+" ++ q)
216
+ }
217
+ })
218
+ }
219
+
220
+ let user = carve(({derived}) => {
221
+ query: "helena",
222
+ name: source("Loading", derived(fetchName)),
223
+ })
224
+
225
+ // Re-query
226
+ user.query = "bob"
227
+ ```
228
+
229
+ #### `source` + `derived` inside `carve` (conditional loader strategy)
230
+
231
+ ```rescript
232
+ open Tilia
233
+
234
+ let loader = service => self => (previous, set) => {
235
+ // 1. Synchronous read (tracked)
236
+ let id = self.projectId
237
+ set(stale(previous))
238
+
239
+ // 2. Delegate async work
240
+ let _ = service.loadProject(id)->Promise.thenResolve(project => {
241
+ set(loaded(project))
242
+ })
243
+ }
244
+
245
+ let selectProject = self => id => self.projectId = id
246
+
247
+ let projectBranch = carve(({derived}) => {
248
+ projectId: "main",
249
+ project: source(empty(), derived(loader(service))),
250
+ selectProject: derived(selectProject),
251
+ })
252
+ ```
253
+
254
+ Use this when loading depends on feature fields (`self.projectId`) and keep `previous` to preserve old UI data until new values are ready.
255
+
256
+ ### `store`
257
+
258
+ Managed state with setup returning current value and receiving a setter.
259
+
260
+ ```rescript
261
+ type auth = LoggedOut | Loading | LoggedIn
262
+
263
+ let machine = set => LoggedOut
264
+ let app = tilia({auth: store(machine)})
265
+ ```
266
+
267
+ ### `changed` (write tracking for sync connectors)
268
+
269
+ Track which keys are written on a tilia-proxied object. Returns a capture function for `watch` that drains accumulated keys. Each call creates an independent accumulator.
270
+
271
+ - `changed(obj)` -- captures all writes. When read by `watch`, returns the array of written keys and clears the accumulator.
272
+ - `changed(obj, ~guard=() => expr)` -- optional reactive guard. When guard returns false, keys accumulate silently without triggering the watcher. When guard flips to true, all accumulated keys drain and the effect fires.
273
+
274
+ ```rescript
275
+ open Tilia
276
+
277
+ type syncService = {sync: array<string> => unit}
278
+ type localDb = {batchWrite: array<string> => unit}
279
+ type actor = {mutable online: bool}
280
+
281
+ let makeItemsRepo = (service: syncService, localDb: localDb, actor: actor) => {
282
+ let data = tilia(Dict.make())
283
+
284
+ // Local DB: always sync
285
+ watch(changed(data), keys => {
286
+ localDb.batchWrite(keys)
287
+ })
288
+
289
+ // Remote: sync only when online
290
+ watch(changed(data, ~guard=() => actor.online), keys => {
291
+ service.sync(keys)
292
+ })
293
+
294
+ data
295
+ }
296
+ ```
297
+
298
+ Multiple repos use the same pattern:
299
+
300
+ ```rescript
301
+ watch(changed(settingsRepo.data, ~guard=() => actor.online), keys => {
302
+ settingsService.sync(keys)
303
+ })
304
+ ```
305
+
306
+ Architectural summary:
307
+ - `source` handles inbound (loading from external into reactive data)
308
+ - `changed` + `watch` handles outbound (pushing reactive writes to external)
309
+ - The guard parameter leverages tilia's natural tracking for offline accumulation
310
+
311
+ ### `make`
312
+
313
+ Create isolated Tilia context (`tilia`, `carve`, `observe`, etc.).
314
+
315
+ ```rescript
316
+ let ctx = make()
317
+ let local = ctx.tilia({count: 0})
318
+ ```
319
+
320
+ ## React Integration
321
+
322
+ ### Dependency Injection (useApp)
323
+
324
+ Create a context-based hook to inject the app state. Track with `leaf`, provision app with `useApp`.
325
+
326
+ ```rescript
327
+ let context = React.createContext(emptyApp)
328
+ let useApp = () => React.useContext(context)
329
+ ```
330
+
331
+ ### Avoid Over-Destructuring
332
+
333
+ Do not destructure all state variables at the top of a component, as it defeats granular tracking by reading everything immediately.
334
+
335
+ ```rescript
336
+ // ❌ BAD: Reads `total` immediately, defeating conditional tracking
337
+ let {cart: {total}} = useApp()
338
+
339
+ // ✅ GOOD: Read properties only when needed in the JSX
340
+ let {cart} = useApp()
341
+ <div>{React.float(cart.total)}</div>
342
+ ```
343
+
344
+ ## Generation Rules for AI
345
+
346
+ - Prefer `carve` over ad-hoc `tilia` for feature modules.
347
+ - Keep `carve` declarative and short.
348
+ - Extract domain logic into external functions.
349
+ - Functions wired with `derived` take `self` first.
350
+ - Use `source` for async query/re-query flows.
351
+ - Explain `set` as imperative emitter and `previous` as last emitted value.
352
+ - Use `changed` + `watch` for outbound sync connectors (persistence, remote sync).
353
+ - `source` = inbound, `changed` = outbound.
354
+
@@ -0,0 +1,370 @@
1
+ # Tilia LLM Guide (TypeScript)
2
+
3
+ AI-focused TypeScript documentation for the full Tilia API.
4
+
5
+ ## Install
6
+
7
+ npm install tilia @tilia/react
8
+
9
+ ## Primary Rule
10
+
11
+ - Use `carve` as the default for feature modules.
12
+ - `carve` binds a feature into one reactive object.
13
+ - `carve` must stay glue-only and avoid domain complexity.
14
+ - Put behavior in standalone arrow functions that accept `self`.
15
+ - Bind with `field: derived(field)` where possible.
16
+
17
+ ## Canonical Carve Pattern
18
+
19
+ ```typescript
20
+ import { carve, source } from "tilia";
21
+
22
+ type Feature = {
23
+ count: number;
24
+ double: number;
25
+ add: (count: number) => void;
26
+ };
27
+
28
+ type Service = {
29
+ fetchCount: () => (previous: number, set: (value: number) => void) => void;
30
+ updateCount: (next: number, rollback: () => void) => void;
31
+ };
32
+
33
+ const double = (self: Feature): number => self.count * 2;
34
+
35
+ const add =
36
+ (service: Service) =>
37
+ (self: Feature) =>
38
+ (count: number): void => {
39
+ const prevValue = self.count;
40
+ self.count += count; // optimistic write
41
+ service.updateCount(self.count, () => (self.count = prevValue));
42
+ };
43
+
44
+ export const makeFeature = (service: Service) =>
45
+ carve<Feature>(({ derived }) => ({
46
+ count: source(0, service.fetchCount()),
47
+ double: derived(double),
48
+ add: derived(add(service)),
49
+ }));
50
+
51
+ const feature = makeFeature(service);
52
+ feature.add(4);
53
+ ```
54
+
55
+ ## Anti-Pattern (Avoid)
56
+
57
+ ```typescript
58
+ import { carve } from "tilia";
59
+
60
+ // Avoid: logic-heavy body inside carve.
61
+ const feature = carve(({ derived }) => ({
62
+ count: 0,
63
+ double: derived((self) => {
64
+ let acc = 0;
65
+ for (let i = 0; i < self.count; i++) acc += 2;
66
+ return acc;
67
+ }),
68
+ }));
69
+ ```
70
+
71
+ ## Feature File Organization
72
+
73
+ Use this if the project does not provide other guidelines.
74
+
75
+ ```text
76
+ [feature-name]/
77
+ index.ts // carve glue
78
+ type.ts // ts type of the feature
79
+ computed.ts // all computed/derived values
80
+ actions.ts // all mutating functions
81
+ service.ts // external dependencies (db fetch, etc)
82
+ ```
83
+
84
+ ## Full API Map (TypeScript)
85
+
86
+ ### `tilia`
87
+
88
+ Wrap object/array into reactive proxy.
89
+
90
+ ```typescript
91
+ import { tilia } from "tilia";
92
+ const state = tilia({ count: 0 });
93
+ state.count = 1;
94
+ ```
95
+
96
+ ### `carve`
97
+
98
+ Create feature object and inject `self` via `derived`.
99
+
100
+ ```typescript
101
+ import { carve } from "tilia";
102
+
103
+ type Feature = { value: number; doubled: number };
104
+ const doubled = (self: Feature): number => self.value * 2;
105
+
106
+ const feature = carve<Feature>(({ derived }) => ({
107
+ value: 1,
108
+ doubled: derived(doubled),
109
+ }));
110
+ ```
111
+
112
+ ### `observe`
113
+
114
+ Push reactivity callback.
115
+
116
+ ```typescript
117
+ import { observe } from "tilia";
118
+ observe(() => console.log(state.count));
119
+ ```
120
+
121
+ ### `watch`
122
+
123
+ Capture and effect separation.
124
+
125
+ ```typescript
126
+ import { watch } from "tilia";
127
+ watch(
128
+ () => state.count,
129
+ (value) => console.log(value),
130
+ );
131
+ ```
132
+
133
+ ### `batch`
134
+
135
+ Group writes and flush once.
136
+
137
+ ```typescript
138
+ import { batch } from "tilia";
139
+ batch(() => {
140
+ state.a = 1;
141
+ state.b = 2;
142
+ });
143
+ ```
144
+
145
+ ### `signal`
146
+
147
+ Single mutable reactive value and setter.
148
+
149
+ ```typescript
150
+ import { signal } from "tilia";
151
+ const [count, setCount] = signal(0);
152
+ setCount(2);
153
+ ```
154
+
155
+ ### `derived` (signal API)
156
+
157
+ Derived signal from signals/reactive reads.
158
+
159
+ ```typescript
160
+ import { signal, derived } from "tilia";
161
+ const [a, setA] = signal(1);
162
+ const b = derived(() => a.value * 2);
163
+ setA(2);
164
+ ```
165
+
166
+ ### `lift`
167
+
168
+ Expose signal in object as reactive value.
169
+
170
+ ```typescript
171
+ import { signal, lift, tilia } from "tilia";
172
+ const [s, setS] = signal(0);
173
+ const state = tilia({ count: lift(s), setS });
174
+ ```
175
+
176
+ ### `readonly`
177
+
178
+ Insert immutable data wrapper without tracking inner mutations.
179
+
180
+ ```typescript
181
+ import { tilia, readonly } from "tilia";
182
+ const app = tilia({ form: readonly({ version: 1 }) });
183
+ ```
184
+
185
+ ### `computed`
186
+
187
+ Pull-based derived value with cache + invalidation.
188
+
189
+ ```typescript
190
+ import { computed, tilia } from "tilia";
191
+ const state = tilia({
192
+ count: 1,
193
+ double: computed(() => state.count * 2),
194
+ });
195
+ ```
196
+
197
+ ### `source` (async query and re-query)
198
+
199
+ Use `source(initial, setup)` for async loading and re-loading.
200
+
201
+ - **Tracking rule:** Never use `async` in the `setup` function. Tilia tracks reactive reads during synchronous execution of `setup` only. Tracking ONLY HAPPENS INSIDE A CALLBACK. Read dependencies synchronously, then delegate async work.
202
+ - `initial` is returned before first `set`.
203
+ - `setup(previous, set)` runs on first read.
204
+ - `setup(previous, set)` runs again when tracked dependencies in setup change.
205
+ - `set(next)` imperatively publishes a new value.
206
+ - `previous` is the latest emitted value, useful for incremental updates.
207
+ - `previous` also supports stale-while-revalidate UI (keep old data visible, e.g. greyed out, while reloading to avoid blinking).
208
+
209
+ ```typescript
210
+ import { carve, source } from "tilia";
211
+
212
+ const sleep = () => new Promise((resolve) => setTimeout(resolve, 10));
213
+
214
+ type User = { query: string; name: string };
215
+
216
+ const fetchName = (self: User) => (previous: string, set: (value: string) => void): void => {
217
+ // 1. Synchronous read (tracked)
218
+ const q = self.query;
219
+
220
+ // 2. Delegate async work
221
+ sleep().then(() => {
222
+ if (q === "helena") set("Helena");
223
+ else if (q === "bob") set("William");
224
+ else set(`${previous}+${q}`);
225
+ });
226
+ };
227
+
228
+ const user = carve<User>(({ derived }) => ({
229
+ query: "helena",
230
+ name: source("Loading", derived(fetchName)),
231
+ }));
232
+
233
+ // Re-query
234
+ user.query = "bob";
235
+ ```
236
+
237
+ #### `source` + `derived` inside `carve` (conditional loader strategy)
238
+
239
+ ```typescript
240
+ const loader =
241
+ (service: Service) =>
242
+ (self: { projectId: string }) =>
243
+ (previous: Project, set: (value: Project) => void) => {
244
+ // 1. Synchronous read (tracked)
245
+ const id = self.projectId;
246
+ set(stale(previous));
247
+
248
+ // 2. Delegate async work
249
+ service.loadProject(id).then((project) => {
250
+ set(loaded(project));
251
+ });
252
+ };
253
+
254
+ const selectProject = (self: ProjectBranch) => (id: string) => {
255
+ self.projectId = id;
256
+ };
257
+
258
+ const projectBranch = carve<ProjectBranch>(({ derived }) => ({
259
+ projectId: "main",
260
+ project: source(empty(), derived(loader(service))),
261
+ selectProject: derived(selectProject),
262
+ }));
263
+ ```
264
+
265
+ Use this when loading depends on feature fields (`self.projectId`) and keep `previous` to preserve old UI data until new values are ready.
266
+
267
+ ### `store`
268
+
269
+ Managed value with setup that returns current state and receives setter.
270
+
271
+ ```typescript
272
+ import { tilia, store } from "tilia";
273
+ type Auth = { t: "LoggedOut" } | { t: "LoggedIn" };
274
+ const auth = (set: (next: Auth) => void): Auth => ({ t: "LoggedOut" });
275
+ const app = tilia({ auth: store(auth) });
276
+ ```
277
+
278
+ ### `changed` (write tracking for sync connectors)
279
+
280
+ Track which keys are written on a tilia-proxied object. Returns a capture function for `watch` that drains accumulated keys. Each call creates an independent accumulator.
281
+
282
+ - `changed(obj)` -- captures all writes. When read by `watch`, returns the array of written keys and clears the accumulator.
283
+ - `changed(obj, guard)` -- optional reactive guard function. When guard returns false, keys accumulate silently without triggering the watcher. When guard flips to true, all accumulated keys drain and the effect fires.
284
+
285
+ ```typescript
286
+ import { tilia, watch, changed } from "tilia";
287
+
288
+ type SyncService = { sync: (keys: string[]) => void };
289
+ type LocalDb = { batchWrite: (keys: string[]) => void };
290
+ type Actor = { online: boolean };
291
+
292
+ const makeItemsRepo = (service: SyncService, localDb: LocalDb, actor: Actor) => {
293
+ const data = tilia<Record<string, unknown>>({});
294
+
295
+ // Local DB: always sync
296
+ watch(changed(data), (keys) => {
297
+ localDb.batchWrite(keys);
298
+ });
299
+
300
+ // Remote: sync only when online
301
+ watch(changed(data, () => actor.online), (keys) => {
302
+ service.sync(keys);
303
+ });
304
+
305
+ return data;
306
+ };
307
+ ```
308
+
309
+ Multiple repos use the same pattern:
310
+
311
+ ```typescript
312
+ watch(changed(settingsRepo.data, () => actor.online), (keys) => {
313
+ settingsService.sync(keys);
314
+ });
315
+ ```
316
+
317
+ Architectural summary:
318
+ - `source` handles inbound (loading from external into reactive data)
319
+ - `changed` + `watch` handles outbound (pushing reactive writes to external)
320
+ - The guard parameter leverages tilia's natural tracking for offline accumulation
321
+
322
+ ### `make`
323
+
324
+ Create isolated Tilia context.
325
+
326
+ ```typescript
327
+ import { make } from "tilia";
328
+ const ctx = make();
329
+ const local = ctx.tilia({ count: 0 });
330
+ ```
331
+
332
+ ## React Integration
333
+
334
+ ### Dependency Injection (useApp)
335
+
336
+ Create a context-based hook to inject the app state. Track with `leaf`, provision app with `useApp`.
337
+
338
+ ```typescript
339
+ import { createContext, useContext } from "react";
340
+
341
+ const AppContext = createContext<App>(emptyApp);
342
+ export const useApp = () => {
343
+ return useContext(AppContext);
344
+ };
345
+ ```
346
+
347
+ ### Avoid Over-Destructuring
348
+
349
+ Do not destructure all state variables at the top of a component, as it defeats granular tracking by reading everything immediately.
350
+
351
+ ```typescript
352
+ // ❌ BAD: Reads `total` immediately, defeating conditional tracking
353
+ const { cart: { total } } = useApp();
354
+
355
+ // ✅ GOOD: Read properties only when needed in the JSX
356
+ const { cart } = useApp();
357
+ return <div>{cart.total}</div>;
358
+ ```
359
+
360
+ ## Generation Rules for AI
361
+
362
+ - Prefer `carve` for feature boundaries.
363
+ - Keep `carve` declarative and short.
364
+ - Use arrow functions for helper logic.
365
+ - Helpers wired through `derived` must accept `self`.
366
+ - Use `source` for async query/re-query flows.
367
+ - Explain `set` as imperative emission and `previous` as last emitted value.
368
+ - Use `changed` + `watch` for outbound sync connectors (persistence, remote sync).
369
+ - `source` = inbound, `changed` = outbound.
370
+