@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.
@@ -43,6 +43,7 @@ function createCompanyService(store, suppliedLimits = DEFAULT_COMPANY_LIMITS) {
43
43
  const result = await store.create({ name: name.name, nameKey: name.key, ...website.value }, { maxCompanies: limits.maxPerWorkspace });
44
44
  if (result.kind === "created") return { ok: true, company: result.company };
45
45
  if (result.kind === "duplicate") return fail({ reason: "duplicate" });
46
+ if (result.kind === "inTrash") return fail({ reason: "in-trash", id: result.id });
46
47
  if (result.kind === "limit") return fail({ reason: "limit" });
47
48
  return unknownKind("create", result);
48
49
  }
@@ -77,8 +78,10 @@ function createCompanyService(store, suppliedLimits = DEFAULT_COMPANY_LIMITS) {
77
78
  if (result.kind === "updated") return { ok: true, before: result.before, after: result.after };
78
79
  if (result.kind === "notFound") return fail({ reason: "not-found" });
79
80
  if (result.kind === "duplicate") return fail({ reason: "duplicate" });
81
+ if (result.kind === "inTrash") return fail({ reason: "in-trash", id: result.id });
80
82
  return unknownKind("update", result);
81
83
  }
84
+ const trashable = () => typeof store.trash === "function" ? store : null;
82
85
  return {
83
86
  async list() {
84
87
  return [...await store.list()].sort(byName);
@@ -99,6 +102,35 @@ function createCompanyService(store, suppliedLimits = DEFAULT_COMPANY_LIMITS) {
99
102
  if (result.kind === "notFound") return fail({ reason: "not-found" });
100
103
  return unknownKind("remove", result);
101
104
  },
105
+ async trash(id, actorId) {
106
+ const s = trashable();
107
+ if (!s) return fail({ reason: "unsupported" });
108
+ const result = await s.trash(id, actorId);
109
+ if (result.kind === "trashed") return { ok: true, before: result.before, after: result.after };
110
+ if (result.kind === "notFound") return fail({ reason: "not-found" });
111
+ if (result.kind === "alreadyTrashed") return fail({ reason: "already-trashed" });
112
+ return unknownKind("trash", result);
113
+ },
114
+ async restore(id) {
115
+ const s = trashable();
116
+ if (!s) return fail({ reason: "unsupported" });
117
+ const result = await s.restore(id);
118
+ if (result.kind === "restored") return { ok: true, before: result.before, after: result.after };
119
+ if (result.kind === "notFound") return fail({ reason: "not-found" });
120
+ if (result.kind === "notTrashed") return fail({ reason: "not-trashed" });
121
+ return unknownKind("restore", result);
122
+ },
123
+ async listTrashed() {
124
+ const s = trashable();
125
+ if (!s) return fail({ reason: "unsupported" });
126
+ return { ok: true, companies: [...await s.listTrashed()] };
127
+ },
128
+ async getAny(id) {
129
+ const s = trashable();
130
+ if (!s) return fail({ reason: "unsupported" });
131
+ const company = await s.getAny(id);
132
+ return company ? { ok: true, company } : fail({ reason: "not-found" });
133
+ },
102
134
  async addMember(companyId, personId, input, actorId) {
103
135
  if (!await store.get(companyId)) return fail({ reason: "not-found" });
104
136
  if (!await store.personExists(personId)) return fail({ reason: "person-gone" });
@@ -158,7 +190,9 @@ var memberKey = (companyId, personId) => `${companyId}\0${personId}`;
158
190
  var personKey = (workspace, id) => `${workspace}\0${id}`;
159
191
  function createMemoryCompanyWorld(options = {}) {
160
192
  const serialise = options.serialise ?? true;
193
+ const softDelete = options.softDelete === true;
161
194
  const companies = /* @__PURE__ */ new Map();
195
+ let trashSequence = 0;
162
196
  const people = /* @__PURE__ */ new Set();
163
197
  const memberships = /* @__PURE__ */ new Map();
164
198
  let sequence = 0;
@@ -174,10 +208,21 @@ function createMemoryCompanyWorld(options = {}) {
174
208
  const copy = (record) => ({ ...record });
175
209
  const copyMember = (record) => ({ ...record });
176
210
  function store(workspace) {
177
- const mine = () => [...companies.values()].filter((row) => row.workspace === workspace).map((row) => row.record);
178
- const own = (id) => {
211
+ const rowsAny = () => [...companies.values()].filter((row) => row.workspace === workspace);
212
+ const mine = () => rowsAny().filter((row) => !row.trashed).map((row) => row.record);
213
+ const ownRowAny = (id) => {
179
214
  const row = companies.get(id);
180
- return row && row.workspace === workspace ? row.record : void 0;
215
+ return row && row.workspace === workspace ? row : void 0;
216
+ };
217
+ const own = (id) => {
218
+ const row = ownRowAny(id);
219
+ return row && !row.trashed ? row.record : void 0;
220
+ };
221
+ const holderOf = (nameKey, exceptId) => rowsAny().find((row) => row.record.id !== exceptId && row.record.nameKey === nameKey);
222
+ const collision = (nameKey, exceptId) => {
223
+ const holder = holderOf(nameKey, exceptId);
224
+ if (!holder) return null;
225
+ return holder.trashed ? { kind: "inTrash", id: holder.record.id } : { kind: "duplicate" };
181
226
  };
182
227
  const personIsMine = (id) => people.has(personKey(workspace, id));
183
228
  const membersOfCompany = (companyId) => [...memberships.values()].filter((m) => m.workspace === workspace && m.record.companyId === companyId);
@@ -189,7 +234,7 @@ function createMemoryCompanyWorld(options = {}) {
189
234
  if (membersOfCompany(companyId).length >= limits.maxMembers) return { kind: "memberLimit" };
190
235
  return null;
191
236
  }
192
- return {
237
+ const base = {
193
238
  async list() {
194
239
  return mine().map(copy);
195
240
  },
@@ -207,8 +252,9 @@ function createMemoryCompanyWorld(options = {}) {
207
252
  },
208
253
  create(input, limits) {
209
254
  return exclusive(async () => {
210
- if (mine().length >= limits.maxCompanies) return { kind: "limit" };
211
- if (mine().some((company) => company.nameKey === input.nameKey)) return { kind: "duplicate" };
255
+ if (rowsAny().length >= limits.maxCompanies) return { kind: "limit" };
256
+ const taken = collision(input.nameKey);
257
+ if (taken) return taken;
212
258
  await tick();
213
259
  const record = { id: `company_${++sequence}`, name: input.name, nameKey: input.nameKey, website: input.website, domain: input.domain };
214
260
  companies.set(record.id, { workspace, record });
@@ -220,7 +266,8 @@ function createMemoryCompanyWorld(options = {}) {
220
266
  const current = own(id);
221
267
  if (!current) return { kind: "notFound" };
222
268
  const before = copy(current);
223
- if (patch.rename && mine().some((company) => company.id !== id && company.nameKey === patch.rename?.nameKey)) return { kind: "duplicate" };
269
+ const taken = patch.rename ? collision(patch.rename.nameKey, id) : null;
270
+ if (taken) return taken;
224
271
  await tick();
225
272
  if (patch.rename) {
226
273
  current.name = patch.rename.name;
@@ -235,7 +282,7 @@ function createMemoryCompanyWorld(options = {}) {
235
282
  },
236
283
  remove(id) {
237
284
  return exclusive(async () => {
238
- const current = own(id);
285
+ const current = ownRowAny(id)?.record;
239
286
  if (!current) return { kind: "notFound" };
240
287
  const memberCount = membersOfCompany(id).length;
241
288
  await tick();
@@ -311,6 +358,40 @@ function createMemoryCompanyWorld(options = {}) {
311
358
  return found;
312
359
  }
313
360
  };
361
+ if (!softDelete) return base;
362
+ const trashable = {
363
+ ...base,
364
+ trash(id, actorId) {
365
+ return exclusive(async () => {
366
+ const row = ownRowAny(id);
367
+ if (!row) return { kind: "notFound" };
368
+ if (row.trashed) return { kind: "alreadyTrashed" };
369
+ const before = copy(row.record);
370
+ await tick();
371
+ row.trashed = { at: ++trashSequence, by: actorId };
372
+ return { kind: "trashed", before, after: copy(row.record) };
373
+ });
374
+ },
375
+ restore(id) {
376
+ return exclusive(async () => {
377
+ const row = ownRowAny(id);
378
+ if (!row) return { kind: "notFound" };
379
+ if (!row.trashed) return { kind: "notTrashed" };
380
+ const before = copy(row.record);
381
+ await tick();
382
+ delete row.trashed;
383
+ return { kind: "restored", before, after: copy(row.record) };
384
+ });
385
+ },
386
+ async listTrashed() {
387
+ return rowsAny().filter((row) => row.trashed).sort((a, b) => b.trashed.at - a.trashed.at).map((row) => copy(row.record));
388
+ },
389
+ async getAny(id) {
390
+ const row = ownRowAny(id);
391
+ return row ? copy(row.record) : null;
392
+ }
393
+ };
394
+ return trashable;
314
395
  }
315
396
  return {
316
397
  store,
@@ -341,6 +422,7 @@ function createMemoryCompanyHarness(options = {}) {
341
422
  async newWorkspace() {
342
423
  return `workspace_${++workspaces}`;
343
424
  },
425
+ ...options.softDelete === true ? { supportsTrash: true } : {},
344
426
  storeFor: (workspace) => world.store(workspace),
345
427
  async addPerson(workspace) {
346
428
  return world.addPerson(workspace);
@@ -407,23 +489,23 @@ function defineCompanyStoreCompaniesContract(kit) {
407
489
  expect(ids(await store.getMany([taft.id, taft.id]))).toEqual([taft.id]);
408
490
  expect(ids(await store.getMany([unasked.id]))).toEqual([unasked.id]);
409
491
  expect(new Set(ids(await store.list())).size).toBe(3);
410
- const many3 = [taft, other, unasked];
492
+ const many4 = [taft, other, unasked];
411
493
  const bigLimits = { maxCompanies: 1e3 };
412
494
  for (let i = 0; i < 117; i++) {
413
495
  const result = await store.create({ name: `Company ${i}`, nameKey: `company ${i}`, ...site("shared.com") }, bigLimits);
414
496
  if (result.kind !== "created") throw new Error(`setup: could not create Company ${i}: ${result.kind}`);
415
- many3.push(result.company);
497
+ many4.push(result.company);
416
498
  }
417
499
  expect((await store.list()).length).toBe(120);
418
- expect(ids(await store.list())).toEqual(ids(many3));
419
- expect(ids(await store.getMany(many3.map((company) => company.id)))).toEqual(ids(many3));
420
- expect(ids(await store.findByDomain("shared.com"))).toEqual(ids(many3.slice(3)));
500
+ expect(ids(await store.list())).toEqual(ids(many4));
501
+ expect(ids(await store.getMany(many4.map((company) => company.id)))).toEqual(ids(many4));
502
+ expect(ids(await store.findByDomain("shared.com"))).toEqual(ids(many4.slice(3)));
421
503
  const everyCount = await store.memberCounts();
422
- expect([...everyCount.keys()].sort()).toEqual(ids(many3));
423
- expect([...everyCount.values()].every((count3) => count3 === 0)).toBe(true);
424
- const askedCount = await store.memberCounts(many3.map((company) => company.id));
425
- expect([...askedCount.keys()].sort()).toEqual(ids(many3));
426
- const last = many3[119];
504
+ expect([...everyCount.keys()].sort()).toEqual(ids(many4));
505
+ expect([...everyCount.values()].every((count4) => count4 === 0)).toBe(true);
506
+ const askedCount = await store.memberCounts(many4.map((company) => company.id));
507
+ expect([...askedCount.keys()].sort()).toEqual(ids(many4));
508
+ const last = many4[119];
427
509
  expect(core(await store.get(last.id))).toEqual(core(last));
428
510
  expect((await store.findByKey(last.nameKey))?.id).toBe(last.id);
429
511
  expect(await store.create({ name: "Copy", nameKey: last.nameKey, ...NO_SITE }, bigLimits)).toEqual({ kind: "duplicate" });
@@ -433,7 +515,7 @@ function defineCompanyStoreCompaniesContract(kit) {
433
515
  expect(removedLast.kind === "removed" && removedLast.company.nameKey).toBe("last renamed");
434
516
  expect((await store.list()).length).toBe(119);
435
517
  const fresh = await store.create({ name: "Fresh", nameKey: "fresh", ...NO_SITE }, bigLimits);
436
- expect(fresh.kind === "created" && fresh.company.id !== last.id && !ids(many3).includes(fresh.company.id)).toBe(true);
518
+ expect(fresh.kind === "created" && fresh.company.id !== last.id && !ids(many4).includes(fresh.company.id)).toBe(true);
437
519
  expect(await store.get(last.id)).toBeNull();
438
520
  });
439
521
  it("text comes back exactly as stored (accents, quotes, backslashes, percent and underscore signs, emoji, a name of the maximum length; given to create and to update), and a domain search is an exact value, never a pattern", async () => {
@@ -1082,7 +1164,7 @@ function defineCompanyStoreReadsContract(kit) {
1082
1164
  await join(b.id, q);
1083
1165
  await join(b.id, r);
1084
1166
  expect(await counts()).toEqual([[a.id, 2], [b.id, 3]].sort());
1085
- for (const [, count3] of await counts()) expect(typeof count3).toBe("number");
1167
+ for (const [, count4] of await counts()) expect(typeof count4).toBe("number");
1086
1168
  await store.addMember(a.id, p, "Again", ACTOR, MEMBER_LIMITS);
1087
1169
  expect(await counts(a.id)).toEqual([[a.id, 2]]);
1088
1170
  expect(await counts(a.id, "missing", "")).toEqual([[a.id, 2]]);
@@ -1553,6 +1635,135 @@ function defineCompanyStoreHooksContract(kit) {
1553
1635
  });
1554
1636
  }
1555
1637
 
1638
+ // src/companies/server/contract-trash.ts
1639
+ var many3 = (n, make) => Promise.all(Array.from({ length: n }, (_, i) => make(i)));
1640
+ var count3 = (results, kind) => results.filter((result) => result.kind === kind).length;
1641
+ function defineCompanyStoreTrashContract(kit) {
1642
+ const { describe, it, expect } = kit.api;
1643
+ async function trashSetup() {
1644
+ const base = await kit.setup();
1645
+ return { ...base, store: base.store };
1646
+ }
1647
+ describe("CompanyStore contract: the Trash", () => {
1648
+ it("trash hides a company from list, get, getMany, findByKey, findByDomain, memberCounts and members, and shows it in listTrashed and getAny; the others stay visible", async () => {
1649
+ const { store, make, person, join } = await trashSetup();
1650
+ const gone = await make(store, "Gone", site("gone.com"));
1651
+ const kept = await make(store, "Kept", site("kept.com"));
1652
+ await join(gone.id, await person());
1653
+ const trashed = await store.trash(gone.id, ACTOR);
1654
+ expect(trashed.kind).toBe("trashed");
1655
+ if (trashed.kind !== "trashed") return;
1656
+ expect(trashed.before.id).toBe(gone.id);
1657
+ expect(trashed.after.id).toBe(gone.id);
1658
+ expect(ids(await store.list())).toEqual([kept.id]);
1659
+ expect(await store.get(gone.id)).toBeNull();
1660
+ expect(ids(await store.getMany([gone.id, kept.id]))).toEqual([kept.id]);
1661
+ expect(await store.findByKey("gone")).toBeNull();
1662
+ expect((await store.findByKey("kept"))?.id).toBe(kept.id);
1663
+ expect(ids(await store.findByDomain("gone.com"))).toEqual([]);
1664
+ expect(ids(await store.findByDomain("kept.com"))).toEqual([kept.id]);
1665
+ expect([...(await store.memberCounts()).keys()]).toEqual([kept.id]);
1666
+ expect(await store.members(gone.id)).toEqual([]);
1667
+ expect(cores(await store.listTrashed())).toEqual(cores([gone]));
1668
+ expect((await store.getAny(gone.id))?.id).toBe(gone.id);
1669
+ expect((await store.getAny(kept.id))?.id).toBe(kept.id);
1670
+ expect(await store.getAny("missing")).toBeNull();
1671
+ });
1672
+ it("trashing twice gives alreadyTrashed, trashing a missing company gives notFound, and neither changes anything", async () => {
1673
+ const { store, make } = await trashSetup();
1674
+ const a = await make(store, "A");
1675
+ expect((await store.trash(a.id, ACTOR)).kind).toBe("trashed");
1676
+ expect((await store.trash(a.id, ACTOR)).kind).toBe("alreadyTrashed");
1677
+ expect((await store.trash("missing", ACTOR)).kind).toBe("notFound");
1678
+ expect(ids(await store.listTrashed())).toEqual([a.id]);
1679
+ });
1680
+ it("restore brings the company back everywhere with its members; restoring a live company gives notTrashed and a missing one notFound", async () => {
1681
+ const { store, make, person, join } = await trashSetup();
1682
+ const a = await make(store, "A", site("a.com"));
1683
+ await join(a.id, await person());
1684
+ await store.trash(a.id, ACTOR);
1685
+ const restored = await store.restore(a.id);
1686
+ expect(restored.kind).toBe("restored");
1687
+ expect(ids(await store.list())).toEqual([a.id]);
1688
+ expect((await store.get(a.id))?.id).toBe(a.id);
1689
+ expect((await store.findByKey("a"))?.id).toBe(a.id);
1690
+ expect(ids(await store.findByDomain("a.com"))).toEqual([a.id]);
1691
+ expect((await store.memberCounts([a.id])).get(a.id)).toBe(1);
1692
+ expect(await store.listTrashed()).toEqual([]);
1693
+ expect((await store.restore(a.id)).kind).toBe("notTrashed");
1694
+ expect((await store.restore("missing")).kind).toBe("notFound");
1695
+ });
1696
+ it("a name held by a trashed company is inTrash (with its id) on create and on update, a name held by a live company is duplicate, and nothing is created or renamed", async () => {
1697
+ const { store, make } = await trashSetup();
1698
+ const trashedOne = await make(store, "Taken");
1699
+ const live = await make(store, "Live");
1700
+ const other = await make(store, "Other");
1701
+ await store.trash(trashedOne.id, ACTOR);
1702
+ expect(await store.create({ name: "TAKEN", nameKey: "taken", ...NO_SITE }, LIMITS)).toEqual({ kind: "inTrash", id: trashedOne.id });
1703
+ expect(await store.create({ name: "Live", nameKey: "live", ...NO_SITE }, LIMITS)).toEqual({ kind: "duplicate" });
1704
+ expect(await store.update(other.id, { rename: { name: "Taken", nameKey: "taken" } })).toEqual({ kind: "inTrash", id: trashedOne.id });
1705
+ expect(await store.update(other.id, { rename: { name: "Live", nameKey: "live" } })).toEqual({ kind: "duplicate" });
1706
+ expect((await store.get(other.id))?.nameKey).toBe("other");
1707
+ expect(ids(await store.list())).toEqual([live.id, other.id].sort());
1708
+ });
1709
+ it("a trashed company cannot be updated (notFound), and a restore frees nothing: its name is taken again as a plain duplicate", async () => {
1710
+ const { store, make } = await trashSetup();
1711
+ const a = await make(store, "A");
1712
+ await store.trash(a.id, ACTOR);
1713
+ expect((await store.update(a.id, { website: { website: "https://a.com", domain: "a.com" } })).kind).toBe("notFound");
1714
+ await store.restore(a.id);
1715
+ expect(await store.create({ name: "A", nameKey: "a", ...NO_SITE }, LIMITS)).toEqual({ kind: "duplicate" });
1716
+ });
1717
+ it("remove stays a hard delete: it removes a live company and a trashed one for good (no listTrashed, no getAny afterwards, and the name is free)", async () => {
1718
+ const { store, make } = await trashSetup();
1719
+ const a = await make(store, "A");
1720
+ const b = await make(store, "B");
1721
+ await store.trash(b.id, ACTOR);
1722
+ expect((await store.remove(a.id)).kind).toBe("removed");
1723
+ expect((await store.remove(b.id)).kind).toBe("removed");
1724
+ expect(await store.getAny(a.id)).toBeNull();
1725
+ expect(await store.getAny(b.id)).toBeNull();
1726
+ expect(await store.listTrashed()).toEqual([]);
1727
+ expect((await store.remove(b.id)).kind).toBe("notFound");
1728
+ expect((await store.create({ name: "B", nameKey: "b", ...NO_SITE }, LIMITS)).kind).toBe("created");
1729
+ });
1730
+ it("a trashed company still counts against the create limit (a workspace at its cap stays at its cap until the company is removed for good)", async () => {
1731
+ const { store, make } = await trashSetup();
1732
+ const a = await make(store, "A");
1733
+ await store.trash(a.id, ACTOR);
1734
+ expect(await store.create({ name: "B", nameKey: "b", ...NO_SITE }, { maxCompanies: 1 })).toEqual({ kind: "limit" });
1735
+ await store.remove(a.id);
1736
+ expect((await store.create({ name: "B", nameKey: "b", ...NO_SITE }, { maxCompanies: 1 })).kind).toBe("created");
1737
+ });
1738
+ it("a workspace never sees, trashes or restores another workspace's companies", async () => {
1739
+ const mine = await trashSetup();
1740
+ const theirs = kit.harness.storeFor(await kit.harness.newWorkspace());
1741
+ const a = await mine.make(mine.store, "A");
1742
+ expect((await theirs.trash(a.id, ACTOR)).kind).toBe("notFound");
1743
+ await mine.store.trash(a.id, ACTOR);
1744
+ expect(await theirs.listTrashed()).toEqual([]);
1745
+ expect(await theirs.getAny(a.id)).toBeNull();
1746
+ expect((await theirs.restore(a.id)).kind).toBe("notFound");
1747
+ expect(ids(await mine.store.listTrashed())).toEqual([a.id]);
1748
+ });
1749
+ it("ten simultaneous trashes of one company give exactly one trashed and nine alreadyTrashed", async () => {
1750
+ const { store, make } = await trashSetup();
1751
+ const a = await make(store, "Racy");
1752
+ const results = await many3(10, () => store.trash(a.id, ACTOR));
1753
+ expect([count3(results, "trashed"), count3(results, "alreadyTrashed")]).toEqual([1, 9]);
1754
+ expect(ids(await store.listTrashed())).toEqual([a.id]);
1755
+ });
1756
+ it("ten simultaneous restores of one trashed company give exactly one restored and nine notTrashed, and it is live afterwards", async () => {
1757
+ const { store, make } = await trashSetup();
1758
+ const a = await make(store, "Racy");
1759
+ await store.trash(a.id, ACTOR);
1760
+ const results = await many3(10, () => store.restore(a.id));
1761
+ expect([count3(results, "restored"), count3(results, "notTrashed")]).toEqual([1, 9]);
1762
+ expect(ids(await store.list())).toEqual([a.id]);
1763
+ });
1764
+ });
1765
+ }
1766
+
1556
1767
  // src/companies/server/contract-tenancy.ts
1557
1768
  function defineCompanyStoreTenancyContract(kit) {
1558
1769
  const { describe, it, expect } = kit.api;
@@ -1567,10 +1778,10 @@ function defineCompanyStoreTenancyContract(kit) {
1567
1778
  if (result.kind !== "added") throw new Error(`setup: could not add a member in the second workspace: ${result.kind}`);
1568
1779
  return result.member;
1569
1780
  };
1570
- const crowdB = async (count3) => {
1781
+ const crowdB = async (count4) => {
1571
1782
  const pb = await personB();
1572
1783
  const companies = [];
1573
- for (let i = 0; i < count3; i++) {
1784
+ for (let i = 0; i < count4; i++) {
1574
1785
  const result = await storeB.create({ name: `B ${i}`, nameKey: `b ${i}`, ...site("b.com") }, { maxCompanies: 1e3 });
1575
1786
  if (result.kind !== "created") throw new Error(`setup: could not create B ${i}: ${result.kind}`);
1576
1787
  await joinB(result.company.id, pb, "B");
@@ -1813,6 +2024,7 @@ function defineCompanyStoreContract(api, harness) {
1813
2024
  defineCompanyStoreConcurrencyContract(kit);
1814
2025
  defineCompanyStoreMembersConcurrencyContract(kit);
1815
2026
  defineCompanyStoreHooksContract(kit);
2027
+ if (harness.supportsTrash === true) defineCompanyStoreTrashContract(kit);
1816
2028
  api.it("cleans up", async () => {
1817
2029
  await harness.cleanup();
1818
2030
  });
@@ -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,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,10 @@
1
+ import {
2
+ DEFAULT_NOTE_LIMITS,
3
+ checkNoteBody,
4
+ cleanNoteBody
5
+ } from "../chunk-3VGJ4NFX.mjs";
6
+ export {
7
+ DEFAULT_NOTE_LIMITS,
8
+ checkNoteBody,
9
+ cleanNoteBody
10
+ };
@@ -0,0 +1,57 @@
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
+ * OPTIONAL. The parent model's nullable "trashed at" column (e.g. `deletedAt`). When set, `create` treats a parent whose column is not NULL as gone (`parentGone`), in both the
14
+ * existence check and the share lock. Off by default: without it the queries are exactly those of 1.5.0.
15
+ */
16
+ softDeleteColumn?: string;
17
+ }
18
+ interface PrismaNoteStoreConfig {
19
+ /** Called each time the store needs the client (never at import), so a test can swap in a client with a bigger pool. */
20
+ client: () => PrismaLikeClient;
21
+ /** The workspace (organization, account, tenant) this store is built for. Every query is scoped by it. */
22
+ workspaceId: string;
23
+ /** Prisma delegate of the note model, e.g. `note`. */
24
+ noteModel: string;
25
+ /** SQL table of the note model, e.g. `Note` (used in the row locks). */
26
+ noteTable: string;
27
+ /** Workspace column on the note model, e.g. `organizationId`. */
28
+ workspaceColumn: string;
29
+ /** The kinds of parent a note can belong to, by kind name, e.g. `{ contact: { noteColumn: 'contactId', model: 'contact', table: 'Contact' } }`. At least one. */
30
+ parents: Record<string, PrismaNoteParentConfig>;
31
+ /** Column AND Prisma field of the note model for who wrote it (plain text). Default `authorId`. */
32
+ authorColumn?: string;
33
+ /** How long a transaction waits for any one lock before it throws (Postgres lock_timeout). Default 5000. */
34
+ lockWaitMs?: number;
35
+ /** Interactive transaction limits. Defaults: maxWait 10000, timeout 15000. */
36
+ transaction?: {
37
+ maxWait?: number;
38
+ timeout?: number;
39
+ };
40
+ /** 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. */
41
+ onBeforeNoteWrite?: () => Promise<void>;
42
+ }
43
+ /** The part of a transaction client the store uses. A real Prisma transaction client satisfies it; model delegates are looked up by name. */
44
+ interface PrismaLikeTx {
45
+ $executeRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;
46
+ $queryRawUnsafe(query: string, ...values: unknown[]): Promise<unknown>;
47
+ }
48
+ interface PrismaLikeClient extends PrismaLikeTx {
49
+ $transaction<R>(fn: (tx: PrismaLikeTx) => Promise<R>, options?: {
50
+ maxWait?: number;
51
+ timeout?: number;
52
+ }): Promise<R>;
53
+ }
54
+
55
+ declare function createPrismaNoteStore(config: PrismaNoteStoreConfig): NoteStore<NoteRecord>;
56
+
57
+ export { type PrismaLikeClient, type PrismaLikeTx, type PrismaNoteParentConfig, type PrismaNoteStoreConfig, createPrismaNoteStore };