@atscript/odata-client 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,574 @@
1
+ import { AtscriptClientShape, ClientError, ClientLike, ClientOptions, MetaResponse, ServerError, TClientCallOptions, TDbActionInfo } from "@atscript/db-client";
2
+ import { ODataCallAnswer, ODataCallInit, ODataCallInput, ODataConnection, ODataMessageContext, ODataOperationConnection, ODataOperationRef, ODataService, ODataSourceOptions, ProtocolContext, ServiceModel } from "@atscript/odata";
3
+ import { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
4
+
5
+ //#region src/batch.d.ts
6
+ /**
7
+ * Calls of the OData clients of one registered service, grouped on purpose into one OData
8
+ * `$batch`, from `odata.createBatch()`. A client call joins it with `{ batch }` (a read, or a
9
+ * write in a changeset of its own) or `{ batch: changeset }` (a write in that changeset), and
10
+ * returns its usual promise, which settles once the batch is sent, as the call alone would; a
11
+ * write of a changeset the service refused rejects with the changeset's error (see
12
+ * {@link ODataClientChangeset}). The reads given a batch go before its writes (a write validates
13
+ * its payload first): do not read back a row written in the same batch.
14
+ */
15
+ interface ODataClientBatch {
16
+ /**
17
+ * A changeset of the batch: the writes given `{ batch: changeset }` are applied all or none. A
18
+ * changeset the service refuses rejects each of them with the one error it answered.
19
+ */
20
+ changeset(): ODataClientChangeset;
21
+ /**
22
+ * Waits until every call given the batch has queued its request (after its validation, its
23
+ * pre-read and the service's connection) or settled, then sends what was queued as one `$batch`
24
+ * (several when they hold more than `batch.maxParts` requests; nothing when no call queued one).
25
+ * Resolves, once every call has settled, with each call's outcome in the order the calls were
26
+ * made: what it resolved with, or its error.
27
+ *
28
+ * @throws Error when the batch has been sent already; so does a call given it once it has gone
29
+ * out.
30
+ */
31
+ send(): Promise<PromiseSettledResult<unknown>[]>;
32
+ }
33
+ /**
34
+ * A changeset of an {@link ODataClientBatch}, from `batch.changeset()`: its writes are applied all
35
+ * or none. When the service refuses it, nothing in it was applied, and every write in it rejects
36
+ * with the one error of the changeset, never read as the write's own answer: a `404` or `410` is
37
+ * `ClientError` 409 `CONFLICT` with the service's message (no write reads as `{ 0, 0 }` or
38
+ * `NOT_FOUND`), a `412` is 503 `SERIALIZATION_FAILURE` (a row changed since it was read: read the
39
+ * rows again and send the batch again; no write is sent again alone, none is a
40
+ * `VersionMismatchError`), any other status what the write alone would get. The engine's error,
41
+ * with its `changeset`, is the `cause`.
42
+ */
43
+ interface ODataClientChangeset {
44
+ /** The batch the changeset is sent with. */
45
+ readonly batch: ODataClientBatch;
46
+ }
47
+ /**
48
+ * The per-call options of an `ODataClient`'s read and write methods: db-client's
49
+ * `TClientCallOptions` and `batch`. A variable typed `ClientLike<T, D, ODataClientCallOptions>`
50
+ * takes them; a plain `ClientLike<T>` or `Client<T>` does not.
51
+ */
52
+ interface ODataClientCallOptions extends TClientCallOptions {
53
+ /**
54
+ * How the call goes out. Default: auto-batched with the calls of the same pass. `false` sends it
55
+ * alone. An {@link ODataClientBatch} queues it in that batch (a write in a changeset of its own),
56
+ * an {@link ODataClientChangeset} queues a write in that changeset.
57
+ */
58
+ batch?: ODataClientBatch | ODataClientChangeset | false;
59
+ }
60
+ //#endregion
61
+ //#region src/client.d.ts
62
+ /** Rows `query()` returns when the query sets no `$limit`, as moost-db's `/query` does. */
63
+ declare const DEFAULT_QUERY_LIMIT = 1000;
64
+ /** The engine and the type a client reads through, once they are known. */
65
+ interface ODataClientTarget {
66
+ service: ODataService;
67
+ type: TAtscriptAnnotatedType;
68
+ /** The service's operations, whose ones bound to the set's type are the client's actions. */
69
+ operations?: ODataOperationConnection;
70
+ }
71
+ interface ODataClientOptions {
72
+ /**
73
+ * The OData service the entity set belongs to. With `connect` instead, the service and the type
74
+ * are taken from what it resolves with, before the client's first call.
75
+ */
76
+ service?: ODataService;
77
+ /** Entity set name, as in the service model. */
78
+ entitySet: string;
79
+ /** The annotated type of the entity set: compiled from the generated `.as`, or built at runtime. */
80
+ type?: TAtscriptAnnotatedType;
81
+ /**
82
+ * With `service` and `type`: the service's operations, the connection of its live source (or
83
+ * anything with the engine, the operation types and, off the fast path, the plan). The
84
+ * operations bound to the set's type are the client's db actions. Without it the client has
85
+ * none. The client factory passes it.
86
+ */
87
+ operations?: ODataOperationConnection;
88
+ /**
89
+ * Resolves with the service and the type when they are not known yet (a live registration of
90
+ * the client factory, which reads the `$metadata` first). Asked before every call until it
91
+ * resolves; a rejection is the call's.
92
+ */
93
+ connect?: () => Promise<ODataClientTarget>;
94
+ /**
95
+ * The URL atscript-ui knows this entity set by. Nothing is fetched from it: it names the client
96
+ * in errors. Default: the type's `db.http.path`, else the entity set name.
97
+ */
98
+ url?: string;
99
+ /**
100
+ * Sent as `Accept-Language` with every OData call, so texts the service translates (text
101
+ * properties, error messages) come back in that language. A function is read per call. The
102
+ * metadata is not affected: its labels are those of the type.
103
+ */
104
+ locale?: string | (() => string | undefined);
105
+ /**
106
+ * Rows `query()` returns when the query sets no `$limit`. Default {@link DEFAULT_QUERY_LIMIT};
107
+ * `0` reads everything the service returns (within the service's `maxPages`).
108
+ */
109
+ queryLimit?: number;
110
+ /**
111
+ * Applied to every OData call of this client: session, headers, read option overrides. Without
112
+ * a `session` the calls are made with the one session the clients of the service share (see
113
+ * {@link ODataClient}): the service's own, else one per service, so a CSRF token is fetched once
114
+ * and reused.
115
+ */
116
+ call?: ODataCallInit;
117
+ }
118
+ /**
119
+ * A client for one entity set of an OData service that atscript-ui (or any code written against
120
+ * `@atscript/db-client`) uses like the `Client` of an atscript-db backend: the same methods, the
121
+ * same result shapes, the same error classes. It talks to the OData service through the
122
+ * `@atscript/odata` engine; no Atscript server is involved.
123
+ *
124
+ * It is a `ClientLike<T, D, ODataClientCallOptions>` of `@atscript/db-client` (every public member
125
+ * of `Client`, its methods taking {@link ODataClientCallOptions}), not a subclass: `instanceof
126
+ * Client` is false. atscript-ui's client factories return `ClientLike`, which takes it as it is.
127
+ *
128
+ * Works: `meta`, `query`, `count`, `pages`, `one`, `getValidator`, `metaEtag`, `invalidateMeta`,
129
+ * the writes `insert`, `update`, `replace`, `remove` where the service allows them, and
130
+ * `aggregate` where the service declares `$apply` (OData v4, `Aggregation.ApplySupported`):
131
+ * grouping, `sum` / `min` / `max` / `avg` (and `count(*)` / `countDistinct` on a non-SAP
132
+ * service), `$having`, sort, paging and `$count` of the groups. A grouped read the set cannot
133
+ * answer, geo search and query targets of actions (`actionOnQuery`, `countActionTarget`) reject
134
+ * with a `ClientError` (status 400, code `NOT_SUPPORTED`, as moost-db answers an adapter's
135
+ * `NOT_SUPPORTED`).
136
+ *
137
+ * Actions, with the `operations` of its service (the client factory passes them): the
138
+ * operations of the live service bound to the set's type are its db actions, as a Moost server's
139
+ * generated base declares them. `meta().actions` lists them (`rows` or `table`, the label of the
140
+ * live `<Name>Params` type, `inputForm` where it has parameters); `getActionForm` is that type;
141
+ * `action(name, ids, input)` validates the input against it and calls the operation (on rows: the
142
+ * rows' tokens read first where the call writes, each sent as `If-Match`; several rows go out as
143
+ * one `$batch` by the operation's grouping, answered as a Moost server answers them: moost-db's
144
+ * action target summary with the values). `availableActions(id)` and `$actions` on a read pass on the
145
+ * service's availability as hints; no call is refused by them. Without operations it declares no
146
+ * actions, as `Client` answers for such a backend.
147
+ *
148
+ * Writes, with the results `Client` gets from moost-db:
149
+ *
150
+ * - `insert(row)` creates the entity (`POST`) → `{ insertedId }`: the key value, or the key
151
+ * object for a composite key; with `returning: true` also `row`, the entity the service
152
+ * returned. `insert(rows)` sends them as one `$batch`, each row in a changeset of its own (one
153
+ * after the other with `batch: false`): not atomic, the rows after a failed one still run →
154
+ * `{ insertedCount, insertedIds }`; when rows failed, a `ClientError` as a Moost server answers
155
+ * it: the first failed row's status and code, every failed row's entries at that row (`[1].City`)
156
+ * and an `INSERTED` entry (`params.insertedId`) for each row created. An array of one row is one
157
+ * `POST`, its failure that of `insert(row)`, no row named.
158
+ * - `update(patch)` changes the members the patch names (`MERGE` on v2, `PATCH` on v4); the
159
+ * patch carries the key and the changes, as db-client sends it. `replace(row)` sends the whole
160
+ * entity (`PUT`). Both → `{ matchedCount, modifiedCount }`: `0, 0` for an entity that does not
161
+ * exist. Arrays are written one by one and summed.
162
+ * - `remove(id)` deletes one entity, by the key value or a key object → `{ deletedCount: 1 }`; an
163
+ * entity that does not exist is a `ClientError` 404 (`NOT_FOUND`), as moost-db answers it.
164
+ *
165
+ * Refused before any call: a write the entity set does not allow (400 `NOT_SUPPORTED`, as a
166
+ * Moost server answers it: the set is not insertable, updatable or deletable, or is
167
+ * draft-enabled), a payload the metadata's type rejects (`ClientValidationError`), and what OData
168
+ * cannot express (400): a `$cas` that is not the set's version token, array operators other than
169
+ * `$replace`, field operators, related entities in an update or replace, `onConflict: "ignore"`.
170
+ *
171
+ * Every call is made with a session (`call.session`, else the session the service was created
172
+ * with, else one per service), so the CSRF token is fetched once.
173
+ *
174
+ * Batching: the read and write methods take `batch` in their options
175
+ * ({@link ODataClientCallOptions}). Absent, the call is
176
+ * auto-batched with the calls of the same pass where the service's engine auto-batches (the
177
+ * factory's live registrations do); `false` sends it alone; a batch or changeset of the factory's
178
+ * `createBatch()` queues its request there (see `ODataClientBatch`). A call answers the same
179
+ * either way.
180
+ *
181
+ * On an entity set with optimistic concurrency every row read carries its ETag as the version
182
+ * token (`__etag`, `versionColumn` of the meta). An update or replace that carries it (the row as
183
+ * read, or `$cas`) sends it as `If-Match`, and a write that matches nothing is answered as moost-db
184
+ * answers it: a change made since the read is a `VersionMismatchError` with the entity's current
185
+ * token (`currentVersion`), a missing entity a 404; a row of an array counts `{ 0, 0 }`. Without
186
+ * it, an update, replace or remove is last-write-wins: the client reads the entity's current ETag
187
+ * right before the write and sends that, which only satisfies the service's If-Match requirement
188
+ * (it would answer `428` otherwise); a change in between has the ETag read and the write sent
189
+ * again, three attempts in all, then a `ClientError` 503 `SERIALIZATION_FAILURE`. An array write
190
+ * is not a transaction: when a row fails, the rows before it stay written (and, for an insert,
191
+ * the rows after it).
192
+ */
193
+ interface ODataClient<T extends AtscriptClientShape = AtscriptClientShape, D extends object = Record<never, never>> extends ClientLike<T, D, ODataClientCallOptions> {
194
+ readonly service: ODataService;
195
+ readonly entitySet: string;
196
+ readonly type: TAtscriptAnnotatedType;
197
+ /** The URL atscript-ui knows the entity set by. */
198
+ readonly url: string;
199
+ }
200
+ interface ODataClientConstructor {
201
+ new <T extends AtscriptClientShape = AtscriptClientShape, D extends object = Record<never, never>>(options: ODataClientOptions): ODataClient<T, D>;
202
+ readonly prototype: ODataClient;
203
+ }
204
+ declare const ODataClient: ODataClientConstructor;
205
+ //#endregion
206
+ //#region src/meta.d.ts
207
+ interface BuildMetaOptions {
208
+ /** The service model the entity set belongs to. */
209
+ model: ServiceModel;
210
+ /** Entity set name, as in `model.entitySets`. */
211
+ entitySet: string;
212
+ /** The annotated type of the entity set: compiled from the generated `.as`, or built at runtime. */
213
+ type: TAtscriptAnnotatedType;
214
+ /**
215
+ * OData version and dialect the capabilities are judged for: the service's `context`. Default:
216
+ * the model's version with the dialect a service gets from that model (`sap` for SAP Gateway
217
+ * and RAP metadata, `standard` otherwise).
218
+ */
219
+ context?: ProtocolContext;
220
+ /**
221
+ * The db actions of the entity set: the operations bound to its type, as a client lists them
222
+ * (`ODataClient` passes those of its live service). Default: none.
223
+ */
224
+ actions?: readonly TDbActionInfo[];
225
+ }
226
+ /**
227
+ * Builds the `/meta` response of an OData entity set: what `@atscript/moost-db` answers on
228
+ * `GET /meta` for a table, computed from the service model and the entity set's annotated type.
229
+ *
230
+ * - `type`: serialized by `serializeMetaType` of `@atscript/db/meta`, the code moost-db serves
231
+ * `/meta` with, so the two are byte-identical for the same type. A property the service
232
+ * computes (`Core.Computed`, v2 `sap:creatable` and `sap:updatable` false, a store-generated
233
+ * column) carries `@meta.readonly` and, when it is a scalar, `@db.default.store` from the
234
+ * generator: forms show it read-only, and they and the insert preflight let an insert leave it
235
+ * out although the type requires it (a key the service assigns).
236
+ * - `fields`: one entry per scalar or collection leaf of the type, nested objects flattened with
237
+ * `.`; navigations and nested-object parents are not listed. `sortable` / `filterable` are the
238
+ * entity set's capabilities. `filterOps` is present where a filterable field accepts less than
239
+ * every comparison (and patterns, for text): a filter restriction of the service, or text that
240
+ * is no `Edm.String` and therefore takes no `$regex`.
241
+ * - `primaryKeys` / `preferredId`: the entity key.
242
+ * - `relations`: the navigations the type carries and the service expands, each with the
243
+ * `direction` of its annotation: `to` / `from` over a foreign key, `store` for one without
244
+ * (`@db.rel.store`, which the generator emits where the service declares no usable foreign
245
+ * key). All of them are read through `$expand`.
246
+ * - `versionColumn`: the version token field (`@db.column.version.token`, the entity's ETag) of an
247
+ * entity set with optimistic concurrency; absent without one. atscript-ui keeps it out of the
248
+ * columns and forms, db-client's validator lifts it into `$cas`.
249
+ * - `crud`: the reads that work, with their controls, and the writes the service allows:
250
+ * `insert` (insertable), `update` and `replace` (updatable), `remove` (deletable), each `[]`.
251
+ * A set that is not addressable or is draft-enabled lists no write.
252
+ * - aggregation: `aggregateFns` lists the functions of the set's `$apply` (none without it),
253
+ * `groupable` marks the filterable single values of such a set, and `crud.query` takes
254
+ * `groupBy`; expressions, conditions, field lists and two-level aggregates are off.
255
+ * - search, vector and geo: `searchable` follows the entity set, the rest is off.
256
+ * - `actions`: the ones given (`options.actions`), else none.
257
+ *
258
+ * @throws Error when the model has no such entity set or the type is not an interface.
259
+ */
260
+ declare function buildMeta(options: BuildMetaOptions): MetaResponse;
261
+ //#endregion
262
+ //#region src/operations.d.ts
263
+ /** An operation named without its form: how `call` reaches one the build does not know. */
264
+ interface ODataOperationName {
265
+ /** The registered service (`@db.space`). */
266
+ service: string;
267
+ /** The name the engine calls it by: the import name, or for a v4 bound one the qualified name. */
268
+ operation: string;
269
+ /** A bound operation: the entity set it is called on. */
270
+ entitySet?: string;
271
+ }
272
+ /** The options of one `call` of the client factory. */
273
+ interface ODataOperationCallOptions {
274
+ /** Aborts the call. */
275
+ signal?: AbortSignal;
276
+ /** `false`: the call is not auto-batched with the calls of the same pass, it goes out alone. */
277
+ batch?: false;
278
+ /**
279
+ * Sent as `Accept-Language`, so the service's messages come in it, as the clients send the
280
+ * locale atscript-ui asks them for (unless the factory's `locale` is `"ignore"`, or its `call`
281
+ * headers name one).
282
+ */
283
+ locale?: string;
284
+ }
285
+ /** What an untyped call of an operation takes. */
286
+ interface ODataUntypedCallInput extends ODataCallInput<Record<string, unknown>, Record<string, unknown>> {
287
+ /** With a name, a bound operation: the entity set it is called on. */
288
+ entitySet?: string;
289
+ }
290
+ //#endregion
291
+ //#region src/factory.d.ts
292
+ /** The URL prefix OData entity sets are addressed under unless the factory is given another. */
293
+ declare const DEFAULT_ODATA_PREFIX = "/odata";
294
+ /**
295
+ * A service of the factory read live: its `$metadata` (and value-help documents) are read before
296
+ * the first call of any of its clients, and the generated module's classes are the live
297
+ * declarations from then on (see `createODataSource` of `@atscript/odata`):
298
+ *
299
+ * ```ts
300
+ * { baseUrl: "/sap/opu/odata/sap/ZSALES_SRV", query: { "sap-client": "100" }, model, types: sales }
301
+ * ```
302
+ *
303
+ * `name` defaults to the name the model module was generated with. Without `model` and `types`
304
+ * the types are built from the live document (runtime-only: no TypeScript types).
305
+ *
306
+ * The browser runs on whatever the live service has: it computes no drift report, holds no
307
+ * operation verdicts and logs nothing about a change; code that uses a property or an operation
308
+ * the live service dropped fails at runtime.
309
+ *
310
+ * Its calls are auto-batched (`batch.auto` of the service options, on here by default): the
311
+ * calls of one synchronous pass go out as one `$batch`, unless the service's `$metadata` says
312
+ * `Capabilities.BatchSupported` is false or the service answers a `$batch` `404`, `405` or `501`.
313
+ * `batch: false` turns it off for the service.
314
+ */
315
+ type LiveServiceRegistration = Omit<ODataSourceOptions, "onDrift" | "verdicts" | "batch"> & {
316
+ /**
317
+ * `$batch` settings: `maxParts` (default 100), `auto` (default `true`). `false`: no `$batch`
318
+ * unless one is asked for: every call goes out alone (unless it is given a batch of
319
+ * `createBatch()`), an action on several rows one call per row (refused when it is applied all
320
+ * or none, grouping `changeSet`), an array insert one create per row. The registration's
321
+ * services (its value-help services too) are created with the engine's `batch: false`, so its
322
+ * clients make no `$batch` of their own either. A call's own `{ batch: false }` sends that call
323
+ * alone.
324
+ */
325
+ batch?: false | ODataSourceOptions["batch"];
326
+ };
327
+ /**
328
+ * A service once read, as `connect()` resolves with it: the engine, the live types, `plan` and
329
+ * `fast` of the `ODataConnection` of `@atscript/odata`, and no drift report or verdicts.
330
+ */
331
+ type LiveServiceConnection = Omit<ODataConnection, "drift" | "refusals">;
332
+ /**
333
+ * A service whose engine and types are at hand, read from no `$metadata`: for tests and tools.
334
+ * An application registers its services live ({@link LiveServiceRegistration}).
335
+ */
336
+ interface FixedServiceRegistration {
337
+ /**
338
+ * The name of the service in URLs: `<prefix>/<name>/<EntitySet>`. Use the name the types were
339
+ * generated with (`@db.space`).
340
+ */
341
+ name: string;
342
+ service: ODataService;
343
+ /**
344
+ * The annotated types of the service's entity sets: the exports of the generated `.as` module
345
+ * (`import * as sales from "./sales.as"`), the `types` of `buildServiceTypes`, or its whole
346
+ * result. Entries that are not entity set types (`@db.table`) serve no URL; the operation types
347
+ * (`<Name>Params`) among them are the forms of the service's operations.
348
+ */
349
+ types: Record<string, unknown>;
350
+ }
351
+ /** One OData service a client factory serves. */
352
+ type ClientServiceRegistration = LiveServiceRegistration | FixedServiceRegistration;
353
+ /**
354
+ * The options atscript-ui passes to a client factory (its `ClientFactoryOptions`, restated so
355
+ * this package does not depend on `@atscript/ui`).
356
+ */
357
+ type ODataClientFactoryCallOptions = Pick<ClientOptions, "metaKey" | "metaStore"> & {
358
+ locale?: string;
359
+ };
360
+ interface ODataClientFactoryOptions {
361
+ services: ClientServiceRegistration[];
362
+ /** Default {@link DEFAULT_ODATA_PREFIX}. A trailing slash is ignored. */
363
+ prefix?: string;
364
+ /**
365
+ * Creates the client of every URL that is not an entity set of a registered service. Default:
366
+ * a plain `@atscript/db-client` `Client`, so one application mixes OData and atscript-db
367
+ * backends. Any `ClientLike` will do, as for atscript-ui's own factories.
368
+ */
369
+ fallback?: (url: string, options?: ODataClientFactoryCallOptions) => ClientLike;
370
+ /**
371
+ * What to do with the locale atscript-ui asks a client for: `accept-language` (default) sends
372
+ * it as `Accept-Language` with every OData call, `ignore` leaves the language to the service
373
+ * (its transport headers, `sap-language`, the logon language).
374
+ */
375
+ locale?: "accept-language" | "ignore";
376
+ /** For every client: see `ODataClientOptions.queryLimit`. */
377
+ queryLimit?: number;
378
+ /** For every client: see `ODataClientOptions.call`. */
379
+ call?: ODataCallInit;
380
+ }
381
+ /**
382
+ * A client factory for atscript-ui (`setDefaultClientFactory`, a table's `clientFactory`). Its
383
+ * clients take {@link ODataClientCallOptions}; a fallback client ignores `batch`.
384
+ */
385
+ interface ODataClientFactory {
386
+ (url: string, options?: ODataClientFactoryCallOptions): ClientLike<AtscriptClientShape, Record<never, never>, ODataClientCallOptions>;
387
+ /**
388
+ * The URL of an entity set of a registered service, or of one of its value-help services
389
+ * (`@odata.valueHelpService`), or `undefined` when it is not served. Before a live service is
390
+ * connected, the URL its entity set would have.
391
+ */
392
+ urlOf(service: string, entitySet: string, valueHelpService?: string): string | undefined;
393
+ /** The service and entity set a URL addresses, or `undefined` for a URL of the fallback. */
394
+ resolve(url: string): {
395
+ service: string;
396
+ entitySet: string;
397
+ valueHelpService?: string;
398
+ } | undefined;
399
+ /**
400
+ * Connects the live services (all, or the one named) now: reads their `$metadata` and makes
401
+ * the generated types live. Call it before the app mounts, so every type an app hands to
402
+ * Atscript UI is the live one; the clients would connect on their first call anyway. Resolves
403
+ * with the connections by service name.
404
+ *
405
+ * @throws what a client call throws for the same failure: `ClientError` when the service
406
+ * refuses the read (401 for a login page), `TransportError` when it cannot be reached or
407
+ * answers no `$metadata` document.
408
+ */
409
+ connect(service?: string): Promise<Record<string, LiveServiceConnection>>;
410
+ /**
411
+ * Calls an operation of a registered service, typed by its handle of the model module's `ops`:
412
+ * `call(ops.GetPrice, { params })`, on rows `call(ops.OrderSet.ReleaseOrder, { row, params })`
413
+ * (the row's key, and its `__etag` as read). The service is connected first. The operation is
414
+ * found in the live service by the handle's name and binding, and its parameters are validated
415
+ * against its live `<Name>Params` type: a handle of an operation the live service no longer has
416
+ * fails (`ClientError` 400, `UNKNOWN_OPERATION` on the entry). `extra` (OData v2 only) sends
417
+ * parameters the operation does not declare, untyped.
418
+ *
419
+ * Answers `{ value, message?, messages?, details? }`, `value` what the operation returned (for
420
+ * the row). Fails as the clients' calls fail: `ClientValidationError` for invalid parameters,
421
+ * before any call; on the row's own token, a `412` is a `VersionMismatchError` with the entity's
422
+ * current token (a 404 when it is gone); without one the ETag is read first (last-write-wins).
423
+ *
424
+ * Calls go with the factory's `call` defaults and the session the service's clients share;
425
+ * `opts.locale` is sent as `Accept-Language`, as the clients send atscript-ui's locale (the
426
+ * registration's `language` is the `$metadata`'s only).
427
+ */
428
+ call<P, R, K>(operation: ODataOperationRef<P, R, K>, input?: ODataCallInput<P, K>, opts?: ODataOperationCallOptions): Promise<ODataCallAnswer<R>>;
429
+ /**
430
+ * Calls an operation by its name, untyped: one the build does not know (only the live service
431
+ * has it) or one of a registration without a model. A name (`"Ns.release"` for a v4 bound
432
+ * operation, the import name otherwise) names an operation of the factory's only service, the
433
+ * entity set of a bound one in `input.entitySet`; with several services, pass
434
+ * `{ service, operation, entitySet? }`.
435
+ *
436
+ * @throws Error for a name when several services are registered, and for a service that is not.
437
+ */
438
+ call(operation: string | ODataOperationName, input?: ODataUntypedCallInput, opts?: ODataOperationCallOptions): Promise<ODataCallAnswer>;
439
+ /**
440
+ * A new batch of a registered service (the name may be left out when only one is registered):
441
+ * the calls of its clients given `{ batch }`, or `{ batch: batch.changeset() }` for writes
442
+ * applied all or none, go out as one `$batch` when `batch.send()` is called. Each call returns
443
+ * its usual promise, which settles as the call alone would. See {@link ODataClientBatch}.
444
+ *
445
+ * @throws Error without a name when several services are registered, and for a service that is
446
+ * not.
447
+ */
448
+ createBatch(service?: string): ODataClientBatch;
449
+ }
450
+ /**
451
+ * Creates the client factory atscript-ui routes through. A URL of the form
452
+ * `<prefix>/<serviceName>/<EntitySet>` gets a {@link ODataClient} for that entity set; every other
453
+ * URL goes to `fallback`.
454
+ *
455
+ * A live service ({@link LiveServiceRegistration}) is read on the first call of any of its
456
+ * clients, or by `connect()`: its `$metadata` and value-help documents, in the language the
457
+ * models were saved in, and its generated module's classes become the live declarations. Until
458
+ * then a URL of the service gets a client that connects first; an entity set the live service
459
+ * does not have answers every call with a `ClientError` 404 (`NOT_FOUND`), moost-db's body, as a
460
+ * Moost server answers it. A failed read is not kept: the next call reads again.
461
+ *
462
+ * Once a service's types are known, the factory writes each entity set's URL into its type as
463
+ * `db.http.path`. That is how atscript-ui finds the target of a foreign key or of a
464
+ * `@ui.valueHelp` binding, both in a served `/meta` type and in a compiled type used directly. A
465
+ * type can carry one URL only: a type object registered with a second factory under another
466
+ * prefix or service name is re-pointed to that one.
467
+ *
468
+ * The calls of a live service's clients are auto-batched: those of one synchronous pass go out as
469
+ * one `$batch` (see {@link LiveServiceRegistration}); `createBatch()` groups calls on purpose.
470
+ *
471
+ * The entity set types of the value-help services of a registered service (generated from its
472
+ * `Common.ValueListReferences` documents, `@odata.valueHelpService`) are registered with it: a
473
+ * URL `<prefix>/<serviceName>/<valueHelpService>/<EntitySet>` (each segment URI-encoded) gets a
474
+ * client that reads the set at the value-help service's root, through
475
+ * `service.valueHelpService(…)`, with the session of the registered service.
476
+ *
477
+ * @throws Error for a service registered twice, and for fixed types that do not belong to the
478
+ * service they are registered with.
479
+ */
480
+ declare function createODataClientFactory(options: ODataClientFactoryOptions): ODataClientFactory;
481
+ //#endregion
482
+ //#region src/errors.d.ts
483
+ /** One entry of a `ClientError` body's `errors` list. */
484
+ type ODataClientErrorEntry = NonNullable<ServerError["errors"]>[number];
485
+ /**
486
+ * The codes this package puts into a `ClientError` body by itself. A failure of the engine a
487
+ * Moost server answers with a `DbError` carries the code moost-db answers it with (`dbFailureOf`
488
+ * of `@atscript/odata`: `INVALID_QUERY`, `NOT_SUPPORTED`, `CONFLICT`); any other error the
489
+ * service answered carries the service's own code.
490
+ *
491
+ * - `NOT_SUPPORTED` (400): the client does not implement the operation yet, the entity set does
492
+ * not allow the write (`NOT_INSERTABLE`, …, of `writeRefusal`) or cannot answer the grouped
493
+ * read (the engine's `UNSUPPORTED_AGGREGATE`), or OData v2 cannot express the read
494
+ * (`UNSUPPORTED_ON_V2`: a filter or sort of a relation), as moost-db answers the core's
495
+ * `NOT_SUPPORTED`
496
+ * - `UNEXPECTED_CONTENT` (401): the service answered with an HTML page where data was asked for,
497
+ * or with a redirect where a write was sent (never followed), which is what a login or
498
+ * single-sign-on redirect leads to
499
+ * - `CAS_NOT_SUPPORTED` (on the entry of a 400 `NOT_SUPPORTED`): a write carries a `$cas` that is
500
+ * not the entity set's version token: an insert, an entity set that declares no optimistic
501
+ * concurrency, an integer version, or a `$cas` that differs from the token the row carries
502
+ * - `UNSUPPORTED_ARRAY_OPERATOR` (on the entry of a 400 `NOT_SUPPORTED`): a patch changes part
503
+ * of a collection (`$insert`, `$update`, `$upsert`, `$remove`); OData replaces a collection as a
504
+ * whole
505
+ * - `UNSUPPORTED_FIELD_OPERATOR` (on the entry of a 400 `NOT_SUPPORTED`): a patch computes a value
506
+ * (`$inc`, `$dec`, `$mul`)
507
+ * - `NOT_FOUND` (404): `remove` of an entity that does not exist, an update or replace with a
508
+ * version token of one, and every call of an entity set the live service no longer has, with
509
+ * moost-db's body (`notFoundError()`)
510
+ * - `VERSION_MISMATCH` (409, a `VersionMismatchError`): an update or replace with the caller's
511
+ * version token met a change (the service answered `412 Precondition Failed`), with moost-db's
512
+ * body: `kind: "version_mismatch"` and the entity's current token, read after the `412`
513
+ */
514
+ type ODataClientErrorCode = "NOT_SUPPORTED" | "UNEXPECTED_CONTENT" | "CAS_NOT_SUPPORTED" | "UNSUPPORTED_ARRAY_OPERATOR" | "UNSUPPORTED_FIELD_OPERATOR" | "NOT_FOUND" | "VERSION_MISMATCH";
515
+ /**
516
+ * What an error is about, for mapping service message targets to field paths: the core's message
517
+ * context (model, entity set, an operation's parameters) and the client's URL.
518
+ */
519
+ interface ODataClientErrorContext extends ODataMessageContext {
520
+ /** The URL the client is known by, named in a `TransportError` that has no request of its own. */
521
+ url?: string;
522
+ }
523
+ /** The error of an operation the client does not implement yet: `400`, `NOT_SUPPORTED`. */
524
+ declare function unsupportedOperation(operation: string, entitySet: string): ClientError;
525
+ /**
526
+ * Maps the target of a service message to a field path of the entity set: `@atscript/odata`'s
527
+ * `messagePath`, the rule both hosts use. `CompanyCode`, `/OrderSet('1')/NetAmount`,
528
+ * `Items(ItemNo='10')/Quantity` and `_it/Address/City` become `CompanyCode`, `NetAmount`,
529
+ * `Items.Quantity` and `Address.City`; a target that names no property of the entity type, and a
530
+ * pseudo target like `/#TRANSIENT#`, yield `""`.
531
+ */
532
+ declare function messagePath(target: string | undefined, context?: ODataClientErrorContext): string;
533
+ /**
534
+ * Turns what the OData engine throws into what `@atscript/db-client` throws, so an application
535
+ * handles both backends with one `instanceof ClientError` / `instanceof TransportError` branch.
536
+ * The error to throw is returned; an error that is already one of db-client's, and any error this
537
+ * package does not know, comes back unchanged.
538
+ *
539
+ * A failure a Moost server answers with a `DbError` (`dbFailureOf` of `@atscript/odata`, the one
540
+ * mapping both hosts use) is the `ClientError` a Moost server's answer becomes: the status
541
+ * moost-db answers the code with and its body (`message`, `statusCode`, `code`, `errors`). The
542
+ * engine's error is its `cause` (not enumerable, outside the body): what the service said behind
543
+ * a generic `STORE_*` message.
544
+ *
545
+ * | Thrown by the engine | Result |
546
+ * | -------------------------------------------------------------- | ------------------------------------------------------------------------- |
547
+ * | `ODataQueryError` `UNSUPPORTED_AGGREGATE`, `UNSUPPORTED_ON_V2` | `ClientError` 400, `NOT_SUPPORTED` |
548
+ * | `ODataWriteError` of `writeRefusal` (`NOT_INSERTABLE`, …) | `ClientError` 400, `NOT_SUPPORTED` |
549
+ * | `ODataQueryError` (other) | `ClientError` 400, `INVALID_QUERY`; `UNKNOWN_FIELD`, … on the entry |
550
+ * | `ODataWriteError` (other) | `ClientError` 400, `INVALID_QUERY`; the engine's code on the entry |
551
+ * | `ODataValueError` | `ClientError` 400, `INVALID_QUERY`, the property |
552
+ * | `ODataServiceError` `PAGE_LIMIT` | `ClientError` 400, `INVALID_QUERY` on `$limit` |
553
+ * | `ODataError` `400` | `ClientError` 400, `INVALID_QUERY`, the service's messages by field |
554
+ * | `ODataError` `409` | `ClientError` 409, `CONFLICT`, as for `400` |
555
+ * | `ODataError` `501` | `ClientError` 400, `NOT_SUPPORTED`, the service's messages by field |
556
+ * | `ODataError` `412` (the last attempt of a last-write-wins write) | `ClientError` 503, `SERIALIZATION_FAILURE` |
557
+ * | `ODataError` `429` | `ClientError` 429, `STORE_THROTTLED`, `params.retryAfter` on the entry |
558
+ * | `ODataError` `504` | `ClientError` 504, `STORE_TIMEOUT` |
559
+ * | `ODataError` `5xx` (other than `501`) | `ClientError` 502, `STORE_FAILED` |
560
+ * | `ODataError` `http` / `csrf` (other) | `ClientError` with the HTTP status, the service's code and messages |
561
+ * | `ODataError` `unexpected-content`, an HTML page or a redirect | `ClientError` 401, `UNEXPECTED_CONTENT` |
562
+ * | `ODataError` `unexpected-content`, otherwise | `TransportError`: a `2xx` answer that cannot be read |
563
+ * | `ODataError` `network` / `aborted` | `TransportError` (`aborted` is `true` for an aborted call) |
564
+ * | `ODataServiceError` (other), an unreadable body | `TransportError`: the service answered, the answer is not usable |
565
+ * | `ValidatorError` (an operation's parameters, `runOperation`) | `ClientValidationError` (400): the validator's entries, nothing sent |
566
+ *
567
+ * The browser calls the service with the user's own session: a `401` or `403` is the user's, and
568
+ * reaches the caller as it is (a Moost server answers its own credentials' refusal `502`). The
569
+ * failures a write maps by itself (a version mismatch of the caller's token, a missing entity) are
570
+ * the client's business, not this function's.
571
+ */
572
+ declare function toClientError(error: unknown, context?: ODataClientErrorContext): unknown;
573
+ //#endregion
574
+ export { type BuildMetaOptions, type ClientServiceRegistration, DEFAULT_ODATA_PREFIX, DEFAULT_QUERY_LIMIT, type FixedServiceRegistration, type LiveServiceConnection, type LiveServiceRegistration, ODataClient, type ODataClientBatch, type ODataClientCallOptions, type ODataClientChangeset, type ODataClientConstructor, type ODataClientErrorCode, type ODataClientErrorContext, type ODataClientErrorEntry, type ODataClientFactory, type ODataClientFactoryCallOptions, type ODataClientFactoryOptions, type ODataClientOptions, type ODataClientTarget, type ODataOperationCallOptions, type ODataOperationName, type ODataUntypedCallInput, buildMeta, createODataClientFactory, messagePath, toClientError, unsupportedOperation };