@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
package/locales/en.json CHANGED
@@ -8,7 +8,8 @@
8
8
  "notFound": "Record not found."
9
9
  },
10
10
  "document": {
11
- "notFound": "Document not found."
11
+ "notFound": "Document not found.",
12
+ "lockVersionConflict": "This record changed. Reload and try again."
12
13
  },
13
14
  "fieldAccess": {
14
15
  "writeDenied": "Write access denied for fields: {fields}."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/crud-core",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -20,16 +20,16 @@
20
20
  "./server/defineCrudJsonApiFeature": "./src/server/defineCrudJsonApiFeature.js",
21
21
  "./server/jsonApiRepository": "./src/server/jsonApiModule/repository.js",
22
22
  "./server/jsonApiService": "./src/server/jsonApiModule/service.js",
23
- "./server/crudModuleConfig": "./src/server/crudModuleConfig.js",
24
23
  "./server/listQueryValidators": "./src/server/listQueryValidators.js",
25
24
  "./server/listFilters": "./src/server/listFilters.js",
26
25
  "./server/routeContracts": "./src/server/routeContracts.js",
26
+ "./server/types": "./src/server/types.js",
27
27
  "./locales/en.json": "./locales/en.json"
28
28
  },
29
29
  "dependencies": {
30
- "@jskit-ai/database-runtime": "0.1.251",
31
- "@jskit-ai/json-rest-api-core": "0.2.2",
32
- "@jskit-ai/resource-crud-core": "0.1.193",
30
+ "@jskit-ai/database-runtime": "0.1.253",
31
+ "@jskit-ai/json-rest-api-core": "0.2.4",
32
+ "@jskit-ai/resource-crud-core": "0.1.195",
33
33
  "json-rest-schema": "^1.0.17",
34
34
  "json-rest-api": "2.1.0"
35
35
  },
@@ -50,7 +50,7 @@
50
50
  }
51
51
  },
52
52
  "peerDependencies": {
53
- "@jskit-ai/http-runtime": "0.2.2",
54
- "@jskit-ai/kernel": "0.2.2"
53
+ "@jskit-ai/http-runtime": "0.2.4",
54
+ "@jskit-ai/kernel": "0.2.4"
55
55
  }
56
56
  }
@@ -33,18 +33,32 @@ from a generator questionnaire or treat a live table as the sole contract.
33
33
  - Migration and resource storage metadata describe the same table.
34
34
  - `apiAccess`, surface access, and `autofilter` agree.
35
35
  - Public routes use public ownership only.
36
- - Workspace routes receive explicit scope validators and route-to-action input.
36
+ - Workspace routes receive explicit scope validators and route-to-action input:
37
+ workspaces-core's `WORKSPACE_CRUD_SCOPE`, never a copied scope literal.
37
38
  - Application source contains one module declaration, not copied generic CRUD
38
39
  repository, service, action, route, and provider files.
39
40
  - Current migration/resource/source state is authoritative; there is no receipt,
40
41
  provenance marker, generator identity, or field-patching lane.
