@jskit-ai/crud-core 0.2.51 → 0.2.53

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/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A generated delete tells an assistant client it is destructive (`extensions.assistant.destructive: true`); list, view, create and update are not. `defineCrudFeature` takes `assistantHints`, such as `{ update: { destructive: true } }`, to add `destructive` or `sendsOutside` to its generated create, update or delete; a hint for another operation, or one that is not `true` or `false`, stops the server naming it. A custom action without an assistant description is described by its route's `summary`, so an MCP client reads what the route says it does.
6
+ - Depends on json-rest-api 3.3.3 exactly (from 3.3.2), the version resource-runtime takes: on a descending sort, rows tied on its last key come in descending id order (the id that breaks ties takes the last key's direction), so MySQL and MariaDB read a descending page from an index leading with that key instead of sorting every row, and leave out the `IS NULL` term where the server already places NULLs last; and capabilities a start could not observe (the server not up yet) are observed again on the next storage call until that succeeds.
5
7
  - Depends on json-rest-api 3.3.2 exactly (from 3.3.1), the version resource-runtime takes: on MariaDB a locking read keeps each IN list below the server's `in_predicate_conversion_threshold`, so a lock of 1,000 ids or values or more holds the rows it names alone, and a write's lock of the records it links to reads their primary key (details in `@jskit-ai/resource-runtime`'s changelog).
6
8
  - Depends on json-rest-api 3.3.1 exactly (from 3.3.0), the version resource-runtime takes: a lock's to-one link check reads the linked table through its primary key on MySQL and MariaDB and holds the linked rows alone (details in `@jskit-ai/resource-runtime`'s changelog). No crud-core code changes.
7
9
  - Depends on json-rest-api 3.3.0 exactly (from 3.2.0), the version resource-runtime takes: its change adds a locking aggregate (`aggregate` with `lockMode` inside a transaction; details in `@jskit-ai/resource-runtime`'s changelog) and names the fix in the single-table refusal of a lock, neither of which a CRUD route reaches, so a CRUD route reads and writes as it did.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/crud-core",
3
- "version": "0.2.51",
3
+ "version": "0.2.53",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -20,9 +20,9 @@
20
20
  "./locales/en.json": "./locales/en.json"
21
21
  },
22
22
  "dependencies": {
23
- "@jskit-ai/resource-core": "0.1.224",
24
- "@jskit-ai/resource-crud-core": "0.1.226",
25
- "json-rest-api": "3.3.2",
23
+ "@jskit-ai/resource-core": "0.1.225",
24
+ "@jskit-ai/resource-crud-core": "0.1.227",
25
+ "json-rest-api": "3.3.3",
26
26
  "json-rest-schema": "^1.0.20"
27
27
  },
28
28
  "description": "Shared server-side CRUD service, repository, route, and query helpers.",
@@ -49,8 +49,8 @@
49
49
  }
50
50
  },
51
51
  "peerDependencies": {
52
- "@jskit-ai/http-runtime": "0.2.33",
53
- "@jskit-ai/kernel": "0.2.33",
54
- "@jskit-ai/resource-runtime": "0.2.47"
52
+ "@jskit-ai/http-runtime": "0.2.35",
53
+ "@jskit-ai/kernel": "0.2.34",
54
+ "@jskit-ai/resource-runtime": "0.2.49"
55
55
  }
56
56
  }
@@ -9,9 +9,9 @@
9
9
  "./shared": "./src/shared/index.js"
10
10
  },
11
11
  "dependencies": {
12
- "@jskit-ai/crud-core": "0.2.51",
13
- "@jskit-ai/resource-core": "0.1.224",
14
- "@jskit-ai/resource-crud-core": "0.1.226"
12
+ "@jskit-ai/crud-core": "0.2.53",
13
+ "@jskit-ai/resource-core": "0.1.225",
14
+ "@jskit-ai/resource-crud-core": "0.1.227"
15
15
  },
