@atscript/typescript 0.2.3 → 0.2.4

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
@@ -1,8 +1,210 @@
1
+ /**
2
+ * Validator error codes, their default English templates and the translation helpers.
3
+ *
4
+ * The validator is locale-agnostic: every error it reports carries a stable `code` and the
5
+ * `params` its message needs, and its `message` is the default English text (the code's
6
+ * template filled with the params) or the app's own text from an annotation (`custom: true`).
7
+ * Translate after the fact with {@link localizeErrors}, or per validator with the `translate`
8
+ * option.
9
+ */
10
+ /**
11
+ * Default English templates of the built-in error codes. `{name}` is replaced with
12
+ * `params.name` (see {@link formatValidatorMessage}).
13
+ */
14
+ declare const VALIDATOR_MESSAGES: Readonly<{
15
+ /** A required string is empty (or whitespace only), or a required optional field is `null`. */
16
+ readonly REQUIRED: "Must not be empty";
17
+ /** A required boolean (`@meta.required` on a boolean) is not `true`. */
18
+ readonly REQUIRED_CHECKED: "Must be checked";
19
+ /** Wrong primitive type. `{ expected, actual }`: type names. */
20
+ readonly TYPE: "Expected {expected}, got {actual}";
21
+ /** Not an array. `{ actual }`: the value's type name. */
22
+ readonly TYPE_ARRAY: "Expected array";
23
+ /** Not an object. `{ actual }`: the value's type name. */
24
+ readonly TYPE_OBJECT: "Expected object";
25
+ /** A decimal that is not a string. `{ actual }`: the value's type name. */
26
+ readonly TYPE_DECIMAL: "Expected string (decimal), got {actual}";
27
+ /** `NaN` or an infinity. `{ actual }`: the value as text. */
28
+ readonly NOT_FINITE: "Expected finite number, got {actual}";
29
+ /** A decimal string in the wrong format. `{ value }`: the string. */
30
+ readonly DECIMAL_FORMAT: "Invalid decimal format: \"{value}\"";
31
+ /** A `never` type. */
32
+ readonly NEVER: "This type is impossible, must be an internal problem";
33
+ /** Not the literal value. `{ expected, actual }`: the literal, the value as text. */
34
+ readonly LITERAL: "Expected {expected}, got {actual}";
35
+ /** No union branch matches. `{ expected }`: the branch kinds (`[string(0)], [number(1)]`). */
36
+ readonly UNION: "Value does not match any of the allowed types: {expected}";
37
+ /**
38
+ * The discriminator of an object union holds no branch's value. Reported at the discriminator
39
+ * property. `{ property, allowed, actual }`: its name, the allowed values, the value as text.
40
+ */
41
+ readonly UNION_DISCRIMINATOR: "Expected one of {allowed}, got {actual}";
42
+ /** A property the type does not declare (`unknownProps: 'error'`). `{ property }`. */
43
+ readonly UNEXPECTED_PROPERTY: "Unexpected property";
44
+ /** A tuple of the wrong length. `{ length }`: the expected length. */
45
+ readonly TUPLE_LENGTH: "Expected array of length {length}";
46
+ /** `@expect.minLength` on a string. `{ min, actual }`: lengths. */
47
+ readonly MIN_LENGTH: "Expected minimum length of {min} characters, got {actual} characters";
48
+ /** `@expect.maxLength` on a string. `{ max, actual }`: lengths. */
49
+ readonly MAX_LENGTH: "Expected maximum length of {max} characters, got {actual} characters";
50
+ /** `@expect.minLength` on an array. `{ min, actual }`: item counts. */
51
+ readonly MIN_ITEMS: "Expected minimum length of {min} items, got {actual} items";
52
+ /** `@expect.maxLength` on an array. `{ max, actual }`: item counts. */
53
+ readonly MAX_ITEMS: "Expected maximum length of {max} items, got {actual} items";
54
+ /** `@expect.array.uniqueItems`: a duplicate item (reported at its index). */
55
+ readonly UNIQUE_ITEMS: "Duplicate items are not allowed";
56
+ /** `@expect.minKeys`. `{ min, actual }`: key counts. */
57
+ readonly MIN_KEYS: "Expected at least {min} properties, got {actual}";
58
+ /** `@expect.maxKeys`. `{ max, actual }`: key counts. */
59
+ readonly MAX_KEYS: "Expected at most {max} properties, got {actual}";
60
+ /** `@expect.pattern` without a message. `{ pattern, flags }`. */
61
+ readonly PATTERN: "Value is expected to match pattern \"{pattern}\"";
62
+ /** `@expect.int`. `{ actual }`: the value. */
63
+ readonly INT: "Expected integer, got {actual}";
64
+ /** `@expect.min`. `{ min, actual }`. */
65
+ readonly MIN: "Expected minimum {min}, got {actual}";
66
+ /** `@expect.max`. `{ max, actual }`. */
67
+ readonly MAX: "Expected maximum {max}, got {actual}";
68
+ /** `@expect.exclusiveMin`. `{ min, actual }`. */
69
+ readonly EXCLUSIVE_MIN: "Expected greater than {min}, got {actual}";
70
+ /** `@expect.exclusiveMax`. `{ max, actual }`. */
71
+ readonly EXCLUSIVE_MAX: "Expected less than {max}, got {actual}";
72
+ /** `string.email`. */
73
+ readonly EMAIL: "Invalid email format.";
74
+ /** `string.phone`. */
75
+ readonly PHONE: "Invalid phone number format.";
76
+ /** `string.date`. */
77
+ readonly DATE: "Invalid date format.";
78
+ /** `string.isoDate`. */
79
+ readonly ISO_DATE: "Invalid ISO date format.";
80
+ /** `string.uuid`. */
81
+ readonly UUID: "Invalid UUID format.";
82
+ /** `string.url`. */
83
+ readonly URL: "Invalid URL format.";
84
+ /** `string.ipv4`. */
85
+ readonly IPV4: "Invalid IPv4 address.";
86
+ /** `string.ipv6`. */
87
+ readonly IPV6: "Invalid IPv6 address.";
88
+ /** `string.ip`. */
89
+ readonly IP: "Invalid IP address.";
90
+ }>;
91
+ /** A built-in validator error code (a key of {@link VALIDATOR_MESSAGES}), or `CUSTOM`. */
92
+ type TValidatorErrorCode = keyof typeof VALIDATOR_MESSAGES | 'CUSTOM';
93
+ /**
94
+ * The built-in validator error codes by name (`VALIDATOR_ERROR_CODES.MIN_LENGTH === 'MIN_LENGTH'`).
95
+ * `CUSTOM` is the code of an error a validator plugin reports without a code of its own.
96
+ */
97
+ declare const VALIDATOR_ERROR_CODES: Readonly<{
98
+ readonly URL: "URL";
99
+ readonly REQUIRED: "REQUIRED";
100
+ readonly REQUIRED_CHECKED: "REQUIRED_CHECKED";
101
+ readonly TYPE: "TYPE";
102
+ readonly TYPE_ARRAY: "TYPE_ARRAY";
103
+ readonly TYPE_OBJECT: "TYPE_OBJECT";
104
+ readonly TYPE_DECIMAL: "TYPE_DECIMAL";
105
+ readonly NOT_FINITE: "NOT_FINITE";
106
+ readonly DECIMAL_FORMAT: "DECIMAL_FORMAT";
107
+ readonly NEVER: "NEVER";
108
+ readonly LITERAL: "LITERAL";
109
+ readonly UNION: "UNION";
110
+ readonly UNION_DISCRIMINATOR: "UNION_DISCRIMINATOR";
111
+ readonly UNEXPECTED_PROPERTY: "UNEXPECTED_PROPERTY";
112
+ readonly TUPLE_LENGTH: "TUPLE_LENGTH";
113
+ readonly MIN_LENGTH: "MIN_LENGTH";
114
+ readonly MAX_LENGTH: "MAX_LENGTH";
115
+ readonly MIN_ITEMS: "MIN_ITEMS";
116
+ readonly MAX_ITEMS: "MAX_ITEMS";
117
+ readonly UNIQUE_ITEMS: "UNIQUE_ITEMS";
118
+ readonly MIN_KEYS: "MIN_KEYS";
119
+ readonly MAX_KEYS: "MAX_KEYS";
120
+ readonly PATTERN: "PATTERN";
121
+ readonly INT: "INT";
122
+ readonly MIN: "MIN";
123
+ readonly MAX: "MAX";
124
+ readonly EXCLUSIVE_MIN: "EXCLUSIVE_MIN";
125
+ readonly EXCLUSIVE_MAX: "EXCLUSIVE_MAX";
126
+ readonly EMAIL: "EMAIL";
127
+ readonly PHONE: "PHONE";
128
+ readonly DATE: "DATE";
129
+ readonly ISO_DATE: "ISO_DATE";
130
+ readonly UUID: "UUID";
131
+ readonly IPV4: "IPV4";
132
+ readonly IPV6: "IPV6";
133
+ readonly IP: "IP";
134
+ readonly CUSTOM: "CUSTOM";
135
+ }>;
136
+ /** A validation error. */
1
137
  interface TError {
138
+ /** Dot path of the value (`''`: the root). */
2
139
  path: string;
140
+ /**
141
+ * The message: the code's template filled with `params` (English by default), or the app's
142
+ * own text from an annotation (`custom: true`), translated when a translator is used.
143
+ */
3
144
  message: string;
145
+ /**
146
+ * Stable code (UPPER_SNAKE): a {@link TValidatorErrorCode} for the validator's own errors,
147
+ * a plugin's own code, or `CUSTOM`. Optional only for errors made by hand.
148
+ */
149
+ code?: TValidatorErrorCode | (string & Record<never, never>);
150
+ /** The values the code's message needs (limits, expected type, pattern, …); JSON-safe. */
151
+ params?: Record<string, unknown>;
152
+ /**
153
+ * `true` when `message` is the app's own text (an annotation's message argument,
154
+ * `@expect.message`, a plugin's message) rather than the code's template: a translator
155
+ * gets that text as the message id instead of the code.
156
+ */
157
+ custom?: boolean;
158
+ /** The errors of each union branch (a union error), in branch order. */
4
159
  details?: TError[];
5
160
  }
