@jskit-ai/crud-core 0.2.3 → 0.2.4

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 (48) hide show
  1. package/locales/en.json +2 -1
  2. package/package.json +7 -7
  3. package/patterns/json-api-resource-package/PATTERN.md +102 -23
  4. package/patterns/json-api-resource-package/example/packages/books/package.json +3 -2
  5. package/patterns/json-api-resource-package/example/packages/books/src/server/types.js +5 -0
  6. package/src/server/createCrudServiceFromResource.js +14 -6
  7. package/src/server/createHooksToCollectChildren.js +123 -97
  8. package/src/server/defineCrudJsonApiFeature.js +40 -8
  9. package/src/server/fieldAccess.js +33 -25
  10. package/src/server/jsonApiModule/actions.js +151 -548
  11. package/src/server/jsonApiModule/assistantExtension.js +386 -0
  12. package/src/server/jsonApiModule/customActionId.js +12 -0
  13. package/src/server/jsonApiModule/repository.js +73 -21
  14. package/src/server/jsonApiModule/routes.js +44 -30
  15. package/src/server/jsonApiModule/service.js +37 -35
  16. package/src/server/jsonApiResourceContract.js +22 -18
  17. package/src/server/listFilterJsonRest.js +304 -0
  18. package/src/server/listFilterTypes.js +427 -0
  19. package/src/server/listFilters.js +26 -722
  20. package/src/server/listQueryValidators.js +26 -21
  21. package/src/server/lookupPathSupport.js +31 -18
  22. package/src/server/lookups.js +20 -34
  23. package/src/server/normalizeOptionalText.js +13 -0
  24. package/src/server/repositorySupport.js +11 -10
  25. package/src/server/resourceRuntime/compiledRuntime.js +284 -0
  26. package/src/server/resourceRuntime/index.js +167 -920
  27. package/src/server/resourceRuntime/listControls.js +333 -0
  28. package/src/server/resourceRuntime/lookupHydration.js +121 -186
  29. package/src/server/resourceRuntime/operationStages.js +140 -0
  30. package/src/server/resourceRuntime/recordValidation.js +65 -0
  31. package/src/server/routeContracts.js +44 -46
  32. package/src/server/serviceEvents.js +42 -118
  33. package/src/server/serviceMethods.js +34 -26
  34. package/src/server/types.js +156 -0
  35. package/test/assistantActionConformance.test.js +8 -5
  36. package/test/assistantPagination.integration.test.js +5 -3
  37. package/test/createCrudServiceFromResource.test.js +0 -18
  38. package/test/customActionId.test.js +12 -0
  39. package/test/defineCrudJsonApiFeature.test.js +193 -28
  40. package/test/errorCodes.test.js +18 -0
  41. package/test/jsonApiRepository.test.js +103 -3
  42. package/test/listFilters.test.js +7 -7
  43. package/test/listQueryValidators.test.js +1 -54
  44. package/test/serviceEvents.test.js +31 -81
  45. package/test/support/crudJsonApiActionOptions.js +37 -0
  46. package/src/server/crudModuleConfig.js +0 -181
  47. package/src/server/lookupHydration.js +0 -710
  48. package/test/crudModuleConfig.test.js +0 -33
@@ -3,11 +3,12 @@ import { resolveScopedApiBasePath } from "@jskit-ai/kernel/shared/surface";
3
3
  import { checkRouteVisibility } from "@jskit-ai/kernel/shared/support/visibility";
4
4
  import { composeSchemaDefinitions } from "@jskit-ai/kernel/shared/validators";
5
5
  import { createCrudJsonApiRouteContracts } from "../routeContracts.js";
6
+ import { buildCrudCustomActionId } from "./customActionId.js";
6
7
 
7
8
  const CUSTOM_ACTION_METHODS = new Set(["DELETE", "GET", "PATCH", "POST", "PUT"]);
8
9
 
