@jskit-ai/crud-core 0.2.14 → 0.2.15

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 (60) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/locales/en.json +1 -11
  3. package/package.json +19 -19
  4. package/patterns/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
  5. package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
  6. package/patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
  7. package/patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
  8. package/patterns/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
  9. package/src/server/createHooksToCollectChildren.js +56 -34
  10. package/src/server/crudContracts.js +54 -0
  11. package/src/server/defineCrudFeature.js +509 -0
  12. package/src/server/jsonApiModule/actions.js +44 -30
  13. package/src/server/jsonApiModule/routes.js +2 -2
  14. package/src/server/jsonApiModule/service.js +213 -32
  15. package/src/server/jsonApiResourceContract.js +41 -1
  16. package/src/server/listQueryValidators.js +1 -1
  17. package/src/server/removedApi.js +87 -0
  18. package/src/server/types.js +26 -50
  19. package/test/assistantActionConformance.test.js +20 -21
  20. package/test/assistantPagination.integration.test.js +32 -42
  21. package/test/createHooksToCollectChildren.test.js +61 -16
  22. package/test/crudFeaturePackagePattern.test.js +50 -0
  23. package/test/crudOnHandles.test.js +454 -0
  24. package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +444 -141
  25. package/test/errorCodes.test.js +11 -52
  26. package/test/hiddenFields.test.js +62 -0
  27. package/test/listQueryValidators.test.js +1 -1
  28. package/test/routeContracts.test.js +1 -1
  29. package/test/support/crudJsonApiActionOptions.js +3 -3
  30. package/test/unservedCrudAutomation.test.js +27 -22
  31. package/patterns/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
  32. package/patterns/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
  33. package/patterns/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
  34. package/src/server/createCrudServiceFromResource.js +0 -63
  35. package/src/server/defineCrudJsonApiFeature.js +0 -346
  36. package/src/server/fieldAccess.js +0 -298
  37. package/src/server/jsonApiModule/repository.js +0 -355
  38. package/src/server/lookupPathSupport.js +0 -58
  39. package/src/server/lookups.js +0 -40
  40. package/src/server/repositorySupport.js +0 -528
  41. package/src/server/resourceRuntime/compiledRuntime.js +0 -284
  42. package/src/server/resourceRuntime/index.js +0 -659
  43. package/src/server/resourceRuntime/listControls.js +0 -333
  44. package/src/server/resourceRuntime/lookupHydration.js +0 -626
  45. package/src/server/resourceRuntime/operationStages.js +0 -140
  46. package/src/server/resourceRuntime/recordValidation.js +0 -65
  47. package/src/server/serviceMethods.js +0 -149
  48. package/test/createCrudServiceFromResource.test.js +0 -323
  49. package/test/fieldAccess.test.js +0 -86
  50. package/test/jsonApiRepository.test.js +0 -333
  51. package/test/jsonApiRepositoryDataCosts.test.js +0 -183
  52. package/test/jsonApiRepositoryPageLimits.test.js +0 -158
  53. package/test/jsonApiRepositoryRowLocks.test.js +0 -137
  54. package/test/jsonApiResourcePackagePattern.test.js +0 -20
  55. package/test/lookups.test.js +0 -111
  56. package/test/repositorySupport.test.js +0 -767
  57. package/test/resourceRuntime.test.js +0 -1014
  58. package/test/serviceMethods.test.js +0 -139
  59. /package/patterns/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
  60. /package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