161
+ /**
162
+ * Translates one error: `id` is the error's `code` for a built-in message, or its message text
163
+ * for app text (`custom`, or no code). Return `undefined` to keep the current message.
164
+ */
165
+ type TValidatorTranslate = (id: string, params: Record<string, unknown>, error: TError) => string | undefined;
166
+ /**
167
+ * Fills a message template: each `{name}` becomes `params.name` (arrays: their items joined
168
+ * with `, `). A placeholder without a param stays as it is.
169
+ */
170
+ declare function formatValidatorMessage(template: string, params: Record<string, unknown> | undefined): string;
171
+ /**
172
+ * Returns `errors` with translated messages (new objects; `details` too): `translate` gets
173
+ * each error's code (or its message text, for app text — see {@link TValidatorTranslate}),
174
+ * params and the error itself. Errors it returns `undefined` for keep their message.
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * const errors = localizeErrors(validator.errors, (id, params) =>
179
+ * i18n.exists(id) ? i18n.t(id, params) : undefined
180
+ * )
181
+ * ```
182
+ */
183
+ declare function localizeErrors(errors: TError[], translate: TValidatorTranslate): TError[];
184
+ /**
185
+ * A {@link TValidatorTranslate} over a map of message templates keyed by code (and, for app
186
+ * text, by the text itself): `{name}` placeholders are filled from the error's params. Ids
187
+ * missing from the map keep their message.
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * // templates served per locale, e.g. { MIN_LENGTH: 'Mindestens {min} Zeichen', … }
192
+ * localizeErrors(errors, messagesTranslator(templates))
193
+ * ```
194
+ */
195
+ declare function messagesTranslator(messages: Record<string, string>): TValidatorTranslate;
196
+
197
+ /**
198
+ * What an error reports besides its message (see {@link Validator.error}): its code (`CUSTOM`
199
+ * when omitted), params and `custom` flag.
200
+ */
201
+ interface TErrorInfo extends Pick<TError, 'code' | 'params'> {
202
+ /**
203
+ * The message is app text (a translator gets it as the id) rather than the code's own
204
+ * message. Default: `true` without a `code`, `false` with one.
205
+ */
206
+ custom?: boolean;
207
+ }
6
208
  /**
7
209
  * A plugin function that can intercept validation.
8
210
  *
@@ -18,6 +220,11 @@ interface TValidatorOptions {
18
220
  unknownProps: 'strip' | 'ignore' | 'error';
19
221
  errorLimit: number;
20
222
  skipList?: Set<string>;
223
+ /**
224
+ * Translates the errors of a failed call (see {@link localizeErrors}) before they are
225
+ * reported (`errors`, the thrown {@link ValidatorError}).
226
+ */
227
+ translate?: TValidatorTranslate;
21
228
  }
