@atscript/typescript 0.2.4 → 0.2.6

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/utils.d.ts CHANGED
@@ -435,6 +435,19 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
435
435
  */
436
436
  private keptKeyCount;
437
437
  }
438
+ /** A union's discriminator, as the validator reports it (see {@link unionDiscriminator}). */
439
+ interface TValidatorDiscriminator {
440
+ property: string;
441
+ /** Per object branch: its index in the union's items, its literal. */
442
+ branches: Array<[index: number, literal: unknown]>;
443
+ }
444
+ /**
445
+ * The discriminator of a union over objects (see {@link detectDiscriminator}), required in every
446
+ * object branch: the property and, per object branch, its index in `items` and its literal. The
447
+ * other branches must reject any object (scalars, arrays, tuples), so only the object branches
448
+ * can match an object value.
449
+ */
450
+ declare function unionDiscriminator(items: TAtscriptAnnotatedType[]): TValidatorDiscriminator | undefined;
438
451
  /** Error thrown by {@link Validator.validate} when validation fails. Contains structured error details. */
439
452
  declare class ValidatorError extends Error {
440
453
  readonly errors: TError[];
@@ -654,9 +667,19 @@ declare function isAnnotatedTypeOfPrimitive(t: TAtscriptAnnotatedType): boolean;
654
667
  * - Strings targeting `number` are trimmed and parsed via `Number()`; only
655
668
  * finite results are accepted.
656
669
  * - Strings targeting `boolean` accept `"true"/"1"` and `"false"/"0"`.
657
- * - Unions try each branch in declared order; the first successful parse wins.
670
+ * - Unions pick one branch and coerce the value against it only (linear, no
671
+ * backtracking). A scalar branch takes what it parses; an object (tuple)
672
+ * branch takes a plain object (an array of its length) unless a literal
673
+ * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
674
+ * does not coerce to it, a string compared after the normalizers of the
675
+ * literal and of the unions it is in. An object takes the branch its
676
+ * discriminator names (as the validator does: the literal itself first, else
677
+ * `"2"` names a `2` literal), else the first whose shape it has (required
678
+ * props present, no undeclared key), else the first that takes it. When no
679
+ * branch takes the value, it is returned untouched.
658
680
  * - Objects recurse into props when the input is a plain object (covers
659
- * `@Query()` DTOs where every field arrives as a string).
681
+ * `@Query()` DTOs where every field arrives as a string), whatever their
682
+ * literal props hold unless tried as a union branch.
660
683
  * - Arrays and tuples coerce items; intersections apply each member in order.
661
684
  * - `string` / `decimal` targets never change string input.
662
685
  *
@@ -674,8 +697,65 @@ declare function coerceForType(def: TAtscriptAnnotatedType, value: unknown): unk
674
697
  */
675
698
  declare function coerceScalar(designType: TAtscriptTypeFinal['designType'], value: unknown): unknown;
676
699
 
700
+ /**
701
+ * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
702
+ * `@normalize.lowercase` and `@normalize.uppercase`.
703
+ *
704
+ * Pure: returns a normalized copy (copy-on-change: untouched objects and arrays are returned as
705
+ * they are) and never mutates `value`. It never validates — run the validator on the result —
706
+ * and does not throw on ordinary input (a cyclic value overflows the stack, as it does in the
707
+ * validator). Only strings change: a string node's normalizers (its own, a type alias's it
708
+ * inherits, a union's it belongs to) apply in a fixed order: trim, then lowercase, then
709
+ * uppercase. Other values (including class instances such as `Date`) and strings without
710
+ * normalizers are returned untouched; a type without normalizers returns `value` at once.
711
+ *
712
+ * Walks plain objects (props and pattern props; unknown keys are kept as they are), arrays,
713
+ * tuples, intersections and unions. An object whose literal prop (`kind: 'cat'`) holds another
714
+ * value is left as it is. A union normalizes a value only when the result does not depend on
715
+ * which branch takes it:
716
+ * - an object union with a discriminator (a literal prop every object branch requires, see
717
+ * `detectDiscriminator`) uses the branch the value's discriminator names;
718
+ * - otherwise every branch that can take the value is tried (a literal branch can take a string
719
+ * only when the normalized string equals its literal): when they all give the same result it
720
+ * is used; when they differ, the branches whose result their own validator accepts are kept,
721
+ * and the result is used when they agree; else the value is returned untouched (ambiguous).
722
+ * The branch validators take `opts` — pass the options the result will be validated with
723
+ * (`partial`, `unknownProps`, …) so a branch is judged as the validator will judge it; default
724
+ * options when omitted. (`unknownProps: 'strip'` judges as `'ignore'`: nothing is stripped.)
725
+ *
726
+ * The intended flow is `coerceForType` → `normalizeForType` → `validate`.
727
+ *
728
+ * @example
729
+ * ```ts
730
+ * // @normalize.trim @normalize.lowercase email: string.email
731
+ * normalizeForType(User, { email: ' Ann@Example.COM ' }) // → { email: 'ann@example.com' }
732
+ * // judged as a partial update will be validated
733
+ * normalizeForType(Patch, body, { partial: true })
734
+ * ```
735
+ */
736
+ declare function normalizeForType<T = unknown>(def: TAtscriptAnnotatedType, value: T, opts?: Partial<TValidatorOptions>): T;
737
+
677
738
  /** A JSON Schema object (draft-compatible). */
