@ordinatio/entities 1.4.0 → 1.5.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,998 @@
1
+ import {
2
+ DEFAULT_NOTE_LIMITS,
3
+ checkNoteBody
4
+ } from "../../chunk-3VGJ4NFX.mjs";
5
+
6
+ // src/entity-notes/server/service.ts
7
+ function unknownKind(method, result) {
8
+ throw new Error(`note store ${method} returned an unknown result kind "${result.kind}": the store and the service are out of step`);
9
+ }
10
+ var MAX_TEXT_ID_LENGTH = 255;
11
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
12
+ var isText = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_TEXT_ID_LENGTH && !value.includes("\0") && !LONE_SURROGATE.test(value);
13
+ var MAX_REVISION = 2147483647;
14
+ var MAX_CURSOR_LENGTH = 512;
15
+ var isStatus = (value) => value === "live" || value === "deleted";
16
+ function createNoteService(store, suppliedLimits = DEFAULT_NOTE_LIMITS) {
17
+ const whole = (value, fallback) => typeof value === "number" && Number.isInteger(value) && value >= 1 ? value : fallback;
18
+ const maxPageSize = whole(suppliedLimits?.maxPageSize, DEFAULT_NOTE_LIMITS.maxPageSize);
19
+ const limits = { ...suppliedLimits, maxPageSize, defaultPageSize: whole(suppliedLimits?.defaultPageSize, DEFAULT_NOTE_LIMITS.defaultPageSize) };
20
+ const fail = (failure) => ({ ok: false, ...failure });
21
+ function pageSize(requested) {
22
+ if (requested === void 0 || !Number.isInteger(requested) || requested < 1) return Math.min(limits.defaultPageSize, limits.maxPageSize);
23
+ return Math.min(requested, limits.maxPageSize);
24
+ }
25
+ return {
26
+ async add(parent, body, authorId) {
27
+ if (!parent || !isText(parent.kind) || !isText(parent.id)) return fail({ reason: "invalid-parent" });
28
+ if (!isText(authorId)) return fail({ reason: "invalid-actor" });
29
+ const checked = checkNoteBody(body, limits.maxBodyLength);
30
+ if (!checked.ok) return fail({ reason: "invalid-body", problem: checked.reason, length: checked.length });
31
+ const result = await store.create({ kind: parent.kind, id: parent.id }, checked.body, authorId);
32
+ if (result.kind === "created") return { ok: true, note: result.note };
33
+ if (result.kind === "parentGone") return fail({ reason: "parent-gone" });
34
+ return unknownKind("create", result);
35
+ },
36
+ async edit(id, body, expectedRevision) {
37
+ if (!isText(id)) return fail({ reason: "not-found" });
38
+ if (!Number.isInteger(expectedRevision) || expectedRevision < 1 || expectedRevision > MAX_REVISION) return fail({ reason: "invalid-revision" });
39
+ const checked = checkNoteBody(body, limits.maxBodyLength);
40
+ if (!checked.ok) return fail({ reason: "invalid-body", problem: checked.reason, length: checked.length });
41
+ const result = await store.update(id, checked.body, expectedRevision);
42
+ if (result.kind === "updated") return { ok: true, before: result.before, after: result.after };
43
+ if (result.kind === "notFound") return fail({ reason: "not-found" });
44
+ if (result.kind === "deleted") return fail({ reason: "deleted" });
45
+ if (result.kind === "conflict") return fail({ reason: "conflict", current: result.current });
46
+ return unknownKind("update", result);
47
+ },
48
+ async remove(id, actorId) {
49
+ if (!isText(id)) return fail({ reason: "not-found" });
50
+ if (!isText(actorId)) return fail({ reason: "invalid-actor" });
51
+ const result = await store.softDelete(id, actorId);
52
+ if (result.kind === "deleted") return { ok: true, before: result.before, after: result.after };
53
+ if (result.kind === "notFound") return fail({ reason: "not-found" });
54
+ if (result.kind === "alreadyDeleted") return fail({ reason: "already-deleted" });
55
+ return unknownKind("softDelete", result);
56
+ },
57
+ async restore(id) {
58
+ if (!isText(id)) return fail({ reason: "not-found" });
59
+ const result = await store.restore(id);
60
+ if (result.kind === "restored") return { ok: true, before: result.before, after: result.after };
61
+ if (result.kind === "notFound") return fail({ reason: "not-found" });
62
+ if (result.kind === "notDeleted") return fail({ reason: "not-deleted" });
63
+ return unknownKind("restore", result);
64
+ },
65
+ async get(id) {
66
+ if (!isText(id)) return fail({ reason: "not-found" });
67
+ const note = await store.get(id);
68
+ return note ? { ok: true, note } : fail({ reason: "not-found" });
69
+ },
70
+ async list(parent, suppliedOptions) {
71
+ const options = suppliedOptions ?? {};
72
+ if (!parent || !isText(parent.kind) || !isText(parent.id)) return fail({ reason: "invalid-parent" });
73
+ if (options.status !== void 0 && !isStatus(options.status)) return fail({ reason: "invalid-status" });
74
+ const cursor = options.cursor ?? null;
75
+ if (cursor !== null && (typeof cursor !== "string" || cursor.length > MAX_CURSOR_LENGTH || cursor.includes("\0") || LONE_SURROGATE.test(cursor))) return fail({ reason: "invalid-cursor" });
76
+ const result = await store.list({ parent: { kind: parent.kind, id: parent.id }, status: options.status ?? "live", limit: pageSize(options.limit), cursor });
77
+ if (result.kind === "page") return { ok: true, notes: result.notes, nextCursor: result.nextCursor };
78
+ if (result.kind === "badCursor") return fail({ reason: "invalid-cursor" });
79
+ return unknownKind("list", result);
80
+ },
81
+ async counts(kind, parentIds, status = "live") {
82
+ const unique = Array.isArray(parentIds) ? [...new Set(parentIds.filter(isText))] : [];
83
+ if (unique.length === 0) return /* @__PURE__ */ new Map();
84
+ if (!isText(kind) || !isStatus(status)) return new Map(unique.map((id) => [id, 0]));
85
+ const counted = await store.countByParent(kind, unique, status);
86
+ return new Map(unique.map((id) => [id, counted.get(id) ?? 0]));
87
+ }
88
+ };
89
+ }
90
+
91
+ // src/entity-notes/server/memory-store.ts
92
+ var tick = () => Promise.resolve();
93
+ var parentKey = (workspace, kind, id) => `${workspace}\0${kind}\0${id}`;
94
+ var CURSOR = /^c1:(-?\d+):([\s\S]+)$/;
95
+ var newestFirst = (a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
96
+ function createMemoryNoteWorld(options = {}) {
97
+ const serialise = options.serialise ?? true;
98
+ const checkParentAtWrite = options.checkParentAtWrite ?? true;
99
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
100
+ const parents = /* @__PURE__ */ new Set();
101
+ const notes = /* @__PURE__ */ new Map();
102
+ let sequence = 0;
103
+ let parentSequence = 0;
104
+ let pendingHook = null;
105
+ let tail = Promise.resolve();
106
+ function exclusive(fn) {
107
+ if (!serialise) return fn();
108
+ const run = tail.then(fn, fn);
109
+ tail = run.then(() => void 0, () => void 0);
110
+ return run;
111
+ }
112
+ const copy = (record) => ({ ...record, createdAt: new Date(record.createdAt), updatedAt: new Date(record.updatedAt), deletedAt: record.deletedAt ? new Date(record.deletedAt) : null });
113
+ function store(workspace) {
114
+ const own = (id) => {
115
+ const row = notes.get(id);
116
+ return row && row.workspace === workspace ? row : void 0;
117
+ };
118
+ const parentIsMine = (parent) => parents.has(parentKey(workspace, parent.kind, parent.id));
119
+ return {
120
+ async create(parent, body, authorId) {
121
+ const exists = await exclusive(async () => parentIsMine(parent));
122
+ if (!exists) return { kind: "parentGone" };
123
+ if (pendingHook) {
124
+ const hook = pendingHook;
125
+ pendingHook = null;
126
+ await hook();
127
+ }
128
+ return exclusive(async () => {
129
+ await tick();
130
+ if (checkParentAtWrite && !parentIsMine(parent)) return { kind: "parentGone" };
131
+ const stamp = now();
132
+ const record = {
133
+ id: options.newId ? options.newId() : `note-${String(++sequence).padStart(9, "0")}`,
134
+ parentKind: parent.kind,
135
+ parentId: parent.id,
136
+ body,
137
+ revision: 1,
138
+ authorId,
139
+ createdAt: stamp,
140
+ updatedAt: stamp,
141
+ deletedAt: null,
142
+ deletedBy: null
143
+ };
144
+ notes.set(record.id, { workspace, record });
145
+ return { kind: "created", note: copy(record) };
146
+ });
147
+ },
148
+ async get(id) {
149
+ const row = own(id);
150
+ return row ? copy(row.record) : null;
151
+ },
152
+ update(id, body, expectedRevision) {
153
+ return exclusive(async () => {
154
+ const row = own(id);
155
+ if (!row) return { kind: "notFound" };
156
+ if (row.record.deletedAt) return { kind: "deleted" };
157
+ if (row.record.revision !== expectedRevision) return { kind: "conflict", current: copy(row.record) };
158
+ await tick();
159
+ const before = copy(row.record);
160
+ row.record = { ...row.record, body, revision: row.record.revision + 1, updatedAt: now() };
161
+ return { kind: "updated", before, after: copy(row.record) };
162
+ });
163
+ },
164
+ softDelete(id, actorId) {
165
+ return exclusive(async () => {
166
+ const row = own(id);
167
+ if (!row) return { kind: "notFound" };
168
+ if (row.record.deletedAt) return { kind: "alreadyDeleted" };
169
+ await tick();
170
+ const before = copy(row.record);
171
+ row.record = { ...row.record, deletedAt: now(), deletedBy: actorId };
172
+ return { kind: "deleted", before, after: copy(row.record) };
173
+ });
174
+ },
175
+ restore(id) {
176
+ return exclusive(async () => {
177
+ const row = own(id);
178
+ if (!row) return { kind: "notFound" };
179
+ if (!row.record.deletedAt) return { kind: "notDeleted" };
180
+ await tick();
181
+ const before = copy(row.record);
182
+ row.record = { ...row.record, deletedAt: null, deletedBy: null };
183
+ return { kind: "restored", before, after: copy(row.record) };
184
+ });
185
+ },
186
+ async list(query) {
187
+ let after = null;
188
+ if (query.cursor !== null) {
189
+ const match = CURSOR.exec(query.cursor);
190
+ if (!match) return { kind: "badCursor" };
191
+ const time = Number(match[1]);
192
+ if (!Number.isFinite(time) || Math.abs(time) > 864e13) return { kind: "badCursor" };
193
+ after = { time, id: match[2] };
194
+ }
195
+ const wantDeleted = query.status === "deleted";
196
+ const all = [...notes.values()].filter((row) => row.workspace === workspace && row.record.parentKind === query.parent.kind && row.record.parentId === query.parent.id && row.record.deletedAt !== null === wantDeleted).map((row) => row.record).sort(newestFirst);
197
+ const rest = after === null ? all : all.filter((note) => note.createdAt.getTime() < after.time || note.createdAt.getTime() === after.time && note.id < after.id);
198
+ const page = rest.slice(0, query.limit);
199
+ const last = page[page.length - 1];
200
+ const more = rest.length > page.length;
201
+ return { kind: "page", notes: page.map(copy), nextCursor: more && last ? `c1:${last.createdAt.getTime()}:${last.id}` : null };
202
+ },
203
+ async countByParent(kind, parentIds, status) {
204
+ const counts = new Map(parentIds.map((id) => [id, 0]));
205
+ const wantDeleted = status === "deleted";
206
+ for (const row of notes.values()) {
207
+ if (row.workspace !== workspace || row.record.parentKind !== kind || row.record.deletedAt !== null !== wantDeleted) continue;
208
+ if (counts.has(row.record.parentId)) counts.set(row.record.parentId, counts.get(row.record.parentId) + 1);
209
+ }
210
+ return counts;
211
+ }
212
+ };
213
+ }
214
+ return {
215
+ store,
216
+ addParent(workspace, kind, id) {
217
+ const parentId = id ?? `parent-${++parentSequence}`;
218
+ parents.add(parentKey(workspace, kind, parentId));
219
+ return parentId;
220
+ },
221
+ async removeParent(workspace, kind, id) {
222
+ await exclusive(async () => {
223
+ parents.delete(parentKey(workspace, kind, id));
224
+ for (const [noteId, row] of [...notes]) if (row.workspace === workspace && row.record.parentKind === kind && row.record.parentId === id) notes.delete(noteId);
225
+ });
226
+ },
227
+ armBeforeNoteWrite(hook) {
228
+ pendingHook = hook;
229
+ }
230
+ };
231
+ }
232
+ function createMemoryNoteHarness(options = {}) {
233
+ const world = createMemoryNoteWorld(options);
234
+ let counter = 0;
235
+ return {
236
+ async newWorkspace() {
237
+ return `workspace-${++counter}`;
238
+ },
239
+ storeFor: (workspace) => world.store(workspace),
240
+ async addParent(workspace, kind, wantedId) {
241
+ return world.addParent(workspace, kind, wantedId);
242
+ },
243
+ removeParent: (workspace, kind, id) => world.removeParent(workspace, kind, id),
244
+ armBeforeNoteWrite: (hook) => world.armBeforeNoteWrite(hook),
245
+ async cleanup() {
246
+ }
247
+ };
248
+ }
249
+
250
+ // src/entity-notes/server/contract-kit.ts
251
+ var ACTOR = "Actor-1";
252
+ var AUTHOR = "Author-1";
253
+ var KIND = "contact";
254
+ var MISSING_IDS = ["missing", "ghost-1", "x'; select 1; --", "note", '"quoted"', "%", "a b", "abc0"];
255
+ var prefixesOf = (real) => [...new Set(real.flatMap((id) => id.length > 1 ? [id.slice(0, -1), id.slice(0, Math.ceil(id.length / 2))] : []))].filter((candidate) => candidate.length > 0 && !real.includes(candidate));
256
+ var nearNow = (time) => {
257
+ const seconds = Math.round(Math.abs((typeof time === "number" ? time : time.getTime()) - Date.now()) / 1e3);
258
+ return seconds <= 600 ? "near now" : `${seconds} seconds away from now (a time-zone or clock mistake?)`;
259
+ };
260
+ var SKEW_MS = 1e3;
261
+ var ids = (list) => list.map((note) => note.id);
262
+ var pause = (ms = 3) => new Promise((resolve) => setTimeout(resolve, ms));
263
+ function inNewestFirstOrder(list) {
264
+ for (let i = 1; i < list.length; i++) {
265
+ const before = list[i - 1];
266
+ const here = list[i];
267
+ const gap = before.createdAt.getTime() - here.createdAt.getTime();
268
+ if (gap < 0) return false;
269
+ if (gap === 0 && !(before.id > here.id)) return false;
270
+ }
271
+ return true;
272
+ }
273
+ async function walk(store, parent, status, limit) {
274
+ const notes = [];
275
+ const sizes = [];
276
+ const cursors = [];
277
+ let cursor = null;
278
+ for (let page = 0; page < 100; page++) {
279
+ const result = await store.list({ parent, status, limit, cursor });
280
+ if (result.kind !== "page") throw new Error("walk: the store answered badCursor for a cursor it produced itself");
281
+ notes.push(...result.notes);
282
+ sizes.push(result.notes.length);
283
+ cursors.push(result.nextCursor);
284
+ if (result.nextCursor === null) return { notes, sizes, cursors };
285
+ cursor = result.nextCursor;
286
+ }
287
+ throw new Error("walk: the listing did not end after 100 pages");
288
+ }
289
+ function makeKit(api, harness) {
290
+ async function setup() {
291
+ const workspace = await harness.newWorkspace();
292
+ const store = harness.storeFor(workspace);
293
+ const newParent = async (kind = KIND, wantedId) => ({ kind, id: await harness.addParent(workspace, kind, wantedId) });
294
+ const add = async (parent, body = "a note", author = AUTHOR) => {
295
+ const result = await store.create(parent, body, author);
296
+ if (result.kind !== "created") throw new Error(`setup: could not add a note: ${result.kind}`);
297
+ return result.note;
298
+ };
299
+ return { workspace, store, newParent, add };
300
+ }
301
+ return { api, harness, setup };
302
+ }
303
+
304
+ // src/entity-notes/server/contract-concurrency.ts
305
+ function defineNoteStoreConcurrencyContract(kit) {
306
+ const { describe, it, expect } = kit.api;
307
+ const { setup } = kit;
308
+ describe("NoteStore contract: simultaneous callers", () => {
309
+ it("ten edits from the same revision give exactly one updated and nine conflict; the note ends at revision 2 with the winner's body", async () => {
310
+ const { store, newParent, add } = await setup();
311
+ const note = await add(await newParent(), "start");
312
+ const results = await Promise.all(Array.from({ length: 10 }, (_, i) => store.update(note.id, `edit ${i}`, 1)));
313
+ const won = results.filter((result) => result.kind === "updated");
314
+ expect(won.length).toBe(1);
315
+ expect(results.filter((result) => result.kind === "conflict").length).toBe(9);
316
+ const winner = won[0];
317
+ const final = await store.get(note.id);
318
+ expect(final).toEqual(winner && winner.kind === "updated" ? winner.after : null);
319
+ expect(final?.revision).toBe(2);
320
+ });
321
+ it("ten deletes of one note give exactly one deleted and nine alreadyDeleted, and the stored deletedBy is the winner's actor", async () => {
322
+ const { store, newParent, add } = await setup();
323
+ const note = await add(await newParent());
324
+ const results = await Promise.all(Array.from({ length: 10 }, (_, i) => store.softDelete(note.id, `actor-${i}`)));
325
+ const won = results.filter((result) => result.kind === "deleted");
326
+ expect(won.length).toBe(1);
327
+ expect(results.filter((result) => result.kind === "alreadyDeleted").length).toBe(9);
328
+ const winner = won[0];
329
+ expect((await store.get(note.id))?.deletedBy).toBe(winner && winner.kind === "deleted" ? winner.after.deletedBy : null);
330
+ });
331
+ it("ten restores of one deleted note give exactly one restored and nine notDeleted, and the note is live", async () => {
332
+ const { store, newParent, add } = await setup();
333
+ const note = await add(await newParent());
334
+ await store.softDelete(note.id, ACTOR);
335
+ const results = await Promise.all(Array.from({ length: 10 }, () => store.restore(note.id)));
336
+ expect(results.filter((result) => result.kind === "restored").length).toBe(1);
337
+ expect(results.filter((result) => result.kind === "notDeleted").length).toBe(9);
338
+ expect((await store.get(note.id))?.deletedAt).toBeNull();
339
+ });
340
+ it("an edit racing a delete (15 rounds) is never conflict, a delete that was reported is never lost, and an edit that was reported leaves revision 2 and its body", async () => {
341
+ const { store, newParent, add } = await setup();
342
+ const parent = await newParent();
343
+ for (let round = 0; round < 15; round++) {
344
+ const note = await add(parent, `round ${round}`);
345
+ let editing;
346
+ let deleting;
347
+ if (round % 2 === 0) {
348
+ editing = store.update(note.id, "edited", 1);
349
+ deleting = store.softDelete(note.id, ACTOR);
350
+ } else {
351
+ deleting = store.softDelete(note.id, ACTOR);
352
+ editing = store.update(note.id, "edited", 1);
353
+ }
354
+ const [edit, del] = await Promise.all([editing, deleting]);
355
+ expect(del.kind).toBe("deleted");
356
+ if (del.kind === "deleted") expect(del.before).toEqual(edit.kind === "updated" ? edit.after : note);
357
+ expect(edit.kind === "updated" || edit.kind === "deleted").toBe(true);
358
+ const final = await store.get(note.id);
359
+ expect(final?.deletedAt === null).toBe(false);
360
+ expect(final === null ? null : [final.revision, final.body]).toEqual(edit.kind === "updated" ? [2, "edited"] : [1, `round ${round}`]);
361
+ }
362
+ });
363
+ it("ten notes made at the same time all land, each with its own id, and are listed and counted", async () => {
364
+ const { store, newParent } = await setup();
365
+ const parent = await newParent();
366
+ const results = await Promise.all(Array.from({ length: 10 }, (_, i) => store.create(parent, `n${i}`, `a${i}`)));
367
+ const made = results.flatMap((result) => result.kind === "created" ? [result.note] : []);
368
+ expect(made.length).toBe(10);
369
+ expect(new Set(ids(made)).size).toBe(10);
370
+ expect(ids((await walk(store, parent, "live", 4)).notes).sort()).toEqual(ids(made).sort());
371
+ expect([...await store.countByParent(parent.kind, [parent.id], "live")]).toEqual([[parent.id, 10]]);
372
+ });
373
+ it("notes made while their parent is being removed: every note that was reported created is gone afterwards (no orphan), later ones are parentGone, and nothing is left to list", async () => {
374
+ const { workspace, store, newParent } = await setup();
375
+ const parent = await newParent();
376
+ const [results] = await Promise.all([
377
+ Promise.all(Array.from({ length: 10 }, (_, i) => store.create(parent, `n${i}`, "a"))),
378
+ kit.harness.removeParent(workspace, parent.kind, parent.id)
379
+ ]);
380
+ for (const result of results) {
381
+ if (result.kind === "created") expect(await store.get(result.note.id)).toBeNull();
382
+ else expect(result).toEqual({ kind: "parentGone" });
383
+ }
384
+ expect(await store.list({ parent, status: "live", limit: 20, cursor: null })).toEqual({ kind: "page", notes: [], nextCursor: null });
385
+ expect([...await store.countByParent(parent.kind, [parent.id], "live")]).toEqual([[parent.id, 0]]);
386
+ });
387
+ });
388
+ }
389
+
390
+ // src/entity-notes/server/contract-hooks.ts
391
+ function defineNoteStoreHooksContract(kit) {
392
+ const { describe, it, expect } = kit.api;
393
+ const { setup, harness } = kit;
394
+ const run = harness.armBeforeNoteWrite ? it : it.skip ?? it;
395
+ const arm = (hook) => {
396
+ if (!harness.armBeforeNoteWrite) throw new Error("This check needs harness.armBeforeNoteWrite (see contract-types.ts): supply the hook, or run with a runner that has it.skip");
397
+ harness.armBeforeNoteWrite(hook);
398
+ };
399
+ describe("NoteStore contract: parent removed while a note is being made", () => {
400
+ run("a parent removed between create's check and its write: the create answers parentGone, stores nothing, and the hook ran once", async () => {
401
+ const { workspace, store, newParent, add } = await setup();
402
+ const parent = await newParent();
403
+ const other = await newParent();
404
+ const kept = await add(other, "kept");
405
+ let ran = 0;
406
+ arm(async () => {
407
+ ran += 1;
408
+ await harness.removeParent(workspace, parent.kind, parent.id);
409
+ });
410
+ expect(await store.create(parent, "too late", "a")).toEqual({ kind: "parentGone" });
411
+ expect(ran).toBe(1);
412
+ expect(await store.list({ parent, status: "live", limit: 10, cursor: null })).toEqual({ kind: "page", notes: [], nextCursor: null });
413
+ expect([...await store.countByParent(parent.kind, [parent.id, other.id], "live")].sort()).toEqual([[parent.id, 0], [other.id, 1]].sort());
414
+ expect(await store.get(kept.id)).toEqual(kept);
415
+ });
416
+ run("the hook runs once, for the next create that gets past the first check: a create stopped by parentGone leaves it armed, and a create after it runs no hook", async () => {
417
+ const { store, newParent } = await setup();
418
+ const parent = await newParent();
419
+ let ran = 0;
420
+ arm(async () => {
421
+ ran += 1;
422
+ });
423
+ expect(await store.create({ kind: parent.kind, id: "missing" }, "x", "a")).toEqual({ kind: "parentGone" });
424
+ expect(ran).toBe(0);
425
+ expect((await store.create(parent, "one", "a")).kind).toBe("created");
426
+ expect(ran).toBe(1);
427
+ expect((await store.create(parent, "two", "a")).kind).toBe("created");
428
+ expect(ran).toBe(1);
429
+ });
430
+ run("the hook may itself use the store: a note made inside it and the note that was being made both exist afterwards, with different ids", async () => {
431
+ const { store, newParent } = await setup();
432
+ const parent = await newParent();
433
+ let inner = null;
434
+ arm(async () => {
435
+ const made = await store.create(parent, "inner", "a");
436
+ inner = made.kind === "created" ? made.note.id : null;
437
+ });
438
+ const outer = await store.create(parent, "outer", "a");
439
+ expect(outer.kind).toBe("created");
440
+ const all = (await walk(store, parent, "live", 10)).notes;
441
+ expect(all.map((note) => note.body).sort()).toEqual(["inner", "outer"]);
442
+ expect(inner !== null && outer.kind === "created" && inner !== outer.note.id).toBe(true);
443
+ });
444
+ });
445
+ }
446
+
447
+ // src/entity-notes/server/contract-lists.ts
448
+ function defineNoteStoreListsContract(kit) {
449
+ const { describe, it, expect } = kit.api;
450
+ const { setup } = kit;
451
+ const NOTHING = { kind: "page", notes: [], nextCursor: null };
452
+ describe("NoteStore contract: lists, pages and counts", () => {
453
+ it("a parent with no notes, a parent that does not exist and a parent that is only the beginning of a real id list an empty page with no cursor, although the real parent has live and deleted notes", async () => {
454
+ const { store, newParent, add } = await setup();
455
+ const empty = await newParent();
456
+ const real = await newParent();
457
+ await add(real, "live");
458
+ await store.softDelete((await add(real, "dead")).id, ACTOR);
459
+ for (const status of ["live", "deleted"]) {
460
+ expect(await store.list({ parent: empty, status, limit: 5, cursor: null })).toEqual(NOTHING);
461
+ expect(await store.list({ parent: { kind: empty.kind, id: "missing" }, status, limit: 5, cursor: null })).toEqual(NOTHING);
462
+ expect(await store.list({ parent: { kind: "nothing", id: "o'brien" }, status, limit: 5, cursor: null })).toEqual(NOTHING);
463
+ for (const id of [`${real.id}x`, ...prefixesOf([real.id])]) expect(await store.list({ parent: { kind: real.kind, id }, status, limit: 5, cursor: null })).toEqual(NOTHING);
464
+ }
465
+ });
466
+ it("a listing shows only the notes of its own parent: two parents of one kind and a parent of another kind with a similar id keep their live and deleted notes apart (the same id under another kind too, where the harness can make one)", async () => {
467
+ const { store, newParent, add } = await setup();
468
+ const [a, b] = [await newParent(), await newParent()];
469
+ const c = await newParent("company", a.id);
470
+ const made = {};
471
+ for (const [parent, label] of [[a, "a1"], [a, "a2"], [b, "b1"], [b, "b2"], [c, "c1"], [c, "c2"]]) made[label] = await add(parent, label);
472
+ for (const label of ["a2", "b2", "c2"]) await store.softDelete(made[label].id, ACTOR);
473
+ const bodies = async (parent, status) => {
474
+ const rows = (await walk(store, parent, status, 10)).notes;
475
+ for (const row of rows) expect(row).toEqual(await store.get(row.id));
476
+ return rows.map((note) => note.body);
477
+ };
478
+ expect(await bodies(a, "live")).toEqual(["a1"]);
479
+ expect(await bodies(a, "deleted")).toEqual(["a2"]);
480
+ expect(await bodies(b, "live")).toEqual(["b1"]);
481
+ expect(await bodies(b, "deleted")).toEqual(["b2"]);
482
+ expect(await bodies(c, "live")).toEqual(["c1"]);
483
+ expect(await bodies(c, "deleted")).toEqual(["c2"]);
484
+ });
485
+ it("a listing is NEWEST FIRST on (createdAt, id) and complete: thirty notes made one after the other come back once each, in order, in one page, and editing a note does not move it", async () => {
486
+ const { store, newParent, add } = await setup();
487
+ const parent = await newParent();
488
+ const made = [];
489
+ for (let i = 0; i < 30; i++) made.push((await add(parent, `n${i} \r
490
+ `)).id);
491
+ const all = await walk(store, parent, "live", 100);
492
+ expect(all.sizes).toEqual([30]);
493
+ expect(all.cursors).toEqual([null]);
494
+ expect(inNewestFirstOrder(all.notes)).toBe(true);
495
+ expect(ids(all.notes).sort()).toEqual([...made].sort());
496
+ const top = await walk(store, parent, "live", 5);
497
+ expect(ids(top.notes)).toEqual(ids(all.notes));
498
+ await pause();
499
+ for (const index of [0, 15, 29]) await store.update(made[index], "edited later", 1);
500
+ const after = await walk(store, parent, "live", 100);
501
+ expect(ids(after.notes)).toEqual(ids(all.notes));
502
+ for (const row of after.notes) expect(row).toEqual(await store.get(row.id));
503
+ });
504
+ it("pages have exactly `limit` notes except the last (also over edited notes), nextCursor is null only on the last page, and a limit equal to the number of notes is one page with no cursor; limits 1, 7, 29 and 30 all walk the same listing", async () => {
505
+ const { store, newParent, add } = await setup();
506
+ const parent = await newParent();
507
+ const made = [];
508
+ for (let i = 0; i < 30; i++) {
509
+ made.push((await add(parent, `n${i}`)).id);
510
+ await pause(2);
511
+ }
512
+ const whole = ids((await walk(store, parent, "live", 100)).notes);
513
+ await pause();
514
+ for (const index of [0, 3, 6, 7, 14, 21, 28, 29]) await store.update(made[index], "edited", 1);
515
+ for (const limit of [1, 7, 29, 30]) {
516
+ const paged = await walk(store, parent, "live", limit);
517
+ expect(ids(paged.notes)).toEqual(whole);
518
+ const full = paged.sizes.slice(0, -1).every((size) => size === limit);
519
+ expect(full && paged.sizes[paged.sizes.length - 1] <= limit && paged.sizes[paged.sizes.length - 1] >= 1).toBe(true);
520
+ expect(paged.cursors.slice(0, -1).every((cursor) => typeof cursor === "string" && cursor.length > 0)).toBe(true);
521
+ expect(paged.cursors[paged.cursors.length - 1]).toBeNull();
522
+ expect(paged.sizes.length).toBe(Math.ceil(30 / limit));
523
+ }
524
+ });
525
+ it("live and deleted listings are apart: a deleted note leaves the live listing and joins the deleted one, and a restored note returns to its ORIGINAL place by createdAt", async () => {
526
+ const { store, newParent, add } = await setup();
527
+ const parent = await newParent();
528
+ const made = [];
529
+ for (let i = 0; i < 10; i++) {
530
+ made.push(await add(parent, i === 2 ? `long ${"\xE9".repeat(9e3)}` : `n${i}`));
531
+ await pause();
532
+ }
533
+ const original = ids((await walk(store, parent, "live", 100)).notes);
534
+ const [two, five, eight] = [made[2], made[5], made[8]];
535
+ for (const note of [five, eight, two]) {
536
+ await store.softDelete(note.id, ACTOR);
537
+ await pause();
538
+ }
539
+ const live = await walk(store, parent, "live", 4);
540
+ expect(live.sizes).toEqual([4, 3]);
541
+ expect(live.cursors[0] === null).toBe(false);
542
+ expect(live.cursors[1]).toBeNull();
543
+ const dead = await walk(store, parent, "deleted", 2);
544
+ expect(ids(live.notes)).toEqual(original.filter((id) => ![two, five, eight].some((note) => note.id === id)));
545
+ expect(ids(dead.notes).sort()).toEqual([two, five, eight].map((note) => note.id).sort());
546
+ expect(inNewestFirstOrder(dead.notes)).toBe(true);
547
+ expect(dead.sizes).toEqual([2, 1]);
548
+ expect(dead.cursors[0] === null).toBe(false);
549
+ expect(dead.cursors[1]).toBeNull();
550
+ const deadAll = await walk(store, parent, "deleted", 100);
551
+ for (const row of deadAll.notes) expect(row).toEqual(await store.get(row.id));
552
+ for (const row of live.notes) expect(row).toEqual(await store.get(row.id));
553
+ if (made[8].createdAt.getTime() > made[5].createdAt.getTime() && made[5].createdAt.getTime() > made[2].createdAt.getTime()) {
554
+ expect(ids(deadAll.notes)).toEqual([eight.id, five.id, two.id]);
555
+ }
556
+ for (const note of [eight, two, five]) await store.restore(note.id);
557
+ expect(ids((await walk(store, parent, "live", 3)).notes)).toEqual(original);
558
+ expect((await walk(store, parent, "deleted", 3)).notes).toEqual([]);
559
+ });
560
+ it("a page can hold 100 notes: 120 notes list as a page of 100 with a cursor and then a page of 20 with none", async () => {
561
+ const { store, newParent, add } = await setup();
562
+ const parent = await newParent();
563
+ for (let i = 0; i < 120; i++) await add(parent, `n${i}`);
564
+ const paged = await walk(store, parent, "live", 100);
565
+ expect(paged.sizes).toEqual([100, 20]);
566
+ expect(paged.cursors[0] === null).toBe(false);
567
+ expect(paged.cursors[1]).toBeNull();
568
+ expect(new Set(ids(paged.notes)).size).toBe(120);
569
+ expect(inNewestFirstOrder(paged.notes)).toBe(true);
570
+ });
571
+ it("paging is by position, not by offset: notes added and deleted between two page fetches never make a note repeat or an unseen note vanish", async () => {
572
+ const { store, newParent, add } = await setup();
573
+ const parent = await newParent();
574
+ const made = [];
575
+ for (let i = 0; i < 12; i++) made.push(await add(parent, `n${i}`));
576
+ const order = ids((await walk(store, parent, "live", 100)).notes);
577
+ const first = await store.list({ parent, status: "live", limit: 4, cursor: null });
578
+ if (first.kind !== "page" || first.nextCursor === null) throw new Error("expected a first page with a cursor");
579
+ const seen = ids(first.notes);
580
+ expect(seen).toEqual(order.slice(0, 4));
581
+ await pause();
582
+ const newer = await add(parent, "added meanwhile");
583
+ const removedUnseen = order[6];
584
+ await store.softDelete(removedUnseen, ACTOR);
585
+ const rest = [];
586
+ let cursor = first.nextCursor;
587
+ for (let pages = 0; cursor !== null; pages++) {
588
+ if (pages > 100) throw new Error("the listing did not end after 100 pages");
589
+ const page = await store.list({ parent, status: "live", limit: 4, cursor });
590
+ if (page.kind !== "page") throw new Error("badCursor");
591
+ rest.push(...ids(page.notes));
592
+ cursor = page.nextCursor;
593
+ }
594
+ const at = first.notes[3];
595
+ const tie = newer.createdAt.getTime() === at.createdAt.getTime();
596
+ const newerFollows = newer.createdAt.getTime() < at.createdAt.getTime() || tie && newer.id < at.id;
597
+ expect(rest.filter((id) => id !== newer.id)).toEqual(order.slice(4).filter((id) => id !== removedUnseen));
598
+ expect(rest.includes(newer.id)).toBe(newerFollows);
599
+ expect(seen.includes(newer.id)).toBe(false);
600
+ });
601
+ it("a cursor still works after the note it points at is deleted: the next page is exactly the notes that follow its position", async () => {
602
+ const { store, newParent, add } = await setup();
603
+ const parent = await newParent();
604
+ for (let i = 0; i < 10; i++) await add(parent, `n${i}`);
605
+ const order = ids((await walk(store, parent, "live", 100)).notes);
606
+ const first = await store.list({ parent, status: "live", limit: 4, cursor: null });
607
+ if (first.kind !== "page" || first.nextCursor === null) throw new Error("expected a first page with a cursor");
608
+ expect((await store.softDelete(order[3], ACTOR)).kind).toBe("deleted");
609
+ const second = await store.list({ parent, status: "live", limit: 100, cursor: first.nextCursor });
610
+ expect(second.kind === "page" ? ids(second.notes) : second.kind).toEqual(order.slice(4));
611
+ });
612
+ it("a cursor the store did not produce is badCursor and never an error: garbage, numbers out of any range, quotes; a good cursor still works afterwards", async () => {
613
+ const { store, newParent, add } = await setup();
614
+ const parent = await newParent();
615
+ for (let i = 0; i < 3; i++) await add(parent, `n${i}`);
616
+ const real = await store.list({ parent, status: "live", limit: 2, cursor: null });
617
+ const goodCursor = real.kind === "page" ? real.nextCursor : null;
618
+ if (goodCursor === null) throw new Error("expected a cursor");
619
+ for (const cursor of [`zzz${goodCursor}`, ` ${goodCursor}`, "garbage", "not a cursor", "0", "-1", "'; select 1; --", '{"a":1}', "c1:99999999999999999999:x", "c1:-99999999999999999999:x", "x".repeat(300)]) {
620
+ expect(await store.list({ parent, status: "live", limit: 2, cursor })).toEqual({ kind: "badCursor" });
621
+ }
622
+ const good = await store.list({ parent, status: "live", limit: 2, cursor: null });
623
+ expect(good.kind === "page" && good.notes.length).toBe(2);
624
+ });
625
+ it("a cursor is only a position: one taken from another parent of the same workspace gives a page of the NEW parent, never of the old one and never an error", async () => {
626
+ const { store, newParent, add } = await setup();
627
+ const [a, b] = [await newParent(), await newParent()];
628
+ const ofB = [];
629
+ for (let i = 0; i < 6; i++) {
630
+ await add(a, `a${i}`);
631
+ ofB.push(await add(b, `b${i}`));
632
+ await pause();
633
+ }
634
+ const first = await store.list({ parent: a, status: "live", limit: 2, cursor: null });
635
+ if (first.kind !== "page" || first.nextCursor === null) throw new Error("expected a cursor");
636
+ const at = first.notes[1];
637
+ const crossed = await store.list({ parent: b, status: "live", limit: 50, cursor: first.nextCursor });
638
+ const olderThanAt = (note) => note.createdAt.getTime() < at.createdAt.getTime() || note.createdAt.getTime() === at.createdAt.getTime() && note.id < at.id;
639
+ const expected = ids((await walk(store, b, "live", 100)).notes).filter((id) => olderThanAt(ofB.find((note) => note.id === id)));
640
+ expect(crossed.kind === "page" ? ids(crossed.notes) : crossed.kind).toEqual(expected);
641
+ const otherStatus = await store.list({ parent: a, status: "deleted", limit: 50, cursor: first.nextCursor });
642
+ expect(otherStatus).toEqual({ kind: "page", notes: [], nextCursor: null });
643
+ });
644
+ it("countByParent counts live and deleted apart, answers EVERY asked id (0 for none, unknown, another kind or odd ids), a repeated id is one entry, and an empty list is an empty map", async () => {
645
+ const { store, newParent, add } = await setup();
646
+ const [a, b, c] = [await newParent(), await newParent(), await newParent("company")];
647
+ const made = [];
648
+ for (const [parent, n] of [[a, 3], [b, 1], [c, 2]]) for (let i = 0; i < n; i++) made.push(await add(parent, `n${i}`));
649
+ await store.softDelete(made[0].id, ACTOR);
650
+ const prefixes = [`${a.id}x`, ...prefixesOf([a.id, b.id])];
651
+ const ofCompany = c.id !== a.id && c.id !== b.id ? [c.id] : [];
652
+ const asked = [a.id, b.id, "missing", "o'brien", a.id, ...ofCompany, ...prefixes];
653
+ const live = await store.countByParent(a.kind, asked, "live");
654
+ expect([...live].sort()).toEqual([[a.id, 2], [b.id, 1], ["o'brien", 0], ["missing", 0], ...ofCompany.map((id) => [id, 0]), ...prefixes.map((id) => [id, 0])].sort());
655
+ const dead = await store.countByParent(a.kind, [a.id, b.id], "deleted");
656
+ expect([...dead].sort()).toEqual([[a.id, 1], [b.id, 0]].sort());
657
+ expect([...await store.countByParent("company", [c.id], "live")]).toEqual([[c.id, 2]]);
658
+ expect([...await store.countByParent(a.kind, [], "live")]).toEqual([]);
659
+ });
660
+ it("countByParent works for 5,000 ids at once: every asked id is present, the two real ones (first and last) are counted and the rest are 0", async () => {
661
+ const { store, newParent, add } = await setup();
662
+ const [a, b] = [await newParent(), await newParent()];
663
+ await add(a, "one");
664
+ await add(b, "one");
665
+ await add(b, "two");
666
+ const asked = [a.id, ...Array.from({ length: 4998 }, (_, i) => `ghost-${i}`), b.id];
667
+ const counted = await store.countByParent(a.kind, asked, "live");
668
+ expect(counted.size).toBe(5e3);
669
+ expect(asked.every((id) => counted.has(id))).toBe(true);
670
+ expect([counted.get(a.id), counted.get(b.id), counted.get("ghost-0"), counted.get("ghost-4997")]).toEqual([1, 2, 0, 0]);
671
+ });
672
+ });
673
+ }
674
+
675
+ // src/entity-notes/server/contract-notes.ts
676
+ function defineNoteStoreNotesContract(kit) {
677
+ const { describe, it, expect } = kit.api;
678
+ const { setup } = kit;
679
+ describe("NoteStore contract: single-note rules", () => {
680
+ it("create stores the note exactly (indentation, newlines, quotes and emoji kept, also a body of the full 10,000 characters) with revision 1, no deletion, valid times near now, and get returns the same note", async () => {
681
+ const { store, newParent, add } = await setup();
682
+ const parent = await newParent();
683
+ const body = ` indented "quote" it's
684
+ second line \xE9\u{1F600} cafe\u0301 \xE9
685
+
686
+ last \r
687
+
688
+ `;
689
+ const note = await add(parent, body, "Author-9");
690
+ expect(note.body).toBe(body);
691
+ expect(note.authorId).toBe("Author-9");
692
+ expect([note.parentKind, note.parentId]).toEqual([parent.kind, parent.id]);
693
+ expect([note.revision, note.deletedAt, note.deletedBy]).toEqual([1, null, null]);
694
+ expect(note.createdAt instanceof Date && note.updatedAt instanceof Date).toBe(true);
695
+ expect(Number.isNaN(note.createdAt.getTime()) || Number.isNaN(note.updatedAt.getTime())).toBe(false);
696
+ expect(note.updatedAt.getTime() >= note.createdAt.getTime() - SKEW_MS).toBe(true);
697
+ expect(nearNow(note.createdAt)).toBe("near now");
698
+ expect(note.id.length > 0).toBe(true);
699
+ expect(await store.get(note.id)).toEqual(note);
700
+ const long = `first line ${"\xE9".repeat(1e4)}`.slice(0, 9994) + "\n end";
701
+ const big = await add(parent, long);
702
+ expect(big.body).toBe(long);
703
+ expect((await store.get(big.id))?.body).toBe(long);
704
+ });
705
+ it("every note gets an id of its own, also when many are made one after the other", async () => {
706
+ const { newParent, add } = await setup();
707
+ const parent = await newParent();
708
+ const made = [];
709
+ for (let i = 0; i < 25; i++) made.push((await add(parent, `note ${i}`)).id);
710
+ expect(new Set(made).size).toBe(25);
711
+ });
712
+ it("create under a parent that does not exist, has another kind, or is only the beginning of a real id answers parentGone and stores nothing", async () => {
713
+ const { store, newParent } = await setup();
714
+ const parent = await newParent();
715
+ for (const bad of [{ kind: parent.kind, id: "missing" }, { kind: "company", id: parent.id }, { kind: parent.kind, id: `${parent.id}'` }, { kind: "nothing", id: "nothing" }, ...prefixesOf([parent.id]).map((id) => ({ kind: parent.kind, id }))]) {
716
+ expect(await store.create(bad, "hello", "a")).toEqual({ kind: "parentGone" });
717
+ const listed = await store.list({ parent: bad, status: "live", limit: 10, cursor: null });
718
+ expect(listed).toEqual({ kind: "page", notes: [], nextCursor: null });
719
+ }
720
+ expect(await store.list({ parent, status: "live", limit: 10, cursor: null })).toEqual({ kind: "page", notes: [], nextCursor: null });
721
+ expect([...await store.countByParent(parent.kind, [parent.id], "live")]).toEqual([[parent.id, 0]]);
722
+ });
723
+ it("get answers null for ids that do not exist (also odd ones, a real id with a character added, and only the beginning of a real id) and returns deleted notes", async () => {
724
+ const { store, newParent, add } = await setup();
725
+ const note = await add(await newParent());
726
+ for (const id of [...MISSING_IDS, `${note.id}x`, `x${note.id}`, ...prefixesOf([note.id])]) expect(await store.get(id)).toBeNull();
727
+ const gone = await store.softDelete(note.id, ACTOR);
728
+ const read = await store.get(note.id);
729
+ expect(read === null ? null : read.id).toBe(note.id);
730
+ expect(gone.kind === "deleted" ? gone.after : null).toEqual(read);
731
+ expect(read === null ? "null" : read.deletedAt === null ? "live" : "deleted").toBe("deleted");
732
+ });
733
+ it("update is compare-and-set: the new body and revision + 1, `before` and `after` right, createdAt and author untouched, updatedAt moved forward, and get agrees", async () => {
734
+ const { store, newParent, add } = await setup();
735
+ const parent = await newParent();
736
+ const note = await add(parent, "first\r\n one \r\n ", "Author-3");
737
+ await pause();
738
+ const probe = await add(parent, "clock probe");
739
+ const clockMoves = probe.createdAt.getTime() > note.createdAt.getTime();
740
+ const one = await store.update(note.id, " second\n\n line \xE9\u{1F600} \r\n ", 1);
741
+ if (one.kind !== "updated") throw new Error(`expected updated, got ${one.kind}`);
742
+ expect(one.before).toEqual(note);
743
+ expect([one.after.body, one.after.revision, one.after.authorId, one.after.id]).toEqual([" second\n\n line \xE9\u{1F600} \r\n ", 2, "Author-3", note.id]);
744
+ expect(one.after.createdAt.getTime()).toBe(note.createdAt.getTime());
745
+ expect(one.after.updatedAt.getTime() >= note.updatedAt.getTime()).toBe(true);
746
+ if (clockMoves) expect(one.after.updatedAt.getTime() > note.updatedAt.getTime()).toBe(true);
747
+ expect([one.after.deletedAt, one.after.deletedBy]).toEqual([null, null]);
748
+ expect(await store.get(note.id)).toEqual(one.after);
749
+ const two = await store.update(note.id, "third", 2);
750
+ expect(two.kind === "updated" ? [two.before.revision, two.after.revision, two.after.body] : two.kind).toEqual([2, 3, "third"]);
751
+ await pause();
752
+ const same = await store.update(note.id, "third", 3);
753
+ expect(same.kind === "updated" ? [same.before.revision, same.after.revision, same.after.body] : same.kind).toEqual([3, 4, "third"]);
754
+ expect((await store.get(note.id))?.revision).toBe(4);
755
+ });
756
+ it("a stale or future revision answers conflict carrying the CURRENT note, and changes nothing", async () => {
757
+ const { store, newParent, add } = await setup();
758
+ const note = await add(await newParent(), "v1\r\n x \r\n ", "Author-4");
759
+ const edited = await store.update(note.id, "v2\r\n y \r\n ", 1);
760
+ if (edited.kind !== "updated") throw new Error("setup");
761
+ await pause();
762
+ for (const revision of [1, 3, 99, 2147483647]) {
763
+ const result = await store.update(note.id, "lost", revision);
764
+ expect(result.kind === "conflict" ? result.current : result.kind).toEqual(edited.after);
765
+ }
766
+ expect(await store.get(note.id)).toEqual(edited.after);
767
+ });
768
+ it("update precedence is notFound, then deleted, then conflict: unknown ids are notFound (also odd ones), a deleted note is deleted whatever the revision, and nothing is written", async () => {
769
+ const { store, newParent, add } = await setup();
770
+ const note = await add(await newParent(), "keep");
771
+ for (const id of [...MISSING_IDS, ...prefixesOf([note.id])]) expect(await store.update(id, "x", 1)).toEqual({ kind: "notFound" });
772
+ const gone = await store.softDelete(note.id, ACTOR);
773
+ if (gone.kind !== "deleted") throw new Error("setup");
774
+ await pause();
775
+ expect(await store.update(note.id, "x", 1)).toEqual({ kind: "deleted" });
776
+ expect(await store.update(note.id, "x", 7)).toEqual({ kind: "deleted" });
777
+ expect(await store.get(note.id)).toEqual(gone.after);
778
+ });
779
+ it("softDelete hides nothing else: it sets deletedAt and deletedBy, leaves revision, updatedAt and body alone, answers before and after, a second delete is alreadyDeleted and keeps the first actor, an unknown id is notFound", async () => {
780
+ const { store, newParent, add } = await setup();
781
+ const parent = await newParent();
782
+ const note = await add(parent, "body\r\n one \r\n ", "Author-5");
783
+ const edited = await store.update(note.id, "body 2\r\n two \r\n ", 1);
784
+ if (edited.kind !== "updated") throw new Error("setup");
785
+ await pause(30);
786
+ const probe = await add(parent, "clock probe");
787
+ const clockMoves = probe.createdAt.getTime() > note.createdAt.getTime();
788
+ const result = await store.softDelete(note.id, "Actor-7");
789
+ if (result.kind !== "deleted") throw new Error(`expected deleted, got ${result.kind}`);
790
+ expect(result.before).toEqual(edited.after);
791
+ expect(result.after).toEqual({ ...result.before, deletedAt: result.after.deletedAt, deletedBy: "Actor-7" });
792
+ expect(result.after.deletedAt instanceof Date).toBe(true);
793
+ const deletedAt = result.after.deletedAt.getTime();
794
+ expect(nearNow(deletedAt)).toBe("near now");
795
+ expect(deletedAt >= note.createdAt.getTime() - SKEW_MS).toBe(true);
796
+ expect(deletedAt >= edited.after.updatedAt.getTime() - SKEW_MS).toBe(true);
797
+ if (clockMoves) expect(deletedAt !== edited.after.updatedAt.getTime() && deletedAt !== note.createdAt.getTime()).toBe(true);
798
+ expect(result.after.deletedBy).toBe("Actor-7");
799
+ expect([result.after.revision, result.after.body]).toEqual([2, "body 2\r\n two \r\n "]);
800
+ expect(result.after.updatedAt.getTime()).toBe(edited.after.updatedAt.getTime());
801
+ expect(await store.get(note.id)).toEqual(result.after);
802
+ await pause();
803
+ expect(await store.softDelete(note.id, "actor-8")).toEqual({ kind: "alreadyDeleted" });
804
+ expect(await store.get(note.id)).toEqual(result.after);
805
+ for (const id of [...MISSING_IDS, ...prefixesOf([note.id])]) expect(await store.softDelete(id, ACTOR)).toEqual({ kind: "notFound" });
806
+ });
807
+ it("restore clears deletedAt and deletedBy and leaves revision, body, createdAt and updatedAt alone (also for an EDITED note); a live note is notDeleted and unchanged, an unknown id is notFound; delete, restore and delete again works, and an edit after a restore continues the revision", async () => {
808
+ const { store, newParent, add } = await setup();
809
+ const first = await add(await newParent(), "body \r\n \n ");
810
+ await pause();
811
+ const edit1 = await store.update(first.id, "body 2 \r\n ", 1);
812
+ if (edit1.kind !== "updated") throw new Error("setup");
813
+ const note = edit1.after;
814
+ await pause();
815
+ expect(await store.restore(note.id)).toEqual({ kind: "notDeleted" });
816
+ expect(await store.get(note.id)).toEqual(note);
817
+ for (const id of [...MISSING_IDS, ...prefixesOf([note.id])]) expect(await store.restore(id)).toEqual({ kind: "notFound" });
818
+ const gone = await store.softDelete(note.id, ACTOR);
819
+ if (gone.kind !== "deleted") throw new Error("setup");
820
+ await pause();
821
+ const back = await store.restore(note.id);
822
+ if (back.kind !== "restored") throw new Error(`expected restored, got ${back.kind}`);
823
+ expect(back.before).toEqual(gone.after);
824
+ expect(back.after).toEqual({ ...back.before, deletedAt: null, deletedBy: null });
825
+ expect([back.after.deletedAt, back.after.deletedBy, back.after.revision, back.after.body]).toEqual([null, null, 2, "body 2 \r\n "]);
826
+ expect(back.after.updatedAt.getTime()).toBe(note.updatedAt.getTime());
827
+ expect(back.after.createdAt.getTime()).toBe(first.createdAt.getTime());
828
+ expect(await store.get(note.id)).toEqual(back.after);
829
+ expect((await store.softDelete(note.id, "actor-2")).kind).toBe("deleted");
830
+ expect((await store.restore(note.id)).kind).toBe("restored");
831
+ const edit = await store.update(note.id, "after restore", 2);
832
+ expect(edit.kind === "updated" ? edit.after.revision : edit.kind).toBe(3);
833
+ });
834
+ it("timestamps keep milliseconds: createdAt, updatedAt and deletedAt of notes made, edited and deleted a few milliseconds apart are not all whole seconds", async () => {
835
+ const { store, newParent, add } = await setup();
836
+ const parent = await newParent();
837
+ const created = [];
838
+ const updated = [];
839
+ const deleted = [];
840
+ for (let i = 0; i < 12; i++) {
841
+ const note = await add(parent, `n${i}`);
842
+ await pause(7);
843
+ await store.update(note.id, `n${i} edited`, 1);
844
+ await pause(7);
845
+ await store.softDelete(note.id, ACTOR);
846
+ const read = await store.get(note.id);
847
+ if (read === null || read.deletedAt === null) throw new Error("setup");
848
+ created.push(read.createdAt.getTime());
849
+ updated.push(read.updatedAt.getTime());
850
+ deleted.push(read.deletedAt.getTime());
851
+ }
852
+ const keepsMilliseconds = (times) => times.some((time) => time % 1e3 !== 0);
853
+ expect(keepsMilliseconds(created)).toBe(true);
854
+ expect(keepsMilliseconds(updated)).toBe(true);
855
+ expect(keepsMilliseconds(deleted)).toBe(true);
856
+ });
857
+ it("removing a parent removes its notes, live and deleted: get, list and counts show nothing, a new note is parentGone, and the notes of other parents (also one of another kind with the same id) are untouched", async () => {
858
+ const { workspace, store, newParent, add } = await setup();
859
+ const doomed = await newParent();
860
+ const stays = await newParent("company", doomed.id);
861
+ const [live, dead, keep] = [await add(doomed, "live"), await add(doomed, "dead"), await add(stays, "keep")];
862
+ await store.softDelete(dead.id, ACTOR);
863
+ await kit.harness.removeParent(workspace, doomed.kind, doomed.id);
864
+ expect(await store.get(live.id)).toBeNull();
865
+ expect(await store.get(dead.id)).toBeNull();
866
+ expect(await store.get(keep.id)).toEqual(keep);
867
+ for (const status of ["live", "deleted"]) expect(await store.list({ parent: doomed, status, limit: 10, cursor: null })).toEqual({ kind: "page", notes: [], nextCursor: null });
868
+ expect([...await store.countByParent(doomed.kind, [doomed.id], "live")]).toEqual([[doomed.id, 0]]);
869
+ expect([...await store.countByParent(doomed.kind, [doomed.id], "deleted")]).toEqual([[doomed.id, 0]]);
870
+ expect(await store.create(doomed, "late", "a")).toEqual({ kind: "parentGone" });
871
+ expect([...await store.countByParent(stays.kind, [stays.id], "live")]).toEqual([[stays.id, 1]]);
872
+ });
873
+ });
874
+ }
875
+
876
+ // src/entity-notes/server/contract-tenancy.ts
877
+ function defineNoteStoreTenancyContract(kit) {
878
+ const { describe, it, expect } = kit.api;
879
+ const { setup } = kit;
880
+ const NOTHING = { kind: "page", notes: [], nextCursor: null };
881
+ describe("NoteStore contract: tenancy", () => {
882
+ it("reads: another workspace's note is null, its parent lists nothing and counts 0, live and deleted", async () => {
883
+ const mine = await setup();
884
+ const theirs = await setup();
885
+ const parent = await theirs.newParent();
886
+ const note = await theirs.add(parent, "secret");
887
+ const gone = await theirs.add(parent, "secret 2");
888
+ await theirs.store.softDelete(gone.id, ACTOR);
889
+ expect(await mine.store.get(note.id)).toBeNull();
890
+ expect(await mine.store.get(gone.id)).toBeNull();
891
+ for (const status of ["live", "deleted"]) {
892
+ expect(await mine.store.list({ parent, status, limit: 10, cursor: null })).toEqual(NOTHING);
893
+ expect([...await mine.store.countByParent(parent.kind, [parent.id], status)]).toEqual([[parent.id, 0]]);
894
+ }
895
+ expect(ids((await walk(theirs.store, parent, "live", 10)).notes)).toEqual([note.id]);
896
+ });
897
+ it("writes: update, softDelete and restore of another workspace's note are notFound and change nothing there", async () => {
898
+ const mine = await setup();
899
+ const theirs = await setup();
900
+ const note = await theirs.add(await theirs.newParent(), "theirs");
901
+ const dead = await theirs.add(await theirs.newParent(), "theirs, deleted");
902
+ await theirs.store.softDelete(dead.id, ACTOR);
903
+ const deadNow = await theirs.store.get(dead.id);
904
+ expect(await mine.store.update(note.id, "mine now", 1)).toEqual({ kind: "notFound" });
905
+ expect(await mine.store.update(note.id, "mine now", 99)).toEqual({ kind: "notFound" });
906
+ expect(await mine.store.update(dead.id, "mine now", 1)).toEqual({ kind: "notFound" });
907
+ expect(await mine.store.update(dead.id, "mine now", 99)).toEqual({ kind: "notFound" });
908
+ expect(await mine.store.softDelete(note.id, ACTOR)).toEqual({ kind: "notFound" });
909
+ expect(await mine.store.softDelete(dead.id, ACTOR)).toEqual({ kind: "notFound" });
910
+ expect(await mine.store.restore(dead.id)).toEqual({ kind: "notFound" });
911
+ expect(await mine.store.restore(note.id)).toEqual({ kind: "notFound" });
912
+ expect(await theirs.store.get(note.id)).toEqual(note);
913
+ expect(await theirs.store.get(dead.id)).toEqual(deadNow);
914
+ });
915
+ it("create under another workspace's parent is parentGone and stores nothing in either workspace", async () => {
916
+ const mine = await setup();
917
+ const theirs = await setup();
918
+ const parent = await theirs.newParent();
919
+ expect(await mine.store.create(parent, "intruder", "a")).toEqual({ kind: "parentGone" });
920
+ expect(await theirs.store.list({ parent, status: "live", limit: 10, cursor: null })).toEqual(NOTHING);
921
+ expect(await mine.store.list({ parent, status: "live", limit: 10, cursor: null })).toEqual(NOTHING);
922
+ });
923
+ it("a cursor from another workspace shows none of its notes: used on my own parent it pages only my notes", async () => {
924
+ const mine = await setup();
925
+ const theirs = await setup();
926
+ const [mineParent, theirParent] = [await mine.newParent(), await theirs.newParent()];
927
+ for (let i = 0; i < 5; i++) {
928
+ await mine.add(mineParent, `mine ${i}`);
929
+ await theirs.add(theirParent, `theirs ${i}`);
930
+ }
931
+ const first = await theirs.store.list({ parent: theirParent, status: "live", limit: 2, cursor: null });
932
+ if (first.kind !== "page" || first.nextCursor === null) throw new Error("expected a cursor");
933
+ const crossed = await mine.store.list({ parent: mineParent, status: "live", limit: 50, cursor: first.nextCursor });
934
+ expect(crossed.kind === "badCursor" || crossed.kind === "page" && crossed.notes.every((note) => note.body.startsWith("mine"))).toBe(true);
935
+ const asTheirs = await mine.store.list({ parent: theirParent, status: "live", limit: 50, cursor: first.nextCursor });
936
+ expect(asTheirs.kind === "badCursor" || asTheirs.kind === "page" && asTheirs.notes.length === 0).toBe(true);
937
+ });
938
+ it("removing a parent in one workspace leaves the notes of a parent with the SAME id in another workspace untouched (where the harness can make one)", async () => {
939
+ const mine = await setup();
940
+ const theirs = await setup();
941
+ const parent = await mine.newParent();
942
+ const twin = await theirs.newParent(parent.kind, parent.id);
943
+ const [m, t] = [await mine.add(parent, "mine"), await theirs.add(twin, "theirs")];
944
+ await kit.harness.removeParent(mine.workspace, parent.kind, parent.id);
945
+ expect(await mine.store.get(m.id)).toBeNull();
946
+ expect(await theirs.store.get(t.id)).toEqual(t);
947
+ expect([...await theirs.store.countByParent(twin.kind, [twin.id], "live")]).toEqual([[twin.id, 1]]);
948
+ expect((await theirs.store.create(twin, "still there", "a")).kind).toBe("created");
949
+ });
950
+ it("a mixed run: notes, edits, deletes and restores in two workspaces leave each workspace listing and counting exactly its own", async () => {
951
+ const a = await setup();
952
+ const b = await setup();
953
+ const [pa, pb] = [await a.newParent(), await b.newParent()];
954
+ const expected = { a: [], b: [] };
955
+ for (let i = 0; i < 12; i++) {
956
+ const [na, nb] = [await a.add(pa, `a${i}`), await b.add(pb, `b${i}`)];
957
+ expected.a.push(na.id);
958
+ expected.b.push(nb.id);
959
+ if (i % 3 === 0) {
960
+ await a.store.update(na.id, `a${i} edited`, 1);
961
+ await b.store.softDelete(nb.id, ACTOR);
962
+ expected.b.pop();
963
+ }
964
+ if (i % 4 === 0) {
965
+ await a.store.softDelete(na.id, ACTOR);
966
+ await a.store.restore(na.id);
967
+ }
968
+ }
969
+ expect(ids((await walk(a.store, pa, "live", 5)).notes).sort()).toEqual([...expected.a].sort());
970
+ expect(ids((await walk(b.store, pb, "live", 5)).notes).sort()).toEqual([...expected.b].sort());
971
+ expect((await walk(a.store, pa, "deleted", 5)).notes).toEqual([]);
972
+ expect((await walk(b.store, pb, "deleted", 5)).notes.length).toBe(4);
973
+ expect([...await a.store.countByParent(pa.kind, [pa.id, pb.id], "live")].sort()).toEqual([[pa.id, 12], [pb.id, 0]].sort());
974
+ expect([...await b.store.countByParent(pb.kind, [pa.id, pb.id], "live")].sort()).toEqual([[pa.id, 0], [pb.id, 8]].sort());
975
+ });
976
+ });
977
+ }
978
+
979
+ // src/entity-notes/server/contract.ts
980
+ function defineNoteStoreContract(api, harness) {
981
+ api.describe("NoteStore contract", () => {
982
+ const kit = makeKit(api, harness);
983
+ defineNoteStoreNotesContract(kit);
984
+ defineNoteStoreListsContract(kit);
985
+ defineNoteStoreTenancyContract(kit);
986
+ defineNoteStoreConcurrencyContract(kit);
987
+ defineNoteStoreHooksContract(kit);
988
+ api.it("cleans up", async () => {
989
+ await harness.cleanup();
990
+ });
991
+ });
992
+ }
993
+ export {
994
+ createMemoryNoteHarness,
995
+ createMemoryNoteWorld,
996
+ createNoteService,
997
+ defineNoteStoreContract
998
+ };