@atscript/db-client 0.1.169 → 0.1.171
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 +63 -15
- package/dist/index.d.cts +22 -3
- package/dist/index.d.mts +22 -3
- package/dist/index.mjs +63 -15
- package/dist/{validator-BfGRI3X9.d.cts → validator-CW__tbcp.d.cts} +37 -5
- package/dist/{validator-DrRph1BQ.d.mts → validator-itAz8BNP.d.mts} +37 -5
- package/dist/validator.cjs +48 -10
- package/dist/validator.d.cts +1 -1
- package/dist/validator.d.mts +1 -1
- package/dist/validator.mjs +50 -12
- package/package.json +9 -9
package/dist/index.cjs
CHANGED
|
@@ -171,11 +171,14 @@ var Client = class {
|
|
|
171
171
|
_lenientWrites;
|
|
172
172
|
_metaStore;
|
|
173
173
|
_metaKey;
|
|
174
|
+
_locale;
|
|
175
|
+
/** The locale {@link _metaPromise} (and the validator, forms) were loaded in. */
|
|
176
|
+
_metaLocale;
|
|
174
177
|
_metaPromise;
|
|
175
178
|
/** The `ETag` of the `/meta` body {@link _metaPromise} resolved to. */
|
|
176
179
|
_metaEtag;
|
|
177
180
|
_validatorPromise;
|
|
178
|
-
/**
|
|
181
|
+
/** Loaded action forms (type + served `$i18n`) keyed by resolved URL. */
|
|
179
182
|
_formCache = /* @__PURE__ */ new Map();
|
|
180
183
|
constructor(path, opts) {
|
|
181
184
|
this._path = path.endsWith("/") ? path.slice(0, -1) : path;
|
|
@@ -186,6 +189,7 @@ var Client = class {
|
|
|
186
189
|
this._lenientWrites = opts?.lenientWrites;
|
|
187
190
|
this._metaStore = opts?.metaStore === false ? void 0 : opts?.metaStore ?? defaultMetaStore;
|
|
188
191
|
this._metaKey = opts?.metaKey;
|
|
192
|
+
this._locale = opts?.locale;
|
|
189
193
|
}
|
|
190
194
|
/**
|
|
191
195
|
* `GET /query` — query records with typed filter, sort, select, and relations.
|
|
@@ -334,8 +338,9 @@ var Client = class {
|
|
|
334
338
|
* as `If-None-Match`, and a `304 Not Modified` reuses the stored body.
|
|
335
339
|
*/
|
|
336
340
|
async meta() {
|
|
341
|
+
const locale = this._syncLocale();
|
|
337
342
|
if (!this._metaPromise) {
|
|
338
|
-
const p = this._loadMeta().then(({ body, etag }) => {
|
|
343
|
+
const p = this._loadMeta(locale).then(({ body, etag }) => {
|
|
339
344
|
if (this._metaPromise === p) this._metaEtag = etag;
|
|
340
345
|
return body;
|
|
341
346
|
}, (err) => {
|
|
@@ -525,15 +530,35 @@ var Client = class {
|
|
|
525
530
|
* Cached per resolved URL.
|
|
526
531
|
*/
|
|
527
532
|
async getActionForm(actionName) {
|
|
533
|
+
return (await this._actionForm(actionName))?.type ?? null;
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* The texts the action's form schema was served with in this client's
|
|
537
|
+
* locale (its `$i18n`: registered message templates and the translated
|
|
538
|
+
* literals of its expressions), or `undefined` when the server sent none
|
|
539
|
+
* or the action has no form. Read from the same cached response as
|
|
540
|
+
* {@link getActionForm}; merge them into your UI texts to show the form's
|
|
541
|
+
* expression results in the user's language.
|
|
542
|
+
*
|
|
543
|
+
* @since 0.1.170
|
|
544
|
+
*/
|
|
545
|
+
async getActionFormTexts(actionName) {
|
|
546
|
+
return (await this._actionForm(actionName))?.texts;
|
|
547
|
+
}
|
|
548
|
+
async _actionForm(actionName) {
|
|
528
549
|
const action = (await this.meta()).actions.find((a) => a.name === actionName);
|
|
529
550
|
if (!action?.inputForm) return null;
|
|
530
551
|
const url = action.formUrl ? `${this._baseUrl}${action.formUrl}` : this._endpointUrl(`meta/form/${encodeURIComponent(action.inputForm)}`);
|
|
531
552
|
return this._loadActionForm(url);
|
|
532
553
|
}
|
|
533
554
|
_loadActionForm(url) {
|
|
555
|
+
this._syncLocale();
|
|
534
556
|
let p = this._formCache.get(url);
|
|
535
557
|
if (!p) {
|
|
536
|
-
const loading = Promise.all([this._requestUrl("GET", url), import("@atscript/typescript/utils")]).then(([schema, { deserializeAnnotatedType }]) =>
|
|
558
|
+
const loading = Promise.all([this._requestUrl("GET", url), import("@atscript/typescript/utils")]).then(([schema, { deserializeAnnotatedType }]) => ({
|
|
559
|
+
type: deserializeAnnotatedType(schema),
|
|
560
|
+
texts: schema.$i18n
|
|
561
|
+
})).catch((err) => {
|
|
537
562
|
if (this._formCache.get(url) === loading) this._formCache.delete(url);
|
|
538
563
|
throw err;
|
|
539
564
|
});
|
|
@@ -549,14 +574,15 @@ var Client = class {
|
|
|
549
574
|
getValidator() {
|
|
550
575
|
return this._getValidator();
|
|
551
576
|
}
|
|
552
|
-
/** Lifts `$cas` to the wire shape, then
|
|
577
|
+
/** Lifts `$cas` to the wire shape, normalizes, then validates the result — which is what gets sent. */
|
|
553
578
|
async _prepareWrite(data, mode) {
|
|
554
579
|
const validator = await this._getValidator();
|
|
555
|
-
const
|
|
556
|
-
validator.validate(
|
|
557
|
-
return
|
|
580
|
+
const prepared = validator.normalize(validator.liftCas(data, mode), mode);
|
|
581
|
+
validator.validate(prepared, mode);
|
|
582
|
+
return prepared;
|
|
558
583
|
}
|
|
559
584
|
_getValidator() {
|
|
585
|
+
this._syncLocale();
|
|
560
586
|
if (!this._validatorPromise) {
|
|
561
587
|
const p = Promise.all([this.meta(), Promise.resolve().then(() => require("./validator.cjs"))]).then(([m, { createClientValidator }]) => createClientValidator(m, { lenientWrites: this._lenientWrites })).catch((err) => {
|
|
562
588
|
if (this._validatorPromise === p) this._validatorPromise = void 0;
|
|
@@ -638,31 +664,48 @@ var Client = class {
|
|
|
638
664
|
const qs = query ? (0, _uniqu_url_builder.buildUrl)(query) : "";
|
|
639
665
|
return this._request("GET", `${endpoint}${qs ? `?${qs}` : ""}`, void 0, { signal });
|
|
640
666
|
}
|
|
641
|
-
async _resolveHeaders() {
|
|
642
|
-
|
|
643
|
-
if (
|
|
644
|
-
return
|
|
667
|
+
async _resolveHeaders(locale = this._currentLocale()) {
|
|
668
|
+
const headers = !this._headers ? {} : typeof this._headers === "function" ? await this._headers() : this._headers;
|
|
669
|
+
if (locale === void 0 || hasHeader(headers, "accept-language")) return headers;
|
|
670
|
+
return {
|
|
671
|
+
...headers,
|
|
672
|
+
"Accept-Language": locale
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
/** `ClientOptions.locale` now. */
|
|
676
|
+
_currentLocale() {
|
|
677
|
+
return typeof this._locale === "function" ? this._locale() : this._locale;
|
|
678
|
+
}
|
|
679
|
+
/** {@link _currentLocale}, after dropping the `/meta`, validator and forms loaded in another one. */
|
|
680
|
+
_syncLocale() {
|
|
681
|
+
const locale = this._currentLocale();
|
|
682
|
+
if (locale !== this._metaLocale) {
|
|
683
|
+
this.invalidateMeta();
|
|
684
|
+
this._metaLocale = locale;
|
|
685
|
+
}
|
|
686
|
+
return locale;
|
|
645
687
|
}
|
|
646
688
|
/**
|
|
647
689
|
* `GET /meta` through the meta store: conditional when the store holds
|
|
648
690
|
* bodies for this key, falling back to a plain request whenever the
|
|
649
691
|
* conditional one cannot be answered from the store.
|
|
650
692
|
*/
|
|
651
|
-
async _loadMeta() {
|
|
693
|
+
async _loadMeta(locale) {
|
|
652
694
|
const url = this._endpointUrl("meta");
|
|
653
695
|
const store = this._metaStore;
|
|
654
696
|
if (!store) {
|
|
655
697
|
const res = await this._fetchUrl(url, {
|
|
656
698
|
method: "GET",
|
|
657
|
-
headers: await this._resolveHeaders()
|
|
699
|
+
headers: await this._resolveHeaders(locale)
|
|
658
700
|
});
|
|
659
701
|
return {
|
|
660
702
|
body: await this._readResponse(res, url, "GET", false),
|
|
661
703
|
etag: res.ok ? readEtag(res) : void 0
|
|
662
704
|
};
|
|
663
705
|
}
|
|
664
|
-
const
|
|
665
|
-
const
|
|
706
|
+
const base = this._metaKey ?? url;
|
|
707
|
+
const key = locale === void 0 ? base : `${base}#${locale}`;
|
|
708
|
+
const headers = await this._resolveHeaders(locale);
|
|
666
709
|
const candidates = store._isUnconditional(key) ? [] : store.candidates(key);
|
|
667
710
|
if (candidates.length > 0) {
|
|
668
711
|
const init = {
|
|
@@ -787,6 +830,11 @@ var Client = class {
|
|
|
787
830
|
}
|
|
788
831
|
}
|
|
789
832
|
};
|
|
833
|
+
/** Whether `headers` has `name` (lower case), in any letter case. */
|
|
834
|
+
function hasHeader(headers, name) {
|
|
835
|
+
for (const key in headers) if (key.toLowerCase() === name) return true;
|
|
836
|
+
return false;
|
|
837
|
+
}
|
|
790
838
|
/**
|
|
791
839
|
* The response's `ETag`, when readable — a cross-origin response hides it
|
|
792
840
|
* 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-
|
|
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";
|
|
@@ -70,11 +70,14 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
|
|
|
70
70
|
private readonly _lenientWrites?;
|
|
71
71
|
private readonly _metaStore;
|
|
72
72
|
private readonly _metaKey?;
|
|
73
|
+
private readonly _locale?;
|
|
74
|
+
/** The locale {@link _metaPromise} (and the validator, forms) were loaded in. */
|
|
75
|
+
private _metaLocale?;
|
|
73
76
|
private _metaPromise?;
|
|
74
77
|
/** The `ETag` of the `/meta` body {@link _metaPromise} resolved to. */
|
|
75
78
|
private _metaEtag?;
|
|
76
79
|
private _validatorPromise?;
|
|
77
|
-
/**
|
|
80
|
+
/** Loaded action forms (type + served `$i18n`) keyed by resolved URL. */
|
|
78
81
|
private _formCache;
|
|
79
82
|
constructor(path: string, opts?: ClientOptions);
|
|
80
83
|
/**
|
|
@@ -362,13 +365,25 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
|
|
|
362
365
|
* Cached per resolved URL.
|
|
363
366
|
*/
|
|
364
367
|
getActionForm(actionName: string): Promise<TAtscriptAnnotatedType | null>;
|
|
368
|
+
/**
|
|
369
|
+
* The texts the action's form schema was served with in this client's
|
|
370
|
+
* locale (its `$i18n`: registered message templates and the translated
|
|
371
|
+
* literals of its expressions), or `undefined` when the server sent none
|
|
372
|
+
* or the action has no form. Read from the same cached response as
|
|
373
|
+
* {@link getActionForm}; merge them into your UI texts to show the form's
|
|
374
|
+
* expression results in the user's language.
|
|
375
|
+
*
|
|
376
|
+
* @since 0.1.170
|
|
377
|
+
*/
|
|
378
|
+
getActionFormTexts(actionName: string): Promise<Record<string, string> | undefined>;
|
|
379
|
+
private _actionForm;
|
|
365
380
|
private _loadActionForm;
|
|
366
381
|
/**
|
|
367
382
|
* Returns a lazily-initialized {@link ClientValidator} backed by the `/meta` type.
|
|
368
383
|
* Useful for accessing `flatMap` and `navFields` (e.g. for form generation).
|
|
369
384
|
*/
|
|
370
385
|
getValidator(): Promise<ClientValidator>;
|
|
371
|
-
/** Lifts `$cas` to the wire shape, then
|
|
386
|
+
/** Lifts `$cas` to the wire shape, normalizes, then validates the result — which is what gets sent. */
|
|
372
387
|
private _prepareWrite;
|
|
373
388
|
private _getValidator;
|
|
374
389
|
private _buildActionBody;
|
|
@@ -385,6 +400,10 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
|
|
|
385
400
|
private _getOrNull;
|
|
386
401
|
private _get;
|
|
387
402
|
private _resolveHeaders;
|
|
403
|
+
/** `ClientOptions.locale` now. */
|
|
404
|
+
private _currentLocale;
|
|
405
|
+
/** {@link _currentLocale}, after dropping the `/meta`, validator and forms loaded in another one. */
|
|
406
|
+
private _syncLocale;
|
|
388
407
|
/**
|
|
389
408
|
* `GET /meta` through the meta store: conditional when the store holds
|
|
390
409
|
* 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-
|
|
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";
|
|
@@ -70,11 +70,14 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
|
|
|
70
70
|
private readonly _lenientWrites?;
|
|
71
71
|
private readonly _metaStore;
|
|
72
72
|
private readonly _metaKey?;
|
|
73
|
+
private readonly _locale?;
|
|
74
|
+
/** The locale {@link _metaPromise} (and the validator, forms) were loaded in. */
|
|
75
|
+
private _metaLocale?;
|
|
73
76
|
private _metaPromise?;
|
|
74
77
|
/** The `ETag` of the `/meta` body {@link _metaPromise} resolved to. */
|
|
75
78
|
private _metaEtag?;
|
|
76
79
|
private _validatorPromise?;
|
|
77
|
-
/**
|
|
80
|
+
/** Loaded action forms (type + served `$i18n`) keyed by resolved URL. */
|
|
78
81
|
private _formCache;
|
|
79
82
|
constructor(path: string, opts?: ClientOptions);
|
|
80
83
|
/**
|
|
@@ -362,13 +365,25 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
|
|
|
362
365
|
* Cached per resolved URL.
|
|
363
366
|
*/
|
|
364
367
|
getActionForm(actionName: string): Promise<TAtscriptAnnotatedType | null>;
|
|
368
|
+
/**
|
|
369
|
+
* The texts the action's form schema was served with in this client's
|
|
370
|
+
* locale (its `$i18n`: registered message templates and the translated
|
|
371
|
+
* literals of its expressions), or `undefined` when the server sent none
|
|
372
|
+
* or the action has no form. Read from the same cached response as
|
|
373
|
+
* {@link getActionForm}; merge them into your UI texts to show the form's
|
|
374
|
+
* expression results in the user's language.
|
|
375
|
+
*
|
|
376
|
+
* @since 0.1.170
|
|
377
|
+
*/
|
|
378
|
+
getActionFormTexts(actionName: string): Promise<Record<string, string> | undefined>;
|
|
379
|
+
private _actionForm;
|
|
365
380
|
private _loadActionForm;
|
|
366
381
|
/**
|
|
367
382
|
* Returns a lazily-initialized {@link ClientValidator} backed by the `/meta` type.
|
|
368
383
|
* Useful for accessing `flatMap` and `navFields` (e.g. for form generation).
|
|
369
384
|
*/
|
|
370
385
|
getValidator(): Promise<ClientValidator>;
|
|
371
|
-
/** Lifts `$cas` to the wire shape, then
|
|
386
|
+
/** Lifts `$cas` to the wire shape, normalizes, then validates the result — which is what gets sent. */
|
|
372
387
|
private _prepareWrite;
|
|
373
388
|
private _getValidator;
|
|
374
389
|
private _buildActionBody;
|
|
@@ -385,6 +400,10 @@ declare class Client<T extends AtscriptClientShape = AtscriptClientShape, D exte
|
|
|
385
400
|
private _getOrNull;
|
|
386
401
|
private _get;
|
|
387
402
|
private _resolveHeaders;
|
|
403
|
+
/** `ClientOptions.locale` now. */
|
|
404
|
+
private _currentLocale;
|
|
405
|
+
/** {@link _currentLocale}, after dropping the `/meta`, validator and forms loaded in another one. */
|
|
406
|
+
private _syncLocale;
|
|
388
407
|
/**
|
|
389
408
|
* `GET /meta` through the meta store: conditional when the store holds
|
|
390
409
|
* bodies for this key, falling back to a plain request whenever the
|
package/dist/index.mjs
CHANGED
|
@@ -170,11 +170,14 @@ var Client = class {
|
|
|
170
170
|
_lenientWrites;
|
|
171
171
|
_metaStore;
|
|
172
172
|
_metaKey;
|
|
173
|
+
_locale;
|
|
174
|
+
/** The locale {@link _metaPromise} (and the validator, forms) were loaded in. */
|
|
175
|
+
_metaLocale;
|
|
173
176
|
_metaPromise;
|
|
174
177
|
/** The `ETag` of the `/meta` body {@link _metaPromise} resolved to. */
|
|
175
178
|
_metaEtag;
|
|
176
179
|
_validatorPromise;
|
|
177
|
-
/**
|
|
180
|
+
/** Loaded action forms (type + served `$i18n`) keyed by resolved URL. */
|
|
178
181
|
_formCache = /* @__PURE__ */ new Map();
|
|
179
182
|
constructor(path, opts) {
|
|
180
183
|
this._path = path.endsWith("/") ? path.slice(0, -1) : path;
|
|
@@ -185,6 +188,7 @@ var Client = class {
|
|
|
185
188
|
this._lenientWrites = opts?.lenientWrites;
|
|
186
189
|
this._metaStore = opts?.metaStore === false ? void 0 : opts?.metaStore ?? defaultMetaStore;
|
|
187
190
|
this._metaKey = opts?.metaKey;
|
|
191
|
+
this._locale = opts?.locale;
|
|
188
192
|
}
|
|
189
193
|
/**
|
|
190
194
|
* `GET /query` — query records with typed filter, sort, select, and relations.
|
|
@@ -333,8 +337,9 @@ var Client = class {
|
|
|
333
337
|
* as `If-None-Match`, and a `304 Not Modified` reuses the stored body.
|
|
334
338
|
*/
|
|
335
339
|
async meta() {
|
|
340
|
+
const locale = this._syncLocale();
|
|
336
341
|
if (!this._metaPromise) {
|
|
337
|
-
const p = this._loadMeta().then(({ body, etag }) => {
|
|
342
|
+
const p = this._loadMeta(locale).then(({ body, etag }) => {
|
|
338
343
|
if (this._metaPromise === p) this._metaEtag = etag;
|
|
339
344
|
return body;
|
|
340
345
|
}, (err) => {
|
|
@@ -524,15 +529,35 @@ var Client = class {
|
|
|
524
529
|
* Cached per resolved URL.
|
|
525
530
|
*/
|
|
526
531
|
async getActionForm(actionName) {
|
|
532
|
+
return (await this._actionForm(actionName))?.type ?? null;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* The texts the action's form schema was served with in this client's
|
|
536
|
+
* locale (its `$i18n`: registered message templates and the translated
|
|
537
|
+
* literals of its expressions), or `undefined` when the server sent none
|
|
538
|
+
* or the action has no form. Read from the same cached response as
|
|
539
|
+
* {@link getActionForm}; merge them into your UI texts to show the form's
|
|
540
|
+
* expression results in the user's language.
|
|
541
|
+
*
|
|
542
|
+
* @since 0.1.170
|
|
543
|
+
*/
|
|
544
|
+
async getActionFormTexts(actionName) {
|
|
545
|
+
return (await this._actionForm(actionName))?.texts;
|
|
546
|
+
}
|
|
547
|
+
async _actionForm(actionName) {
|
|
527
548
|
const action = (await this.meta()).actions.find((a) => a.name === actionName);
|
|
528
549
|
if (!action?.inputForm) return null;
|
|
529
550
|
const url = action.formUrl ? `${this._baseUrl}${action.formUrl}` : this._endpointUrl(`meta/form/${encodeURIComponent(action.inputForm)}`);
|
|
530
551
|
return this._loadActionForm(url);
|
|
531
552
|
}
|
|
532
553
|
_loadActionForm(url) {
|
|
554
|
+
this._syncLocale();
|
|
533
555
|
let p = this._formCache.get(url);
|
|
534
556
|
if (!p) {
|
|
535
|
-
const loading = Promise.all([this._requestUrl("GET", url), import("@atscript/typescript/utils")]).then(([schema, { deserializeAnnotatedType }]) =>
|
|
557
|
+
const loading = Promise.all([this._requestUrl("GET", url), import("@atscript/typescript/utils")]).then(([schema, { deserializeAnnotatedType }]) => ({
|
|
558
|
+
type: deserializeAnnotatedType(schema),
|
|
559
|
+
texts: schema.$i18n
|
|
560
|
+
})).catch((err) => {
|
|
536
561
|
if (this._formCache.get(url) === loading) this._formCache.delete(url);
|
|
537
562
|
throw err;
|
|
538
563
|
});
|
|
@@ -548,14 +573,15 @@ var Client = class {
|
|
|
548
573
|
getValidator() {
|
|
549
574
|
return this._getValidator();
|
|
550
575
|
}
|
|
551
|
-
/** Lifts `$cas` to the wire shape, then
|
|
576
|
+
/** Lifts `$cas` to the wire shape, normalizes, then validates the result — which is what gets sent. */
|
|
552
577
|
async _prepareWrite(data, mode) {
|
|
553
578
|
const validator = await this._getValidator();
|
|
554
|
-
const
|
|
555
|
-
validator.validate(
|
|
556
|
-
return
|
|
579
|
+
const prepared = validator.normalize(validator.liftCas(data, mode), mode);
|
|
580
|
+
validator.validate(prepared, mode);
|
|
581
|
+
return prepared;
|
|
557
582
|
}
|
|
558
583
|
_getValidator() {
|
|
584
|
+
this._syncLocale();
|
|
559
585
|
if (!this._validatorPromise) {
|
|
560
586
|
const p = Promise.all([this.meta(), import("./validator.mjs")]).then(([m, { createClientValidator }]) => createClientValidator(m, { lenientWrites: this._lenientWrites })).catch((err) => {
|
|
561
587
|
if (this._validatorPromise === p) this._validatorPromise = void 0;
|
|
@@ -637,31 +663,48 @@ var Client = class {
|
|
|
637
663
|
const qs = query ? buildUrl(query) : "";
|
|
638
664
|
return this._request("GET", `${endpoint}${qs ? `?${qs}` : ""}`, void 0, { signal });
|
|
639
665
|
}
|
|
640
|
-
async _resolveHeaders() {
|
|
641
|
-
|
|
642
|
-
if (
|
|
643
|
-
return
|
|
666
|
+
async _resolveHeaders(locale = this._currentLocale()) {
|
|
667
|
+
const headers = !this._headers ? {} : typeof this._headers === "function" ? await this._headers() : this._headers;
|
|
668
|
+
if (locale === void 0 || hasHeader(headers, "accept-language")) return headers;
|
|
669
|
+
return {
|
|
670
|
+
...headers,
|
|
671
|
+
"Accept-Language": locale
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
/** `ClientOptions.locale` now. */
|
|
675
|
+
_currentLocale() {
|
|
676
|
+
return typeof this._locale === "function" ? this._locale() : this._locale;
|
|
677
|
+
}
|
|
678
|
+
/** {@link _currentLocale}, after dropping the `/meta`, validator and forms loaded in another one. */
|
|
679
|
+
_syncLocale() {
|
|
680
|
+
const locale = this._currentLocale();
|
|
681
|
+
if (locale !== this._metaLocale) {
|
|
682
|
+
this.invalidateMeta();
|
|
683
|
+
this._metaLocale = locale;
|
|
684
|
+
}
|
|
685
|
+
return locale;
|
|
644
686
|
}
|
|
645
687
|
/**
|
|
646
688
|
* `GET /meta` through the meta store: conditional when the store holds
|
|
647
689
|
* bodies for this key, falling back to a plain request whenever the
|
|
648
690
|
* conditional one cannot be answered from the store.
|
|
649
691
|
*/
|
|
650
|
-
async _loadMeta() {
|
|
692
|
+
async _loadMeta(locale) {
|
|
651
693
|
const url = this._endpointUrl("meta");
|
|
652
694
|
const store = this._metaStore;
|
|
653
695
|
if (!store) {
|
|
654
696
|
const res = await this._fetchUrl(url, {
|
|
655
697
|
method: "GET",
|
|
656
|
-
headers: await this._resolveHeaders()
|
|
698
|
+
headers: await this._resolveHeaders(locale)
|
|
657
699
|
});
|
|
658
700
|
return {
|
|
659
701
|
body: await this._readResponse(res, url, "GET", false),
|
|
660
702
|
etag: res.ok ? readEtag(res) : void 0
|
|
661
703
|
};
|
|
662
704
|
}
|
|
663
|
-
const
|
|
664
|
-
const
|
|
705
|
+
const base = this._metaKey ?? url;
|
|
706
|
+
const key = locale === void 0 ? base : `${base}#${locale}`;
|
|
707
|
+
const headers = await this._resolveHeaders(locale);
|
|
665
708
|
const candidates = store._isUnconditional(key) ? [] : store.candidates(key);
|
|
666
709
|
if (candidates.length > 0) {
|
|
667
710
|
const init = {
|
|
@@ -786,6 +829,11 @@ var Client = class {
|
|
|
786
829
|
}
|
|
787
830
|
}
|
|
788
831
|
};
|
|
832
|
+
/** Whether `headers` has `name` (lower case), in any letter case. */
|
|
833
|
+
function hasHeader(headers, name) {
|
|
834
|
+
for (const key in headers) if (key.toLowerCase() === name) return true;
|
|
835
|
+
return false;
|
|
836
|
+
}
|
|
789
837
|
/**
|
|
790
838
|
* The response's `ETag`, when readable — a cross-origin response hides it
|
|
791
839
|
* 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:
|
|
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:
|
|
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).
|
package/dist/validator.cjs
CHANGED
|
@@ -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((
|
|
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 =
|
|
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;
|
package/dist/validator.d.cts
CHANGED
|
@@ -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-
|
|
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 };
|
package/dist/validator.d.mts
CHANGED
|
@@ -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-
|
|
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 };
|
package/dist/validator.mjs
CHANGED
|
@@ -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,
|
|
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((
|
|
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 =
|
|
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.
|
|
3
|
+
"version": "0.1.171",
|
|
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.
|
|
47
|
-
"@uniqu/url": "^0.2.
|
|
46
|
+
"@uniqu/core": "^0.2.1",
|
|
47
|
+
"@uniqu/url": "^0.2.1"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
|
-
"@atscript/core": "^0.2.
|
|
51
|
-
"@atscript/typescript": "^0.2.
|
|
52
|
-
"unplugin-atscript": "^0.2.
|
|
53
|
-
"@atscript/db": "0.1.
|
|
50
|
+
"@atscript/core": "^0.2.8",
|
|
51
|
+
"@atscript/typescript": "^0.2.8",
|
|
52
|
+
"unplugin-atscript": "^0.2.8",
|
|
53
|
+
"@atscript/db": "0.1.171"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@atscript/typescript": "^0.2.
|
|
57
|
-
"@atscript/db": "^0.1.
|
|
56
|
+
"@atscript/typescript": "^0.2.8",
|
|
57
|
+
"@atscript/db": "^0.1.171"
|
|
58
58
|
},
|
|
59
59
|
"scripts": {
|
|
60
60
|
"build": "vp pack",
|