678
739
  type TJsonSchema = Record<string, any>;
740
+ /** Options of {@link buildJsonSchema} (and of the `jsonSchemaOptions` plugin option). */
741
+ interface TJsonSchemaOptions {
742
+ /**
743
+ * `additionalProperties: false` on every object schema: the schema rejects keys the type does
744
+ * not declare, as the validator does with its default `unknownProps: 'error'`.
745
+ * *(default: `false`)*
746
+ */
747
+ closed?: boolean;
748
+ /**
749
+ * `@meta.description` → `description` and `@meta.label` → `title`, on the schema of the
750
+ * type or field that carries them. *(default: `true`)*
751
+ */
752
+ annotations?: boolean;
753
+ /**
754
+ * A union of literals (`'a' | 'b'`, also with `null`) → `{ type, enum }` instead of an
755
+ * `anyOf` of `const` schemas. *(default: `true`)*
756
+ */
757
+ enums?: boolean;
758
+ }
679
759
  /**
680
760
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
681
761
  *
@@ -691,9 +771,10 @@ type TJsonSchema = Record<string, any>;
691
771
  * ```
692
772
  *
693
773
  * @param type - The annotated type to convert.
774
+ * @param opts - {@link TJsonSchemaOptions}.
694
775
  * @returns A JSON Schema object.
695
776
  */
696
- declare function buildJsonSchema(type: TAtscriptAnnotatedType): TJsonSchema;
777
+ declare function buildJsonSchema(type: TAtscriptAnnotatedType, opts?: TJsonSchemaOptions): TJsonSchema;
697
778
  /**
698
779
  * Converts a JSON Schema object into a {@link TAtscriptAnnotatedType}.
699
780
  *
@@ -726,9 +807,10 @@ declare function fromJsonSchema(schema: TJsonSchema): TAtscriptAnnotatedType;
726
807
  * to it are renamed.
727
808
  *
728
809
  * @param types - Array of annotated types, each with an `id`.
810
+ * @param opts - {@link TJsonSchemaOptions}, for every schema.
729
811
  * @returns An object with `schemas` (keyed by id) and shared `$defs`.
730
812
  */
731
- declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[]): {
813
+ declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[], opts?: TJsonSchemaOptions): {
732
814
  schemas: Record<string, TJsonSchema>;
733
815
  $defs: Record<string, TJsonSchema>;
734
816
  };
