@atscript/db-client 0.1.168 → 0.1.170

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 CHANGED
@@ -130,38 +130,6 @@ function clearMetaStore() {
130
130
  }
131
131
  //#endregion
132
132
  //#region src/client.ts
133
- /**
134
- * HTTP client for moost-db REST endpoints.
135
- *
136
- * Each method maps 1:1 to a controller endpoint:
137
- * - `query()` → `GET /query`
138
- * - `count()` → `GET /query` with `$count`
139
- * - `aggregate()` → `GET /query` with `$groupBy`
140
- * - `pages()` → `GET /pages`
141
- * - `one()` → `GET /one/:id` or `GET /one?compositeKeys`
142
- * - `insert()` → `POST /`
143
- * - `update()` → `PATCH /`
144
- * - `replace()` → `PUT /`
145
- * - `remove()` → `DELETE /:id` or `DELETE /?compositeKeys`
146
- * - `meta()` → `GET /meta`
147
- *
148
- * ```typescript
149
- * const users = new Client<typeof User>('/api/users')
150
- * const all = await users.query()
151
- * const page = await users.pages({ filter: { active: true } }, 1, 20)
152
- * ```
153
- *
154
- * `D` (since 0.1.148) types the display-only fields the controller declares
155
- * with `@DbDecorations`: `$select` of the read methods accepts their keys and
156
- * rows carry them as optional properties. Filter and sort stay over `T`'s own
157
- * fields — a decoration is never filterable or sortable.
158
- *
159
- * ```typescript
160
- * const tickets = new Client<typeof Ticket, TicketDecorations>('/api/tickets')
161
- * const rows = await tickets.query({ controls: { $select: ['title', 'ownerName'] } })
162
- * rows[0].ownerName // string | undefined
163
- * ```
164
- */
165
133
  var Client = class {
166
134
  _path;
167
135
  _baseUrl;
@@ -171,6 +139,9 @@ var Client = class {
171
139
  _lenientWrites;
172
140
  _metaStore;
173
141
  _metaKey;
142
+ _locale;
143
+ /** The locale {@link _metaPromise} (and the validator, forms) were loaded in. */
144
+ _metaLocale;
174
145
  _metaPromise;
175
146
  /** The `ETag` of the `/meta` body {@link _metaPromise} resolved to. */
176
147
  _metaEtag;
@@ -186,6 +157,7 @@ var Client = class {
186
157
  this._lenientWrites = opts?.lenientWrites;
187
158
  this._metaStore = opts?.metaStore === false ? void 0 : opts?.metaStore ?? defaultMetaStore;
188
159
  this._metaKey = opts?.metaKey;
160
+ this._locale = opts?.locale;
189
161
  }
190
162
  /**
191
163
  * `GET /query` — query records with typed filter, sort, select, and relations.
@@ -334,8 +306,9 @@ var Client = class {
334
306
  * as `If-None-Match`, and a `304 Not Modified` reuses the stored body.
335
307
  */
336
308
  async meta() {
309
+ const locale = this._syncLocale();
337
310
  if (!this._metaPromise) {
338
- const p = this._loadMeta().then(({ body, etag }) => {
311
+ const p = this._loadMeta(locale).then(({ body, etag }) => {
339
312
  if (this._metaPromise === p) this._metaEtag = etag;
340
313
  return body;
341
314
  }, (err) => {
@@ -525,15 +498,35 @@ var Client = class {
525
498
  * Cached per resolved URL.
526
499
  */
527
500
  async getActionForm(actionName) {
501
+ return (await this._actionForm(actionName))?.type ?? null;
502
+ }
503
+ /**
504
+ * The texts the action's form schema was served with in this client's
505
+ * locale (its `$i18n`: registered message templates and the translated
506
+ * literals of its expressions), or `undefined` when the server sent none
507
+ * or the action has no form. Read from the same cached response as
508
+ * {@link getActionForm}; merge them into your UI texts to show the form's
509
+ * expression results in the user's language.
510
+ *
511
+ * @since 0.1.170
512
+ */
513
+ async getActionFormTexts(actionName) {
514
+ return (await this._actionForm(actionName))?.texts;
515
+ }
516
+ async _actionForm(actionName) {
528
517
  const action = (await this.meta()).actions.find((a) => a.name === actionName);
529
518
  if (!action?.inputForm) return null;
530
519
  const url = action.formUrl ? `${this._baseUrl}${action.formUrl}` : this._endpointUrl(`meta/form/${encodeURIComponent(action.inputForm)}`);
531
520
  return this._loadActionForm(url);
532
521
  }
533
522
  _loadActionForm(url) {
523
+ this._syncLocale();
534
524
  let p = this._formCache.get(url);
535
525
  if (!p) {
536
- const loading = Promise.all([this._requestUrl("GET", url), import("@atscript/typescript/utils")]).then(([schema, { deserializeAnnotatedType }]) => deserializeAnnotatedType(schema)).catch((err) => {
526
+ const loading = Promise.all([this._requestUrl("GET", url), import("@atscript/typescript/utils")]).then(([schema, { deserializeAnnotatedType }]) => ({
527
+ type: deserializeAnnotatedType(schema),
528
+ texts: schema.$i18n
529
+ })).catch((err) => {
537
530
  if (this._formCache.get(url) === loading) this._formCache.delete(url);
538
531
  throw err;
539
532
  });
@@ -549,14 +542,15 @@ var Client = class {
549
542
  getValidator() {
550
543
  return this._getValidator();
551
544
  }
552
- /** Lifts `$cas` to the wire shape, then runs the preflight validator on the result. */
545
+ /** Lifts `$cas` to the wire shape, normalizes, then validates the result — which is what gets sent. */
553
546
  async _prepareWrite(data, mode) {
554
547
  const validator = await this._getValidator();
555
- const normalized = validator.liftCas(data, mode);
556
- validator.validate(normalized, mode);
557
- return normalized;
548
+ const prepared = validator.normalize(validator.liftCas(data, mode), mode);
549
+ validator.validate(prepared, mode);
550
+ return prepared;
558
551
  }
559
552
  _getValidator() {
553
+ this._syncLocale();
560
554
  if (!this._validatorPromise) {
561
555
  const p = Promise.all([this.meta(), Promise.resolve().then(() => require("./validator.cjs"))]).then(([m, { createClientValidator }]) => createClientValidator(m, { lenientWrites: this._lenientWrites })).catch((err) => {
562
556
  if (this._validatorPromise === p) this._validatorPromise = void 0;
@@ -638,31 +632,48 @@ var Client = class {
638
632
  const qs = query ? (0, _uniqu_url_builder.buildUrl)(query) : "";
639
633
  return this._request("GET", `${endpoint}${qs ? `?${qs}` : ""}`, void 0, { signal });
640
634
  }
641
- async _resolveHeaders() {
642
- if (!this._headers) return {};
643
- if (typeof this._headers === "function") return await this._headers();
644
- return this._headers;
635
+ async _resolveHeaders(locale = this._currentLocale()) {
636
+ const headers = !this._headers ? {} : typeof this._headers === "function" ? await this._headers() : this._headers;
637
+ if (locale === void 0 || hasHeader(headers, "accept-language")) return headers;
638
+ return {
639
+ ...headers,
640
+ "Accept-Language": locale
641
+ };
642
+ }
643
+ /** `ClientOptions.locale` now. */
644
+ _currentLocale() {
645
+ return typeof this._locale === "function" ? this._locale() : this._locale;
646
+ }
647
+ /** {@link _currentLocale}, after dropping the `/meta`, validator and forms loaded in another one. */
648
+ _syncLocale() {
649
+ const locale = this._currentLocale();
650
+ if (locale !== this._metaLocale) {
651
+ this.invalidateMeta();
652
+ this._metaLocale = locale;
653
+ }
654
+ return locale;
645
655
  }
646
656
  /**
647
657
  * `GET /meta` through the meta store: conditional when the store holds
648
658
  * bodies for this key, falling back to a plain request whenever the
649
659
  * conditional one cannot be answered from the store.
650
660
  */
651
- async _loadMeta() {
661
+ async _loadMeta(locale) {
652
662
  const url = this._endpointUrl("meta");
653
663
  const store = this._metaStore;
654
664
  if (!store) {
655
665
  const res = await this._fetchUrl(url, {
656
666
  method: "GET",
657
- headers: await this._resolveHeaders()
667
+ headers: await this._resolveHeaders(locale)
658
668
  });
659
669
  return {
660
670
  body: await this._readResponse(res, url, "GET", false),
661
671
  etag: res.ok ? readEtag(res) : void 0
662
672
  };
663
673
  }
664
- const key = this._metaKey ?? url;
665
- const headers = await this._resolveHeaders();
674
+ const base = this._metaKey ?? url;
675
+ const key = locale === void 0 ? base : `${base}#${locale}`;
676
+ const headers = await this._resolveHeaders(locale);
666
677
  const candidates = store._isUnconditional(key) ? [] : store.candidates(key);
667
678
  if (candidates.length > 0) {
668
679
  const init = {
@@ -787,6 +798,11 @@ var Client = class {
787
798
  }
788
799
  }
789
800
  };
801
+ /** Whether `headers` has `name` (lower case), in any letter case. */
802
+ function hasHeader(headers, name) {
803
+ for (const key in headers) if (key.toLowerCase() === name) return true;
804
+ return false;
805
+ }
790
806
  /**
791
807
  * The response's `ETag`, when readable — a cross-origin response hides it
792
808
  * unless the server sends `Access-Control-Expose-Headers: ETag`.
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as TDbInsertManyResult, A as DecoratedControls, B as OwnOf, C as CalendarBucketLabel, D as DbInsert, E as DataOf, F as InsertOf, G as RowOf, H as PatchOf, I as MetaResponse, J as StageRow, K as SearchIndexInfo, L as NavOf, M as FieldMeta, N as FilterExpr, O as DbPatch, P as IdOf, Q as TDbInsertManyIgnoreResult, R as NestedAggregateQuery, S as BucketUnit, T as ClientResponse, U as RelationInfo, V as PageResult, W as ResponseDataOf, X as TDbDeleteResult, Y as TClientCallOptions, Z as TDbInsertIgnoreResult, _ as AggregateQuery, at as UniqueryControls, b as AtscriptClientShape, c as ActionNotFoundError, ct as WeekStart, d as ActionUnsupportedError, dt as clearMetaStore, et as TDbInsertResult, f as ClientError, ft as defaultMetaStore, g as VersionMismatchErrorBody, h as VersionMismatchError, i as ValidatorMode, it as Uniquery, j as DecoratedQuery, k as DbRow, l as ActionTargetError, lt as MetaStore, m as TransportError, n as ClientValidatorOptions, nt as TDbUpdateResult, o as ActionDisabledError, ot as ValidGroupBy, p as ClientValidationError, q as ServerError, rt as TypedWithRelation, s as ActionDisabledErrorBody, st as ValidNested, t as ClientValidator, tt as TDbQueryTarget, u as ActionTargetErrorBody, ut as MetaStoreOptions, v as AggregateResult, w as ClientOptions, x as BucketExpr, y as AggregateStage, z as NestedAggregateResult } from "./validator-BfGRI3X9.cjs";
1
+ import { $ as TDbInsertManyResult, A as DecoratedControls, B as OwnOf, C as CalendarBucketLabel, D as DbInsert, E as DataOf, F as InsertOf, G as RowOf, H as PatchOf, I as MetaResponse, J as StageRow, K as SearchIndexInfo, L as NavOf, M as FieldMeta, N as FilterExpr, O as DbPatch, P as IdOf, Q as TDbInsertManyIgnoreResult, R as NestedAggregateQuery, S as BucketUnit, T as ClientResponse, U as RelationInfo, V as PageResult, W as ResponseDataOf, X as TDbDeleteResult, Y as TClientCallOptions, Z as TDbInsertIgnoreResult, _ as AggregateQuery, at as UniqueryControls, b as AtscriptClientShape, c as ActionNotFoundError, ct as WeekStart, d as ActionUnsupportedError, dt as clearMetaStore, et as TDbInsertResult, f as ClientError, ft as defaultMetaStore, g as VersionMismatchErrorBody, h as VersionMismatchError, i as ValidatorMode, it as Uniquery, j as DecoratedQuery, k as DbRow, l as ActionTargetError, lt as MetaStore, m as TransportError, n as ClientValidatorOptions, nt as TDbUpdateResult, o as ActionDisabledError, ot as ValidGroupBy, p as ClientValidationError, q as ServerError, rt as TypedWithRelation, s as ActionDisabledErrorBody, st as ValidNested, t as ClientValidator, tt as TDbQueryTarget, u as ActionTargetErrorBody, ut as MetaStoreOptions, v as AggregateResult, w as ClientOptions, x as BucketExpr, y as AggregateStage, z as NestedAggregateResult } from "./validator-CW__tbcp.cjs";
2
2
  import { AggregateQuery as AggregateQuery$1, AggregateResult as AggregateResult$1, BucketSeriesOptions, ComputedExpr, NestedAggregateQuery as NestedAggregateQuery$1, NestedAggregateResult as NestedAggregateResult$1, NextBucketOptions, Uniquery as Uniquery$1, ValidGroupBy as ValidGroupBy$1, ValidNested as ValidNested$1, bucketSeries, bucketStartInstant, nextBucketLabel } from "@uniqu/core";
3
3
  import { TAtscriptAnnotatedType, TSerializedAnnotatedType } from "@atscript/typescript/utils";
4
4
  import { TCrudOp, TCrudPermissions, TDbActionInfo, TDbActionInfo as TDbActionInfo$1, TDbActionIntent, TDbActionLevel, TDbActionProcessor, TDbActionTargetSummary, TDbActionTargetSummary as TDbActionTargetSummary$1, TDbAvailableActions, TDbAvailableActions as TDbAvailableActions$1, TDbDeleteResult as TDbDeleteResult$1, TDbInsertIgnoreResult as TDbInsertIgnoreResult$1, TDbInsertManyIgnoreResult as TDbInsertManyIgnoreResult$1, TDbInsertManyResult as TDbInsertManyResult$1, TDbInsertResult as TDbInsertResult$1, TDbUpdateResult as TDbUpdateResult$1 } from "@atscript/db";
@@ -29,38 +29,6 @@ type NestedShape = {
29
29
  type AggregateCheck<T, Q> = Q extends NestedShape ? ValidNested$1<T, Q> : ValidGroupBy$1<T, Q>;
30
30
  /** The rows `aggregate()` answers for query `Q`. */
31
31
  type AggregateRows<T, Q extends AggregateQuery$1<T> | NestedAggregateQuery$1<T>> = Q extends NestedShape ? NestedAggregateResult$1<T, Q>[] : Q["controls"]["$select"] extends readonly (string | ComputedExpr)[] ? AggregateResult$1<T, Q["controls"]["$select"]>[] : Record<string, unknown>[];
32
- /**
33
- * HTTP client for moost-db REST endpoints.
34
- *
35
- * Each method maps 1:1 to a controller endpoint:
36
- * - `query()` → `GET /query`
37
- * - `count()` → `GET /query` with `$count`
38
- * - `aggregate()` → `GET /query` with `$groupBy`
39
- * - `pages()` → `GET /pages`
40
- * - `one()` → `GET /one/:id` or `GET /one?compositeKeys`
41
- * - `insert()` → `POST /`
42
- * - `update()` → `PATCH /`
43
- * - `replace()` → `PUT /`
44
- * - `remove()` → `DELETE /:id` or `DELETE /?compositeKeys`
45
- * - `meta()` → `GET /meta`
46
- *
47
- * ```typescript
48
- * const users = new Client<typeof User>('/api/users')
49
- * const all = await users.query()
50
- * const page = await users.pages({ filter: { active: true } }, 1, 20)
51
- * ```
52
- *
53
- * `D` (since 0.1.148) types the display-only fields the controller declares
54
- * with `@DbDecorations`: `$select` of the read methods accepts their keys and
55
- * rows carry them as optional properties. Filter and sort stay over `T`'s own
56
- * fields — a decoration is never filterable or sortable.
57
- *
58
- * ```typescript
59
- * const tickets = new Client<typeof Ticket, TicketDecorations>('/api/tickets')
60
- * const rows = await tickets.query({ controls: { $select: ['title', 'ownerName'] } })
61
- * rows[0].ownerName // string | undefined
62
- * ```
63
- */
64
32
  declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D extends object = Record<never, never>> {
65
33
  private readonly _path;
66
34
  private readonly _baseUrl;
@@ -70,6 +38,9 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
70
38
  private readonly _lenientWrites?;
71
39
  private readonly _metaStore;
72
40
  private readonly _metaKey?;
41
+ private readonly _locale?;
42
+ /** The locale {@link _metaPromise} (and the validator, forms) were loaded in. */
43
+ private _metaLocale?;
73
44
  private _metaPromise?;
74
45
  /** The `ETag` of the `/meta` body {@link _metaPromise} resolved to. */
75
46
  private _metaEtag?;
@@ -362,13 +333,25 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
362
333
  * Cached per resolved URL.
363
334
  */
364
335
  getActionForm(actionName: string): Promise<TAtscriptAnnotatedType | null>;
336
+ /**
337
+ * The texts the action's form schema was served with in this client's
338
+ * locale (its `$i18n`: registered message templates and the translated
339
+ * literals of its expressions), or `undefined` when the server sent none
340
+ * or the action has no form. Read from the same cached response as
341
+ * {@link getActionForm}; merge them into your UI texts to show the form's
342
+ * expression results in the user's language.
343
+ *
344
+ * @since 0.1.170
345
+ */
346
+ getActionFormTexts(actionName: string): Promise<Record<string, string> | undefined>;
347
+ private _actionForm;
365
348
  private _loadActionForm;
366
349
  /**
367
350
  * Returns a lazily-initialized {@link ClientValidator} backed by the `/meta` type.
368
351
  * Useful for accessing `flatMap` and `navFields` (e.g. for form generation).
369
352
  */
370
353
  getValidator(): Promise<ClientValidator>;
371
- /** Lifts `$cas` to the wire shape, then runs the preflight validator on the result. */
354
+ /** Lifts `$cas` to the wire shape, normalizes, then validates the result — which is what gets sent. */
372
355
  private _prepareWrite;
373
356
  private _getValidator;
374
357
  private _buildActionBody;
@@ -385,6 +368,10 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
385
368
  private _getOrNull;
386
369
  private _get;
387
370
  private _resolveHeaders;
371
+ /** `ClientOptions.locale` now. */
372
+ private _currentLocale;
373
+ /** {@link _currentLocale}, after dropping the `/meta`, validator and forms loaded in another one. */
374
+ private _syncLocale;
388
375
  /**
389
376
  * `GET /meta` through the meta store: conditional when the store holds
390
377
  * bodies for this key, falling back to a plain request whenever the
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as TDbInsertManyResult, A as DecoratedControls, B as OwnOf, C as CalendarBucketLabel, D as DbInsert, E as DataOf, F as InsertOf, G as RowOf, H as PatchOf, I as MetaResponse, J as StageRow, K as SearchIndexInfo, L as NavOf, M as FieldMeta, N as FilterExpr, O as DbPatch, P as IdOf, Q as TDbInsertManyIgnoreResult, R as NestedAggregateQuery, S as BucketUnit, T as ClientResponse, U as RelationInfo, V as PageResult, W as ResponseDataOf, X as TDbDeleteResult, Y as TClientCallOptions, Z as TDbInsertIgnoreResult, _ as AggregateQuery, at as UniqueryControls, b as AtscriptClientShape, c as ActionNotFoundError, ct as WeekStart, d as ActionUnsupportedError, dt as clearMetaStore, et as TDbInsertResult, f as ClientError, ft as defaultMetaStore, g as VersionMismatchErrorBody, h as VersionMismatchError, i as ValidatorMode, it as Uniquery, j as DecoratedQuery, k as DbRow, l as ActionTargetError, lt as MetaStore, m as TransportError, n as ClientValidatorOptions, nt as TDbUpdateResult, o as ActionDisabledError, ot as ValidGroupBy, p as ClientValidationError, q as ServerError, rt as TypedWithRelation, s as ActionDisabledErrorBody, st as ValidNested, t as ClientValidator, tt as TDbQueryTarget, u as ActionTargetErrorBody, ut as MetaStoreOptions, v as AggregateResult, w as ClientOptions, x as BucketExpr, y as AggregateStage, z as NestedAggregateResult } from "./validator-DrRph1BQ.mjs";
1
+ import { $ as TDbInsertManyResult, A as DecoratedControls, B as OwnOf, C as CalendarBucketLabel, D as DbInsert, E as DataOf, F as InsertOf, G as RowOf, H as PatchOf, I as MetaResponse, J as StageRow, K as SearchIndexInfo, L as NavOf, M as FieldMeta, N as FilterExpr, O as DbPatch, P as IdOf, Q as TDbInsertManyIgnoreResult, R as NestedAggregateQuery, S as BucketUnit, T as ClientResponse, U as RelationInfo, V as PageResult, W as ResponseDataOf, X as TDbDeleteResult, Y as TClientCallOptions, Z as TDbInsertIgnoreResult, _ as AggregateQuery, at as UniqueryControls, b as AtscriptClientShape, c as ActionNotFoundError, ct as WeekStart, d as ActionUnsupportedError, dt as clearMetaStore, et as TDbInsertResult, f as ClientError, ft as defaultMetaStore, g as VersionMismatchErrorBody, h as VersionMismatchError, i as ValidatorMode, it as Uniquery, j as DecoratedQuery, k as DbRow, l as ActionTargetError, lt as MetaStore, m as TransportError, n as ClientValidatorOptions, nt as TDbUpdateResult, o as ActionDisabledError, ot as ValidGroupBy, p as ClientValidationError, q as ServerError, rt as TypedWithRelation, s as ActionDisabledErrorBody, st as ValidNested, t as ClientValidator, tt as TDbQueryTarget, u as ActionTargetErrorBody, ut as MetaStoreOptions, v as AggregateResult, w as ClientOptions, x as BucketExpr, y as AggregateStage, z as NestedAggregateResult } from "./validator-itAz8BNP.mjs";
2
2
  import { AggregateQuery as AggregateQuery$1, AggregateResult as AggregateResult$1, BucketSeriesOptions, ComputedExpr, NestedAggregateQuery as NestedAggregateQuery$1, NestedAggregateResult as NestedAggregateResult$1, NextBucketOptions, Uniquery as Uniquery$1, ValidGroupBy as ValidGroupBy$1, ValidNested as ValidNested$1, bucketSeries, bucketStartInstant, nextBucketLabel } from "@uniqu/core";
3
3
  import { TAtscriptAnnotatedType, TSerializedAnnotatedType } from "@atscript/typescript/utils";
4
4
  import { TCrudOp, TCrudPermissions, TDbActionInfo, TDbActionInfo as TDbActionInfo$1, TDbActionIntent, TDbActionLevel, TDbActionProcessor, TDbActionTargetSummary, TDbActionTargetSummary as TDbActionTargetSummary$1, TDbAvailableActions, TDbAvailableActions as TDbAvailableActions$1, TDbDeleteResult as TDbDeleteResult$1, TDbInsertIgnoreResult as TDbInsertIgnoreResult$1, TDbInsertManyIgnoreResult as TDbInsertManyIgnoreResult$1, TDbInsertManyResult as TDbInsertManyResult$1, TDbInsertResult as TDbInsertResult$1, TDbUpdateResult as TDbUpdateResult$1 } from "@atscript/db";
@@ -29,38 +29,6 @@ type NestedShape = {
29
29
  type AggregateCheck<T, Q> = Q extends NestedShape ? ValidNested$1<T, Q> : ValidGroupBy$1<T, Q>;
30
30
  /** The rows `aggregate()` answers for query `Q`. */
31
31
  type AggregateRows<T, Q extends AggregateQuery$1<T> | NestedAggregateQuery$1<T>> = Q extends NestedShape ? NestedAggregateResult$1<T, Q>[] : Q["controls"]["$select"] extends readonly (string | ComputedExpr)[] ? AggregateResult$1<T, Q["controls"]["$select"]>[] : Record<string, unknown>[];
32
- /**
33
- * HTTP client for moost-db REST endpoints.
34
- *
35
- * Each method maps 1:1 to a controller endpoint:
36
- * - `query()` → `GET /query`
37
- * - `count()` → `GET /query` with `$count`
38
- * - `aggregate()` → `GET /query` with `$groupBy`
39
- * - `pages()` → `GET /pages`
40
- * - `one()` → `GET /one/:id` or `GET /one?compositeKeys`
41
- * - `insert()` → `POST /`
42
- * - `update()` → `PATCH /`
43
- * - `replace()` → `PUT /`
44
- * - `remove()` → `DELETE /:id` or `DELETE /?compositeKeys`
45
- * - `meta()` → `GET /meta`
46
- *
47
- * ```typescript
48
- * const users = new Client<typeof User>('/api/users')
49
- * const all = await users.query()
50
- * const page = await users.pages({ filter: { active: true } }, 1, 20)
51
- * ```
52
- *
53
- * `D` (since 0.1.148) types the display-only fields the controller declares
54
- * with `@DbDecorations`: `$select` of the read methods accepts their keys and
55
- * rows carry them as optional properties. Filter and sort stay over `T`'s own
56
- * fields — a decoration is never filterable or sortable.
57
- *
58
- * ```typescript
59
- * const tickets = new Client<typeof Ticket, TicketDecorations>('/api/tickets')
60
- * const rows = await tickets.query({ controls: { $select: ['title', 'ownerName'] } })
61
- * rows[0].ownerName // string | undefined
62
- * ```
63
- */
64
32
  declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D extends object = Record<never, never>> {
65
33
  private readonly _path;
66
34
  private readonly _baseUrl;
@@ -70,6 +38,9 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
70
38
  private readonly _lenientWrites?;
71
39
  private readonly _metaStore;
72
40
  private readonly _metaKey?;
41
+ private readonly _locale?;
42
+ /** The locale {@link _metaPromise} (and the validator, forms) were loaded in. */
43
+ private _metaLocale?;
73
44
  private _metaPromise?;
74
45
  /** The `ETag` of the `/meta` body {@link _metaPromise} resolved to. */
75
46
  private _metaEtag?;
@@ -362,13 +333,25 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
362
333
  * Cached per resolved URL.
363
334
  */
364
335
  getActionForm(actionName: string): Promise<TAtscriptAnnotatedType | null>;
336
+ /**
337
+ * The texts the action's form schema was served with in this client's
338
+ * locale (its `$i18n`: registered message templates and the translated
339
+ * literals of its expressions), or `undefined` when the server sent none
340
+ * or the action has no form. Read from the same cached response as
341
+ * {@link getActionForm}; merge them into your UI texts to show the form's
342
+ * expression results in the user's language.
343
+ *
344
+ * @since 0.1.170
345
+ */
346
+ getActionFormTexts(actionName: string): Promise<Record<string, string> | undefined>;
347
+ private _actionForm;
365
348
  private _loadActionForm;
366
349
  /**
367
350
  * Returns a lazily-initialized {@link ClientValidator} backed by the `/meta` type.
368
351
  * Useful for accessing `flatMap` and `navFields` (e.g. for form generation).
369
352
  */
370
353
  getValidator(): Promise<ClientValidator>;
371
- /** Lifts `$cas` to the wire shape, then runs the preflight validator on the result. */
354
+ /** Lifts `$cas` to the wire shape, normalizes, then validates the result — which is what gets sent. */
372
355
  private _prepareWrite;
373
356
  private _getValidator;
374
357
  private _buildActionBody;
@@ -385,6 +368,10 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
385
368
  private _getOrNull;
386
369
  private _get;
387
370
  private _resolveHeaders;
371
+ /** `ClientOptions.locale` now. */
372
+ private _currentLocale;
373
+ /** {@link _currentLocale}, after dropping the `/meta`, validator and forms loaded in another one. */
374
+ private _syncLocale;
388
375
  /**
389
376
  * `GET /meta` through the meta store: conditional when the store holds
390
377
  * bodies for this key, falling back to a plain request whenever the
package/dist/index.mjs CHANGED
@@ -129,38 +129,6 @@ function clearMetaStore() {
129
129
  }
130
130
  //#endregion
131
131
  //#region src/client.ts
132
- /**
133
- * HTTP client for moost-db REST endpoints.
134
- *
135
- * Each method maps 1:1 to a controller endpoint:
136
- * - `query()` → `GET /query`
137
- * - `count()` → `GET /query` with `$count`
138
- * - `aggregate()` → `GET /query` with `$groupBy`
139
- * - `pages()` → `GET /pages`
140
- * - `one()` → `GET /one/:id` or `GET /one?compositeKeys`
141
- * - `insert()` → `POST /`
142
- * - `update()` → `PATCH /`
143
- * - `replace()` → `PUT /`
144
- * - `remove()` → `DELETE /:id` or `DELETE /?compositeKeys`
145
- * - `meta()` → `GET /meta`
146
- *
147
- * ```typescript
148
- * const users = new Client<typeof User>('/api/users')
149
- * const all = await users.query()
150
- * const page = await users.pages({ filter: { active: true } }, 1, 20)
151
- * ```
152
- *
153
- * `D` (since 0.1.148) types the display-only fields the controller declares
154
- * with `@DbDecorations`: `$select` of the read methods accepts their keys and
155
- * rows carry them as optional properties. Filter and sort stay over `T`'s own
156
- * fields — a decoration is never filterable or sortable.
157
- *
158
- * ```typescript
159
- * const tickets = new Client<typeof Ticket, TicketDecorations>('/api/tickets')
160
- * const rows = await tickets.query({ controls: { $select: ['title', 'ownerName'] } })
161
- * rows[0].ownerName // string | undefined
162
- * ```
163
- */
164
132
  var Client = class {
165
133
  _path;
166
134
  _baseUrl;
@@ -170,6 +138,9 @@ var Client = class {
170
138
  _lenientWrites;
171
139
  _metaStore;
172
140
  _metaKey;
141
+ _locale;
142
+ /** The locale {@link _metaPromise} (and the validator, forms) were loaded in. */
143
+ _metaLocale;
173
144
  _metaPromise;
174
145
  /** The `ETag` of the `/meta` body {@link _metaPromise} resolved to. */
175
146
  _metaEtag;
@@ -185,6 +156,7 @@ var Client = class {
185
156
  this._lenientWrites = opts?.lenientWrites;
186
157
  this._metaStore = opts?.metaStore === false ? void 0 : opts?.metaStore ?? defaultMetaStore;
187
158
  this._metaKey = opts?.metaKey;
159
+ this._locale = opts?.locale;
188
160
  }
189
161
  /**
190
162
  * `GET /query` — query records with typed filter, sort, select, and relations.
@@ -333,8 +305,9 @@ var Client = class {
333
305
  * as `If-None-Match`, and a `304 Not Modified` reuses the stored body.
334
306
  */
335
307
  async meta() {
308
+ const locale = this._syncLocale();
336
309
  if (!this._metaPromise) {
337
- const p = this._loadMeta().then(({ body, etag }) => {
310
+ const p = this._loadMeta(locale).then(({ body, etag }) => {
338
311
  if (this._metaPromise === p) this._metaEtag = etag;
339
312
  return body;
340
313
  }, (err) => {
@@ -524,15 +497,35 @@ var Client = class {
524
497
  * Cached per resolved URL.
525
498
  */
526
499
  async getActionForm(actionName) {
500
+ return (await this._actionForm(actionName))?.type ?? null;
501
+ }
502
+ /**
503
+ * The texts the action's form schema was served with in this client's
504
+ * locale (its `$i18n`: registered message templates and the translated
505
+ * literals of its expressions), or `undefined` when the server sent none
506
+ * or the action has no form. Read from the same cached response as
507
+ * {@link getActionForm}; merge them into your UI texts to show the form's
508
+ * expression results in the user's language.
509
+ *
510
+ * @since 0.1.170
511
+ */
512
+ async getActionFormTexts(actionName) {
513
+ return (await this._actionForm(actionName))?.texts;
514
+ }
515
+ async _actionForm(actionName) {
527
516
  const action = (await this.meta()).actions.find((a) => a.name === actionName);
528
517
  if (!action?.inputForm) return null;
529
518
  const url = action.formUrl ? `${this._baseUrl}${action.formUrl}` : this._endpointUrl(`meta/form/${encodeURIComponent(action.inputForm)}`);
530
519
  return this._loadActionForm(url);
531
520
  }
532
521
  _loadActionForm(url) {
522
+ this._syncLocale();
533
523
  let p = this._formCache.get(url);
534
524
  if (!p) {
535
- const loading = Promise.all([this._requestUrl("GET", url), import("@atscript/typescript/utils")]).then(([schema, { deserializeAnnotatedType }]) => deserializeAnnotatedType(schema)).catch((err) => {
525
+ const loading = Promise.all([this._requestUrl("GET", url), import("@atscript/typescript/utils")]).then(([schema, { deserializeAnnotatedType }]) => ({
526
+ type: deserializeAnnotatedType(schema),
527
+ texts: schema.$i18n
528
+ })).catch((err) => {
536
529
  if (this._formCache.get(url) === loading) this._formCache.delete(url);
537
530
  throw err;
538
531
  });
@@ -548,14 +541,15 @@ var Client = class {
548
541
  getValidator() {
549
542
  return this._getValidator();
550
543
  }
551
- /** Lifts `$cas` to the wire shape, then runs the preflight validator on the result. */
544
+ /** Lifts `$cas` to the wire shape, normalizes, then validates the result — which is what gets sent. */
552
545
  async _prepareWrite(data, mode) {
553
546
  const validator = await this._getValidator();
554
- const normalized = validator.liftCas(data, mode);
555
- validator.validate(normalized, mode);
556
- return normalized;
547
+ const prepared = validator.normalize(validator.liftCas(data, mode), mode);
548
+ validator.validate(prepared, mode);
549
+ return prepared;
557
550
  }
558
551
  _getValidator() {
552
+ this._syncLocale();
559
553
  if (!this._validatorPromise) {
560
554
  const p = Promise.all([this.meta(), import("./validator.mjs")]).then(([m, { createClientValidator }]) => createClientValidator(m, { lenientWrites: this._lenientWrites })).catch((err) => {
561
555
  if (this._validatorPromise === p) this._validatorPromise = void 0;
@@ -637,31 +631,48 @@ var Client = class {
637
631
  const qs = query ? buildUrl(query) : "";
638
632
  return this._request("GET", `${endpoint}${qs ? `?${qs}` : ""}`, void 0, { signal });
639
633
  }
640
- async _resolveHeaders() {
641
- if (!this._headers) return {};
642
- if (typeof this._headers === "function") return await this._headers();
643
- return this._headers;
634
+ async _resolveHeaders(locale = this._currentLocale()) {
635
+ const headers = !this._headers ? {} : typeof this._headers === "function" ? await this._headers() : this._headers;
636
+ if (locale === void 0 || hasHeader(headers, "accept-language")) return headers;
637
+ return {
638
+ ...headers,
639
+ "Accept-Language": locale
640
+ };
641
+ }
642
+ /** `ClientOptions.locale` now. */
643
+ _currentLocale() {
644
+ return typeof this._locale === "function" ? this._locale() : this._locale;
645
+ }
646
+ /** {@link _currentLocale}, after dropping the `/meta`, validator and forms loaded in another one. */
647
+ _syncLocale() {
648
+ const locale = this._currentLocale();
649
+ if (locale !== this._metaLocale) {
650
+ this.invalidateMeta();
651
+ this._metaLocale = locale;
652
+ }
653
+ return locale;
644
654
  }
645
655
  /**
646
656
  * `GET /meta` through the meta store: conditional when the store holds
647
657
  * bodies for this key, falling back to a plain request whenever the
648
658
  * conditional one cannot be answered from the store.
649
659
  */
650
- async _loadMeta() {
660
+ async _loadMeta(locale) {
651
661
  const url = this._endpointUrl("meta");
652
662
  const store = this._metaStore;
653
663
  if (!store) {
654
664
  const res = await this._fetchUrl(url, {
655
665
  method: "GET",
656
- headers: await this._resolveHeaders()
666
+ headers: await this._resolveHeaders(locale)
657
667
  });
658
668
  return {
659
669
  body: await this._readResponse(res, url, "GET", false),
660
670
  etag: res.ok ? readEtag(res) : void 0
661
671
  };
662
672
  }
663
- const key = this._metaKey ?? url;
664
- const headers = await this._resolveHeaders();
673
+ const base = this._metaKey ?? url;
674
+ const key = locale === void 0 ? base : `${base}#${locale}`;
675
+ const headers = await this._resolveHeaders(locale);
665
676
  const candidates = store._isUnconditional(key) ? [] : store.candidates(key);
666
677
  if (candidates.length > 0) {
667
678
  const init = {
@@ -786,6 +797,11 @@ var Client = class {
786
797
  }
787
798
  }
788
799
  };
800
+ /** Whether `headers` has `name` (lower case), in any letter case. */
801
+ function hasHeader(headers, name) {
802
+ for (const key in headers) if (key.toLowerCase() === name) return true;
803
+ return false;
804
+ }
789
805
  /**
790
806
  * The response's `ETag`, when readable — a cross-origin response hides it
791
807
  * unless the server sends `Access-Control-Expose-Headers: ETag`.
@@ -167,6 +167,20 @@ interface ClientOptions {
167
167
  * the body already loaded for another one.
168
168
  */
169
169
  metaKey?: string;
170
+ /**
171
+ * The locale to ask the server for (since 0.1.170): sent as
172
+ * `Accept-Language` on every request (unless `headers` carries one), so a
173
+ * server with a translator answers in that language — `/meta` texts, error
174
+ * messages and the templates (`/meta` `type.$i18n`) the preflight
175
+ * validator translates its errors with. A function is read per request.
176
+ *
177
+ * The cached `/meta`, the validator built from it and the loaded action
178
+ * forms belong to the locale they were loaded in: after a switch, the next
179
+ * call loads them again (revalidated through `metaStore`, which keeps one
180
+ * entry per locale — a switch back costs a `304`). Already-held results
181
+ * stay as they are: re-read them (in a UI, remount on a locale change).
182
+ */
183
+ locale?: string | (() => string | undefined);
170
184
  }
171
185
  /** Search index metadata from the server. */
172
186
  type SearchIndexInfo = TSearchIndexInfo;
@@ -360,10 +374,7 @@ declare class ClientValidationError extends ClientError {
360
374
  name: string;
361
375
  /** `true`: the request never left the client. */
362
376
  readonly preflight: true;
363
- constructor(errors: Array<{
364
- path: string;
365
- message: string;
366
- }>);
377
+ constructor(errors: ServerErrorEntry[]);
367
378
  }
368
379
  /**
369
380
  * Wire-body shape for `ActionDisabledError` responses (HTTP 409). Extends
@@ -532,6 +543,13 @@ interface ClientValidatorOptions {
532
543
  * (strict preflight catches typos).
533
544
  */
534
545
  lenientWrites?: boolean;
546
+ /**
547
+ * Message templates and texts to translate the preflight's errors with
548
+ * (since 0.1.170) — the served type's `$i18n` (`/meta` `type.$i18n`), which
549
+ * {@link createClientValidator} passes by default. Errors keep their
550
+ * `code` / `params`; ids missing from it keep the English message.
551
+ */
552
+ messages?: Readonly<Record<string, string>>;
535
553
  }
536
554
  /**
537
555
  * Client-side validator backed by an Atscript type from the `/meta` endpoint.
@@ -541,7 +559,9 @@ interface ClientValidatorOptions {
541
559
  declare class ClientValidator {
542
560
  private _type;
543
561
  private _validators;
562
+ private _options;
544
563
  private _lenientWrites;
564
+ private _translate?;
545
565
  /** Flat map of dotted field paths to their annotated types. */
546
566
  readonly flatMap: Map<string, TAtscriptAnnotatedType>;
547
567
  /** Set of field paths that are navigation relations (TO/FROM/VIA). */
@@ -561,12 +581,24 @@ declare class ClientValidator {
561
581
  */
562
582
  liftCas(data: unknown, mode: ValidatorMode): unknown;
563
583
  private _liftCasItem;
584
+ /**
585
+ * Applies the type's `@normalize.*` to write data (one item or an array)
586
+ * the way the server's write in `mode` does — patch operators and nested
587
+ * relation data included. Run it before {@link validate} and send its
588
+ * result. Pure and copy-on-change; never validates.
589
+ *
590
+ * @since 0.1.170
591
+ */
592
+ normalize(data: unknown, mode: ValidatorMode): unknown;
564
593
  /**
565
594
  * Validate data for a given write mode.
566
- * Throws `ClientValidationError` if validation fails.
595
+ * Throws `ClientValidationError` if validation fails. Validates `data` as
596
+ * given — run {@link normalize} first.
567
597
  */
568
598
  validate(data: unknown, mode: ValidatorMode): void;
569
599
  private _getValidator;
600
+ /** The options of `mode`'s validator — one object per mode (normalization judges with it too). */
601
+ private _getOptions;
570
602
  }
571
603
  /**
572
604
  * Create a {@link ClientValidator} from a meta response (or promise).
@@ -167,6 +167,20 @@ interface ClientOptions {
167
167
  * the body already loaded for another one.
168
168
  */
169
169
  metaKey?: string;
170
+ /**
171
+ * The locale to ask the server for (since 0.1.170): sent as
172
+ * `Accept-Language` on every request (unless `headers` carries one), so a
173
+ * server with a translator answers in that language — `/meta` texts, error
174
+ * messages and the templates (`/meta` `type.$i18n`) the preflight
175
+ * validator translates its errors with. A function is read per request.
176
+ *
177
+ * The cached `/meta`, the validator built from it and the loaded action
178
+ * forms belong to the locale they were loaded in: after a switch, the next
179
+ * call loads them again (revalidated through `metaStore`, which keeps one
180
+ * entry per locale — a switch back costs a `304`). Already-held results
181
+ * stay as they are: re-read them (in a UI, remount on a locale change).
182
+ */
183
+ locale?: string | (() => string | undefined);
170
184
  }
171
185
  /** Search index metadata from the server. */
172
186
  type SearchIndexInfo = TSearchIndexInfo;
@@ -360,10 +374,7 @@ declare class ClientValidationError extends ClientError {
360
374
  name: string;
361
375
  /** `true`: the request never left the client. */
362
376
  readonly preflight: true;
363
- constructor(errors: Array<{
364
- path: string;
365
- message: string;
366
- }>);
377
+ constructor(errors: ServerErrorEntry[]);
367
378
  }
368
379
  /**
369
380
  * Wire-body shape for `ActionDisabledError` responses (HTTP 409). Extends
@@ -532,6 +543,13 @@ interface ClientValidatorOptions {
532
543
  * (strict preflight catches typos).
533
544
  */
534
545
  lenientWrites?: boolean;
546
+ /**
547
+ * Message templates and texts to translate the preflight's errors with
548
+ * (since 0.1.170) — the served type's `$i18n` (`/meta` `type.$i18n`), which
549
+ * {@link createClientValidator} passes by default. Errors keep their
550
+ * `code` / `params`; ids missing from it keep the English message.
551
+ */
552
+ messages?: Readonly<Record<string, string>>;
535
553
  }
536
554
  /**
537
555
  * Client-side validator backed by an Atscript type from the `/meta` endpoint.
@@ -541,7 +559,9 @@ interface ClientValidatorOptions {
541
559
  declare class ClientValidator {
542
560
  private _type;
543
561
  private _validators;
562
+ private _options;
544
563
  private _lenientWrites;
564
+ private _translate?;
545
565
  /** Flat map of dotted field paths to their annotated types. */
546
566
  readonly flatMap: Map<string, TAtscriptAnnotatedType>;
547
567
  /** Set of field paths that are navigation relations (TO/FROM/VIA). */
@@ -561,12 +581,24 @@ declare class ClientValidator {
561
581
  */
562
582
  liftCas(data: unknown, mode: ValidatorMode): unknown;
563
583
  private _liftCasItem;
584
+ /**
585
+ * Applies the type's `@normalize.*` to write data (one item or an array)
586
+ * the way the server's write in `mode` does — patch operators and nested
587
+ * relation data included. Run it before {@link validate} and send its
588
+ * result. Pure and copy-on-change; never validates.
589
+ *
590
+ * @since 0.1.170
591
+ */
592
+ normalize(data: unknown, mode: ValidatorMode): unknown;
564
593
  /**
565
594
  * Validate data for a given write mode.
566
- * Throws `ClientValidationError` if validation fails.
595
+ * Throws `ClientValidationError` if validation fails. Validates `data` as
596
+ * given — run {@link normalize} first.
567
597
  */
568
598
  validate(data: unknown, mode: ValidatorMode): void;
569
599
  private _getValidator;
600
+ /** The options of `mode`'s validator — one object per mode (normalization judges with it too). */
601
+ private _getOptions;
570
602
  }
571
603
  /**
572
604
  * Create a {@link ClientValidator} from a meta response (or promise).
@@ -11,7 +11,9 @@ let _atscript_db_validator = require("@atscript/db/validator");
11
11
  var ClientValidator = class {
12
12
  _type;
13
13
  _validators = /* @__PURE__ */ new Map();
14
+ _options = /* @__PURE__ */ new Map();
14
15
  _lenientWrites;
16
+ _translate;
15
17
  /** Flat map of dotted field paths to their annotated types. */
16
18
  flatMap;
17
19
  /** Set of field paths that are navigation relations (TO/FROM/VIA). */
@@ -22,6 +24,7 @@ var ClientValidator = class {
22
24
  this._type = type;
23
25
  this._lenientWrites = opts?.lenientWrites === true;
24
26
  this.versionColumn = opts?.versionColumn;
27
+ if (opts?.messages) this._translate = (0, _atscript_typescript_utils.messagesTranslator)(opts.messages);
25
28
  const ctx = (0, _atscript_db_validator.buildValidationContext)(type);
26
29
  this.flatMap = ctx.flatMap;
27
30
  this.navFields = ctx.navFields;
@@ -52,17 +55,35 @@ var ClientValidator = class {
52
55
  try {
53
56
  (0, _atscript_db_validator.reconcileCas)(clone, this.versionColumn, "version");
54
57
  } catch (e) {
55
- if (e instanceof _atscript_db_validator.DbError) throw new require_client_error.ClientValidationError(e.errors.map((err) => ({
56
- path: `${prefix}${err.path}`,
57
- message: err.message
58
- })));
58
+ if (e instanceof _atscript_db_validator.DbError) throw new require_client_error.ClientValidationError(e.errors.map((err) => toEntry(err, `${prefix}${err.path}`)));
59
59
  throw e;
60
60
  }
61
61
  return clone;
62
62
  }
63
63
  /**
64
+ * Applies the type's `@normalize.*` to write data (one item or an array)
65
+ * the way the server's write in `mode` does — patch operators and nested
66
+ * relation data included. Run it before {@link validate} and send its
67
+ * result. Pure and copy-on-change; never validates.
68
+ *
69
+ * @since 0.1.170
70
+ */
71
+ normalize(data, mode) {
72
+ const opts = this._getOptions(mode);
73
+ if (Array.isArray(data)) {
74
+ let out;
75
+ for (let i = 0; i < data.length; i++) {
76
+ const next = (0, _atscript_db_validator.normalizeWritePayload)(this._type, data[i], mode, opts);
77
+ if (next !== data[i]) (out ??= data.slice())[i] = next;
78
+ }
79
+ return out ?? data;
80
+ }
81
+ return (0, _atscript_db_validator.normalizeWritePayload)(this._type, data, mode, opts);
82
+ }
83
+ /**
64
84
  * Validate data for a given write mode.
65
- * Throws `ClientValidationError` if validation fails.
85
+ * Throws `ClientValidationError` if validation fails. Validates `data` as
86
+ * given — run {@link normalize} first.
66
87
  */
67
88
  validate(data, mode) {
68
89
  const isArray = Array.isArray(data);
@@ -75,20 +96,26 @@ var ClientValidator = class {
75
96
  };
76
97
  for (let i = 0; i < items.length; i++) if (!validator.validate(items[i], true, ctx)) {
77
98
  const prefix = isArray ? `[${i}]` : "";
78
- throw new require_client_error.ClientValidationError(validator.errors.map((e) => ({
79
- path: prefix ? e.path ? `${prefix}.${e.path}` : prefix : e.path,
80
- message: e.message
81
- })));
99
+ throw new require_client_error.ClientValidationError((this._translate ? (0, _atscript_typescript_utils.localizeErrors)(validator.errors, this._translate) : validator.errors).map((err) => toEntry(err, prefix ? err.path ? `${prefix}.${err.path}` : prefix : err.path)));
82
100
  }
83
101
  }
84
102
  _getValidator(mode) {
85
103
  let v = this._validators.get(mode);
86
104
  if (!v) {
87
- v = (0, _atscript_db_validator.buildDbValidator)(this._type, mode, void 0, this._lenientWrites ? { unknownProps: "ignore" } : void 0);
105
+ v = this._type.validator(this._getOptions(mode));
88
106
  this._validators.set(mode, v);
89
107
  }
90
108
  return v;
91
109
  }
110
+ /** The options of `mode`'s validator — one object per mode (normalization judges with it too). */
111
+ _getOptions(mode) {
112
+ let opts = this._options.get(mode);
113
+ if (!opts) {
114
+ opts = (0, _atscript_db_validator.dbValidatorOptions)(this._type, mode, void 0, this._lenientWrites ? { unknownProps: "ignore" } : void 0);
115
+ this._options.set(mode, opts);
116
+ }
117
+ return opts;
118
+ }
92
119
  };
93
120
  /**
94
121
  * Create a {@link ClientValidator} from a meta response (or promise).
@@ -103,9 +130,20 @@ var ClientValidator = class {
103
130
  function createClientValidator(meta, opts) {
104
131
  return new ClientValidator((0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.type), {
105
132
  versionColumn: meta.versionColumn,
133
+ messages: meta.type.$i18n,
106
134
  ...opts
107
135
  });
108
136
  }
137
+ /** An error entry at `path`, keeping its `code` / `params` (never `details`). */
138
+ function toEntry({ message, code, params }, path) {
139
+ const entry = {
140
+ path,
141
+ message
142
+ };
143
+ if (code !== void 0) entry.code = code;
144
+ if (params !== void 0) entry.params = params;
145
+ return entry;
146
+ }
109
147
  //#endregion
110
148
  exports.ClientValidationError = require_client_error.ClientValidationError;
111
149
  exports.ClientValidator = ClientValidator;
@@ -1,2 +1,2 @@
1
- import { a as createClientValidator, i as ValidatorMode, n as ClientValidatorOptions, p as ClientValidationError, r as DbValidationContext, t as ClientValidator } from "./validator-BfGRI3X9.cjs";
1
+ import { a as createClientValidator, i as ValidatorMode, n as ClientValidatorOptions, p as ClientValidationError, r as DbValidationContext, t as ClientValidator } from "./validator-CW__tbcp.cjs";
2
2
  export { ClientValidationError, ClientValidator, ClientValidatorOptions, type DbValidationContext, type ValidatorMode, createClientValidator };
@@ -1,2 +1,2 @@
1
- import { a as createClientValidator, i as ValidatorMode, n as ClientValidatorOptions, p as ClientValidationError, r as DbValidationContext, t as ClientValidator } from "./validator-DrRph1BQ.mjs";
1
+ import { a as createClientValidator, i as ValidatorMode, n as ClientValidatorOptions, p as ClientValidationError, r as DbValidationContext, t as ClientValidator } from "./validator-itAz8BNP.mjs";
2
2
  export { ClientValidationError, ClientValidator, ClientValidatorOptions, type DbValidationContext, type ValidatorMode, createClientValidator };
@@ -1,6 +1,6 @@
1
1
  import { o as ClientValidationError } from "./client-error-Dn4WeNft.mjs";
2
- import { deserializeAnnotatedType } from "@atscript/typescript/utils";
3
- import { DbError, buildDbValidator, buildValidationContext, reconcileCas } from "@atscript/db/validator";
2
+ import { deserializeAnnotatedType, localizeErrors, messagesTranslator } from "@atscript/typescript/utils";
3
+ import { DbError, buildValidationContext, dbValidatorOptions, normalizeWritePayload, reconcileCas } from "@atscript/db/validator";
4
4
  //#region src/validator.ts
5
5
  /**
6
6
  * Client-side validator backed by an Atscript type from the `/meta` endpoint.
@@ -10,7 +10,9 @@ import { DbError, buildDbValidator, buildValidationContext, reconcileCas } from
10
10
  var ClientValidator = class {
11
11
  _type;
12
12
  _validators = /* @__PURE__ */ new Map();
13
+ _options = /* @__PURE__ */ new Map();
13
14
  _lenientWrites;
15
+ _translate;
14
16
  /** Flat map of dotted field paths to their annotated types. */
15
17
  flatMap;
16
18
  /** Set of field paths that are navigation relations (TO/FROM/VIA). */
@@ -21,6 +23,7 @@ var ClientValidator = class {
21
23
  this._type = type;
22
24
  this._lenientWrites = opts?.lenientWrites === true;
23
25
  this.versionColumn = opts?.versionColumn;
26
+ if (opts?.messages) this._translate = messagesTranslator(opts.messages);
24
27
  const ctx = buildValidationContext(type);
25
28
  this.flatMap = ctx.flatMap;
26
29
  this.navFields = ctx.navFields;
@@ -51,17 +54,35 @@ var ClientValidator = class {
51
54
  try {
52
55
  reconcileCas(clone, this.versionColumn, "version");
53
56
  } catch (e) {
54
- if (e instanceof DbError) throw new ClientValidationError(e.errors.map((err) => ({
55
- path: `${prefix}${err.path}`,
56
- message: err.message
57
- })));
57
+ if (e instanceof DbError) throw new ClientValidationError(e.errors.map((err) => toEntry(err, `${prefix}${err.path}`)));
58
58
  throw e;
59
59
  }
60
60
  return clone;
61
61
  }
62
62
  /**
63
+ * Applies the type's `@normalize.*` to write data (one item or an array)
64
+ * the way the server's write in `mode` does — patch operators and nested
65
+ * relation data included. Run it before {@link validate} and send its
66
+ * result. Pure and copy-on-change; never validates.
67
+ *
68
+ * @since 0.1.170
69
+ */
70
+ normalize(data, mode) {
71
+ const opts = this._getOptions(mode);
72
+ if (Array.isArray(data)) {
73
+ let out;
74
+ for (let i = 0; i < data.length; i++) {
75
+ const next = normalizeWritePayload(this._type, data[i], mode, opts);
76
+ if (next !== data[i]) (out ??= data.slice())[i] = next;
77
+ }
78
+ return out ?? data;
79
+ }
80
+ return normalizeWritePayload(this._type, data, mode, opts);
81
+ }
82
+ /**
63
83
  * Validate data for a given write mode.
64
- * Throws `ClientValidationError` if validation fails.
84
+ * Throws `ClientValidationError` if validation fails. Validates `data` as
85
+ * given — run {@link normalize} first.
65
86
  */
66
87
  validate(data, mode) {
67
88
  const isArray = Array.isArray(data);
@@ -74,20 +95,26 @@ var ClientValidator = class {
74
95
  };
75
96
  for (let i = 0; i < items.length; i++) if (!validator.validate(items[i], true, ctx)) {
76
97
  const prefix = isArray ? `[${i}]` : "";
77
- throw new ClientValidationError(validator.errors.map((e) => ({
78
- path: prefix ? e.path ? `${prefix}.${e.path}` : prefix : e.path,
79
- message: e.message
80
- })));
98
+ throw new ClientValidationError((this._translate ? localizeErrors(validator.errors, this._translate) : validator.errors).map((err) => toEntry(err, prefix ? err.path ? `${prefix}.${err.path}` : prefix : err.path)));
81
99
  }
82
100
  }
83
101
  _getValidator(mode) {
84
102
  let v = this._validators.get(mode);
85
103
  if (!v) {
86
- v = buildDbValidator(this._type, mode, void 0, this._lenientWrites ? { unknownProps: "ignore" } : void 0);
104
+ v = this._type.validator(this._getOptions(mode));
87
105
  this._validators.set(mode, v);
88
106
  }
89
107
  return v;
90
108
  }
109
+ /** The options of `mode`'s validator — one object per mode (normalization judges with it too). */
110
+ _getOptions(mode) {
111
+ let opts = this._options.get(mode);
112
+ if (!opts) {
113
+ opts = dbValidatorOptions(this._type, mode, void 0, this._lenientWrites ? { unknownProps: "ignore" } : void 0);
114
+ this._options.set(mode, opts);
115
+ }
116
+ return opts;
117
+ }
91
118
  };
92
119
  /**
93
120
  * Create a {@link ClientValidator} from a meta response (or promise).
@@ -102,8 +129,19 @@ var ClientValidator = class {
102
129
  function createClientValidator(meta, opts) {
103
130
  return new ClientValidator(deserializeAnnotatedType(meta.type), {
104
131
  versionColumn: meta.versionColumn,
132
+ messages: meta.type.$i18n,
105
133
  ...opts
106
134
  });
107
135
  }
136
+ /** An error entry at `path`, keeping its `code` / `params` (never `details`). */
137
+ function toEntry({ message, code, params }, path) {
138
+ const entry = {
139
+ path,
140
+ message
141
+ };
142
+ if (code !== void 0) entry.code = code;
143
+ if (params !== void 0) entry.params = params;
144
+ return entry;
145
+ }
108
146
  //#endregion
109
147
  export { ClientValidationError, ClientValidator, createClientValidator };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-client",
3
- "version": "0.1.168",
3
+ "version": "0.1.170",
4
4
  "description": "Browser-compatible HTTP client for @atscript/moost-db REST endpoints.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -43,18 +43,18 @@
43
43
  "access": "public"
44
44
  },
45
45
  "dependencies": {
46
- "@uniqu/core": "^0.2.0",
47
- "@uniqu/url": "^0.2.0"
46
+ "@uniqu/core": "^0.2.1",
47
+ "@uniqu/url": "^0.2.1"
48
48
  },
49
49
  "devDependencies": {
50
- "@atscript/core": "^0.2.4",
51
- "@atscript/typescript": "^0.2.4",
52
- "unplugin-atscript": "^0.2.4",
53
- "@atscript/db": "0.1.168"
50
+ "@atscript/core": "^0.2.7",
51
+ "@atscript/typescript": "^0.2.7",
52
+ "unplugin-atscript": "^0.2.7",
53
+ "@atscript/db": "0.1.170"
54
54
  },
55
55
  "peerDependencies": {
56
- "@atscript/typescript": "^0.2.4",
57
- "@atscript/db": "^0.1.168"
56
+ "@atscript/typescript": "^0.2.7",
57
+ "@atscript/db": "^0.1.170"
58
58
  },
59
59
  "scripts": {
60
60
  "build": "vp pack",