@@ -1,626 +0,0 @@
1
- import { isRecord, normalizeOpaqueId, normalizeText, normalizeUniqueTextList } from "@jskit-ai/kernel/shared/support/normalize";
2
- import { normalizeVisibilityContext } from "@jskit-ai/kernel/shared/support/visibility";
3
- import {
4
- normalizeCrudLookupApiPath,
5
- normalizeCrudLookupNamespace,
6
- resolveCrudLookupApiPathFromNamespace,
7
- resolveCrudLookupContainerKey
8
- } from "@jskit-ai/resource-crud-core/shared/crudLookup";
9
- import { buildCrudFieldContractMap } from "@jskit-ai/resource-crud-core/shared/crudFieldContract";
10
- import { normalizeLookupOwnershipFilter } from "../lookupPathSupport.js";
11
-
12
- const DEFAULT_LOOKUP_INCLUDE = "*";
13
- const DEFAULT_LOOKUP_MAX_DEPTH = 3;
14
- const MAX_LOOKUP_MAX_DEPTH = 10;
15
-
16
- /** @typedef {ReturnType<typeof buildCrudLookupRuntime>} LookupRuntime */
17
-
18
- function normalizeLookupRelationEntry(entry, outputKeys) {
19
- if (!isRecord(entry)) {
20
- return null;
21
- }
22
-
23
- const key = normalizeText(entry.key);
24
- if (!key) {
25
- return null;
26
- }
27
-
28
- const relation = entry.relation;
29
- if (!isRecord(relation)) {
30
- return null;
31
- }
32
-
33
- const relationKind = normalizeText(relation.kind).toLowerCase();
34
- if (relationKind !== "lookup" && relationKind !== "collection") {
35
- return null;
36
- }
37
-
38
- const namespace =
39
- normalizeCrudLookupNamespace(relation.namespace) ||
40
- normalizeCrudLookupNamespace(relation.apiPath);
41
- if (!namespace) {
42
- return null;
43
- }
44
- const explicitApiPath = normalizeCrudLookupApiPath(relation.apiPath);
45
- const apiPath = explicitApiPath || resolveCrudLookupApiPathFromNamespace(namespace);
46
-
47
- if (relationKind === "lookup") {
48
- if (!outputKeys.has(key)) {
49
- return null;
50
- }
51
- const valueKey = normalizeText(relation.valueKey) || "id";
52
-
53
- return Object.freeze({
54
- key,
55
- relation: Object.freeze({
56
- kind: "lookup",
57
- namespace,
58
- apiPath,
59
- valueKey,
60
- hydrateOnList: relation.hydrateOnList !== false,
61
- hydrateOnView: relation.hydrateOnView !== false
62
- })
63
- });
64
- }
65
-
66
- const foreignKey = normalizeText(relation.foreignKey);
67
- if (!foreignKey) {
68
- return null;
69
- }
70
-
71
- const parentValueKey = normalizeText(relation.parentValueKey) || "id";
72
- if (!outputKeys.has(parentValueKey)) {
73
- return null;
74
- }
75
-
76
- return Object.freeze({
77
- key,
78
- relation: Object.freeze({
79
- kind: "collection",
80
- namespace,
81
- apiPath,
82
- foreignKey,
83
- parentValueKey,
84
- hydrateOnList: relation.hydrateOnList !== false,
85
- hydrateOnView: relation.hydrateOnView !== false
86
- })
87
- });
88
- }
89
-
90
- function normalizeLookupDefaultInclude(value) {
91
- const normalized = normalizeText(value);
92
- if (!normalized) {
93
- return DEFAULT_LOOKUP_INCLUDE;
94
- }
95
-
96
- if (normalized.toLowerCase() === "none") {
97
- return "none";
98
- }
99
-
100
- return normalized;
101
- }
102
-
103
- function normalizeLookupMaxDepth(value) {
104
- const parsed = Number(value);
105
- if (!Number.isInteger(parsed) || parsed < 0) {
106
- return DEFAULT_LOOKUP_MAX_DEPTH;
107
- }
108
-
109
- return Math.min(parsed, MAX_LOOKUP_MAX_DEPTH);
110
- }
111
-
112
- function resolveLookupRuntimeDefaults(resource) {
113
- const lookupContract = resource.contract?.lookup;
114
- if (
115
- lookupContract !== undefined &&
116
- lookupContract !== null &&
117
- (typeof lookupContract !== "object" || Array.isArray(lookupContract))
118
- ) {
119
- throw new TypeError("crud lookup runtime requires resource.contract.lookup to be an object when provided.");
120
- }
121
-
122
- return {
123
- defaultInclude: normalizeLookupDefaultInclude(lookupContract?.defaultInclude),
124
- maxDepth: normalizeLookupMaxDepth(lookupContract?.maxDepth)
125
- };
126
- }
127
-
128
- /**
129
- * A resource's lookup relations, resolved once: the error context, the
130
- * resource's namespace and lookup container key, the default include and
131
- * depth, and each lookup entry, in order and by key.
132
- * @param {import("../types.js").CrudResourceDefinition} resource
133
- * @param {{ outputKeys: readonly string[], context: string }} options
134
- */
135
- function buildCrudLookupRuntime(resource, { outputKeys, context }) {
136
- const outputKeySet = new Set(outputKeys);
137
-
138
- const sourceEntries = Object.values(buildCrudFieldContractMap(resource, {
139
- context: "crud lookup runtime field contract"
140
- }));
141
- const lookupEntries = [];
142
- const seenKeys = new Set();
143
-
144
- for (const entry of sourceEntries) {
145
- const normalizedEntry = normalizeLookupRelationEntry(entry, outputKeySet);
146
- if (!normalizedEntry) {
147
- continue;
148
- }
149
-
150
- if (seenKeys.has(normalizedEntry.key)) {
151
- continue;
152
- }
153
- seenKeys.add(normalizedEntry.key);
154
- lookupEntries.push(normalizedEntry);
155
- }
156
-
157
- const lookupEntryByKey = lookupEntries.reduce((accumulator, entry) => {
158
- accumulator[entry.key] = entry;
159
- return accumulator;
160
- }, {});
161
-
162
- const containerKey = resolveCrudLookupContainerKey(resource, {
163
- context: "crud lookup runtime container key"
164
- });
165
- const namespace =
166
- normalizeCrudLookupNamespace(resource.namespace) ||
167
- normalizeCrudLookupNamespace(resource.apiPath);
168
- const defaults = resolveLookupRuntimeDefaults(resource);
169
-
170
- return Object.freeze({
171
- context,
172
- namespace,
173
- containerKey,
174
- defaultInclude: defaults.defaultInclude,
175
- maxDepth: defaults.maxDepth,
176
- entries: Object.freeze(lookupEntries),
177
- byKey: Object.freeze(lookupEntryByKey)
178
- });
179
- }
180
-
181
- function normalizeLookupIdentifier(value) {
182
- return normalizeOpaqueId(value, { fallback: "" });
183
- }
184
-
185
- /**
186
- * @param {unknown} include
187
- * @param {string} defaultInclude The lookup runtime's normalized default include.
188
- */
189
- function normalizeIncludePaths(include, defaultInclude) {
190
- const normalizedInclude = normalizeText(include) || defaultInclude;
191
- if (normalizedInclude.toLowerCase() === "none") {
192
- return [];
193
- }
194
-
195
- const tokens = normalizeUniqueTextList(normalizedInclude.split(","));
196
- const paths = [];
197
-
198
- for (const token of tokens) {
199
- const normalizedToken = normalizeText(token);
200
- if (!normalizedToken) {
201
- continue;
202
- }
203
-
204
- if (normalizedToken.toLowerCase() === "none") {
205
- return [];
206
- }
207
-
208
- const segments = normalizedToken
209
- .split(".")
210
- .map((entry) => normalizeText(entry))
211
- .filter(Boolean);
212
-
213
- if (segments.length > 0) {
214
- paths.push(segments);
215
- }
216
- }
217
-
218
- return paths;
219
- }
220
-
221
- /** @param {string[][]} paths Normalized include paths below one lookup. */
222
- function resolveChildIncludeFromPaths(paths) {
223
- const pathKeys = new Set();
224
- let includesAll = false;
225
-
226
- for (const path of paths) {
227
- if (path.length < 1) {
228
- continue;
229
- }
230
- if (path[0] === "*") {
231
- includesAll = true;
232
- continue;
233
- }
234
-
235
- pathKeys.add(path.join("."));
236
- }
237
-
238
- if (includesAll) {
239
- return "*";
240
- }
241
- if (pathKeys.size < 1) {
242
- return "none";
243
- }
244
- return [...pathKeys].join(",");
245
- }
246
-
247
- function shouldHydrateByMode(entry, mode) {
248
- const relation = entry.relation;
249
- if (mode === "view") {
250
- return relation.hydrateOnView !== false;
251
- }
252
- return relation.hydrateOnList !== false;
253
- }
254
-
255
- /**
256
- * @param {LookupRuntime} runtime
257
- * @param {unknown} include
258
- * @param {{ mode: string, includeWasExplicit: boolean, skippedNamespaces: Set<string> }} options
259
- */
260
- function buildLookupHydrationPlan(runtime, include, { mode, includeWasExplicit, skippedNamespaces }) {
261
- const { context, entries } = runtime;
262
- const includePaths = normalizeIncludePaths(include, runtime.defaultInclude);
263
- if (includePaths.length < 1) {
264
- return {
265
- entries: [],
266
- childIncludeByKey: {}
267
- };
268
- }
269
-
270
- if (entries.length < 1) {
271
- const wildcardOnlyInclude = includePaths.every((pathSegments) => pathSegments[0] === "*");
272
- if (includeWasExplicit === true && wildcardOnlyInclude !== true) {
273
- throw new Error(`${context} include requires lookups, but the resource declares no lookup relations.`);
274
- }
275
- return {
276
- entries: [],
277
- childIncludeByKey: {}
278
- };
279
- }
280
-
281
- const selectedEntries = [];
282
- const childIncludeByKey = {};
283
- const seenKeys = new Set();
284
-
285
- function appendEntry(entry, childPaths) {
286
- if (seenKeys.has(entry.key)) {
287
- return;
288
- }
289
-
290
- if (!includeWasExplicit && !shouldHydrateByMode(entry, mode)) {
291
- return;
292
- }
293
-
294
- if (skippedNamespaces.has(entry.relation.namespace)) {
295
- return;
296
- }
297
-
298
- seenKeys.add(entry.key);
299
- selectedEntries.push(entry);
300
- childIncludeByKey[entry.key] = resolveChildIncludeFromPaths(childPaths);
301
- }
302
-
303
- const includeAll = includePaths.some((segments) => segments[0] === "*");
304
- if (includeAll) {
305
- for (const entry of entries) {
306
- appendEntry(entry, [["*"]]);
307
- }
308
- }
309
-
310
- for (const pathSegments of includePaths) {
311
- const [head, ...tail] = pathSegments;
312
- if (head === "*") {
313
- continue;
314
- }
315
-
316
- const entry = runtime.byKey[head];
317
- if (!entry) {
318
- throw new Error(`${context} include references unknown lookup key "${head}".`);
319
- }
320
-
321
- appendEntry(
322
- entry,
323
- tail.length > 0
324
- ? [tail]
325
- : []
326
- );
327
- }
328
-
329
- return {
330
- entries: selectedEntries,
331
- childIncludeByKey
332
- };
333
- }
334
-
335
- function resolveLookupResolver(repositoryOptions, callOptions, { context }) {
336
- const resolver = callOptions.resolveLookup || repositoryOptions.resolveLookup;
337
- // readable-check: allow method-probe - input validation: the application passes resolveLookup(relation) in its options
338
- if (typeof resolver !== "function") {
339
- throw new TypeError(`${context} requires resolveLookup(relation) to hydrate lookups.`);
340
- }
341
- return resolver;
342
- }
343
-
344
- function resolveLookupDepthRuntime(runtime, repositoryOptions, callOptions) {
345
- const maxDepth = normalizeLookupMaxDepth(
346
- callOptions.lookupMaxDepth ?? repositoryOptions.lookupMaxDepth ?? runtime.maxDepth
347
- );
348
-
349
- const parsedDepth = Number(callOptions.lookupDepth);
350
- const depth = Number.isInteger(parsedDepth) && parsedDepth >= 0 ? parsedDepth : 0;
351
-
352
- return {
353
- depth,
354
- maxDepth
355
- };
356
- }
357
-
358
- function buildLookupGroupKey(relation) {
359
- if (relation.kind === "collection") {
360
- return `collection::${relation.namespace}::${relation.foreignKey}::${relation.parentValueKey}`;
361
- }
362
- return `lookup::${relation.namespace}::${relation.valueKey}`;
363
- }
364
-
365
- function normalizeLookupRelationValues(records, entries, childIncludeByKey) {
366
- const byGroup = new Map();
367
- for (const entry of entries) {
368
- const relation = entry.relation;
369
- const groupKey = buildLookupGroupKey(relation);
370
- if (!byGroup.has(groupKey)) {
371
- byGroup.set(groupKey, {
372
- relation,
373
- entries: [],
374
- values: [],
375
- childIncludes: new Set()
376
- });
377
- }
378
-
379
- const group = byGroup.get(groupKey);
380
- group.entries.push(entry);
381
- group.childIncludes.add(normalizeText(childIncludeByKey[entry.key]) || "none");
382
- }
383
-
384
- for (const group of byGroup.values()) {
385
- const seen = new Set();
386
- for (const record of records) {
387
- for (const entry of group.entries) {
388
- const relation = entry.relation;
389
- const rawValue = relation.kind === "collection"
390
- ? record[relation.parentValueKey]
391
- : record[entry.key];
392
- const normalized = normalizeLookupIdentifier(rawValue);
393
- if (!normalized || seen.has(normalized)) {
394
- continue;
395
- }
396
- seen.add(normalized);
397
- group.values.push(rawValue);
398
- }
399
- }
400
- }
401
-
402
- return byGroup;
403
- }
404
-
405
- function resolveGroupChildInclude(group) {
406
- const includeSet = new Set();
407
- let includeAll = false;
408
-
409
- for (const includeValue of group.childIncludes) {
410
- const normalized = normalizeText(includeValue);
411
- if (!normalized || normalized.toLowerCase() === "none") {
412
- continue;
413
- }
414
-
415
- if (normalized === "*") {
416
- includeAll = true;
417
- continue;
418
- }
419
-
420
- for (const token of normalizeUniqueTextList(normalized.split(","))) {
421
- if (token === "*") {
422
- includeAll = true;
423
- continue;
424
- }
425
- includeSet.add(token);
426
- }
427
- }
428
-
429
- if (includeAll) {
430
- return "*";
431
- }
432
- if (includeSet.size < 1) {
433
- return "none";
434
- }
435
- return [...includeSet].join(",");
436
- }
437
-
438
- function normalizeLookup(provider, relation, { context }) {
439
- // readable-check: allow method-probe - input validation: an application's resolveLookup must return a provider object
440
- if (!isRecord(provider)) {
441
- throw new Error(`${context} could not resolve lookup "${relation.namespace}".`);
442
- }
443
- // readable-check: allow method-probe - input validation: an application's resolveLookup must return a provider with listByIds()
444
- if (typeof provider.listByIds !== "function") {
445
- throw new Error(`${context} lookup "${relation.namespace}" must expose listByIds(ids, options).`);
446
- }
447
- return provider;
448
- }
449
-
450
- function resolveLookupVisibilityContext(provider, relation, callOptions, { context }) {
451
- const parentVisibilityContext = normalizeVisibilityContext(callOptions.visibilityContext);
452
- const lookupOwnershipFilter = normalizeLookupOwnershipFilter(provider.ownershipFilter, {
453
- context: `${context} lookup ownershipFilter`
454
- });
455
-
456
- if (!lookupOwnershipFilter) {
457
- if (parentVisibilityContext.visibility !== "public") {
458
- throw new Error(
459
- `${context} lookup "${relation.namespace}" must declare ownershipFilter when parent visibility is "${parentVisibilityContext.visibility}".`
460
- );
461
- }
462
- return callOptions.visibilityContext;
463
- }
464
-
465
- const nextVisibilityContext = {
466
- visibility: lookupOwnershipFilter
467
- };
468
- if (lookupOwnershipFilter === "workspace" || lookupOwnershipFilter === "workspace_user") {
469
- nextVisibilityContext.scopeOwnerId = parentVisibilityContext.scopeOwnerId;
470
- }
471
- if (lookupOwnershipFilter === "user" || lookupOwnershipFilter === "workspace_user") {
472
- nextVisibilityContext.userId = parentVisibilityContext.userId;
473
- }
474
-
475
- return nextVisibilityContext;
476
- }
477
-
478
- function buildLookupRecordMap(records, valueKey) {
479
- const lookupMap = new Map();
480
- for (const record of Array.isArray(records) ? records : []) {
481
- const lookupId = normalizeLookupIdentifier(record?.[valueKey]);
482
- if (!lookupId || lookupMap.has(lookupId)) {
483
- continue;
484
- }
485
- lookupMap.set(lookupId, record);
486
- }
487
- return lookupMap;
488
- }
489
-
490
- function buildLookupCollectionMap(records, foreignKey) {
491
- const collectionMap = new Map();
492
- for (const record of Array.isArray(records) ? records : []) {
493
- const ownerId = normalizeLookupIdentifier(record?.[foreignKey]);
494
- if (!ownerId) {
495
- continue;
496
- }
497
- const currentRecords = collectionMap.get(ownerId);
498
- if (currentRecords) {
499
- currentRecords.push(record);
500
- continue;
501
- }
502
- collectionMap.set(ownerId, [record]);
503
- }
504
- return collectionMap;
505
- }
506
-
507
- function resolveLookupVisitedNamespaces(runtime, callOptions) {
508
- const namespaces = [];
509
- const seen = new Set();
510
-
511
- function appendNamespace(value) {
512
- const normalized = normalizeCrudLookupNamespace(value);
513
- if (!normalized || seen.has(normalized)) {
514
- return;
515
- }
516
- seen.add(normalized);
517
- namespaces.push(normalized);
518
- }
519
-
520
- const sourceVisitedNamespaces = Array.isArray(callOptions.lookupVisitedNamespaces)
521
- ? callOptions.lookupVisitedNamespaces
522
- : [];
523
- for (const namespace of sourceVisitedNamespaces) {
524
- appendNamespace(namespace);
525
- }
526
- appendNamespace(runtime.namespace);
527
-
528
- return namespaces;
529
- }
530
-
531
- /**
532
- * Records with their lookups hydrated under the lookup container key, up to the lookup depth.
533
- * @param {object[]} records
534
- * @param {LookupRuntime} runtime
535
- * @param {{ include: unknown, mode: "list" | "view", repositoryOptions: object, callOptions: object }} options
536
- */
537
- async function hydrateCrudLookupRecords(records, runtime, { include, mode, repositoryOptions, callOptions }) {
538
- const { context, containerKey: lookupContainerKey } = runtime;
539
- if (records.length < 1) {
540
- return records;
541
- }
542
-
543
- const depthRuntime = resolveLookupDepthRuntime(runtime, repositoryOptions, callOptions);
544
- if (depthRuntime.depth >= depthRuntime.maxDepth) {
545
- return records;
546
- }
547
-
548
- const visitedNamespaces = resolveLookupVisitedNamespaces(runtime, callOptions);
549
-
550
- const lookupPlan = buildLookupHydrationPlan(runtime, include, {
551
- mode,
552
- includeWasExplicit: normalizeText(include).length > 0,
553
- skippedNamespaces: new Set(visitedNamespaces)
554
- });
555
- const selectedEntries = lookupPlan.entries;
556
- if (selectedEntries.length < 1) {
557
- return records;
558
- }
559
-
560
- const resolveLookup = resolveLookupResolver(repositoryOptions, callOptions, { context });
561
-
562
- const relationGroups = normalizeLookupRelationValues(records, selectedEntries, lookupPlan.childIncludeByKey);
563
- const groupRecordMaps = new Map();
564
- for (const group of relationGroups.values()) {
565
- if (group.values.length < 1) {
566
- groupRecordMaps.set(buildLookupGroupKey(group.relation), new Map());
567
- continue;
568
- }
569
-
570
- const provider = normalizeLookup(resolveLookup(group.relation), group.relation, { context });
571
- const childVisibilityContext = resolveLookupVisibilityContext(provider, group.relation, callOptions, { context });
572
- const childInclude = resolveGroupChildInclude(group);
573
- const groupValueKey = group.relation.kind === "collection"
574
- ? group.relation.foreignKey
575
- : group.relation.valueKey;
576
- const groupRecords = await provider.listByIds(group.values, {
577
- ...callOptions,
578
- visibilityContext: childVisibilityContext,
579
- include: childInclude,
580
- lookupDepth: depthRuntime.depth + 1,
581
- lookupMaxDepth: depthRuntime.maxDepth,
582
- lookupVisitedNamespaces: visitedNamespaces,
583
- valueKey: groupValueKey
584
- });
585
- groupRecordMaps.set(
586
- buildLookupGroupKey(group.relation),
587
- group.relation.kind === "collection"
588
- ? buildLookupCollectionMap(groupRecords, group.relation.foreignKey)
589
- : buildLookupRecordMap(groupRecords, group.relation.valueKey)
590
- );
591
- }
592
-
593
- return records.map((record) => {
594
- const baseRecord = isRecord(record) ? record : {};
595
- const existingLookups = isRecord(baseRecord[lookupContainerKey])
596
- ? baseRecord[lookupContainerKey]
597
- : {};
598
- const nextLookups = { ...existingLookups };
599
-
600
- for (const entry of selectedEntries) {
601
- const relation = entry.relation;
602
- const lookupMap = groupRecordMaps.get(buildLookupGroupKey(relation)) || new Map();
603
- if (relation.kind === "collection") {
604
- const ownerId = normalizeLookupIdentifier(baseRecord[relation.parentValueKey]);
605
- nextLookups[entry.key] = ownerId ? (lookupMap.get(ownerId) || []) : [];
606
- continue;
607
- }
608
- const lookupId = normalizeLookupIdentifier(baseRecord[entry.key]);
609
- if (!lookupId) {
610
- nextLookups[entry.key] = null;
611
- continue;
612
- }
613
- nextLookups[entry.key] = lookupMap.get(lookupId) || null;
614
- }
615
-
616
- return {
617
- ...baseRecord,
618
- [lookupContainerKey]: nextLookups
619
- };
620
- });
621
- }
622
-
623
- export {
624
- buildCrudLookupRuntime,
625
- hydrateCrudLookupRecords
626
- };