16
16
  "jskit": {
17
17
  "kind": "runtime",
@@ -58,6 +58,7 @@ const FEATURE_OPTIONS = new Set([
58
58
  "internal",
59
59
  "routes",
60
60
  "listFilterQueryValidator",
61
+ "assistantHints",
61
62
  "permissions",
62
63
  "scope",
63
64
  "requires",
@@ -351,6 +352,9 @@ function projectEnabledServiceOperations(service, operations) {
351
352
  * @param {object} [feature.actions] Custom actions, by name.
352
353
  * @param {string[]} [feature.operations] Defaults to every operation the CRUD contract offers.
353
354
  * @param {string} [feature.realtimeAudience] Defaults to "event_scope".
355
+ * @param {Record<string, { destructive?: boolean, sendsOutside?: boolean }>} [feature.assistantHints] What an assistant
356
+ * client is told about the feature's generated create, update or delete beyond the defaults (a delete is
357
+ * destructive), such as `{ update: { destructive: true } }` for a table whose every edit it should ask about first.
354
358
  */
355
359
  function defineCrudFeature(feature) {
356
360
  assertKnownOptions(feature);
@@ -376,7 +380,8 @@ function defineCrudFeature(feature) {
376
380
  operationInputs = {},
377
381
  actions = {},
378
382
  operations = undefined,
379
- realtimeAudience = "event_scope"
383
+ realtimeAudience = "event_scope",
384
+ assistantHints = undefined
380
385
  } = feature;
381
386
  if (!isCrudContract(crud)) {
382
387
  throw new TypeError("defineCrudFeature requires crud, a CRUD contract from defineCrudContract.");
@@ -463,7 +468,8 @@ function defineCrudFeature(feature) {
463
468
  permissions: permissionOptions
464
469
  }),
465
470
  scopeInputValidator: normalizedScope.actionInputValidator,
466
- servedOverHttp
471
+ servedOverHttp,
472
+ assistantHints
467
473
  }));
468
474
 
469
475
  return defineFeature({
@@ -18,6 +18,8 @@ import { buildCrudCustomActionId } from "./customActionId.js";
18
18
  import { withRemovedProperties } from "../removedApi.js";
19
19
 
20
20
  const CRUD_OPERATION_NAMES = Object.freeze(["list", "view", "create", "update", "delete"]);
21
+ const HINTED_OPERATION_NAMES = Object.freeze(["create", "update", "delete"]);
22
+ const ASSISTANT_HINT_NAMES = Object.freeze(["destructive", "sendsOutside"]);
21
23
  const CRUD_MUTATION_NAMES = new Set(["create", "update", "delete"]);
22
24
  const CRUD_LIFECYCLE_PHASES = Object.freeze(["before", "execute", "after", "afterCommit"]);
23
25
  const SERVED_ACTION_CHANNELS = Object.freeze(["api", "automation", "internal"]);
@@ -121,6 +123,21 @@ function buildLifecycleContext(value) {
121
123
  }, REMOVED_LIFECYCLE_PROPERTIES, "A CRUD lifecycle hook's argument"));
122
124
  }
123
125
 