22
229
  /** Context exposed to {@link TValidatorPlugin} functions. */
23
230
  interface TValidatorPluginContext {
@@ -101,8 +308,26 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
101
308
  protected push(name: string): void;
102
309
  protected pop(saveErrors: boolean): TError[] | null | undefined;
103
310
  protected clear(): void;
104
- protected error(message: string, path?: string, details?: TError[]): TError;
105
- /** Adds `error`, already made, to the errors of the current level (as {@link error} does). */
311
+ /**
312
+ * Reports an error at `path` (default: the current path). `info` gives its code and params;
313
+ * without it the error is app text with code `CUSTOM` (a plugin's own message).
314
+ */
315
+ protected error(message: string, path?: string, details?: TError[], info?: TErrorInfo): TError;
316
+ /**
317
+ * Reports built-in error `code`: `custom` (the app's message from an annotation) when given,
318
+ * else the code's template filled with `params`.
319
+ */
320
+ private fail;
321
+ /** Reports built-in error `code` at `path` (see {@link fail}), with `details` (a union's). */
322
+ private builtin;
323
+ /** {@link fail} of a type mismatch of `def`: its `@expect.message` replaces the message. */
324
+ private mismatch;
325
+ /** The `@meta.required` error of `def` (custom message or the type's default). */
326
+ private required;
327
+ /**
328
+ * Adds `error`, already made, to the errors of the current level (as {@link error} does);
329
+ * `true` once the level holds as many errors as the limit.
330
+ */
106
331
  private report;
107
332
  protected throw(): void;
108
333
  /**
@@ -145,6 +370,19 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
145
370
  protected get root(): T;
146
371
  protected validateAnnotatedType(def: TAtscriptAnnotatedType, value: any): boolean;
147
372
  protected validateUnion(def: TAtscriptAnnotatedType<TAtscriptTypeComplex>, value: any): boolean;
373
+ /** Reports the error of union `def` no branch matched (`details`: the branches' errors). */
374
+ private unionError;
375
+ /**
376
+ * The errors of an object union over object `value` with a shared literal discriminator (see
377
+ * {@link unionDiscriminator}), reported in place of the union error: the errors of the branch
378
+ * the value's discriminator picks, or one `UNION_DISCRIMINATOR` error at the discriminator
379
+ * when it picks none. `undefined` (nothing reported) for other unions and values.
380
+ */
381
+ private discriminatedErrors;
382
+ /** Reports `errors`, made already, until the error limit is reached. */
383
+ private reportAll;
384
+ /** Whether missing props are allowed at the current depth (the `partial` option). */
385
+ private partialHere;
148
386
  /** A union branch failed after branches of nested unions over objects did (see `unionMemo`). */
149
387
  private wasteBranch;
150
388
  /** The outcome this call recorded for union `def` over `value` at `path` (see `unionMemo`). */
@@ -181,11 +419,21 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
181
419
  protected validateNumber(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: number): boolean;
182
420
  /** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */
183
421
  protected validateNumberConstraints(meta: TMetadataMap<AtscriptMetadata>, value: number): boolean;
184
- /** Reports a failed number bound: its custom message, else `Expected <label> <bound>, got <value>`. */
185
- private numberBoundFailed;
186
422
  protected validateBoolean(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: boolean): boolean;
187
423
  /** `@meta.required` check for a boolean value (must be `true`). */
188
424
  protected validateBooleanConstraints(meta: TMetadataMap<AtscriptMetadata>, value: boolean): boolean;
425
+ /**
426
+ * `@expect.minKeys` / `maxKeys` checks for an object value, matched as `shape`: the keys the
427
+ * result keeps are counted (see {@link keptKeyCount}; `skipList`: the skip list keys here).
428
+ */
429
+ protected validateObjectConstraints(meta: TMetadataMap<AtscriptMetadata>, value: object, shape: TAtscriptAnnotatedType, skipList: Set<string> | undefined): boolean;
430
+ /**
431
+ * The keys of object `value` (matched as `shape`) the result keeps: every own key with
432
+ * `unknownProps: 'ignore'`; else (and with 'strip', and 'error', where the others are errors
433
+ * of their own) the keys `shape` declares, its pattern props match or the skip list names.
434
+ * Matched as anything other than an object type, every own key.
435
+ */
436
+ private keptKeyCount;
189
437
  }
