@jskit-ai/crud-core 0.2.14 → 0.2.15

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/locales/en.json +1 -11
  3. package/package.json +19 -19
  4. package/patterns/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
  5. package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
  6. package/patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
  7. package/patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
  8. package/patterns/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
  9. package/src/server/createHooksToCollectChildren.js +56 -34
  10. package/src/server/crudContracts.js +54 -0
  11. package/src/server/defineCrudFeature.js +509 -0
  12. package/src/server/jsonApiModule/actions.js +44 -30
  13. package/src/server/jsonApiModule/routes.js +2 -2
  14. package/src/server/jsonApiModule/service.js +213 -32
  15. package/src/server/jsonApiResourceContract.js +41 -1
  16. package/src/server/listQueryValidators.js +1 -1
  17. package/src/server/removedApi.js +87 -0
  18. package/src/server/types.js +26 -50
  19. package/test/assistantActionConformance.test.js +20 -21
  20. package/test/assistantPagination.integration.test.js +32 -42
  21. package/test/createHooksToCollectChildren.test.js +61 -16
  22. package/test/crudFeaturePackagePattern.test.js +50 -0
  23. package/test/crudOnHandles.test.js +454 -0
  24. package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +444 -141
  25. package/test/errorCodes.test.js +11 -52
  26. package/test/hiddenFields.test.js +62 -0
  27. package/test/listQueryValidators.test.js +1 -1
  28. package/test/routeContracts.test.js +1 -1
  29. package/test/support/crudJsonApiActionOptions.js +3 -3
  30. package/test/unservedCrudAutomation.test.js +27 -22
  31. package/patterns/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
  32. package/patterns/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
  33. package/patterns/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
  34. package/src/server/createCrudServiceFromResource.js +0 -63
  35. package/src/server/defineCrudJsonApiFeature.js +0 -346
  36. package/src/server/fieldAccess.js +0 -298
  37. package/src/server/jsonApiModule/repository.js +0 -355
  38. package/src/server/lookupPathSupport.js +0 -58
  39. package/src/server/lookups.js +0 -40
  40. package/src/server/repositorySupport.js +0 -528
  41. package/src/server/resourceRuntime/compiledRuntime.js +0 -284
  42. package/src/server/resourceRuntime/index.js +0 -659
  43. package/src/server/resourceRuntime/listControls.js +0 -333
  44. package/src/server/resourceRuntime/lookupHydration.js +0 -626
  45. package/src/server/resourceRuntime/operationStages.js +0 -140
  46. package/src/server/resourceRuntime/recordValidation.js +0 -65
  47. package/src/server/serviceMethods.js +0 -149
  48. package/test/createCrudServiceFromResource.test.js +0 -323
  49. package/test/fieldAccess.test.js +0 -86
  50. package/test/jsonApiRepository.test.js +0 -333
  51. package/test/jsonApiRepositoryDataCosts.test.js +0 -183
  52. package/test/jsonApiRepositoryPageLimits.test.js +0 -158
  53. package/test/jsonApiRepositoryRowLocks.test.js +0 -137
  54. package/test/jsonApiResourcePackagePattern.test.js +0 -20
  55. package/test/lookups.test.js +0 -111
  56. package/test/repositorySupport.test.js +0 -767
  57. package/test/resourceRuntime.test.js +0 -1014
  58. package/test/serviceMethods.test.js +0 -139
  59. /package/patterns/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
  60. /package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
