@atscript/db-odata 0.0.0-stage → 0.0.1

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,1374 @@
1
+ import { BaseDbAdapter, DbError, DbSpace, isPlainObject, searchIndexNotFoundMessage } from "@atscript/db";
2
+ import { VERSION_TOKEN, allowedWrites, changeByKey, createODataSource, createSession, dbFailureOf, describeEntitySet, describeField, dialectFor, isODataError, isODataPayloadError, isODataQueryError, isODataServiceError, rowsFailure, runOperation, sendEach, sendsRowToken, storeFailure, withLocale, writeFailureOf, writeRefusal } from "@atscript/odata";
3
+ import { resolveAlias } from "@uniqu/core";
4
+ import { createHash } from "node:crypto";
5
+ //#region src/errors.ts
6
+ /**
7
+ * An operation the adapter refuses before any request: one OData cannot express (a write by a
8
+ * filter, a field operator, a grouped read `$apply` has no form for), or one the service model
9
+ * does not allow (a write to an entity set that is not insertable, updatable or deletable, or
10
+ * that is draft-enabled; a grouped read of a set without `$apply`, or of what it does not
11
+ * aggregate).
12
+ *
13
+ * A `DbError` with atscript-db's code `NOT_SUPPORTED` (the adapter cannot perform what was asked),
14
+ * which moost-db answers with `400`: the request can avoid it. Its one entry names no `params`, as
15
+ * moost-db's `NOT_SUPPORTED` does, and is coded `NOT_SUPPORTED`, or as the browser client codes the
16
+ * same refusal (`UNSUPPORTED_FIELD_OPERATOR` for a field operator, `CAS_NOT_SUPPORTED` for a
17
+ * version number); the browser client answers a write the entity set does not allow, and a
18
+ * grouped read it cannot answer, with the same body (`dbFailureOf` of `@atscript/odata`).
19
+ */
20
+ var ODataNotSupportedError = class extends DbError {
21
+ name = "ODataNotSupportedError";
22
+ /** The adapter method that was called (`insertMany`, `updateOne`, `deleteMany`, `aggregate`, …). */
23
+ operation;
24
+ /**
25
+ * @param message why it is refused; by default that the adapter does not support `operation`
26
+ * @param cause the engine's refusal; the entry's `path` is the one an `ODataQueryError` names
27
+ * (the field or control it is about), else empty
28
+ * @param entry the entry's `path` and `code` where the browser client names the same refusal
29
+ * so (a field operator at its field, `UNSUPPORTED_FIELD_OPERATOR`; a version number at `$cas`,
30
+ * `CAS_NOT_SUPPORTED`); by default `NOT_SUPPORTED` at the path above
31
+ */
32
+ constructor(operation, entitySet, message, cause, entry = {}) {
33
+ const text = message ?? `${operation} is not supported by the OData adapter ("${entitySet}")`;
34
+ const path = entry.path ?? (isODataQueryError(cause) ? cause.path ?? "" : "");
35
+ super("NOT_SUPPORTED", [{
36
+ path,
37
+ message: text,
38
+ code: entry.code ?? "NOT_SUPPORTED"
39
+ }], text, cause === void 0 ? void 0 : { cause });
40
+ this.operation = operation;
41
+ }
42
+ };
43
+ /** Also true for an `ODataNotSupportedError` created by another copy of this package. */
44
+ function isODataNotSupportedError(value) {
45
+ return value instanceof ODataNotSupportedError || value instanceof Error && value.name === "ODataNotSupportedError" && typeof value.operation === "string";
46
+ }
47
+ /**
48
+ * What a Moost server answers for a failure of its own call that `dbFailureOf` leaves to the
49
+ * host: the service could not be reached, refused the server's credentials (`401`, `403`) or a
50
+ * write without a session the CSRF token needs, answered another status, a page or a payload that
51
+ * is no OData answer, or a paging link that leads nowhere: `STORE_FAILED`; the call was aborted
52
+ * (`callTimeout`): `STORE_TIMEOUT`. The server calls the service with credentials it is given,
53
+ * never the caller's own, so each is a fault behind the server, not of the request.
54
+ */
55
+ function serverFailureOf(error) {
56
+ if (isODataError(error)) return storeFailure(error.kind === "aborted" ? "STORE_TIMEOUT" : "STORE_FAILED");
57
+ if (isODataServiceError(error) || isODataPayloadError(error)) return storeFailure("STORE_FAILED");
58
+ }
59
+ /**
60
+ * Turns what the OData engine throws into the `DbError` the atscript-db stack expects, with the
61
+ * original as `cause`:
62
+ *
63
+ * - every failure `dbFailureOf` of `@atscript/odata` maps (the one mapping both hosts answer
64
+ * with): `NOT_SUPPORTED` for what OData or the entity set cannot do (a write the set does not
65
+ * allow, a grouped read it cannot answer, what OData v2 cannot express); `INVALID_QUERY` for a
66
+ * read or write the engine refused (moost-db's codes on the entries: `UNKNOWN_FIELD`,
67
+ * `FIELD_NOT_PERMITTED`, …; a refused write keeps the engine's code), a value that cannot be
68
+ * written, a read past `maxPages` (on `$limit`) and a `400` of the service (its messages by
69
+ * field); `CONFLICT` for a `409` of the service; `SERIALIZATION_FAILURE` for a write that met a
70
+ * change between reading the entity's ETag and writing on every attempt; `STORE_THROTTLED`
71
+ * (`params.retryAfter`), `STORE_TIMEOUT` and `STORE_FAILED` for the service's `429`, `504` and
72
+ * other `5xx`
73
+ * - every other failure of the service, which `dbFailureOf` leaves to the host: `STORE_FAILED`
74
+ * (it could not be reached, refused the server's credentials or a write without a session,
75
+ * answered another status or no OData answer; a `404` is one of them: a key read never gets here
76
+ * with it, the engine answers that with "no entity", and the adapter answers a write by key that
77
+ * meets one with "nothing matched"), `STORE_TIMEOUT` (the call was aborted)
78
+ *
79
+ * moost-db answers the `STORE_*` codes `502`, `504` and `429` (with `Retry-After`) and logs every
80
+ * `5xx` with the cause; their messages are generic, what the service said stays in the cause.
81
+ * Anything else (a `DbError`, an error of the `init` hook, a bug) is returned as it is.
82
+ *
83
+ * @param model the service model, which maps the targets of the service's messages to field paths
84
+ */
85
+ function toDbError(error, entitySet, model) {
86
+ const failure = dbFailureOf(error, {
87
+ model,
88
+ entitySet
89
+ }) ?? serverFailureOf(error);
90
+ if (!failure) return error;
91
+ return new DbError(failure.code, failure.entries, failure.message, { cause: error });
92
+ }
93
+ /**
94
+ * What `runOperation` answered, or threw, with each error mapped as a call on its row alone: the
95
+ * one rule of the space's and a table's `callOperation`. A `412` on the caller's own version token
96
+ * (the row carries `token`: the entity changed since the caller read it) is `null`, the row's
97
+ * version mismatch for the caller to answer: one row resolves `null`, a row of several is
98
+ * `{ index, error: null }` in `failed`. A row the service has no entity for (the ETag read finds
99
+ * none, or the call is answered `404` or `410`) is a `DbError` `NOT_FOUND`; every other failure is
100
+ * mapped by {@link toDbError}, as a refused `changeSet` run of several rows is.
101
+ *
102
+ * @param context `token`, the field the rows carry the version token in, where the call sends it
103
+ * as `If-Match` (`sendsRowToken`; none: no `null`); the entity set and the model that map the
104
+ * targets of the service's messages
105
+ */
106
+ async function operationAnswer(running, rows = [], context) {
107
+ const { token, entitySet, model } = context;
108
+ const mapped = (error, row) => {
109
+ const failure = writeFailureOf(error);
110
+ if (token !== void 0 && typeof row?.[token] === "string" && row[token] !== "" && failure === "changed") return null;
111
+ if (row !== void 0 && failure === "not-found") return new DbError("NOT_FOUND", [{
112
+ path: "",
113
+ message: "Not found"
114
+ }], "Not found", { cause: error });
115
+ return toDbError(error, entitySet, model);
116
+ };
117
+ let answer;
118
+ try {
119
+ answer = await running;
120
+ } catch (error) {
121
+ const failure = mapped(error, rows.length === 1 ? rows[0] : void 0);
122
+ if (failure === null) return null;
123
+ throw failure;
124
+ }
125
+ if (answer.failed) answer.failed = answer.failed.map(({ index, error }) => ({
126
+ index,
127
+ error: mapped(error, rows[index])
128
+ }));
129
+ return answer;
130
+ }
131
+ //#endregion
132
+ //#region src/refusals.ts
133
+ /** The verdict refusing `operation` among a connection's refusals; `undefined` when it fits. */
134
+ function refusalIn(connection, operation) {
135
+ const verdict = connection?.refusals?.[operation.paramsType];
136
+ return verdict && verdict.operation.operation === operation.operation ? verdict : void 0;
137
+ }
138
+ //#endregion
139
+ //#region src/read-spec.ts
140
+ function isKeyValue(value) {
141
+ const type = typeof value;
142
+ return type === "string" || type === "number" || type === "boolean" || type === "bigint" || value instanceof Date;
143
+ }
144
+ function collectEqualities(filter, found) {
145
+ if (!isPlainObject(filter)) return false;
146
+ for (const [name, value] of Object.entries(filter)) {
147
+ if (value === void 0) continue;
148
+ if (name === "$and") {
149
+ if (!Array.isArray(value)) return false;
150
+ if (!value.every((member) => collectEqualities(member, found))) return false;
151
+ continue;
152
+ }
153
+ if (name.startsWith("$")) return false;
154
+ let operand = value;
155
+ if (isPlainObject(value)) {
156
+ const operators = Object.keys(value);
157
+ if (operators.length !== 1 || operators[0] !== "$eq") return false;
158
+ operand = value.$eq;
159
+ }
160
+ if (!isKeyValue(operand)) return false;
161
+ if (found.has(name) && found.get(name) !== operand) return false;
162
+ found.set(name, operand);
163
+ }
164
+ return true;
165
+ }
166
+ /**
167
+ * The entity key a filter addresses, when the filter is exactly an equality on every key property
168
+ * and nothing else: `{ K: v }`, `{ K: { $eq: v } }`, several keys in one object or spread over a
169
+ * `$and`. This is how an id lookup of the table layer arrives. `undefined` for every other filter.
170
+ */
171
+ function keyOf(filter, keys) {
172
+ if (keys.length === 0) return void 0;
173
+ const found = /* @__PURE__ */ new Map();
174
+ if (!collectEqualities(filter, found) || found.size !== keys.length) return void 0;
175
+ const key = {};
176
+ for (const name of keys) {
177
+ if (!found.has(name)) return void 0;
178
+ key[name] = found.get(name);
179
+ }
180
+ return key;
181
+ }
182
+ const covers = (ancestor, path) => path === ancestor || path.startsWith(`${ancestor}.`);
183
+ /** The paths a `$select` asks for, with no path listed under a selected parent. */
184
+ function selectedPaths(select, leaves) {
185
+ const projection = select.asProjection;
186
+ if (!projection) return void 0;
187
+ const entries = Object.entries(projection);
188
+ if (entries[0][1] === 1) {
189
+ const included = entries.filter(([, flag]) => flag === 1).map(([path]) => path);
190
+ return included.filter((path) => !included.some((other) => other !== path && covers(other, path)));
191
+ }
192
+ const excluded = entries.filter(([, flag]) => flag === 0).map(([path]) => path);
193
+ return leaves.filter((leaf) => !excluded.some((path) => covers(path, leaf)));
194
+ }
195
+ /**
196
+ * `$sort` as `$orderby`. A key property the service cannot sort by is left out: the table layer
197
+ * appends the primary key to every `$sort` as a tie-breaker, after its own capability check, and
198
+ * a tie-breaker the service cannot honour must not fail the read. Any other property is passed
199
+ * on, and the query layer refuses the read when the service cannot sort by it.
200
+ */
201
+ function orderByOf(sort, context) {
202
+ const orderBy = [];
203
+ for (const [path, direction] of Object.entries(sort ?? {})) {
204
+ if (context.unsortableKeys.includes(path)) continue;
205
+ orderBy.push(direction === -1 ? {
206
+ path,
207
+ desc: true
208
+ } : { path });
209
+ }
210
+ return orderBy;
211
+ }
212
+ function count(value) {
213
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
214
+ }
215
+ /**
216
+ * Translates what the table layer hands an adapter into a {@link ReadSpec}:
217
+ *
218
+ * - `filter` is passed on as it is: paths use `.` between segments on both sides
219
+ * - `$select` → `select` (an exclusion projection becomes the remaining leaves), without the
220
+ * version token, which the service does not have: the adapter fills it from the ETag
221
+ * - `$sort` → `orderBy`, without the key properties the service cannot sort by
222
+ * - `$skip` / `$limit` → `skip` / `top`
223
+ *
224
+ * `$with` is left to {@link withRelations}: its entries name the tables of the relations, whose
225
+ * adapters translate their part. The other controls are not reads of an entity set and are
226
+ * ignored here.
227
+ */
228
+ function readShapeOf(query, context) {
229
+ const { controls } = query;
230
+ const spec = { entitySet: context.entitySet };
231
+ if (query.filter && Object.keys(query.filter).length > 0) spec.filter = query.filter;
232
+ const shape = { spec };
233
+ const select = controls.$select ? selectedPaths(controls.$select, context.leaves) : void 0;
234
+ if (select) {
235
+ spec.select = select.filter((path) => path !== context.token);
236
+ shape.projection = select.map((path) => path.split("."));
237
+ }
238
+ const orderBy = orderByOf(controls.$sort, context);
239
+ if (orderBy.length > 0) spec.orderBy = orderBy;
240
+ const skip = count(controls.$skip);
241
+ if (skip) spec.skip = skip;
242
+ const top = count(controls.$limit);
243
+ if (top !== void 0) spec.top = top;
244
+ return shape;
245
+ }
246
+ /**
247
+ * `shape` of a related table's read, whose rows keep the table's key: a selection of the relation
248
+ * is widened with the key properties it leaves out, as atscript-db's relation loader keeps the key
249
+ * of a related row it joins by, and as the service sends it (the browser client hands the rows on
250
+ * as they come).
251
+ */
252
+ function keepingKey(shape, key) {
253
+ const { projection } = shape;
254
+ if (!projection) return shape;
255
+ for (const name of key) if (!projection.some((segments) => segments.length === 1 && segments[0] === name)) projection.push([name]);
256
+ return shape;
257
+ }
258
+ /** The expansion of a relation: the parts of its table's read an expansion takes. */
259
+ function expansionOf({ nav, shape }) {
260
+ const { filter, select, orderBy, expand } = shape.spec;
261
+ const expansion = { navigation: nav };
262
+ if (filter) expansion.filter = filter;
263
+ if (select) expansion.select = select;
264
+ if (orderBy) expansion.orderBy = orderBy;
265
+ if (expand) expansion.expand = expand;
266
+ return expansion;
267
+ }
268
+ /**
269
+ * `shape` with the relations of `$with` as expansions of its request (`$expand`): the filter,
270
+ * selection, sort and nested relations of each go with it. The table layer never pages a
271
+ * relation of this adapter. The navigations join the projection, so a `$select` of the read does
272
+ * not cut them away.
273
+ */
274
+ function withRelations(shape, relations) {
275
+ if (relations.length === 0) return shape;
276
+ shape.relations = relations;
277
+ shape.spec.expand = relations.map(expansionOf);
278
+ if (shape.projection) for (const { nav } of relations) shape.projection.push([nav]);
279
+ return shape;
280
+ }
281
+ function copyPath(from, to, segments, depth) {
282
+ const name = segments[depth];
283
+ if (!Object.hasOwn(from, name)) return;
284
+ const value = from[name];
285
+ if (depth === segments.length - 1 || !isPlainObject(value)) {
286
+ to[name] = value;
287
+ return;
288
+ }
289
+ const target = isPlainObject(to[name]) ? to[name] : {};
290
+ to[name] = target;
291
+ copyPath(value, target, segments, depth + 1);
292
+ }
293
+ /** The rows with only the selected paths; the rows themselves when everything is selected. */
294
+ function projectRows(rows, projection) {
295
+ if (!projection) return rows;
296
+ return rows.map((row) => {
297
+ const projected = {};
298
+ for (const segments of projection) copyPath(row, projected, segments, 0);
299
+ return projected;
300
+ });
301
+ }
302
+ /**
303
+ * The rows of a read cut back to its shape: the selected paths of each row, and the related
304
+ * rows of each relation cut back to the relation's own shape, at every depth. The service
305
+ * returns more than was asked for (the key always, a complex value as a whole on v2).
306
+ */
307
+ function shapeRows(rows, shape) {
308
+ const shaped = projectRows(rows, shape.projection);
309
+ for (const { nav, shape: related } of shape.relations ?? []) for (const row of shaped) {
310
+ const value = row[nav];
311
+ if (Array.isArray(value)) row[nav] = shapeRows(value, related);
312
+ else if (isPlainObject(value)) row[nav] = shapeRows([value], related)[0];
313
+ }
314
+ return shaped;
315
+ }
316
+ //#endregion
317
+ //#region src/write-payload.ts
318
+ /**
319
+ * A value that replaces a complex value as a whole, with every member it leaves out set to
320
+ * `null`: OData merges a complex value sent with `PATCH` / `MERGE` into the stored one, so an
321
+ * omitted member would otherwise keep its stored value.
322
+ */
323
+ function wholeValue(value, path, membersOf) {
324
+ const whole = {};
325
+ for (const [name, member] of Object.entries(value)) whole[name] = isPlainObject(member) ? wholeValue(member, `${path}.${name}`, membersOf) : member;
326
+ for (const name of membersOf(path) ?? []) if (!Object.hasOwn(whole, name)) whole[name] = null;
327
+ return whole;
328
+ }
329
+ /**
330
+ * The payload of an OData partial update (`PATCH` on v4, `MERGE` on v2) for a patch as the table
331
+ * layer hands it to `updateOne`:
332
+ *
333
+ * - a top-level member is set as it is; a complex value (an object) replaces the stored one,
334
+ * which is what the table layer means by it (`@db.patch.strategy "replace"`, the default), so
335
+ * the members it leaves out are sent as `null`
336
+ * - a dot path (`Address.City`, from a `@db.patch.strategy "merge"` object) is written into its
337
+ * complex value, whose other members the service keeps: OData merges complex values in a
338
+ * partial update
339
+ * - an array is a collection, which OData replaces as a whole
340
+ */
341
+ function patchPayload(data, membersOf) {
342
+ const payload = {};
343
+ const paths = [];
344
+ for (const [name, value] of Object.entries(data)) if (name.includes(".")) paths.push([name.split("."), value]);
345
+ else payload[name] = isPlainObject(value) ? wholeValue(value, name, membersOf) : value;
346
+ for (const [segments, value] of paths) {
347
+ let target = payload;
348
+ for (const segment of segments.slice(0, -1)) {
349
+ const next = target[segment];
350
+ target = isPlainObject(next) ? next : target[segment] = {};
351
+ }
352
+ target[segments.at(-1)] = isPlainObject(value) ? wholeValue(value, segments.join("."), membersOf) : value;
353
+ }
354
+ return payload;
355
+ }
356
+ //#endregion
357
+ //#region src/odata-adapter.ts
358
+ /** The name of the one search index an entity set with free-text search has. */
359
+ const ODATA_SEARCH_INDEX = "DEFAULT";
360
+ const STORE_DEFAULT_FNS = new Set(["store"]);
361
+ /** What the table layer reads a primary-key or foreign-key field with. */
362
+ const KEY_FILTER_OPS = ["$eq", "$in"];
363
+ /** A query-layer operator that is a comparison of atscript-db (no relation predicate). */
364
+ function isComparison(op) {
365
+ return op !== "$some" && op !== "$none";
366
+ }
367
+ function under(path, parents) {
368
+ return parents.some((parent) => path.startsWith(`${parent}.`));
369
+ }
370
+ /** The first field a field operator (`$inc`, `$mul`) names; `undefined` when there is none. */
371
+ function fieldOpPath(ops) {
372
+ return [ops?.inc, ops?.mul].flatMap((fields) => Object.keys(fields ?? {}))[0];
373
+ }
374
+ function sendInit(init) {
375
+ const { read: _read, maxPages: _maxPages, ...send } = init;
376
+ return send;
377
+ }
378
+ /**
379
+ * An `@atscript/db` adapter over an entity set of an OData v2 / v4 service, through the
380
+ * `@atscript/odata` engine. One instance serves one table; its entity set is the table's name
381
+ * (`@db.table`, which the generator writes as the entity set's name).
382
+ *
383
+ * Writes go one entity at a time, by key: create, partial update, replace and delete. Writes by a
384
+ * filter and field operators throw {@link ODataNotSupportedError} before any request. On an entity
385
+ * set with optimistic concurrency the table has a version token (the entity's ETag): an update or
386
+ * replace that carries it (`$cas`) is sent with it as `If-Match`, and a change made since the
387
+ * caller's read matches nothing, which moost-db answers as its version mismatch. One that does
388
+ * not carry it, and every delete, is last-write-wins: the adapter reads the current ETag right
389
+ * before the write, which satisfies the service's If-Match requirement but detects no change made
390
+ * since the caller's own read (a change between that read and the write has the write sent again,
391
+ * three attempts at most, then `SERIALIZATION_FAILURE`). A call the service does not serve is a
392
+ * `STORE_FAILED`, `STORE_TIMEOUT` or `STORE_THROTTLED` (see `toDbError`). There
393
+ * are no transactions: a write of several rows that fails midway leaves the rows written before
394
+ * it. The relations of `$with` ride the read as `$expand` (see {@link supportsWithInRead}).
395
+ */
396
+ var ODataAdapter = class extends BaseDbAdapter {
397
+ _set;
398
+ _leaves;
399
+ _members;
400
+ _keyFields;
401
+ _aggregateFns;
402
+ _fields = /* @__PURE__ */ new Map();
403
+ _service;
404
+ provide;
405
+ /** The entity set (the table's name) and the value-help service the adapter was bound to. */
406
+ _bound;
407
+ /** What the entity set was described from: the live model, or the saved one for a gone set. */
408
+ _described;
409
+ _gone = false;
410
+ constructor(service, options = {}) {
411
+ super();
412
+ this.options = options;
413
+ this.provide = typeof service === "function" ? service : () => service;
414
+ }
415
+ /**
416
+ * The service the table is read from: the one the adapter was created with, or, for a type of
417
+ * one of its value-help services (`@odata.valueHelpService`), that service's engine
418
+ * (`service.valueHelpService(…)`).
419
+ *
420
+ * @throws Error before the service is known (a live space not connected yet).
421
+ */
422
+ get service() {
423
+ this.describe();
424
+ return this._service;
425
+ }
426
+ /**
427
+ * Whether the live service no longer has the entity set (a live space only): every call of
428
+ * the table then throws a plain `Error`, a fault of the server's build (moost-db answers it
429
+ * `500`); the OData controller bases of `@atscript/moost-odata` answer such a table `404` first.
430
+ */
431
+ get gone() {
432
+ this.describe();
433
+ return this._gone;
434
+ }
435
+ /** Describes the entity set once the service is known; see {@link entitySet}. */
436
+ describe() {
437
+ if (this._set) return this._set;
438
+ const bound = this._bound;
439
+ if (!bound) throw new Error("The OData adapter is not bound to a table: it has no entity set");
440
+ const base = this.provide();
441
+ if (!base) throw new Error(`Table "${bound.name}": its OData space is not connected. Call \`await space.connect()\` before the tables are used (before \`app.init()\`).`);
442
+ const { saved } = this.options;
443
+ let service = base;
444
+ if (bound.valueHelp !== void 0) {
445
+ service = base.valueHelpService(bound.valueHelp);
446
+ if (!service && !saved) throw new Error(`The OData service has no value-help service "${bound.valueHelp}" (table "${bound.name}"). Create the service from the model module generated with the types, which holds its value-help services.`);
447
+ }
448
+ if (service && Object.hasOwn(service.model.entitySets, bound.name)) {
449
+ this._service = service;
450
+ this._described = {
451
+ model: service.model,
452
+ context: service.context
453
+ };
454
+ } else {
455
+ const model = bound.valueHelp === void 0 ? saved : saved?.valueHelpServices?.[bound.valueHelp]?.model;
456
+ if (!model || !Object.hasOwn(model.entitySets, bound.name)) throw new Error(`The OData service has no entity set "${bound.name}"`);
457
+ this._gone = true;
458
+ this._service = service ?? base;
459
+ this._described = {
460
+ model,
461
+ context: {
462
+ version: model.version,
463
+ dialect: dialectFor(model)
464
+ }
465
+ };
466
+ }
467
+ this._set = describeEntitySet(this._described.model, bound.name, this._described.context);
468
+ return this._set;
469
+ }
470
+ /**
471
+ * Refuses every call of a table whose entity set the live service no longer has: the server's
472
+ * build no longer fits the service, which no request can avoid (a plain `Error`).
473
+ */
474
+ refuseGone() {
475
+ if (!this.gone) return;
476
+ throw new Error(`The OData service no longer has the entity set "${this._bound.name}"`);
477
+ }
478
+ /**
479
+ * Why an operation of the build bound to this entity set is refused: its verdict when the live
480
+ * service no longer has it or no longer fits the build's calls of it (see
481
+ * `ODataSpace.refusalOf`); `undefined` when it fits.
482
+ */
483
+ refusalOf(operation) {
484
+ return refusalIn(this.options.connection?.(), operation);
485
+ }
486
+ /**
487
+ * Calls an operation bound to this entity set (`runOperation` of `@atscript/odata`, the entity
488
+ * set filled in), with the space's credentials and session, as every call of the table: on the
489
+ * collection, or, for an operation called on rows, on `rows` (each with its key and, where the
490
+ * set has a version token, its `__etag`). The handle of an unbound operation (it names no entity
491
+ * set) is called unbound: a db action of the table over it. The parameters are validated against
492
+ * the live operation type (the validator's `ValidatorError`); what the call throws is mapped as
493
+ * the table's calls are (`toDbError`).
494
+ *
495
+ * A call that sends the caller's version token (a call that writes, on a row with its `__etag`;
496
+ * see `sendsRowToken`) that the service refuses with `412` resolves `null`: the entity changed
497
+ * since the caller read it, a version mismatch for the caller to answer (a Moost server answers
498
+ * it as moost-db answers a stale write: `409` with the current token, or `404`). Without the
499
+ * token the ETag is read first, and read again when the entity changed in between
500
+ * (`retryWhileChanged`, then `SERIALIZATION_FAILURE`).
501
+ *
502
+ * A row the service has no entity for (the ETag read before its call finds none, or the call is
503
+ * answered `404` or `410`) is a `DbError` `NOT_FOUND`, which the OData controller bases answer as
504
+ * moost-db answers a missing row (`notFoundError()`, `404`). An operation the live service no
505
+ * longer has never gets here: its verdict refuses it before any call.
506
+ *
507
+ * Several rows go out as one `$batch` by `input.grouping` (see `runOperation`; one call per row
508
+ * on a service created with `batch: false`, as a space's `batch: false` creates it). Each row of
509
+ * an `isolated` run that failed is in `failed`, its error mapped as a call on that row alone: a
510
+ * `DbError` (`toDbError`, `NOT_FOUND` above), or `null` for a `412` on its own `__etag` (its
511
+ * version mismatch, as for one row). A `changeSet` run the service refused throws its one error,
512
+ * mapped so (`SERIALIZATION_FAILURE` for a `412`, `CONFLICT` for a `404`: nothing was applied;
513
+ * the entries of a message that names a row at that row, `[1]`).
514
+ *
515
+ * @throws Error for an entity set the live service no longer has.
516
+ */
517
+ async callOperation(input) {
518
+ this.refuseGone();
519
+ const connection = this.options.connection?.();
520
+ if (!connection) throw new Error(`Table "${this.entitySet.name}": an operation runs on the connection of an OData space (createODataSpace), which it has not`);
521
+ const init = sendInit(await this.options.init?.() ?? {});
522
+ const run = typeof input.operation !== "string" && input.operation.entitySet === void 0 ? { ...input } : {
523
+ ...input,
524
+ entitySet: this.entitySet.name
525
+ };
526
+ return operationAnswer(runOperation(connection, run, init), input.rows, {
527
+ token: sendsRowToken(connection, run) ? this.token : void 0,
528
+ entitySet: this.entitySet.name,
529
+ model: this.service.model
530
+ });
531
+ }
532
+ registerReadable(...args) {
533
+ super.registerReadable(...args);
534
+ const [readable] = args;
535
+ const valueHelp = readable.type.metadata.get("odata.valueHelpService");
536
+ this._bound = {
537
+ name: readable.tableName,
538
+ ...typeof valueHelp === "string" ? { valueHelp } : {}
539
+ };
540
+ if (this.provide()) this.describe();
541
+ }
542
+ /**
543
+ * The entity set this adapter reads, as the query layer describes it: from the live model, or,
544
+ * for a set the live service no longer has, from the saved one.
545
+ */
546
+ get entitySet() {
547
+ return this.describe();
548
+ }
549
+ /** A complex type is a nested object; paths arrive as `Address.City`. */
550
+ supportsNestedObjects() {
551
+ return true;
552
+ }
553
+ /** Referential integrity is the service's business. */
554
+ supportsNativeForeignKeys() {
555
+ return true;
556
+ }
557
+ /**
558
+ * The relations of `$with` are read in the request of the rows, as `$expand`: every row comes
559
+ * back with its related rows under the navigation name. Each `$with` entry goes into the
560
+ * expansion as the table layer hands it over, with its filter (a relation's own and any a
561
+ * controller conjoined into the entry), its `$select` and `$sort` and its nested entries, so a
562
+ * scope a server adds to a relation reaches the service. OData v2 has no options in an
563
+ * expansion other than the selection: there a filter or sort of a relation is refused
564
+ * (`NOT_SUPPORTED`), never dropped. The table layer refuses paging a relation itself.
565
+ *
566
+ * A navigation the service declares no foreign key for (`@db.rel.store`) is read the same way.
567
+ */
568
+ supportsWithInRead() {
569
+ return true;
570
+ }
571
+ /** A relation is read through `$expand`: only to a table of the same service. */
572
+ sharesStoreWith(other) {
573
+ return super.sharesStoreWith(other) && other.service === this.service;
574
+ }
575
+ /**
576
+ * The aggregate functions of the entity set's `$apply` (`aggregateFns` of `describeEntitySet`):
577
+ * none on OData v2 and on a set the service declares no `Aggregation.ApplySupported` for; `sum`,
578
+ * `min`, `max`, `avg` on an SAP service; also `count` and `countDistinct` on any other. The
579
+ * table layer refuses any other function before {@link aggregate} is called.
580
+ */
581
+ aggregateFns() {
582
+ this._aggregateFns ??= new Set(this.entitySet.aggregateFns);
583
+ return this._aggregateFns;
584
+ }
585
+ /**
586
+ * `store`: a property the service computes (`@db.default.store`, which the generator emits) is
587
+ * left to the service when an insert leaves it out, and a value given for it is dropped by the
588
+ * engine. The key the service assigns comes back in `insertedId`.
589
+ */
590
+ nativeDefaultFns() {
591
+ return STORE_DEFAULT_FNS;
592
+ }
593
+ /**
594
+ * The row version is the entity's ETag, which the service moves on every write: the generator
595
+ * emits a version token field on every entity set with optimistic concurrency. Reads fill it;
596
+ * an update or replace with `$cas` sends it as `If-Match`.
597
+ */
598
+ supportsVersionTokens() {
599
+ return true;
600
+ }
601
+ /**
602
+ * Whether the service can compare the field with a value. A property whose type has no literal
603
+ * form (a stream, a geo value, `Edm.Untyped`) answers `false` although the query layer takes a
604
+ * null check on it: this method is about value comparison; {@link filterOps} lists the
605
+ * operators. A primary-key or foreign-key field is always filterable, by `$eq` and `$in`.
606
+ */
607
+ canFilterField(fd) {
608
+ if (fd.encrypted) return false;
609
+ return this.fieldOf(fd.path).filterOps.includes("$eq") || this.keyFields.has(fd.path);
610
+ }
611
+ /**
612
+ * The operators the service lets a filter use on the field: `allowedFilterOps` of
613
+ * `describeField` (what the query layer translates for the property's type, narrowed by the
614
+ * service's filter restriction). `[]` for a field the service does not let you filter by, so a
615
+ * lone `$exists` is refused there too. The table layer refuses any other operator before a
616
+ * request, and `/meta` serves the list.
617
+ *
618
+ * A primary-key or foreign-key field always keeps `$eq` and `$in`, which the table layer reads
619
+ * by itself (key reads, relation loads) and requires of such a field: a key the service declares
620
+ * non-filterable, or single-value only, still lists them. An equality on the whole key is a key
621
+ * read (`EntitySet(key)`), which needs no filter; any other filter on it the service judges.
622
+ */
623
+ filterOps(fd) {
624
+ const ops = this.fieldOf(fd.path).allowedFilterOps.filter(isComparison);
625
+ if (!this.keyFields.has(fd.path)) return ops;
626
+ return [...KEY_FILTER_OPS.filter((op) => !ops.includes(op)), ...ops];
627
+ }
628
+ /** The primary-key and foreign-key fields of the table. */
629
+ get keyFields() {
630
+ if (!this._keyFields) {
631
+ const fields = new Set(this._table.primaryKeys);
632
+ for (const fk of this._table.foreignKeys.values()) for (const field of fk.fields) fields.add(field);
633
+ this._keyFields = fields;
634
+ }
635
+ return this._keyFields;
636
+ }
637
+ canSortField(fd) {
638
+ return !fd.encrypted && !fd.isGeoPoint && this.fieldOf(fd.path).sortable;
639
+ }
640
+ isSearchable() {
641
+ return this.entitySet.searchable;
642
+ }
643
+ getSearchIndexes() {
644
+ if (!this.isSearchable()) return [];
645
+ return [{
646
+ name: ODATA_SEARCH_INDEX,
647
+ type: "text",
648
+ description: "Free-text search of the OData service",
649
+ isDefault: true
650
+ }];
651
+ }
652
+ fieldOf(path) {
653
+ let field = this._fields.get(path);
654
+ if (!field) {
655
+ const { name } = this.entitySet;
656
+ const { model, context } = this._described;
657
+ field = describeField(model, name, path, context);
658
+ this._fields.set(path, field);
659
+ }
660
+ return field;
661
+ }
662
+ /**
663
+ * A filter that is exactly an equality on every key property is read by key
664
+ * (`EntitySet(key)`); anything else is the first row of a collection read. A missing entity is
665
+ * `null`.
666
+ */
667
+ findOne(query) {
668
+ return this.call(async (init) => {
669
+ const shape = this.shapeOf(query);
670
+ const key = shape.spec.skip ? void 0 : keyOf(query.filter, this.entitySet.key);
671
+ if (key) {
672
+ const { entitySet, select, expand } = shape.spec;
673
+ const found = await this.service.readOne({
674
+ entitySet,
675
+ key,
676
+ select,
677
+ expand
678
+ }, init);
679
+ if (!found) return null;
680
+ return shapeRows(this.withTokens([found.row], [found.etag]), shape)[0];
681
+ }
682
+ const read = await this.service.read({
683
+ ...shape.spec,
684
+ top: 1
685
+ }, init);
686
+ return read.rows.length > 0 ? this.rowsOf(read, shape)[0] : null;
687
+ });
688
+ }
689
+ /**
690
+ * Reads the matching rows; the engine follows the paging links of the service up to `$limit`.
691
+ * A read without `$limit` that the service cuts into more pages than the engine follows fails
692
+ * (`INVALID_QUERY` on `$limit`) instead of answering with a part of the rows.
693
+ */
694
+ findMany(query) {
695
+ return this.call(async (init) => {
696
+ const shape = this.shapeOf(query);
697
+ return this.rowsOf(await this.service.read(shape.spec, init), shape);
698
+ });
699
+ }
700
+ /**
701
+ * `/$count`; a filter that is exactly an equality on every key property is a key read instead,
702
+ * which also works on a set that cannot count or demands a filter on other properties. The
703
+ * table layer asks this way whether the row of a patch with nothing to write exists.
704
+ */
705
+ count(query) {
706
+ return this.call(async (init) => {
707
+ const key = keyOf(query.filter, this.entitySet.key);
708
+ if (!key) return this.service.count(this.countSpecOf(query), init);
709
+ const { name: entitySet, key: select } = this.entitySet;
710
+ return await this.service.readOne({
711
+ entitySet,
712
+ key,
713
+ select
714
+ }, init) ? 1 : 0;
715
+ });
716
+ }
717
+ /** One request: the rows with the inline count of the service. */
718
+ findManyWithCount(query) {
719
+ return this.call((init) => this.readWithCount(this.shapeOf(query), init));
720
+ }
721
+ search(text, query, indexName) {
722
+ return this.call(async (init) => {
723
+ const shape = this.searchShapeOf(text, query, indexName);
724
+ return this.rowsOf(await this.service.read(shape.spec, init), shape);
725
+ });
726
+ }
727
+ searchWithCount(text, query, indexName) {
728
+ return this.call((init) => this.readWithCount(this.searchShapeOf(text, query, indexName), init));
729
+ }
730
+ /**
731
+ * A grouped read, as one OData v4 `$apply` request (`planAggregate` of `@atscript/odata`): the
732
+ * filter, the grouping with its aggregates, `$having` as a filter of the groups, then `$sort`,
733
+ * `$skip` and `$limit` over the groups; `$count` asks for the number of groups
734
+ * (`$top=0&$count=true`) and answers `[{ count }]`. Rows come back with the grouped fields
735
+ * (nested under a complex property) and every aggregate under its alias, decoded as reads are
736
+ * (a decimal as a string, a count as a number).
737
+ *
738
+ * Refused with {@link ODataNotSupportedError} before any request: a set that cannot aggregate
739
+ * (OData v2, no `Aggregation.ApplySupported`), and what the service model rules out (an amount
740
+ * whose currency is not grouped, `sum` / `avg` of what is no number, `count` of a field,
741
+ * `$search`). What only the service knows it answers itself.
742
+ */
743
+ aggregate(query) {
744
+ return this.call(async (init) => {
745
+ const spec = this.aggregateSpecOf(query);
746
+ try {
747
+ const result = await this.service.aggregate(spec, init);
748
+ return spec.count ? [{ count: result.count }] : result.rows;
749
+ } catch (error) {
750
+ if (isODataQueryError(error) && error.code === "UNSUPPORTED_AGGREGATE") throw new ODataNotSupportedError("aggregate", this.entitySet.name, error.message, error);
751
+ throw error;
752
+ }
753
+ });
754
+ }
755
+ /**
756
+ * Creates the entity: `POST` to the entity set. Resolves with its key: the one the service
757
+ * reports (from the returned entity, else from the `Location` / `OData-EntityId` header), else
758
+ * the one in `data` when it was sent. A key property the service computes is not sent (the
759
+ * engine drops it), so its value in `data` does not count.
760
+ */
761
+ insertOne(data) {
762
+ return this.write("insertOne", "insert", async (init) => ({ insertedId: await this.create(data, init) }));
763
+ }
764
+ /**
765
+ * One `POST` per row. Several rows go out as one `$batch`, each row in a changeset of its own
766
+ * (on OData v4 the service is asked to continue past a failed part): it is not atomic, and the
767
+ * rows after a failed one still run. On a service created with `batch: false` (a space's
768
+ * `batch: false`) or without `$batch`, the rows go one after the other, on past a failed one,
769
+ * answered alike. The table
770
+ * layer inserts a single row this way too: one plain `POST`, its failure its own.
771
+ *
772
+ * Several rows answer `{ insertedCount, insertedIds }` in request order when every row was
773
+ * created. When rows failed it throws the first failed row's error (its code), with every
774
+ * failed row's entries at that row (`[1].City`, `[1]`) and, for each row created, an entry
775
+ * `{ path: "[j]", code: "INSERTED", message, params: { insertedId } }`; its message says how many
776
+ * rows were created and which failed (`rowsFailure` of `@atscript/odata`). Every row failed: the
777
+ * first row's message, no `INSERTED` entry. A `$batch` that failed as a whole: that failure,
778
+ * mapped as a single call's (nothing is known to have run).
779
+ */
780
+ insertMany(data) {
781
+ return this.write("insertMany", "insert", async (init) => {
782
+ if (data.length === 1) return {
783
+ insertedCount: 1,
784
+ insertedIds: [await this.create(data[0], init)]
785
+ };
786
+ const set = this.entitySet.name;
787
+ const rows = data.map((row) => this.withoutToken(row));
788
+ const settled = await sendEach(this.service, rows.length, (index, target) => target.batch ? target.batch.create(set, rows[index]) : this.service.create(set, rows[index], target.init), init);
789
+ const created = [];
790
+ const failed = [];
791
+ settled.forEach((outcome, index) => {
792
+ if (outcome.status === "rejected") failed.push({
793
+ index,
794
+ error: toDbError(outcome.reason, set, this.service.model)
795
+ });
796
+ else created.push({
797
+ index,
798
+ insertedId: this.insertedId(rows[index], outcome.value)
799
+ });
800
+ });
801
+ if (failed.length === 0) return {
802
+ insertedCount: created.length,
803
+ insertedIds: created.map((row) => row.insertedId)
804
+ };
805
+ const [first] = failed;
806
+ if (!failed.every(({ error }) => error instanceof DbError)) throw first.error;
807
+ const { message, entries } = rowsFailure(rows.length, failed.map(({ index, error }) => {
808
+ const { code, message, errors } = error;
809
+ return {
810
+ index,
811
+ code,
812
+ message,
813
+ entries: errors
814
+ };
815
+ }), created);
816
+ const error = first.error;
817
+ throw new DbError(error.code, entries, message, { cause: error.cause });
818
+ });
819
+ }
820
+ /**
821
+ * Replaces the entity (`PUT`) addressed by `filter`, which has to be an equality on every key
822
+ * property. Properties the service maintains are not sent. An entity the service does not
823
+ * have matches nothing.
824
+ */
825
+ replaceOne(filter, data, expectedVersion) {
826
+ return this.write("replaceOne", "update", async (init, operation) => {
827
+ const key = this.keyFor(operation, filter);
828
+ return this.change(operation, key, init, expectedVersion, (etag) => this.service.replace(this.entitySet.name, key, data, {
829
+ ...init,
830
+ etag
831
+ }));
832
+ });
833
+ }
834
+ /**
835
+ * Partially updates the entity (`MERGE` on v2, `PATCH` on v4) addressed by `filter`, which has
836
+ * to be an equality on every key property. A complex value in `data` replaces the stored one
837
+ * (its other members are sent as `null`); a dot path is merged into it. Field operators
838
+ * (`$inc`, `$mul`) are refused. An entity the service does not have matches nothing.
839
+ */
840
+ updateOne(filter, data, ops, expectedVersion) {
841
+ return this.write("updateOne", "update", async (init, operation) => {
842
+ const opPath = fieldOpPath(ops);
843
+ if (opPath !== void 0) throw new ODataNotSupportedError(operation, this.entitySet.name, "Field operators ($inc, $mul) cannot be expressed in an OData write: send the new value", void 0, {
844
+ path: opPath,
845
+ code: "UNSUPPORTED_FIELD_OPERATOR"
846
+ });
847
+ const key = this.keyFor(operation, filter);
848
+ const patch = patchPayload(data, (path) => this.membersOf(path));
849
+ return this.change(operation, key, init, expectedVersion, (etag) => this.service.update(this.entitySet.name, key, patch, {
850
+ ...init,
851
+ etag
852
+ }));
853
+ });
854
+ }
855
+ /**
856
+ * Deletes the entity addressed by `filter`, which has to be an equality on every key property.
857
+ * An entity the service does not have is not deleted (`deletedCount: 0`). Last-write-wins, as
858
+ * an update without a version token: the current ETag is read right before the delete, again
859
+ * when the entity changed in between (`retryWhileChanged`).
860
+ */
861
+ deleteOne(filter) {
862
+ return this.write("deleteOne", "delete", async (init, operation) => {
863
+ const key = this.keyFor(operation, filter);
864
+ const { matched } = await changeByKey((etag) => this.service.remove(this.entitySet.name, key, {
865
+ ...init,
866
+ etag
867
+ }), this.byKey(key, init));
868
+ return { deletedCount: matched ? 1 : 0 };
869
+ });
870
+ }
871
+ updateMany() {
872
+ return this.refuseByFilter("updateMany");
873
+ }
874
+ replaceMany() {
875
+ return this.refuseByFilter("replaceMany");
876
+ }
877
+ deleteMany() {
878
+ return this.refuseByFilter("deleteMany");
879
+ }
880
+ /** The service owns its schema: there is nothing to create. */
881
+ ensureTable() {
882
+ return Promise.resolve();
883
+ }
884
+ refuseByFilter(operation) {
885
+ const name = this._set?.name ?? "";
886
+ return Promise.reject(new ODataNotSupportedError(operation, name, `${operation} writes the rows a filter matches; the OData adapter writes one entity of "${name}" at a time, by its key`));
887
+ }
888
+ /**
889
+ * The writes the service model allows on the entity set, as the adapter applies them
890
+ * (`allowedWrites` of `@atscript/odata`, the rule the browser client follows too): none on a set
891
+ * that is draft-enabled, can only be reached through a navigation, or holds the parameters of a
892
+ * parameterized view. Every other write is refused with {@link ODataNotSupportedError} before any
893
+ * request.
894
+ */
895
+ get allowedWrites() {
896
+ return allowedWrites(this.entitySet);
897
+ }
898
+ /**
899
+ * What the service model says about writing to the entity set, whatever the write sends:
900
+ * `writeRefusal` of `@atscript/odata`.
901
+ */
902
+ refuseUnless(operation, write) {
903
+ const refusal = writeRefusal(this.entitySet, write);
904
+ if (refusal) throw new ODataNotSupportedError(operation, this.entitySet.name, refusal.message, refusal);
905
+ }
906
+ /** The key of a write by key; any other filter is refused (there is no write by query). */
907
+ keyFor(operation, filter) {
908
+ const { name, key: names } = this.entitySet;
909
+ const key = keyOf(filter, names);
910
+ if (key) return key;
911
+ throw new ODataNotSupportedError(operation, name, `${operation} needs a filter that is exactly an equality on every key property of "${name}" (${names.join(", ")}): an OData service writes one entity by its key`);
912
+ }
913
+ /**
914
+ * Runs a write: refuses what the service model does not allow before anything is asked, then
915
+ * calls `init` once and maps what the write throws (see `toDbError`).
916
+ */
917
+ async write(operation, write, run) {
918
+ this.refuseGone();
919
+ this.refuseUnless(operation, write);
920
+ const init = sendInit(await this.options.init?.() ?? {});
921
+ try {
922
+ return await run(init, operation);
923
+ } catch (error) {
924
+ throw toDbError(error, this.entitySet.name, this.service.model);
925
+ }
926
+ }
927
+ async create(data, init) {
928
+ const row = this.withoutToken(data);
929
+ return this.insertedId(row, await this.service.create(this.entitySet.name, row, init));
930
+ }
931
+ /** The row to create: the service issues the ETag, so a token given with it means nothing. */
932
+ withoutToken(data) {
933
+ const { token } = this;
934
+ if (!token || !Object.hasOwn(data, token)) return data;
935
+ const { [token]: _token, ...rest } = data;
936
+ return rest;
937
+ }
938
+ /**
939
+ * The key of a created row: the one the service reports (from the returned entity, else from
940
+ * the `Location` / `OData-EntityId` header), else the one sent.
941
+ */
942
+ insertedId(data, result) {
943
+ const written = { ...data };
944
+ for (const path of result.dropped ?? []) delete written[path];
945
+ if (result.key) Object.assign(written, result.key);
946
+ return this._resolveInsertedId(written, void 0, result.key);
947
+ }
948
+ /**
949
+ * How a write by key reads the entity (`changeByKey` of `@atscript/odata`): its ETag, when the
950
+ * entity set declares optimistic concurrency (with or without naming the properties), read
951
+ * right before a write without the caller's token to be sent as `If-Match`; when the entity
952
+ * answers without one, `*` is sent (the set wants an If-Match). After a write with nothing to
953
+ * send, its existence is read
954
+ * by the key alone.
955
+ *
956
+ * The pre-read only satisfies the service's If-Match requirement (it would answer `428`
957
+ * otherwise). It is not optimistic concurrency: the ETag is read by the adapter, not carried
958
+ * from the caller's own read, so the write is last-write-wins and overwrites whatever changed
959
+ * since the caller read the entity. A change in the moment between this read and the write (a
960
+ * `412`) has the ETag read again and the write sent again (three attempts); conflict detection
961
+ * is the caller's version token (`$cas`, see {@link change}).
962
+ */
963
+ byKey(key, init) {
964
+ const { name: entitySet, key: select, optimisticConcurrency } = this.entitySet;
965
+ return {
966
+ read: async () => {
967
+ const found = await this.service.readOne({
968
+ entitySet,
969
+ key
970
+ }, init);
971
+ return found ? { etag: found.etag } : void 0;
972
+ },
973
+ readEtag: optimisticConcurrency !== void 0,
974
+ exists: async () => !!await this.service.readOne({
975
+ entitySet,
976
+ key,
977
+ select
978
+ }, init)
979
+ };
980
+ }
981
+ /**
982
+ * An update or replace by key (`changeByKey` of `@atscript/odata`). With `expected` (the
983
+ * caller's version token, from `$cas`) it is sent as `If-Match` and nothing is read first: a
984
+ * `412` (the entity changed) and a `404` match nothing, which moost-db answers as its version
985
+ * mismatch (409, the current token) or a missing row. Without it, the ETag the set needs is
986
+ * read right before the write (last-write-wins), and read again when the entity changed in
987
+ * between (three attempts, then `SERIALIZATION_FAILURE`).
988
+ */
989
+ async change(operation, key, init, expected, send) {
990
+ if (expected !== void 0 && typeof expected !== "string") throw new ODataNotSupportedError(operation, this.entitySet.name, "A version number ($cas) cannot be checked by an OData service, which compares ETags: send the entity's version token", void 0, {
991
+ path: "$cas",
992
+ code: "CAS_NOT_SUPPORTED"
993
+ });
994
+ const { matched, modified } = await changeByKey(send, {
995
+ ...this.byKey(key, init),
996
+ ...expected === void 0 ? {} : { etag: expected }
997
+ });
998
+ return {
999
+ matchedCount: matched ? 1 : 0,
1000
+ modifiedCount: modified ? 1 : 0
1001
+ };
1002
+ }
1003
+ /**
1004
+ * The members of the complex value at `path`, from the table's stored fields
1005
+ * (`storedDescriptors`: no navigation property or part of one).
1006
+ */
1007
+ membersOf(path) {
1008
+ if (!this._members) {
1009
+ const members = /* @__PURE__ */ new Map();
1010
+ for (const fd of this._table.storedDescriptors) {
1011
+ const dot = fd.path.lastIndexOf(".");
1012
+ if (dot < 0) continue;
1013
+ const parent = fd.path.slice(0, dot);
1014
+ const list = members.get(parent) ?? [];
1015
+ list.push(fd.path.slice(dot + 1));
1016
+ members.set(parent, list);
1017
+ }
1018
+ this._members = members;
1019
+ }
1020
+ return this._members.get(path);
1021
+ }
1022
+ /** Runs an operation with the call options of the current request, and maps what it throws. */
1023
+ async call(run) {
1024
+ this.refuseGone();
1025
+ const init = await this.options.init?.() ?? {};
1026
+ try {
1027
+ return await run({
1028
+ ...init,
1029
+ read: {
1030
+ selectUnits: false,
1031
+ ...init.read
1032
+ }
1033
+ });
1034
+ } catch (error) {
1035
+ throw toDbError(error, this._set?.name ?? "", this.service.model);
1036
+ }
1037
+ }
1038
+ get context() {
1039
+ const { name, key, sortableKey } = this.entitySet;
1040
+ const context = {
1041
+ entitySet: name,
1042
+ unsortableKeys: key.filter((name) => !sortableKey.includes(name)),
1043
+ leaves: this.leaves
1044
+ };
1045
+ if (this.token) context.token = this.token;
1046
+ return context;
1047
+ }
1048
+ /**
1049
+ * The version token field of the table (`@db.column.version.token`, which the generator emits on
1050
+ * an entity set with optimistic concurrency); `undefined` when it has none.
1051
+ */
1052
+ get token() {
1053
+ return this._table.versionToken ? this._table.versionColumn : void 0;
1054
+ }
1055
+ /**
1056
+ * The rows of a read, each with its ETag as the version token, cut back to the selection, and
1057
+ * their related rows to theirs.
1058
+ */
1059
+ rowsOf(result, shape) {
1060
+ return shapeRows(this.withTokens(result.rows, result.etags ?? []), shape);
1061
+ }
1062
+ /** Puts each row's ETag into the version token field, when the table has one. */
1063
+ withTokens(rows, etags) {
1064
+ const { token } = this;
1065
+ if (!token) return rows;
1066
+ for (const [i, row] of rows.entries()) {
1067
+ const etag = etags[i];
1068
+ if (etag !== void 0) row[token] = etag;
1069
+ }
1070
+ return rows;
1071
+ }
1072
+ /**
1073
+ * The paths an exclusion projection is taken from: every stored field (`storedDescriptors`:
1074
+ * navigation properties are none) that holds no other field, a collection counting as one
1075
+ * field.
1076
+ */
1077
+ get leaves() {
1078
+ if (!this._leaves) {
1079
+ const stored = this._table.storedDescriptors;
1080
+ const collections = stored.filter((fd) => fd.designType === "array").map((fd) => fd.path);
1081
+ const paths = stored.map((fd) => fd.path).filter((path) => !under(path, collections));
1082
+ this._leaves = paths.filter((path) => collections.includes(path) || !paths.some((other) => other.startsWith(`${path}.`)));
1083
+ }
1084
+ return this._leaves;
1085
+ }
1086
+ /**
1087
+ * The read of a query, with the `$with` entries as expansions: each translated by the adapter
1088
+ * of its table (one of the same service, see {@link sharesStoreWith}), nested entries included.
1089
+ * Related rows keep their key at every depth, whatever their selection.
1090
+ */
1091
+ shapeOf(query) {
1092
+ return withRelations(readShapeOf(query, this.context), (query.controls.$with ?? []).map(({ nav, isArray, target, query: related }) => {
1093
+ const adapter = target.adapter;
1094
+ return {
1095
+ nav,
1096
+ isArray,
1097
+ shape: keepingKey(adapter.shapeOf(related), adapter.entitySet.key)
1098
+ };
1099
+ }));
1100
+ }
1101
+ /** What the table layer hands {@link aggregate}, as the engine's grouped read. */
1102
+ aggregateSpecOf(query) {
1103
+ const { controls } = query;
1104
+ const spec = {
1105
+ entitySet: this.entitySet.name,
1106
+ groupBy: [...controls.$groupBy ?? []],
1107
+ aggregates: (controls.$select?.aggregates ?? []).map((expr) => ({
1108
+ fn: expr.$fn,
1109
+ field: String(expr.$field),
1110
+ alias: resolveAlias(expr)
1111
+ }))
1112
+ };
1113
+ if (query.filter && Object.keys(query.filter).length > 0) spec.filter = query.filter;
1114
+ const having = controls.$having;
1115
+ if (having && Object.keys(having).length > 0) spec.having = having;
1116
+ const sort = Object.entries(controls.$sort ?? {});
1117
+ if (sort.length > 0) spec.orderBy = sort.map(([path, direction]) => direction === -1 ? {
1118
+ path,
1119
+ desc: true
1120
+ } : { path });
1121
+ if (typeof controls.$search === "string" && controls.$search !== "") spec.search = controls.$search;
1122
+ if (controls.$count) {
1123
+ spec.count = true;
1124
+ spec.top = 0;
1125
+ return spec;
1126
+ }
1127
+ if (typeof controls.$skip === "number" && controls.$skip > 0) spec.skip = controls.$skip;
1128
+ if (typeof controls.$limit === "number") spec.top = controls.$limit;
1129
+ return spec;
1130
+ }
1131
+ countSpecOf(query) {
1132
+ const spec = { entitySet: this.entitySet.name };
1133
+ if (query.filter && Object.keys(query.filter).length > 0) spec.filter = query.filter;
1134
+ return spec;
1135
+ }
1136
+ searchShapeOf(text, query, indexName) {
1137
+ if (indexName !== void 0 && indexName !== "DEFAULT") throw new DbError("INVALID_QUERY", [{
1138
+ path: "$index",
1139
+ message: searchIndexNotFoundMessage(indexName)
1140
+ }]);
1141
+ const shape = this.shapeOf(query);
1142
+ shape.spec.search = text;
1143
+ return shape;
1144
+ }
1145
+ async readWithCount(shape, init) {
1146
+ const result = await this.service.read({
1147
+ ...shape.spec,
1148
+ count: true
1149
+ }, init);
1150
+ return {
1151
+ data: this.rowsOf(result, shape),
1152
+ count: result.count ?? 0
1153
+ };
1154
+ }
1155
+ };
1156
+ //#endregion
1157
+ //#region src/sessions.ts
1158
+ /** How long an unused session is kept unless `ttl` says otherwise: 30 minutes. */
1159
+ const DEFAULT_SESSION_TTL = 30 * 6e4;
1160
+ /** How many sessions a space keeps unless `max` says otherwise. */
1161
+ const DEFAULT_MAX_SESSIONS = 1e3;
1162
+ /** Headers that are no credentials: they do not tell sessions apart. */
1163
+ const NOT_CREDENTIALS = new Set(["accept-language"]);
1164
+ function positive(value, fallback, name) {
1165
+ if (value === void 0) return fallback;
1166
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`createODataSpace: "sessions.${name}" must be a positive number`);
1167
+ return value;
1168
+ }
1169
+ /**
1170
+ * Gives each call the session of the credentials it sends: the cookies the service set for them
1171
+ * and the CSRF token bound to those cookies. The key is the SHA-256 of the call's headers (names
1172
+ * in lower case, sorted, values exact), `Accept-Language` left out; with no header, the one
1173
+ * session of the space's static credentials, or none when it has none either: such calls stay
1174
+ * stateless. A call that brings a session of its own keeps it. Bounded and expiring; a dropped
1175
+ * session is no error, the next call starts a new one.
1176
+ */
1177
+ function sessionKeeper(options, staticCredentials) {
1178
+ const ttl = positive(options.ttl, DEFAULT_SESSION_TTL, "ttl");
1179
+ const max = Math.floor(positive(options.max, 1e3, "max")) || 1;
1180
+ const entries = /* @__PURE__ */ new Map();
1181
+ const get = (key) => {
1182
+ const now = Date.now();
1183
+ for (const [known, entry] of entries) {
1184
+ if (now - entry.usedAt < ttl) break;
1185
+ entries.delete(known);
1186
+ }
1187
+ const entry = entries.get(key) ?? {
1188
+ session: createSession(),
1189
+ usedAt: now
1190
+ };
1191
+ entry.usedAt = now;
1192
+ entries.delete(key);
1193
+ entries.set(key, entry);
1194
+ while (entries.size > max) entries.delete(entries.keys().next().value);
1195
+ return entry.session;
1196
+ };
1197
+ return (init) => {
1198
+ if (init.session) return init;
1199
+ const credentials = Object.entries(init.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]).filter(([name]) => !NOT_CREDENTIALS.has(name)).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1200
+ if (credentials.length === 0 && !staticCredentials) return init;
1201
+ const key = createHash("sha256").update(JSON.stringify(credentials)).digest("hex");
1202
+ return {
1203
+ ...init,
1204
+ session: get(key)
1205
+ };
1206
+ };
1207
+ }
1208
+ //#endregion
1209
+ //#region src/space.ts
1210
+ const notConnected = () => /* @__PURE__ */ new Error("The OData space is not connected: call `await space.connect()` before `app.init()`");
1211
+ /**
1212
+ * A `DbSpace` over an OData service: its entity sets are its tables. A live space reads the
1213
+ * service's `$metadata` with {@link connect}, before the application's controllers are created.
1214
+ */
1215
+ var ODataSpace = class extends DbSpace {
1216
+ /** The live source; absent on a space over an engine at hand. */
1217
+ source;
1218
+ _connection;
1219
+ defaultInit;
1220
+ callInit;
1221
+ constructor(adapterFactory, options, from = {}) {
1222
+ super(adapterFactory, options);
1223
+ if (from.source) this.source = from.source;
1224
+ if (from.fixed) this._connection = {
1225
+ name: "",
1226
+ service: from.fixed,
1227
+ types: {},
1228
+ fast: true
1229
+ };
1230
+ this.defaultInit = from.connect;
1231
+ this.callInit = from.call;
1232
+ }
1233
+ /** The connection, once {@link connect} succeeded (from the start on a fixed space). */
1234
+ get connection() {
1235
+ return this._connection;
1236
+ }
1237
+ /** The engine of the connection. @throws Error before the space is connected. */
1238
+ get service() {
1239
+ if (!this._connection) throw notConnected();
1240
+ return this._connection.service;
1241
+ }
1242
+ /**
1243
+ * Reads the live `$metadata` and value-help documents, in the language the models were saved
1244
+ * in, and makes the generated types live (`createODataSource` of `@atscript/odata`): call it
1245
+ * once before `app.init()`, which creates the controllers and binds them to the tables. The
1246
+ * read is made with `init`, else with the space's own `init` (the credentials the server is
1247
+ * given). Resolves with the same connection ever after. What the live metadata changed against
1248
+ * the saved one is logged once as a warning: entity sets gone or allowing fewer writes,
1249
+ * properties added, removed or changed.
1250
+ *
1251
+ * @throws what reading `$metadata` throws: the `ODataError` of a refused or failed read, the
1252
+ * parser's `Error` for an answer that is no `$metadata` document.
1253
+ */
1254
+ async connect(init) {
1255
+ if (this._connection) return this._connection;
1256
+ const call = await (init ?? this.defaultInit)?.();
1257
+ this._connection = await this.source.connect(call && sendInit(call));
1258
+ return this._connection;
1259
+ }
1260
+ /**
1261
+ * Why an operation of the build is refused: its verdict when the live service no longer has it
1262
+ * (`gone`) or changed it so that the build's calls no longer fit (`incompatible`); `undefined`
1263
+ * when it fits. A live space holds the live service to the build: the verdicts are computed
1264
+ * once, on `connect()`, when the live `$metadata` differs from the saved one.
1265
+ */
1266
+ refusalOf(operation) {
1267
+ return refusalIn(this._connection, operation);
1268
+ }
1269
+ /**
1270
+ * Calls an operation of the service (`runOperation` of `@atscript/odata`), with the space's
1271
+ * credentials, the session it keeps for them and its language, as the tables' calls are made: an
1272
+ * unbound one, or a bound one with `entitySet` (a set's table calls its own with
1273
+ * `ODataAdapter.callOperation`). An operation the live service no longer fits is refused first
1274
+ * (see {@link refusalOf}); the parameters are validated against the live operation type (the
1275
+ * validator's `ValidatorError`). What the call throws, and the error of each row in `failed`, is
1276
+ * mapped as the adapter's `callOperation` maps it: a call that sends the caller's version token
1277
+ * (a call that writes, on a row with its `__etag`) refused with `412` is that row's version
1278
+ * mismatch, for the caller to answer (one row resolves `null`, a row of several is
1279
+ * `{ index, error: null }` in `failed`), a row the service has no entity for a `DbError`
1280
+ * `NOT_FOUND`, the rest as the tables' calls (`toDbError`).
1281
+ *
1282
+ * @throws Error before the space is connected.
1283
+ */
1284
+ async callOperation(input) {
1285
+ const connection = this._connection;
1286
+ if (!connection) throw notConnected();
1287
+ const init = sendInit(await this.callInit?.() ?? {});
1288
+ const { operation } = input;
1289
+ const entitySet = input.entitySet ?? (typeof operation === "string" ? void 0 : operation.entitySet) ?? "";
1290
+ return operationAnswer(runOperation(connection, input, init), input.rows, {
1291
+ token: sendsRowToken(connection, input) ? VERSION_TOKEN : void 0,
1292
+ entitySet,
1293
+ model: connection.service.model
1294
+ });
1295
+ }
1296
+ };
1297
+ /**
1298
+ * Creates a `DbSpace` over an OData service: `space.getTable(Type)` returns a table that reads the
1299
+ * entity set `Type` was generated from (or built from at runtime). A type of one of the service's
1300
+ * value-help services (`@odata.valueHelpService`) is read at that service's root, through
1301
+ * `service.valueHelpService(…)`, with the space's `init`.
1302
+ *
1303
+ * The generated types name the service as their `@db.space`: registered under that name with
1304
+ * moost-db's `provideDbSpace(space, "sales")`, the space serves model-token controllers
1305
+ * (`@TableController(sales.Order, …)`). Never run schema sync over it: the service owns its
1306
+ * schema.
1307
+ *
1308
+ * Live (`baseUrl`, `model`, `types`, …): the tables can be created at import (the controllers'
1309
+ * decorators); `connect()` reads the live `$metadata` before `app.init()`. The space holds the
1310
+ * live service to the build: an operation of the build the live service no longer fits is
1311
+ * refused (`refusalOf`, `callOperation`) and listed in the drift report. An entity set the live
1312
+ * service no longer has keeps its table, and every call of it throws a plain `Error` (the
1313
+ * server's build no longer fits the service: moost-db answers `500`); the OData controller bases
1314
+ * of `@atscript/moost-odata` answer every endpoint of such a table `404` instead.
1315
+ *
1316
+ * Every call of a table is made with the space's `init` (credentials, a time limit), with the
1317
+ * session the space keeps for the credentials it sends, and, when the models name the language
1318
+ * they were saved in, with that language as `Accept-Language` (unless `init` names one), so
1319
+ * labels and data texts come in one language.
1320
+ */
1321
+ function createODataSpace(options) {
1322
+ const { logger, onClose, sessions, init: own } = options;
1323
+ const space = {
1324
+ logger,
1325
+ onClose
1326
+ };
1327
+ if ("service" in options && options.service) {
1328
+ const keep = sessions === false ? void 0 : sessionKeeper(sessions ?? {}, false);
1329
+ const init = keep ? async () => keep(await own?.() ?? {}) : own;
1330
+ const fixed = options.service;
1331
+ let instance;
1332
+ const factory = () => new ODataAdapter(fixed, {
1333
+ ...init ? { init } : {},
1334
+ connection: () => instance?.connection
1335
+ });
1336
+ instance = new ODataSpace(factory, space, {
1337
+ fixed,
1338
+ connect: own,
1339
+ call: init
1340
+ });
1341
+ return instance;
1342
+ }
1343
+ const { logger: _logger, onClose: _onClose, sessions: _sessions, init: _init, onDrift, batch, ...sourceOptions } = options;
1344
+ const warn = (message) => logger ? logger.warn(message) : console.warn(message);
1345
+ const source = createODataSource({
1346
+ ...sourceOptions,
1347
+ batch: batch === false ? false : {
1348
+ ...batch,
1349
+ auto: false
1350
+ },
1351
+ onDrift: onDrift ?? ((_drift, message) => warn(message)),
1352
+ verdicts: true
1353
+ });
1354
+ const { language } = source;
1355
+ const keep = sessions === false ? void 0 : sessionKeeper(sessions ?? {}, !!sourceOptions.headers);
1356
+ const init = async () => {
1357
+ const call = withLocale(await own?.() ?? {}, language);
1358
+ return keep ? keep(call) : call;
1359
+ };
1360
+ let instance;
1361
+ const factory = () => new ODataAdapter(() => instance?.connection?.service, {
1362
+ init,
1363
+ ...sourceOptions.model ? { saved: sourceOptions.model } : {},
1364
+ connection: () => instance?.connection
1365
+ });
1366
+ instance = new ODataSpace(factory, space, {
1367
+ source,
1368
+ connect: own,
1369
+ call: init
1370
+ });
1371
+ return instance;
1372
+ }
1373
+ //#endregion
1374
+ export { DEFAULT_MAX_SESSIONS, DEFAULT_SESSION_TTL, ODATA_SEARCH_INDEX, ODataAdapter, ODataNotSupportedError, ODataSpace, createODataSpace, isODataNotSupportedError, toDbError };