190
438
  /** Error thrown by {@link Validator.validate} when validation fails. Contains structured error details. */
191
439
  declare class ValidatorError extends Error {
@@ -428,28 +676,6 @@ declare function coerceScalar(designType: TAtscriptTypeFinal['designType'], valu
428
676
 
429
677
  /** A JSON Schema object (draft-compatible). */
430
678
  type TJsonSchema = Record<string, any>;
431
- /**
432
- * Describes a discriminator property shared by all variants of a union.
433
- *
434
- * Returned by {@link detectDiscriminator} when a union qualifies as a
435
- * discriminated (a.k.a. tagged) union — every variant is an object that
436
- * carries the same literal-valued property with a distinct value.
437
- */
438
- type TUnionDiscriminator = {
439
- /** Name of the discriminator property shared by all variants. */
440
- propertyName: string;
441
- /** Maps the literal value of `propertyName` → variant index in `items`. */
442
- indexMapping: Record<string, number>;
443
- };
444
- /**
445
- * Detects a discriminator property across union items.
446
- *
447
- * Scans all items for object-typed members that share a common property
448
- * with distinct const/literal values. If exactly one such property exists,
449
- * it is returned as the discriminator. Returns `null` when no qualifying
450
- * property exists, or when more than one does (ambiguous).
451
- */
452
- declare function detectDiscriminator(items: TAtscriptAnnotatedType[]): TUnionDiscriminator | null;
453
679
  /**
454
680
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
455
681
  *
@@ -507,6 +733,29 @@ declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[]): {
507
733
  $defs: Record<string, TJsonSchema>;
508
734
  };
509
735
 
736
+ /**
737
+ * Describes a discriminator property shared by all variants of a union.
738
+ *
739
+ * Returned by {@link detectDiscriminator} when a union qualifies as a
740
+ * discriminated (a.k.a. tagged) union — every variant is an object that
741
+ * carries the same literal-valued property with a distinct value.
742
+ */
743
+ type TUnionDiscriminator = {
744
+ /** Name of the discriminator property shared by all variants. */
745
+ propertyName: string;
746
+ /** Maps the literal value of `propertyName` → variant index in `items`. */
747
+ indexMapping: Record<string, number>;
748
+ };
749
+ /**
750
+ * Detects a discriminator property across union items.
751
+ *
752
+ * Scans all items for object-typed members that share a common property
753
+ * with distinct const/literal values. If exactly one such property exists,
754
+ * it is returned as the discriminator. Returns `null` when no qualifying
755
+ * property exists, or when more than one does (ambiguous).
756
+ */
757
+ declare function detectDiscriminator(items: TAtscriptAnnotatedType[]): TUnionDiscriminator | null;
758
+
510
759
  /**
511
760
  * Type-safe dispatch over `TAtscriptAnnotatedType` by its `type.kind`.
512
761
  *
@@ -993,11 +1242,17 @@ declare class LayerMap<K = unknown, V = unknown> extends AnnotationMap<K, V> {
993
1242
  /** `get` read through the layers (see the file comment). */
994
1243
  private liveGet;
995
1244
  has(key: K): boolean;
1245
+ /** `has` read through the layers (see the file comment). */
1246
+ private liveHas;
996
1247
  /** An append key: the bases' values (lowest priority first), then the own ones. */
997
1248
  private append;
998
1249
  /** The effective keys: own first, then the bases' in priority order. */
999
1250
  private effectiveKeys;
1000
1251
  private liveKeys;
1252
+ /** Deletes the own value of `key`; a key hidden from the bases (`hideKey`) shows them again. */
1253
+ delete(key: K): boolean;
1254
+ /** Deletes the own values; the keys hidden from the bases (`hideKey`) show them again. */
1255
+ clear(): void;
1001
1256
  keys(): MapIterator<K>;
1002
1257
  values(): MapIterator<V>;
1003
1258
  entries(): MapIterator<[K, V]>;
@@ -1017,6 +1272,35 @@ declare function metaEmpty(m: Map<unknown, unknown>): boolean;
1017
1272
  */
1018
1273
  declare function watchLayer(m: Map<unknown, unknown>, seen?: Set<object>): boolean;
1019
1274
 
1275
+ /**
1276
+ * The annotations holding user-facing text (labels, descriptions, error messages): the arguments
1277
+ * their specs flag `userText`. Core's are known from the start ({@link CORE_USER_TEXT}); a plugin's
1278
+ * are registered by the generated modules that write them (`$ut`), or by the plugin itself
1279
+ * ({@link registerUserText}), so a translator finds them at runtime without the specs.
1280
+ */
1281
+ /** `true`: the value itself is the text; a list: those fields of the value object are. */
1282
+ type TUserTextFields = true | readonly string[];
1283
+ /**
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.
1286
+ * For plugins that write such metadata at runtime; generated modules register what they write.
1287
+ */
1288
+ declare function registerUserText(key: string, fields?: TUserTextFields): void;
1289
+ /**
1290
+ * 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.
1292
+ */
1293
+ declare function $ut(...entries: string[]): void;
1294
+ /**
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).
1299
+ */
1300
+ declare function userTextOf(key: string): TUserTextFields | undefined;
1301
+ /** Every metadata key holding user-facing text known so far (see {@link userTextOf}). */
1302
+ declare function userTextKeys(): ReadonlyMap<string, TUserTextFields>;
1303
+
1020
1304
  type TNode = TAtscriptAnnotatedType;
1021
1305
  /**
1022
1306
  * The node at `path` below `root` (see {@link child}); `NOT_READY` while it is not built, or
@@ -1121,5 +1405,5 @@ type NavPropsOf<T> = T extends {
1121
1405
  __navProps: infer N extends Record<string, unknown>;
1122
1406
  } ? N : Record<string, never>;
1123
1407
 
1124
- export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, LayerMap, SERIALIZE_VERSION, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, mergeJsonSchemas, metaEmpty, pendingStatements, registerCompiledCheck, serializeAnnotatedType, throwFeatureDisabled, watchLayer };
1125
- export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptField, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TFlattenOptions, TJsonSchema, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValueResolver };
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 };
package/dist/utils.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as statelessRegExp, B as VALIDATOR_KEYS, C as isAnnotatedTypeOfPrimitive, D as ValidatorError, E as Validator, F as watchLayer, H as boundOf, I as invalidateCompiledValidators, L as metadataWriteCount, M as $nr, N as LayerMap, O as registerCompiledCheck, P as metaEmpty, R as touched, S as isAnnotatedType, T as propAtChain, V as arrayKeyProps, _ as annotate, a as $f, b as createObjectTypeDef, c as $ps, d as appliedBlockModules, f as pendingStatements, g as enterCut, h as cutKey, i as $end, j as $ak, k as jsonSchemaPattern, l as $q, m as cutAs, n as $alias, o as $fc, r as $blk, s as $ft, t as uniqueName, u as $sh, v as createAnnotatedTypeNode, w as isPhantomType, x as defineAnnotatedType, y as createMetadataMap, z as DECIMAL_RE } from "./unique-name-hg1CyPIs.mjs";
1
+ import { $ as boundOf, A as propAtChain, B as jsonSchemaPattern, C as createAnnotatedTypeNode, D as isAnnotatedType, E as defineAnnotatedType, F as formatValidatorMessage, G as metaEmpty, H as $ak, I as localizeErrors, J as metadataWriteCount, K as watchLayer, L as messagesTranslator, M as ValidatorError, N as VALIDATOR_ERROR_CODES, O as isAnnotatedTypeOfPrimitive, P as VALIDATOR_MESSAGES, Q as arrayKeyProps, R as registerCompiledCheck, S as annotate, T as createObjectTypeDef, U as $nr, V as statelessRegExp, W as LayerMap, X as DECIMAL_RE, Y as touched, Z as VALIDATOR_KEYS, _ as pendingStatements, a as userTextOf, b as cutKey, c as $blk, d as $fc, f as $ft, g as appliedBlockModules, h as $sh, i as userTextKeys, j as Validator, k as isPhantomType, l as $end, m as $q, o as uniqueName, p as $ps, q as invalidateCompiledValidators, r as registerUserText, s as $alias, t as $ut, u as $f, w as createMetadataMap, x as enterCut, y as cutAs, z as detectDiscriminator } from "./user-text-qL59indq.mjs";
2
2
 
3
3
  //#region packages/typescript/src/runtime/coerce.ts
4
4
  /**
@@ -206,48 +206,6 @@ function isPlainObject$1(value) {
206
206
  //#endregion
207
207
  //#region packages/typescript/src/runtime/json-schema.ts
208
208
  /**
209
- * Detects a discriminator property across union items.
210
- *
211
- * Scans all items for object-typed members that share a common property
212
- * with distinct const/literal values. If exactly one such property exists,
213
- * it is returned as the discriminator. Returns `null` when no qualifying
214
- * property exists, or when more than one does (ambiguous).
215
- */ function detectDiscriminator(items) {
216
- if (items.length < 2) return null;
217
- for (const item of items) if (item.type.kind !== "object") return null;
218
- const firstObj = items[0].type;
219
- const candidates = [];
220
- for (const [propName, propType] of firstObj.props.entries()) if (propType.type.kind === "" && propType.type.value !== void 0) candidates.push(propName);
221
- let result = null;
222
- for (const candidate of candidates) {
223
- const values = /* @__PURE__ */ new Set();
224
- const indexMapping = {};
225
- let valid = true;
226
- for (let i = 0; i < items.length; i++) {
227
- const prop = items[i].type.props.get(candidate);
228
- if (!prop || prop.type.kind !== "" || prop.type.value === void 0) {
229
- valid = false;
230
- break;
231
- }
232
- const val = prop.type.value;
233
- if (values.has(val)) {
234
- valid = false;
235
- break;
236
- }
237
- values.add(val);
238
- indexMapping[String(val)] = i;
239
- }
240
- if (valid) {
241
- if (result) return null;
242
- result = {
243
- propertyName: candidate,
244
- indexMapping
245
- };
246
- }
247
- }
248
- return result;
249
- }
250
- /**
251
209
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
252
210
  *
253
211
  * Translates the atscript type structure and validation metadata
@@ -375,7 +333,7 @@ function isPlainObject$1(value) {
375
333
  defs.get(typeDef).schema = yield buildObject(def);
376
334
  building = outer;
377
335
  }
378
- return ref(typeDef);
336
+ return withKeyCounts(ref(typeDef), def.metadata);
379
337
  }
380
338
  if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
381
339
  const repeated = atRoot ? void 0 : shared.get(typeDef);
@@ -423,7 +381,11 @@ function isPlainObject$1(value) {
423
381
  return out;
424
382
  };
425
383
  const kind = def.type.kind;
426
- if (kind === "object") return yield buildObject(def);
384
+ if (kind === "object") {
385
+ const schema = yield buildObject(def);
386
+ applyKeyCounts(schema, meta);
387
+ return schema;
388
+ }
427
389
  if (kind === "array") {
428
390
  const d = def;
429
391
  const schema = {
@@ -445,6 +407,7 @@ function isPlainObject$1(value) {
445
407
  maxItems: items.length
446
408
  };
447
409
  const disc = detectDiscriminator(items);
410
+ let schema;
448
411
  if (disc) {
449
412
  const mapping = {};
450
413
  for (const [val, idx] of Object.entries(disc.indexMapping)) {
@@ -456,16 +419,19 @@ function isPlainObject$1(value) {
456
419
  ]);
457
420
  else mapping[val] = `#/oneOf/${idx}`;
458
421
  }
459
- return {
422
+ schema = {
460
423
  oneOf: built,
461
424
  discriminator: {
462
425
  propertyName: disc.propertyName,
463
426
  mapping
464
427
  }
465
428
  };
429
+ } else {
430
+ if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
431
+ schema = { anyOf: built };
466
432
  }
467
- if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
468
- return { anyOf: built };
433
+ applyKeyCounts(schema, meta);
434
+ return schema;
469
435
  }
470
436
  return forAnnotatedType(def, {
471
437
  phantom() {
@@ -706,6 +672,23 @@ function withoutUniqueItems(meta) {
706
672
  const maxLength = meta.get("expect.maxLength");
707
673
  if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
708
674
  }
675
+ /**
676
+ * `@expect.minKeys` / `maxKeys` → `minProperties` / `maxProperties` (they constrain objects
677
+ * only, so they also sit on a union's schema as they are).
678
+ */ function applyKeyCounts(schema, meta) {
679
+ const minKeys = meta.get("expect.minKeys");
680
+ if (minKeys !== void 0) schema.minProperties = boundOf(minKeys, "count");
681
+ const maxKeys = meta.get("expect.maxKeys");
682
+ if (maxKeys !== void 0) schema.maxProperties = boundOf(maxKeys, "count");
683
+ }
684
+ /** `schema` (a `$ref`) with the key counts of `meta`, if any (beside it, in an `allOf`). */ function withKeyCounts(schema, meta) {
685
+ const counts = {};
686
+ applyKeyCounts(counts, meta);
687
+ return Object.keys(counts).length > 0 ? {
688
+ allOf: [schema],
689
+ ...counts
690
+ } : schema;
691
+ }
709
692
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
710
693
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
711
694
  if (schema.type === "string") {
@@ -861,6 +844,8 @@ const UPPER_BOUNDS = new Set([
861
844
  handle.prop(key, propType);
862
845
  }
863
846
  for (const [pattern, propSchema] of Object.entries(s.patternProperties ?? {})) handle.propPattern(compilePattern(pattern), convert(propSchema));
847
+ if (typeof s.minProperties === "number") handle.annotate("expect.minKeys", { count: s.minProperties });
848
+ if (typeof s.maxProperties === "number") handle.annotate("expect.maxKeys", { count: s.maxProperties });
864
849
  return handle.$type;
865
850
  }
866
851
  if (s.type === "array") {
@@ -1025,27 +1010,31 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1025
1010
  }
1026
1011
  if (mode === "db") {
1027
1012
  const dbValue = prop.metadata.get("db.default");
1028
- if (dbValue !== void 0) {
1029
- const parsed = parseRawValue(dbValue, prop);
1030
- if (parsed !== void 0 && prop.validator({ unknownProps: "ignore" }).validate(parsed, true)) return { value: parsed };
1031
- return;
1032
- }
1013
+ if (dbValue !== void 0) return validRawValue(dbValue, prop);
1033
1014
  if (prop.metadata.has("db.default.increment")) return { value: "increment" };
1034
1015
  if (prop.metadata.has("db.default.uuid")) return { value: "uuid" };
1035
1016
  if (prop.metadata.has("db.default.now")) return { value: "now" };
1036
1017
  return;
1037
1018
  }
1038
1019
  const metaKey = mode === "default" ? "meta.default" : "meta.example";
1039
- const rawStr = prop.metadata.get(metaKey);
1040
- if (rawStr === void 0) return;
1041
- const parsed = parseRawValue(rawStr, prop);
1042
- if (parsed === void 0) return;
1043
- if (prop.validator({ unknownProps: "ignore" }).validate(parsed, true)) return { value: parsed };
1020
+ const metaValue = prop.metadata.get(metaKey);
1021
+ if (metaValue === void 0) return;
1022
+ return validRawValue(metaValue, prop);
1044
1023
  }
1045
1024
  /**
1046
- * Parses a raw annotation string into a JS value.
1047
- * Strings are returned as-is for string types; everything else goes through JSON.parse.
1025
+ * An annotation's raw value as a valid value of `prop` (see {@link parseRawValue}); a string the
1026
+ * JSON reading does not fit is tried as the string itself (a `decimal` field, `decimal | null`).
1027
+ */ function validRawValue(raw, prop) {
1028
+ const validator = prop.validator({ unknownProps: "ignore" });
1029
+ const parsed = parseRawValue(raw, prop);
1030
+ if (parsed !== void 0 && validator.validate(parsed, true)) return { value: parsed };
1031
+ if (typeof raw === "string" && parsed !== raw && validator.validate(raw, true)) return { value: raw };
1032
+ }
1033
+ /**
1034
+ * Parses a raw annotation value into a JS value: a number / boolean literal (a `value`
1035
+ * argument) as it is; a string as-is for string types, else through JSON.parse.
1048
1036
  */ function parseRawValue(raw, prop) {
1037
+ if (typeof raw !== "string") return raw;
1049
1038
  if (prop.type.kind === "" && prop.type.designType === "string") return raw;
1050
1039
  try {
1051
1040
  return JSON.parse(raw);
@@ -1060,7 +1049,8 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1060
1049
  case "number": return 0;
1061
1050
  case "boolean": return false;
1062
1051
  case "undefined": return;
1063
- case "null": return null;
1052
+ case "null":
1053
+ case "any": return null;
1064
1054
  default: return;
1065
1055
  }
1066
1056
  }
@@ -1158,7 +1148,12 @@ function* buildStructure(def, path, mode, walk) {
1158
1148
  const items = [];
1159
1149
  for (const item of type.items) items.push(yield build(item, path, mode, walk));
1160
1150
  if (items.some(stops)) return STOPPED;
1161
- const values = items.filter((item) => item !== STOPPED);
1151
+ const isAny = (i) => {
1152
+ const t = type.items[i].type;
1153
+ return t.kind === "" && t.designType === "any";
1154
+ };
1155
+ const kept = items.filter((item, i) => item !== STOPPED && !isAny(i));
1156
+ const values = kept.length > 0 ? kept : items.filter((item) => item !== STOPPED);
1162
1157
  return values.length > 0 && values.every(isPlainObject) ? Object.assign({}, ...values) : values[0];
1163
1158
  }
1164
1159
  default: throw new Error(`Unknown type kind "${type.kind}"`);
@@ -1896,4 +1891,4 @@ function* deserializeTypeDef(t, resolved) {
1896
1891
  }
1897
1892
 
1898
1893
  //#endregion
1899
- export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, LayerMap, SERIALIZE_VERSION, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, mergeJsonSchemas, metaEmpty, pendingStatements, registerCompiledCheck, serializeAnnotatedType, throwFeatureDisabled, watchLayer };
1894
+ 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/typescript",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Atscript: typescript-gen support.",
5
5
  "keywords": [
6
6
  "annotations",
@@ -63,18 +63,18 @@
63
63
  "./package.json": "./package.json"
64
64
  },
65
65
  "dependencies": {
66
- "@moostjs/event-cli": "^0.7.0",
67
- "moost": "^0.7.0"
66
+ "@moostjs/event-cli": "^0.7.2",
67
+ "moost": "^0.7.2"
68
68
  },
69
69
  "devDependencies": {
70
- "@atscript/db": "^0.1.166",
70
+ "@atscript/db": "^0.1.167",
71
71
  "@uniqu/core": "^0.1.15",
72
72
  "ajv": "8.20.0",
73
73
  "vitest": "4.1.12"
74
74
  },
75
75
  "peerDependencies": {
76
76
  "@atscript/db": "^0.1.159",
77
- "@atscript/core": "^0.2.3"
77
+ "@atscript/core": "^0.2.4"
78
78
  },
79
79
  "peerDependenciesMeta": {
80
80
  "@atscript/db": {