9
- function createScopeInput(scopeInput, request) {
10
- if (typeof scopeInput !== "function") {
10
+ function buildScopeInput(scopeInput, request) {
11
+ if (!scopeInput) {
11
12
  return {};
12
13
  }
13
14
  const result = scopeInput(request);
@@ -17,9 +18,9 @@ function createScopeInput(scopeInput, request) {
17
18
  return result;
18
19
  }
19
20
 
20
- function createCustomActionInput(scopeInput, route, request) {
21
- const scopedInput = createScopeInput(scopeInput, request);
22
- if (typeof route.input === "function") {
21
+ function buildCustomActionInput(scopeInput, route, request) {
22
+ const scopedInput = buildScopeInput(scopeInput, request);
23
+ if (route.input) {
23
24
  const input = route.input(request);
24
25
  if (!input || typeof input !== "object" || Array.isArray(input)) {
25
26
  throw new TypeError("CRUD custom action route.input() must return an object.");
@@ -34,11 +35,7 @@ function createCustomActionInput(scopeInput, route, request) {
34
35
  };
35
36
  }
36
37
 
37
- function normalizeCustomActionRoutes(actions = {}, namespace = "") {
38
- if (!actions || typeof actions !== "object" || Array.isArray(actions)) {
39
- throw new TypeError("CRUD actions must be an object.");
40
- }
41
-
38
+ function normalizeCustomActionRoutes(actions, namespace) {
42
39
  return Object.freeze(Object.entries(actions).flatMap(([name, definition]) => {
43
40
  if (!definition?.route) return [];
44
41
  const route = definition.route;
@@ -56,6 +53,7 @@ function normalizeCustomActionRoutes(actions = {}, namespace = "") {
56
53
  if (!route.contract || typeof route.contract !== "object" || Array.isArray(route.contract)) {
57
54
  throw new TypeError(`CRUD custom action "${name}" route.contract must be an object.`);
58
55
  }
56
+ // readable-check: allow method-probe - input validation: a custom action route's input must be a function
59
57
  if (route.input != null && typeof route.input !== "function") {
60
58
  throw new TypeError(`CRUD custom action "${name}" route.input must be a function.`);
61
59
  }
@@ -65,7 +63,7 @@ function normalizeCustomActionRoutes(actions = {}, namespace = "") {
65
63
  }
66
64
  return [Object.freeze({
67
65
  name,
68
- actionId: String(definition.id || `${namespace}.${name}`).trim(),
66
+ actionId: buildCrudCustomActionId(namespace, name, definition),
69
67
  method,
70
68
  path,
71
69
  contract: route.contract,
@@ -76,25 +74,41 @@ function normalizeCustomActionRoutes(actions = {}, namespace = "") {
76
74
  }));
77
75
  }
78
76
 
77
+ /**
78
+ * Registers the routes of one CRUD feature, from the options defineCrudJsonApiFeature resolved.
79
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router
80
+ * @param {object} options
81
+ * @param {string} options.namespace
82
+ * @param {import("../types.js").CrudResourceDefinition} options.resource
83
+ * @param {string} options.routeBase
84
+ * @param {string} options.relativePath
85
+ * @param {string} options.surface
86
+ * @param {string} options.ownershipFilter
87
+ * @param {string} options.access
88
+ * @param {boolean} options.internal
89
+ * @param {readonly string[]} options.operations
90
+ * @param {Record<string, object>} options.actions The feature's custom actions, by name.
91
+ * @param {{ create?: object, update?: object }} options.operationInputs
92
+ * @param {object | null} options.listFilterQueryValidator
93
+ * @param {object | null} options.routeParamsValidator
94
+ * @param {((request: object) => object) | null} options.scopeInput
95
+ */
79
96
  function registerCrudJsonApiRoutes(router, {
80
97
  namespace,
81
98
  resource,
82
- routeBase = "/",
99
+ routeBase,
83
100
  relativePath,
84
101
  surface,
85
102
  ownershipFilter,
86
103
  access,
87
- internal = false,
88
- operations = ["list", "view", "create", "update", "delete"],
89
- actions = {},
90
- operationInputs = {},
91
- listFilterQueryValidator = null,
92
- routeParamsValidator = null,
93
- scopeInput = null
94
- } = {}) {
95
- if (!router || typeof router.register !== "function") {
96
- throw new TypeError("registerCrudJsonApiRoutes requires router.");
97
- }
104
+ internal,
105
+ operations,
106
+ actions,
107
+ operationInputs,
108
+ listFilterQueryValidator,
109
+ routeParamsValidator,
110
+ scopeInput
111
+ }) {
98
112
  const normalizedSurface = normalizeSurfaceId(surface);
99
113
  const basePath = resolveScopedApiBasePath({
100
114
  routeBase,
@@ -139,7 +153,7 @@ function registerCrudJsonApiRoutes(router, {
139
153
  const response = await request.executeAction({
140
154
  actionId: actionId("list"),
141
155
  input: {
142
- ...createScopeInput(scopeInput, request),
156
+ ...buildScopeInput(scopeInput, request),
143
157
  ...(request.input.query || {})
144
158
  }
145
159
  });
@@ -160,7 +174,7 @@ function registerCrudJsonApiRoutes(router, {
160
174
  const response = await request.executeAction({
161
175
  actionId: actionId("view"),
162
176
  input: {
163
- ...createScopeInput(scopeInput, request),
177
+ ...buildScopeInput(scopeInput, request),
164
178
  recordId: request.input.params.recordId,
165
179
  ...(request.input.query || {})
166
180
  }
@@ -182,7 +196,7 @@ function registerCrudJsonApiRoutes(router, {
182
196
  const response = await request.executeAction({
183
197
  actionId: actionId("create"),
184
198
  input: {
185
- ...createScopeInput(scopeInput, request),
199
+ ...buildScopeInput(scopeInput, request),
186
200
  ...(request.input.body || {})
187
201
  }
188
202
  });
@@ -203,7 +217,7 @@ function registerCrudJsonApiRoutes(router, {
203
217
  const response = await request.executeAction({
204
218
  actionId: actionId("update"),
205
219
  input: {
206
- ...createScopeInput(scopeInput, request),
220
+ ...buildScopeInput(scopeInput, request),
207
221
  recordId: request.input.params.recordId,
208
222
  ...(request.input.body || {})
209
223
  }
@@ -225,7 +239,7 @@ function registerCrudJsonApiRoutes(router, {
225
239
  const response = await request.executeAction({
226
240
  actionId: actionId("delete"),
227
241
  input: {
228
- ...createScopeInput(scopeInput, request),
242
+ ...buildScopeInput(scopeInput, request),
229
243
  recordId: request.input.params.recordId
230
244
  }
231
245
  });
@@ -259,7 +273,7 @@ function registerCrudJsonApiRoutes(router, {
259
273
  async function (request, reply) {
260
274
  const response = await request.executeAction({
261
275
  actionId: actionRoute.actionId,
262
- input: createCustomActionInput(scopeInput, actionRoute, request)
276
+ input: buildCustomActionInput(scopeInput, actionRoute, request)
263
277
  });
264
278
  const nextReply = reply.code(actionRoute.statusCode);
265
279
  if (actionRoute.statusCode === 204) {
@@ -272,4 +286,4 @@ function registerCrudJsonApiRoutes(router, {
272
286
  }
273
287
  }
274
288
 
275
- export { normalizeCustomActionRoutes, registerCrudJsonApiRoutes };
289
+ export { registerCrudJsonApiRoutes };
@@ -1,50 +1,52 @@
1
1
  import { returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
2
+ import { resolveTransaction } from "@jskit-ai/database-runtime/shared";
2
3
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
3
4
 
4
- function requireDocument(document = null) {
5
+ function requireDocument(document) {
5
6
  if (!document) {
6
7
  throw new AppError(404, "Document not found.", { code: "crud.document.notFound" });
7
8
  }
8
9
  return document;
9
10
  }
10
11
 
11
- function createCrudJsonApiService({ repository } = {}) {
12
- if (!repository) {
13
- throw new TypeError("createCrudJsonApiService requires repository.");
12
+ /**
13
+ * What a service call hands its repository: the call's transaction and action
14
+ * context, each null when the call has none.
15
+ * @param {{ trx?: import("@jskit-ai/database-runtime/server/types").RuntimeKnexTransaction | null, context?: object | null }} [options]
16
+ */
17
+ function repositoryCallOptions(options = {}) {
18
+ return { trx: resolveTransaction(options), context: options.context || null };
19
+ }
20
+
21
+ /** @param {{ repository: import("../types.js").CrudRepository }} dependencies */
22
+ function createCrudJsonApiService({ repository }) {
23
+ async function queryDocuments(query, options) {
24
+ return returnJsonApiDocument(await repository.queryDocuments(query, repositoryCallOptions(options)));
25
+ }
26
+
27
+ async function getDocumentById(recordId, query, options) {
28
+ return returnJsonApiDocument(requireDocument(await repository.getDocumentById(recordId, query, repositoryCallOptions(options))));
29
+ }
30
+
31
+ async function createDocument(payload, options) {
32
+ return returnJsonApiDocument(await repository.createDocument(payload, repositoryCallOptions(options)));
33
+ }
34
+
35
+ async function patchDocumentById(recordId, payload, options) {
36
+ return returnJsonApiDocument(requireDocument(await repository.patchDocumentById(recordId, payload, repositoryCallOptions(options))));
37
+ }
38
+
39
+ async function deleteDocumentById(recordId, options) {
40
+ return repository.deleteDocumentById(recordId, repositoryCallOptions(options));
14
41
  }
15
42
 
16
43
  return Object.freeze({
17
- async queryDocuments(query = {}, options = {}) {
18
- return returnJsonApiDocument(await repository.queryDocuments(query, {
19
- trx: options.trx || null,
20
- context: options.context || null
21
- }));
22
- },
23
- async getDocumentById(recordId, query = {}, options = {}) {
24
- return returnJsonApiDocument(requireDocument(await repository.getDocumentById(recordId, query, {
25
- trx: options.trx || null,
26
- context: options.context || null
27
- })));
28
- },
29
- async createDocument(payload = {}, options = {}) {
30
- return returnJsonApiDocument(await repository.createDocument(payload, {
31
- trx: options.trx || null,
32
- context: options.context || null
33
- }));
34
- },
35
- async patchDocumentById(recordId, payload = {}, options = {}) {
36
- return returnJsonApiDocument(requireDocument(await repository.patchDocumentById(recordId, payload, {
37
- trx: options.trx || null,
38
- context: options.context || null
39
- })));
40
- },
41
- async deleteDocumentById(recordId, options = {}) {
42
- return repository.deleteDocumentById(recordId, {
43
- trx: options.trx || null,
44
- context: options.context || null
45
- });
46
- }
44
+ queryDocuments,
45
+ getDocumentById,
46
+ createDocument,
47
+ patchDocumentById,
48
+ deleteDocumentById
47
49
  });
48
50
  }
49
51
 
50
- export { createCrudJsonApiService };
52
+ export { createCrudJsonApiService, repositoryCallOptions };
@@ -1,12 +1,9 @@
1
- import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
1
+ import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
2
  import { resolveCrudResourceScopeName } from "@jskit-ai/resource-crud-core/shared/crudLookup";
3
3
 
4
- function isRecord(value) {
5
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6
- }
7
-
8
4
  function resolveSchemaFieldDefinitions(definition = null) {
9
5
  const schema = definition?.schema;
6
+ // readable-check: allow method-probe - data: a resource schema without field definitions has none
10
7
  if (!schema || typeof schema.getFieldDefinitions !== "function") {
11
8
  return {};
12
9
  }
@@ -20,9 +17,9 @@ function resolveJsonApiRelationshipEntries(definition = null) {
20
17
 
21
18
  for (const [fieldKey, fieldDefinition] of Object.entries(resolveSchemaFieldDefinitions(definition))) {
22
19
  const normalizedFieldDefinition = isRecord(fieldDefinition) ? fieldDefinition : {};
23
- const relationshipType = String(normalizedFieldDefinition.belongsTo || "").trim();
20
+ const relationshipType = normalizeText(normalizedFieldDefinition.belongsTo);
24
21
  if (relationshipType) {
25
- const relationshipName = String(normalizedFieldDefinition.as || fieldKey || "").trim();
22
+ const relationshipName = normalizeText(normalizedFieldDefinition.as || fieldKey);
26
23
  if (!relationshipName) {
27
24
  continue;
28
25
  }
@@ -31,7 +28,7 @@ function resolveJsonApiRelationshipEntries(definition = null) {
31
28
  attributeKey: fieldKey,
32
29
  relationshipName,
33
30
  relationshipType,
34
- labelKey: String(normalizedFieldDefinition?.relation?.labelKey || "").trim(),
31
+ labelKey: normalizeText(normalizedFieldDefinition.relation?.labelKey),
35
32
  required: normalizedFieldDefinition.required === true,
36
33
  nullable: normalizedFieldDefinition.nullable === true
37
34
  }));
@@ -41,7 +38,7 @@ function resolveJsonApiRelationshipEntries(definition = null) {
41
38
  const relation = isRecord(normalizedFieldDefinition.relation)
42
39
  ? normalizedFieldDefinition.relation
43
40
  : {};
44
- if (String(relation.kind || "").trim().toLowerCase() !== "collection") {
41
+ if (normalizeText(relation.kind).toLowerCase() !== "collection") {
45
42
  continue;
46
43
  }
47
44
 
@@ -52,9 +49,7 @@ function resolveJsonApiRelationshipEntries(definition = null) {
52
49
  continue;
53
50
  }
54
51
 
55
- const collectionRelationshipName = String(
56
- relation.as || normalizedFieldDefinition.as || fieldKey || ""
57
- ).trim();
52
+ const collectionRelationshipName = normalizeText(relation.as || normalizedFieldDefinition.as || fieldKey);
58
53
  if (!collectionRelationshipName) {
59
54
  continue;
60
55
  }
@@ -63,7 +58,7 @@ function resolveJsonApiRelationshipEntries(definition = null) {
63
58
  attributeKey: fieldKey,
64
59
  relationshipName: collectionRelationshipName,
65
60
  relationshipType: collectionRelationshipType,
66
- labelKey: String(relation.labelKey || "").trim(),
61
+ labelKey: normalizeText(relation.labelKey),
67
62
  many: true,
68
63
  required: normalizedFieldDefinition.required === true,
69
64
  nullable: normalizedFieldDefinition.nullable === true
@@ -73,12 +68,20 @@ function resolveJsonApiRelationshipEntries(definition = null) {
73
68
  return Object.freeze(entries);
74
69
  }
75
70
 
76
- function resolveJsonApiFieldsetContract(resource = {}) {
77
- const primaryType = normalizeText(resource?.namespace);
78
- const relationshipEntries = resolveJsonApiRelationshipEntries(resource?.operations?.view?.output);
79
- const lookupContainerKey = normalizeText(resource?.contract?.lookup?.containerKey);
71
+ /**
72
+ * The lookup container key a resource's contract declares, or "" when it declares none.
73
+ * @param {import("./types.js").CrudResourceDefinition} resource
74
+ */
75
+ function resolveDeclaredLookupContainerKey(resource) {
76
+ return normalizeText(resource.contract?.lookup?.containerKey);
77
+ }
78
+
79
+ function resolveJsonApiFieldsetContract(resource) {
80
+ const primaryType = normalizeText(resource.namespace);
81
+ const relationshipEntries = resolveJsonApiRelationshipEntries(resource.operations?.view?.output);
82
+ const lookupContainerKey = resolveDeclaredLookupContainerKey(resource);
80
83
  const primaryFields = Object.freeze(
81
- Object.keys(resolveSchemaFieldDefinitions(resource?.operations?.view?.output))
84
+ Object.keys(resolveSchemaFieldDefinitions(resource.operations?.view?.output))
82
85
  .map((entry) => normalizeText(entry))
83
86
  .filter((entry) => entry && entry !== lookupContainerKey)
84
87
  );
@@ -113,6 +116,7 @@ function resolveJsonApiFieldsetContract(resource = {}) {
113
116
  }
114
117
 
115
118
  export {
119
+ resolveDeclaredLookupContainerKey,
116
120
  resolveJsonApiFieldsetContract,
117
121
  resolveJsonApiRelationshipEntries,
118
122
  resolveSchemaFieldDefinitions
@@ -0,0 +1,304 @@
1
+ import { normalizeObjectInput } from "@jskit-ai/kernel/shared/validators";
2
+ import {
3
+ isRecord,
4
+ normalizeObject,
5
+ normalizeText
6
+ } from "@jskit-ai/kernel/shared/support/normalize";
7
+ import {
8
+ defineCrudListFilters,
9
+ CRUD_LIST_FILTER_TYPE_FLAG,
10
+ CRUD_LIST_FILTER_TYPE_ENUM,
11
+ CRUD_LIST_FILTER_TYPE_ENUM_MANY,
12
+ CRUD_LIST_FILTER_TYPE_RECORD_ID,
13
+ CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY,
14
+ CRUD_LIST_FILTER_TYPE_DATE,
15
+ CRUD_LIST_FILTER_TYPE_DATE_RANGE,
16
+ CRUD_LIST_FILTER_TYPE_NUMBER_RANGE,
17
+ CRUD_LIST_FILTER_TYPE_PRESENCE,
18
+ CRUD_LIST_FILTER_PRESENCE_PRESENT,
19
+ CRUD_LIST_FILTER_PRESENCE_MISSING
20
+ } from "@jskit-ai/resource-crud-core/shared/crudListFilters";
21
+ import {
22
+ recordIdTransportSchema,
23
+ cloneTransportSchema,
24
+ addDaysToDateFilterValue,
25
+ applyDefaultFilterQuery
26
+ } from "./listFilterTypes.js";
27
+
28
+ const JSON_REST_INTERNAL_FILTER_PREFIX = "__jskit";
29
+
30
+ function normalizeColumnsMap(columns = {}) {
31
+ const source = normalizeObject(columns);
32
+ const normalized = {};
33
+ for (const [key, value] of Object.entries(source)) {
34
+ const normalizedKey = normalizeText(key);
35
+ const normalizedValue = normalizeText(value);
36
+ if (!normalizedKey || !normalizedValue) {
37
+ continue;
38
+ }
39
+
40
+ normalized[normalizedKey] = normalizedValue;
41
+ }
42
+
43
+ return Object.freeze(normalized);
44
+ }
45
+
46
+ function resolveJsonRestFilterActualField(filter = {}, columns = {}) {
47
+ const meta = isRecord(filter.meta?.jsonRest) ? filter.meta.jsonRest : {};
48
+ return normalizeText(meta.actualField || meta.column || columns[filter.key] || filter.key);
49
+ }
50
+
51
+ function renderInternalJsonRestFilterKey(filter = {}, suffix = "") {
52
+ return [
53
+ JSON_REST_INTERNAL_FILTER_PREFIX,
54
+ filter.queryKey,
55
+ suffix
56
+ ]
57
+ .map((entry) => normalizeText(entry))
58
+ .filter(Boolean)
59
+ .join("_");
60
+ }
61
+
62
+ function buildJsonRestSearchSchemaEntry({
63
+ type = "string",
64
+ actualField = "",
65
+ filterOperator = "=",
66
+ extra = {}
67
+ } = {}) {
68
+ return {
69
+ type,
70
+ ...(actualField ? { actualField } : {}),
71
+ ...(filterOperator ? { filterOperator } : {}),
72
+ ...extra
73
+ };
74
+ }
75
+
76
+ function buildJsonRestFilterItemSchema(filter = {}) {
77
+ if (filter.type === CRUD_LIST_FILTER_TYPE_ENUM_MANY) {
78
+ return {
79
+ type: "string",
80
+ enum: (Array.isArray(filter.options) ? filter.options : []).map((entry) => entry.value)
81
+ };
82
+ }
83
+
84
+ if (filter.type === CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY) {
85
+ return cloneTransportSchema(recordIdTransportSchema);
86
+ }
87
+
88
+ return {};
89
+ }
90
+
91
+ function buildJsonRestSimpleFilterSearchSchemaEntry(filter = {}, { actualField = "" } = {}) {
92
+ if (filter.type === CRUD_LIST_FILTER_TYPE_FLAG) {
93
+ return buildJsonRestSearchSchemaEntry({
94
+ type: "boolean",
95
+ actualField,
96
+ filterOperator: "="
97
+ });
98
+ }
99
+
100
+ if (filter.type === CRUD_LIST_FILTER_TYPE_ENUM) {
101
+ return buildJsonRestSearchSchemaEntry({
102
+ type: "string",
103
+ actualField,
104
+ filterOperator: "=",
105
+ extra: {
106
+ enum: (Array.isArray(filter.options) ? filter.options : []).map((entry) => entry.value)
107
+ }
108
+ });
109
+ }
110
+
111
+ if (filter.type === CRUD_LIST_FILTER_TYPE_ENUM_MANY || filter.type === CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY) {
112
+ return buildJsonRestSearchSchemaEntry({
113
+ type: "array",
114
+ actualField,
115
+ filterOperator: "in",
116
+ extra: {
117
+ items: buildJsonRestFilterItemSchema(filter)
118
+ }
119
+ });
120
+ }
121
+
122
+ if (filter.type === CRUD_LIST_FILTER_TYPE_RECORD_ID) {
123
+ return buildJsonRestSearchSchemaEntry({
124
+ type: "id",
125
+ actualField,
126
+ filterOperator: "="
127
+ });
128
+ }
129
+
130
+ return null;
131
+ }
132
+
133
+ function buildJsonRestRangeFilterSearchSchemaEntries(filter = {}, { actualField = "" } = {}) {
134
+ if (filter.type === CRUD_LIST_FILTER_TYPE_DATE || filter.type === CRUD_LIST_FILTER_TYPE_DATE_RANGE) {
135
+ return {
136
+ [renderInternalJsonRestFilterKey(filter, "from")]: buildJsonRestSearchSchemaEntry({
137
+ type: "dateTime",
138
+ actualField,
139
+ filterOperator: ">="
140
+ }),
141
+ [renderInternalJsonRestFilterKey(filter, "toExclusive")]: buildJsonRestSearchSchemaEntry({
142
+ type: "dateTime",
143
+ actualField,
144
+ filterOperator: "<"
145
+ })
146
+ };
147
+ }
148
+
149
+ if (filter.type === CRUD_LIST_FILTER_TYPE_NUMBER_RANGE) {
150
+ return {
151
+ [renderInternalJsonRestFilterKey(filter, "min")]: buildJsonRestSearchSchemaEntry({
152
+ type: "number",
153
+ actualField,
154
+ filterOperator: ">="
155
+ }),
156
+ [renderInternalJsonRestFilterKey(filter, "max")]: buildJsonRestSearchSchemaEntry({
157
+ type: "number",
158
+ actualField,
159
+ filterOperator: "<="
160
+ })
161
+ };
162
+ }
163
+
164
+ return {};
165
+ }
166
+
167
+ function buildJsonRestPresenceFilterSearchSchemaEntry(filter = {}, { actualField = "" } = {}) {
168
+ return {
169
+ type: "string",
170
+ enum: [CRUD_LIST_FILTER_PRESENCE_PRESENT, CRUD_LIST_FILTER_PRESENCE_MISSING],
171
+ applyFilter(queryBuilder, value) {
172
+ applyDefaultFilterQuery(queryBuilder, filter, value, actualField);
173
+ }
174
+ };
175
+ }
176
+
177
+ function buildJsonRestCustomFilterSearchSchemaEntry(filter, customApply) {
178
+ return {
179
+ type: "none",
180
+ applyFilter(queryBuilder, value) {
181
+ customApply(queryBuilder, value, {
182
+ filter,
183
+ filters: Object.freeze({
184
+ [filter.key]: value
185
+ })
186
+ });
187
+ }
188
+ };
189
+ }
190
+
191
+ function resolveCrudListFilterEntries(value = {}) {
192
+ if (isRecord(value.filters)) {
193
+ return Object.values(normalizeObject(value.filters));
194
+ }
195
+
196
+ return Object.values(defineCrudListFilters(value));
197
+ }
198
+
199
+ function createCrudListFilterJsonRestSearchSchema(runtime = {}, { columns = {}, apply = {} } = {}) {
200
+ const filterEntries = resolveCrudListFilterEntries(runtime);
201
+ const normalizedColumns = normalizeColumnsMap(columns);
202
+ const schema = {};
203
+
204
+ for (const filter of filterEntries) {
205
+ // readable-check: allow method-probe - input validation: apply holds an application's optional custom filters; other filters use the default
206
+ const customApply = typeof apply[filter.key] === "function" ? apply[filter.key] : null;
207
+ if (customApply) {
208
+ schema[filter.queryKey] = buildJsonRestCustomFilterSearchSchemaEntry(filter, customApply);
209
+ continue;
210
+ }
211
+
212
+ const actualField = resolveJsonRestFilterActualField(filter, normalizedColumns);
213
+ if (!actualField) {
214
+ continue;
215
+ }
216
+
217
+ const simpleEntry = buildJsonRestSimpleFilterSearchSchemaEntry(filter, { actualField });
218
+ if (simpleEntry) {
219
+ schema[filter.queryKey] = simpleEntry;
220
+ continue;
221
+ }
222
+
223
+ if (filter.type === CRUD_LIST_FILTER_TYPE_PRESENCE) {
224
+ schema[filter.queryKey] = buildJsonRestPresenceFilterSearchSchemaEntry(filter, { actualField });
225
+ continue;
226
+ }
227
+
228
+ Object.assign(schema, buildJsonRestRangeFilterSearchSchemaEntries(filter, { actualField }));
229
+ }
230
+
231
+ return Object.freeze(schema);
232
+ }
233
+
234
+ function addJsonRestDateFilterValues(target = {}, filter = {}, value = "") {
235
+ const nextDate = addDaysToDateFilterValue(value, 1);
236
+ if (value) {
237
+ target[renderInternalJsonRestFilterKey(filter, "from")] = `${value} 00:00:00`;
238
+ }
239
+ if (nextDate) {
240
+ target[renderInternalJsonRestFilterKey(filter, "toExclusive")] = `${nextDate} 00:00:00`;
241
+ }
242
+ }
243
+
244
+ function addJsonRestFilterValue(target = {}, filter = {}, value) {
245
+ if (filter.type === CRUD_LIST_FILTER_TYPE_DATE) {
246
+ addJsonRestDateFilterValues(target, filter, value);
247
+ return;
248
+ }
249
+
250
+ if (filter.type === CRUD_LIST_FILTER_TYPE_DATE_RANGE) {
251
+ if (value?.from) {
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;
261
+ }
262
+
263
+ if (filter.type === CRUD_LIST_FILTER_TYPE_NUMBER_RANGE) {
264
+ if (value?.min != null) {
265
+ target[renderInternalJsonRestFilterKey(filter, "min")] = value.min;
266
+ }
267
+ if (value?.max != null) {
268
+ target[renderInternalJsonRestFilterKey(filter, "max")] = value.max;
269
+ }
270
+ return;
271
+ }
272
+
273
+ target[filter.queryKey] = value;
274
+ }
275
+
276
+ function normalizeCrudListFilterJsonRestQuery(runtime = {}, query = {}) {
277
+ const source = normalizeObjectInput(query);
278
+ const filterEntries = Object.values(normalizeObject(runtime.filters));
279
+ const filterQueryKeys = new Set(filterEntries.map((filter) => filter.queryKey));
280
+ const parsedFilters = runtime.parseQuery(source);
281
+ const normalized = {};
282
+
283
+ for (const [key, value] of Object.entries(source)) {
284
+ if (!filterQueryKeys.has(key)) {
285
+ normalized[key] = value;
286
+ }
287
+ }
288
+
289
+ for (const filter of filterEntries) {
290
+ if (!Object.hasOwn(parsedFilters, filter.key)) {
291
+ continue;
292
+ }
293
+
294
+ addJsonRestFilterValue(normalized, filter, parsedFilters[filter.key]);
295
+ }
296
+
297
+ return normalized;
298
+ }
299
+
300
+ export {
301
+ normalizeColumnsMap,
302
+ createCrudListFilterJsonRestSearchSchema,
303
+ normalizeCrudListFilterJsonRestQuery
304
+ };