@atscript/moost-odata 0.0.0-stage → 0.0.2

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/dist/index.mjs ADDED
@@ -0,0 +1,681 @@
1
+ import { current, tryGetCurrent } from "@wooksjs/event-core";
2
+ import { httpKind, useCookies, useHeaders } from "@wooksjs/event-http";
3
+ import { ODataAdapter, ODataSpace } from "@atscript/db-odata";
4
+ import { AsDbController, AsDbReadableController, ReadableController, UseValidationErrorTransform, badRequest, dbActionBodySlot, dbErrorToHttp, findReadableBinding, notFoundError, resolveDbSpace, useDbActionTarget } from "@atscript/moost-db";
5
+ import { DbError, isNavRelation } from "@atscript/db";
6
+ import { incompatibleOperationError, rowsFailure } from "@atscript/odata";
7
+ import { HttpError } from "@moostjs/event-http";
8
+ import { Inherit, getMoostMate, useControllerContext } from "moost";
9
+ import { isAnnotatedType } from "@atscript/typescript/utils";
10
+ //#region src/request.ts
11
+ const NO_HEADERS = Object.freeze({});
12
+ /**
13
+ * The HTTP request of the current event, read with Wooks' `useHeaders` and `useCookies`. Resolved
14
+ * through the event context Wooks keeps in `AsyncLocalStorage`, so every overlapping request sees
15
+ * its own, wherever in its call chain this is asked.
16
+ */
17
+ function currentIncomingRequest() {
18
+ const current = tryGetCurrent();
19
+ const event = current?.has(httpKind.keys.req) ? current : void 0;
20
+ const headers = event ? useHeaders(event) : NO_HEADERS;
21
+ const header = (name) => {
22
+ const value = headers[name.toLowerCase()];
23
+ return Array.isArray(value) ? value.join(", ") : value;
24
+ };
25
+ return {
26
+ headers,
27
+ event,
28
+ header,
29
+ cookie: (name) => event ? useCookies(event).getCookie(name) ?? void 0 : void 0
30
+ };
31
+ }
32
+ //#endregion
33
+ //#region src/auth.ts
34
+ /**
35
+ * Headers sent with every call: `staticHeaders({ "x-api-key": key })`, a credential the server was
36
+ * given in a header of its own.
37
+ */
38
+ function staticHeaders(headers) {
39
+ const fixed = { ...headers };
40
+ return () => ({ headers: { ...fixed } });
41
+ }
42
+ /** HTTP Basic authentication of a technical user. */
43
+ function basicAuth(options) {
44
+ const { user, password } = options;
45
+ if (user === "" || user.includes(":")) throw new Error("basicAuth: the user name must not be empty and cannot contain \":\"");
46
+ const value = `Basic ${Buffer.from(`${user}:${password}`, "utf8").toString("base64")}`;
47
+ return () => ({ headers: { Authorization: value } });
48
+ }
49
+ function bearerHeader(token) {
50
+ if (typeof token !== "string" || token === "") throw new Error("bearerAuth: there is no token to authenticate with");
51
+ return { headers: { Authorization: `Bearer ${token}` } };
52
+ }
53
+ /**
54
+ * Bearer authentication of a technical user: a token, or a function asked for one at every table
55
+ * operation, which caches and refreshes a token that expires (an OAuth client-credentials token,
56
+ * for example). The function runs in the request it is asked for and receives it.
57
+ */
58
+ function bearerAuth(token) {
59
+ if (typeof token === "string") {
60
+ bearerHeader(token);
61
+ return () => bearerHeader(token);
62
+ }
63
+ return () => {
64
+ const value = token(currentIncomingRequest());
65
+ return typeof value === "string" ? bearerHeader(value) : value.then(bearerHeader);
66
+ };
67
+ }
68
+ /**
69
+ * Limits every table operation to `ms` milliseconds, all its OData requests together. A call
70
+ * that takes longer fails as a timeout, which the error mapping answers with `504`.
71
+ */
72
+ function callTimeout(ms) {
73
+ if (!Number.isFinite(ms) || ms <= 0) throw new Error("callTimeout: the limit must be a positive number of milliseconds");
74
+ return () => ({ signal: AbortSignal.timeout(ms) });
75
+ }
76
+ function mergeInits(parts) {
77
+ const merged = {};
78
+ const headers = /* @__PURE__ */ new Map();
79
+ const signals = [];
80
+ let read;
81
+ for (const part of parts) {
82
+ if (!part) continue;
83
+ for (const [key, value] of Object.entries(part)) if (value !== void 0) merged[key] = value;
84
+ for (const [name, value] of Object.entries(part.headers ?? {})) headers.set(name.toLowerCase(), [name, value]);
85
+ if (part.signal) signals.push(part.signal);
86
+ if (part.read) read = Object.assign(read ?? {}, part.read);
87
+ }
88
+ if (Object.keys(merged).length === 0) return void 0;
89
+ if (headers.size > 0) merged.headers = Object.fromEntries(headers.values());
90
+ if (read) merged.read = read;
91
+ if (signals.length > 1) merged.signal = AbortSignal.any(signals);
92
+ return merged;
93
+ }
94
+ /**
95
+ * One strategy out of several: each is asked for the current request and the answers are merged
96
+ * in the order given. A later header replaces an earlier one of the same name (in any case), a
97
+ * later session replaces an earlier one, read options are merged, and the call is aborted when
98
+ * any of the signals fires.
99
+ *
100
+ * ```ts
101
+ * combineAuth(basicAuth({ user, password }), callTimeout(15_000))
102
+ * ```
103
+ */
104
+ function combineAuth(...strategies) {
105
+ return async () => mergeInits(await Promise.all(strategies.map(async (init) => init())));
106
+ }
107
+ //#endregion
108
+ //#region src/controller-checks.ts
109
+ /** The adapter of a readable when it is one of `@atscript/db-odata`. */
110
+ function odataAdapterOf(readable) {
111
+ const adapter = readable?.getAdapter();
112
+ return adapter instanceof ODataAdapter ? adapter : void 0;
113
+ }
114
+ /**
115
+ * `crud` without the writes the entity set does not allow: `insert`, `update` and `replace`,
116
+ * `remove`, by `allowedWrites` of the adapter (`crud` as it is for a table of another adapter).
117
+ * What `ODataTableController` does in `buildCrud`; a moost-db controller of another base over an
118
+ * OData table (an ARBAC controller of aooth) does the same:
119
+ *
120
+ * ```ts
121
+ * protected override buildCrud() {
122
+ * return allowedCrud(super.buildCrud(), this.readable);
123
+ * }
124
+ * ```
125
+ */
126
+ function allowedCrud(crud, readable) {
127
+ const adapter = odataAdapterOf(readable);
128
+ if (!adapter) return crud;
129
+ const allowed = adapter.allowedWrites;
130
+ const pruned = { ...crud };
131
+ if (!allowed.insert) delete pruned.insert;
132
+ if (!allowed.update) {
133
+ delete pruned.update;
134
+ delete pruned.replace;
135
+ }
136
+ if (!allowed.delete) delete pruned.remove;
137
+ return pruned;
138
+ }
139
+ /**
140
+ * Refuses every endpoint of a table whose entity set the live service no longer has, `/meta`
141
+ * included: moost-db's `404` `NOT_FOUND` (`notFoundError()`), the answer of a missing row. The
142
+ * adapter itself would answer such a table with a plain `Error` (`500`), a fault of the server's
143
+ * build. Nothing for any other table. What the OData bases do in `prepareRequest`, which moost-db
144
+ * runs first on every endpoint; a moost-db controller of another base does the same:
145
+ *
146
+ * ```ts
147
+ * protected override async prepareRequest(ctx: TDbRequestContext) {
148
+ * refuseGoneEntitySet(this.readable);
149
+ * await super.prepareRequest?.(ctx); // the base's own, when it has one (aooth's ARBAC check)
150
+ * }
151
+ * ```
152
+ */
153
+ function refuseGoneEntitySet(readable) {
154
+ if (odataAdapterOf(readable)?.gone) throw notFoundError();
155
+ }
156
+ //#endregion
157
+ //#region \0@oxc-project+runtime@0.121.0/helpers/decorate.js
158
+ function __decorate(decorators, target, key, desc) {
159
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
160
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
161
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
162
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
163
+ }
164
+ //#endregion
165
+ //#region src/operations.ts
166
+ const mate = () => getMoostMate();
167
+ /**
168
+ * Marks a controller method as the route of an OData operation: `operation` is its typed handle
169
+ * of the model module's `ops` (`ops.OrderSet.ReleaseOrder`). The generated bases put it on every
170
+ * method they generate, beside moost-db's own decorators (`@DbAction`, `@InputForm`,
171
+ * `@DbActionRows`); `runOperation()` of the method's controller calls the operation it names, and
172
+ * the OData bases refuse an operation the live service no longer fits before anything else runs.
173
+ *
174
+ * A method of your own calls an operation the same way: a db action of your table controller over
175
+ * an unbound operation (a toolbar or row button) takes `@DbAction`, its route, this marker with
176
+ * the operation's handle, and `this.runOperation({ params })`.
177
+ */
178
+ function ODataOperation(operation, options = {}) {
179
+ const mark = {
180
+ operation,
181
+ ...options.grouping ? options : {}
182
+ };
183
+ return mate().decorate("odata_operation", mark);
184
+ }
185
+ /** The mark of the method handling the current event. */
186
+ function currentMark() {
187
+ const context = useControllerContext();
188
+ const mark = context.getMethodMeta()?.odata_operation;
189
+ if (!mark) throw new Error(`runOperation() was called from ${context.getMethod() ?? "a method"}, which has no @ODataOperation(handle): mark the method with the operation's handle`);
190
+ return mark;
191
+ }
192
+ /**
193
+ * Refuses an operation of the build the live service no longer fits: one it no longer has with
194
+ * moost-db's `404` (`notFoundError()`), one it changed with the core's plain `Error` (a fault of
195
+ * the server's build: moost-db answers `500` and logs it).
196
+ */
197
+ function refuse(verdict) {
198
+ if (!verdict) return;
199
+ if (verdict.verdict === "gone") throw notFoundError();
200
+ throw incompatibleOperationError(verdict);
201
+ }
202
+ /** The operations among a controller's db actions, by action name: what its `@ODataOperation` names. */
203
+ const byController = /* @__PURE__ */ new WeakMap();
204
+ function operationsOf(ctor, app) {
205
+ let found = byController.get(ctor);
206
+ if (found) return found;
207
+ found = /* @__PURE__ */ new Map();
208
+ const overview = app.getControllersOverview().find((o) => o.type === ctor);
209
+ for (const handler of overview?.handlers ?? []) {
210
+ const meta = handler.meta;
211
+ const name = meta.atscript_db_action?.name;
212
+ if (name !== void 0 && meta.odata_operation) found.set(name, meta.odata_operation);
213
+ }
214
+ byController.set(ctor, found);
215
+ return found;
216
+ }
217
+ /** The verdict refusing the action `name` of a controller, when it is one of its operations. */
218
+ function refusalOfAction(host, name) {
219
+ const mark = operationsOf(host.ctor, host.app).get(name);
220
+ return mark && odataAdapterOf(host.readable)?.refusalOf(mark.operation);
221
+ }
222
+ /**
223
+ * `prepareRequest` of the bases: an action (`action`, and a view's `delegatedAction`) naming one
224
+ * of the controller's operations the live service no longer fits is refused, after the guards
225
+ * and before the ids are read, the rows loaded or the handler runs.
226
+ */
227
+ function refuseRefusedOperation(host, ctx) {
228
+ if (ctx.endpoint !== "action" && ctx.endpoint !== "delegatedAction" || !ctx.action) return;
229
+ refuse(refusalOfAction(host, ctx.action));
230
+ }
231
+ /**
232
+ * `buildActions` of the bases: the actions without the operations the live service refuses. Every
233
+ * list of actions follows it: `/meta`, `$actions`, `/meta/actions` and a view's delegated entries.
234
+ */
235
+ function withoutRefusedActions(host, actions) {
236
+ return actions.filter((action) => !refusalOfAction(host, action.name));
237
+ }
238
+ /** The key of a row: what moost-db's action target names it by, and what it is read again by. */
239
+ function keyOf(readable, row) {
240
+ return Object.fromEntries(readable.primaryKeys.map((key) => [key, row[key]]));
241
+ }
242
+ /**
243
+ * A row the service has no entity for (the adapter's `DbError` `NOT_FOUND`: the ETag read before
244
+ * its call found none, or the call was answered `404`): moost-db's answer to a missing row,
245
+ * `notFoundError()`. Any other error as it is.
246
+ */
247
+ function missingRow(error) {
248
+ return error instanceof DbError && error.code === "NOT_FOUND" ? notFoundError() : error;
249
+ }
250
+ /** The answer moost-db gives an error of a row's call; `undefined` for one it does not map. */
251
+ function bodyOf(error) {
252
+ if (error instanceof DbError) return dbErrorToHttp(error).body;
253
+ if (error instanceof HttpError) return error.body;
254
+ }
255
+ /**
256
+ * The error of a run on several rows where every row failed: the first row's answer (its status,
257
+ * code and message, as that call alone would have been answered), with the entries of every row
258
+ * at that row (`[i]`, `[i].Note`; `rowsFailure` of `@atscript/odata`).
259
+ */
260
+ function everyRowFailed(errors) {
261
+ const bodies = errors.map(bodyOf);
262
+ if (!bodies.every((body) => body !== void 0)) return errors[0];
263
+ const { entries } = rowsFailure(errors.length, bodies.map(({ message, code, params, errors }, index) => ({
264
+ index,
265
+ message,
266
+ entries: errors ?? [],
267
+ code,
268
+ params
269
+ })));
270
+ const [first] = errors;
271
+ if (first instanceof DbError) return new DbError(first.code, entries, first.message, { cause: first.cause });
272
+ const body = bodies[0];
273
+ return new HttpError(body.statusCode, {
274
+ ...body,
275
+ errors: entries
276
+ });
277
+ }
278
+ /**
279
+ * The answer of an operation on rows: moost-db's action target summary (the gate's skipped
280
+ * rows, the rows the run failed on reported with `fail(id, error)`, its counts), each failed row
281
+ * with the status, code and message its call alone would have been answered with, and the
282
+ * operation's values and messages. Every row of the request's ids failed: the error of
283
+ * {@link everyRowFailed}. Where the gate skipped rows, or on a query target, the rows handed to
284
+ * the run are not the request's ids, and a run whose every row failed answers the summary, as
285
+ * moost-db's own targets do (`processed: 0`, `failed` by id, `skipped` kept). (One row never gets
286
+ * here: the runner sends it as a plain call, whose failure is its own error.)
287
+ */
288
+ async function rowsAnswer(readable, rows, answer, stale) {
289
+ const failed = await Promise.all((answer.failed ?? []).map(async ({ index, error }) => ({
290
+ index,
291
+ error: error === null ? await stale(keyOf(readable, rows[index])) : missingRow(error)
292
+ })));
293
+ const target = useDbActionTarget();
294
+ if (failed.length > 0 && failed.length === rows.length && target.kind === "ids" && target.summary().skipped.length === 0) throw everyRowFailed(failed.map((f) => f.error));
295
+ for (const { index, error } of failed) target.fail(keyOf(readable, rows[index]), error);
296
+ const summary = target.summary();
297
+ const { failed: _failed, ...ran } = answer;
298
+ return {
299
+ ...summary,
300
+ failed: summary.failed,
301
+ ...ran
302
+ };
303
+ }
304
+ /** Whether an id names the row of `key`: the same value for each key property. */
305
+ function sameRow(readable, id, key) {
306
+ if (id === null || typeof id !== "object") return false;
307
+ const values = id;
308
+ return readable.primaryKeys.every((name) => String(values[name]) === String(key[name]));
309
+ }
310
+ /**
311
+ * The error of a refused changeset of several rows, its entries that name a row (`[k]`, with the
312
+ * row's key as `params.id`) at that row's index in the request's ids (`[j]`), the rows handed to
313
+ * the run being those the gate left; on a query target, which lists no ids, at `""` with
314
+ * `params.id`. Any other error as it is.
315
+ */
316
+ async function atRequestRows(readable, error) {
317
+ if (!(error instanceof DbError) || !error.errors.some((entry) => entry.params?.id)) return error;
318
+ const { ids } = await current().get(dbActionBodySlot);
319
+ const requested = useDbActionTarget().kind === "ids" && Array.isArray(ids) ? ids : [];
320
+ const entries = error.errors.map((entry) => {
321
+ const id = entry.params?.id;
322
+ const at = id ? /^\[\d+\]\.?/.exec(entry.path) : null;
323
+ if (!id || !at) return entry;
324
+ const index = requested.findIndex((requestedId) => sameRow(readable, requestedId, id));
325
+ const rest = entry.path.slice(at[0].length);
326
+ return {
327
+ ...entry,
328
+ path: index < 0 ? "" : rest ? `[${index}].${rest}` : `[${index}]`
329
+ };
330
+ });
331
+ return new DbError(error.code, entries, error.message, { cause: error.cause });
332
+ }
333
+ /**
334
+ * `runOperation()` of the set bases: the marked operation, bound to the controller's entity set,
335
+ * by the grouping of its mark. On rows it answers {@link ODataRowsAnswer}.
336
+ */
337
+ async function runSetOperation(readable, input, stale) {
338
+ const { operation, grouping } = currentMark();
339
+ const adapter = odataAdapterOf(readable);
340
+ if (!adapter) throw new Error(`runOperation(): the table "${readable.tableName}" is no table of an OData space`);
341
+ refuse(adapter.refusalOf(operation));
342
+ const rows = input.rows ?? input.ids;
343
+ if (rows?.some((row) => row === null || row === void 0)) throw notFoundError();
344
+ let answer;
345
+ try {
346
+ answer = await adapter.callOperation({
347
+ operation,
348
+ ...rows ? { rows } : {},
349
+ ...input.params ? { params: input.params } : {},
350
+ ...input.extra ? { extra: input.extra } : {},
351
+ ...grouping ? { grouping } : {}
352
+ });
353
+ } catch (error) {
354
+ throw rows ? missingRow(await atRequestRows(readable, error)) : missingRow(error);
355
+ }
356
+ if (answer === null) throw await stale(keyOf(readable, rows[0]));
357
+ return rows ? rowsAnswer(readable, rows, answer, stale) : answer;
358
+ }
359
+ let ODataOperationsController = class ODataOperationsController {
360
+ /**
361
+ * Calls the operation the current method is marked with (`@ODataOperation`), with `params` (the
362
+ * body; none for a request without one) and, on OData v2, `extra`: parameters the operation does not declare, sent untyped (set
363
+ * them in an override, never from a request). Answers `{ value, message?, messages?, details? }`.
364
+ */
365
+ async runOperation(input = {}) {
366
+ const { operation } = currentMark();
367
+ const space = resolveDbSpace(operation.service);
368
+ if (!(space instanceof ODataSpace)) throw new Error(`runOperation(): the space registered as "${operation.service}" is no OData space (createODataSpace)`);
369
+ refuse(space.refusalOf(operation));
370
+ const { params } = input;
371
+ return space.callOperation({
372
+ operation,
373
+ params: params === void 0 || params === null || params === "" ? {} : params,
374
+ ...input.extra ? { extra: input.extra } : {}
375
+ });
376
+ }
377
+ };
378
+ ODataOperationsController = __decorate([UseValidationErrorTransform()], ODataOperationsController);
379
+ //#endregion
380
+ //#region src/readable-controller.ts
381
+ /**
382
+ * Refuses a `$search` that moost-db's `applySearchFallback` returned unapplied (`applied` is the
383
+ * filter it was given) because neither the table nor a `@db.column.searchable` field can take it:
384
+ * `400` `INVALID_QUERY` on `$search`, where moost-db would answer every row unsearched. What the
385
+ * OData bases do; a moost-db controller of another base does the same:
386
+ *
387
+ * ```ts
388
+ * protected override applySearchFallback(filter: FilterExpr | undefined, controls: Record<string, unknown>) {
389
+ * const applied = super.applySearchFallback(filter, controls);
390
+ * refuseUnappliedSearch(this.readable, filter, controls, applied);
391
+ * return applied;
392
+ * }
393
+ * ```
394
+ */
395
+ function refuseUnappliedSearch(readable, filter, controls, applied) {
396
+ if (applied === filter && controls.$search && controls.$vector === void 0 && !readable.isSearchable()) throw badRequest("$search", `"${readable.tableName}" has no free-text search`, "INVALID_QUERY");
397
+ }
398
+ /**
399
+ * The read-only controller of `@atscript/moost-db` (`AsDbReadableController`) for an entity set of
400
+ * an OData service. Declare one per entity set, as with any moost-db controller:
401
+ *
402
+ * ```ts
403
+ * ‎@ReadableController(sales.Customer, "api/sales/CustomerSet")
404
+ * export class CustomerSetController extends ODataReadableController<typeof sales.Customer> {}
405
+ * ```
406
+ *
407
+ * The model token resolves the space the application registered under the types' `@db.space`
408
+ * (`provideDbSpace(space, "sales")`); a table of the space (`space.getTable(sales.Customer)`)
409
+ * binds as well.
410
+ *
411
+ * What it adds to moost-db's controller:
412
+ *
413
+ * - **`$search`** on an entity set the service cannot search is refused with `400`; moost-db would
414
+ * answer with every row unsearched. A type whose fields carry `@db.column.searchable` keeps
415
+ * moost-db's substring search over those fields.
416
+ * - **An entity set the live service no longer has** answers every endpoint, `/meta` included,
417
+ * with moost-db's `404` `NOT_FOUND`, from `prepareRequest`. A subclass that implements
418
+ * `prepareRequest` itself calls `super.prepareRequest(ctx)` first.
419
+ *
420
+ * A failure of the service needs nothing of it: the adapter throws atscript-db's `STORE_FAILED`,
421
+ * `STORE_TIMEOUT` or `STORE_THROTTLED`, which every moost-db controller answers `502`, `504` or
422
+ * `429` (with `Retry-After`) and logs.
423
+ *
424
+ * A class of your own between yours and this one needs Moost's `@Inherit()`, as with any Moost
425
+ * controller base.
426
+ */
427
+ var ODataReadableController = class extends AsDbReadableController {
428
+ applySearchFallback(filter, controls) {
429
+ const applied = super.applySearchFallback(filter, controls);
430
+ refuseUnappliedSearch(this.readable, filter, controls, applied);
431
+ return applied;
432
+ }
433
+ get operationHost() {
434
+ return {
435
+ readable: this.readable,
436
+ ctor: this.constructor,
437
+ app: this.app
438
+ };
439
+ }
440
+ /**
441
+ * Refuses a set the live service no longer has (`404` on every endpoint, `/meta` included) and
442
+ * an operation of the build it no longer fits (an action of the controller: `404` when the
443
+ * service no longer has it, `500` when it changed it). A subclass that implements it calls
444
+ * `super.prepareRequest(ctx)` first.
445
+ */
446
+ prepareRequest(ctx) {
447
+ refuseGoneEntitySet(this.readable);
448
+ refuseRefusedOperation(this.operationHost, ctx);
449
+ }
450
+ /**
451
+ * The db actions, without the operations the live service no longer fits: what `/meta`,
452
+ * `$actions` and `/meta/actions` list.
453
+ */
454
+ buildActions() {
455
+ return withoutRefusedActions(this.operationHost, super.buildActions());
456
+ }
457
+ runOperation(input = {}) {
458
+ return runSetOperation(this.readable, input, (id) => this._disambiguateMismatch(id, this.readable.versionColumn));
459
+ }
460
+ };
461
+ Inherit()(ODataReadableController);
462
+ //#endregion
463
+ //#region src/table-controller.ts
464
+ /**
465
+ * The read and write controller of `@atscript/moost-db` (`AsDbController`: `POST`, `PUT`,
466
+ * `PATCH`, `DELETE` next to the read endpoints) for an entity set the service lets you write to.
467
+ * Declare one per entity set, as with any moost-db controller:
468
+ *
469
+ * ```ts
470
+ * ‎@TableController(sales.Order, "api/sales/OrderSet")
471
+ * export class OrderSetController extends ODataTableController<typeof sales.Order> {}
472
+ * ```
473
+ *
474
+ * The model token resolves the space the application registered under the types' `@db.space`
475
+ * (`provideDbSpace(space, "sales")`); a table of the space (`space.getTable(sales.Order)`) binds
476
+ * as well.
477
+ *
478
+ * Everything `ODataReadableController` adds, and:
479
+ *
480
+ * - **Only the writes the entity set allows** are offered: `/meta` lists in `crud` the writes the
481
+ * live service allows (`allowedWrites` of `@atscript/db-odata`). Another write is refused before
482
+ * any request with moost-db's `400` `NOT_SUPPORTED`, naming why. That holds for a set that takes
483
+ * no write at all, and for one the live service no longer lets you write to: the application
484
+ * starts either way.
485
+ * - **An entity set the live service no longer has** answers every endpoint with `404`
486
+ * `NOT_FOUND`, from `prepareRequest` (a subclass that implements it calls
487
+ * `super.prepareRequest(ctx)` first).
488
+ *
489
+ * Its writes are those of `@atscript/db-odata`: one entity at a time, by key, and last-write-wins,
490
+ * each in the session the space keeps for the credentials it sends.
491
+ */
492
+ var ODataTableController = class extends AsDbController {
493
+ buildCrud() {
494
+ return allowedCrud(super.buildCrud(), this.readable);
495
+ }
496
+ applySearchFallback(filter, controls) {
497
+ const applied = super.applySearchFallback(filter, controls);
498
+ refuseUnappliedSearch(this.readable, filter, controls, applied);
499
+ return applied;
500
+ }
501
+ get operationHost() {
502
+ return {
503
+ readable: this.readable,
504
+ ctor: this.constructor,
505
+ app: this.app
506
+ };
507
+ }
508
+ /**
509
+ * Refuses a set the live service no longer has (`404` on every endpoint, `/meta` included) and
510
+ * an operation of the build it no longer fits (an action of the controller: `404` when the
511
+ * service no longer has it, `500` when it changed it). A subclass that implements it calls
512
+ * `super.prepareRequest(ctx)` first.
513
+ */
514
+ prepareRequest(ctx) {
515
+ refuseGoneEntitySet(this.readable);
516
+ refuseRefusedOperation(this.operationHost, ctx);
517
+ }
518
+ /**
519
+ * The db actions, without the operations the live service no longer fits: what `/meta`,
520
+ * `$actions` and `/meta/actions` list.
521
+ */
522
+ buildActions() {
523
+ return withoutRefusedActions(this.operationHost, super.buildActions());
524
+ }
525
+ runOperation(input = {}) {
526
+ return runSetOperation(this.readable, input, (id) => this._disambiguateMismatch(id, this.readable.versionColumn));
527
+ }
528
+ };
529
+ Inherit()(ODataTableController);
530
+ //#endregion
531
+ //#region src/value-help-controllers.ts
532
+ /** A route segment that is plain text: no parameter (`:`), wildcard (`*`) or escape. */
533
+ const SEGMENT = /^[A-Za-z0-9_.~-]+$/;
534
+ const metaOf = (type) => type.metadata;
535
+ /**
536
+ * The routes made for each space. Moost takes a second handler on one path without a word, and
537
+ * runs it when the first one throws: a request its guard refuses would be answered by the twin.
538
+ */
539
+ const routesMade = /* @__PURE__ */ new WeakMap();
540
+ /** What tells an entity set apart: its service (`@db.space`), its value-help service, its name. */
541
+ function setKey(type) {
542
+ const metadata = metaOf(type);
543
+ const entitySet = metadata.get("db.table");
544
+ if (typeof entitySet !== "string") return void 0;
545
+ const valueHelpService = metadata.get("odata.valueHelpService");
546
+ return JSON.stringify([
547
+ metadata.get("db.space"),
548
+ typeof valueHelpService === "string" ? valueHelpService : "",
549
+ entitySet
550
+ ]);
551
+ }
552
+ /** The type a controller class serves, by moost-db's binding; `undefined` for another class. */
553
+ function servedType(ctor) {
554
+ const binding = findReadableBinding(ctor);
555
+ if (!binding) return void 0;
556
+ return binding.model ?? binding.resolve().type;
557
+ }
558
+ /** The `@ui.valueHelp` targets on the properties of a type, nested objects and arrays included. */
559
+ function valueHelpTargets(type, into, seen = /* @__PURE__ */ new Set()) {
560
+ const def = type.type;
561
+ if (seen.has(def)) return;
562
+ seen.add(def);
563
+ if (def.kind === "array") return valueHelpTargets(def.of, into, seen);
564
+ if (def.kind !== "object") return;
565
+ for (const prop of def.props.values()) {
566
+ if (isNavRelation(prop)) continue;
567
+ const help = metaOf(prop).get("ui.valueHelp");
568
+ const target = typeof help?.target === "function" ? help.target() : void 0;
569
+ if (isAnnotatedType(target)) into.add(target);
570
+ valueHelpTargets(prop, into, seen);
571
+ }
572
+ }
573
+ /** Refuses a base whose controllers would serve writes, or would get no routes. */
574
+ function checkBase(base) {
575
+ if (base !== ODataReadableController && !(base.prototype instanceof ODataReadableController)) throw new Error(`valueHelpControllers: \`base\` ${base.name} is no ODataReadableController: value-help routes are read-only, so the base extends ODataReadableController`);
576
+ const mate = getMoostMate();
577
+ for (let c = base; c !== ODataReadableController; c = Object.getPrototypeOf(c)) if (!mate.read(c)?.inherit) throw new Error(`valueHelpControllers: ${c.name} carries no @Inherit(): Moost passes the routes of ODataReadableController down only through classes marked @Inherit(). Add @Inherit() to ${c.name}.`);
578
+ }
579
+ /**
580
+ * The read-only controllers of the value-help sets of a live space: call it after
581
+ * `await space.connect()` and before `app.init()`, and register what it returns.
582
+ *
583
+ * ```ts
584
+ * await space.connect();
585
+ * const own = [OrderSetController];
586
+ * app.registerControllers(
587
+ * ...own,
588
+ * ...valueHelpControllers(space, { prefix: "api/vh", base: SalesValueHelp, own }),
589
+ * );
590
+ * await app.init();
591
+ * ```
592
+ *
593
+ * Which sets: without `own`, every set of the service's value-help services; with `own`, every
594
+ * `@ui.valueHelp` target of the types those controllers serve, in the service or in a
595
+ * value-help service, except the sets they serve. Taken from the live types, so a value-help set
596
+ * only the live `$metadata` has is served too.
597
+ *
598
+ * Each controller is `class extends base {}`, named `<EntitySet>ValueHelpController`, bound with
599
+ * moost-db's `@ReadableController` at `<prefix>/<service>/<EntitySet>` (a set of the service) or
600
+ * `<prefix>/<service>/<value-help service>/<EntitySet>` (the reference path without `..`
601
+ * segments). moost-db publishes that path as the target's `db.http.path`, so the `/meta` of the
602
+ * parent carries it and Atscript UI offers the picker. `$with` and relational filters are refused
603
+ * with `400`; there are no write routes.
604
+ *
605
+ * The reads are the space's own (its `init`): the service sees the server's technical user, never
606
+ * the end user. Who may call these routes is the application's to decide, through `base` and its
607
+ * global interceptors, as for every controller it declares.
608
+ *
609
+ * A set with a name that is no plain route segment (`[A-Za-z0-9_.~-]`) gets no route, with a
610
+ * warning on the console.
611
+ *
612
+ * Each route is made once per space: a second call with the same prefix throws, as do two
613
+ * value-help services whose references differ only by `.` or `..` segments. Two spaces with one
614
+ * service name and one prefix would make the same routes, which the helper cannot see: give each
615
+ * space its own name, and let `new MoostHttp({ router: { disableDuplicatePath: true } })` make
616
+ * `app.init()` refuse any path registered twice.
617
+ *
618
+ * @throws Error before the space is connected, for a space over an engine at hand (it has no
619
+ * types), for a `base` that is no `ODataReadableController` or misses `@Inherit()`, and for a
620
+ * route already made for the space.
621
+ */
622
+ function valueHelpControllers(space, options) {
623
+ const { prefix, base = ODataReadableController, own } = options;
624
+ if (!space.source) throw new Error("valueHelpControllers: the space is over an engine at hand, which has no types; create a live space (`createODataSpace({ baseUrl, model, types })`)");
625
+ const connection = space.connection;
626
+ if (!connection) throw new Error("valueHelpControllers: the OData space is not connected: call `await space.connect()` first");
627
+ checkBase(base);
628
+ const live = new Set(Object.values(connection.types));
629
+ let targets;
630
+ if (own) {
631
+ const served = own.map(servedType).filter((type) => type !== void 0);
632
+ const skip = new Set(served.map(setKey));
633
+ const found = /* @__PURE__ */ new Set();
634
+ for (const type of served) valueHelpTargets(type, found);
635
+ targets = [...found].filter((type) => {
636
+ const key = setKey(type);
637
+ return live.has(type) && key !== void 0 && !skip.has(key);
638
+ });
639
+ } else targets = [...live].filter((type) => typeof metaOf(type).get("odata.valueHelpService") === "string" && setKey(type) !== void 0);
640
+ const root = prefix.replace(/^\/+|\/+$/g, "");
641
+ const planned = targets.flatMap((type) => {
642
+ const metadata = metaOf(type);
643
+ const entitySet = metadata.get("db.table");
644
+ const valueHelpService = metadata.get("odata.valueHelpService");
645
+ const segments = [
646
+ connection.name,
647
+ ...typeof valueHelpService === "string" ? valueHelpService.split("/").filter((s) => s !== "" && s !== "." && s !== "..") : [],
648
+ entitySet
649
+ ];
650
+ const odd = segments.find((segment) => !SEGMENT.test(segment));
651
+ if (odd !== void 0) {
652
+ console.warn(`valueHelpControllers: no route for the entity set "${entitySet}": "${odd}" is no plain route segment`);
653
+ return [];
654
+ }
655
+ return [{
656
+ type,
657
+ entitySet,
658
+ route: [root, ...segments].filter(Boolean).join("/")
659
+ }];
660
+ });
661
+ const made = new Set(routesMade.get(space));
662
+ for (const { route } of planned) {
663
+ if (made.has(route)) throw new Error(`valueHelpControllers: the route "${route}" is made twice for this space (a second call with the same prefix, or value-help services whose references differ only by "." or ".." segments): a request one handler's guard refuses would be answered by the other`);
664
+ made.add(route);
665
+ }
666
+ routesMade.set(space, made);
667
+ return planned.map(({ type, entitySet, route }) => {
668
+ const Controller = class extends base {
669
+ async prepareRequest(ctx) {
670
+ if (ctx.controls?.$with !== void 0) throw badRequest("$with", "A value-help route reads no relations", "INVALID_QUERY");
671
+ if (ctx.hasRelationFilters) throw badRequest("", "A value-help route takes no relational filter", "INVALID_QUERY");
672
+ await super.prepareRequest(ctx);
673
+ }
674
+ };
675
+ Object.defineProperty(Controller, "name", { value: `${entitySet}ValueHelpController` });
676
+ ReadableController(space.getTable(type), route)(Controller);
677
+ return Controller;
678
+ });
679
+ }
680
+ //#endregion
681
+ export { ODataOperation, ODataOperationsController, ODataReadableController, ODataTableController, allowedCrud, basicAuth, bearerAuth, callTimeout, combineAuth, currentIncomingRequest, refuseGoneEntitySet, refuseUnappliedSearch, staticHeaders, valueHelpControllers };