@ordinatio/entities 1.3.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.
- package/README.md +8 -0
- package/dist/chunk-3VGJ4NFX.mjs +29 -0
- package/dist/chunk-ZWID3JLL.mjs +123 -0
- package/dist/companies/index.d.mts +60 -0
- package/dist/companies/index.mjs +24 -0
- package/dist/companies/prisma/index.d.mts +58 -0
- package/dist/companies/prisma/index.mjs +276 -0
- package/dist/companies/server/index.d.mts +167 -0
- package/dist/companies/server/index.mjs +1826 -0
- package/dist/constants-BwInbMWC.d.mts +11 -0
- package/dist/constants-DV-gn6u8.d.mts +22 -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 +52 -0
- package/dist/entity-notes/prisma/index.mjs +279 -0
- package/dist/entity-notes/server/index.d.mts +153 -0
- package/dist/entity-notes/server/index.mjs +998 -0
- package/dist/types-B4DY5xj3.d.mts +123 -0
- package/dist/types-CbfseUAS.d.mts +169 -0
- package/package.json +32 -2
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
interface NoteLimits {
|
|
2
|
+
/** Longest note body after cleaning, in UTF-16 code units (the unit `String.length` and a text column's JavaScript value use; an emoji outside the basic plane counts as 2). */
|
|
3
|
+
maxBodyLength: number;
|
|
4
|
+
/** How many notes a list returns when the caller does not say. */
|
|
5
|
+
defaultPageSize: number;
|
|
6
|
+
/** The most notes one list call may return, whatever the caller asks for: a parent page lists them, so an unbounded page would slow it. */
|
|
7
|
+
maxPageSize: number;
|
|
8
|
+
}
|
|
9
|
+
declare const DEFAULT_NOTE_LIMITS: Readonly<NoteLimits>;
|
|
10
|
+
|
|
11
|
+
export { DEFAULT_NOTE_LIMITS as D, type NoteLimits as N };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
interface CompanyLimits {
|
|
2
|
+
/** Longest company name, in characters, after cleaning. */
|
|
3
|
+
maxNameLength: number;
|
|
4
|
+
/** Longest role text on a membership ("Partner", "Office manager"), after cleaning. */
|
|
5
|
+
maxRoleLength: number;
|
|
6
|
+
/** Longest stored website (after it is normalised: scheme, host, a non-default port and the path; no query, fragment or credentials). */
|
|
7
|
+
maxWebsiteLength: number;
|
|
8
|
+
/** Per-workspace ceiling: pickers load every company, so an unbounded list would slow every form. */
|
|
9
|
+
maxPerWorkspace: number;
|
|
10
|
+
/** How many people one company may hold: a company page lists them. */
|
|
11
|
+
maxMembersPerCompany: number;
|
|
12
|
+
}
|
|
13
|
+
declare const DEFAULT_COMPANY_LIMITS: Readonly<CompanyLimits>;
|
|
14
|
+
/**
|
|
15
|
+
* Domains where the mailbox belongs to a person, not to an organisation: an email from `ann@gmail.com` says nothing about her employer, so such
|
|
16
|
+
* a domain is NEVER suggested as a company. Exact matches only, lower case, sorted. NOT exhaustive (there are regional variants and new
|
|
17
|
+
* providers every year): a missing entry means a wrong suggestion that a person has to decline, never a wrong automatic link, because a
|
|
18
|
+
* suggestion is only ever offered.
|
|
19
|
+
*/
|
|
20
|
+
declare const FREE_MAIL_DOMAINS: readonly string[];
|
|
21
|
+
|
|
22
|
+
export { type CompanyLimits as C, DEFAULT_COMPANY_LIMITS as D, FREE_MAIL_DOMAINS as F };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export { D as DEFAULT_NOTE_LIMITS, N as NoteLimits } from '../constants-BwInbMWC.mjs';
|
|
2
|
+
|
|
3
|
+
/** Cleans a note body (see the file header). Not a string gives an empty string. */
|
|
4
|
+
declare function cleanNoteBody(body: unknown): string;
|
|
5
|
+
type NoteBodyCheck = {
|
|
6
|
+
ok: true;
|
|
7
|
+
body: string;
|
|
8
|
+
} | {
|
|
9
|
+
ok: false;
|
|
10
|
+
reason: 'empty' | 'too-long';
|
|
11
|
+
length: number;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Cleans the body and checks its length (1 to `maxLength`, default 10,000, in UTF-16 code units like the stored value). `maxLength` must be a positive whole number: anything
|
|
15
|
+
* else (NaN, 0, a negative, a fraction, Infinity) is a caller's mistake and the default applies, so a bad limit can never switch the cap off.
|
|
16
|
+
*/
|
|
17
|
+
declare function checkNoteBody(body: unknown, maxLength?: number): NoteBodyCheck;
|
|
18
|
+
|
|
19
|
+
export { type NoteBodyCheck, checkNoteBody, cleanNoteBody };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { N as NoteStore, a as NoteRecord } from '../../types-B4DY5xj3.mjs';
|
|
2
|
+
|
|
3
|
+
interface PrismaNoteParentConfig {
|
|
4
|
+
/** The note model's NULLABLE column AND Prisma field that holds the id of this kind of parent, e.g. `contactId`. */
|
|
5
|
+
noteColumn: string;
|
|
6
|
+
/** Prisma delegate of the parent's model, e.g. `contact`. */
|
|
7
|
+
model: string;
|
|
8
|
+
/** SQL table of the parent, e.g. `Contact` (used in the share lock on the parent row). */
|
|
9
|
+
table: string;
|
|
10
|
+
/** The parent model's workspace column. Defaults to the note's. */
|
|
11
|
+
workspaceColumn?: string;
|
|
12
|
+
}
|
|
13
|
+
interface PrismaNoteStoreConfig {
|
|
14
|
+
/** Called each time the store needs the client (never at import), so a test can swap in a client with a bigger pool. */
|
|
15
|
+
client: () => PrismaLikeClient;
|
|
16
|
+
/** The workspace (organization, account, tenant) this store is built for. Every query is scoped by it. */
|
|
17
|
+
workspaceId: string;
|
|
18
|
+
/** Prisma delegate of the note model, e.g. `note`. */
|
|
19
|
+
noteModel: string;
|
|
20
|
+
/** SQL table of the note model, e.g. `Note` (used in the row locks). */
|
|
21
|
+
noteTable: string;
|
|
22
|
+
/** Workspace column on the note model, e.g. `organizationId`. */
|
|
23
|
+
workspaceColumn: string;
|
|
24
|
+
/** The kinds of parent a note can belong to, by kind name, e.g. `{ contact: { noteColumn: 'contactId', model: 'contact', table: 'Contact' } }`. At least one. */
|
|
25
|
+
parents: Record<string, PrismaNoteParentConfig>;
|
|
26
|
+
/** Column AND Prisma field of the note model for who wrote it (plain text). Default `authorId`. */
|
|
27
|
+
authorColumn?: string;
|
|
28
|
+
/** How long a transaction waits for any one lock before it throws (Postgres lock_timeout). Default 5000. */
|
|
29
|
+
lockWaitMs?: number;
|
|
30
|
+
/** Interactive transaction limits. Defaults: maxWait 10000, timeout 15000. */
|
|
31
|
+
transaction?: {
|
|
32
|
+
maxWait?: number;
|
|
33
|
+
timeout?: number;
|
|
34
|
+
};
|
|
35
|
+
/** TEST ONLY: runs inside `create` after the parent check and before the write, holding NO lock and no open transaction, so a test can delete the parent there. */
|
|
36
|
+
onBeforeNoteWrite?: () => Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/** The part of a transaction client the store uses. A real Prisma transaction client satisfies it; model delegates are looked up by name. */
|
|
39
|
+
interface PrismaLikeTx {
|
|
40
|
+
$executeRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;
|
|
41
|
+
$queryRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;
|
|
42
|
+
}
|
|
43
|
+
interface PrismaLikeClient extends PrismaLikeTx {
|
|
44
|
+
$transaction<R>(fn: (tx: PrismaLikeTx) => Promise<R>, options?: {
|
|
45
|
+
maxWait?: number;
|
|
46
|
+
timeout?: number;
|
|
47
|
+
}): Promise<R>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
declare function createPrismaNoteStore(config: PrismaNoteStoreConfig): NoteStore<NoteRecord>;
|
|
51
|
+
|
|
52
|
+
export { type PrismaLikeClient, type PrismaLikeTx, type PrismaNoteParentConfig, type PrismaNoteStoreConfig, createPrismaNoteStore };
|
|
@@ -0,0 +1,279 @@
|
|
|
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
|
+
kinds.set(kind, { kind, noteColumn, model: model2, workspaceColumn: parentWorkspace, sqlTable: quote(table), sqlWorkspaceColumn: quote(parentWorkspace) });
|
|
41
|
+
}
|
|
42
|
+
if (kinds.size === 0) throw new Error("createPrismaNoteStore: parents must name at least one kind of parent");
|
|
43
|
+
const model = (client, name) => {
|
|
44
|
+
const found = client[name];
|
|
45
|
+
if (typeof found !== "object" || found === null) throw new Error(`createPrismaNoteStore: the Prisma client has no model "${name}" (check the configuration)`);
|
|
46
|
+
return found;
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
workspaceId: config.workspaceId,
|
|
50
|
+
workspaceColumn,
|
|
51
|
+
authorColumn,
|
|
52
|
+
sql: { noteTable: quote(noteTable), workspaceColumn: quote(workspaceColumn) },
|
|
53
|
+
txOptions,
|
|
54
|
+
beforeNoteWrite: config.onBeforeNoteWrite,
|
|
55
|
+
client: config.client,
|
|
56
|
+
parent: (kind) => kinds.get(kind),
|
|
57
|
+
model,
|
|
58
|
+
notes: (client) => model(client, noteModel),
|
|
59
|
+
noteWhere: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId }),
|
|
60
|
+
toRecord(row) {
|
|
61
|
+
const fields = row;
|
|
62
|
+
for (const parent of kinds.values()) {
|
|
63
|
+
const parentId = fields[parent.noteColumn];
|
|
64
|
+
if (typeof parentId === "string" && parentId !== "") {
|
|
65
|
+
return {
|
|
66
|
+
id: fields.id,
|
|
67
|
+
parentKind: parent.kind,
|
|
68
|
+
parentId,
|
|
69
|
+
body: fields.body,
|
|
70
|
+
revision: fields.revision,
|
|
71
|
+
authorId: fields[authorColumn],
|
|
72
|
+
createdAt: fields.createdAt,
|
|
73
|
+
updatedAt: fields.updatedAt,
|
|
74
|
+
deletedAt: fields.deletedAt ?? null,
|
|
75
|
+
deletedBy: fields.deletedBy ?? null
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
throw new Error(`createPrismaNoteStore: note ${String(fields.id)} has none of the configured parent columns set`);
|
|
80
|
+
},
|
|
81
|
+
async limitLockWait(tx) {
|
|
82
|
+
await tx.$executeRawUnsafe(`SELECT set_config('lock_timeout', $1, true)`, `${lockWaitMs}ms`);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/entity-notes/prisma/cursor.ts
|
|
88
|
+
var SHAPE = /^v1\.([A-Za-z0-9_-]+)$/;
|
|
89
|
+
var MIN_TIME = -621355968e5;
|
|
90
|
+
var MAX_TIME = 253402300799999;
|
|
91
|
+
function toBase64Url(text) {
|
|
92
|
+
const bytes = new TextEncoder().encode(text);
|
|
93
|
+
let binary = "";
|
|
94
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
95
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
96
|
+
}
|
|
97
|
+
function fromBase64Url(encoded) {
|
|
98
|
+
try {
|
|
99
|
+
const padded = encoded.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - encoded.length % 4) % 4);
|
|
100
|
+
const binary = atob(padded);
|
|
101
|
+
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
102
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function encodeCursor(time, id) {
|
|
108
|
+
return `v1.${toBase64Url(JSON.stringify([time, id]))}`;
|
|
109
|
+
}
|
|
110
|
+
function decodeCursor(cursor) {
|
|
111
|
+
const match = SHAPE.exec(cursor);
|
|
112
|
+
if (!match) return null;
|
|
113
|
+
const json = fromBase64Url(match[1]);
|
|
114
|
+
if (json === null) return null;
|
|
115
|
+
let parsed;
|
|
116
|
+
try {
|
|
117
|
+
parsed = JSON.parse(json);
|
|
118
|
+
} catch {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
if (!Array.isArray(parsed) || parsed.length !== 2) return null;
|
|
122
|
+
const [time, id] = parsed;
|
|
123
|
+
if (typeof time !== "number" || !Number.isInteger(time) || time < MIN_TIME || time > MAX_TIME) return null;
|
|
124
|
+
if (typeof id !== "string" || id.length === 0 || id.length > 255 || id.includes("\0")) return null;
|
|
125
|
+
return encodeCursor(time, id) === cursor ? { time, id } : null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/entity-notes/prisma/reads.ts
|
|
129
|
+
var IDS_PER_QUERY = 1e4;
|
|
130
|
+
function chunksOf(items) {
|
|
131
|
+
const pieces = [];
|
|
132
|
+
for (let start = 0; start < items.length; start += IDS_PER_QUERY) pieces.push(items.slice(start, start + IDS_PER_QUERY));
|
|
133
|
+
return pieces;
|
|
134
|
+
}
|
|
135
|
+
function createNoteReads(context) {
|
|
136
|
+
const { noteWhere } = context;
|
|
137
|
+
const db = () => context.client();
|
|
138
|
+
const statusFilter = (status) => status === "live" ? null : { not: null };
|
|
139
|
+
return {
|
|
140
|
+
async get(id) {
|
|
141
|
+
const row = await context.notes(db()).findFirst({ where: noteWhere({ id }) });
|
|
142
|
+
return row ? context.toRecord(row) : null;
|
|
143
|
+
},
|
|
144
|
+
async list(query) {
|
|
145
|
+
let after = null;
|
|
146
|
+
if (query.cursor !== null) {
|
|
147
|
+
after = decodeCursor(query.cursor);
|
|
148
|
+
if (after === null) return { kind: "badCursor" };
|
|
149
|
+
}
|
|
150
|
+
const parent = context.parent(query.parent.kind);
|
|
151
|
+
if (!parent) return { kind: "page", notes: [], nextCursor: null };
|
|
152
|
+
const where = noteWhere({
|
|
153
|
+
[parent.noteColumn]: query.parent.id,
|
|
154
|
+
deletedAt: statusFilter(query.status),
|
|
155
|
+
...after ? { OR: [{ createdAt: { lt: new Date(after.time) } }, { createdAt: new Date(after.time), id: { lt: after.id } }] } : {}
|
|
156
|
+
});
|
|
157
|
+
const rows = await context.notes(db()).findMany({ where, orderBy: [{ createdAt: "desc" }, { id: "desc" }], take: query.limit + 1 });
|
|
158
|
+
const notes = rows.slice(0, query.limit).map((row) => context.toRecord(row));
|
|
159
|
+
const last = notes[notes.length - 1];
|
|
160
|
+
return { kind: "page", notes, nextCursor: rows.length > query.limit && last ? encodeCursor(last.createdAt.getTime(), last.id) : null };
|
|
161
|
+
},
|
|
162
|
+
async countByParent(kind, parentIds, status) {
|
|
163
|
+
const counts = new Map(parentIds.map((id) => [id, 0]));
|
|
164
|
+
const parent = context.parent(kind);
|
|
165
|
+
if (!parent) return counts;
|
|
166
|
+
for (const piece of chunksOf([...counts.keys()])) {
|
|
167
|
+
const grouped = await context.notes(db()).groupBy({
|
|
168
|
+
by: [parent.noteColumn],
|
|
169
|
+
where: noteWhere({ [parent.noteColumn]: { in: piece }, deletedAt: statusFilter(status) }),
|
|
170
|
+
_count: { _all: true }
|
|
171
|
+
});
|
|
172
|
+
for (const row of grouped) counts.set(row[parent.noteColumn], row._count._all);
|
|
173
|
+
}
|
|
174
|
+
return counts;
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/entity-notes/prisma/errors.ts
|
|
180
|
+
function hasCode(error, code, depth) {
|
|
181
|
+
if (typeof error !== "object" || error === null || depth > 4) return false;
|
|
182
|
+
const fields = error;
|
|
183
|
+
if (fields.code === code) return true;
|
|
184
|
+
return ["cause", "meta", "originalError", "driverAdapterError"].some((key) => hasCode(fields[key], code, depth + 1));
|
|
185
|
+
}
|
|
186
|
+
var isForeignKeyViolation = (error) => hasCode(error, "P2003", 0);
|
|
187
|
+
|
|
188
|
+
// src/entity-notes/prisma/writes.ts
|
|
189
|
+
function createNoteWrites(context) {
|
|
190
|
+
const { noteWhere, sql } = context;
|
|
191
|
+
const db = () => context.client();
|
|
192
|
+
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;
|
|
193
|
+
const read = async (tx, id) => {
|
|
194
|
+
const row = await context.notes(tx).findFirst({ where: noteWhere({ id }) });
|
|
195
|
+
return row ? context.toRecord(row) : null;
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
async create(parent, body, authorId) {
|
|
199
|
+
const kind = context.parent(parent.kind);
|
|
200
|
+
if (!kind) return { kind: "parentGone" };
|
|
201
|
+
const parentExists = async () => await context.model(db(), kind.model).findFirst({ where: { id: parent.id, [kind.workspaceColumn]: context.workspaceId }, select: { id: true } }) != null;
|
|
202
|
+
if (!await parentExists()) return { kind: "parentGone" };
|
|
203
|
+
if (context.beforeNoteWrite) await context.beforeNoteWrite();
|
|
204
|
+
try {
|
|
205
|
+
return await db().$transaction(async (tx) => {
|
|
206
|
+
await context.limitLockWait(tx);
|
|
207
|
+
const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${kind.sqlTable} WHERE "id" = $1 AND ${kind.sqlWorkspaceColumn} = $2 FOR KEY SHARE`, parent.id, context.workspaceId);
|
|
208
|
+
if (locked.length === 0) return { kind: "parentGone" };
|
|
209
|
+
const stamp = /* @__PURE__ */ new Date();
|
|
210
|
+
const row = await context.notes(tx).create({
|
|
211
|
+
data: { ...noteWhere(), [kind.noteColumn]: parent.id, body, revision: 1, [context.authorColumn]: authorId, createdAt: stamp, updatedAt: stamp, deletedAt: null, deletedBy: null }
|
|
212
|
+
});
|
|
213
|
+
return { kind: "created", note: context.toRecord(row) };
|
|
214
|
+
}, context.txOptions);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (isForeignKeyViolation(error)) return { kind: "parentGone" };
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
async update(id, body, expectedRevision) {
|
|
221
|
+
return db().$transaction(async (tx) => {
|
|
222
|
+
await context.limitLockWait(tx);
|
|
223
|
+
if (!await lockNote(tx, id)) return { kind: "notFound" };
|
|
224
|
+
const before = await read(tx, id);
|
|
225
|
+
if (!before) return { kind: "notFound" };
|
|
226
|
+
if (before.deletedAt !== null) return { kind: "deleted" };
|
|
227
|
+
if (before.revision !== expectedRevision) return { kind: "conflict", current: before };
|
|
228
|
+
const { count } = await context.notes(tx).updateMany({
|
|
229
|
+
where: noteWhere({ id, revision: expectedRevision, deletedAt: null }),
|
|
230
|
+
data: { body, revision: expectedRevision + 1, updatedAt: /* @__PURE__ */ new Date() }
|
|
231
|
+
});
|
|
232
|
+
const after = await read(tx, id);
|
|
233
|
+
if (count === 0 || !after) return after ? after.deletedAt !== null ? { kind: "deleted" } : { kind: "conflict", current: after } : { kind: "notFound" };
|
|
234
|
+
return { kind: "updated", before, after };
|
|
235
|
+
}, context.txOptions);
|
|
236
|
+
},
|
|
237
|
+
async softDelete(id, actorId) {
|
|
238
|
+
return db().$transaction(async (tx) => {
|
|
239
|
+
await context.limitLockWait(tx);
|
|
240
|
+
if (!await lockNote(tx, id)) return { kind: "notFound" };
|
|
241
|
+
const before = await read(tx, id);
|
|
242
|
+
if (!before) return { kind: "notFound" };
|
|
243
|
+
if (before.deletedAt !== null) return { kind: "alreadyDeleted" };
|
|
244
|
+
const { count } = await context.notes(tx).updateMany({
|
|
245
|
+
where: noteWhere({ id, deletedAt: null }),
|
|
246
|
+
data: { deletedAt: /* @__PURE__ */ new Date(), deletedBy: actorId, updatedAt: before.updatedAt }
|
|
247
|
+
});
|
|
248
|
+
const after = await read(tx, id);
|
|
249
|
+
if (count === 0 || !after) return after ? { kind: "alreadyDeleted" } : { kind: "notFound" };
|
|
250
|
+
return { kind: "deleted", before, after };
|
|
251
|
+
}, context.txOptions);
|
|
252
|
+
},
|
|
253
|
+
async restore(id) {
|
|
254
|
+
return db().$transaction(async (tx) => {
|
|
255
|
+
await context.limitLockWait(tx);
|
|
256
|
+
if (!await lockNote(tx, id)) return { kind: "notFound" };
|
|
257
|
+
const before = await read(tx, id);
|
|
258
|
+
if (!before) return { kind: "notFound" };
|
|
259
|
+
if (before.deletedAt === null) return { kind: "notDeleted" };
|
|
260
|
+
const { count } = await context.notes(tx).updateMany({
|
|
261
|
+
where: { ...noteWhere({ id }), NOT: { deletedAt: null } },
|
|
262
|
+
data: { deletedAt: null, deletedBy: null, updatedAt: before.updatedAt }
|
|
263
|
+
});
|
|
264
|
+
const after = await read(tx, id);
|
|
265
|
+
if (count === 0 || !after) return after ? { kind: "notDeleted" } : { kind: "notFound" };
|
|
266
|
+
return { kind: "restored", before, after };
|
|
267
|
+
}, context.txOptions);
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// src/entity-notes/prisma/index.ts
|
|
273
|
+
function createPrismaNoteStore(config) {
|
|
274
|
+
const context = createContext(config);
|
|
275
|
+
return { ...createNoteReads(context), ...createNoteWrites(context) };
|
|
276
|
+
}
|
|
277
|
+
export {
|
|
278
|
+
createPrismaNoteStore
|
|
279
|
+
};
|
|
@@ -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 };
|