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