@@ -0,0 +1,454 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import knexLib from "knex";
4
+ import { simplifyJsonApiResult } from "@jskit-ai/http-runtime/shared";
5
+ import { validateSchemaPayload } from "@jskit-ai/kernel/shared/validators";
6
+ import { passedOn } from "@jskit-ai/resource-runtime/server";
7
+ import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
8
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
9
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
10
+ import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
11
+ import { createCrudService } from "../src/server/jsonApiModule/service.js";
12
+ import { createCrudContracts } from "../src/server/crudContracts.js";
13
+ import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
14
+
15
+ const WORKSPACE_ONE = Object.freeze({ scopeValues: Object.freeze({ workspaceId: "1" }) });
16
+
17
+ // 250 notes in workspace 1, read through json-rest-api's default page cap (100), with an audit table beside them.
18
+ async function createFixture(t) {
19
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
20
+ t.after(() => knex.destroy());
21
+ await knex.schema.createTable("notes", (table) => {
22
+ table.increments("id");
23
+ table.integer("workspace_id").notNullable();
24
+ table.string("title").notNullable();
25
+ table.string("internal_note");
26
+ });
27
+ await knex.schema.createTable("note_audits", (table) => {
28
+ table.increments("id");
29
+ table.integer("workspace_id").notNullable();
30
+ table.string("message").notNullable();
31
+ });
32
+ await knex.batchInsert("notes", Array.from({ length: 250 }, (_, index) => ({
33
+ workspace_id: 1,
34
+ title: `Note ${index + 1}`,
35
+ internal_note: "staff only"
36
+ })), 100);
37
+ const notes = defineTableResource({
38
+ name: "notes",
39
+ tableName: "notes",
40
+ ownership: "workspace",
41
+ schema: {
42
+ workspaceId: { type: "id", storage: { column: "workspace_id" } },
43
+ title: { type: "string", required: true, search: true },
44
+ // A column the contract below does not name.
45
+ internalNote: { type: "string", nullable: true, storage: { column: "internal_note" } }
46
+ }
47
+ });
48
+ const audits = defineTableResource({
49
+ name: "noteAudits",
50
+ tableName: "note_audits",
51
+ ownership: "workspace",
52
+ schema: {
53
+ workspaceId: { type: "id", storage: { column: "workspace_id" } },
54
+ message: { type: "string", required: true }
55
+ }
56
+ });
57
+ const runtime = await createTestResourceRuntime({ knex });
58
+ const resources = await runtime.own("test.notes", [notes, audits]);
59
+ const repository = resources.notes;
60
+ const crud = defineCrudContract(notes, {
61
+ namespace: "notes",
62
+ fields: { title: { output: "required", create: "required", patch: "optional" } }
63
+ });
64
+ const service = createCrudService({ repository, crud });
65
+ const actionsFor = (options) => createCrudJsonApiActions(crudJsonApiActionOptions({
66
+ namespace: "notes",
67
+ resource: crud,
68
+ repository,
69
+ service,
70
+ surface: "admin",
71
+ permissionForOperation: () => ({ require: "authenticated" }),
72
+ ...options
73
+ }));
74
+ return { knex, repository, audits: resources.noteAudits, crud, service, actionsFor };
75
+ }
76
+
77
+ test("the list action keeps answering a larger limit with one capped page", async (t) => {
78
+ const { repository, actionsFor } = await createFixture(t);
79
+ assert.equal(repository.pageLimits().request, 100);
80
+ const [list] = actionsFor({ operations: ["list"] });
81
+
82
+ for (const limit of [500, "250", 100]) {
83
+ const result = await list.execute({ limit }, WORKSPACE_ONE);
84
+ assert.equal(result.value.data.length, 100, `limit ${limit}`);
85
+ assert.equal(result.value.meta.pagination.pageSize, 100, `limit ${limit}`);
86
+ assert.equal(result.value.meta.pagination.hasMore, true, `limit ${limit}`);
87
+ assert.equal(typeof result.value.meta.pagination.cursor.next, "string");
88
+ }
89
+ const first = await list.execute({ limit: 20 }, WORKSPACE_ONE);
90
+ assert.equal(first.value.data.length, 20);
91
+ // A cursor alone pages on at json-rest-api's default page size.
92
+ const next = await list.execute({ cursor: first.value.meta.pagination.cursor.next }, WORKSPACE_ONE);
93
+ assert.equal(next.value.data[0].attributes.title, "Note 21");
94
+ });
95
+
96
+ test("a column the contract does not name is neither returned nor accepted", async (t) => {
97
+ const { knex, actionsFor } = await createFixture(t);
98
+ const [list, view, create, update] = actionsFor({ operations: ["list", "view", "create", "update"] });
99
+ const page = await list.execute({ limit: 5 }, WORKSPACE_ONE);
100
+ assert.deepEqual(page.value.data.map(({ attributes }) => Object.keys(attributes)), Array(5).fill(["title"]));
101
+ assert.deepEqual(Object.keys((await view.execute({ recordId: "1" }, WORKSPACE_ONE)).value.data.attributes), ["title"]);
102
+ const created = await create.execute({ title: "New" }, WORKSPACE_ONE);
103
+ assert.deepEqual(Object.keys(created.value.data.attributes), ["title"]);
104
+ const updated = await update.execute({ recordId: "1", title: "Renamed" }, WORKSPACE_ONE);
105
+ assert.deepEqual(Object.keys(updated.value.data.attributes), ["title"]);
106
+ // The action runtime validates each input against the action's input before execute runs.
107
+ for (const [action, input] of [[create, { title: "New" }], [update, { recordId: "1" }]]) {
108
+ assert.throws(() => validateSchemaPayload(action.input, { ...input, internalNote: "set by a request" }, { phase: "input" }),
109
+ (error) => Object.hasOwn(error.fieldErrors || {}, "internalNote"), action.operation);
110
+ }
111
+ assert.equal((await knex("notes").where({ id: 1 }).first()).internal_note, "staff only");
112
+ });
113
+
114
+ // Notes, each by an author and with an editor, both authors; the authors table keeps a column no contract names.
115
+ async function createIncludeFixture(t, { authorOutput = "optional", authorsShow = { name: { output: "required" } } } = {}) {
116
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
117
+ t.after(() => knex.destroy());
118
+ await knex.schema.createTable("authors", (table) => {
119
+ table.increments("id");
120
+ table.string("name").notNullable();
121
+ table.string("secret_note");
122
+ });
123
+ await knex.schema.createTable("notes", (table) => {
124
+ table.increments("id");
125
+ table.string("title").notNullable();
126
+ table.integer("author_id");
127
+ table.integer("editor_id");
128
+ });
129
+ await knex("authors").insert([{ name: "Ada", secret_note: "private" }, { name: "Grace", secret_note: "private" }]);
130
+ await knex("notes").insert([{ title: "First", author_id: 1, editor_id: 2 }, { title: "Second", author_id: 1, editor_id: 2 }]);
131
+ const authors = defineTableResource({
132
+ name: "authors",
133
+ tableName: "authors",
134
+ ownership: "public",
135
+ schema: {
136
+ name: { type: "string", required: true },
137
+ secretNote: { type: "string", nullable: true, storage: { column: "secret_note" } }
138
+ }
139
+ });
140
+ const notes = defineTableResource({
141
+ name: "notes",
142
+ tableName: "notes",
143
+ ownership: "public",
144
+ schema: {
145
+ title: { type: "string", required: true },
146
+ authorId: { type: "id", nullable: true, lookup: "authors", storage: { column: "author_id" } },
147
+ editorId: { type: "id", nullable: true, lookup: "authors", storage: { column: "editor_id" } }
148
+ }
149
+ });
150
+ const runtime = await createTestResourceRuntime({ knex });
151
+ const resources = await runtime.own("test.notes", [notes, authors]);
152
+ // The notes contract names the author but not the editor. The authors table's own contract, served to another
153
+ // surface, shows more of each author than any include does.
154
+ const crud = defineCrudContract(notes, {
155
+ namespace: "notes",
156
+ operations: ["list", "view"],
157
+ fields: { title: { output: "required" }, authorId: { output: authorOutput } }
158
+ });
159
+ const contracts = createCrudContracts();
160
+ contracts.register(crud);
161
+ contracts.register(defineCrudContract(authors, { namespace: "authors", operations: ["list", "view"], fields: authorsShow }));
162
+ contracts.seal();
163
+ return createCrudService({ repository: resources.notes, crud });
164
+ }
165
+
166
+ test("a record a form saves back as the CRUD service showed it keeps its link to an author the writer cannot see", async (t) => {
167
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
168
+ t.after(() => knex.destroy());
169
+ await knex.schema.createTable("authors", (table) => {
170
+ table.increments("id");
171
+ table.string("name").notNullable();
172
+ table.boolean("retired").notNullable().defaultTo(false);
173
+ });
174
+ await knex.schema.createTable("notes", (table) => {
175
+ table.increments("id");
176
+ table.string("title").notNullable();
177
+ table.integer("author_id");
178
+ });
179
+ await knex("authors").insert([{ name: "Ada", retired: false }, { name: "Grace", retired: true }]);
180
+ await knex("notes").insert([{ title: "Draft", author_id: 2 }, { title: "Other", author_id: 2 }]);
181
+ const authors = defineTableResource({
182
+ name: "authors",
183
+ tableName: "authors",
184
+ ownership: "public",
185
+ schema: { name: { type: "string", required: true }, retired: { type: "boolean", defaultTo: false } }
186
+ });
187
+ const notes = defineTableResource({
188
+ name: "notes",
189
+ tableName: "notes",
190
+ ownership: "public",
191
+ schema: {
192
+ title: { type: "string", required: true },
193
+ authorId: { type: "id", nullable: true, lookup: "authors", storage: { column: "author_id" } }
194
+ }
195
+ });
196
+ const runtime = await createTestResourceRuntime({ knex });
197
+ // A request sees only authors still writing, so a retired author's link reads as null.
198
+ const resources = await runtime.own("test.notes", [notes, {
199
+ resource: authors,
200
+ rowPolicy: ({ query, column, caller }) => {
201
+ if (caller.kind !== "system") query.where(column("retired"), false);
202
+ return true;
203
+ }
204
+ }]);
205
+ const crud = defineCrudContract(notes, {
206
+ namespace: "notes",
207
+ operations: ["list", "view", "patch"],
208
+ fields: { title: { output: "required", patch: "optional" }, authorId: { output: "optional", patch: "optional" } }
209
+ });
210
+ const service = createCrudService({ repository: resources.notes, crud });
211
+ const authorOf = async (id) => (await knex("notes").where({ id }).first("author_id")).author_id;
212
+
213
+ const shown = simplifyJsonApiResult(await service.view("1", {}, {}));
214
+ assert.equal(shown.authorId, null);
215
+ await service.patch("1", { title: "Final", authorId: shown.authorId }, {});
216
+ assert.deepEqual(await knex("notes").where({ id: 1 }).first("title", "author_id"), { title: "Final", author_id: 2 });
217
+ // Linking an author the writer sees applies, and so does clearing that link.
218
+ await service.patch("2", { authorId: "1" }, {});
219
+ assert.equal(await authorOf(2), 1);
220
+ await service.patch("2", { authorId: null }, {});
221
+ assert.equal(await authorOf(2), null);
222
+ });
223
+
224
+ test("an included record shows only its id, and a relationship the contract does not name is left out", async (t) => {
225
+ const service = await createIncludeFixture(t, { authorsShow: { name: { output: "required" }, secretNote: { output: "optional" } } });
226
+ const page = await service.list({ include: "author,editor" }, {});
227
+ const view = await service.view("1", { include: "author,editor" }, {});
228
+ for (const document of [page.value, view.value]) {
229
+ const records = Array.isArray(document.data) ? document.data : [document.data];
230
+ for (const record of records) {
231
+ assert.deepEqual(Object.keys(record.attributes), ["title"]);
232
+ assert.deepEqual(Object.keys(record.relationships), ["author"]);
233
+ }
234
+ // Grace is only the editor, which the contract does not name, so she is not included at all. Ada shows nothing
235
+ // of the authors contract, which another surface serves with her secret note.
236
+ assert.deepEqual(document.included.map(({ type, id, attributes }) => [type, id, attributes]), [["authors", "1", {}]]);
237
+ }
238
+ });
239
+
240
+ test("an included record shows its lookup's label and the fields the including contract lists, never another contract's", async (t) => {
241
+ const authorsShow = { name: { output: "required" }, secretNote: { output: "optional" } };
242
+ const listed = await createIncludeFixture(t, { authorsShow, authorOutput: { required: false, includeFields: ["name"] } });
243
+ assert.deepEqual((await listed.view("1", { include: "author" }, {})).value.included.map(({ attributes }) => attributes), [{ name: "Ada" }]);
244
+ const labelled = await createIncludeFixture(t, { authorsShow, authorOutput: { required: false, relation: { kind: "lookup", namespace: "authors", valueKey: "id", labelKey: "name" } } });
245
+ assert.deepEqual((await labelled.view("1", { include: "author" }, {})).value.included.map(({ attributes }) => attributes), [{ name: "Ada" }]);
246
+ assert.throws(
247
+ () => createCrudService({ repository: {}, crud: defineCrudContract(defineTableResource({ name: "cards", tableName: "cards", ownership: "public", schema: { authorId: { type: "id", lookup: "authors" } } }), { namespace: "cards", operations: ["view"], fields: { authorId: { output: { includeFields: "name" } } } }) }),
248
+ /authorId\.includeFields must list the fields an included record shows/u
249
+ );
250
+ // The registry still keeps one contract per namespace.
251
+ const contracts = createCrudContracts();
252
+ const memos = defineTableResource({ name: "memos", tableName: "memos", ownership: "public", schema: { title: { type: "string", required: true } } });
253
+ const memosCrud = defineCrudContract(memos, { namespace: "memos", operations: ["list", "view"], fields: { title: { output: "required" } } });
254
+ contracts.register(memosCrud);
255
+ contracts.register(memosCrud);
256
+ assert.throws(
257
+ () => contracts.register(defineCrudContract(memos, { namespace: "memos", operations: ["list"], fields: { title: { output: "required" } } })),
258
+ /Two CRUD contracts are served under the namespace "memos"/u
259
+ );
260
+ });
261
+
262
+ test("an include shows the records it links to only as deep, and only with the fields, as the including contract lists", async (t) => {
263
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
264
+ t.after(() => knex.destroy());
265
+ await knex.schema.createTable("publishers", (table) => {
266
+ table.increments("id");
267
+ table.string("name").notNullable();
268
+ table.string("secret");
269
+ });
270
+ await knex.schema.createTable("authors", (table) => {
271
+ table.increments("id");
272
+ table.string("name").notNullable();
273
+ table.string("secret_note");
274
+ table.integer("publisher_id");
275
+ });
276
+ await knex.schema.createTable("notes", (table) => {
277
+ table.increments("id");
278
+ table.string("title").notNullable();
279
+ table.integer("author_id");
280
+ });
281
+ await knex("publishers").insert({ name: "Acme", secret: "private" });
282
+ await knex("authors").insert({ name: "Ada", secret_note: "private", publisher_id: 1 });
283
+ await knex("notes").insert({ title: "First", author_id: 1 });
284
+ const publishers = defineTableResource({
285
+ name: "publishers",
286
+ tableName: "publishers",
287
+ ownership: "public",
288
+ schema: { name: { type: "string", required: true }, secret: { type: "string", nullable: true } }
289
+ });
290
+ const authors = defineTableResource({
291
+ name: "authors",
292
+ tableName: "authors",
293
+ ownership: "public",
294
+ schema: {
295
+ name: { type: "string", required: true },
296
+ secretNote: { type: "string", nullable: true, storage: { column: "secret_note" } },
297
+ publisherId: { type: "id", nullable: true, lookup: "publishers", storage: { column: "publisher_id" } }
298
+ }
299
+ });
300
+ const notes = defineTableResource({
301
+ name: "notes",
302
+ tableName: "notes",
303
+ ownership: "public",
304
+ schema: { title: { type: "string", required: true }, authorId: { type: "id", nullable: true, lookup: "authors", storage: { column: "author_id" } } }
305
+ });
306
+ const runtime = await createTestResourceRuntime({ knex });
307
+ const resources = await runtime.own("test.notes", [notes, authors, publishers]);
308
+ const serve = (includeFields) => createCrudService({
309
+ repository: resources.notes,
310
+ crud: defineCrudContract(notes, { namespace: "notes", operations: ["view"], fields: { title: { output: "required" }, authorId: { output: { required: false, includeFields } } } })
311
+ });
312
+ const shown = async (includeFields) => (await serve(includeFields).view("1", { include: "author,author.publisher" }, {})).value.included
313
+ .map(({ type, attributes, relationships }) => [type, attributes, Object.keys(relationships ?? {})]);
314
+
315
+ assert.deepEqual(await shown(["name", { publisher: ["name"] }]), [["authors", { name: "Ada" }, ["publisher"]], ["publishers", { name: "Acme" }, []]]);
316
+ // A level-2 field shows only when the including contract lists it.
317
+ assert.deepEqual(await shown(["name", { publisher: ["name", "secret"] }]), [["authors", { name: "Ada" }, ["publisher"]], ["publishers", { name: "Acme", secret: "private" }, []]]);
318
+ // A nested record the contract does not list is not answered, and the link to it is left out.
319
+ assert.deepEqual(await shown(["name"]), [["authors", { name: "Ada" }, []]]);
320
+ assert.deepEqual(await shown([{ publisher: [] }]), [["authors", {}, ["publisher"]], ["publishers", {}, []]]);
321
+ for (const malformed of [[{ publisher: "name" }], [""], [{}]]) {
322
+ assert.throws(() => serve(malformed), /authorId\.includeFields(\.publisher)? must list the fields an included record shows/u);
323
+ }
324
+ });
325
+
326
+ test("the CRUD service answers documents, and 404 for a record that is missing or out of scope", async (t) => {
327
+ const { service } = await createFixture(t);
328
+ const page = await service.list({ title: "Note 7", fields: { notes: ["title"] } }, { context: WORKSPACE_ONE });
329
+ assert.deepEqual(page.value.data.map(({ id, attributes }) => [id, attributes]), [["7", { title: "Note 7" }]]);
330
+ assert.equal((await service.view("7", {}, { context: WORKSPACE_ONE })).value.data.attributes.title, "Note 7");
331
+ const otherWorkspace = Object.freeze({ scopeValues: Object.freeze({ workspaceId: "2" }) });
332
+ for (const run of [
333
+ () => service.view("7", {}, { context: otherWorkspace }),
334
+ () => service.patch("7", { title: "Taken" }, { context: otherWorkspace }),
335
+ () => service.view("999", {}, { context: WORKSPACE_ONE })
336
+ ]) {
337
+ await assert.rejects(run, { status: 404, code: "crud.document.notFound" });
338
+ }
339
+ assert.equal(await service.delete("999", { context: WORKSPACE_ONE }), null);
340
+ });
341
+
342
+ test("a repository decorator receives only the context, the transaction and the document format", async (t) => {
343
+ const { repository, audits, crud } = await createFixture(t);
344
+ const received = [];
345
+ // A decorator that also reads another table hands it only { context, trx }, so that read keeps its own rules.
346
+ const decorated = Object.freeze({
347
+ ...repository,
348
+ async get(id, params, options) {
349
+ received.push(Object.keys(options).sort());
350
+ await assert.rejects(audits.get("999", {}, passedOn(options)), (error) => error.code === "REST_API_RESOURCE" && error.subtype === "not_found");
351
+ return repository.get(id, params, options);
352
+ },
353
+ async delete(id, options) {
354
+ received.push(Object.keys(options).sort());
355
+ return repository.delete(id, options);
356
+ }
357
+ });
358
+ const service = createCrudService({ repository: decorated, crud });
359
+ assert.equal((await service.view("7", {}, { context: WORKSPACE_ONE })).value.data.attributes.title, "Note 7");
360
+ await assert.rejects(service.view("999", {}, { context: WORKSPACE_ONE }), { status: 404, code: "crud.document.notFound" });
361
+ assert.equal(await service.delete("999", { context: WORKSPACE_ONE }), null);
362
+ assert.equal(await service.delete("8", { context: WORKSPACE_ONE }), "8");
363
+ await repository.withTransaction({ context: WORKSPACE_ONE }, (txOptions) => service.view("7", {}, txOptions));
364
+ assert.deepEqual(received, [
365
+ ["context", "format"],
366
+ ["context", "format"],
367
+ ["context"],
368
+ ["context"],
369
+ ["context", "format", "trx"]
370
+ ]);
371
+ });
372
+
373
+ test("a mutation's hooks and its standard write share one transaction and roll back together", async (t) => {
374
+ const { knex, audits, actionsFor } = await createFixture(t);
375
+ const lifecycle = (fail) => ({
376
+ update: {
377
+ async after({ input, options }) {
378
+ await audits.create({ message: `Renamed ${input.recordId}` }, options);
379
+ if (fail) {
380
+ throw new Error("Abandon the rename");
381
+ }
382
+ }
383
+ }
384
+ });
385
+ const [update] = actionsFor({ operations: ["update"], operationLifecycle: lifecycle(true) });
386
+ await assert.rejects(update.execute({ recordId: "1", title: "Renamed" }, WORKSPACE_ONE), /Abandon the rename/u);
387
+ assert.equal((await knex("notes").where({ id: 1 }).first()).title, "Note 1");
388
+ assert.deepEqual(await knex("note_audits"), []);
389
+
390
+ const [kept] = actionsFor({ operations: ["update"], operationLifecycle: lifecycle(false) });
391
+ await kept.execute({ recordId: "1", title: "Renamed" }, WORKSPACE_ONE);
392
+ assert.equal((await knex("notes").where({ id: 1 }).first()).title, "Renamed");
393
+ assert.deepEqual(await knex("note_audits").pluck("message"), ["Renamed 1"]);
394
+ });
395
+
396
+ test("a failing CRUD afterCommit hook reports committed and leaves the actual write stored", async (t) => {
397
+ const { knex, actionsFor } = await createFixture(t);
398
+ const failure = Object.freeze(new Error("Notification failed"));
399
+ const [update] = actionsFor({
400
+ operations: ["update"],
401
+ operationLifecycle: { update: { afterCommit() { throw failure; } } }
402
+ });
403
+ await assert.rejects(
404
+ () => update.execute({ recordId: "1", title: "Kindred" }, WORKSPACE_ONE),
405
+ (error) => error.transactionOutcome === "committed" && error.cause === failure
406
+ );
407
+ assert.equal((await knex("notes").where({ id: 1 }).first()).title, "Kindred");
408
+ });
409
+
410
+ test("the CRUD service's writes are stamped with createdAt and updatedAt when the table stores them", async (t) => {
411
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
412
+ t.after(() => knex.destroy());
413
+ await knex.schema.createTable("memos", (table) => {
414
+ table.increments("id");
415
+ table.string("title").notNullable();
416
+ table.string("created_at").notNullable();
417
+ table.string("updated_at").notNullable();
418
+ });
419
+ const memos = defineTableResource({
420
+ name: "memos",
421
+ tableName: "memos",
422
+ ownership: "public",
423
+ schema: {
424
+ title: { type: "string", required: true },
425
+ createdAt: { type: "dateTime", storage: { column: "created_at", writeSerializer: "datetime-utc" } },
426
+ updatedAt: { type: "dateTime", storage: { column: "updated_at", writeSerializer: "datetime-utc" } }
427
+ }
428
+ });
429
+ const runtime = await createTestResourceRuntime({ knex });
430
+ const { memos: repository } = await runtime.own("test.memos", [memos]);
431
+ const service = createCrudService({
432
+ repository,
433
+ crud: defineCrudContract(memos, { namespace: "memos", fields: { title: { output: "required", create: "required", patch: "optional" } } })
434
+ });
435
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-08T01:02:03.000Z") });
436
+
437
+ const created = await service.create({ title: "First" }, {});
438
+ const id = created.value.data.id;
439
+ const stored = async () => knex("memos").where({ id }).first("created_at", "updated_at");
440
+ assert.deepEqual(await stored(), { created_at: "2026-11-08 01:02:03.000", updated_at: "2026-11-08 01:02:03.000" });
441
+
442
+ t.mock.timers.setTime(Date.parse("2026-11-08T05:06:07.000Z"));
443
+ await service.patch(id, { title: "Second" }, {});
444
+ assert.deepEqual(await stored(), { created_at: "2026-11-08 01:02:03.000", updated_at: "2026-11-08 05:06:07.000" });
445
+
446
+ // A request, which carries its context, cannot set them: a create body's createdAt and a patch body's updatedAt
447
+ // give way to the server's time.
448
+ const request = { context: {} };
449
+ const forged = await service.create({ title: "Forged", createdAt: "2020-01-02T03:04:05.000Z" }, request);
450
+ const forgedId = forged.value.data.id;
451
+ await service.patch(forgedId, { title: "Forged again", updatedAt: "2020-01-02T03:04:05.000Z" }, request);
452
+ assert.deepEqual(await knex("memos").where({ id: forgedId }).first("created_at", "updated_at"),
453
+ { created_at: "2026-11-08 05:06:07.000", updated_at: "2026-11-08 05:06:07.000" });
454
+ });