@jskit-ai/crud-core 0.2.25 → 0.2.27

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.
@@ -0,0 +1,238 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import Fastify from "fastify";
4
+ import { catalogMessage, formatMessage, messageKeyForCode, mergeCatalogs } from "@jskit-ai/kernel/shared/i18n";
5
+ import kernelEnglish from "@jskit-ai/kernel/locales/en.json" with { type: "json" };
6
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
7
+ import { createPackageTestKnex, startTestFeatures } 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 { createRouter } from "../../kernel/server/http/lib/router.js";
11
+ import { registerRoutes } from "../../kernel/server/http/lib/routeRegistration.js";
12
+ import { registerApiErrorHandler } from "../../kernel/server/http/errorHandling.js";
13
+ import crudEnglish from "../locales/en.json" with { type: "json" };
14
+ import { CrudContractsProvider } from "../src/server/crudContracts.js";
15
+ import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
16
+
17
+ const english = mergeCatalogs(kernelEnglish, crudEnglish);
18
+ const API = Object.freeze({ channel: "api", surface: "home" });
19
+ const INCLUDE = "customer,customer.region";
20
+
21
+ // orders -> customer (customers) -> region (regions), two levels deep; no include reaches tags.
22
+ const regions = defineTableResource({
23
+ name: "regions",
24
+ tableName: "regions",
25
+ ownership: "public",
26
+ schema: {
27
+ name: { type: "string", required: true },
28
+ code: { type: "string", nullable: true },
29
+ secret: { type: "string", nullable: true }
30
+ }
31
+ });
32
+ const customers = defineTableResource({
33
+ name: "customers",
34
+ tableName: "customers",
35
+ ownership: "public",
36
+ schema: {
37
+ name: { type: "string", required: true },
38
+ regionId: { type: "id", nullable: true, lookup: "regions", storage: { column: "region_id" } }
39
+ }
40
+ });
41
+ const tags = defineTableResource({
42
+ name: "tags",
43
+ tableName: "tags",
44
+ ownership: "public",
45
+ schema: { label: { type: "string", required: true } }
46
+ });
47
+ const orders = defineTableResource({
48
+ name: "orders",
49
+ tableName: "orders",
50
+ ownership: "public",
51
+ schema: {
52
+ reference: { type: "string", required: true },
53
+ customerId: { type: "id", nullable: true, lookup: "customers", storage: { column: "customer_id" } }
54
+ }
55
+ });
56
+ const ordersContract = defineCrudContract(orders, {
57
+ namespace: "orders",
58
+ apiAccess: "public",
59
+ operations: ["list", "view"],
60
+ fields: {
61
+ reference: { output: "required" },
62
+ customerId: { output: { required: false, includeFields: ["name", { region: ["name", "code"] }] } }
63
+ }
64
+ });
65
+ // invoices -> customer (customers), one level: nothing to defer, so the list's input schema judges every fieldset key.
66
+ const invoices = defineTableResource({
67
+ name: "invoices",
68
+ tableName: "invoices",
69
+ ownership: "public",
70
+ schema: {
71
+ number: { type: "string", required: true },
72
+ customerId: { type: "id", nullable: true, lookup: "customers", storage: { column: "customer_id" } }
73
+ }
74
+ });
75
+ const invoicesContract = defineCrudContract(invoices, {
76
+ namespace: "invoices",
77
+ apiAccess: "public",
78
+ operations: ["list", "view"],
79
+ fields: {
80
+ number: { output: "required" },
81
+ customerId: { output: { required: false, includeFields: ["name"] } }
82
+ }
83
+ });
84
+
85
+ // The orders and invoices features serve their records; another feature owns the tables their includes reach.
86
+ async function startOrders(t) {
87
+ const knex = await createPackageTestKnex(t, { environment: process.env });
88
+ const router = createRouter();
89
+ const started = await startTestFeatures({
90
+ knex,
91
+ features: [
92
+ CrudContractsProvider,
93
+ defineFeature({ id: "test.customers", owns: [customers, regions, tags], setup: () => ({}) }),
94
+ defineCrudFeature({ crud: ordersContract, surface: "home" }),
95
+ defineCrudFeature({ crud: invoicesContract, surface: "home" })
96
+ ],
97
+ requires: { actions: "runtime.actions" },
98
+ inputs: { "runtime.http": { router } },
99
+ createTables: true
100
+ });
101
+ t.after(started.stop);
102
+ await knex("regions").insert({ name: "North", code: "N", secret: "private" });
103
+ await knex("customers").insert({ name: "Acme", region_id: 1 });
104
+ await knex("tags").insert({ label: "Urgent" });
105
+ await knex("orders").insert({ reference: "A-1", customer_id: 1 });
106
+ await knex("invoices").insert({ number: "INV-1", customer_id: 1 });
107
+ return { actions: started.capabilities.actions, router };
108
+ }
109
+
110
+ function includedOf(document) {
111
+ return document.included
112
+ .map(({ type, attributes }) => [type, attributes])
113
+ .sort(([left], [right]) => left.localeCompare(right));
114
+ }
115
+
116
+ // The client translates a code only when the server's English is the catalog's English for it, with its params.
117
+ function assertCatalogRenders({ code, params }, sentEnglish) {
118
+ assert.equal(formatMessage(catalogMessage(english, messageKeyForCode(code)), params), sentEnglish, code);
119
+ }
120
+
121
+ test("a list or view narrows a record its include reaches two levels down with fields[<type>], to fields the include shows", async (t) => {
122
+ const { actions } = await startOrders(t);
123
+ const read = (actionId, fields, input = {}) => actions.execute({
124
+ actionId,
125
+ input: { ...input, include: INCLUDE, ...(fields ? { fields } : {}) },
126
+ context: API
127
+ });
128
+
129
+ // The include shows the region's name and code; fields[regions] narrows the region, in a list and in a view.
130
+ assert.deepEqual(includedOf((await read("crud.orders.list")).value), [
131
+ ["customers", { name: "Acme" }],
132
+ ["regions", { name: "North", code: "N" }]
133
+ ]);
134
+ for (const [actionId, input] of [["crud.orders.list", {}], ["crud.orders.view", { recordId: "1" }]]) {
135
+ assert.deepEqual(includedOf((await read(actionId, { regions: ["name"] }, input)).value), [
136
+ ["customers", { name: "Acme" }],
137
+ ["regions", { name: "North" }]
138
+ ], actionId);
139
+ }
140
+
141
+ // A field the include does not show, and a type no include reaches, stay refused.
142
+ for (const [fields, code, english] of [
143
+ [{ regions: ["secret"] }, "crud.query.fieldsNotShown", /^fields\[regions\] may name only what this read's includes show of regions: name, code\. It names secret\.$/u],
144
+ [{ tags: ["label"] }, "crud.query.fieldsKeysInvalidWithAliases", /Allowed keys: "orders", "customers", "regions"\./u]
145
+ ]) {
146
+ const [field] = Object.keys(fields).map((type) => `fields.${type}`);
147
+ await assert.rejects(read("crud.orders.list", fields), (error) => {
148
+ assert.equal(error.status, 400);
149
+ assert.equal(error.details.fieldErrorCodes[field].code, code);
150
+ assert.match(error.details.fieldErrors[field], english);
151
+ assertCatalogRenders(error.details.fieldErrorCodes[field], error.details.fieldErrors[field]);
152
+ return true;
153
+ });
154
+ }
155
+ });
156
+
157
+ test("over HTTP, fields[<type>] narrows a record two include levels down and refuses unshown fields and unreached types", async (t) => {
158
+ const { actions, router } = await startOrders(t);
159
+ const app = Fastify();
160
+ t.after(() => app.close());
161
+ registerApiErrorHandler(app);
162
+ registerRoutes(app, { routes: router.list(), actions });
163
+ const { path } = router.list().find((route) => route.method === "GET" && route.path.endsWith("/orders"));
164
+ const get = (query) => app.inject({ method: "GET", url: `${path}?include=${INCLUDE}&${query}` });
165
+
166
+ const narrowed = await get("fields%5Bregions%5D=name");
167
+ assert.equal(narrowed.statusCode, 200, narrowed.body);
168
+ assert.deepEqual(includedOf(narrowed.json()), [["customers", { name: "Acme" }], ["regions", { name: "North" }]]);
169
+
170
+ for (const [query, code] of [
171
+ ["fields%5Bregions%5D=secret", "crud.query.fieldsNotShown"],
172
+ ["fields%5Btags%5D=label", "crud.query.fieldsKeysInvalidWithAliases"]
173
+ ]) {
174
+ const response = await get(query);
175
+ assert.equal(response.statusCode, 400, `${query}: ${response.body}`);
176
+ assert.ok(response.body.includes(`"${code}"`), `${query}: ${response.body}`);
177
+ }
178
+ });
179
+
180
+ // The list action's input schema refuses a bad key of a contract whose includes stop at their first level; the check
181
+ // the action runs refuses it for one whose includes reach further. A client or an assistant tool reads both alike.
182
+ const BAD_KEYS = Object.freeze([
183
+ [{ customer: ["name"] }, "fields.customer"],
184
+ [{ nosuch: ["name"] }, "fields.nosuch"]
185
+ ]);
186
+
187
+ test("a fieldset keyed by a relationship alias or by no type is refused as the action input refuses one, whether the includes reach nested types or not", async (t) => {
188
+ const { actions } = await startOrders(t);
189
+ const refusal = (actionId, fields) => actions.execute({ actionId, input: { include: "customer", fields }, context: API }).then(
190
+ () => assert.fail(`${actionId} took fields ${JSON.stringify(fields)}`),
191
+ (error) => error
192
+ );
193
+
194
+ for (const [fields, field] of BAD_KEYS) {
195
+ const nested = await refusal("crud.orders.list", fields);
196
+ const flat = await refusal("crud.invoices.list", fields);
197
+ assert.equal(nested.constructor, flat.constructor);
198
+ for (const [error, allowedKeys] of [[nested, '"orders", "customers", "regions"'], [flat, '"invoices", "customers"']]) {
199
+ assert.equal(error.status, 400);
200
+ assert.equal(error.code, "ACTION_VALIDATION_FAILED");
201
+ assert.equal(error.message, "Validation failed.");
202
+ assert.deepEqual(Object.keys(error.details.fieldErrors), [field]);
203
+ assert.deepEqual(error.details.fieldErrorCodes[field], {
204
+ code: "crud.query.fieldsKeysInvalidWithAliases",
205
+ params: { allowedTypes: allowedKeys, aliasGuidance: 'use "customers" instead of "customer"' }
206
+ });
207
+ assert.equal(
208
+ error.details.fieldErrors[field],
209
+ `fields keys must be JSON:API resource types. Allowed keys: ${allowedKeys}. Relationship aliases are invalid ` +
210
+ 'keys; use "customers" instead of "customer".'
211
+ );
212
+ assertCatalogRenders(error.details.fieldErrorCodes[field], error.details.fieldErrors[field]);
213
+ }
214
+ }
215
+ });
216
+
217
+ test("over HTTP, a fieldset keyed by a relationship alias or by no type answers alike whether the includes reach nested types or not", async (t) => {
218
+ const { actions, router } = await startOrders(t);
219
+ const app = Fastify();
220
+ t.after(() => app.close());
221
+ registerApiErrorHandler(app);
222
+ registerRoutes(app, { routes: router.list(), actions });
223
+ const listPath = (namespace) => router.list().find((route) => route.method === "GET" && route.path.endsWith(`/${namespace}`)).path;
224
+
225
+ for (const [fields, field] of BAD_KEYS) {
226
+ const [type] = Object.keys(fields);
227
+ const [nested, flat] = await Promise.all(["orders", "invoices"].map((namespace) => app.inject({
228
+ method: "GET",
229
+ url: `${listPath(namespace)}?include=customer&fields%5B${type}%5D=name`
230
+ })));
231
+ for (const response of [nested, flat]) {
232
+ assert.equal(response.statusCode, 400, `${field}: ${response.body}`);
233
+ for (const expected of ['"ACTION_VALIDATION_FAILED"', '"crud.query.fieldsKeysInvalidWithAliases"', 'use \\"customers\\" instead of \\"customer\\"']) {
234
+ assert.ok(response.body.includes(expected), `${field} ${expected}: ${response.body}`);
235
+ }
236
+ }
237
+ }
238
+ });