@@ -743,7 +825,11 @@ declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[]): {
743
825
  type TUnionDiscriminator = {
744
826
  /** Name of the discriminator property shared by all variants. */
745
827
  propertyName: string;
746
- /** Maps the literal value of `propertyName` → variant index in `items`. */
828
+ /**
829
+ * Maps the literal value of `propertyName` (as a string) → variant index in `items`. An object
830
+ * without a prototype: look a value up directly (`indexMapping[String(tag)]`), a key such as
831
+ * `constructor` finds nothing.
832
+ */
747
833
  indexMapping: Record<string, number>;
748
834
  };
749
835
  /**
@@ -824,17 +910,19 @@ declare function throwFeatureDisabled(feature: string, option: string, annotatio
824
910
 
825
911
  /**
826
912
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
827
- * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
828
- * (`static toJsonSchema()`).
913
+ * a type tree write (a block, a runtime edit of metadata or shape: see `typeWrites`). Called by
914
+ * generated code (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same
915
+ * for every call of a type).
829
916
  */
830
- declare function lazyJsonSchema(type: TAtscriptAnnotatedType): TJsonSchema;
917
+ declare function lazyJsonSchema(type: TAtscriptAnnotatedType, opts?: TJsonSchemaOptions): TJsonSchema;
831
918
  /**
832
919
  * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
833
920
  * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
834
921
  * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
835
- * metadata writes are not seen (as in 0.1.110). Called by generated code.
922
+ * metadata writes are not seen (as in 0.1.110). Called by generated code, with the
923
+ * `jsonSchemaOptions` of the build (the literal was built with them).
836
924
  */
837
- declare function bundledSchemaOf(type: TAtscriptAnnotatedType, literal: () => TJsonSchema, modules?: readonly string[]): TJsonSchema;
925
+ declare function bundledSchemaOf(type: TAtscriptAnnotatedType, literal: () => TJsonSchema, modules?: readonly string[], opts?: TJsonSchemaOptions): TJsonSchema;
838
926
 
839
927
  type TSite = [optional: number, mask: number, def: number, shape: string, slot: number];
840
928
  type TDef = Array<string | number | boolean | string[] | TSite | TSite[]>;
@@ -1031,6 +1119,13 @@ declare const SERIALIZE_VERSION = 2;
1031
1119
  interface TSerializedAnnotatedType extends TSerializedAnnotatedTypeInner {
1032
1120
  /** Format version for forward compatibility */
1033
1121
  $v: number;
1122
+ /**
1123
+ * Texts a server serves with the type for the client, in the locale it was translated to
1124
+ * (see `translateServed`): message templates by code (`{name}` placeholders) and translated
1125
+ * texts by their source text — what `messagesTranslator()` takes. Never written by
1126
+ * `serializeAnnotatedType`; `deserializeAnnotatedType` ignores it.
1127
+ */
1128
+ $i18n?: Record<string, string>;
1034
1129
  }
1035
1130
  /** Serialized annotated type node (used for nested types within the top-level). */
1036
1131
  interface TSerializedAnnotatedTypeInner {
@@ -1188,6 +1283,40 @@ declare function serializeAnnotatedType(type: TAtscriptAnnotatedType, options?:
1188
1283
  */
1189
1284
  declare function deserializeAnnotatedType(data: TSerializedAnnotatedType): TAtscriptAnnotatedType;
1190
1285
 
1286
+ /**
1287
+ * Translating a serialized type (or any JSON carrying serialized types) before it is served:
1288
+ * the user-facing text of its metadata is replaced, the string literals of its expressions are
1289
+ * collected for the client.
1290
+ */
1291
+ /**
1292
+ * Translates the user-facing text of serialized annotated types (the output of
1293
+ * `serializeAnnotatedType`, or any JSON holding such output) with `t`. Every `metadata` object
1294
+ * found at any depth is read with {@link userTextOf}:
1295
+ *
1296
+ * - a text key's value (each item of a `multiple` list; the named fields of a value object) is
1297
+ * replaced by `t(text)` — except a primitive's built-in format message (`string.email`'s), which
1298
+ * the validator reports by its code (`EMAIL`), translated on the client through `$i18n`;
1299
+ * - an expression key's value (function source evaluated by the client) stays as it is: the
1300
+ * string literals in it (`'…'`, `"…"`, and `` `…` `` templates without `${…}`) are translated,
1301
+ * and `texts` maps each literal translated to its translation — serve it to the client, which
1302
+ * translates the expressions' results by exact match.
1303
+ *
1304
+ * `t` returns `undefined` (anything but a string) to keep a text. The input is never changed: the
1305
+ * result shares every part with no translated text, and is `json` itself when nothing was
1306
+ * translated.
1307
+ *
1308
+ * @example
1309
+ * ```ts
1310
+ * const { value, texts } = translateServed(serializeAnnotatedType(Product), text =>
1311
+ * i18n.exists(text) ? i18n.t(text) : undefined
1312
+ * )
1313
+ * ```
1314
+ */
1315
+ declare function translateServed<T>(json: T, t: (text: string) => string | undefined): {
1316
+ value: T;
1317
+ texts: Record<string, string>;
1318
+ };
1319
+
1191
1320
  /**
1192
1321
  * Metadata layers: the runtime's one metadata mechanism.
1193
1322
  *
@@ -1198,7 +1327,7 @@ declare function deserializeAnnotatedType(data: TSerializedAnnotatedType): TAtsc
1198
1327
  * a base shows through every layer over it.
1199
1328
  *
1200
1329
  * Reads go through a flattened view of the effective entries, rebuilt on the first read after any
1201
- * metadata write (one global write counter: `metadataWriteCount`). The view is used only while
1330
+ * type tree write (one global write counter: `typeWriteCount`). The view is used only while
1202
1331
  * every map below is tracked (an `AnnotationMap` or a `LayerMap`, whose writes the counter
1203
1332
  * sees); otherwise the reads are live. A raw write the counter does not see (a node's map swapped,
1204
1333
  * `node.metadata = X`, or edited in place) must be followed by `invalidateCompiledValidators()`,
@@ -1223,11 +1352,11 @@ declare class LayerMap<K = unknown, V = unknown> extends AnnotationMap<K, V> {
1223
1352
  r: boolean;
1224
1353
  /**
1225
1354
  * The flattened view: every effective entry (as the layered reads give it, in their order),
1226
- * built on the first read after a metadata write (`w` ≠ `metadataWrites`); `undefined` while a
1355
+ * built on the first read after a type tree write (`w` ≠ `typeWrites`); `undefined` while a
1227
1356
  * map below is not tracked (a plain `Map` or a subclass: its writes are not counted, read live).
1228
1357
  */
1229
1358
  private f;
1230
- /** `metadataWrites` when {@link f} was built (`-1`: not built). */
1359
+ /** `typeWrites` when {@link f} was built (`-1`: not built). */
1231
1360
  private w;
1232
1361
  constructor(bases: TLayerNode[], reference?: boolean, own?: Iterable<readonly [K, V]> | null);
1233
1362
  /**
@@ -1278,24 +1407,29 @@ declare function watchLayer(m: Map<unknown, unknown>, seen?: Set<object>): boole
1278
1407
  * are registered by the generated modules that write them (`$ut`), or by the plugin itself
1279
1408
  * ({@link registerUserText}), so a translator finds them at runtime without the specs.
1280
1409
  */
1281
- /** `true`: the value itself is the text; a list: those fields of the value object are. */
1282
- type TUserTextFields = true | readonly string[];
1283
1410
  /**
1284
- * Registers metadata key `key` as holding user-facing text: `true` (default) — its value is the
1285
- * text; a list of field names — those fields of its value object are. Fields add up across calls.
1411
+ * `true`: the value itself is the text; `'expression'`: the value is the source of a function the
1412
+ * client evaluates, its string literals the texts; a list: those fields of the value object are
1413
+ * (a name ending in `()`: that field is an expression).
1414
+ */
1415
+ type TUserTextFields = true | 'expression' | readonly string[];
1416
+ /**
1417
+ * Registers metadata key `key` as holding user-facing text (see {@link TUserTextFields}; `true` by
1418
+ * default). Fields add up across calls; a whole-value kind replaces a field list, and an
1419
+ * expression wins over text (`name()` over `name`), whatever the order of the calls.
1286
1420
  * For plugins that write such metadata at runtime; generated modules register what they write.
1287
1421
  */
1288
1422
  declare function registerUserText(key: string, fields?: TUserTextFields): void;
1289
1423
  /**
1290
1424
  * Registers user-text keys written by a generated module (see {@link registerUserText}): `key` —
1291
- * the value itself; `key:field` — that field of the value object.
1425
+ * the value itself; `key()` — the value is an expression; `key:field` — that field of the value
1426
+ * object; `key:field()` — that field is an expression.
1292
1427
  */
1293
1428
  declare function $ut(...entries: string[]): void;
1294
1429
  /**
1295
- * Where metadata key `key` holds user-facing text: `true` — its value is the text (a string; for
1296
- * a `multiple` annotation, each item of the list); a list of field names — those fields of its
1297
- * value object (each item's, for a list); `undefined` — no user-facing text. Core keys are known
1298
- * from the start; a plugin's once a module writing them is loaded (or the plugin registered them).
1430
+ * Where metadata key `key` holds user-facing text (see {@link TUserTextFields}; for a `multiple`
1431
+ * annotation, each item of its list), `undefined` when it holds none. Core keys are known from the
1432
+ * start; a plugin's once a module writing them is loaded (or the plugin registered them).
1299
1433
  */
1300
1434
  declare function userTextOf(key: string): TUserTextFields | undefined;
1301
1435
  /** Every metadata key holding user-facing text known so far (see {@link userTextOf}). */
@@ -1405,5 +1539,5 @@ type NavPropsOf<T> = T extends {
1405
1539
  __navProps: infer N extends Record<string, unknown>;
1406
1540
  } ? N : Record<string, never>;
1407
1541
 
1408
- export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, LayerMap, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, userTextKeys, userTextOf, watchLayer };
1409
- export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptField, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TError, TErrorInfo, TFlattenOptions, TJsonSchema, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TUserTextFields, TValidatorErrorCode, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValidatorTranslate, TValueResolver };
1542
+ export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, LayerMap, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, unionDiscriminator, userTextKeys, userTextOf, watchLayer };
1543
+ export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptField, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TError, TErrorInfo, TFlattenOptions, TJsonSchema, TJsonSchemaOptions, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TUserTextFields, TValidatorDiscriminator, TValidatorErrorCode, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValidatorTranslate, TValueResolver };