@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.
- package/CHANGELOG.md +6 -0
- package/locales/en.json +1 -0
- package/package.json +6 -6
- package/patterns/crud-feature-package/PATTERN.md +2 -1
- package/patterns/crud-feature-package/example/packages/books/package.json +3 -3
- package/src/server/crudContracts.js +18 -4
- package/src/server/defineCrudFeature.js +3 -2
- package/src/server/jsonApiModule/actions.js +16 -2
- package/src/server/jsonApiModule/service.js +15 -3
- package/src/server/listFilterJsonRest.js +93 -77
- package/src/server/listFilterTypes.js +18 -17
- package/src/server/listFilters.js +10 -14
- package/src/server/listQueryValidators.js +94 -15
- package/test/assistantActionConformance.test.js +80 -7
- package/test/listFilterRoutes.test.js +190 -0
- package/test/listFilters.test.js +53 -2
- package/test/listQueryValidators.test.js +63 -0
- package/test/listUndeclaredQuery.test.js +2 -2
- package/test/nestedIncludeFieldsets.test.js +238 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- A `date`, `dateRange` or `numberRange` list filter with a custom `apply` filters a list whose service passes its query through `toJsonRestQuery` (step 5 of the structured-filters guide), where json-rest-api refused the list with 422 "Field not allowed": its search schema entry (`jsonRestSearchSchema`) takes the filter's own key, but `toJsonRestQuery` sent the internal bound keys of a range filter without one (`__jskit_<key>_from` and `__jskit_<key>_toExclusive`, or `_min` and `_max`). It now sends such a filter under its own key with its parsed value, a day, `{ from, to }` or `{ min, max }`, which json-rest-api hands the `apply` as `applyQuery` does. Each filter's search schema entries and the values `toJsonRestQuery` sends for it now come from one place, so a list sends only keys its search schema declares, for every filter type with or without an `apply`; range filters without one keep their bound keys. Tests list orders over HTTP through such filters and check every type.
|
|
6
|
+
- A CRUD list or view whose includes reach below their first level refuses a `fields` key that is a relationship alias, or that names no type it shows, as it did before 0.2.26 and as a contract whose includes stop at their first level does: 400 `ACTION_VALIDATION_FAILED` naming `fields.<key>`, with the allowed types and the type to use for each alias (`crud.query.fieldsKeysInvalidWithAliases`), before the action runs. Since 0.2.26 the list and view actions checked such keys inside `execute` and threw kernel's `createValidationError` (`validation_failed`), so an assistant tool calling the list with `fields: { pet: [...] }` was told only "Validation failed.", without the field or the type to use, and the generated action registered with another `execute` (as a test stubs it) took the key. The check (`createIncludedFieldsetsCheck`) is now the actions' `checkInput`, which the kernel's action pipeline runs right after the input schema; its `crud.query.fieldsNotShown` refusal is answered the same way, and a fieldset for a type the includes reach still narrows it.
|
|
7
|
+
- A CRUD list over HTTP takes a filter that holds several values (`recordIdMany`, `enumMany`, and the list's `id`) as one comma-separated value too, `filter[customer]=1,2`, the form JSON:API gives a list, where the route's query validation refused it with 400 before the filter could split it (since 0.2.46 the filter reads `1,2` as `["1", "2"]`, but only a value the client named twice reached it in that form). Each entry must still be valid: `filter[customer]=1,,2` or a value the filter does not offer still answers 400.
|
|
8
|
+
- A `recordIdMany` list filter's search schema entry (`jsonRestSearchSchema`) takes `{ type: "id" }` items, where its items were a JSON Schema `anyOf`, which json-rest-schema refuses: a list asked for such a filter (`filter[customer]=1&filter[customer]=2`) answered 500 instead of the rows of those ids. `listFilterRoutes.test.js` lists orders by customer over HTTP.
|
|
9
|
+
- A CRUD list asked over HTTP with a `dateRange` or `numberRange` filter (`filter[arrival]=2026-03-01..2026-03-31`, `filter[total]=15..35`) answers exactly the rows inside the range, where it answered 400: the list action read the route's parsed `{ from, to }` again and refused it (`@jskit-ai/resource-crud-core` now takes it), and past that `toJsonRestQuery` dropped it. A malformed range still answers 400. A `date` or `dateRange` filter's search keys (`__jskit_<key>_from`, `__jskit_<key>_toExclusive`) now hold the day's start as ISO 8601 in UTC (`2026-03-01T00:00:00.000Z`, was `2026-03-01 00:00:00`), the form json-rest-api's `dateTime` search keys take: the old form was refused with 422, so a date filter never filtered through `jsonRestSearchSchema`. `listFilterRoutes.test.js` lists orders over HTTP through a filter contract's route and action validators, search schema and `toJsonRestQuery`, on SQLite.
|
|
10
|
+
- A CRUD list or view takes a sparse fieldset for a record its includes reach below their first level, so `?include=customer,customer.region&fields[regions]=name` narrows the included regions where it answered 400. Such a `fields[<type>]` names only the fields and links the contract's `includeFields` lists of that type there, by every path that reaches it, and refuses any other field with a 400 coded `crud.query.fieldsNotShown` that names what it shows; a type no include reaches stays refused (`crud.query.fieldsKeysInvalid`, whose allowed keys now list the types reached). The includes still decide what an included record shows: a fieldset only narrows it. Types the contract links to directly keep taking any field name, as before. Only the tables an include crosses name such a type, so `CrudContractsProvider` resolves the types each contract's includes reach when it seals the registry at boot (`resolveIncludedTypes`, which was `checkIncludedFields` and still refuses a link listed as a field; `contracts.includedTypes(crud)`), and the list and view actions check those fieldsets when they run: `createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true })` lets such a key through to `createIncludedFieldsetsCheck(resource)`, and without `deferIncludedTypes` refuses it as before. A test proves the narrowing and both refusals through the actions and over HTTP.
|
|
5
11
|
- Depends on json-rest-api 3.1.4 exactly (from 3.1.3), from the registry with its published integrity: a patch, put or patchMany that stores the values a row already holds answers the row as stored on MySQL and MariaDB (it answered the values this transaction first read), and AnyAPI storage checks its tables' columns with one statement at start-up.
|
|
6
12
|
- A CRUD list asked over HTTP for two or more values of a filter that takes several (`recordIdMany`, `enumMany`, and the list's `id`) answers the rows matching any of them, where it answered 400 (`@jskit-ai/resource-crud-core` reads the comma-separated value the route makes of them). The list's `id` passes the undeclared-key check, which a test proves.
|
|
7
13
|
- **Breaking.** A CRUD list refuses a query key its route does not take with a 400 coded `crud.query.undeclaredKeys`, naming the key and the keys the list takes. Fastify's validation dropped an undeclared key without a word, so `?filter[status]=open` on a list that declares no `status` filter answered every row as if it were unfiltered. Upgrading: declare the filter in the feature's `listFilterQueryValidator` and the resource's searchSchema, or stop sending it.
|
package/locales/en.json
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
"fieldsByTypeInvalid": "fields expects an object keyed by JSON:API resource type, such as {example}.",
|
|
11
11
|
"fieldsKeysInvalid": "fields keys must be JSON:API resource types. Allowed keys: {allowedTypes}.",
|
|
12
12
|
"fieldsKeysInvalidWithAliases": "fields keys must be JSON:API resource types. Allowed keys: {allowedTypes}. Relationship aliases are invalid keys; {aliasGuidance}.",
|
|
13
|
+
"fieldsNotShown": "fields[{type}] may name only what this read's includes show of {type}: {shown}. It names {fields}.",
|
|
13
14
|
"undeclaredKeys": "This list does not take {unknown}: an undeclared query key would be dropped, and the list would answer as if it had not been sent. It takes {known}. To filter on a field, add it to the feature's listFilterQueryValidator and the resource's searchSchema; to search, send filter[q] and give the resource searchSchema.q."
|
|
14
15
|
}
|
|
15
16
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/crud-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.27",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24.0.0"
|
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
"./locales/en.json": "./locales/en.json"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@jskit-ai/resource-core": "0.1.
|
|
24
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
23
|
+
"@jskit-ai/resource-core": "0.1.210",
|
|
24
|
+
"@jskit-ai/resource-crud-core": "0.1.212",
|
|
25
25
|
"json-rest-api": "3.1.4",
|
|
26
26
|
"json-rest-schema": "^1.0.20"
|
|
27
27
|
},
|
|
@@ -49,8 +49,8 @@
|
|
|
49
49
|
}
|
|
50
50
|
},
|
|
51
51
|
"peerDependencies": {
|
|
52
|
-
"@jskit-ai/http-runtime": "0.2.
|
|
53
|
-
"@jskit-ai/kernel": "0.2.
|
|
54
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
52
|
+
"@jskit-ai/http-runtime": "0.2.19",
|
|
53
|
+
"@jskit-ai/kernel": "0.2.19",
|
|
54
|
+
"@jskit-ai/resource-runtime": "0.2.24"
|
|
55
55
|
}
|
|
56
56
|
}
|
|
@@ -132,7 +132,8 @@ so an action without an HTTP route would otherwise reach records that no route
|
|
|
132
132
|
shows the user. The actions of an `internal: true` or `routes: false` feature
|
|
133
133
|
therefore stay off `automation` (the assistant cannot call them) unless their
|
|
134
134
|
permission names a permission (`require: "all"` or `"any"`), as the workspace
|
|
135
|
-
scope's default `crud.<namespace>.<operation>` permissions do
|
|
135
|
+
scope's default `crud.<namespace>.<operation>` permissions do (the operation is
|
|
136
|
+
`list`, `view`, `create`, `update` or `delete`; an HTTP `PATCH` is `update`). Give such a
|
|
136
137
|
feature explicit `permissions` when the assistant should read it for the users
|
|
137
138
|
who hold them; the default for other surfaces, `require: "authenticated"`,
|
|
138
139
|
would admit every signed-in user. An additional action's own `channels`
|
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
"./shared": "./src/shared/index.js"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@jskit-ai/crud-core": "0.2.
|
|
13
|
-
"@jskit-ai/resource-core": "0.1.
|
|
14
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
12
|
+
"@jskit-ai/crud-core": "0.2.27",
|
|
13
|
+
"@jskit-ai/resource-core": "0.1.210",
|
|
14
|
+
"@jskit-ai/resource-crud-core": "0.1.212"
|
|
15
15
|
},
|
|
16
16
|
"jskit": {
|
|
17
17
|
"kind": "runtime",
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
2
|
-
import {
|
|
2
|
+
import { resolveIncludedTypes } from "./jsonApiModule/service.js";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* The CRUD contracts an application serves, one per namespace. Each CRUD
|
|
@@ -10,6 +10,8 @@ import { checkIncludedFields } from "./jsonApiModule/service.js";
|
|
|
10
10
|
function createCrudContracts() {
|
|
11
11
|
/** @type {import("./types.js").CrudContract[]} */
|
|
12
12
|
const registered = [];
|
|
13
|
+
/** @type {Map<import("./types.js").CrudContract, Map<string, Set<string>>>} What resolveIncludedTypes answered for each contract at boot. */
|
|
14
|
+
const includedTypesByContract = new Map();
|
|
13
15
|
let sealed = false;
|
|
14
16
|
|
|
15
17
|
/**
|
|
@@ -32,21 +34,33 @@ function createCrudContracts() {
|
|
|
32
34
|
|
|
33
35
|
/**
|
|
34
36
|
* Ends registration. Given the resource runtime's owned table resources by name, it first checks each contract's
|
|
35
|
-
* includes against the tables they include
|
|
37
|
+
* includes against the tables they include and keeps the types they reach below their first level (see
|
|
38
|
+
* resolveIncludedTypes): at boot every feature owns its tables.
|
|
36
39
|
* @param {(name: string) => ({ name: string, schema: Record<string, any> } | null)} [tableResource]
|
|
37
40
|
*/
|
|
38
41
|
function seal(tableResource) {
|
|
39
42
|
if (tableResource) {
|
|
40
43
|
for (const crud of registered) {
|
|
41
|
-
|
|
44
|
+
includedTypesByContract.set(crud, resolveIncludedTypes(crud, tableResource));
|
|
42
45
|
}
|
|
43
46
|
}
|
|
44
47
|
sealed = true;
|
|
45
48
|
}
|
|
46
49
|
|
|
50
|
+
/**
|
|
51
|
+
* The JSON:API types a registered contract's includes reach below their first level, each with the fields it shows
|
|
52
|
+
* there: empty until the registry is sealed with the application's table resources.
|
|
53
|
+
* @param {import("./types.js").CrudContract} crud
|
|
54
|
+
* @returns {ReadonlyMap<string, ReadonlySet<string>>}
|
|
55
|
+
*/
|
|
56
|
+
function includedTypes(crud) {
|
|
57
|
+
return includedTypesByContract.get(crud) ?? new Map();
|
|
58
|
+
}
|
|
59
|
+
|
|
47
60
|
return Object.freeze({
|
|
48
61
|
register,
|
|
49
|
-
seal
|
|
62
|
+
seal,
|
|
63
|
+
includedTypes
|
|
50
64
|
});
|
|
51
65
|
}
|
|
52
66
|
|
|
@@ -516,7 +516,7 @@ function defineCrudFeature(feature) {
|
|
|
516
516
|
resourceApi: Object.freeze(withRemovedProperties({ repository: exposed, crud, service }, REMOVED_RESOURCE_API, "A CRUD feature's capability"))
|
|
517
517
|
};
|
|
518
518
|
},
|
|
519
|
-
actions({ resourceApi, ...required }) {
|
|
519
|
+
actions({ resourceApi, crudContracts, ...required }) {
|
|
520
520
|
const actionDependencies = Object.freeze(Object.fromEntries(
|
|
521
521
|
Object.keys(featureRequirements).map((name) => [name, required[name]])
|
|
522
522
|
));
|
|
@@ -529,7 +529,8 @@ function defineCrudFeature(feature) {
|
|
|
529
529
|
dependencies: actionDependencies,
|
|
530
530
|
scopeInputKeys: normalizedScope.inputKeys,
|
|
531
531
|
realtimeAudience,
|
|
532
|
-
definitions: actionDefinitions()
|
|
532
|
+
definitions: actionDefinitions(),
|
|
533
|
+
includedTypes: () => crudContracts.includedTypes(crud)
|
|
533
534
|
});
|
|
534
535
|
}
|
|
535
536
|
});
|
|
@@ -7,6 +7,7 @@ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
|
|
|
7
7
|
import { ARCHITECTURE_ID_PATTERN } from "@jskit-ai/kernel/shared/capabilities";
|
|
8
8
|
import { ACTION_INPUT_DEFAULT_MODE } from "@jskit-ai/kernel/server/actions";
|
|
9
9
|
import {
|
|
10
|
+
createIncludedFieldsetsCheck,
|
|
10
11
|
createJsonApiFieldsetsQueryValidator,
|
|
11
12
|
createStandardCrudListQueryValidators,
|
|
12
13
|
createStandardCrudViewQueryValidators
|
|
@@ -35,15 +36,18 @@ function resolveCrudActionChannels(permission, servedOverHttp) {
|
|
|
35
36
|
|
|
36
37
|
function buildActionInput(resource, operation, scopeInputValidator, listFilterQueryValidator, operationInputs) {
|
|
37
38
|
const definitions = scopeInputValidator ? [scopeInputValidator] : [];
|
|
39
|
+
// A fieldset for a type the includes reach below their first level is checked by the action's checkInput, after this
|
|
40
|
+
// schema (see createIncludedFieldsetsCheck): only the tables they cross name that type, and every feature owns its
|
|
41
|
+
// tables at boot.
|
|
38
42
|
if (operation === "list") {
|
|
39
43
|
definitions.push(...createStandardCrudListQueryValidators({
|
|
40
44
|
resource,
|
|
41
45
|
listFilterQueryValidator,
|
|
42
|
-
fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource })
|
|
46
|
+
fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true })
|
|
43
47
|
}));
|
|
44
48
|
} else if (operation === "view") {
|
|
45
49
|
definitions.push(recordIdParamsValidator, ...createStandardCrudViewQueryValidators({
|
|
46
|
-
fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource })
|
|
50
|
+
fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true })
|
|
47
51
|
}));
|
|
48
52
|
} else if (operation === "create") {
|
|
49
53
|
definitions.push(operationInputs.create || resource.operations.create.body);
|
|
@@ -242,6 +246,9 @@ function createCrudJsonApiActionDefinitions({
|
|
|
242
246
|
* @param {boolean} dependencies.servedOverHttp False when the feature is internal or registers no routes.
|
|
243
247
|
* @param {ReturnType<typeof createCrudJsonApiActionDefinitions>} [dependencies.definitions] What
|
|
244
248
|
* createCrudJsonApiActionDefinitions built from the same options, when the caller keeps it; built here otherwise.
|
|
249
|
+
* @param {() => ReadonlyMap<string, ReadonlySet<string>>} [dependencies.includedTypes] The types the contract's
|
|
250
|
+
* includes reach below their first level, with the fields each shows there: the CRUD contracts' includedTypes once
|
|
251
|
+
* they are sealed. Without it, a list or view takes no fieldset for such a type.
|
|
245
252
|
*/
|
|
246
253
|
function createCrudJsonApiActions({
|
|
247
254
|
namespace,
|
|
@@ -253,9 +260,13 @@ function createCrudJsonApiActions({
|
|
|
253
260
|
dependencies: actionDependencies,
|
|
254
261
|
realtimeAudience,
|
|
255
262
|
definitions: builtDefinitions,
|
|
263
|
+
includedTypes = () => new Map(),
|
|
256
264
|
...definitionOptions
|
|
257
265
|
}) {
|
|
258
266
|
const definitions = builtDefinitions ?? createCrudJsonApiActionDefinitions({ namespace, resource, ...definitionOptions });
|
|
267
|
+
const checkIncludedFieldsets = createIncludedFieldsetsCheck(resource);
|
|
268
|
+
// A read's input refuses a fieldset for a type its includes do not show, as its schema refuses any other bad key.
|
|
269
|
+
const checkReadInput = (input) => checkIncludedFieldsets(input.fields, includedTypes());
|
|
259
270
|
const mutationEvent = (operation, entityId) => buildCrudRecordChangedEvent({
|
|
260
271
|
namespace,
|
|
261
272
|
operation,
|
|
@@ -370,12 +381,14 @@ function createCrudJsonApiActions({
|
|
|
370
381
|
operation: "list",
|
|
371
382
|
kind: "query",
|
|
372
383
|
events: [],
|
|
384
|
+
checkInput: checkReadInput,
|
|
373
385
|
execute: (input, context) => executeOperation("list", input, context, listDocuments)
|
|
374
386
|
},
|
|
375
387
|
{
|
|
376
388
|
operation: "view",
|
|
377
389
|
kind: "query",
|
|
378
390
|
events: [],
|
|
391
|
+
checkInput: checkReadInput,
|
|
379
392
|
execute: (input, context) => executeOperation("view", input, context, viewDocument)
|
|
380
393
|
},
|
|
381
394
|
{
|
|
@@ -411,6 +424,7 @@ function createCrudJsonApiActions({
|
|
|
411
424
|
output: null,
|
|
412
425
|
extensions: built.extensions,
|
|
413
426
|
events: definition.events,
|
|
427
|
+
...(definition.checkInput ? { checkInput: definition.checkInput } : {}),
|
|
414
428
|
execute: definition.execute
|
|
415
429
|
});
|
|
416
430
|
});
|
|
@@ -104,17 +104,23 @@ function linksOf(resource) {
|
|
|
104
104
|
}
|
|
105
105
|
|
|
106
106
|
/**
|
|
107
|
+
* Checks each level of a contract's includes against the table resource it reaches, and answers the JSON:API types
|
|
108
|
+
* they reach below their first level, each with the fields it shows there (its listed fields and links, by every
|
|
109
|
+
* path that reaches it). Only those tables name such a type, so the CRUD actions check a sparse fieldset for one
|
|
110
|
+
* against this answer (see createIncludedFieldsetsCheck).
|
|
107
111
|
* Refuses a field an include lists that is a link of the included record: a belongs-to field, by its key
|
|
108
112
|
* (`locationId`) or its relationship (`location`), or a collection relation. A JSON:API document answers a link
|
|
109
113
|
* under the record's relationships, never among its attributes, so the field would never show and the record would
|
|
110
114
|
* read as if it had no link. The list names a link as `{ location: [] }`, which answers the linked record's id, with
|
|
111
115
|
* the fields to show of that record inside it. Each level is checked against its own table resource; a level whose
|
|
112
|
-
* resource no feature owns is left to the request.
|
|
116
|
+
* resource no feature owns is left to the request, and the types below it are not answered.
|
|
113
117
|
* @param {import("../types.js").CrudContract} crud
|
|
114
118
|
* @param {(name: string) => ({ name: string, schema: Record<string, any> } | null)} tableResource The resource runtime's
|
|
115
119
|
* owned table resources, by name.
|
|
120
|
+
* @returns {Map<string, Set<string>>}
|
|
116
121
|
*/
|
|
117
|
-
function
|
|
122
|
+
function resolveIncludedTypes(crud, tableResource) {
|
|
123
|
+
const reached = new Map();
|
|
118
124
|
const check = (label, resourceName, { attributes, relationships }) => {
|
|
119
125
|
const resource = tableResource(resourceName);
|
|
120
126
|
if (!resource) {
|
|
@@ -136,6 +142,11 @@ function checkIncludedFields(crud, tableResource) {
|
|
|
136
142
|
for (const [relationshipName, nested] of Object.entries(relationships)) {
|
|
137
143
|
const link = links.get(relationshipName);
|
|
138
144
|
if (link?.target) {
|
|
145
|
+
const shown = reached.get(link.target) ?? new Set();
|
|
146
|
+
reached.set(link.target, shown);
|
|
147
|
+
for (const name of [...nested.attributes, ...Object.keys(nested.relationships)]) {
|
|
148
|
+
shown.add(name);
|
|
149
|
+
}
|
|
139
150
|
check(`${label}.${relationshipName}`, link.target, nested);
|
|
140
151
|
}
|
|
141
152
|
}
|
|
@@ -143,6 +154,7 @@ function checkIncludedFields(crud, tableResource) {
|
|
|
143
154
|
for (const { attributeKey, relationshipType, include } of contractShape(crud).relationships) {
|
|
144
155
|
check(`${attributeKey}.includeFields`, relationshipType, include);
|
|
145
156
|
}
|
|
157
|
+
return reached;
|
|
146
158
|
}
|
|
147
159
|
|
|
148
160
|
// What each CRUD contract shows, by contract. defineCrudContract deep-freezes a contract, so what it shows is worked
|
|
@@ -323,4 +335,4 @@ function createCrudService({ repository, crud }) {
|
|
|
323
335
|
});
|
|
324
336
|
}
|
|
325
337
|
|
|
326
|
-
export {
|
|
338
|
+
export { createCrudService, resolveIncludedTypes };
|
|
@@ -19,8 +19,6 @@ import {
|
|
|
19
19
|
CRUD_LIST_FILTER_PRESENCE_MISSING
|
|
20
20
|
} from "@jskit-ai/resource-crud-core/shared/crudListFilters";
|
|
21
21
|
import {
|
|
22
|
-
recordIdTransportSchema,
|
|
23
|
-
cloneTransportSchema,
|
|
24
22
|
addDaysToDateFilterValue,
|
|
25
23
|
applyDefaultFilterQuery
|
|
26
24
|
} from "./listFilterTypes.js";
|
|
@@ -81,8 +79,9 @@ function buildJsonRestFilterItemSchema(filter = {}) {
|
|
|
81
79
|
};
|
|
82
80
|
}
|
|
83
81
|
|
|
82
|
+
// A json-rest-schema field definition, never JSON Schema: json-rest-schema refuses an `anyOf` item.
|
|
84
83
|
if (filter.type === CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY) {
|
|
85
|
-
return
|
|
84
|
+
return { type: "id" };
|
|
86
85
|
}
|
|
87
86
|
|
|
88
87
|
return {};
|
|
@@ -196,109 +195,126 @@ function resolveCrudListFilterEntries(value = {}) {
|
|
|
196
195
|
return Object.values(defineCrudListFilters(value));
|
|
197
196
|
}
|
|
198
197
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
198
|
+
// The instant a filter's day starts, in the form json-rest-api's dateTime search keys take (ISO 8601 with its zone,
|
|
199
|
+
// which refuses "2026-03-01 00:00:00"): midnight UTC, the zone a dateTime is stored in.
|
|
200
|
+
function dateFilterDayStart(date) {
|
|
201
|
+
return `${date}T00:00:00.000Z`;
|
|
202
|
+
}
|
|
203
203
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
204
|
+
// The internal bound keys a range filter without a custom apply sends for its parsed value: a date's day, or a
|
|
205
|
+
// dateRange's days, as the instants from the first day's start to the day after the last; a numberRange's bounds.
|
|
206
|
+
function buildJsonRestRangeFilterValues(filter = {}, value) {
|
|
207
|
+
const bounds = {};
|
|
208
|
+
if (filter.type === CRUD_LIST_FILTER_TYPE_DATE || filter.type === CRUD_LIST_FILTER_TYPE_DATE_RANGE) {
|
|
209
|
+
const { from, to } = filter.type === CRUD_LIST_FILTER_TYPE_DATE ? { from: value, to: value } : value || {};
|
|
210
|
+
const nextDate = to ? addDaysToDateFilterValue(to, 1) : "";
|
|
211
|
+
if (from) {
|
|
212
|
+
bounds[renderInternalJsonRestFilterKey(filter, "from")] = dateFilterDayStart(from);
|
|
210
213
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
if (!actualField) {
|
|
214
|
-
continue;
|
|
214
|
+
if (nextDate) {
|
|
215
|
+
bounds[renderInternalJsonRestFilterKey(filter, "toExclusive")] = dateFilterDayStart(nextDate);
|
|
215
216
|
}
|
|
217
|
+
}
|
|
216
218
|
|
|
217
|
-
|
|
218
|
-
if (
|
|
219
|
-
|
|
220
|
-
continue;
|
|
219
|
+
if (filter.type === CRUD_LIST_FILTER_TYPE_NUMBER_RANGE) {
|
|
220
|
+
if (value?.min != null) {
|
|
221
|
+
bounds[renderInternalJsonRestFilterKey(filter, "min")] = value.min;
|
|
221
222
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
schema[filter.queryKey] = buildJsonRestPresenceFilterSearchSchemaEntry(filter, { actualField });
|
|
225
|
-
continue;
|
|
223
|
+
if (value?.max != null) {
|
|
224
|
+
bounds[renderInternalJsonRestFilterKey(filter, "max")] = value.max;
|
|
226
225
|
}
|
|
227
|
-
|
|
228
|
-
Object.assign(schema, buildJsonRestRangeFilterSearchSchemaEntries(filter, { actualField }));
|
|
229
226
|
}
|
|
230
227
|
|
|
231
|
-
return
|
|
228
|
+
return bounds;
|
|
232
229
|
}
|
|
233
230
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
231
|
+
/**
|
|
232
|
+
* How one filter reaches json-rest-api: the search schema entries it declares, and the filter values
|
|
233
|
+
* `toJsonRestQuery` sends for its parsed value. Both come from here, so a list sends only keys its search schema
|
|
234
|
+
* declares. A filter with a custom apply sends its own key with its parsed value, whatever its type (a day,
|
|
235
|
+
* `{ from, to }` or `{ min, max }`), which is what `applyQuery` hands that apply; a range filter without one sends its
|
|
236
|
+
* internal bound keys, which compare its field.
|
|
237
|
+
*/
|
|
238
|
+
function resolveJsonRestFilterProjection(filter, { columns, apply }) {
|
|
239
|
+
const ownKey = (schemaEntry) => ({
|
|
240
|
+
filter,
|
|
241
|
+
schema: { [filter.queryKey]: schemaEntry },
|
|
242
|
+
values: (value) => ({ [filter.queryKey]: value })
|
|
243
|
+
});
|
|
244
|
+
// readable-check: allow method-probe - input validation: apply holds an application's optional custom filters; other filters use the default
|
|
245
|
+
const customApply = typeof apply[filter.key] === "function" ? apply[filter.key] : null;
|
|
246
|
+
if (customApply) {
|
|
247
|
+
return ownKey(buildJsonRestCustomFilterSearchSchemaEntry(filter, customApply));
|
|
238
248
|
}
|
|
239
|
-
if (nextDate) {
|
|
240
|
-
target[renderInternalJsonRestFilterKey(filter, "toExclusive")] = `${nextDate} 00:00:00`;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
249
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
return;
|
|
250
|
+
const actualField = resolveJsonRestFilterActualField(filter, columns);
|
|
251
|
+
const simpleEntry = buildJsonRestSimpleFilterSearchSchemaEntry(filter, { actualField });
|
|
252
|
+
if (simpleEntry) {
|
|
253
|
+
return ownKey(simpleEntry);
|
|
248
254
|
}
|
|
249
255
|
|
|
250
|
-
if (filter.type ===
|
|
251
|
-
|
|
252
|
-
target[renderInternalJsonRestFilterKey(filter, "from")] = `${value.from} 00:00:00`;
|
|
253
|
-
}
|
|
254
|
-
if (value?.to) {
|
|
255
|
-
const nextDate = addDaysToDateFilterValue(value.to, 1);
|
|
256
|
-
if (nextDate) {
|
|
257
|
-
target[renderInternalJsonRestFilterKey(filter, "toExclusive")] = `${nextDate} 00:00:00`;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
return;
|
|
256
|
+
if (filter.type === CRUD_LIST_FILTER_TYPE_PRESENCE) {
|
|
257
|
+
return ownKey(buildJsonRestPresenceFilterSearchSchemaEntry(filter, { actualField }));
|
|
261
258
|
}
|
|
262
259
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
260
|
+
return {
|
|
261
|
+
filter,
|
|
262
|
+
schema: buildJsonRestRangeFilterSearchSchemaEntries(filter, { actualField }),
|
|
263
|
+
values: (value) => buildJsonRestRangeFilterValues(filter, value)
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function resolveJsonRestFilterProjections(runtime = {}, { columns = {}, apply = {} } = {}) {
|
|
268
|
+
const normalizedColumns = normalizeColumnsMap(columns);
|
|
269
|
+
return resolveCrudListFilterEntries(runtime)
|
|
270
|
+
.map((filter) => resolveJsonRestFilterProjection(filter, { columns: normalizedColumns, apply }));
|
|
271
|
+
}
|
|
272
272
|
|
|
273
|
-
|
|
273
|
+
function mergeJsonRestSearchSchema(projections = []) {
|
|
274
|
+
return Object.freeze(Object.assign({}, ...projections.map((projection) => projection.schema)));
|
|
274
275
|
}
|
|
275
276
|
|
|
276
|
-
function
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
const filterQueryKeys = new Set(filterEntries.map((filter) => filter.queryKey));
|
|
280
|
-
const parsedFilters = runtime.parseQuery(source);
|
|
281
|
-
const normalized = {};
|
|
277
|
+
function createCrudListFilterJsonRestSearchSchema(runtime = {}, { columns = {}, apply = {} } = {}) {
|
|
278
|
+
return mergeJsonRestSearchSchema(resolveJsonRestFilterProjections(runtime, { columns, apply }));
|
|
279
|
+
}
|
|
282
280
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
281
|
+
/**
|
|
282
|
+
* A filter runtime's search schema and its `toJsonRestQuery(query)`, which keeps the query's other keys and replaces
|
|
283
|
+
* each filter's value with the filter values its projection sends for it.
|
|
284
|
+
* @param {{ filters: Record<string, object>, parseQuery: (query: object) => Record<string, unknown> }} runtime
|
|
285
|
+
*/
|
|
286
|
+
function createCrudListFilterJsonRest(runtime, { columns = {}, apply = {} } = {}) {
|
|
287
|
+
const projections = resolveJsonRestFilterProjections(runtime, { columns, apply });
|
|
288
|
+
const filterQueryKeys = new Set(projections.map(({ filter }) => filter.queryKey));
|
|
289
|
+
|
|
290
|
+
function toJsonRestQuery(query = {}) {
|
|
291
|
+
const source = normalizeObjectInput(query);
|
|
292
|
+
const parsedFilters = runtime.parseQuery(source);
|
|
293
|
+
const normalized = {};
|
|
294
|
+
|
|
295
|
+
for (const [key, value] of Object.entries(source)) {
|
|
296
|
+
if (!filterQueryKeys.has(key)) {
|
|
297
|
+
normalized[key] = value;
|
|
298
|
+
}
|
|
286
299
|
}
|
|
287
|
-
}
|
|
288
300
|
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
301
|
+
for (const { filter, values } of projections) {
|
|
302
|
+
if (Object.hasOwn(parsedFilters, filter.key)) {
|
|
303
|
+
Object.assign(normalized, values(parsedFilters[filter.key]));
|
|
304
|
+
}
|
|
292
305
|
}
|
|
293
306
|
|
|
294
|
-
|
|
307
|
+
return normalized;
|
|
295
308
|
}
|
|
296
309
|
|
|
297
|
-
return
|
|
310
|
+
return Object.freeze({
|
|
311
|
+
searchSchema: mergeJsonRestSearchSchema(projections),
|
|
312
|
+
toJsonRestQuery
|
|
313
|
+
});
|
|
298
314
|
}
|
|
299
315
|
|
|
300
316
|
export {
|
|
301
317
|
normalizeColumnsMap,
|
|
302
318
|
createCrudListFilterJsonRestSearchSchema,
|
|
303
|
-
|
|
319
|
+
createCrudListFilterJsonRest
|
|
304
320
|
};
|
|
@@ -96,7 +96,9 @@ function cloneTransportSchema(value) {
|
|
|
96
96
|
);
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
-
|
|
99
|
+
// A filter that takes several values takes them as the client sends them, `filter[x]=1&filter[x]=2`, or as one
|
|
100
|
+
// comma-separated value, `filter[x]=1,2`, the form JSON:API gives a list (and the one the parse reads either as).
|
|
101
|
+
function buildSingleOrMultiTransportSchema(itemSchema, itemPattern = "") {
|
|
100
102
|
return {
|
|
101
103
|
anyOf: [
|
|
102
104
|
cloneTransportSchema(itemSchema),
|
|
@@ -104,11 +106,17 @@ function buildSingleOrMultiTransportSchema(itemSchema) {
|
|
|
104
106
|
type: "array",
|
|
105
107
|
items: cloneTransportSchema(itemSchema),
|
|
106
108
|
minItems: 1
|
|
107
|
-
}
|
|
109
|
+
},
|
|
110
|
+
...(itemPattern ? [{ type: "string", pattern: `^${itemPattern}(?:,${itemPattern})+$` }] : [])
|
|
108
111
|
]
|
|
109
112
|
};
|
|
110
113
|
}
|
|
111
114
|
|
|
115
|
+
function allowedValuesPattern(allowedValues) {
|
|
116
|
+
const alternatives = allowedValues.map((value) => String(value).replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"));
|
|
117
|
+
return alternatives.length > 0 ? `(?:${alternatives.join("|")})` : "";
|
|
118
|
+
}
|
|
119
|
+
|
|
112
120
|
function addDaysToDateFilterValue(value = "", days = 0) {
|
|
113
121
|
const normalizedValue = parseCrudListFilterQueryValue(
|
|
114
122
|
{ type: CRUD_LIST_FILTER_TYPE_DATE },
|
|
@@ -176,14 +184,11 @@ const FILTER_TYPE_SERVER_HANDLERS = Object.freeze({
|
|
|
176
184
|
}),
|
|
177
185
|
[CRUD_LIST_FILTER_TYPE_ENUM_MANY]: Object.freeze({
|
|
178
186
|
buildTransportSchema({ discardInvalidValues, allowedValues }) {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
enum: allowedValues
|
|
185
|
-
}
|
|
186
|
-
);
|
|
187
|
+
if (discardInvalidValues) {
|
|
188
|
+
return buildSingleOrMultiTransportSchema(looseTextTransportSchema);
|
|
189
|
+
}
|
|
190
|
+
const allowedValueSchema = { type: "string", enum: allowedValues };
|
|
191
|
+
return buildSingleOrMultiTransportSchema(allowedValueSchema, allowedValuesPattern(allowedValues));
|
|
187
192
|
},
|
|
188
193
|
applyQuery: applyInFilterQuery
|
|
189
194
|
}),
|
|
@@ -197,11 +202,9 @@ const FILTER_TYPE_SERVER_HANDLERS = Object.freeze({
|
|
|
197
202
|
}),
|
|
198
203
|
[CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY]: Object.freeze({
|
|
199
204
|
buildTransportSchema({ discardInvalidValues }) {
|
|
200
|
-
return
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
: recordIdTransportSchema
|
|
204
|
-
);
|
|
205
|
+
return discardInvalidValues
|
|
206
|
+
? buildSingleOrMultiTransportSchema(looseStringOrNumberTransportSchema)
|
|
207
|
+
: buildSingleOrMultiTransportSchema(recordIdTransportSchema, RECORD_ID_PATTERN.slice(1, -1));
|
|
205
208
|
},
|
|
206
209
|
applyQuery: applyInFilterQuery
|
|
207
210
|
}),
|
|
@@ -417,8 +420,6 @@ function applyDefaultFilterQuery(queryBuilder, filter = {}, value, column = "")
|
|
|
417
420
|
}
|
|
418
421
|
|
|
419
422
|
export {
|
|
420
|
-
recordIdTransportSchema,
|
|
421
|
-
cloneTransportSchema,
|
|
422
423
|
addDaysToDateFilterValue,
|
|
423
424
|
buildCrudListFilterQueryField,
|
|
424
425
|
createCrudListFilterQuerySchema,
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
import {
|
|
10
10
|
normalizeColumnsMap,
|
|
11
11
|
createCrudListFilterJsonRestSearchSchema,
|
|
12
|
-
|
|
12
|
+
createCrudListFilterJsonRest
|
|
13
13
|
} from "./listFilterJsonRest.js";
|
|
14
14
|
import {
|
|
15
15
|
buildCrudListFilterQueryField,
|
|
@@ -101,24 +101,20 @@ function createCrudListFilters(definitions = {}, { columns = {}, apply = {} } =
|
|
|
101
101
|
return queryValidatorsByInvalidValueMode[invalidValueMode];
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
104
|
+
const jsonRest = createCrudListFilterJsonRest({
|
|
105
|
+
filters: normalizedFilters,
|
|
106
|
+
parseQuery: parseFilterPayload
|
|
107
|
+
}, {
|
|
108
|
+
columns: normalizedColumns,
|
|
109
|
+
apply
|
|
110
|
+
});
|
|
110
111
|
|
|
111
112
|
return Object.freeze({
|
|
112
113
|
filters: normalizedFilters,
|
|
113
114
|
createQueryValidator,
|
|
114
115
|
parseQuery: parseFilterPayload,
|
|
115
|
-
toJsonRestQuery,
|
|
116
|
-
jsonRestSearchSchema:
|
|
117
|
-
filters: normalizedFilters
|
|
118
|
-
}, {
|
|
119
|
-
columns: normalizedColumns,
|
|
120
|
-
apply
|
|
121
|
-
}),
|
|
116
|
+
toJsonRestQuery: jsonRest.toJsonRestQuery,
|
|
117
|
+
jsonRestSearchSchema: jsonRest.searchSchema,
|
|
122
118
|
applyQuery
|
|
123
119
|
});
|
|
124
120
|
}
|