@jskit-ai/crud-core 0.2.2 → 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
@@ -1,419 +1,25 @@
1
1
  import {
2
2
  composeSchemaDefinitions,
3
- createSchema,
4
3
  recordIdParamsValidator
5
4
  } from "@jskit-ai/kernel/shared/validators";
6
5
  import { RestApiWriteError } from "json-rest-api";
7
- import { normalizeJsonApiFieldsets } from "@jskit-ai/kernel/shared/support/jsonApiFieldsets";
6
+ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
8
7
  import { ARCHITECTURE_ID_PATTERN } from "@jskit-ai/kernel/shared/capabilities";
9
- import { createEntityChangedActionEvent } from "@jskit-ai/kernel/server/actions";
10
- import {
11
- decodeJsonApiResourceResponse,
12
- normalizeJsonApiDocument,
13
- unwrapJsonApiResult
14
- } from "@jskit-ai/http-runtime/shared";
15
- import { resolveCrudRecordChangedEvent } from "@jskit-ai/resource-crud-core/shared/crudNamespaceSupport";
16
- import {
17
- resolveJsonApiFieldsetContract,
18
- resolveJsonApiRelationshipEntries,
19
- resolveSchemaFieldDefinitions
20
- } from "../jsonApiResourceContract.js";
8
+ import { ACTION_INPUT_DEFAULT_MODE } from "@jskit-ai/kernel/server/actions";
21
9
  import {
22
10
  createJsonApiFieldsetsQueryValidator,
23
11
  createStandardCrudListQueryValidators,
24
12
  createStandardCrudViewQueryValidators
25
13
  } from "../listQueryValidators.js";
14
+ import { buildCrudRecordChangedEvent, resolveCrudJsonApiEntityIdFromResult } from "../serviceEvents.js";
15
+ import { createCrudAssistantExtension } from "./assistantExtension.js";
16
+ import { buildCrudCustomActionId } from "./customActionId.js";
26
17
 
27
18
  const CRUD_OPERATION_NAMES = Object.freeze(["list", "view", "create", "update", "delete"]);
28
19
  const CRUD_MUTATION_NAMES = new Set(["create", "update", "delete"]);
29
20
  const CRUD_LIFECYCLE_PHASES = Object.freeze(["before", "execute", "after", "afterCommit"]);
