@jskit-ai/crud-core 0.2.13 → 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.
- package/CHANGELOG.md +16 -0
- package/locales/en.json +1 -11
- package/package.json +19 -19
- package/patterns/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
- package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
- package/patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
- package/patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
- package/patterns/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
- package/src/server/createHooksToCollectChildren.js +56 -34
- package/src/server/crudContracts.js +54 -0
- package/src/server/defineCrudFeature.js +509 -0
- package/src/server/jsonApiModule/actions.js +44 -30
- package/src/server/jsonApiModule/routes.js +2 -2
- package/src/server/jsonApiModule/service.js +213 -32
- package/src/server/jsonApiResourceContract.js +41 -1
- package/src/server/listQueryValidators.js +1 -1
- package/src/server/removedApi.js +87 -0
- package/src/server/types.js +26 -50
- package/test/assistantActionConformance.test.js +20 -21
- package/test/assistantPagination.integration.test.js +32 -42
- package/test/createHooksToCollectChildren.test.js +61 -16
- package/test/crudFeaturePackagePattern.test.js +50 -0
- package/test/crudOnHandles.test.js +454 -0
- package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +444 -141
- package/test/errorCodes.test.js +11 -52
- package/test/hiddenFields.test.js +62 -0
- package/test/listQueryValidators.test.js +1 -1
- package/test/routeContracts.test.js +1 -1
- package/test/support/crudJsonApiActionOptions.js +3 -3
- package/test/unservedCrudAutomation.test.js +27 -22
- package/patterns/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
- package/patterns/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
- package/patterns/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
- package/src/server/createCrudServiceFromResource.js +0 -63
- package/src/server/defineCrudJsonApiFeature.js +0 -346
- package/src/server/fieldAccess.js +0 -298
- package/src/server/jsonApiModule/repository.js +0 -355
- package/src/server/lookupPathSupport.js +0 -58
- package/src/server/lookups.js +0 -40
- package/src/server/repositorySupport.js +0 -528
- package/src/server/resourceRuntime/compiledRuntime.js +0 -284
- package/src/server/resourceRuntime/index.js +0 -659
- package/src/server/resourceRuntime/listControls.js +0 -333
- package/src/server/resourceRuntime/lookupHydration.js +0 -626
- package/src/server/resourceRuntime/operationStages.js +0 -140
- package/src/server/resourceRuntime/recordValidation.js +0 -65
- package/src/server/serviceMethods.js +0 -149
- package/test/createCrudServiceFromResource.test.js +0 -323
- package/test/fieldAccess.test.js +0 -86
- package/test/jsonApiRepository.test.js +0 -333
- package/test/jsonApiRepositoryDataCosts.test.js +0 -183
- package/test/jsonApiRepositoryPageLimits.test.js +0 -158
- package/test/jsonApiRepositoryRowLocks.test.js +0 -137
- package/test/jsonApiResourcePackagePattern.test.js +0 -20
- package/test/lookups.test.js +0 -111
- package/test/repositorySupport.test.js +0 -767
- package/test/resourceRuntime.test.js +0 -1014
- package/test/serviceMethods.test.js +0 -139
- /package/patterns/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
- /package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The CRUD contracts an application serves, one per namespace. Each CRUD
|
|
5
|
+
* feature registers its contract during setup, and the registry is sealed at
|
|
6
|
+
* boot. A contract never shapes another contract's answers: an included
|
|
7
|
+
* record shows only what the including contract names (see the CRUD service).
|
|
8
|
+
*/
|
|
9
|
+
function createCrudContracts() {
|
|
10
|
+
/** @type {import("./types.js").CrudContract[]} */
|
|
11
|
+
const registered = [];
|
|
12
|
+
let sealed = false;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Adds a served contract. One contract served on several surfaces registers once; two contracts under one namespace
|
|
16
|
+
* are refused, since the namespace names one API.
|
|
17
|
+
* @param {import("./types.js").CrudContract} crud
|
|
18
|
+
*/
|
|
19
|
+
function register(crud) {
|
|
20
|
+
if (sealed) {
|
|
21
|
+
throw new Error(`CRUD contract "${crud.namespace}" registered after boot: CRUD features register their contracts during setup.`);
|
|
22
|
+
}
|
|
23
|
+
const same = registered.find((entry) => entry.namespace === crud.namespace);
|
|
24
|
+
if (same && same !== crud) {
|
|
25
|
+
throw new Error(`Two CRUD contracts are served under the namespace "${crud.namespace}". Give each contract its own namespace.`);
|
|
26
|
+
}
|
|
27
|
+
if (!same) {
|
|
28
|
+
registered.push(crud);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function seal() {
|
|
33
|
+
sealed = true;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return Object.freeze({
|
|
37
|
+
register,
|
|
38
|
+
seal
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const CrudContractsProvider = defineProvider({
|
|
43
|
+
id: "crud.contracts",
|
|
44
|
+
provides: {
|
|
45
|
+
contracts: "crud.contracts"
|
|
46
|
+
},
|
|
47
|
+
setup: () => ({ contracts: createCrudContracts() }),
|
|
48
|
+
/** @param {object} _dependencies @param {{ outputs: { contracts: ReturnType<typeof createCrudContracts> } }} context */
|
|
49
|
+
boot(_dependencies, { outputs }) {
|
|
50
|
+
outputs.contracts.seal();
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
export { CrudContractsProvider, createCrudContracts };
|
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
import { defineFeature } from "@jskit-ai/kernel/server/features";
|
|
2
|
+
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
|
+
import { isWorkspaceRouteVisibility } from "@jskit-ai/kernel/shared/support/visibility";
|
|
4
|
+
import { isTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
5
|
+
import { withoutHiddenFields } from "@jskit-ai/resource-runtime/server";
|
|
6
|
+
import { isCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
|
|
7
|
+
import {
|
|
8
|
+
assertCrudOperationName,
|
|
9
|
+
createCrudJsonApiActions,
|
|
10
|
+
normalizeCrudOperationLifecycle
|
|
11
|
+
} from "./jsonApiModule/actions.js";
|
|
12
|
+
import { registerCrudJsonApiRoutes } from "./jsonApiModule/routes.js";
|
|
13
|
+
import { createCrudService } from "./jsonApiModule/service.js";
|
|
14
|
+
import {
|
|
15
|
+
LEGACY_REPOSITORY_METHODS,
|
|
16
|
+
LEGACY_SERVICE_METHODS,
|
|
17
|
+
rejectLegacyMethods,
|
|
18
|
+
withRemovedProperties
|
|
19
|
+
} from "./removedApi.js";
|
|
20
|
+
|
|
21
|
+
const RESERVED_REQUIREMENT_NAMES = Object.freeze([
|
|
22
|
+
"context",
|
|
23
|
+
"crud",
|
|
24
|
+
"crudContracts",
|
|
25
|
+
"http",
|
|
26
|
+
"input",
|
|
27
|
+
"options",
|
|
28
|
+
"ownerRepository",
|
|
29
|
+
"repository",
|
|
30
|
+
"resource",
|
|
31
|
+
"resources",
|
|
32
|
+
"result",
|
|
33
|
+
"service",
|
|
34
|
+
"standard",
|
|
35
|
+
"systemContext"
|
|
36
|
+
]);
|
|
37
|
+
const CRUD_SERVICE_METHOD_BY_OPERATION = Object.freeze({
|
|
38
|
+
list: "list",
|
|
39
|
+
view: "view",
|
|
40
|
+
create: "create",
|
|
41
|
+
update: "patch",
|
|
42
|
+
delete: "delete"
|
|
43
|
+
});
|
|
44
|
+
const CRUD_SERVICE_METHODS = new Set(Object.values(CRUD_SERVICE_METHOD_BY_OPERATION));
|
|
45
|
+
const CRUD_ACTION_OPERATIONS = Object.freeze(Object.keys(CRUD_SERVICE_METHOD_BY_OPERATION));
|
|
46
|
+
// The options defineCrudFeature takes.
|
|
47
|
+
const FEATURE_OPTIONS = new Set([
|
|
48
|
+
"crud",
|
|
49
|
+
"id",
|
|
50
|
+
"capability",
|
|
51
|
+
"surface",
|
|
52
|
+
"owns",
|
|
53
|
+
"ownerRepository",
|
|
54
|
+
"visibility",
|
|
55
|
+
"systemScope",
|
|
56
|
+
"relativePath",
|
|
57
|
+
"internal",
|
|
58
|
+
"routes",
|
|
59
|
+
"listFilterQueryValidator",
|
|
60
|
+
"permissions",
|
|
61
|
+
"scope",
|
|
62
|
+
"requires",
|
|
63
|
+
"decorateRepository",
|
|
64
|
+
"decorateService",
|
|
65
|
+
"operationLifecycle",
|
|
66
|
+
"operationInputs",
|
|
67
|
+
"actions",
|
|
68
|
+
"operations",
|
|
69
|
+
"realtimeAudience"
|
|
70
|
+
]);
|
|
71
|
+
// Options the earlier CRUD feature took, and where each now goes.
|
|
72
|
+
const REPLACED_FEATURE_OPTIONS = Object.freeze({
|
|
73
|
+
resource: "crud, the CRUD contract",
|
|
74
|
+
ownershipFilter: "visibility",
|
|
75
|
+
searchSchema: "an owns entry: owns: [{ resource, searchSchema }]",
|
|
76
|
+
rowPolicy: "an owns entry: owns: [{ resource, rowPolicy }]",
|
|
77
|
+
queryFields: "an owns entry: owns: [{ resource, queryFields }]",
|
|
78
|
+
hooks: "an owns entry: owns: [{ resource, hooks }]"
|
|
79
|
+
});
|
|
80
|
+
// What decorateRepository, decorateService and the feature's capability no longer carry.
|
|
81
|
+
const RESOURCE_RENAMED = "it is now crud, the CRUD contract.";
|
|
82
|
+
const REMOVED_REPOSITORY_DEPENDENCIES = Object.freeze({
|
|
83
|
+
resource: RESOURCE_RENAMED,
|
|
84
|
+
database: "read and write through repository and resources (each owned table's handle), and open a transaction with repository.withTransaction(options, work).",
|
|
85
|
+
http: "defineCrudFeature registers the routes; name any other capability the repository needs in requires.",
|
|
86
|
+
jsonRestApi: "each owned table's handle is in resources, by its resource name."
|
|
87
|
+
});
|
|
88
|
+
const REMOVED_SERVICE_DEPENDENCIES = Object.freeze({ resource: RESOURCE_RENAMED });
|
|
89
|
+
const REMOVED_RESOURCE_API = Object.freeze({ resource: RESOURCE_RENAMED });
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Refuses an option defineCrudFeature does not take, naming where an earlier
|
|
93
|
+
* option now goes, so a setting is never silently ignored.
|
|
94
|
+
* @param {Record<string, unknown>} options
|
|
95
|
+
*/
|
|
96
|
+
function assertKnownOptions(options) {
|
|
97
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) {
|
|
98
|
+
throw new TypeError("defineCrudFeature takes an options object.");
|
|
99
|
+
}
|
|
100
|
+
for (const name of Object.keys(options)) {
|
|
101
|
+
if (FEATURE_OPTIONS.has(name)) {
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (Object.hasOwn(REPLACED_FEATURE_OPTIONS, name)) {
|
|
105
|
+
throw new TypeError(`defineCrudFeature no longer takes ${name}: use ${REPLACED_FEATURE_OPTIONS[name]}.`);
|
|
106
|
+
}
|
|
107
|
+
throw new TypeError(`defineCrudFeature does not take ${name}. Its options are ${[...FEATURE_OPTIONS].join(", ")}.`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Refuses a permission for anything but an action the feature defines: one of
|
|
113
|
+
* its operations (list, view, create, update, delete) or a custom action.
|
|
114
|
+
* @param {object | null} permissions
|
|
115
|
+
* @param {object} actions
|
|
116
|
+
*/
|
|
117
|
+
function assertPermissionNames(permissions, actions) {
|
|
118
|
+
if (!permissions || typeof permissions !== "object" || Array.isArray(permissions)) {
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
// An action's permission is read under its lower-case name.
|
|
122
|
+
const actionNames = new Set([...CRUD_ACTION_OPERATIONS, ...Object.keys(actions)].map((name) => normalizeText(name).toLowerCase()));
|
|
123
|
+
for (const name of Object.keys(permissions)) {
|
|
124
|
+
const actionName = normalizeText(name).toLowerCase();
|
|
125
|
+
if (!actionNames.has(actionName)) {
|
|
126
|
+
const hint = actionName === "patch" ? ' (a patch is the "update" action)' : "";
|
|
127
|
+
throw new TypeError(
|
|
128
|
+
`defineCrudFeature permissions.${name} names no action of the feature${hint}. ` +
|
|
129
|
+
`Its actions are ${[...actionNames].join(", ")}.`
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
if (actionName !== name) {
|
|
133
|
+
throw new TypeError(`defineCrudFeature reads the permission of action ${name} as permissions.${actionName}; name it so.`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Refuses a service that lacks, as its own property, a method an enabled
|
|
140
|
+
* operation's route and action call, so the feature fails at boot rather than
|
|
141
|
+
* on a request.
|
|
142
|
+
* @param {object} service
|
|
143
|
+
* @param {readonly string[]} operations
|
|
144
|
+
*/
|
|
145
|
+
function assertServiceOperations(service, operations) {
|
|
146
|
+
for (const operation of operations) {
|
|
147
|
+
const method = CRUD_SERVICE_METHOD_BY_OPERATION[operation];
|
|
148
|
+
// readable-check: allow method-probe - input validation: decorateService returns the application's own service
|
|
149
|
+
if (typeof service?.[method] !== "function") {
|
|
150
|
+
throw new TypeError(
|
|
151
|
+
`defineCrudFeature decorateService must return a service with its own ${method}(), which the ${operation} operation calls; ` +
|
|
152
|
+
"spread the service it is given ({ ...service, ... }) to keep the standard one."
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function normalizeAccess(crud = {}) {
|
|
159
|
+
const access = normalizeText(crud.apiAccess).toLowerCase() || "authenticated";
|
|
160
|
+
if (access !== "authenticated" && access !== "public") {
|
|
161
|
+
throw new TypeError('defineCrudFeature crud apiAccess must be "authenticated" or "public".');
|
|
162
|
+
}
|
|
163
|
+
return access;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function normalizeScope(scope = {}) {
|
|
167
|
+
if (!scope || typeof scope !== "object" || Array.isArray(scope)) {
|
|
168
|
+
throw new TypeError("defineCrudFeature scope must be an object.");
|
|
169
|
+
}
|
|
170
|
+
return Object.freeze({
|
|
171
|
+
routeBase: normalizeText(scope.routeBase) || "/",
|
|
172
|
+
actionInputValidator: scope.actionInputValidator || null,
|
|
173
|
+
routeParamsValidator: scope.routeParamsValidator || null,
|
|
174
|
+
inputKeys: Object.freeze([...new Set(
|
|
175
|
+
(Array.isArray(scope.inputKeys) ? scope.inputKeys : [])
|
|
176
|
+
.map((entry) => normalizeText(entry))
|
|
177
|
+
.filter(Boolean)
|
|
178
|
+
)]),
|
|
179
|
+
// readable-check: allow method-probe - input validation: the scope an application passes may define input()
|
|
180
|
+
input: typeof scope.input === "function" ? scope.input : null
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// The route visibility of a table's ownership: a workspace_or_shared table's routes are a workspace's.
|
|
185
|
+
function routeOwnership(ownership) {
|
|
186
|
+
return ownership === "workspace_or_shared" ? "workspace" : ownership;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The feature's owns: its CRUD contract's table resource first, unless an
|
|
191
|
+
* entry gives that resource its server-only extras, then the other tables.
|
|
192
|
+
* A feature serving another owner's table owns only the other tables, if any.
|
|
193
|
+
* @param {import("./types.js").CrudContract} crud
|
|
194
|
+
* @param {ReadonlyArray<object>} owns
|
|
195
|
+
* @param {string} ownerRepository
|
|
196
|
+
*/
|
|
197
|
+
function crudOwns(crud, owns, ownerRepository) {
|
|
198
|
+
if (!Array.isArray(owns)) {
|
|
199
|
+
throw new TypeError("defineCrudFeature owns must be an array of table resources or { resource, ...extras } entries.");
|
|
200
|
+
}
|
|
201
|
+
const ownsCrudResource = owns.some((entry) => (isTableResource(entry) ? entry : entry?.resource) === crud.resource);
|
|
202
|
+
if (ownerRepository) {
|
|
203
|
+
if (ownsCrudResource) {
|
|
204
|
+
throw new TypeError(`defineCrudFeature serves "${crud.resource.name}" through ${ownerRepository}, so it cannot own it too.`);
|
|
205
|
+
}
|
|
206
|
+
return owns.length > 0 ? Object.freeze([...owns]) : undefined;
|
|
207
|
+
}
|
|
208
|
+
return Object.freeze(ownsCrudResource ? [...owns] : [crud.resource, ...owns]);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function assertWorkspaceScope(scope, ownershipFilter) {
|
|
212
|
+
if (!isWorkspaceRouteVisibility(ownershipFilter)) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const missing = [];
|
|
216
|
+
if (scope.routeBase === "/") missing.push("routeBase");
|
|
217
|
+
if (!scope.actionInputValidator) missing.push("actionInputValidator");
|
|
218
|
+
if (!scope.routeParamsValidator) missing.push("routeParamsValidator");
|
|
219
|
+
if (scope.inputKeys.length < 1) missing.push("inputKeys");
|
|
220
|
+
if (!scope.input) missing.push("input");
|
|
221
|
+
if (missing.length > 0) {
|
|
222
|
+
throw new TypeError(
|
|
223
|
+
`Workspace CRUD feature requires explicit scope ${missing.join(", ")}.`
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function normalizeFeatureRequirements(requires = {}) {
|
|
229
|
+
if (!requires || typeof requires !== "object" || Array.isArray(requires)) {
|
|
230
|
+
throw new TypeError("defineCrudFeature requires must be an object.");
|
|
231
|
+
}
|
|
232
|
+
for (const name of RESERVED_REQUIREMENT_NAMES) {
|
|
233
|
+
if (Object.hasOwn(requires, name)) {
|
|
234
|
+
throw new TypeError(`defineCrudFeature requires reserves the local name ${name}.`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return Object.freeze({ ...requires });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function operationsFromResource(resource) {
|
|
241
|
+
const operationMap = Object.freeze({
|
|
242
|
+
list: "list",
|
|
243
|
+
view: "view",
|
|
244
|
+
create: "create",
|
|
245
|
+
patch: "update",
|
|
246
|
+
delete: "delete"
|
|
247
|
+
});
|
|
248
|
+
return Object.keys(resource?.operations || {})
|
|
249
|
+
.map((operation) => operationMap[operation])
|
|
250
|
+
.filter(Boolean);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function normalizeOperations(operations, resource) {
|
|
254
|
+
const source = operations === undefined ? operationsFromResource(resource) : operations;
|
|
255
|
+
if (!Array.isArray(source) || source.length < 1) {
|
|
256
|
+
throw new TypeError("defineCrudFeature operations must be a non-empty array.");
|
|
257
|
+
}
|
|
258
|
+
return Object.freeze([...new Set(source.map((operation) => assertCrudOperationName(operation)))]);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* @param {string} actionName
|
|
263
|
+
* @param {{ access: string, workspaceScoped: boolean, permissions: { namespace: string } & Record<string, unknown> }} policy
|
|
264
|
+
*/
|
|
265
|
+
function resolveActionPermission(actionName, { access, workspaceScoped, permissions }) {
|
|
266
|
+
const normalizedActionName = normalizeText(actionName).toLowerCase();
|
|
267
|
+
if (!normalizedActionName) {
|
|
268
|
+
throw new TypeError("CRUD action name is required.");
|
|
269
|
+
}
|
|
270
|
+
const explicitPermission = permissions[normalizedActionName];
|
|
271
|
+
if (explicitPermission && typeof explicitPermission === "object") {
|
|
272
|
+
return explicitPermission;
|
|
273
|
+
}
|
|
274
|
+
if (typeof explicitPermission === "string" && explicitPermission.trim()) {
|
|
275
|
+
return Object.freeze({
|
|
276
|
+
require: "all",
|
|
277
|
+
permissions: [explicitPermission.trim()]
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
if (access === "public") {
|
|
281
|
+
return Object.freeze({ require: "none" });
|
|
282
|
+
}
|
|
283
|
+
if (workspaceScoped) {
|
|
284
|
+
return Object.freeze({
|
|
285
|
+
require: "all",
|
|
286
|
+
permissions: [`crud.${permissions.namespace}.${normalizedActionName}`]
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
return Object.freeze({ require: "authenticated" });
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function projectEnabledServiceOperations(service, operations) {
|
|
293
|
+
const enabledMethods = new Set(operations.map((operation) => CRUD_SERVICE_METHOD_BY_OPERATION[operation]));
|
|
294
|
+
return Object.freeze(Object.fromEntries(
|
|
295
|
+
Object.entries(service).filter(([name]) => !CRUD_SERVICE_METHODS.has(name) || enabledMethods.has(name))
|
|
296
|
+
));
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* A feature serving a CRUD contract over HTTP and the action catalogue. It owns
|
|
301
|
+
* the contract's table resource (and the tables in `owns`): its repository is
|
|
302
|
+
* that table's handle, which `decorateRepository` may wrap, and its CRUD service
|
|
303
|
+
* (list, view, create, patch, delete) is the HTTP edge, answering JSON:API
|
|
304
|
+
* documents. The capability's repository refuses a read whose `fields` names a
|
|
305
|
+
* hidden field of the table unless it runs in a system context: the methods
|
|
306
|
+
* decorateRepository adds read them with the handle itself.
|
|
307
|
+
* @param {object} feature
|
|
308
|
+
* @param {import("./types.js").CrudContract} feature.crud The CRUD contract the feature serves, on its table resource.
|
|
309
|
+
* @param {string} feature.surface The surface whose routes serve it.
|
|
310
|
+
* @param {ReadonlyArray<object>} [feature.owns] More tables the feature owns, and `{ resource, rowPolicy, hooks, searchSchema, ... }`
|
|
311
|
+
* entries giving a table, the CRUD's own among them, its server-only extras.
|
|
312
|
+
* @param {string} [feature.ownerRepository] The capability of the repository another feature, the table's one owner,
|
|
313
|
+
* provides for it, such as users-core's `users.profiles`: the feature then serves its CRUD surface through that
|
|
314
|
+
* repository and does not own the table.
|
|
315
|
+
* @param {string} [feature.systemScope] Why the feature works across every workspace and user; decorateRepository then receives systemContext(reason).
|
|
316
|
+
* @param {string} [feature.visibility] The routes' visibility, when it differs from the table's ownership: a
|
|
317
|
+
* workspace's admin surface serving a table every workspace shares (such as users) names "workspace", so its
|
|
318
|
+
* routes resolve the caller's workspace and their actions check its permissions. The rows a call reaches still
|
|
319
|
+
* follow the table's ownership.
|
|
320
|
+
* @param {string} [feature.id] Defaults to `crud.<namespace>`.
|
|
321
|
+
* @param {string} [feature.capability] Defaults to the feature id.
|
|
322
|
+
* @param {string} [feature.relativePath] Defaults to the namespace, with dashes.
|
|
323
|
+
* @param {boolean} [feature.internal] True keeps the routes off the HTTP server.
|
|
324
|
+
* @param {boolean} [feature.routes] False registers no HTTP routes. Either way, an action no permission
|
|
325
|
+
* guards is then left off the automation channel, so the assistant cannot run it.
|
|
326
|
+
* @param {object | null} [feature.listFilterQueryValidator]
|
|
327
|
+
* @param {object | null} [feature.permissions]
|
|
328
|
+
* @param {import("./types.js").CrudScope} [feature.scope] The route base, validators, input keys and input() of a scoped resource.
|
|
329
|
+
* @param {Record<string, string>} [feature.requires] More capabilities the feature requires, by name.
|
|
330
|
+
* @param {((dependencies: { repository: import("./types.js").CrudRepository, resources: Record<string, import("./types.js").CrudRepository>, crud: import("./types.js").CrudContract } & Record<string, any>) => import("./types.js").CrudRepository | Promise<import("./types.js").CrudRepository>) | null} [feature.decorateRepository]
|
|
331
|
+
* Receives the CRUD table's handle (or the owner's repository) as repository, every owned table's handle as
|
|
332
|
+
* resources, the CRUD contract, systemContext with systemScope, and the feature's requires.
|
|
333
|
+
* @param {((dependencies: { service: import("./types.js").CrudService, repository: import("./types.js").CrudRepository, crud: import("./types.js").CrudContract } & Record<string, any>) => import("./types.js").CrudService | Promise<import("./types.js").CrudService>) | null} [feature.decorateService]
|
|
334
|
+
* Receives the CRUD service, the (decorated) repository, the CRUD contract and the feature's requires.
|
|
335
|
+
* @param {import("./types.js").CrudOperationLifecycle} [feature.operationLifecycle]
|
|
336
|
+
* @param {object} [feature.operationInputs]
|
|
337
|
+
* @param {object} [feature.actions] Custom actions, by name.
|
|
338
|
+
* @param {string[]} [feature.operations] Defaults to every operation the CRUD contract offers.
|
|
339
|
+
* @param {string} [feature.realtimeAudience] Defaults to "event_scope".
|
|
340
|
+
*/
|
|
341
|
+
function defineCrudFeature(feature) {
|
|
342
|
+
assertKnownOptions(feature);
|
|
343
|
+
const {
|
|
344
|
+
crud,
|
|
345
|
+
id = "",
|
|
346
|
+
capability = "",
|
|
347
|
+
surface,
|
|
348
|
+
owns = [],
|
|
349
|
+
ownerRepository = "",
|
|
350
|
+
visibility = "",
|
|
351
|
+
systemScope = undefined,
|
|
352
|
+
relativePath = "",
|
|
353
|
+
internal = false,
|
|
354
|
+
routes = true,
|
|
355
|
+
listFilterQueryValidator = null,
|
|
356
|
+
permissions = null,
|
|
357
|
+
scope = {},
|
|
358
|
+
requires = {},
|
|
359
|
+
decorateRepository = null,
|
|
360
|
+
decorateService = null,
|
|
361
|
+
operationLifecycle = {},
|
|
362
|
+
operationInputs = {},
|
|
363
|
+
actions = {},
|
|
364
|
+
operations = undefined,
|
|
365
|
+
realtimeAudience = "event_scope"
|
|
366
|
+
} = feature;
|
|
367
|
+
if (!isCrudContract(crud)) {
|
|
368
|
+
throw new TypeError("defineCrudFeature requires crud, a CRUD contract from defineCrudContract.");
|
|
369
|
+
}
|
|
370
|
+
const tableResource = crud.resource;
|
|
371
|
+
const namespace = crud.namespace;
|
|
372
|
+
const featureId = normalizeText(id) || `crud.${namespace}`;
|
|
373
|
+
const featureCapability = normalizeText(capability) || featureId;
|
|
374
|
+
const normalizedSurface = normalizeText(surface).toLowerCase();
|
|
375
|
+
if (!normalizedSurface) {
|
|
376
|
+
throw new TypeError("defineCrudFeature requires surface.");
|
|
377
|
+
}
|
|
378
|
+
const ownershipFilter = normalizeText(visibility).toLowerCase() || routeOwnership(tableResource.ownership);
|
|
379
|
+
const normalizedRelativePath = normalizeText(relativePath) || `/${namespace.replace(/_/gu, "-")}`;
|
|
380
|
+
const access = normalizeAccess(crud);
|
|
381
|
+
if (access === "public" && ownershipFilter !== "public") {
|
|
382
|
+
throw new TypeError('A public CRUD feature serves a table resource whose ownership (or visibility) is "public".');
|
|
383
|
+
}
|
|
384
|
+
const normalizedScope = normalizeScope(scope);
|
|
385
|
+
const featureRequirements = normalizeFeatureRequirements(requires);
|
|
386
|
+
if (typeof ownerRepository !== "string") {
|
|
387
|
+
throw new TypeError("defineCrudFeature ownerRepository must be the capability of the table owner's repository.");
|
|
388
|
+
}
|
|
389
|
+
const featureOwns = crudOwns(crud, owns, ownerRepository.trim());
|
|
390
|
+
const enabledOperations = normalizeOperations(operations, crud);
|
|
391
|
+
if (typeof routes !== "boolean") {
|
|
392
|
+
throw new TypeError("defineCrudFeature routes must be a boolean.");
|
|
393
|
+
}
|
|
394
|
+
if (decorateRepository != null && typeof decorateRepository !== "function") {
|
|
395
|
+
throw new TypeError("defineCrudFeature decorateRepository must be a function.");
|
|
396
|
+
}
|
|
397
|
+
if (decorateService != null && typeof decorateService !== "function") {
|
|
398
|
+
throw new TypeError("defineCrudFeature decorateService must be a function.");
|
|
399
|
+
}
|
|
400
|
+
const normalizedOperationLifecycle = normalizeCrudOperationLifecycle(operationLifecycle);
|
|
401
|
+
if (!operationInputs || typeof operationInputs !== "object" || Array.isArray(operationInputs)) {
|
|
402
|
+
throw new TypeError("defineCrudFeature operationInputs must be an object.");
|
|
403
|
+
}
|
|
404
|
+
if (!actions || typeof actions !== "object" || Array.isArray(actions)) {
|
|
405
|
+
throw new TypeError("defineCrudFeature actions must be an object.");
|
|
406
|
+
}
|
|
407
|
+
assertPermissionNames(permissions, actions);
|
|
408
|
+
assertWorkspaceScope(normalizedScope, ownershipFilter);
|
|
409
|
+
const workspaceScoped = isWorkspaceRouteVisibility(ownershipFilter);
|
|
410
|
+
const permissionOptions = permissions && typeof permissions === "object" && !Array.isArray(permissions)
|
|
411
|
+
? { ...permissions, namespace }
|
|
412
|
+
: { namespace };
|
|
413
|
+
|
|
414
|
+
return defineFeature({
|
|
415
|
+
id: featureId,
|
|
416
|
+
domain: "crud",
|
|
417
|
+
...(featureOwns ? { owns: featureOwns } : {}),
|
|
418
|
+
...(systemScope === undefined ? {} : { systemScope }),
|
|
419
|
+
requires: {
|
|
420
|
+
http: "runtime.http",
|
|
421
|
+
crudContracts: "crud.contracts",
|
|
422
|
+
...(ownerRepository.trim() ? { ownerRepository: ownerRepository.trim() } : {}),
|
|
423
|
+
...featureRequirements
|
|
424
|
+
},
|
|
425
|
+
provides: {
|
|
426
|
+
resourceApi: featureCapability
|
|
427
|
+
},
|
|
428
|
+
async setup({ http, crudContracts, resources = {}, systemContext, ownerRepository: servedRepository, ...featureDependencies }) {
|
|
429
|
+
crudContracts.register(crud);
|
|
430
|
+
const handle = servedRepository || resources[tableResource.name];
|
|
431
|
+
const repository = decorateRepository
|
|
432
|
+
? rejectLegacyMethods(await decorateRepository(Object.freeze(withRemovedProperties({
|
|
433
|
+
repository: handle,
|
|
434
|
+
resources,
|
|
435
|
+
crud,
|
|
436
|
+
...(systemContext ? { systemContext } : {}),
|
|
437
|
+
...featureDependencies
|
|
438
|
+
}, REMOVED_REPOSITORY_DEPENDENCIES, "decorateRepository's dependencies"))), LEGACY_REPOSITORY_METHODS, "The repository decorateRepository returned")
|
|
439
|
+
: handle;
|
|
440
|
+
const defaultService = createCrudService({ repository, crud });
|
|
441
|
+
const decoratedService = decorateService
|
|
442
|
+
? rejectLegacyMethods(await decorateService(Object.freeze(withRemovedProperties({
|
|
443
|
+
service: defaultService,
|
|
444
|
+
repository,
|
|
445
|
+
crud,
|
|
446
|
+
...featureDependencies
|
|
447
|
+
}, REMOVED_SERVICE_DEPENDENCIES, "decorateService's dependencies"))), LEGACY_SERVICE_METHODS, "The service decorateService returned")
|
|
448
|
+
: defaultService;
|
|
449
|
+
const service = projectEnabledServiceOperations(decoratedService, enabledOperations);
|
|
450
|
+
assertServiceOperations(service, enabledOperations);
|
|
451
|
+
if (routes) {
|
|
452
|
+
registerCrudJsonApiRoutes(http.router, {
|
|
453
|
+
namespace,
|
|
454
|
+
resource: crud,
|
|
455
|
+
routeBase: normalizedScope.routeBase,
|
|
456
|
+
relativePath: normalizedRelativePath,
|
|
457
|
+
surface: normalizedSurface,
|
|
458
|
+
ownershipFilter,
|
|
459
|
+
access,
|
|
460
|
+
internal,
|
|
461
|
+
operations: enabledOperations,
|
|
462
|
+
actions,
|
|
463
|
+
listFilterQueryValidator,
|
|
464
|
+
operationInputs,
|
|
465
|
+
routeParamsValidator: normalizedScope.routeParamsValidator,
|
|
466
|
+
scopeInput: normalizedScope.input
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
// The handle decorateRepository receives answers hidden fields to the owner's own methods; other features,
|
|
470
|
+
// and this feature's actions, read them only in a system context, through any method the repository holds.
|
|
471
|
+
const exposed = withoutHiddenFields(repository, [
|
|
472
|
+
tableResource,
|
|
473
|
+
...(featureOwns ?? []).map((entry) => (isTableResource(entry) ? entry : entry.resource))
|
|
474
|
+
]);
|
|
475
|
+
return {
|
|
476
|
+
resourceApi: Object.freeze(withRemovedProperties({ repository: exposed, crud, service }, REMOVED_RESOURCE_API, "A CRUD feature's capability"))
|
|
477
|
+
};
|
|
478
|
+
},
|
|
479
|
+
actions({ resourceApi, ...required }) {
|
|
480
|
+
const actionDependencies = Object.freeze(Object.fromEntries(
|
|
481
|
+
Object.keys(featureRequirements).map((name) => [name, required[name]])
|
|
482
|
+
));
|
|
483
|
+
return createCrudJsonApiActions({
|
|
484
|
+
namespace,
|
|
485
|
+
resource: crud,
|
|
486
|
+
repository: resourceApi.repository,
|
|
487
|
+
service: resourceApi.service,
|
|
488
|
+
surface: normalizedSurface,
|
|
489
|
+
operations: enabledOperations,
|
|
490
|
+
listFilterQueryValidator,
|
|
491
|
+
operationLifecycle: normalizedOperationLifecycle,
|
|
492
|
+
operationInputs,
|
|
493
|
+
actions,
|
|
494
|
+
dependencies: actionDependencies,
|
|
495
|
+
permissionForOperation: (operation) => resolveActionPermission(operation, {
|
|
496
|
+
access,
|
|
497
|
+
workspaceScoped,
|
|
498
|
+
permissions: permissionOptions
|
|
499
|
+
}),
|
|
500
|
+
scopeInputValidator: normalizedScope.actionInputValidator,
|
|
501
|
+
scopeInputKeys: normalizedScope.inputKeys,
|
|
502
|
+
realtimeAudience,
|
|
503
|
+
servedOverHttp: routes && !internal
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
export { defineCrudFeature };
|