@ordinatio/entities 1.4.0 → 1.6.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.
- package/README.md +20 -0
- package/dist/chunk-3VGJ4NFX.mjs +29 -0
- package/dist/companies/prisma/index.d.mts +19 -1
- package/dist/companies/prisma/index.mjs +123 -25
- package/dist/companies/server/index.d.mts +48 -2
- package/dist/companies/server/index.mjs +234 -22
- package/dist/constants-BwInbMWC.d.mts +11 -0
- package/dist/entity-notes/index.d.mts +19 -0
- package/dist/entity-notes/index.mjs +10 -0
- package/dist/entity-notes/prisma/index.d.mts +57 -0
- package/dist/entity-notes/prisma/index.mjs +284 -0
- package/dist/entity-notes/server/index.d.mts +153 -0
- package/dist/entity-notes/server/index.mjs +998 -0
- package/dist/tags/prisma/index.d.mts +5 -0
- package/dist/tags/prisma/index.mjs +4 -2
- package/dist/types-B4DY5xj3.d.mts +123 -0
- package/dist/{types-CbfseUAS.d.mts → types-BJl_PZDf.d.mts} +42 -1
- package/package.json +17 -2
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// src/entity-notes/prisma/identifiers.ts
|
|
2
|
+
var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
3
|
+
var RESERVED = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype", "toString", "valueOf", "hasOwnProperty"]);
|
|
4
|
+
function assertIdentifier(value, what) {
|
|
5
|
+
if (typeof value !== "string" || !IDENTIFIER.test(value) || RESERVED.has(value)) {
|
|
6
|
+
throw new Error(`createPrismaNoteStore: ${what} must be a plain identifier (letters, digits and underscores, not starting with a digit), got ${JSON.stringify(value)}`);
|
|
7
|
+
}
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
function quote(identifier) {
|
|
11
|
+
return `"${identifier}"`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/entity-notes/prisma/context.ts
|
|
15
|
+
var FIXED_COLUMNS = /* @__PURE__ */ new Set(["id", "body", "revision", "createdAt", "updatedAt", "deletedAt", "deletedBy"]);
|
|
16
|
+
function createContext(config) {
|
|
17
|
+
if (typeof config.client !== "function") throw new Error("createPrismaNoteStore: client must be a function that returns the Prisma client");
|
|
18
|
+
if (typeof config.workspaceId !== "string" || config.workspaceId === "") throw new Error("createPrismaNoteStore: workspaceId must be a non-empty string");
|
|
19
|
+
const workspaceColumn = assertIdentifier(config.workspaceColumn, "workspaceColumn");
|
|
20
|
+
const noteModel = assertIdentifier(config.noteModel, "noteModel");
|
|
21
|
+
const noteTable = assertIdentifier(config.noteTable, "noteTable");
|
|
22
|
+
const authorColumn = assertIdentifier(config.authorColumn ?? "authorId", "authorColumn");
|
|
23
|
+
if (FIXED_COLUMNS.has(workspaceColumn) || FIXED_COLUMNS.has(authorColumn) || workspaceColumn === authorColumn) {
|
|
24
|
+
throw new Error("createPrismaNoteStore: workspaceColumn and authorColumn must be different columns and must not be one of the fixed ones (id, body, revision, createdAt, updatedAt, deletedAt, deletedBy)");
|
|
25
|
+
}
|
|
26
|
+
const lockWaitMs = config.lockWaitMs ?? 5e3;
|
|
27
|
+
if (!Number.isInteger(lockWaitMs) || lockWaitMs <= 0) throw new Error("createPrismaNoteStore: lockWaitMs must be a positive integer");
|
|
28
|
+
const txOptions = { maxWait: config.transaction?.maxWait ?? 1e4, timeout: config.transaction?.timeout ?? 15e3 };
|
|
29
|
+
if (typeof config.parents !== "object" || config.parents === null) throw new Error("createPrismaNoteStore: parents must be an object with one entry per kind of parent");
|
|
30
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
31
|
+
const taken = /* @__PURE__ */ new Set([workspaceColumn, authorColumn]);
|
|
32
|
+
for (const [kind, parent] of Object.entries(config.parents)) {
|
|
33
|
+
if (kind === "") throw new Error("createPrismaNoteStore: a parent kind must not be empty");
|
|
34
|
+
const noteColumn = assertIdentifier(parent?.noteColumn, `parents.${kind}.noteColumn`);
|
|
35
|
+
if (FIXED_COLUMNS.has(noteColumn) || taken.has(noteColumn)) throw new Error(`createPrismaNoteStore: parents.${kind}.noteColumn "${noteColumn}" is already used by another column (each kind needs its own column)`);
|
|
36
|
+
taken.add(noteColumn);
|
|
37
|
+
const model2 = assertIdentifier(parent.model, `parents.${kind}.model`);
|
|
38
|
+
const table = assertIdentifier(parent.table, `parents.${kind}.table`);
|
|
39
|
+
const parentWorkspace = assertIdentifier(parent.workspaceColumn ?? workspaceColumn, `parents.${kind}.workspaceColumn`);
|
|
40
|
+
const resolved = { kind, noteColumn, model: model2, workspaceColumn: parentWorkspace, sqlTable: quote(table), sqlWorkspaceColumn: quote(parentWorkspace) };
|
|
41
|
+
if (parent.softDeleteColumn !== void 0) {
|
|
42
|
+
resolved.softDeleteColumn = assertIdentifier(parent.softDeleteColumn, `parents.${kind}.softDeleteColumn`);
|
|
43
|
+
resolved.sqlSoftDeleteColumn = quote(resolved.softDeleteColumn);
|
|
44
|
+
}
|
|
45
|
+
kinds.set(kind, resolved);
|
|
46
|
+
}
|
|
47
|
+
if (kinds.size === 0) throw new Error("createPrismaNoteStore: parents must name at least one kind of parent");
|
|
48
|
+
const model = (client, name) => {
|
|
49
|
+
const found = client[name];
|
|
50
|
+
if (typeof found !== "object" || found === null) throw new Error(`createPrismaNoteStore: the Prisma client has no model "${name}" (check the configuration)`);
|
|
51
|
+
return found;
|
|
52
|
+
};
|
|
53
|
+
return {
|
|
54
|
+
workspaceId: config.workspaceId,
|
|
55
|
+
workspaceColumn,
|
|
56
|
+
authorColumn,
|
|
57
|
+
sql: { noteTable: quote(noteTable), workspaceColumn: quote(workspaceColumn) },
|
|
58
|
+
txOptions,
|
|
59
|
+
beforeNoteWrite: config.onBeforeNoteWrite,
|
|
60
|
+
client: config.client,
|
|
61
|
+
parent: (kind) => kinds.get(kind),
|
|
62
|
+
model,
|
|
63
|
+
notes: (client) => model(client, noteModel),
|
|
64
|
+
noteWhere: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId }),
|
|
65
|
+
toRecord(row) {
|
|
66
|
+
const fields = row;
|
|
67
|
+
for (const parent of kinds.values()) {
|
|
68
|
+
const parentId = fields[parent.noteColumn];
|
|
69
|
+
if (typeof parentId === "string" && parentId !== "") {
|
|
70
|
+
return {
|
|
71
|
+
id: fields.id,
|
|
72
|
+
parentKind: parent.kind,
|
|
73
|
+
parentId,
|
|
74
|
+
body: fields.body,
|
|
75
|
+
revision: fields.revision,
|
|
76
|
+
authorId: fields[authorColumn],
|
|
77
|
+
createdAt: fields.createdAt,
|
|
78
|
+
updatedAt: fields.updatedAt,
|
|
79
|
+
deletedAt: fields.deletedAt ?? null,
|
|
80
|
+
deletedBy: fields.deletedBy ?? null
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
throw new Error(`createPrismaNoteStore: note ${String(fields.id)} has none of the configured parent columns set`);
|
|
85
|
+
},
|
|
86
|
+
async limitLockWait(tx) {
|
|
87
|
+
await tx.$executeRawUnsafe(`SELECT set_config('lock_timeout', $1, true)`, `${lockWaitMs}ms`);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// src/entity-notes/prisma/cursor.ts
|
|
93
|
+
var SHAPE = /^v1\.([A-Za-z0-9_-]+)$/;
|
|
94
|
+
var MIN_TIME = -621355968e5;
|
|
95
|
+
var MAX_TIME = 253402300799999;
|
|
96
|
+
function toBase64Url(text) {
|
|
97
|
+
const bytes = new TextEncoder().encode(text);
|
|
98
|
+
let binary = "";
|
|
99
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
100
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
101
|
+
}
|
|
102
|
+
function fromBase64Url(encoded) {
|
|
103
|
+
try {
|
|
104
|
+
const padded = encoded.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - encoded.length % 4) % 4);
|
|
105
|
+
const binary = atob(padded);
|
|
106
|
+
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
107
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
108
|
+
} catch {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function encodeCursor(time, id) {
|
|
113
|
+
return `v1.${toBase64Url(JSON.stringify([time, id]))}`;
|
|
114
|
+
}
|
|
115
|
+
function decodeCursor(cursor) {
|
|
116
|
+
const match = SHAPE.exec(cursor);
|
|
117
|
+
if (!match) return null;
|
|
118
|
+
const json = fromBase64Url(match[1]);
|
|
119
|
+
if (json === null) return null;
|
|
120
|
+
let parsed;
|
|
121
|
+
try {
|
|
122
|
+
parsed = JSON.parse(json);
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
if (!Array.isArray(parsed) || parsed.length !== 2) return null;
|
|
127
|
+
const [time, id] = parsed;
|
|
128
|
+
if (typeof time !== "number" || !Number.isInteger(time) || time < MIN_TIME || time > MAX_TIME) return null;
|
|
129
|
+
if (typeof id !== "string" || id.length === 0 || id.length > 255 || id.includes("\0")) return null;
|
|
130
|
+
return encodeCursor(time, id) === cursor ? { time, id } : null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// src/entity-notes/prisma/reads.ts
|
|
134
|
+
var IDS_PER_QUERY = 1e4;
|
|
135
|
+
function chunksOf(items) {
|
|
136
|
+
const pieces = [];
|
|
137
|
+
for (let start = 0; start < items.length; start += IDS_PER_QUERY) pieces.push(items.slice(start, start + IDS_PER_QUERY));
|
|
138
|
+
return pieces;
|
|
139
|
+
}
|
|
140
|
+
function createNoteReads(context) {
|
|
141
|
+
const { noteWhere } = context;
|
|
142
|
+
const db = () => context.client();
|
|
143
|
+
const statusFilter = (status) => status === "live" ? null : { not: null };
|
|
144
|
+
return {
|
|
145
|
+
async get(id) {
|
|
146
|
+
const row = await context.notes(db()).findFirst({ where: noteWhere({ id }) });
|
|
147
|
+
return row ? context.toRecord(row) : null;
|
|
148
|
+
},
|
|
149
|
+
async list(query) {
|
|
150
|
+
let after = null;
|
|
151
|
+
if (query.cursor !== null) {
|
|
152
|
+
after = decodeCursor(query.cursor);
|
|
153
|
+
if (after === null) return { kind: "badCursor" };
|
|
154
|
+
}
|
|
155
|
+
const parent = context.parent(query.parent.kind);
|
|
156
|
+
if (!parent) return { kind: "page", notes: [], nextCursor: null };
|
|
157
|
+
const where = noteWhere({
|
|
158
|
+
[parent.noteColumn]: query.parent.id,
|
|
159
|
+
deletedAt: statusFilter(query.status),
|
|
160
|
+
...after ? { OR: [{ createdAt: { lt: new Date(after.time) } }, { createdAt: new Date(after.time), id: { lt: after.id } }] } : {}
|
|
161
|
+
});
|
|
162
|
+
const rows = await context.notes(db()).findMany({ where, orderBy: [{ createdAt: "desc" }, { id: "desc" }], take: query.limit + 1 });
|
|
163
|
+
const notes = rows.slice(0, query.limit).map((row) => context.toRecord(row));
|
|
164
|
+
const last = notes[notes.length - 1];
|
|
165
|
+
return { kind: "page", notes, nextCursor: rows.length > query.limit && last ? encodeCursor(last.createdAt.getTime(), last.id) : null };
|
|
166
|
+
},
|
|
167
|
+
async countByParent(kind, parentIds, status) {
|
|
168
|
+
const counts = new Map(parentIds.map((id) => [id, 0]));
|
|
169
|
+
const parent = context.parent(kind);
|
|
170
|
+
if (!parent) return counts;
|
|
171
|
+
for (const piece of chunksOf([...counts.keys()])) {
|
|
172
|
+
const grouped = await context.notes(db()).groupBy({
|
|
173
|
+
by: [parent.noteColumn],
|
|
174
|
+
where: noteWhere({ [parent.noteColumn]: { in: piece }, deletedAt: statusFilter(status) }),
|
|
175
|
+
_count: { _all: true }
|
|
176
|
+
});
|
|
177
|
+
for (const row of grouped) counts.set(row[parent.noteColumn], row._count._all);
|
|
178
|
+
}
|
|
179
|
+
return counts;
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/entity-notes/prisma/errors.ts
|
|
185
|
+
function hasCode(error, code, depth) {
|
|
186
|
+
if (typeof error !== "object" || error === null || depth > 4) return false;
|
|
187
|
+
const fields = error;
|
|
188
|
+
if (fields.code === code) return true;
|
|
189
|
+
return ["cause", "meta", "originalError", "driverAdapterError"].some((key) => hasCode(fields[key], code, depth + 1));
|
|
190
|
+
}
|
|
191
|
+
var isForeignKeyViolation = (error) => hasCode(error, "P2003", 0);
|
|
192
|
+
|
|
193
|
+
// src/entity-notes/prisma/writes.ts
|
|
194
|
+
function createNoteWrites(context) {
|
|
195
|
+
const { noteWhere, sql } = context;
|
|
196
|
+
const db = () => context.client();
|
|
197
|
+
const lockNote = async (tx, id) => (await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.noteTable} WHERE "id" = $1 AND ${sql.workspaceColumn} = $2 FOR UPDATE`, id, context.workspaceId)).length > 0;
|
|
198
|
+
const read = async (tx, id) => {
|
|
199
|
+
const row = await context.notes(tx).findFirst({ where: noteWhere({ id }) });
|
|
200
|
+
return row ? context.toRecord(row) : null;
|
|
201
|
+
};
|
|
202
|
+
return {
|
|
203
|
+
async create(parent, body, authorId) {
|
|
204
|
+
const kind = context.parent(parent.kind);
|
|
205
|
+
if (!kind) return { kind: "parentGone" };
|
|
206
|
+
const parentExists = async () => await context.model(db(), kind.model).findFirst({ where: { id: parent.id, [kind.workspaceColumn]: context.workspaceId, ...kind.softDeleteColumn ? { [kind.softDeleteColumn]: null } : {} }, select: { id: true } }) != null;
|
|
207
|
+
if (!await parentExists()) return { kind: "parentGone" };
|
|
208
|
+
if (context.beforeNoteWrite) await context.beforeNoteWrite();
|
|
209
|
+
try {
|
|
210
|
+
return await db().$transaction(async (tx) => {
|
|
211
|
+
await context.limitLockWait(tx);
|
|
212
|
+
const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${kind.sqlTable} WHERE "id" = $1 AND ${kind.sqlWorkspaceColumn} = $2${kind.sqlSoftDeleteColumn ? ` AND ${kind.sqlSoftDeleteColumn} IS NULL` : ""} FOR KEY SHARE`, parent.id, context.workspaceId);
|
|
213
|
+
if (locked.length === 0) return { kind: "parentGone" };
|
|
214
|
+
const stamp = /* @__PURE__ */ new Date();
|
|
215
|
+
const row = await context.notes(tx).create({
|
|
216
|
+
data: { ...noteWhere(), [kind.noteColumn]: parent.id, body, revision: 1, [context.authorColumn]: authorId, createdAt: stamp, updatedAt: stamp, deletedAt: null, deletedBy: null }
|
|
217
|
+
});
|
|
218
|
+
return { kind: "created", note: context.toRecord(row) };
|
|
219
|
+
}, context.txOptions);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
if (isForeignKeyViolation(error)) return { kind: "parentGone" };
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
async update(id, body, expectedRevision) {
|
|
226
|
+
return db().$transaction(async (tx) => {
|
|
227
|
+
await context.limitLockWait(tx);
|
|
228
|
+
if (!await lockNote(tx, id)) return { kind: "notFound" };
|
|
229
|
+
const before = await read(tx, id);
|
|
230
|
+
if (!before) return { kind: "notFound" };
|
|
231
|
+
if (before.deletedAt !== null) return { kind: "deleted" };
|
|
232
|
+
if (before.revision !== expectedRevision) return { kind: "conflict", current: before };
|
|
233
|
+
const { count } = await context.notes(tx).updateMany({
|
|
234
|
+
where: noteWhere({ id, revision: expectedRevision, deletedAt: null }),
|
|
235
|
+
data: { body, revision: expectedRevision + 1, updatedAt: /* @__PURE__ */ new Date() }
|
|
236
|
+
});
|
|
237
|
+
const after = await read(tx, id);
|
|
238
|
+
if (count === 0 || !after) return after ? after.deletedAt !== null ? { kind: "deleted" } : { kind: "conflict", current: after } : { kind: "notFound" };
|
|
239
|
+
return { kind: "updated", before, after };
|
|
240
|
+
}, context.txOptions);
|
|
241
|
+
},
|
|
242
|
+
async softDelete(id, actorId) {
|
|
243
|
+
return db().$transaction(async (tx) => {
|
|
244
|
+
await context.limitLockWait(tx);
|
|
245
|
+
if (!await lockNote(tx, id)) return { kind: "notFound" };
|
|
246
|
+
const before = await read(tx, id);
|
|
247
|
+
if (!before) return { kind: "notFound" };
|
|
248
|
+
if (before.deletedAt !== null) return { kind: "alreadyDeleted" };
|
|
249
|
+
const { count } = await context.notes(tx).updateMany({
|
|
250
|
+
where: noteWhere({ id, deletedAt: null }),
|
|
251
|
+
data: { deletedAt: /* @__PURE__ */ new Date(), deletedBy: actorId, updatedAt: before.updatedAt }
|
|
252
|
+
});
|
|
253
|
+
const after = await read(tx, id);
|
|
254
|
+
if (count === 0 || !after) return after ? { kind: "alreadyDeleted" } : { kind: "notFound" };
|
|
255
|
+
return { kind: "deleted", before, after };
|
|
256
|
+
}, context.txOptions);
|
|
257
|
+
},
|
|
258
|
+
async restore(id) {
|
|
259
|
+
return db().$transaction(async (tx) => {
|
|
260
|
+
await context.limitLockWait(tx);
|
|
261
|
+
if (!await lockNote(tx, id)) return { kind: "notFound" };
|
|
262
|
+
const before = await read(tx, id);
|
|
263
|
+
if (!before) return { kind: "notFound" };
|
|
264
|
+
if (before.deletedAt === null) return { kind: "notDeleted" };
|
|
265
|
+
const { count } = await context.notes(tx).updateMany({
|
|
266
|
+
where: { ...noteWhere({ id }), NOT: { deletedAt: null } },
|
|
267
|
+
data: { deletedAt: null, deletedBy: null, updatedAt: before.updatedAt }
|
|
268
|
+
});
|
|
269
|
+
const after = await read(tx, id);
|
|
270
|
+
if (count === 0 || !after) return after ? { kind: "notDeleted" } : { kind: "notFound" };
|
|
271
|
+
return { kind: "restored", before, after };
|
|
272
|
+
}, context.txOptions);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// src/entity-notes/prisma/index.ts
|
|
278
|
+
function createPrismaNoteStore(config) {
|
|
279
|
+
const context = createContext(config);
|
|
280
|
+
return { ...createNoteReads(context), ...createNoteWrites(context) };
|
|
281
|
+
}
|
|
282
|
+
export {
|
|
283
|
+
createPrismaNoteStore
|
|
284
|
+
};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { a as NoteRecord, b as NoteStatus, c as NoteParent, N as NoteStore } from '../../types-B4DY5xj3.mjs';
|
|
2
|
+
export { d as NoteCreateResult, e as NoteDeleteResult, f as NoteListQuery, g as NoteListResult, h as NoteRestoreResult, i as NoteUpdateResult } from '../../types-B4DY5xj3.mjs';
|
|
3
|
+
import { N as NoteLimits } from '../../constants-BwInbMWC.mjs';
|
|
4
|
+
|
|
5
|
+
/** Why a call did not do what was asked, with the context an app needs for its message. */
|
|
6
|
+
type NoteFailure<T extends NoteRecord> = {
|
|
7
|
+
reason: 'invalid-body';
|
|
8
|
+
problem: 'empty' | 'too-long';
|
|
9
|
+
length: number;
|
|
10
|
+
} | {
|
|
11
|
+
reason: 'invalid-parent';
|
|
12
|
+
}
|
|
13
|
+
/** The author or the actor is not a non-empty text id. */
|
|
14
|
+
| {
|
|
15
|
+
reason: 'invalid-actor';
|
|
16
|
+
}
|
|
17
|
+
/** `status` is neither `live` nor `deleted`. */
|
|
18
|
+
| {
|
|
19
|
+
reason: 'invalid-status';
|
|
20
|
+
} | {
|
|
21
|
+
reason: 'invalid-revision';
|
|
22
|
+
} | {
|
|
23
|
+
reason: 'invalid-cursor';
|
|
24
|
+
} | {
|
|
25
|
+
reason: 'parent-gone';
|
|
26
|
+
} | {
|
|
27
|
+
reason: 'not-found';
|
|
28
|
+
}
|
|
29
|
+
/** A deleted note cannot be edited: restore it first. */
|
|
30
|
+
| {
|
|
31
|
+
reason: 'deleted';
|
|
32
|
+
} | {
|
|
33
|
+
reason: 'already-deleted';
|
|
34
|
+
} | {
|
|
35
|
+
reason: 'not-deleted';
|
|
36
|
+
}
|
|
37
|
+
/** Someone saved this note since the editor loaded it: `current` is what is stored now. */
|
|
38
|
+
| {
|
|
39
|
+
reason: 'conflict';
|
|
40
|
+
current: T;
|
|
41
|
+
};
|
|
42
|
+
type NoteResult<T extends NoteRecord, V> = ({
|
|
43
|
+
ok: true;
|
|
44
|
+
} & V) | ({
|
|
45
|
+
ok: false;
|
|
46
|
+
} & NoteFailure<T>);
|
|
47
|
+
interface NoteListOptions {
|
|
48
|
+
/** Default `live`. */
|
|
49
|
+
status?: NoteStatus;
|
|
50
|
+
/** Default 50, at most 200 (the limits' page sizes); anything that is not a whole number of at least 1 gets the default. */
|
|
51
|
+
limit?: number;
|
|
52
|
+
/** An opaque cursor from `nextCursor` of an earlier page of the same listing. */
|
|
53
|
+
cursor?: string | null;
|
|
54
|
+
}
|
|
55
|
+
interface NoteService<T extends NoteRecord> {
|
|
56
|
+
/** Adds a note to a parent. `body` is cleaned; the stored text is the cleaned one. `authorId` must be a non-empty text (`invalid-actor` otherwise). */
|
|
57
|
+
add(parent: NoteParent, body: string, authorId: string): Promise<NoteResult<T, {
|
|
58
|
+
note: T;
|
|
59
|
+
}>>;
|
|
60
|
+
/** Edits a note that the editor loaded at `expectedRevision`: a stale revision is a `conflict` carrying the current note, and nothing changes. */
|
|
61
|
+
edit(id: string, body: string, expectedRevision: number): Promise<NoteResult<T, {
|
|
62
|
+
before: T;
|
|
63
|
+
after: T;
|
|
64
|
+
}>>;
|
|
65
|
+
/** Soft delete: the note is hidden from the live list and kept. `actorId` must be a non-empty text (`invalid-actor` otherwise). */
|
|
66
|
+
remove(id: string, actorId: string): Promise<NoteResult<T, {
|
|
67
|
+
before: T;
|
|
68
|
+
after: T;
|
|
69
|
+
}>>;
|
|
70
|
+
restore(id: string): Promise<NoteResult<T, {
|
|
71
|
+
before: T;
|
|
72
|
+
after: T;
|
|
73
|
+
}>>;
|
|
74
|
+
/** One note, a deleted one included (check `deletedAt`). */
|
|
75
|
+
get(id: string): Promise<NoteResult<T, {
|
|
76
|
+
note: T;
|
|
77
|
+
}>>;
|
|
78
|
+
/** One page of a parent's notes, newest first. An unknown `status` is `invalid-status`. */
|
|
79
|
+
list(parent: NoteParent, options?: NoteListOptions): Promise<NoteResult<T, {
|
|
80
|
+
notes: T[];
|
|
81
|
+
nextCursor: string | null;
|
|
82
|
+
}>>;
|
|
83
|
+
/** How many notes (live by default) each of these parents of one kind has: EXACTLY the asked ids appear (the service guarantees it, zero where the store says nothing); an id that is not a non-empty text is ignored; an empty list is an empty map. */
|
|
84
|
+
counts(kind: string, parentIds: string[], status?: NoteStatus): Promise<Map<string, number>>;
|
|
85
|
+
}
|
|
86
|
+
declare function createNoteService<T extends NoteRecord>(store: NoteStore<T>, suppliedLimits?: NoteLimits): NoteService<T>;
|
|
87
|
+
|
|
88
|
+
interface NoteContractRunner {
|
|
89
|
+
describe: (name: string, body: () => void) => void;
|
|
90
|
+
it: ((name: string, body: () => Promise<void>) => void) & {
|
|
91
|
+
skip?: (name: string, body: () => Promise<void>) => void;
|
|
92
|
+
};
|
|
93
|
+
expect: (value: unknown) => {
|
|
94
|
+
toBe(expected: unknown): void;
|
|
95
|
+
toEqual(expected: unknown): void;
|
|
96
|
+
toBeNull(): void;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
interface NoteStoreHarness {
|
|
100
|
+
/** A fresh, empty workspace id. Every test uses its own, so tests never see each other's rows. */
|
|
101
|
+
newWorkspace(): Promise<string>;
|
|
102
|
+
/** The store for one workspace. Called repeatedly for the same id: it must give the same data. */
|
|
103
|
+
storeFor(workspace: string): NoteStore<NoteRecord>;
|
|
104
|
+
/**
|
|
105
|
+
* Creates a real parent of the given kind (a contact, a company ...) in the workspace and returns its id. `wantedId` is OPTIONAL: when given, a harness that can use that id for the
|
|
106
|
+
* parent returns it (so the contract can make a parent of another kind with the SAME id); a harness whose ids cannot be chosen ignores it and returns an id of its own, and the one
|
|
107
|
+
* check that needs the shared id then skips that part.
|
|
108
|
+
*/
|
|
109
|
+
addParent(workspace: string, kind: string, wantedId?: string): Promise<string>;
|
|
110
|
+
/**
|
|
111
|
+
* Deletes a parent with everything that points at it (its notes): what a database's cascading delete does. NOTE: the contract also passes ids that do not exist, such as 'missing',
|
|
112
|
+
* 'ghost-1' or 'nothing', for notes and for parents (a prefix of a real id, quotes too; never an empty text, a NUL or a lone surrogate, which the service refuses first): an adapter with
|
|
113
|
+
* uuid or integer id columns must answer them as "not found" instead of failing the cast.
|
|
114
|
+
*/
|
|
115
|
+
removeParent(workspace: string, kind: string, id: string): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* OPTIONAL test seam, for the parent-deleted-while-creating check (./contract-hooks; no other check uses it). Arms a ONE-SHOT hook that the next `create` runs AFTER it has checked that
|
|
118
|
+
* the parent exists and BEFORE the write (the write re-checks the parent, atomically, and inserts), so a test can delete the parent at exactly the dangerous moment. The hook is taken
|
|
119
|
+
* (cleared) BEFORE it is called and runs with no lock held and no transaction open: it may itself call any store method. A create stopped earlier by `parentGone` does not run the hook
|
|
120
|
+
* and leaves it armed (an adapter built as ONE `INSERT ... SELECT ... WHERE EXISTS` statement has no separate first check: its harness wrapper looks the parent up first, before arming, and
|
|
121
|
+
* returns `parentGone` itself without running the hook). Without it that check is shown as skipped when your runner has `it.skip`; if not, it will run and fail, so supply the hook.
|
|
122
|
+
*/
|
|
123
|
+
armBeforeNoteWrite?(hook: () => Promise<void>): void;
|
|
124
|
+
/** Removes everything the tests created. */
|
|
125
|
+
cleanup(): Promise<void>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
interface MemoryNoteWorldOptions {
|
|
129
|
+
/** Default true. False removes the one-at-a-time chain so races become visible (for proving that concurrency checks can fail). */
|
|
130
|
+
serialise?: boolean;
|
|
131
|
+
/** Default true. False drops the parent re-check at write time (for proving that the deleted-parent check can fail). */
|
|
132
|
+
checkParentAtWrite?: boolean;
|
|
133
|
+
/** The clock; default `() => new Date()`. */
|
|
134
|
+
now?: () => Date;
|
|
135
|
+
/** Makes the id of each new note; default `note-000000001`, `note-000000002` ... (they sort in creation order). Pass random ids to prove that nothing depends on ids sorting in creation order. */
|
|
136
|
+
newId?: () => string;
|
|
137
|
+
}
|
|
138
|
+
interface MemoryNoteWorld {
|
|
139
|
+
store(workspace: string): NoteStore<NoteRecord>;
|
|
140
|
+
/** Registers a parent (a contact, a company ...) of a workspace and returns its id. */
|
|
141
|
+
addParent(workspace: string, kind: string, id?: string): string;
|
|
142
|
+
/** Removes a parent and every note of it, deleted ones included (what a database's cascading delete does). */
|
|
143
|
+
removeParent(workspace: string, kind: string, id: string): Promise<void>;
|
|
144
|
+
/** Arms a ONE-SHOT hook run by the next `create` IN THIS WORLD that gets past its first check, between that check and its write. */
|
|
145
|
+
armBeforeNoteWrite(hook: () => Promise<void>): void;
|
|
146
|
+
}
|
|
147
|
+
declare function createMemoryNoteWorld(options?: MemoryNoteWorldOptions): MemoryNoteWorld;
|
|
148
|
+
/** A harness over a fresh in-memory world, for running the contract suite against this store (a product's own tests can use it as a template for theirs). */
|
|
149
|
+
declare function createMemoryNoteHarness(options?: MemoryNoteWorldOptions): NoteStoreHarness;
|
|
150
|
+
|
|
151
|
+
declare function defineNoteStoreContract(api: NoteContractRunner, harness: NoteStoreHarness): void;
|
|
152
|
+
|
|
153
|
+
export { type MemoryNoteWorld, type MemoryNoteWorldOptions, type NoteContractRunner, type NoteFailure, type NoteListOptions, NoteParent, NoteRecord, type NoteResult, type NoteService, NoteStatus, NoteStore, type NoteStoreHarness, createMemoryNoteHarness, createMemoryNoteWorld, createNoteService, defineNoteStoreContract };
|