126
+ /**
127
+ * A custom action's extensions, its assistant description taken from its route's summary when it declares none, so a
128
+ * client reading the action's tools reads what its route says it does; undefined when it has neither.
129
+ * @param {{ extensions?: object, route?: { summary?: string } }} definition
130
+ */
131
+ function withRouteSummary(definition) {
132
+ const summary = typeof definition.route?.summary === "string" ? definition.route.summary.trim() : "";
133
+ const assistant = isRecord(definition.extensions?.assistant) ? definition.extensions.assistant : null;
134
+ if (!summary || assistant?.description) return definition.extensions;
135
+ return Object.freeze({
136
+ ...definition.extensions,
137
+ assistant: Object.freeze({ ...assistant, description: summary })
138
+ });
139
+ }
140
+
124
141
  function normalizeAdditionalActions(definitions, { namespace, surface, permissionForAction, scopeInputValidator, servedOverHttp }) {
125
142
  return Object.freeze(Object.entries(definitions).map(([name, definition]) => {
126
143
  const actionName = String(name || "").trim();
@@ -149,8 +166,10 @@ function normalizeAdditionalActions(definitions, { namespace, surface, permissio
149
166
 
150
167
  const kind = definition.kind || "command";
151
168
  const permission = definition.permission || permissionForAction(actionName);
169
+ const extensions = withRouteSummary(definition);
152
170
  return Object.freeze({
153
171
  ...definition,
172
+ ...(extensions ? { extensions } : {}),
154
173
  name: actionName,
155
174
  id: buildCrudCustomActionId(namespace, actionName, definition),
156
175
  version: definition.version || 1,
@@ -168,6 +187,34 @@ function normalizeAdditionalActions(definitions, { namespace, surface, permissio
168
187
  }));
169
188
  }
170
189
 
190
+ /**
191
+ * The hints a feature declares for its generated changes, such as `{ update: { destructive: true } }` for a table
192
+ * whose every edit a client should ask about first; each is laid over the generated action's own.
193
+ * @param {unknown} hints
194
+ * @param {readonly string[]} operations The feature's enabled operations.
195
+ * @returns {Record<string, Readonly<{ destructive?: boolean, sendsOutside?: boolean }>>}
196
+ */
197
+ function normalizeOperationAssistantHints(hints, operations) {
198
+ if (hints === undefined || hints === null) return {};
199
+ if (typeof hints !== "object" || Array.isArray(hints)) {
200
+ throw new TypeError("defineCrudFeature assistantHints maps create, update or delete to { destructive?, sendsOutside? }.");
201
+ }
202
+ return Object.fromEntries(Object.entries(hints).map(([operation, declared]) => {
203
+ if (!HINTED_OPERATION_NAMES.includes(operation) || !operations.includes(operation)) {
204
+ throw new TypeError(`defineCrudFeature assistantHints.${operation}: hints are for the feature's own create, update or delete.`);
205
+ }
206
+ if (!declared || typeof declared !== "object" || Array.isArray(declared)) {
207
+ throw new TypeError(`defineCrudFeature assistantHints.${operation} must be { destructive?, sendsOutside? }.`);
208
+ }
209
+ for (const [name, value] of Object.entries(declared)) {
210
+ if (!ASSISTANT_HINT_NAMES.includes(name) || typeof value !== "boolean") {
211
+ throw new TypeError(`defineCrudFeature assistantHints.${operation}.${name}: a hint is destructive or sendsOutside, true or false.`);
212
+ }
213
+ }
214
+ return [operation, Object.freeze({ ...declared })];
215
+ }));
216
+ }
217
+
171
218
  /**
172
219
  * What a CRUD feature's actions take from its definition alone, so a feature builds it once and every composition
173
220
  * reuses it: each enabled standard operation's id, channels, permission, input and assistant extension, and the
@@ -183,6 +230,8 @@ function normalizeAdditionalActions(definitions, { namespace, surface, permissio
183
230
  * @param {{ create?: object, update?: object }} definition.operationInputs
184
231
  * @param {Record<string, object>} definition.actions The feature's custom actions, by name.
185
232
  * @param {boolean} definition.servedOverHttp False when the feature is internal or registers no routes.
233
+ * @param {Record<string, { destructive?: boolean, sendsOutside?: boolean }>} [definition.assistantHints] Hints for its
234
+ * generated create, update or delete.
186
235
  */
187
236
  function createCrudJsonApiActionDefinitions({
188
237
  namespace,
@@ -194,8 +243,10 @@ function createCrudJsonApiActionDefinitions({
194
243
  listFilterQueryValidator,
195
244
  operationInputs,
196
245
  actions,
197
- servedOverHttp
246
+ servedOverHttp,
247
+ assistantHints = undefined
198
248
  }) {
249
+ const operationHints = normalizeOperationAssistantHints(assistantHints, operations);
199
250
  const additional = normalizeAdditionalActions(actions, {
200
251
  namespace,
201
252
  surface,
@@ -214,7 +265,7 @@ function createCrudJsonApiActionDefinitions({
214
265
  permission,
215
266
  input: buildActionInput(resource, operation, scopeInputValidator, listFilterQueryValidator, operationInputs),
216
267
  extensions: Object.freeze({
217
- assistant: createCrudAssistantExtension(resource, namespace, operation)
268
+ assistant: Object.freeze({ ...createCrudAssistantExtension(resource, namespace, operation), ...operationHints[operation] })
218
269
  })
219
270
  });
220
271
  });
@@ -376,6 +376,8 @@ function createCrudAssistantExtension(resource, namespace, operation) {
376
376
 
377
377
  return Object.freeze({
378
378
  description: actionLabel,
379
+ // A delete is the one generated operation a client asks about as destructive: a record it removes is gone.
380
+ destructive: operation === "delete",
379
381
  output,
380
382
  transformResult
381
383
  });
@@ -0,0 +1,81 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createSchema } from "@jskit-ai/kernel/shared/validators";
4
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
5
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
6
+ import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
7
+ import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
8
+
9
+ // What an assistant or a remote client reads about each generated action: a delete says it is destructive, a feature's
10
+ // assistantHints add to its generated changes, and a custom action without a description of its own is described by
11
+ // its route's summary.
12
+
13
+ const notes = defineTableResource({
14
+ name: "notes",
15
+ tableName: "notes",
16
+ ownership: "workspace",
17
+ schema: { workspaceId: { type: "id", storage: { column: "workspace_id" } }, title: { type: "string", required: true } }
18
+ });
19
+ const crud = defineCrudContract(notes, {
20
+ namespace: "notes",
21
+ fields: { title: { output: "required", create: "required", patch: "optional" } }
22
+ });
23
+ const orderInput = Object.freeze({ schema: createSchema({ orderedIds: { type: "array", required: true, items: { type: "id" } } }), mode: "create" });
24
+
25
+ function definitionsWith(actions, options = {}) {
26
+ const definitions = createCrudJsonApiActions(crudJsonApiActionOptions({
27
+ namespace: "notes",
28
+ resource: crud,
29
+ service: {},
30
+ surface: "admin",
31
+ permissionForOperation: () => ({ require: "authenticated" }),
32
+ actions,
33
+ ...options
34
+ }));
35
+ return new Map(definitions.map((definition) => [definition.id, definition]));
36
+ }
37
+
38
+ test("a generated delete is marked destructive and no other generated operation is", () => {
39
+ const byId = definitionsWith({});
40
+ assert.equal(byId.get("crud.notes.delete").extensions.assistant.destructive, true);
41
+ for (const operation of ["list", "view", "create", "update"]) {
42
+ assert.equal(byId.get(`crud.notes.${operation}`).extensions.assistant.destructive, false, operation);
43
+ }
44
+ });
45
+
46
+ test("a feature's assistantHints mark its generated changes, and a hint it cannot have stops it", () => {
47
+ const byId = definitionsWith({}, { assistantHints: { create: { sendsOutside: true }, update: { destructive: true } } });
48
+ assert.equal(byId.get("crud.notes.update").extensions.assistant.destructive, true);
49
+ assert.equal(byId.get("crud.notes.create").extensions.assistant.sendsOutside, true);
50
+ assert.equal(byId.get("crud.notes.create").extensions.assistant.destructive, false);
51
+ assert.equal(byId.get("crud.notes.update").extensions.assistant.description, "Update a notes record.", "the generated extension stays");
52
+ assert.equal(typeof byId.get("crud.notes.update").extensions.assistant.transformResult, "function");
53
+ for (const [hints, pattern] of [
54
+ [[], /assistantHints maps create, update or delete/u],
55
+ [{ list: { destructive: true } }, /assistantHints\.list: hints are for the feature's own create, update or delete/u],
56
+ [{ update: true }, /assistantHints\.update must be/u],
57
+ [{ update: { destructive: "yes" } }, /assistantHints\.update\.destructive: a hint is destructive or sendsOutside, true or false/u],
58
+ [{ update: { readOnly: true } }, /assistantHints\.update\.readOnly/u]
59
+ ]) {
60
+ assert.throws(() => definitionsWith({}, { assistantHints: hints }), pattern, JSON.stringify(hints));
61
+ }
62
+ assert.throws(() => definitionsWith({}, { operations: ["list", "view"], assistantHints: { update: { destructive: true } } }),
63
+ /assistantHints\.update: hints are for the feature's own/u, "an operation the feature does not have");
64
+ });
65
+
66
+ test("a custom action is described by its route's summary unless it describes itself, and keeps its own hints", () => {
67
+ const route = (summary) => ({ method: "POST", path: "/reorder", contract: { body: orderInput }, statusCode: 200, summary });
68
+ const byId = definitionsWith({
69
+ reorder: { input: orderInput, execute: async () => ({}), route: route("Persist the complete note order.") },
70
+ archive: {
71
+ input: orderInput,
72
+ execute: async () => ({}),
73
+ route: route("Archive notes."),
74
+ extensions: { assistant: { description: "Archive the given notes for good.", destructive: true } }
75
+ },
76
+ tidy: { input: orderInput, execute: async () => ({}) }
77
+ });
78
+ assert.equal(byId.get("crud.notes.reorder").extensions.assistant.description, "Persist the complete note order.");
79
+ assert.deepEqual(byId.get("crud.notes.archive").extensions.assistant, { description: "Archive the given notes for good.", destructive: true });
80
+ assert.equal(byId.get("crud.notes.tidy").extensions.assistant, undefined, "without a route or description it says nothing");
81
+ });
@@ -87,7 +87,7 @@ test("assistant list traverses real SQL pages with sparse fields and capped limi
87
87
  const expectedIds = await knex("books")
88
88
  .where("workspace_id", 1)
89
89
  .orderBy("created_at", "desc")
90
- .orderBy("id", "asc")
90
+ .orderBy("id", "desc")
91
91
  .pluck("id");
92
92
 
93
93
  for (const limit of [100, 200]) {
@@ -4,7 +4,7 @@ import test from "node:test";
4
4
  import { createPackageTestKnex, createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
5
5
  import { bookCrud, bookResource } from "../patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js";
6
6
 
7
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
7
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
8
8
  const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
9
9
 
10
10
  const providerPath = new URL(
@@ -13,7 +13,7 @@ import { CrudContractsProvider, createCrudContracts } from "../src/server/crudCo
13
13
  import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
14
14
  import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
15
15
 
16
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
16
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
17
17
  const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
18
18
 
19
19
  const WORKSPACE_ONE = Object.freeze({ scopeValues: Object.freeze({ workspaceId: "1" }) });
@@ -6,7 +6,7 @@ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudCont
6
6
  import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
7
7
  import { CrudContractsProvider } from "../src/server/crudContracts.js";
8
8
 
9
- // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
9
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
10
10
  const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
11
11
 
12
12
  test("a CRUD feature's repository reads a hidden field of its table only in a system context; its owner's methods read it", async (t) => {