@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
@@ -5,7 +5,7 @@ import { requireCrudNamespace } from "@jskit-ai/resource-crud-core/shared/crudNa
5
5
  import { createCrudFieldAccessRuntime } from "./fieldAccess.js";
6
6
 
7
7
  function createCrudServiceRuntime(resource = {}, { context = "crudService" } = {}) {
8
- const namespace = requireCrudNamespace(resource?.namespace, { context: `${context} resource.namespace` });
8
+ const namespace = requireCrudNamespace(resource.namespace, { context: `${context} resource.namespace` });
9
9
  const fieldAccessRuntime = createCrudFieldAccessRuntime(resource, { context });
10
10
 
11
11
  return Object.freeze({
@@ -16,13 +16,6 @@ function createCrudServiceRuntime(resource = {}, { context = "crudService" } = {
16
16
  });
17
17
  }
18
18
 
19
- function requireCrudServiceRepository(runtime = {}, repository = null) {
20
- if (!repository) {
21
- throw new Error(`${runtime?.context || "crudService"} requires repository.`);
22
- }
23
- return repository;
24
- }
25
-
26
19
  function splitCrudListRepositoryCall(query = {}, options = {}) {
27
20
  const normalizedQuery = normalizeObjectInput(query);
28
21
  const repositoryQuery = {
@@ -40,26 +33,32 @@ function splitCrudListRepositoryCall(query = {}, options = {}) {
40
33
  ? options
41
34
  : {
42
35
  ...options,
43
- include: options?.include === undefined ? normalizedInclude : options.include
36
+ include: options.include === undefined ? normalizedInclude : options.include
44
37
  }
45
38
  };
46
39
  }
47
40
 
41
+ /**
42
+ * @param {import("./types.js").CrudServiceRuntime} runtime
43
+ * @param {import("./types.js").CrudRecordRepository} repository
44
+ */
48
45
  async function crudServiceListRecords(runtime, repository, fieldAccess = {}, query = {}, options = {}) {
49
- const resolvedRepository = requireCrudServiceRepository(runtime, repository);
50
46
  const repositoryCall = splitCrudListRepositoryCall(query, options);
51
- const result = await resolvedRepository.list(repositoryCall.query, repositoryCall.options);
47
+ const result = await repository.list(repositoryCall.query, repositoryCall.options);
52
48
  return runtime.fieldAccessRuntime.filterReadableListResult(result, fieldAccess, {
53
49
  action: "list",
54
50
  query,
55
51
  options,
56
- context: options?.context
52
+ context: options.context
57
53
  });
58
54
  }
59
55
 
56
+ /**
57
+ * @param {import("./types.js").CrudServiceRuntime} runtime
58
+ * @param {import("./types.js").CrudRecordRepository} repository
59
+ */
60
60
  async function crudServiceGetRecord(runtime, repository, fieldAccess = {}, recordId, options = {}) {
61
- const resolvedRepository = requireCrudServiceRepository(runtime, repository);
62
- const record = await resolvedRepository.findById(recordId, options);
61
+ const record = await repository.findById(recordId, options);
63
62
  if (!record) {
64
63
  throw new AppError(404, "Record not found.", { code: "crud.record.notFound" });
65
64
  }
@@ -68,32 +67,38 @@ async function crudServiceGetRecord(runtime, repository, fieldAccess = {}, recor
68
67
  action: "view",
69
68
  recordId,
70
69
  options,
71
- context: options?.context
70
+ context: options.context
72
71
  });
73
72
  }
74
73
 
74
+ /**
75
+ * @param {import("./types.js").CrudServiceRuntime} runtime
76
+ * @param {import("./types.js").CrudRecordRepository} repository
77
+ */
75
78
  async function crudServiceCreateRecord(runtime, repository, fieldAccess = {}, payload = {}, options = {}) {
76
- const resolvedRepository = requireCrudServiceRepository(runtime, repository);
77
79
  const writablePayload = await runtime.fieldAccessRuntime.enforceWritablePayload(payload, fieldAccess, {
78
80
  action: "create",
79
81
  payload,
80
82
  options,
81
- context: options?.context
83
+ context: options.context
82
84
  });
83
- const record = await resolvedRepository.create(writablePayload, options);
85
+ const record = await repository.create(writablePayload, options);
84
86
  if (!record) {
85
87
  throw new Error(`${runtime.namespace}Service could not load the created record.`);
86
88
  }
87
89
  return runtime.fieldAccessRuntime.filterReadableRecord(record, fieldAccess, {
88
90
  action: "create",
89
91
  options,
90
- context: options?.context
92
+ context: options.context
91
93
  });
92
94
  }
93
95
 
96
+ /**
97
+ * @param {import("./types.js").CrudServiceRuntime} runtime
98
+ * @param {import("./types.js").CrudRecordRepository} repository
99
+ */
94
100
  async function crudServiceUpdateRecord(runtime, repository, fieldAccess = {}, recordId, payload = {}, options = {}) {
95
- const resolvedRepository = requireCrudServiceRepository(runtime, repository);
96
- const existingRecord = await resolvedRepository.findById(recordId, options);
101
+ const existingRecord = await repository.findById(recordId, options);
97
102
  if (!existingRecord) {
98
103
  throw new AppError(404, "Record not found.", { code: "crud.record.notFound" });
99
104
  }
@@ -103,11 +108,11 @@ async function crudServiceUpdateRecord(runtime, repository, fieldAccess = {}, re
103
108
  recordId,
104
109
  payload,
105
110
  options,
106
- context: options?.context,
111
+ context: options.context,
107
112
  existingRecord
108
113
  });
109
114
 
110
- const record = await resolvedRepository.updateById(recordId, writablePayload, {
115
+ const record = await repository.updateById(recordId, writablePayload, {
111
116
  ...options,
112
117
  existingRecord
113
118
  });
@@ -118,13 +123,16 @@ async function crudServiceUpdateRecord(runtime, repository, fieldAccess = {}, re
118
123
  action: "update",
119
124
  recordId,
120
125
  options,
121
- context: options?.context
126
+ context: options.context
122
127
  });
123
128
  }
124
129
 
130
+ /**
131
+ * @param {import("./types.js").CrudServiceRuntime} runtime
132
+ * @param {import("./types.js").CrudRecordRepository} repository
133
+ */
125
134
  async function crudServiceDeleteRecord(runtime, repository, fieldAccess = {}, recordId, options = {}) {
126
- const resolvedRepository = requireCrudServiceRepository(runtime, repository);
127
- const deleted = await resolvedRepository.deleteById(recordId, options);
135
+ const deleted = await repository.deleteById(recordId, options);
128
136
  if (!deleted) {
129
137
  throw new AppError(404, "Record not found.", { code: "crud.record.notFound" });
130
138
  }
@@ -0,0 +1,156 @@
1
+ // The types of the capability a CRUD feature provides, for features that require it,
2
+ // of what its custom actions receive, and of the records repository a CRUD service uses.
3
+
4
+ /**
5
+ * The resource definition a CRUD feature serves, as defineCrudResource returns it.
6
+ * @typedef {object} CrudResourceDefinition
7
+ */
8
+
9
+ /**
10
+ * The JSON:API repository a CRUD feature provides as its capability's `repository`.
11
+ * @typedef {ReturnType<typeof import("./jsonApiModule/repository.js").createCrudJsonApiRepository>} CrudRepository
12
+ */
13
+
14
+ /**
15
+ * The JSON:API service a CRUD feature provides as its capability's `service`.
16
+ * @typedef {ReturnType<typeof import("./jsonApiModule/service.js").createCrudJsonApiService>} CrudService
17
+ */
18
+
19
+ /**
20
+ * A tagged JSON:API result, as returnJsonApiDocument and returnJsonApiData
21
+ * (`@jskit-ai/http-runtime/shared`) build it. A CRUD service's document methods
22
+ * and a feature's standard list, view, create and update operations return
23
+ * document results; an execute hook or a decorated service may return a data
24
+ * result (one record) instead.
25
+ * @typedef {ReturnType<typeof import("@jskit-ai/http-runtime/shared").returnJsonApiDocument>} CrudJsonApiResult
26
+ */
27
+
28
+ /**
29
+ * The scope of a scoped CRUD resource: the route base its routes live under,
30
+ * the validators of the scope's route params and action input, the input keys
31
+ * the scope owns, and input(request), which reads them from a request.
32
+ * Workspaces-core's WORKSPACE_CRUD_SCOPE is the workspace one.
33
+ * @typedef {object} CrudScope
34
+ * @property {string} [routeBase]
35
+ * @property {object} [actionInputValidator]
36
+ * @property {object} [routeParamsValidator]
37
+ * @property {ReadonlyArray<string>} [inputKeys]
38
+ * @property {(request: any) => Record<string, unknown>} [input]
39
+ */
40
+
41
+ /**
42
+ * What a `defineCrudJsonApiFeature` feature provides under the capability its
43
+ * application names: the resource, its repository and its service, after any
44
+ * decorateRepository and decorateService. The service keeps only the methods
45
+ * of the feature's enabled operations.
46
+ * @typedef {object} CrudResourceApi
47
+ * @property {CrudResourceDefinition} resource
48
+ * @property {CrudRepository} repository
49
+ * @property {CrudService} service
50
+ */
51
+
52
+ /**
53
+ * What a custom action's `execute` receives from its CRUD feature: the input
54
+ * its schema validated, the action context, the feature's resource, repository
55
+ * and service, and each capability in the feature's `requires`, under its local
56
+ * name. `Service` is the service decorateService returns, when it adds methods;
57
+ * `Requires` holds the types of the required capabilities an action uses;
58
+ * `Repository` is the repository decorateRepository returns, when it adds methods.
59
+ * @template [Service=CrudService]
60
+ * @template [Requires={}]
61
+ * @template [Repository=CrudRepository]
62
+ * @typedef {{
63
+ * input: any,
64
+ * context: object,
65
+ * resource: CrudResourceDefinition,
66
+ * repository: Repository,
67
+ * service: Service
68
+ * } & Requires} CrudCustomActionInvocation
69
+ */
70
+
71
+ /**
72
+ * What an `operationLifecycle` hook receives: the operation, the input its
73
+ * schema validated, the action context, the feature's resource, repository
74
+ * and service, and `trx`, the transaction a create, update or delete runs in
75
+ * (null for list and view, and in afterCommit, which runs after the commit).
76
+ * `after` and `afterCommit` also receive the operation's `result` (the JSON:API
77
+ * document result; null for delete); `execute` receives `standard(nextInput)`,
78
+ * which runs the standard operation and returns its result.
79
+ * `Service` and `Repository` are what decorateService and decorateRepository
80
+ * return, when they add methods a hook calls.
81
+ * @template [Service=CrudService]
82
+ * @template [Repository=CrudRepository]
83
+ * @typedef {object} CrudLifecycleContext
84
+ * @property {"list" | "view" | "create" | "update" | "delete"} operation
85
+ * @property {any} input
86
+ * @property {object} context
87
+ * @property {CrudResourceDefinition} resource
88
+ * @property {Repository} repository
89
+ * @property {Service} service
90
+ * @property {import("@jskit-ai/database-runtime/server/types").RuntimeKnexTransaction | null} trx
91
+ * @property {CrudJsonApiResult | null} [result]
92
+ * @property {(nextInput?: object) => Promise<CrudJsonApiResult | null>} [standard]
93
+ */
94
+
95
+ /**
96
+ * One standard operation's hooks: `before`, `execute` and `after` share a
97
+ * mutation's transaction, `execute` replaces the standard operation, and
98
+ * `afterCommit` (mutations only) runs once the transaction has committed.
99
+ * `execute` returns what `standard()` returns: the operation's tagged JSON:API
100
+ * result (null for delete). A create's must carry the created record with its
101
+ * id, as a document result (what `standard()` returns) or a data result
102
+ * (`returnJsonApiData(record)`), since its created and record-changed events
103
+ * read the record's id from it; a create that returns anything else, such as
104
+ * an untagged document or record, fails inside its transaction.
105
+ * @template [Service=CrudService]
106
+ * @template [Repository=CrudRepository]
107
+ * @typedef {object} CrudLifecycleHooks
108
+ * @property {(hook: CrudLifecycleContext<Service, Repository>) => unknown} [before]
109
+ * @property {(hook: CrudLifecycleContext<Service, Repository>) => Promise<CrudJsonApiResult | null> | CrudJsonApiResult | null} [execute]
110
+ * @property {(hook: CrudLifecycleContext<Service, Repository>) => unknown} [after]
111
+ * @property {(hook: CrudLifecycleContext<Service, Repository>) => unknown} [afterCommit]
112
+ */
113
+
114
+ /**
115
+ * A CRUD feature's `operationLifecycle`: the hooks of each standard operation
116
+ * that has any. Type a lifecycle declared apart from its feature with it:
117
+ * `@type {CrudOperationLifecycle<DrumsService, DrumsRepository>}`.
118
+ * @template [Service=CrudService]
119
+ * @template [Repository=CrudRepository]
120
+ * @typedef {{ list?: CrudLifecycleHooks<Service, Repository>, view?: CrudLifecycleHooks<Service, Repository>, create?: CrudLifecycleHooks<Service, Repository>, update?: CrudLifecycleHooks<Service, Repository>, delete?: CrudLifecycleHooks<Service, Repository> }} CrudOperationLifecycle
121
+ */
122
+
123
+ /**
124
+ * The records repository a CRUD service reads and writes through, as createCrudResourceRuntime builds it.
125
+ * @typedef {ReturnType<typeof import("./resourceRuntime/index.js").createCrudResourceRuntime>} CrudRecordRepository
126
+ */
127
+
128
+ /**
129
+ * What a records repository resolves once from its resource and options, and each of its calls reads.
130
+ * @typedef {ReturnType<typeof import("./resourceRuntime/compiledRuntime.js").buildCompiledCrudRepositoryRuntime>} CompiledCrudRepositoryRuntime
131
+ */
132
+
133
+ /**
134
+ * The repository a lookup reads: any object with listByIds().
135
+ * @typedef {object} CrudLookupRepository
136
+ * @property {(ids: unknown[], options?: Record<string, unknown>) => Promise<unknown>} listByIds
137
+ * @property {string} [ownershipFilter] The ownership filter its records use.
138
+ */
139
+
140
+ /**
141
+ * A records service's field access policy: the fields a call may read and
142
+ * write (a list, a set, "*", or a function of the call that returns one), and
143
+ * whether a write to another field throws or is stripped.
144
+ * createFieldAccessForRoleMatrix builds one from a role matrix.
145
+ * @typedef {object} CrudFieldAccess
146
+ * @property {unknown} [readable]
147
+ * @property {unknown} [writable]
148
+ * @property {"throw" | "strip"} [writeMode]
149
+ */
150
+
151
+ /**
152
+ * The resource, namespace and field access a CRUD service's methods share.
153
+ * @typedef {ReturnType<typeof import("./serviceMethods.js").createCrudServiceRuntime>} CrudServiceRuntime
154
+ */
155
+
156
+ export {};
@@ -9,6 +9,7 @@ import {
9
9
  import { returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
10
10
  import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
11
11
  import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
12
+ import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
12
13
 
13
14
  const BOOKINGS = Object.freeze([
14
15
  Object.freeze({
@@ -141,8 +142,10 @@ function createBookingDocument(query = {}) {
141
142
  data,
142
143
  ...(included.length > 0 ? { included } : {}),
143
144
  meta: {
144
- page: {
145
- nextCursor: limit < BOOKINGS.length ? `after-${rows.at(-1)?.id}` : null
145
+ pagination: {
146
+ cursor: {
147
+ next: limit < BOOKINGS.length ? `after-${rows.at(-1)?.id}` : null
148
+ }
146
149
  }
147
150
  }
148
151
  };
@@ -164,7 +167,7 @@ function createFixture() {
164
167
  });
165
168
  }
166
169
  };
167
- const definitions = createCrudJsonApiActions({
170
+ const definitions = createCrudJsonApiActions(crudJsonApiActionOptions({
168
171
  namespace: "bookings",
169
172
  resource,
170
173
  service,
@@ -181,7 +184,7 @@ function createFixture() {
181
184
  require: "all",
182
185
  permissions: ["bookings.list"]
183
186
  })
184
- });
187
+ }));
185
188
  const actions = createActionCatalogue();
186
189
  actions.register({
187
190
  contributorId: "test.generated-bookings",
@@ -424,7 +427,7 @@ test("generated CRUD list contracts conform through native assistant discovery a
424
427
  assert.equal(response.ok, false);
425
428
  assert.equal(response.error.code, "ACTION_VALIDATION_FAILED");
426
429
  assert.equal(response.error.status, 400);
427
- assert.match(response.error.message, /include expects a comma-separated string such as "pet,service"/u);
430
+ assert.match(response.error.message, /include expects a comma-separated string such as "author,publisher"/u);
428
431
  });
429
432
 
430
433
  await t.test("invalid array-shaped fields gives an actionable validation result", async () => {
@@ -1,6 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import knexLib from "knex";
4
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
4
5
  import { createServiceToolCatalog } from "@jskit-ai/assistant-core/server";
5
6
  import { createActionCatalogue } from "@jskit-ai/kernel/server/actions";
6
7
  import {
@@ -11,6 +12,7 @@ import {
11
12
  } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
12
13
  import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
13
14
  import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
15
+ import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
14
16
  import { createCrudJsonApiRepository } from "../src/server/jsonApiModule/repository.js";
15
17
  import { createCrudJsonApiService } from "../src/server/jsonApiModule/service.js";
16
18
 
@@ -51,7 +53,7 @@ test("assistant list traverses real SQL pages with sparse fields and capped limi
51
53
  createdAt: { type: "dateTime", temporalPrecision: 3, column: "created_at" }
52
54
  }
53
55
  });
54
- const api = await createJsonRestApiHost({ knex });
56
+ const api = await createJsonRestApiHost({ knex, logger: silentLogger });
55
57
  await addResourceIfMissing(api, "books", createJsonRestResourceScopeOptions(resource));
56
58
  const repository = createCrudJsonApiRepository({ api, resource, resourceScopeName: "books" });
57
59
  const service = createCrudJsonApiService({ repository });
@@ -59,14 +61,14 @@ test("assistant list traverses real SQL pages with sparse fields and capped limi
59
61
  actions.register({
60
62
  contributorId: "test.books",
61
63
  domain: "books",
62
- actions: createCrudJsonApiActions({
64
+ actions: createCrudJsonApiActions(crudJsonApiActionOptions({
63
65
  namespace: "books",
64
66
  resource,
65
67
  service,
66
68
  surface: "admin",
67
69
  operations: ["list"],
68
70
  permissionForOperation: () => ({ require: "all", permissions: ["books.list"] })
69
- })
71
+ }))
70
72
  });
71
73
  const catalog = createServiceToolCatalog(actions, { maxDirectTools: 0 });
72
74
  const context = {
@@ -63,24 +63,6 @@ function createRepositoryDouble(overrides = {}) {
63
63
  };
64
64
  }
65
65
 
66
- test("createCrudServiceFromResource builds default service events", () => {
67
- const { baseServiceEvents } = createCrudServiceFromResource({
68
- namespace: "contacts"
69
- });
70
-
71
- assert.equal(baseServiceEvents.createRecord[0].realtime.event, "contacts.record.changed");
72
- assert.equal(baseServiceEvents.updateRecord[0].realtime.event, "contacts.record.changed");
73
- assert.equal(baseServiceEvents.deleteRecord[0].realtime.event, "contacts.record.changed");
74
- });
75
-
76
- test("createCrudServiceFromResource normalizes namespace for realtime event names", () => {
77
- const { baseServiceEvents } = createCrudServiceFromResource({
78
- namespace: "customer-orders"
79
- });
80
-
81
- assert.equal(baseServiceEvents.createRecord[0].realtime.event, "customer_orders.record.changed");
82
- });
83
-
84
66
  test("createCrudServiceFromResource delegates service methods and applies 404 semantics", async () => {
85
67
  const { createBaseService } = createCrudServiceFromResource({
86
68
  namespace: "contacts"
@@ -0,0 +1,12 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ import { buildCrudCustomActionId } from "../src/server/jsonApiModule/customActionId.js";
5
+
6
+ test("a CRUD custom action's id defaults to crud.<namespace>.<name>, as the built-in operations' ids", () => {
7
+ assert.equal(buildCrudCustomActionId("books", "confirm", {}), "crud.books.confirm");
8
+ });
9
+
10
+ test("a CRUD custom action's explicit id is kept, trimmed", () => {
11
+ assert.equal(buildCrudCustomActionId("books", "confirm", { id: " books.confirmed " }), "books.confirmed");
12
+ });