42
+ - The package exports the type of the capability it provides:
43
+ `src/server/types.js` declares `AppBooks` (for `app.books`) as crud-core's
44
+ `CrudResourceApi`, exported as `./server/types`. A feature that requires
45
+ `app.books` names that type in a JSDoc `@param`; code given only its service
46
+ or repository names crud-core's `CrudService` or `CrudRepository`.
47
+ - Code the declaration adds follows [typed features](https://github.com/mobily-enterprises/jskit-ai/blob/main/packages/agent-docs/site/guide/framework/typed-features.md):
48
+ `decorateService`, `decorateRepository`, `operationLifecycle` hooks and named
49
+ `actions` call the collaborators they receive directly, with no `typeof`
50
+ probe, optional call, absent default, slot setter or module-level registry.
51
+ Each action's `execute` is one call to one service method with the
52
+ validated input, and its argument is typed as crud-core's
53
+ `CrudCustomActionInvocation`. Keep one copy of each helper per package, files
54
+ under 750 lines and functions under 600.
41
55
 
42
56
  ## Framework APIs
43
57
 
44
58
  Use `defineCrudResource()` from `@jskit-ai/resource-crud-core` and
45
59
  `defineCrudJsonApiFeature()` from `@jskit-ai/crud-core`. The latter composes the
46
- JSON REST resource, repository, service events, standard CRUD actions, route
47
- contracts, access policy, and HTTP routes.
60
+ JSON REST resource, repository, service, standard CRUD actions with their
61
+ record-changed events, route contracts, access policy, and HTTP routes.
48
62
 
49
63
  ## Example files
50
64
 
@@ -55,6 +69,7 @@ Paths below are relative to this pattern directory:
55
69
  example/migrations/20260815000000_books.cjs
56
70
  example/packages/books/package.json
57
71
  example/packages/books/src/server/BooksFeature.js
72
+ example/packages/books/src/server/types.js
58
73
  example/packages/books/src/shared/bookResource.js
59
74
  example/packages/books/src/shared/index.js
60
75
  ```
@@ -67,6 +82,8 @@ guide.
67
82
 
68
83
  `BooksFeature.js` is deliberately tiny: it binds the readable resource contract
69
84
  to the framework module and exports the resulting provider.
85
+ `types.js` declares the type of the `app.books` capability, for features that
86
+ require it.
70
87
 
71
88
  ## List search is part of the initial composition
72
89
 
@@ -89,8 +106,15 @@ an unfiltered collection can satisfy a matching-row-only assertion.
89
106
 
90
107
  Change the package name, resource fields, table, surface, ownership filter,
91
108
  relative route, messages, and migration. Supply explicit permissions when the
92
- surface uses named policy. For workspace ownership, add the workspace route and
93
- action validators through the module's `scope` option. The feature exposes the
109
+ surface uses named policy. For workspace ownership, pass `scope:
110
+ WORKSPACE_CRUD_SCOPE` (`@jskit-ai/workspaces-core/server/support/workspaceCrud`):
111
+ the `/w/:workspaceSlug` route base, the workspace route and action validators
112
+ and the slug input. A repository method of such a feature reads the workspace
113
+ id with `resolveWorkspaceScopeValue(options.context)`
114
+ (`@jskit-ai/json-rest-api-core/server/jsonRestApiHost`), and a
115
+ hand-written workspace route's path is
116
+ `resolveWorkspaceRoutePath("relative-path")`
117
+ (`@jskit-ai/workspaces-core/server/support/workspaceRoutePaths`). The feature exposes the
94
118
  operations declared by the resource. Use `operations` only to narrow that
95
119
  surface further; do not register unused mutation actions and routes. Use
96
120
  `routes: false` only for an internal
@@ -108,7 +132,13 @@ capabilities in `requires` and provide `decorateService({ service, repository,
108
132
  resource, ...dependencies })`. Retain the standard methods, override only the
109
133
  methods whose CRUD behavior changes, and add resource-related domain methods
110
134
  such as `confirmBooking()` or `sendReminder()` directly to that service. Those
111
- additional methods remain available through the resource capability. When the
135
+ additional methods remain available through the resource capability. An
136
+ overridden `createDocument()` returns the created record, with its id, as a
137
+ tagged JSON:API result: a document result (`returnJsonApiDocument`), as the
138
+ standard one does, or a data result (`returnJsonApiData(record)`). The create
139
+ action's created and `record.changed` events read the record's id from it, and
140
+ a create whose service returns an untagged document or record, or a result
141
+ without the record's id, fails in every channel. When the
112
142
  product needs only a few additional queries or locking operations, provide
113
143
  `decorateRepository({ repository, database, http, jsonRestApi, resource,
114
144
  ...dependencies })`; return the standard methods plus only those unique
@@ -118,14 +148,28 @@ Use `operationLifecycle` for behavior surrounding a standard operation. Its
118
148
  per-operation `before`, `execute`, and `after` phases share one repository
119
149
  transaction for create, update, and delete. An `execute` hook receives
120
150
  `standard(nextInput)` so it can retain the framework write while adjusting its
121
- input or coordinating other repository work. `afterCommit` runs only after the
122
- mutation transaction succeeds. Put durable external delivery behind an outbox
123
- written inside the transaction; do not make an email or webhook the arbiter of
124
- whether an already-committed request appears successful.
151
+ input or coordinating other repository work, and returns what `standard()`
152
+ returns: the operation's tagged JSON:API result (null for delete). A create's
153
+ `execute` returns the created record with its id, as the document result
154
+ `standard()` returns or as `returnJsonApiData(record)`, because the create's
155
+ events read its id; a create that returns anything else fails inside its
156
+ transaction. `after` and `afterCommit` receive that `result`, so a record id is
157
+ `result.value.data.id` for a document result. `afterCommit` runs only after the
158
+ mutation transaction succeeds. A hook's argument is `CrudLifecycleContext` from
159
+ `@jskit-ai/crud-core/server/types`; type a lifecycle declared apart from its
160
+ feature with `CrudOperationLifecycle`, whose type arguments are the decorated
161
+ service and repository its hooks call. Put durable external delivery behind an
162
+ outbox written inside the transaction; do not make an email or webhook the
163
+ arbiter of whether an already-committed request appears successful.
125
164
 
126
165
  Declare resource-related non-CRUD commands in `actions`. Each named action has
127
166
  a normal JSKIT input, permission, audit, events, and `execute({ input, context,
128
- service, repository, ...dependencies })` contract. Its optional `route`
167
+ service, repository, ...dependencies })` contract. Type that argument with
168
+ `CrudCustomActionInvocation` from `@jskit-ai/crud-core/server/types`. Its first
169
+ type argument is the service the action calls, when `decorateService` adds the
170
+ method; its second holds the types of required capabilities the action uses,
171
+ by local name; its third is the repository the action calls, when
172
+ `decorateRepository` adds the method. Its optional `route`
129
173
  declares an HTTP method, path below the resource base, explicit route contract,
130
174
  status code, and optional request-to-action input mapper. This is the normal
131
175
  home for `confirm`, `publish`, `cancel`, `reorder`, or `sendReminder`. Move to a
@@ -139,25 +183,58 @@ Use `operationInputs.create` or `operationInputs.update` when a standard CRUD
139
183
  operation intentionally accepts a small virtual product field that is handled
140
184
  by the service decorator rather than stored on the resource row.
141
185
 
186
+ A decorator lives in a module of its own and returns its result frozen, with
187
+ each added method a named function. Spreading belongs here only, over the CRUD
188
+ service or repository, whose members are the contract's. `types.js` names the
189
+ decorated types once:
190
+
191
+ ```js
192
+ // bookingsService.js
193
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
194
+
195
+ /**
196
+ * The bookings service: the CRUD service plus booking confirmation and the
197
+ * checks and history its updates need.
198
+ * @param {object} dependencies
199
+ * @param {import("@jskit-ai/crud-core/server/types").CrudService} dependencies.service
200
+ * @param {import("./types.js").BookingsRepository} dependencies.repository
201
+ */
202
+ function decorateBookingsService({ service, repository }) {
203
+ async function confirmBooking(recordId, options) {
204
+ return repository.confirmBooking(recordId, options);
205
+ }
206
+
207
+ async function assertUpdateAllowed(recordId, options) {
208
+ if (await repository.isBookingLocked(recordId, options)) {
209
+ throw new AppError(409, "This booking is locked.", { code: "bookings.locked" });
210
+ }
211
+ }
212
+
213
+ async function recordUpdateCompleted(recordId, options) {
214
+ return repository.addBookingHistoryEntry(recordId, "updated", options);
215
+ }
216
+
217
+ return Object.freeze({ ...service, confirmBooking, assertUpdateAllowed, recordUpdateCompleted });
218
+ }
219
+
220
+ // types.js
221
+ /** @typedef {ReturnType<typeof import("./bookingsRepository.js").decorateBookingsRepository>} BookingsRepository */
222
+ /** @typedef {ReturnType<typeof import("./bookingsService.js").decorateBookingsService>} BookingsService */
223
+ ```
224
+
142
225
  ```js
143
226
  const BookingsFeature = defineCrudJsonApiFeature({
144
227
  resource: bookingResource,
145
228
  surface: "app",
146
- decorateService({ service, repository }) {
147
- return {
148
- ...service,
149
- async confirmBooking(recordId, options) {
150
- return repository.confirmBooking(recordId, options);
151
- }
152
- };
153
- },
229
+ decorateRepository: decorateBookingsRepository,
230
+ decorateService: decorateBookingsService,
154
231
  operationLifecycle: {
155
232
  update: {
156
233
  async before({ input, service, trx, context }) {
157
234
  await service.assertUpdateAllowed(input.recordId, { trx, context });
158
235
  },
159
236
  async afterCommit({ result, service, context }) {
160
- await service.recordUpdateCompleted(result.data.id, { context });
237
+ await service.recordUpdateCompleted(result.value.data.id, { context });
161
238
  }
162
239
  }
163
240
  },
@@ -165,9 +242,8 @@ const BookingsFeature = defineCrudJsonApiFeature({
165
242
  confirm: {
166
243
  input: confirmBookingInput,
167
244
  permission: { require: "all", permissions: ["bookings.confirm"] },
168
- execute({ input, context, service }) {
169
- return service.confirmBooking(input.recordId, { context });
170
- },
245
+ /** @param {import("@jskit-ai/crud-core/server/types").CrudCustomActionInvocation<import("./types.js").BookingsService>} action */
246
+ execute: ({ input, context, service }) => service.confirmBooking(input.recordId, { context }),
171
247
  route: {
172
248
  method: "POST",
173
249
  path: "/:recordId/confirm",
@@ -203,3 +279,6 @@ const BookingsFeature = defineCrudJsonApiFeature({
203
279
  - public access combined with user or workspace ownership
204
280
  - implicit workspace route parameters or permissions
205
281
  - receipt, replay, provenance, ownership-marker, or scaffold-shape files
282
+ - probing a collaborator, defaulting one to `null`, `{}` or a no-op, setters
283
+ that fill a slot after construction, and module-level registries in
284
+ decorators, lifecycle hooks or actions
@@ -5,11 +5,12 @@
5
5
  "type": "module",
6
6
  "exports": {
7
7
  "./server/BooksFeature": "./src/server/BooksFeature.js",
8
+ "./server/types": "./src/server/types.js",
8
9
  "./shared": "./src/shared/index.js"
9
10
  },
10
11
  "dependencies": {
11
- "@jskit-ai/crud-core": "0.2.2",
12
- "@jskit-ai/resource-crud-core": "0.1.193"
12
+ "@jskit-ai/crud-core": "0.2.4",
13
+ "@jskit-ai/resource-crud-core": "0.1.195"
13
14
  },
14
15
  "jskit": {
15
16
  "kind": "runtime",
@@ -0,0 +1,5 @@
1
+ // The type of the `app.books` capability, for features that require it.
2
+
3
+ /** @typedef {import("@jskit-ai/crud-core/server/types").CrudResourceApi} AppBooks */
4
+
5
+ export {};
@@ -1,4 +1,3 @@
1
- import { createCrudServiceEvents } from "./serviceEvents.js";
2
1
  import {
3
2
  createCrudServiceRuntime,
4
3
  crudServiceListRecords,
@@ -8,11 +7,21 @@ import {
8
7
  crudServiceDeleteRecord
9
8
  } from "./serviceMethods.js";
10
9
 
11
- function createCrudServiceFromResource(resource = {}, { context = "crudService" } = {}) {
10
+ /**
11
+ * A records service factory for one resource.
12
+ * @param {import("./types.js").CrudResourceDefinition} resource
13
+ * @param {{ context?: string }} [options] The name the service's errors give it.
14
+ */
15
+ function createCrudServiceFromResource(resource, { context = "crudService" } = {}) {
12
16
  const runtime = createCrudServiceRuntime(resource, { context });
13
- const baseServiceEvents = createCrudServiceEvents(resource, { context });
14
17
 
15
- function createBaseService({ repository, fieldAccess = {} } = {}) {
18
+ /**
19
+ * @param {object} dependencies
20
+ * @param {import("./types.js").CrudRecordRepository} dependencies.repository
21
+ * @param {import("./types.js").CrudFieldAccess} [dependencies.fieldAccess] Defaults to no field restrictions.
22
+ */
23
+ function createBaseService({ repository, fieldAccess = {} }) {
24
+ // readable-check: allow required-collaborators - safety invariant: without a repository every operation of the service fails later, far from the resource that lacks one
16
25
  if (!repository) {
17
26
  throw new Error(`${context} requires repository.`);
18
27
  }
@@ -47,8 +56,7 @@ function createCrudServiceFromResource(resource = {}, { context = "crudService"
47
56
  }
48
57
 
49
58
  return Object.freeze({
50
- createBaseService,
51
- baseServiceEvents
59
+ createBaseService
52
60
  });
53
61
  }
54
62
 
@@ -18,7 +18,11 @@ function normalizeOwnerKey(value) {
18
18
  return String(value).trim();
19
19
  }
20
20
 
21
- function toDefaultChildCallOptions(callOptions = {}) {
21
+ function readParentId(record) {
22
+ return record?.id;
23
+ }
24
+
25
+ function toDefaultChildCallOptions({ callOptions = {} } = {}) {
22
26
  const nextOptions = {};
23
27
  if (Object.hasOwn(callOptions, "trx")) {
24
28
  nextOptions.trx = callOptions.trx;
@@ -31,6 +35,7 @@ function toDefaultChildCallOptions(callOptions = {}) {
31
35
  }
32
36
 
33
37
  function resolveListChildrenHandler(options = {}, { context = "createHooksToCollectChildren" } = {}) {
38
+ // readable-check: allow method-probe - input validation: an application passes listChildren() or a childRepository to read through
34
39
  if (typeof options.listChildren === "function") {
35
40
  return options.listChildren;
36
41
  }
@@ -79,6 +84,7 @@ function resolveListChildrenHandler(options = {}, { context = "createHooksToColl
79
84
  }
80
85
 
81
86
  function resolveGetChildOwnerId(options = {}, { context = "createHooksToCollectChildren" } = {}) {
87
+ // readable-check: allow method-probe - input validation: an application passes getChildOwnerId() or the key that holds the owner id
82
88
  if (typeof options.getChildOwnerId === "function") {
83
89
  return options.getChildOwnerId;
84
90
  }
@@ -101,24 +107,45 @@ function resolveGetChildOwnerId(options = {}, { context = "createHooksToCollectC
101
107
  };
102
108
  }
103
109
 
104
- function resolveLookupContainerKey(record = {}, hookContext = {}, options = {}) {
110
+ function resolveChildrenContainerKey(hookContext = {}, options = {}) {
105
111
  const explicitContainerKey = normalizeText(options.lookupContainerKey);
106
112
  if (explicitContainerKey) {
107
113
  return explicitContainerKey;
108
114
  }
109
115
 
110
- const runtimeContainerKey = normalizeText(hookContext?.runtime?.lookup?.containerKey);
116
+ const runtimeContainerKey = normalizeText(hookContext.runtime?.lookup?.containerKey);
111
117
  if (runtimeContainerKey) {
112
118
  return runtimeContainerKey;
113
119
  }
114
120
 
115
- if (Object.hasOwn(record, "lookups")) {
116
- return "lookups";
117
- }
118
-
119
121
  return "lookups";
120
122
  }
121
123
 
124
+ /**
125
+ * Hooks that load the children of a page of records in one call (afterQuery) and attach each record's
126
+ * children to it (transformReturnedRecord).
127
+ * @param {object} options
128
+ * @param {string} options.childKey The key the children are attached under.
129
+ * @param {string} [options.context] The name errors give the hooks.
130
+ * @param {(ids: unknown[], callOptions: object, hookContext: object) => Promise<object[]>} [options.listChildren]
131
+ * Lists the children of the owner ids; otherwise childRepository's childListMethod does.
132
+ * @param {object} [options.childRepository]
133
+ * @param {string} [options.childListMethod]
134
+ * @param {string} [options.childForeignKey]
135
+ * @param {(child: object, hookContext: object) => unknown} [options.getChildOwnerId]
136
+ * Reads a child's owner id; otherwise childOwnerIdKey or childForeignKey names it.
137
+ * @param {string} [options.childOwnerIdKey]
138
+ * @param {(record: object, hookContext: object) => unknown} [options.getParentId] Reads a record's id.
139
+ * @param {(value: unknown) => string} [options.normalizeOwnerKey] Turns an owner id into a map key.
140
+ * @param {(input: { callOptions: object, records: object[], ownerIds: unknown[], context: object }) => object} [options.buildChildCallOptions]
141
+ * The options the children are listed with; by default the query's trx and visibilityContext.
142
+ * @param {(record: object, children: object[], hookContext: object) => object} [options.attachChildren]
143
+ * Returns the record with its children; by default under childKey in the lookup container, or on
144
+ * the record itself when attachToLookupContainer is false.
145
+ * @param {symbol | string} [options.stateMapKey]
146
+ * @param {boolean} [options.attachToLookupContainer]
147
+ * @param {string} [options.lookupContainerKey]
148
+ */
122
149
  function createHooksToCollectChildren(options = {}) {
123
150
  const context = normalizeText(options.context) || "createHooksToCollectChildren";
124
151
  const childKey = normalizeText(options.childKey);
@@ -129,118 +156,117 @@ function createHooksToCollectChildren(options = {}) {
129
156
  const listChildren = resolveListChildrenHandler(options, {
130
157
  context
131
158
  });
132
- const getParentId = typeof options.getParentId === "function"
133
- ? options.getParentId
134
- : (record = {}) => record?.id;
159
+ const {
160
+ getParentId = readParentId,
161
+ normalizeOwnerKey: normalizeCollectionOwnerKey = normalizeOwnerKey,
162
+ buildChildCallOptions = toDefaultChildCallOptions,
163
+ attachChildren = attachChildrenToRecord
164
+ } = options;
135
165
  const getChildOwnerId = resolveGetChildOwnerId(options, {
136
166
  context
137
167
  });
138
- const normalizeCollectionOwnerKey = typeof options.normalizeOwnerKey === "function"
139
- ? options.normalizeOwnerKey
140
- : normalizeOwnerKey;
141
- const buildChildCallOptions = typeof options.buildChildCallOptions === "function"
142
- ? options.buildChildCallOptions
143
- : ({ callOptions = {} } = {}) => toDefaultChildCallOptions(callOptions);
144
168
  const stateMapKey = options.stateMapKey || Symbol(`crud.children.${childKey}`);
145
169
  const attachToLookupContainer = options.attachToLookupContainer !== false;
146
- const attachChildren = typeof options.attachChildren === "function"
147
- ? options.attachChildren
148
- : (record = {}, children = [], hookContext = {}) => {
149
- if (!attachToLookupContainer) {
150
- return {
151
- ...record,
152
- [childKey]: children
153
- };
154
- }
155
-
156
- const containerKey = resolveLookupContainerKey(record, hookContext, options);
157
- const sourceContainer = record?.[containerKey];
158
- const normalizedContainer =
159
- sourceContainer && typeof sourceContainer === "object" && !Array.isArray(sourceContainer)
160
- ? sourceContainer
161
- : {};
162
170
 
171
+ function attachChildrenToRecord(record, children = [], hookContext = {}) {
172
+ if (!attachToLookupContainer) {
163
173
  return {
164
174
  ...record,
165
- [containerKey]: {
166
- ...normalizedContainer,
167
- [childKey]: children
168
- }
175
+ [childKey]: children
169
176
  };
170
- };
177
+ }
171
178
 
172
- return Object.freeze({
173
- async afterQuery(records = [], ctx = {}) {
174
- const normalizedRecords = Array.isArray(records) ? records : [];
175
- const ownerIds = [];
176
- const seenOwnerKeys = new Set();
177
-
178
- for (const record of normalizedRecords) {
179
- const ownerId = getParentId(record, ctx);
180
- const ownerKey = normalizeCollectionOwnerKey(ownerId);
181
- if (!ownerKey || seenOwnerKeys.has(ownerKey)) {
182
- continue;
183
- }
184
-
185
- seenOwnerKeys.add(ownerKey);
186
- ownerIds.push(ownerId);
179
+ const containerKey = resolveChildrenContainerKey(hookContext, options);
180
+ const sourceContainer = record?.[containerKey];
181
+ const normalizedContainer =
182
+ sourceContainer && typeof sourceContainer === "object" && !Array.isArray(sourceContainer)
183
+ ? sourceContainer
184
+ : {};
185
+
186
+ return {
187
+ ...record,
188
+ [containerKey]: {
189
+ ...normalizedContainer,
190
+ [childKey]: children
187
191
  }
192
+ };
193
+ }
188
194
 
189
- const state = ctx?.state && typeof ctx.state === "object" ? ctx.state : null;
190
- if (!state) {
191
- throw new TypeError(`${context} requires ctx.state object.`);
192
- }
195
+ async function afterQuery(records = [], ctx = {}) {
196
+ const normalizedRecords = Array.isArray(records) ? records : [];
197
+ const ownerIds = [];
198
+ const seenOwnerKeys = new Set();
193
199
 
194
- if (ownerIds.length < 1) {
195
- state[stateMapKey] = new Map();
196
- return;
200
+ for (const record of normalizedRecords) {
201
+ const ownerId = getParentId(record, ctx);
202
+ const ownerKey = normalizeCollectionOwnerKey(ownerId);
203
+ if (!ownerKey || seenOwnerKeys.has(ownerKey)) {
204
+ continue;
197
205
  }
198
206
 
199
- const childCallOptions = buildChildCallOptions({
200
- callOptions: ctx.callOptions || {},
201
- records: normalizedRecords,
202
- ownerIds,
203
- context: ctx
204
- });
205
- const children = await listChildren(ownerIds, childCallOptions, ctx);
206
- if (!Array.isArray(children)) {
207
- throw new TypeError(`${context} listChildren must return an array.`);
208
- }
207
+ seenOwnerKeys.add(ownerKey);
208
+ ownerIds.push(ownerId);
209
+ }
209
210
 
210
- const childrenByOwnerKey = new Map();
211
- for (const child of children) {
212
- const childOwnerId = getChildOwnerId(child, ctx);
213
- const childOwnerKey = normalizeCollectionOwnerKey(childOwnerId);
214
- if (!childOwnerKey) {
215
- continue;
216
- }
217
-
218
- const currentList = childrenByOwnerKey.get(childOwnerKey);
219
- if (currentList) {
220
- currentList.push(child);
221
- continue;
222
- }
223
-
224
- childrenByOwnerKey.set(childOwnerKey, [child]);
225
- }
211
+ const state = ctx.state && typeof ctx.state === "object" ? ctx.state : null;
212
+ if (!state) {
213
+ throw new TypeError(`${context} requires ctx.state object.`);
214
+ }
215
+
216
+ if (ownerIds.length < 1) {
217
+ state[stateMapKey] = new Map();
218
+ return;
219
+ }
226
220
 
227
- state[stateMapKey] = childrenByOwnerKey;
228
- },
221
+ const childCallOptions = buildChildCallOptions({
222
+ callOptions: ctx.callOptions || {},
223
+ records: normalizedRecords,
224
+ ownerIds,
225
+ context: ctx
226
+ });
227
+ const children = await listChildren(ownerIds, childCallOptions, ctx);
228
+ if (!Array.isArray(children)) {
229
+ throw new TypeError(`${context} listChildren must return an array.`);
230
+ }
229
231
 
230
- transformReturnedRecord(record = {}, ctx = {}) {
231
- if (!record || typeof record !== "object" || Array.isArray(record)) {
232
- return record;
232
+ const childrenByOwnerKey = new Map();
233
+ for (const child of children) {
234
+ const childOwnerId = getChildOwnerId(child, ctx);
235
+ const childOwnerKey = normalizeCollectionOwnerKey(childOwnerId);
236
+ if (!childOwnerKey) {
237
+ continue;
233
238
  }
234
239
 
235
- const state = ctx?.state && typeof ctx.state === "object" ? ctx.state : null;
236
- const childrenByOwnerKey = state ? state[stateMapKey] : null;
237
- const ownerKey = normalizeCollectionOwnerKey(getParentId(record, ctx));
238
- const children = ownerKey && childrenByOwnerKey instanceof Map
239
- ? (childrenByOwnerKey.get(ownerKey) || [])
240
- : [];
240
+ const currentList = childrenByOwnerKey.get(childOwnerKey);
241
+ if (currentList) {
242
+ currentList.push(child);
243
+ continue;
244
+ }
245
+
246
+ childrenByOwnerKey.set(childOwnerKey, [child]);
247
+ }
248
+
249
+ state[stateMapKey] = childrenByOwnerKey;
250
+ }
241
251
 
242
- return attachChildren(record, children, ctx);
252
+ function transformReturnedRecord(record = {}, ctx = {}) {
253
+ if (!record || typeof record !== "object" || Array.isArray(record)) {
254
+ return record;
243
255
  }
256
+
257
+ const state = ctx.state && typeof ctx.state === "object" ? ctx.state : null;
258
+ const childrenByOwnerKey = state ? state[stateMapKey] : null;
259
+ const ownerKey = normalizeCollectionOwnerKey(getParentId(record, ctx));
260
+ const children = ownerKey && childrenByOwnerKey instanceof Map
261
+ ? (childrenByOwnerKey.get(ownerKey) || [])
262
+ : [];
263
+
264
+ return attachChildren(record, children, ctx);
265
+ }
266
+
267
+ return Object.freeze({
268
+ afterQuery,
269
+ transformReturnedRecord
244
270
  });
245
271
  }
246
272