30
- const CRUD_ASSISTANT_RESOURCE_OPERATION = Object.freeze({
31
- list: "list",
32
- view: "view",
33
- create: "create",
34
- update: "patch",
35
- delete: "delete"
36
- });
37
-
38
- function isRecord(value) {
39
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
40
- }
41
-
42
- function normalizeOptionalCursor(value) {
43
- if (value == null) {
44
- return null;
45
- }
46
- const normalized = String(value).trim();
47
- return normalized || null;
48
- }
49
-
50
- function resolveAssistantResultValue(result) {
51
- const taggedResult = unwrapJsonApiResult(result);
52
- const value = taggedResult ? taggedResult.value : result;
53
- const document = normalizeJsonApiDocument(value);
54
- return {
55
- value,
56
- document
57
- };
58
- }
59
-
60
- function createProjectionRecordSchema(recordSchema, {
61
- lookupContainerKey = "",
62
- relationshipEntries = []
63
- } = {}) {
64
- const definitions = recordSchema?.getFieldDefinitions?.();
65
- if (!isRecord(definitions)) {
66
- return recordSchema;
67
- }
68
-
69
- const fields = Object.fromEntries(
70
- Object.entries(definitions).map(([fieldKey, fieldDefinition]) => [
71
- fieldKey,
72
- {
73
- ...fieldDefinition,
74
- required: fieldKey === "id" && fieldDefinition?.required === true
75
- }
76
- ])
77
- );
78
- if (lookupContainerKey && isRecord(fields[lookupContainerKey])) {
79
- const createRelatedRecordSchema = (entry) => createSchema({
80
- id: {
81
- type: "string",
82
- required: true
83
- },
84
- ...(entry.labelKey && entry.labelKey !== "id"
85
- ? {
86
- [entry.labelKey]: {
87
- type: "string",
88
- required: false,
89
- nullable: true
90
- }
91
- }
92
- : {})
93
- });
94
- const lookupFields = Object.fromEntries(
95
- relationshipEntries.map((entry) => [
96
- entry.relationshipName,
97
- entry.many === true
98
- ? {
99
- type: "array",
100
- required: false,
101
- items: {
102
- type: "object",
103
- schema: createRelatedRecordSchema(entry),
104
- additionalProperties: true
105
- }
106
- }
107
- : {
108
- type: "object",
109
- required: false,
110
- schema: createRelatedRecordSchema(entry),
111
- additionalProperties: true
112
- }
113
- ])
114
- );
115
- fields[lookupContainerKey] = {
116
- ...fields[lookupContainerKey],
117
- type: "object",
118
- required: false,
119
- ...(Object.keys(lookupFields).length > 0 ? { schema: createSchema(lookupFields) } : {}),
120
- additionalProperties: true
121
- };
122
- }
123
-
124
- return createSchema(fields);
125
- }
126
-
127
- function createProjectionOutputDefinition(output, operation, relationshipEntries, lookupContainerKey) {
128
- if (!output || (operation !== "list" && operation !== "view")) {
129
- return output;
130
- }
131
-
132
- if (operation === "view") {
133
- return Object.freeze({
134
- schema: createProjectionRecordSchema(output.schema, { lookupContainerKey, relationshipEntries }),
135
- mode: "replace"
136
- });
137
- }
138
-
139
- const listFields = resolveSchemaFieldDefinitions(output);
140
- const items = listFields.items;
141
- if (!isRecord(items) || items.type !== "array" || typeof items.items?.getFieldDefinitions !== "function") {
142
- return output;
143
- }
144
-
145
- return Object.freeze({
146
- schema: createSchema({
147
- ...listFields,
148
- items: {
149
- ...items,
150
- items: createProjectionRecordSchema(items.items, { lookupContainerKey, relationshipEntries })
151
- }
152
- }),
153
- mode: "replace"
154
- });
155
- }
156
-
157
- function createCrudAssistantTransport(resource, operation, relationshipEntries, lookupContainerKey) {
158
- const lookupFieldMap = Object.fromEntries(
159
- relationshipEntries
160
- .filter((entry) => entry.many !== true)
161
- .map((entry) => [entry.relationshipName, entry.attributeKey])
162
- );
163
- return Object.freeze({
164
- kind: "jsonapi-resource",
165
- responseType: resource.namespace,
166
- responseKind: operation === "list" ? "collection" : "record",
167
- ...(lookupContainerKey ? { lookupContainerKey } : {}),
168
- ...(Object.keys(lookupFieldMap).length > 0 ? { lookupFieldMap } : {})
169
- });
170
- }
171
-
172
- function projectCrudAssistantRecordFields(record, selectedFields = null, {
173
- preserveKeys = []
174
- } = {}) {
175
- if (!isRecord(record) || !Array.isArray(selectedFields)) {
176
- return record;
177
- }
178
-
179
- const allowedKeys = new Set(["id", ...preserveKeys, ...selectedFields]);
180
- return Object.fromEntries(
181
- Object.entries(record).filter(([key]) => allowedKeys.has(key))
182
- );
183
- }
184
-
185
- function projectCrudAssistantLookupValue(value, selectedFields = null) {
186
- if (Array.isArray(value)) {
187
- return value.map((entry) => projectCrudAssistantRecordFields(entry, selectedFields));
188
- }
189
- return projectCrudAssistantRecordFields(value, selectedFields);
190
- }
191
-
192
- function projectCrudAssistantReadRecord(record, {
193
- lookupContainerKey = "",
194
- primaryFields = null,
195
- relatedFieldsByLookupKey = new Map()
196
- } = {}) {
197
- if (!isRecord(record)) {
198
- return record;
199
- }
200
-
201
- const primaryProjection = projectCrudAssistantRecordFields(record, primaryFields, {
202
- preserveKeys: lookupContainerKey && isRecord(record[lookupContainerKey])
203
- ? [lookupContainerKey]
204
- : []
205
- });
206
- const projectedRecord = primaryProjection === record ? { ...record } : primaryProjection;
207
- if (!lookupContainerKey || !isRecord(projectedRecord[lookupContainerKey])) {
208
- return projectedRecord;
209
- }
210
-
211
- projectedRecord[lookupContainerKey] = Object.fromEntries(
212
- Object.entries(projectedRecord[lookupContainerKey]).map(([lookupKey, value]) => {
213
- return [
214
- lookupKey,
215
- projectCrudAssistantLookupValue(value, relatedFieldsByLookupKey.get(lookupKey))
216
- ];
217
- })
218
- );
219
- return projectedRecord;
220
- }
221
-
222
- function createCrudAssistantResultProjection(input = {}, resource = {}, relationshipEntries = []) {
223
- const primaryType = String(resource?.namespace || "").trim();
224
- const fieldsets = normalizeJsonApiFieldsets(input?.fields, {
225
- primaryType
226
- });
227
- if (Object.keys(fieldsets).length < 1) {
228
- return null;
229
- }
230
-
231
- const relatedFieldsByLookupKey = new Map();
232
- for (const entry of relationshipEntries) {
233
- const selectedFields = fieldsets[entry.relationshipType];
234
- if (!Array.isArray(selectedFields)) {
235
- continue;
236
- }
237
- relatedFieldsByLookupKey.set(entry.relationshipName, selectedFields);
238
- relatedFieldsByLookupKey.set(entry.attributeKey, selectedFields);
239
- }
240
-
241
- return {
242
- primaryFields: fieldsets[primaryType],
243
- relatedFieldsByLookupKey
244
- };
245
- }
246
-
247
- function projectCrudAssistantReadResult(result, projection = null, {
248
- lookupContainerKey = ""
249
- } = {}) {
250
- if (!projection) {
251
- return result;
252
- }
253
-
254
- const projectionOptions = {
255
- ...projection,
256
- lookupContainerKey
257
- };
258
- if (isRecord(result) && Array.isArray(result.items)) {
259
- return {
260
- ...result,
261
- items: result.items.map((entry) => projectCrudAssistantReadRecord(entry, projectionOptions))
262
- };
263
- }
264
-
265
- return projectCrudAssistantReadRecord(result, projectionOptions);
266
- }
267
-
268
- function transformCrudAssistantResult(operation, result, {
269
- input = {},
270
- resource,
271
- relationshipEntries = [],
272
- lookupContainerKey = ""
273
- } = {}) {
274
- if (operation === "delete") {
275
- const resolved = resolveAssistantResultValue(result);
276
- if (isRecord(resolved.value) && resolved.value.deleted === true && resolved.value.id != null) {
277
- return resolved.value;
278
- }
279
- return {
280
- id: String(input.recordId || ""),
281
- deleted: true
282
- };
283
- }
284
-
285
- const resolved = resolveAssistantResultValue(result);
286
- const projection = operation === "list" || operation === "view"
287
- ? createCrudAssistantResultProjection(input, resource, relationshipEntries)
288
- : null;
289
- const projectReadResult = (value) => projectCrudAssistantReadResult(value, projection, {
290
- lookupContainerKey
291
- });
292
- if (operation === "list") {
293
- if (resolved.document.kind === "collection") {
294
- const decoded = decodeJsonApiResourceResponse(
295
- resolved.value,
296
- createCrudAssistantTransport(resource, operation, relationshipEntries, lookupContainerKey)
297
- );
298
- return projectReadResult({
299
- items: decoded.items,
300
- nextCursor: normalizeOptionalCursor(decoded.nextCursor)
301
- });
302
- }
303
- if (Array.isArray(resolved.value)) {
304
- return projectReadResult({
305
- items: resolved.value,
306
- nextCursor: null
307
- });
308
- }
309
- if (isRecord(resolved.value) && Array.isArray(resolved.value.items)) {
310
- return projectReadResult({
311
- items: resolved.value.items,
312
- nextCursor: normalizeOptionalCursor(resolved.value.nextCursor)
313
- });
314
- }
315
- return resolved.value;
316
- }
317
-
318
- if (resolved.document.kind === "resource") {
319
- return projectReadResult(decodeJsonApiResourceResponse(
320
- resolved.value,
321
- createCrudAssistantTransport(resource, operation, relationshipEntries, lookupContainerKey)
322
- ));
323
- }
324
- return projectReadResult(resolved.value);
325
- }
326
-
327
- function createCrudAssistantReadDescription({
328
- fieldsetContract,
329
- lookupContainerKey = "",
330
- namespace = "",
331
- operation = "list"
332
- } = {}) {
333
- const relationshipEntries = fieldsetContract.relationshipEntries;
334
- const firstRelationship = relationshipEntries[0] || null;
335
- const includeExample = relationshipEntries.length > 0
336
- ? relationshipEntries.slice(0, 2).map((entry) => entry.relationshipName).join(",")
337
- : "pet,service";
338
- const fieldsExample = firstRelationship
339
- ? ` fields can be {\"${namespace}\":[\"${firstRelationship.attributeKey}\"],` +
340
- `\"${firstRelationship.relationshipType}\":[\"${firstRelationship.labelKey || "id"}\"]}.`
341
- : ` fields can be {\"${namespace}\":[\"id\"]}.`;
342
- const aliasGuidance = fieldsetContract.aliasMappings
343
- .map((entry) => `use \"${entry.resourceType}\" instead of \"${entry.alias}\"`)
344
- .join("; ");
345
- const fieldsetKeyGuidance = fieldsetContract.resourceTypes.length > 0
346
- ? ` fields keys must be JSON:API resource types: ${fieldsetContract.resourceTypes.map((entry) => `\"${entry}\"`).join(", ")}.` +
347
- (aliasGuidance ? ` Relationship aliases are invalid fieldset keys; ${aliasGuidance}.` : "")
348
- : "";
349
- const primaryFieldGuidance = fieldsetContract.primaryFields.length > 0
350
- ? ` Valid \"${namespace}\" fields: ${fieldsetContract.primaryFields.map((entry) => `\"${entry}\"`).join(", ")}.`
351
- : "";
352
- const relationshipGuidance = relationshipEntries.length > 0
353
- ? ` Include relationships: ${relationshipEntries.map((entry) => {
354
- const lookupPath = lookupContainerKey
355
- ? ` -> ${operation === "list" ? "items[]." : ""}${lookupContainerKey}.${entry.relationshipName}`
356
- : "";
357
- return `\"${entry.relationshipName}\" -> resource type \"${entry.relationshipType}\"${lookupPath}`;
358
- }).join("; ")}.`
359
- : "";
360
21
 
361
- const subject = operation === "list" ? `List ${namespace} records.` : `View a ${namespace} record.`;
362
- return `${subject} include must be a comma-separated string such as \"${includeExample}\";` +
363
- `${fieldsExample}${fieldsetKeyGuidance}${primaryFieldGuidance}${relationshipGuidance}`;
364
- }
365
-
366
- function createCrudAssistantExtension(resource, namespace, operation) {
367
- const resourceOperation = CRUD_ASSISTANT_RESOURCE_OPERATION[operation];
368
- const nativeOutput = resource?.operations?.[resourceOperation]?.output || null;
369
- const recordOutput = operation === "list"
370
- ? Object.freeze({
371
- schema: resolveSchemaFieldDefinitions(nativeOutput).items?.items,
372
- mode: "replace"
373
- })
374
- : nativeOutput;
375
- const relationshipEntries = resolveJsonApiRelationshipEntries(recordOutput);
376
- const lookupContainerKey = String(resource?.contract?.lookup?.containerKey || "").trim();
377
- const output = createProjectionOutputDefinition(
378
- nativeOutput,
379
- operation,
380
- relationshipEntries,
381
- lookupContainerKey
382
- );
383
- const actionLabel = operation === "list" || operation === "view"
384
- ? createCrudAssistantReadDescription({
385
- fieldsetContract: resolveJsonApiFieldsetContract(resource),
386
- lookupContainerKey,
387
- namespace,
388
- operation
389
- })
390
- : operation === "create"
391
- ? `Create a ${namespace} record.`
392
- : operation === "update"
393
- ? `Update a ${namespace} record.`
394
- : `Delete a ${namespace} record.`;
395
-
396
- return Object.freeze({
397
- description: actionLabel,
398
- output,
399
- transformResult(result, context) {
400
- return transformCrudAssistantResult(operation, result, {
401
- ...context,
402
- resource,
403
- relationshipEntries,
404
- lookupContainerKey
405
- });
406
- }
407
- });
408
- }
409
-
410
- function createActionInput(
411
- resource,
412
- operation,
413
- scopeInputValidator = null,
414
- listFilterQueryValidator = null,
415
- operationInputs = {}
416
- ) {
22
+ function buildActionInput(resource, operation, scopeInputValidator, listFilterQueryValidator, operationInputs) {
417
23
  const definitions = scopeInputValidator ? [scopeInputValidator] : [];
418
24
  if (operation === "list") {
419
25
  definitions.push(...createStandardCrudListQueryValidators({
@@ -433,18 +39,23 @@ function createActionInput(
433
39
  definitions.push(recordIdParamsValidator);
434
40
  }
435
41
 
436
- return composeSchemaDefinitions(definitions, operation === "create" ? { mode: "create" } : {});
42
+ // Only update changes part of a record; every other operation's input is strict.
43
+ return composeSchemaDefinitions(definitions, { mode: operation === "update" ? "patch" : "create" });
437
44
  }
438
45
 
439
- function omitInputKeys(input = {}, keys = []) {
440
- const result = { ...(input && typeof input === "object" && !Array.isArray(input) ? input : {}) };
46
+ /**
47
+ * @param {object} input
48
+ * @param {readonly string[]} keys
49
+ */
50
+ function omitInputKeys(input, keys) {
51
+ const result = { ...(isRecord(input) ? input : {}) };
441
52
  for (const key of keys) {
442
53
  delete result[key];
443
54
  }
444
55
  return result;
445
56
  }
446
57
 
447
- function normalizeCrudOperationLifecycle(value = {}) {
58
+ function normalizeCrudOperationLifecycle(value) {
448
59
  if (!value || typeof value !== "object" || Array.isArray(value)) {
449
60
  throw new TypeError("CRUD operationLifecycle must be an object.");
450
61
  }
@@ -459,6 +70,7 @@ function normalizeCrudOperationLifecycle(value = {}) {
459
70
  if (!CRUD_LIFECYCLE_PHASES.includes(name)) {
460
71
  throw new TypeError(`CRUD operationLifecycle.${operation} has unknown phase "${name}".`);
461
72
  }
73
+ // readable-check: allow method-probe - input validation: each operationLifecycle phase an application passes must be a function
462
74
  if (typeof hooks[name] !== "function") {
463
75
  throw new TypeError(`CRUD operationLifecycle.${operation}.${name} must be a function.`);
464
76
  }
@@ -471,18 +83,8 @@ function normalizeCrudOperationLifecycle(value = {}) {
471
83
  return Object.freeze(lifecycle);
472
84
  }
473
85
 
474
- function createLifecycleContext(value = {}) {
475
- const {
476
- operation,
477
- input,
478
- context,
479
- resource,
480
- repository,
481
- service,
482
- trx = null,
483
- result,
484
- standard
485
- } = value;
86
+ function buildLifecycleContext(value) {
87
+ const { operation, input, context, resource, repository, service, trx, result, standard } = value;
486
88
  return Object.freeze({
487
89
  operation,
488
90
  input,
@@ -492,21 +94,12 @@ function createLifecycleContext(value = {}) {
492
94
  service,
493
95
  trx,
494
96
  ...(Object.hasOwn(value, "result") ? { result } : {}),
495
- ...(typeof standard === "function" ? { standard } : {})
97
+ ...(standard ? { standard } : {})
496
98
  });
497
99
  }
498
100
 
499
- function normalizeAdditionalActions(value = {}, {
500
- namespace,
501
- surface,
502
- permissionForAction,
503
- scopeInputValidator = null
504
- } = {}) {
505
- if (!value || typeof value !== "object" || Array.isArray(value)) {
506
- throw new TypeError("CRUD actions must be an object.");
507
- }
508
-
509
- return Object.freeze(Object.entries(value).map(([name, definition]) => {
101
+ function normalizeAdditionalActions(definitions, { namespace, surface, permissionForAction, scopeInputValidator }) {
102
+ return Object.freeze(Object.entries(definitions).map(([name, definition]) => {
510
103
  const actionName = String(name || "").trim();
511
104
  if (!ARCHITECTURE_ID_PATTERN.test(actionName)) {
512
105
  throw new TypeError(`CRUD custom action name "${actionName}" is invalid.`);
@@ -517,116 +110,165 @@ function normalizeAdditionalActions(value = {}, {
517
110
  if (!definition || typeof definition !== "object" || Array.isArray(definition)) {
518
111
  throw new TypeError(`CRUD custom action "${actionName}" must be an object.`);
519
112
  }
113
+ // readable-check: allow method-probe - input validation: an application's custom action must have execute()
520
114
  if (typeof definition.execute !== "function") {
521
115
  throw new TypeError(`CRUD custom action "${actionName}" requires execute().`);
522
116
  }
523
117
  if (!definition.input || typeof definition.input !== "object" || Array.isArray(definition.input)) {
524
118
  throw new TypeError(`CRUD custom action "${actionName}" requires an input schema.`);
525
119
  }
120
+ if (Object.hasOwn(definition, "idempotency")) {
121
+ throw new TypeError(`CRUD custom action "${actionName}" declares idempotency. Action definitions no longer declare idempotency.`);
122
+ }
526
123
 
527
124
  const kind = definition.kind || "command";
528
125
  return Object.freeze({
529
126
  ...definition,
530
127
  name: actionName,
531
- id: String(definition.id || `${namespace}.${actionName}`).trim(),
128
+ id: buildCrudCustomActionId(namespace, actionName, definition),
532
129
  version: definition.version || 1,
533
130
  kind,
534
131
  channels: definition.channels || ["api", "automation", "internal"],
535
132
  surfaces: definition.surfaces || [surface],
536
133
  permission: definition.permission || permissionForAction(actionName),
537
134
  input: scopeInputValidator
538
- ? composeSchemaDefinitions([scopeInputValidator, definition.input])
135
+ ? composeSchemaDefinitions([scopeInputValidator, definition.input], {
136
+ mode: definition.input.mode || ACTION_INPUT_DEFAULT_MODE
137
+ })
539
138
  : definition.input,
540
- idempotency: definition.idempotency || (kind === "query" ? "none" : "optional"),
541
139
  events: definition.events || []
542
140
  });
543
141
  }));
544
142
  }
545
143
 
144
+ /**
145
+ * The standard and custom actions of one CRUD feature, from the options
146
+ * defineCrudJsonApiFeature resolved.
147
+ * @param {object} dependencies
148
+ * @param {string} dependencies.namespace
149
+ * @param {import("../types.js").CrudResourceDefinition} dependencies.resource
150
+ * @param {import("../types.js").CrudRepository} dependencies.repository
151
+ * @param {import("../types.js").CrudService} dependencies.service
152
+ * @param {string} dependencies.surface
153
+ * @param {(operation: string) => object} dependencies.permissionForOperation Also answers for each custom action's name.
154
+ * @param {readonly string[]} dependencies.operations
155
+ * @param {object | null} dependencies.scopeInputValidator
156
+ * @param {readonly string[]} dependencies.scopeInputKeys
157
+ * @param {object | null} dependencies.listFilterQueryValidator
158
+ * @param {import("../types.js").CrudOperationLifecycle} dependencies.operationLifecycle What normalizeCrudOperationLifecycle returned.
159
+ * @param {{ create?: object, update?: object }} dependencies.operationInputs
160
+ * @param {Record<string, object>} dependencies.actions The feature's custom actions, by name.
161
+ * @param {Record<string, unknown>} dependencies.dependencies The capabilities in the feature's `requires`, by local name.
162
+ * @param {string} dependencies.realtimeAudience
163
+ */
546
164
  function createCrudJsonApiActions({
547
165
  namespace,
548
166
  resource,
549
- repository = null,
167
+ repository,
550
168
  service,
551
169
  surface,
552
170
  permissionForOperation,
553
- permissionForAction = permissionForOperation,
554
- operations = CRUD_OPERATION_NAMES,
555
- scopeInputValidator = null,
556
- scopeInputKeys = [],
557
- listFilterQueryValidator = null,
558
- operationLifecycle = {},
559
- operationInputs = {},
560
- actions: additionalActionDefinitions = {},
561
- dependencies = {},
562
- realtimeAudience = "event_scope"
563
- } = {}) {
564
- const actionId = (operation) => `crud.${namespace}.${operation}`;
565
- if (!service || typeof service !== "object") {
566
- throw new TypeError("createCrudJsonApiActions requires service.");
567
- }
568
- const permission = (operation) => permissionForOperation(operation);
569
- const input = (operation) => createActionInput(
570
- resource,
571
- operation,
572
- scopeInputValidator,
573
- listFilterQueryValidator,
574
- operationInputs
575
- );
576
- const recordChangedEvent = resolveCrudRecordChangedEvent(namespace);
577
- const mutationEvent = (operation, entityId) => createEntityChangedActionEvent({
578
- source: "crud",
579
- entity: "record",
171
+ operations,
172
+ scopeInputValidator,
173
+ scopeInputKeys,
174
+ listFilterQueryValidator,
175
+ operationLifecycle,
176
+ operationInputs,
177
+ actions,
178
+ dependencies,
179
+ realtimeAudience
180
+ }) {
181
+ const mutationEvent = (operation, entityId) => buildCrudRecordChangedEvent({
182
+ namespace,
580
183
  operation,
581
184
  entityId,
582
- realtime: {
583
- event: recordChangedEvent,
584
- audience: realtimeAudience
585
- }
185
+ audience: realtimeAudience
586
186
  });
587
- const lifecycle = normalizeCrudOperationLifecycle(operationLifecycle);
588
- const additionalActions = normalizeAdditionalActions(additionalActionDefinitions, {
187
+ const additionalActions = normalizeAdditionalActions(actions, {
589
188
  namespace,
590
189
  surface,
591
- permissionForAction,
190
+ permissionForAction: permissionForOperation,
592
191
  scopeInputValidator
593
192
  });
594
193
 
595
- async function executeOperation(operation, value, context, defaultExecute) {
596
- const hooks = lifecycle[operation];
194
+ function listDocuments(input, context) {
195
+ return service.queryDocuments(omitInputKeys(input, scopeInputKeys), { context });
196
+ }
197
+
198
+ function viewDocument(input, context) {
199
+ return service.getDocumentById(input.recordId, omitInputKeys(input, [...scopeInputKeys, "recordId"]), { context });
200
+ }
201
+
202
+ function createDocument(input, context, trx) {
203
+ return service.createDocument(omitInputKeys(input, scopeInputKeys), { context, trx });
204
+ }
205
+
206
+ function updateDocument(input, context, trx) {
207
+ return service.patchDocumentById(input.recordId, omitInputKeys(input, [...scopeInputKeys, "recordId"]), { context, trx });
208
+ }
209
+
210
+ function deleteDocument(input, context, trx) {
211
+ return service.deleteDocumentById(input.recordId, { context, trx });
212
+ }
213
+
214
+ /**
215
+ * An operation's result, checked where its events depend on it: a create
216
+ * returns the created record, with its id, as a tagged JSON:API result of a
217
+ * kind the HTTP transport encodes (returnJsonApiDocument, as the service's
218
+ * createDocument and a lifecycle's standard() do, or returnJsonApiData), since
219
+ * its created and record-changed events read the record's id from it.
220
+ * @param {string} operation
221
+ * @param {unknown} result
222
+ */
223
+ function requireOperationResult(operation, result) {
224
+ if (operation === "create" && !resolveCrudJsonApiEntityIdFromResult({ result })) {
225
+ throw new TypeError(
226
+ `CRUD ${namespace} create must return the created record, with its id, as a tagged JSON:API result ` +
227
+ "(returnJsonApiDocument, as createDocument() and a lifecycle's standard() do, or returnJsonApiData)."
228
+ );
229
+ }
230
+ return result;
231
+ }
232
+
233
+ /**
234
+ * Runs one standard operation through the feature's lifecycle hooks for it, if any.
235
+ * @param {string} operation
236
+ * @param {object} input
237
+ * @param {object} context
238
+ * @param {(input: object, context: object, trx: object | null) => Promise<any>} runStandard
239
+ */
240
+ async function executeOperation(operation, input, context, runStandard) {
241
+ const hooks = operationLifecycle[operation];
597
242
  if (!hooks) {
598
- return defaultExecute(value, null);
243
+ return requireOperationResult(operation, await runStandard(input, context, null));
599
244
  }
600
245
 
601
246
  async function run(trx = null) {
602
- const base = { operation, input: value, context, resource, repository, service, trx };
247
+ const base = { operation, input, context, resource, repository, service, trx };
603
248
  if (hooks.before) {
604
- await hooks.before(createLifecycleContext(base));
249
+ await hooks.before(buildLifecycleContext(base));
605
250
  }
606
- const standard = (nextInput = value) => defaultExecute(nextInput, trx);
607
- const result = hooks.execute
608
- ? await hooks.execute(createLifecycleContext({ ...base, standard }))
609
- : await standard();
251
+ const standard = (nextInput = input) => runStandard(nextInput, context, trx);
252
+ const result = requireOperationResult(operation, hooks.execute
253
+ ? await hooks.execute(buildLifecycleContext({ ...base, standard }))
254
+ : await standard());
610
255
  if (hooks.after) {
611
- await hooks.after(createLifecycleContext({ ...base, result }));
256
+ await hooks.after(buildLifecycleContext({ ...base, result }));
612
257
  }
613
258
  return result;
614
259
  }
615
260
 
616
- const mutation = CRUD_MUTATION_NAMES.has(operation);
617
- if (mutation && (!repository || typeof repository.withTransaction !== "function")) {
618
- throw new TypeError(`CRUD operationLifecycle.${operation} requires repository.withTransaction().`);
619
- }
620
- const result = mutation ? await repository.withTransaction(run) : await run();
261
+ const result = CRUD_MUTATION_NAMES.has(operation) ? await repository.withTransaction(run) : await run();
621
262
  if (hooks.afterCommit) {
622
263
  try {
623
- await hooks.afterCommit(createLifecycleContext({
264
+ await hooks.afterCommit(buildLifecycleContext({
624
265
  operation,
625
- input: value,
266
+ input,
626
267
  context,
627
268
  resource,
628
269
  repository,
629
270
  service,
271
+ trx: null,
630
272
  result
631
273
  }));
632
274
  } catch (error) {
@@ -643,80 +285,51 @@ function createCrudJsonApiActions({
643
285
  {
644
286
  operation: "list",
645
287
  kind: "query",
646
- idempotency: "none",
647
- async execute(value, context) {
648
- return executeOperation("list", value, context, (nextInput) =>
649
- service.queryDocuments(omitInputKeys(nextInput, scopeInputKeys), { context })
650
- );
651
- }
288
+ events: [],
289
+ execute: (input, context) => executeOperation("list", input, context, listDocuments)
652
290
  },
653
291
  {
654
292
  operation: "view",
655
293
  kind: "query",
656
- idempotency: "none",
657
- async execute(value, context) {
658
- return executeOperation("view", value, context, (nextInput) => {
659
- const query = omitInputKeys(nextInput, [...scopeInputKeys, "recordId"]);
660
- return service.getDocumentById(nextInput.recordId, query, { context });
661
- });
662
- }
294
+ events: [],
295
+ execute: (input, context) => executeOperation("view", input, context, viewDocument)
663
296
  },
664
297
  {
665
298
  operation: "create",
666
299
  kind: "command",
667
- idempotency: "optional",
668
- events: [mutationEvent("created", ({ result }) => result?.data?.id ?? result?.value?.data?.id)],
669
- async execute(value, context) {
670
- return executeOperation("create", value, context, (nextInput, trx) =>
671
- service.createDocument(omitInputKeys(nextInput, scopeInputKeys), { context, trx })
672
- );
673
- }
300
+ events: [mutationEvent("created", resolveCrudJsonApiEntityIdFromResult)],
301
+ execute: (input, context) => executeOperation("create", input, context, createDocument)
674
302
  },
675
303
  {
676
304
  operation: "update",
677
305
  kind: "command",
678
- idempotency: "optional",
679
- events: [mutationEvent("updated", ({ input: value }) => value?.recordId)],
680
- async execute(value, context) {
681
- return executeOperation("update", value, context, (nextInput, trx) => {
682
- const patch = omitInputKeys(nextInput, [...scopeInputKeys, "recordId"]);
683
- return service.patchDocumentById(nextInput.recordId, patch, { context, trx });
684
- });
685
- }
306
+ events: [mutationEvent("updated", ({ input }) => input.recordId)],
307
+ execute: (input, context) => executeOperation("update", input, context, updateDocument)
686
308
  },
687
309
  {
688
310
  operation: "delete",
689
311
  kind: "command",
690
- idempotency: "optional",
691
- events: [mutationEvent("deleted", ({ input: value }) => value?.recordId)],
692
- async execute(value, context) {
693
- return executeOperation("delete", value, context, (nextInput, trx) =>
694
- service.deleteDocumentById(nextInput.recordId, { context, trx })
695
- );
696
- }
312
+ events: [mutationEvent("deleted", ({ input }) => input.recordId)],
313
+ execute: (input, context) => executeOperation("delete", input, context, deleteDocument)
697
314
  }
698
315
  ];
699
316
 
700
317
  const enabledOperations = new Set(operations);
701
- const standardActions = standardDefinitions.filter((definition) => enabledOperations.has(definition.operation)).map((definition) => {
702
- const id = actionId(definition.operation);
703
- return Object.freeze({
704
- id,
705
- version: 1,
706
- kind: definition.kind,
707
- channels: ["api", "automation", "internal"],
708
- surfaces: [surface],
709
- permission: permission(definition.operation),
710
- input: input(definition.operation),
711
- output: null,
712
- extensions: Object.freeze({
713
- assistant: createCrudAssistantExtension(resource, namespace, definition.operation)
714
- }),
715
- idempotency: definition.idempotency,
716
- events: definition.events || [],
717
- execute: definition.execute
718
- });
719
- });
318
+ const standardActions = standardDefinitions.filter((definition) => enabledOperations.has(definition.operation)).map((definition) => Object.freeze({
319
+ id: `crud.${namespace}.${definition.operation}`,
320
+ version: 1,
321
+ kind: definition.kind,
322
+ channels: ["api", "automation", "internal"],
323
+ surfaces: [surface],
324
+ permission: permissionForOperation(definition.operation),
325
+ input: buildActionInput(resource, definition.operation, scopeInputValidator, listFilterQueryValidator, operationInputs),
326
+ output: null,
327
+ extensions: Object.freeze({
328
+ assistant: createCrudAssistantExtension(resource, namespace, definition.operation)
329
+ }),
330
+ events: definition.events,
331
+ execute: definition.execute
332
+ }));
720
333
  const productActions = additionalActions.map((definition) => Object.freeze({
721
334
  id: definition.id,
722
335
  version: definition.version,
@@ -725,20 +338,10 @@ function createCrudJsonApiActions({
725
338
  surfaces: definition.surfaces,
726
339
  input: definition.input,
727
340
  output: definition.output || null,
728
- idempotency: definition.idempotency,
729
341
  permission: definition.permission,
730
342
  extensions: definition.extensions || {},
731
343
  events: definition.events,
732
- async execute(value, context) {
733
- return definition.execute(Object.freeze({
734
- ...dependencies,
735
- input: value,
736
- context,
737
- resource,
738
- repository,
739
- service
740
- }));
741
- }
344
+ execute: (input, context) => definition.execute(Object.freeze({ ...dependencies, input, context, resource, repository, service }))
742
345
  }));
743
346
  return Object.freeze([...standardActions, ...productActions]);
744
347
  }