@ftrdotdev/pi-tracker 0.7.0 → 0.9.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,5 +1,7 @@
1
1
  import { assert, it } from "@effect/vitest";
2
+ import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
2
3
  import { Effect, Option, Result } from "effect";
4
+ import { migrationStateArbitrary, trackerStateArbitrary } from "../../test-support/generators.ts";
3
5
  import {
4
6
  decodeStateEffect,
5
7
  emptyState,
@@ -23,22 +25,22 @@ const decodeOrThrow = (snapshot: unknown): TrackerState =>
23
25
 
24
26
  /** A realistic two-list state used by several tests. */
25
27
  const sampleState = (): TrackerState =>
26
- new TrackerState({
28
+ TrackerState.make({
27
29
  lists: [
28
- new TodoList({
30
+ TodoList.make({
29
31
  id: 1,
30
32
  name: "Work",
31
33
  nextItemId: 3,
32
34
  items: [
33
- new TodoItem({ id: 1, title: "write plan", done: true }),
34
- new TodoItem({ id: 2, title: "implement tracker", done: false }),
35
+ TodoItem.make({ id: 1, title: "write plan", done: true }),
36
+ TodoItem.make({ id: 2, title: "implement tracker", done: false }),
35
37
  ],
36
38
  }),
37
- new TodoList({
39
+ TodoList.make({
38
40
  id: 2,
39
41
  name: "Home",
40
42
  nextItemId: 2,
41
- items: [new TodoItem({ id: 1, title: "water plants", done: false })],
43
+ items: [TodoItem.make({ id: 1, title: "water plants", done: false })],
42
44
  }),
43
45
  ],
44
46
  activeListId: 1,
@@ -53,48 +55,26 @@ it("emptyState produces the canonical empty snapshot", () => {
53
55
  });
54
56
  });
55
57
 
56
- it("empty state round-trips through encode/decode", () => {
57
- roundTripsTo(emptyState(), encodeState(emptyState()));
58
- });
59
-
60
- it("a realistic state round-trips, preserving order", () => {
61
- const state = sampleState();
62
- roundTripsTo(state, encodeState(state));
63
- const decoded = decodeOrThrow(encodeState(state));
64
- assert.deepStrictEqual(decoded.lists, state.lists);
65
- assert.strictEqual(decoded.activeListId, 1);
66
- assert.strictEqual(decoded.nextListId, 3);
67
- });
68
-
69
- it("item ids and deps round-trip", () => {
70
- const state = new TrackerState({
71
- lists: [
72
- new TodoList({
73
- id: 1,
74
- name: "Work",
75
- nextItemId: 4,
76
- items: [
77
- new TodoItem({ id: 1, title: "a", done: true }),
78
- new TodoItem({ id: 3, title: "b", done: false, deps: ["Work:1"] }),
79
- ],
80
- }),
81
- ],
82
- activeListId: 1,
83
- nextListId: 2,
84
- });
58
+ it.prop(
59
+ "any tracker state round-trips through encode and decode",
60
+ { state: trackerStateArbitrary },
61
+ ({ state }) => {
62
+ // Compare encoded forms: decoding applies the schema's defaults, so the
63
+ // decoded value diffs from the fixture on those fields.
64
+ assert.deepStrictEqual(encodeState(decodeOrThrow(encodeState(state))), encodeState(state));
65
+ },
66
+ { arbitrary: { runs: PROPERTY_RUNS } },
67
+ );
85
68
 
86
- roundTripsTo(state, encodeState(state));
87
-
88
- const decoded = decodeOrThrow(encodeState(state));
89
- assert.deepStrictEqual(
90
- decoded.lists[0]?.items.map((i) => [i.id, i.deps]),
91
- [
92
- [1, []],
93
- [3, ["Work:1"]],
94
- ],
95
- );
96
- assert.strictEqual(decoded.lists[0]?.nextItemId, 4);
97
- });
69
+ it.prop(
70
+ "an encoded tracker snapshot is plain JSON",
71
+ { state: trackerStateArbitrary },
72
+ ({ state }) => {
73
+ const encoded = encodeState(state);
74
+ assert.deepStrictEqual(JSON.parse(JSON.stringify(encoded)), encoded);
75
+ },
76
+ { arbitrary: { runs: PROPERTY_RUNS } },
77
+ );
98
78
 
99
79
  it("encoded snapshots carry item ids, deps, and the list counter", () => {
100
80
  const encoded = encodeState(sampleState());
@@ -119,15 +99,9 @@ it("decoded values are real class instances", () => {
119
99
  it("constructors validate their input", () => {
120
100
  // Invalid types / missing fields throw at construction time. (The invalid
121
101
  // inputs are cast because the constructor signature is already typed.)
122
- assert.throws(() => new TodoItem({ title: 42, done: false } as never));
123
- assert.throws(() => new TodoItem({ title: "x" } as never));
124
- assert.throws(() => new TrackerState({} as never));
125
- });
126
-
127
- it("encoded snapshots are JSON-serializable", () => {
128
- const state = sampleState();
129
- const encoded = encodeState(state);
130
- assert.deepStrictEqual(JSON.parse(JSON.stringify(encoded)), encoded);
102
+ assert.throws(() => TodoItem.make({ title: 42, done: false } as never));
103
+ assert.throws(() => TodoItem.make({ title: "x" } as never));
104
+ assert.throws(() => TrackerState.make({} as never));
131
105
  });
132
106
 
133
107
  it("activeListId: null round-trips as null (not undefined)", () => {
@@ -149,9 +123,9 @@ it("unknown extra keys are ignored (forward compatibility)", () => {
149
123
  });
150
124
 
151
125
  it("rejects a snapshot with the wrong field type", () => {
152
- const result = Effect.runSync(Effect.result(decodeStateEffect({ lists: 42 })));
153
- assert(Result.isFailure(result));
154
- const failure = Option.getOrThrow(Result.getFailure(result));
126
+ const result = Effect.result(decodeStateEffect({ lists: 42 })).pipe(Effect.runSync);
127
+ if (!Result.isFailure(result)) assert.fail("expected a failure");
128
+ const failure = Result.getFailure(result).pipe(Option.getOrThrow);
155
129
  assert.strictEqual(failure._tag, "SchemaError");
156
130
  assert.match(failure.message, /lists/i);
157
131
  });
@@ -162,8 +136,8 @@ it("rejects a snapshot with an invalid item field", () => {
162
136
  activeListId: null,
163
137
  nextListId: 2,
164
138
  };
165
- const result = Effect.runSync(Effect.result(decodeStateEffect(bad)));
166
- assert(Result.isFailure(result));
139
+ const result = Effect.result(decodeStateEffect(bad)).pipe(Effect.runSync);
140
+ if (!Result.isFailure(result)) assert.fail("expected a failure");
167
141
  });
168
142
 
169
143
  it("drops a legacy string item id so old sessions stay loadable", () => {
@@ -177,7 +151,7 @@ it("drops a legacy string item id so old sessions stay loadable", () => {
177
151
  nextItemId: 9,
178
152
  };
179
153
  const decoded = decodeOrThrow(legacy);
180
- assert.deepStrictEqual(decoded.lists[0]?.items, [new TodoItem({ title: "x", done: false })]);
154
+ assert.deepStrictEqual(decoded.lists[0]?.items, [TodoItem.make({ title: "x", done: false })]);
181
155
  });
182
156
 
183
157
  it("splits a legacy text item into a title and a description", () => {
@@ -218,18 +192,75 @@ it("enforces Int list ids (fractional ids are rejected)", () => {
218
192
  activeListId: null,
219
193
  nextListId: 2,
220
194
  };
221
- const result = Effect.runSync(Effect.result(decodeStateEffect(bad)));
222
- assert(Result.isFailure(result));
195
+ const result = Effect.result(decodeStateEffect(bad)).pipe(Effect.runSync);
196
+ if (!Result.isFailure(result)) assert.fail("expected a failure");
223
197
  });
224
198
 
225
199
  it("rejects a snapshot missing required fields", () => {
226
- const result = Effect.runSync(Effect.result(decodeStateEffect({ lists: [] })));
227
- assert(Result.isFailure(result));
200
+ const result = Effect.result(decodeStateEffect({ lists: [] })).pipe(Effect.runSync);
201
+ if (!Result.isFailure(result)) assert.fail("expected a failure");
228
202
  });
229
203
 
230
204
  it("rejects non-object input", () => {
231
205
  for (const bad of ["not json", 42, null, undefined, [1, 2]]) {
232
- const result = Effect.runSync(Effect.result(decodeStateEffect(bad)));
233
- assert(Result.isFailure(result), `expected ${JSON.stringify(bad)} to fail`);
206
+ const result = Effect.result(decodeStateEffect(bad)).pipe(Effect.runSync);
207
+ if (!Result.isFailure(result)) assert.fail(`expected ${JSON.stringify(bad)} to fail`);
234
208
  }
235
209
  });
210
+
211
+ it.prop(
212
+ "migration gives every item a positive id",
213
+ { state: migrationStateArbitrary },
214
+ ({ state }) => {
215
+ for (const list of migrateState(state).lists) {
216
+ assert(list.items.every((item) => item.id >= 1));
217
+ }
218
+ },
219
+ { arbitrary: { runs: PROPERTY_RUNS } },
220
+ );
221
+
222
+ it.prop(
223
+ "migration leaves each list counter above the highest item id",
224
+ { state: migrationStateArbitrary },
225
+ ({ state }) => {
226
+ for (const list of migrateState(state).lists) {
227
+ assert(list.nextItemId > Math.max(0, ...list.items.map((item) => item.id)));
228
+ }
229
+ },
230
+ { arbitrary: { runs: PROPERTY_RUNS } },
231
+ );
232
+
233
+ it.prop(
234
+ "migration is idempotent",
235
+ { state: migrationStateArbitrary },
236
+ ({ state }) => {
237
+ assert.deepStrictEqual(
238
+ encodeState(migrateState(migrateState(state))),
239
+ encodeState(migrateState(state)),
240
+ );
241
+ },
242
+ { arbitrary: { runs: PROPERTY_RUNS } },
243
+ );
244
+
245
+ it.prop(
246
+ "migration preserves titles, completion flags, descriptions, references and dependencies",
247
+ { state: migrationStateArbitrary },
248
+ ({ state }) => {
249
+ const migrated = migrateState(state);
250
+ assert.strictEqual(migrated.lists.length, state.lists.length);
251
+ for (const [listIndex, list] of state.lists.entries()) {
252
+ const after = migrated.lists[listIndex]!;
253
+ assert.strictEqual(after.items.length, list.items.length);
254
+ for (const [position, item] of list.items.entries()) {
255
+ const kept = after.items[position]!;
256
+ assert.strictEqual(kept.title, item.title);
257
+ assert.strictEqual(kept.done, item.done);
258
+ assert.strictEqual(kept.description, item.description);
259
+ assert.deepStrictEqual(kept.refs, item.refs);
260
+ assert.deepStrictEqual(kept.produces, item.produces);
261
+ assert.deepStrictEqual(kept.deps, item.deps);
262
+ }
263
+ }
264
+ },
265
+ { arbitrary: { runs: PROPERTY_RUNS } },
266
+ );
@@ -67,8 +67,8 @@ const itemProduces = Schema.Array(declaredProduct).pipe(
67
67
  Schema.withConstructorDefault(Effect.succeed([])),
68
68
  );
69
69
 
70
- export type DeclaredReference = Schema.Schema.Type<typeof declaredReference>;
71
- export type DeclaredProduct = Schema.Schema.Type<typeof declaredProduct>;
70
+ export type DeclaredReference = typeof declaredReference.Type;
71
+ export type DeclaredProduct = typeof declaredProduct.Type;
72
72
 
73
73
  /**
74
74
  * Sentinel for a list that stored no item id counter, which means the snapshot
@@ -83,7 +83,9 @@ const itemCounter = Schema.Int.pipe(
83
83
  Schema.withConstructorDefault(Effect.succeed(1)),
84
84
  );
85
85
 
86
- export class TodoItem extends Schema.Class<TodoItem>("tracker/TodoItem")({
86
+ export class TodoItem extends Schema.Class<TodoItem, { readonly brand: unique symbol }>(
87
+ "tracker/TodoItem",
88
+ )({
87
89
  id: itemId,
88
90
  title: Schema.String,
89
91
  description: itemDescription,
@@ -93,7 +95,9 @@ export class TodoItem extends Schema.Class<TodoItem>("tracker/TodoItem")({
93
95
  deps: itemDeps,
94
96
  }) {}
95
97
 
96
- export class TodoList extends Schema.Class<TodoList>("tracker/TodoList")({
98
+ export class TodoList extends Schema.Class<TodoList, { readonly brand: unique symbol }>(
99
+ "tracker/TodoList",
100
+ )({
97
101
  id: Schema.Int,
98
102
  name: Schema.String,
99
103
  // Strictly-increasing counter ⇒ stable item ids, never reused after deletes.
@@ -101,7 +105,9 @@ export class TodoList extends Schema.Class<TodoList>("tracker/TodoList")({
101
105
  items: Schema.Array(TodoItem),
102
106
  }) {}
103
107
 
104
- export class TrackerState extends Schema.Class<TrackerState>("tracker/TrackerState")({
108
+ export class TrackerState extends Schema.Class<TrackerState, { readonly brand: unique symbol }>(
109
+ "tracker/TrackerState",
110
+ )({
105
111
  lists: Schema.Array(TodoList),
106
112
  // null = no active list (avoids Option in the serialized snapshot)
107
113
  activeListId: Schema.NullOr(Schema.Int),
@@ -117,7 +123,7 @@ export class TrackerState extends Schema.Class<TrackerState>("tracker/TrackerSta
117
123
  * constructors validate their input (`new TodoItem({ text: 42, ... })` throws).
118
124
  */
119
125
  export const emptyState = (): TrackerState =>
120
- new TrackerState({ lists: [], activeListId: null, nextListId: 1 });
126
+ TrackerState.make({ lists: [], activeListId: null, nextListId: 1 });
121
127
 
122
128
  // --------------------------------------------------------------------------
123
129
  // Legacy snapshot tolerance
@@ -125,7 +131,7 @@ export const emptyState = (): TrackerState =>
125
131
 
126
132
  /** A copy of `item` with a replaced id. */
127
133
  const withId = (item: TodoItem, id: number): TodoItem =>
128
- new TodoItem({
134
+ TodoItem.make({
129
135
  id,
130
136
  title: item.title,
131
137
  description: item.description,
@@ -146,7 +152,7 @@ const withId = (item: TodoItem, id: number): TodoItem =>
146
152
  */
147
153
  const migrateList = (list: TodoList): TodoList => {
148
154
  if (list.nextItemId === LEGACY_ITEM_COUNTER) {
149
- return new TodoList({
155
+ return TodoList.make({
150
156
  id: list.id,
151
157
  name: list.name,
152
158
  items: list.items.map((item, index) => withId(item, index + 1)),
@@ -163,7 +169,7 @@ const migrateList = (list: TodoList): TodoList => {
163
169
  counter += 1;
164
170
  return assigned;
165
171
  });
166
- return new TodoList({ id: list.id, name: list.name, items, nextItemId: counter });
172
+ return TodoList.make({ id: list.id, name: list.name, items, nextItemId: counter });
167
173
  };
168
174
 
169
175
  /**
@@ -171,7 +177,7 @@ const migrateList = (list: TodoList): TodoList => {
171
177
  * every list has a counter above its ids. Pure; called once per restore.
172
178
  */
173
179
  export const migrateState = (state: TrackerState): TrackerState =>
174
- new TrackerState({
180
+ TrackerState.make({
175
181
  lists: state.lists.map(migrateList),
176
182
  activeListId: state.activeListId,
177
183
  nextListId: state.nextListId,
@@ -20,37 +20,36 @@ layer(
20
20
  }),
21
21
  )("TrackerPersistence", (it) => {
22
22
  const sampleState = (): TrackerState =>
23
- new TrackerState({
23
+ TrackerState.make({
24
24
  lists: [
25
- new TodoList({
25
+ TodoList.make({
26
26
  id: 1,
27
27
  name: "Work",
28
28
  nextItemId: 3,
29
29
  items: [
30
- new TodoItem({ id: 1, title: "write plan", done: true }),
31
- new TodoItem({ id: 2, title: "implement tracker", done: false }),
30
+ TodoItem.make({ id: 1, title: "write plan", done: true }),
31
+ TodoItem.make({ id: 2, title: "implement tracker", done: false }),
32
32
  ],
33
33
  }),
34
- new TodoList({
34
+ TodoList.make({
35
35
  id: 2,
36
36
  name: "Home",
37
37
  nextItemId: 2,
38
- items: [new TodoItem({ id: 1, title: "water plants", done: false })],
38
+ items: [TodoItem.make({ id: 1, title: "water plants", done: false })],
39
39
  }),
40
40
  ],
41
41
  activeListId: 1,
42
42
  nextListId: 3,
43
43
  });
44
44
 
45
- const decodeFailureOf = (snapshot: unknown) =>
46
- Effect.gen(function* () {
47
- const persistence = yield* TrackerPersistence;
48
- const result = yield* Effect.result(persistence.restore(snapshot));
49
- assert(Result.isFailure(result), `expected ${JSON.stringify(snapshot)} to fail`);
50
- const failure = Option.getOrThrow(Result.getFailure(result));
51
- assert.strictEqual(failure._tag, "SchemaError");
52
- return failure.message;
53
- });
45
+ const decodeFailureOf = Effect.fnUntraced(function* (snapshot: unknown) {
46
+ const persistence = yield* TrackerPersistence;
47
+ const result = yield* Effect.result(persistence.restore(snapshot));
48
+ if (!Result.isFailure(result)) assert.fail(`expected ${JSON.stringify(snapshot)} to fail`);
49
+ const failure = Result.getFailure(result).pipe(Option.getOrThrow);
50
+ assert.strictEqual(failure._tag, "SchemaError");
51
+ return failure.message;
52
+ });
54
53
 
55
54
  it.effect("save writes the encoded snapshot", () =>
56
55
  Effect.gen(function* () {
@@ -162,13 +161,13 @@ layer(
162
161
  };
163
162
 
164
163
  const restored = yield* persistence.restore(legacy);
165
- const expected = new TrackerState({
164
+ const expected = TrackerState.make({
166
165
  lists: [
167
- new TodoList({
166
+ TodoList.make({
168
167
  id: 1,
169
168
  name: "Work",
170
169
  nextItemId: 2,
171
- items: [new TodoItem({ id: 1, title: "a", done: false })],
170
+ items: [TodoItem.make({ id: 1, title: "a", done: false })],
172
171
  }),
173
172
  ],
174
173
  activeListId: 1,
@@ -176,7 +175,7 @@ layer(
176
175
  });
177
176
  assert.deepStrictEqual(encodeState(restored), encodeState(expected));
178
177
  assert.deepStrictEqual(restored.lists[0]?.items, [
179
- new TodoItem({ id: 1, title: "a", done: false }),
178
+ TodoItem.make({ id: 1, title: "a", done: false }),
180
179
  ]);
181
180
  }),
182
181
  );
@@ -2,7 +2,7 @@ import { Context, Effect, Layer, Schema } from "effect";
2
2
  import { TrackerState, decodeStateEffect, encodeStateEffect, migrateState } from "./domain.ts";
3
3
 
4
4
  /** The plain JSON shape of a `TrackerState` (what goes into the session). */
5
- export type EncodedState = Schema.Codec.Encoded<typeof TrackerState>;
5
+ export type EncodedState = typeof TrackerState.Encoded;
6
6
 
7
7
  /**
8
8
  * Persistence boundary for the tracker state.
@@ -27,7 +27,7 @@ export class TrackerPersistence extends Context.Service<
27
27
  readonly save: (state: TrackerState) => Effect.Effect<void, Schema.SchemaError>;
28
28
  readonly restore: (snapshot: unknown) => Effect.Effect<TrackerState, Schema.SchemaError>;
29
29
  }
30
- >()("tracker/TrackerPersistence") {
30
+ >()("@ftrdotdev/pi-tracker/core/persistence/TrackerPersistence") {
31
31
  static readonly layer = (
32
32
  append: (encoded: EncodedState) => void,
33
33
  ): Layer.Layer<TrackerPersistence> =>
@@ -41,7 +41,8 @@ export class TrackerPersistence extends Context.Service<
41
41
  });
42
42
 
43
43
  const restore = Effect.fn("TrackerPersistence.restore")(function* (snapshot: unknown) {
44
- return migrateState(yield* decodeStateEffect(snapshot));
44
+ const decoded = yield* decodeStateEffect(snapshot);
45
+ return migrateState(decoded);
45
46
  });
46
47
 
47
48
  return TrackerPersistence.of({ save, restore });