@jskit-ai/crud-core 0.2.65 → 0.2.67
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 CRUD list or view's sparse fieldset for its own records, named by the contract's namespace as its routes and the assistant's description name it (`fields[job_kinds]=name`), narrows them when the table resource's name is not the namespace in camelCase (`taskTypes` as `job_kinds`; jskit-ai#503). The service passed the namespace key on, and json-rest-api refused it with "Unknown resource type 'jobKinds' requested in sparse fields"; it now names that fieldset by the table resource.
|
|
6
|
+
- A CRUD action's documents carry the contract's namespace as their records' JSON:API type, as its HTTP routes answer it, whatever its table resource is named (jskit-ai#503). The CRUD service answered json-rest-api's documents, which type a record by its table resource's name, so a resource served under another namespace (`checklistTypes` as `checklist_types`) answered `checklistTypes` from its list, view, create and update actions; its HTTP routes still answered `checklist_types` because the response schema writes the type it declares. The assistant's result transform, which decodes the action's document as the routes answer it, then refused every such list and view (and create and update) with "Expected JSON:API resource type checklist_types, received checklistTypes.", a 500. The service now gives its own records the namespace as their type; a link and the included record it reaches keep the table resource's name, as the routes answer them, so a reader still pairs them.
|
|
5
7
|
- Each CRUD route names the action it runs (`actionId`, `crud.<namespace>.<operation>` or the custom action's id), so a signed-in CRUD route answers a caller without the action's permission 403 before validating the query, path or body, and before refusing an undeclared list query key (#497).
|
|
6
8
|
- Depends on json-rest-api 3.3.5 exactly (from 3.3.4), the version resource-runtime takes: a read validates and parses only what it must, and a patch answering nothing or its id, and a delete, read no stored row columns that nothing uses (details in `@jskit-ai/resource-runtime`'s changelog). No crud-core code changes.
|
|
7
9
|
- Depends on json-rest-api 3.3.4 exactly (from 3.3.3), the version resource-runtime takes: a write finds the relationships that reference its resource from an index built once per published schema (details in `@jskit-ai/resource-runtime`'s changelog). No crud-core code changes.
|
package/package.json
CHANGED
|
@@ -188,6 +188,11 @@ function contractShapes(crud) {
|
|
|
188
188
|
*/
|
|
189
189
|
function createCrudService({ repository, crud }) {
|
|
190
190
|
const resourceName = crud.resource.name;
|
|
191
|
+
// The JSON:API type of the contract's own records: its namespace, the API's public name, which its routes answer and
|
|
192
|
+
// every reader of its documents expects. json-rest-api types a record by its table resource's name, which a contract
|
|
193
|
+
// may serve under another namespace (checklistTypes as checklist_types). A link and the included record it reaches
|
|
194
|
+
// keep that name, so a reader still pairs them.
|
|
195
|
+
const recordType = crud.namespace;
|
|
191
196
|
const { own, linked: shapes } = contractShapes(crud);
|
|
192
197
|
|
|
193
198
|
/**
|
|
@@ -226,7 +231,8 @@ function createCrudService({ repository, crud }) {
|
|
|
226
231
|
if (!document?.data) {
|
|
227
232
|
return returnJsonApiDocument(document);
|
|
228
233
|
}
|
|
229
|
-
const records = (Array.isArray(document.data) ? document.data : [document.data])
|
|
234
|
+
const records = (Array.isArray(document.data) ? document.data : [document.data])
|
|
235
|
+
.map((record) => ({ ...shownRecord(record, own), type: recordType }));
|
|
230
236
|
const shown = { ...document, data: Array.isArray(document.data) ? records : records[0] };
|
|
231
237
|
if (document.included) {
|
|
232
238
|
const included = new Map(document.included.map((record) => [`${record.type}:${record.id}`, record]));
|
|
@@ -251,6 +257,21 @@ function createCrudService({ repository, crud }) {
|
|
|
251
257
|
return returnJsonApiDocument(shown);
|
|
252
258
|
}
|
|
253
259
|
|
|
260
|
+
/**
|
|
261
|
+
* The json-rest-api query params of an HTTP query. Its sparse fieldset for the contract's own records is named by their
|
|
262
|
+
* type, the namespace, and json-rest-api names them by the table resource, which a namespace need not spell
|
|
263
|
+
* (taskTypes as job_kinds).
|
|
264
|
+
* @param {Record<string, unknown>} query
|
|
265
|
+
*/
|
|
266
|
+
function queryParams(query) {
|
|
267
|
+
const fields = query?.fields;
|
|
268
|
+
if (recordType === resourceName || !isRecord(fields) || !Object.hasOwn(fields, recordType)) {
|
|
269
|
+
return buildJsonRestQueryParams(resourceName, query);
|
|
270
|
+
}
|
|
271
|
+
const { [recordType]: ownFields, ...linkedFields } = fields;
|
|
272
|
+
return buildJsonRestQueryParams(resourceName, { ...query, fields: { ...linkedFields, [resourceName]: ownFields } });
|
|
273
|
+
}
|
|
274
|
+
|
|
254
275
|
/**
|
|
255
276
|
* What the repository, or a decorator over it, receives: the caller's context and transaction, and the one setting
|
|
256
277
|
* the service names, JSON:API documents. A decorator passes only `{ context, trx }` on to another table.
|
|
@@ -267,7 +288,7 @@ function createCrudService({ repository, crud }) {
|
|
|
267
288
|
* @param {{ context?: object | null, trx?: object | null }} options
|
|
268
289
|
*/
|
|
269
290
|
async function list(query, options) {
|
|
270
|
-
return answer(await repository.query(
|
|
291
|
+
return answer(await repository.query(queryParams(query), documentOptions(options)));
|
|
271
292
|
}
|
|
272
293
|
|
|
273
294
|
/**
|
|
@@ -283,7 +304,7 @@ function createCrudService({ repository, crud }) {
|
|
|
283
304
|
);
|
|
284
305
|
}
|
|
285
306
|
try {
|
|
286
|
-
return answer(requireDocument(await repository.get(recordId,
|
|
307
|
+
return answer(requireDocument(await repository.get(recordId, queryParams(query), documentOptions(options))));
|
|
287
308
|
} catch (error) {
|
|
288
309
|
throw isNotFound(error, resourceName) ? documentNotFound() : error;
|
|
289
310
|
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import Fastify from "fastify";
|
|
4
|
+
import knexLib from "knex";
|
|
5
|
+
import { createServiceToolCatalog } from "@jskit-ai/assistant-core/server";
|
|
6
|
+
import { startTestFeatures } from "@jskit-ai/resource-runtime/test";
|
|
7
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
8
|
+
import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
|
|
9
|
+
import { createRouter } from "../../kernel/server/http/lib/router.js";
|
|
10
|
+
import { registerRoutes } from "../../kernel/server/http/lib/routeRegistration.js";
|
|
11
|
+
import { registerApiErrorHandler } from "../../kernel/server/http/errorHandling.js";
|
|
12
|
+
import { CrudContractsProvider } from "../src/server/crudContracts.js";
|
|
13
|
+
import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
|
|
14
|
+
|
|
15
|
+
// Tables named in camelCase, served under snake_case namespaces, as an application's checklist types and templates are:
|
|
16
|
+
// the namespace is the API's public name, and the JSON:API type its documents carry.
|
|
17
|
+
const checklistTypes = defineTableResource({
|
|
18
|
+
name: "checklistTypes",
|
|
19
|
+
tableName: "checklistTypes",
|
|
20
|
+
ownership: "public",
|
|
21
|
+
schema: {
|
|
22
|
+
name: { type: "string", required: true }
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
const checklistTemplates = defineTableResource({
|
|
26
|
+
name: "checklistTemplates",
|
|
27
|
+
tableName: "checklistTemplates",
|
|
28
|
+
ownership: "public",
|
|
29
|
+
schema: {
|
|
30
|
+
title: { type: "string", required: true },
|
|
31
|
+
checklistTypeId: { type: "id", nullable: true, lookup: "checklist_types", storage: { column: "checklist_type_id" } }
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
const checklistTypesContract = defineCrudContract(checklistTypes, {
|
|
35
|
+
namespace: "checklist_types",
|
|
36
|
+
apiAccess: "public",
|
|
37
|
+
fields: {
|
|
38
|
+
name: { output: "required", create: "required", patch: "optional" }
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
const checklistTemplatesContract = defineCrudContract(checklistTemplates, {
|
|
42
|
+
namespace: "checklist_templates",
|
|
43
|
+
apiAccess: "public",
|
|
44
|
+
operations: ["list", "view", "create", "patch"],
|
|
45
|
+
contract: { lookup: { containerKey: "lookups" } },
|
|
46
|
+
fields: {
|
|
47
|
+
title: { output: "required", create: "required", patch: "optional" },
|
|
48
|
+
checklistTypeId: { output: { required: false, includeFields: ["name"] }, create: "optional", patch: "optional" }
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
const API = Object.freeze({ channel: "api", surface: "home" });
|
|
52
|
+
|
|
53
|
+
async function startChecklists(t) {
|
|
54
|
+
const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
|
|
55
|
+
t.after(() => knex.destroy());
|
|
56
|
+
const router = createRouter();
|
|
57
|
+
const started = await startTestFeatures({
|
|
58
|
+
knex,
|
|
59
|
+
features: [
|
|
60
|
+
CrudContractsProvider,
|
|
61
|
+
defineCrudFeature({ crud: checklistTypesContract, surface: "home" }),
|
|
62
|
+
defineCrudFeature({ crud: checklistTemplatesContract, surface: "home" })
|
|
63
|
+
],
|
|
64
|
+
requires: { actions: "runtime.actions" },
|
|
65
|
+
inputs: { "runtime.http": { router } },
|
|
66
|
+
createTables: true
|
|
67
|
+
});
|
|
68
|
+
t.after(started.stop);
|
|
69
|
+
await knex("checklistTypes").insert([{ id: 1, name: "Safety" }, { id: 2, name: "Hygiene" }]);
|
|
70
|
+
await knex("checklistTemplates").insert({ id: 1, title: "Morning round", checklist_type_id: 1 });
|
|
71
|
+
const app = Fastify();
|
|
72
|
+
t.after(() => app.close());
|
|
73
|
+
registerApiErrorHandler(app);
|
|
74
|
+
registerRoutes(app, { routes: router.list(), actions: started.capabilities.actions });
|
|
75
|
+
const pathOf = (actionId) => router.list().find((route) => route.actionId === actionId).path;
|
|
76
|
+
return { actions: started.capabilities.actions, app, pathOf };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const byId = (left, right) => Number(left.id) - Number(right.id);
|
|
80
|
+
|
|
81
|
+
// The JSON:API type of each primary record a document carries.
|
|
82
|
+
function primaryTypes(document) {
|
|
83
|
+
return (Array.isArray(document.data) ? document.data : [document.data]).map(({ type }) => type);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
test("a CRUD action's documents carry its namespace as their JSON:API type, as its HTTP routes answer, whatever its table is named", async (t) => {
|
|
87
|
+
const { actions, app, pathOf } = await startChecklists(t);
|
|
88
|
+
const execute = async (actionId, input) => (await actions.execute({ actionId, input, context: API })).value;
|
|
89
|
+
|
|
90
|
+
// The HTTP routes answer the namespace.
|
|
91
|
+
const listed = await app.inject({ method: "GET", url: pathOf("crud.checklist_types.list") });
|
|
92
|
+
assert.equal(listed.statusCode, 200, listed.body);
|
|
93
|
+
assert.deepEqual(primaryTypes(listed.json()), ["checklist_types", "checklist_types"]);
|
|
94
|
+
|
|
95
|
+
// The actions the routes run answer the same type, for every operation that answers a document.
|
|
96
|
+
assert.deepEqual(primaryTypes(await execute("crud.checklist_types.list", {})), ["checklist_types", "checklist_types"]);
|
|
97
|
+
assert.deepEqual(primaryTypes(await execute("crud.checklist_types.view", { recordId: "1" })), ["checklist_types"]);
|
|
98
|
+
assert.deepEqual(primaryTypes(await execute("crud.checklist_types.create", { name: "Fire" })), ["checklist_types"]);
|
|
99
|
+
assert.deepEqual(primaryTypes(await execute("crud.checklist_types.update", { recordId: "3", name: "Fire drill" })), ["checklist_types"]);
|
|
100
|
+
|
|
101
|
+
// A record's link and the included record it reaches name the same type, in the action's document and over HTTP, so
|
|
102
|
+
// a reader finds the included record from the link.
|
|
103
|
+
const viewUrl = `${pathOf("crud.checklist_templates.view").replace(":recordId", "1")}?include=checklistType`;
|
|
104
|
+
const viewed = await app.inject({ method: "GET", url: viewUrl });
|
|
105
|
+
assert.equal(viewed.statusCode, 200, viewed.body);
|
|
106
|
+
for (const document of [viewed.json(), await execute("crud.checklist_templates.view", { recordId: "1", include: "checklistType" })]) {
|
|
107
|
+
assert.deepEqual(primaryTypes(document), ["checklist_templates"]);
|
|
108
|
+
const link = document.data.relationships.checklistType.data;
|
|
109
|
+
assert.deepEqual(document.included.map(({ type, id, attributes }) => ({ type, id, attributes })), [
|
|
110
|
+
{ type: link.type, id: link.id, attributes: { name: "Safety" } }
|
|
111
|
+
]);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("the assistant lists, views, creates, updates and deletes the records of a resource whose table is not named as its namespace", async (t) => {
|
|
116
|
+
const { actions } = await startChecklists(t);
|
|
117
|
+
const catalog = createServiceToolCatalog(actions, { maxDirectTools: 0 });
|
|
118
|
+
const context = { actor: { id: "7" }, surface: "home" };
|
|
119
|
+
const toolSet = catalog.resolveToolSet(context);
|
|
120
|
+
const call = (toolName, payload) => catalog.executeToolCall({ toolName, argumentsText: JSON.stringify(payload), context, toolSet });
|
|
121
|
+
async function run(actionId, input) {
|
|
122
|
+
const contract = await call("assistant_action_contract", { actionId, version: 1 });
|
|
123
|
+
assert.equal(contract.ok, true, JSON.stringify(contract));
|
|
124
|
+
const executed = await call("assistant_action_execute", { actionId, version: 1, input });
|
|
125
|
+
assert.equal(executed.ok, true, `${actionId}: ${JSON.stringify(executed)}`);
|
|
126
|
+
return executed.result.result;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
for (const input of [{ limit: 100 }, { fields: { checklist_types: ["name"] } }]) {
|
|
130
|
+
const listed = await run("crud.checklist_types.list", input);
|
|
131
|
+
assert.deepEqual({ ...listed, items: listed.items.toSorted(byId) }, {
|
|
132
|
+
items: [{ id: "1", name: "Safety" }, { id: "2", name: "Hygiene" }],
|
|
133
|
+
nextCursor: null
|
|
134
|
+
}, JSON.stringify(input));
|
|
135
|
+
}
|
|
136
|
+
assert.deepEqual(await run("crud.checklist_types.view", { recordId: "1" }), { id: "1", name: "Safety" });
|
|
137
|
+
const created = await run("crud.checklist_types.create", { name: "Fire" });
|
|
138
|
+
assert.equal(created.name, "Fire");
|
|
139
|
+
assert.deepEqual(await run("crud.checklist_types.update", { recordId: created.id, name: "Fire drill" }), {
|
|
140
|
+
id: created.id,
|
|
141
|
+
name: "Fire drill"
|
|
142
|
+
});
|
|
143
|
+
assert.deepEqual(await run("crud.checklist_types.delete", { recordId: created.id }), { id: created.id, deleted: true });
|
|
144
|
+
|
|
145
|
+
// A record's included link reaches the model as its lookup, in a list and in a view.
|
|
146
|
+
const listed = await run("crud.checklist_templates.list", { include: "checklistType" });
|
|
147
|
+
assert.equal(listed.items.length, 1);
|
|
148
|
+
for (const template of [listed.items[0], await run("crud.checklist_templates.view", { recordId: "1", include: "checklistType" })]) {
|
|
149
|
+
assert.equal(template.title, "Morning round");
|
|
150
|
+
assert.deepEqual(template.lookups.checklistType, { id: "1", name: "Safety" });
|
|
151
|
+
}
|
|
152
|
+
const moved = await run("crud.checklist_templates.update", { recordId: "1", checklistTypeId: "2" });
|
|
153
|
+
assert.equal(String(moved.checklistTypeId), "2");
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test("a sparse fieldset named by the namespace narrows the records of a resource whose name the namespace does not spell", async (t) => {
|
|
157
|
+
const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
|
|
158
|
+
t.after(() => knex.destroy());
|
|
159
|
+
const taskTypes = defineTableResource({
|
|
160
|
+
name: "taskTypes",
|
|
161
|
+
tableName: "taskTypes",
|
|
162
|
+
ownership: "public",
|
|
163
|
+
schema: { name: { type: "string", required: true }, code: { type: "string", nullable: true } }
|
|
164
|
+
});
|
|
165
|
+
const jobKinds = defineCrudContract(taskTypes, {
|
|
166
|
+
namespace: "job_kinds",
|
|
167
|
+
apiAccess: "public",
|
|
168
|
+
operations: ["list", "view"],
|
|
169
|
+
fields: { name: { output: "required" }, code: { output: { required: false } } }
|
|
170
|
+
});
|
|
171
|
+
const router = createRouter();
|
|
172
|
+
const started = await startTestFeatures({
|
|
173
|
+
knex,
|
|
174
|
+
features: [CrudContractsProvider, defineCrudFeature({ crud: jobKinds, surface: "home" })],
|
|
175
|
+
requires: { actions: "runtime.actions" },
|
|
176
|
+
inputs: { "runtime.http": { router } },
|
|
177
|
+
createTables: true
|
|
178
|
+
});
|
|
179
|
+
t.after(started.stop);
|
|
180
|
+
await knex("taskTypes").insert({ id: 1, name: "Inspection", code: "INS" });
|
|
181
|
+
const { actions } = started.capabilities;
|
|
182
|
+
|
|
183
|
+
for (const [actionId, input] of [["crud.job_kinds.list", {}], ["crud.job_kinds.view", { recordId: "1" }]]) {
|
|
184
|
+
const document = (await actions.execute({ actionId, input: { ...input, fields: { job_kinds: ["name"] } }, context: API })).value;
|
|
185
|
+
const [record] = Array.isArray(document.data) ? document.data : [document.data];
|
|
186
|
+
assert.deepEqual({ type: record.type, attributes: record.attributes }, { type: "job_kinds", attributes: { name: "Inspection" } }, actionId);
|
|
187
|
+
}
|
|
188
|
+
});
|
|
@@ -73,7 +73,8 @@ async function startFeatures(context, features) {
|
|
|
73
73
|
function toolActionIds(actions, permissions) {
|
|
74
74
|
const catalog = createServiceToolCatalog(actions, { maxDirectTools: 100 });
|
|
75
75
|
const toolSet = catalog.resolveToolSet({ actor: { id: "7" }, permissions, surface: "home" });
|
|
76
|
-
|
|
76
|
+
// The ids of the actions the tools reach: the tool that reads on in a long result reaches none.
|
|
77
|
+
return toolSet.tools.filter((tool) => tool.actionId).map((tool) => tool.actionId).sort();
|
|
77
78
|
}
|
|
78
79
|
|
|
79
80
|
test("the assistant reaches a CRUD action without HTTP routes only when a permission guards it", async (context) => {
|