tilia 5.2.0 → 6.0.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.
@@ -1,403 +0,0 @@
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
- #### Loading state sentinel pattern
268
-
269
- To represent a "loading" state, use an empty tilia object as a sentinel. Use `===` identity comparison to distinguish "loading" from "loaded but empty."
270
-
271
- ```typescript
272
- const loading = tilia({});
273
- const repo = carve(({ derived }) => ({
274
- data: source(loading, derived(loader(service))),
275
- }));
276
- if (repo.data === loading) { /* still loading */ }
277
- ```
278
-
279
- ### `store`
280
-
281
- Managed value with setup that returns current state and receives setter.
282
-
283
- ```typescript
284
- import { tilia, store } from "tilia";
285
- type Auth = { t: "LoggedOut" } | { t: "LoggedIn" };
286
- const auth = (set: (next: Auth) => void): Auth => ({ t: "LoggedOut" });
287
- const app = tilia({ auth: store(auth) });
288
- ```
289
-
290
- ### `changing` (write tracking for sync connectors)
291
-
292
- Track key-level writes on a tilia-proxied dict. Takes an accessor `() => Record<string, T>` so the tracker can follow source swaps. Returns `{ changes, mute }`: `changes` drains accumulated changes into `{ upsert, remove }` when read by `watch`; `mute` runs a callback with tracking suppressed. `upsert` contains objects captured at write time. `remove` contains keys of deleted entries. Last write wins per key. Each call creates an independent accumulator.
293
-
294
- - `changing(() => data)` -- returns `{ changes, mute }`. `changes` drains accumulated changes as `{ upsert: T[], remove: string[] }`. `mute(fn)` runs `fn` without tracking (for inbound writes).
295
- - `changing(() => data, guard)` -- optional reactive guard function. When guard returns false, changes accumulate silently. When guard flips to true, all accumulated changes drain and the effect fires.
296
-
297
- ```typescript
298
- import { tilia, watch, changing } from "tilia";
299
-
300
- type Item = { id: string; name: string; quantity: number };
301
- type SyncService = {
302
- upsert: (items: Item[]) => void;
303
- remove: (ids: string[]) => void;
304
- };
305
- type LocalDb = {
306
- upsert: (items: Item[]) => void;
307
- remove: (ids: string[]) => void;
308
- };
309
- type Actor = { online: boolean };
310
-
311
- const makeItemsRepo = (service: SyncService, localDb: LocalDb, actor: Actor) => {
312
- const data = tilia<Record<string, Item>>({});
313
-
314
- // Local DB: always sync
315
- const { changes } = changing(() => data);
316
- watch(changes, ({ upsert, remove }) => {
317
- localDb.upsert(upsert);
318
- localDb.remove(remove);
319
- });
320
-
321
- // Remote: sync only when online
322
- const remote = changing(() => data, () => actor.online);
323
- watch(remote.changes, ({ upsert, remove }) => {
324
- service.upsert(upsert);
325
- service.remove(remove);
326
- });
327
-
328
- // Inbound: apply remote data without triggering outbound sync
329
- // remote.mute(() => Object.assign(data, remoteData));
330
-
331
- return data;
332
- };
333
- ```
334
-
335
- Multiple repos use the same pattern:
336
-
337
- ```typescript
338
- const settings = changing(() => settingsRepo.data, () => actor.online);
339
- watch(settings.changes, ({ upsert, remove }) => {
340
- settingsService.upsert(upsert);
341
- settingsService.remove(remove);
342
- });
343
- ```
344
-
345
- Architectural summary:
346
- - `source` handles inbound (loading from external into reactive data)
347
- - `changing` + `watch` handles outbound (pushing reactive writes to external)
348
- - `changes` returns `{ upsert, remove }` — upsert contains objects captured at write time, remove contains keys of deleted entries
349
- - `mute` prevents feedback loops: inbound writes are reactive but not tracked
350
- - The guard parameter leverages tilia's natural tracking for offline accumulation
351
- - The accessor pattern `() => data` lets the tracker follow source swaps automatically
352
-
353
- ### `make`
354
-
355
- Create isolated Tilia context.
356
-
357
- ```typescript
358
- import { make } from "tilia";
359
- const ctx = make();
360
- const local = ctx.tilia({ count: 0 });
361
- ```
362
-
363
- ## React Integration
364
-
365
- ### Dependency Injection (useApp)
366
-
367
- Create a context-based hook to inject the app state. Track with `leaf`, provision app with `useApp`.
368
-
369
- ```typescript
370
- import { createContext, useContext } from "react";
371
-
372
- const AppContext = createContext<App>(emptyApp);
373
- export const useApp = () => {
374
- return useContext(AppContext);
375
- };
376
- ```
377
-
378
- ### Avoid Over-Destructuring
379
-
380
- Do not destructure all state variables at the top of a component, as it defeats granular tracking by reading everything immediately.
381
-
382
- ```typescript
383
- // ❌ BAD: Reads `total` immediately, defeating conditional tracking
384
- const { cart: { total } } = useApp();
385
-
386
- // ✅ GOOD: Read properties only when needed in the JSX
387
- const { cart } = useApp();
388
- return <div>{cart.total}</div>;
389
- ```
390
-
391
- ## Generation Rules for AI
392
-
393
- - Prefer `carve` for feature boundaries.
394
- - Keep `carve` declarative and short.
395
- - Use arrow functions for helper logic.
396
- - Helpers wired through `derived` must accept `self`.
397
- - Use `source` for async query/re-query flows.
398
- - Explain `set` as imperative emission and `previous` as last emitted value.
399
- - Use `changing(() => data)` + `watch` for outbound sync connectors (persistence, remote sync). Destructure `{ changes, mute }`.
400
- - `changes` returns `{ upsert, remove }` — upsert contains objects, remove contains keys. Use the accessor pattern so the tracker follows source swaps.
401
- - Use `mute` for inbound writes to prevent feedback loops in bidirectional sync.
402
- - `source` = inbound, `changing` = outbound.
403
-