@asaidimu/anansi 4.0.2 → 8.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.cts CHANGED
@@ -1,10 +1,405 @@
1
- import * as _faker_js_faker from '@faker-js/faker';
2
- import { Faker } from '@faker-js/faker';
3
- import { LogicalOperator, QueryDSL, QueryFilter } from '@asaidimu/query';
4
- import { StandardSchemaV1 } from '@standard-schema/spec';
5
- import LightningFS from '@isomorphic-git/lightning-fs';
6
- import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
7
-
1
+ import "@asaidimu/query";
2
+ //#region src/schema/generated.d.ts
3
+ type ComparisonOperator = "eq" | "neq" | "lt" | "lte" | "gt" | "gte" | "in" | "nin" | "contains" | "ncontains" | "exists" | "nexists";
4
+ type Constraint = ConstraintMetadata & ConstraintUnion;
5
+ interface ConstraintGroup {
6
+ operator: LogicalOperatorEnum;
7
+ rules: ConstraintUnion[];
8
+ }
9
+ interface ConstraintMetadata {
10
+ description?: string;
11
+ name: string;
12
+ }
13
+ interface ConstraintRule {
14
+ fields?: String[];
15
+ parameters?: unknown;
16
+ predicate: string;
17
+ }
18
+ type ConstraintUnion = ConstraintRule | ConstraintGroup;
19
+ interface FieldDefinition {
20
+ default?: unknown;
21
+ deprecated?: boolean;
22
+ description?: string;
23
+ metadata?: unknown;
24
+ name: string;
25
+ nullable?: boolean;
26
+ required?: boolean;
27
+ schema?: SchemaReference | SchemaReferenceArray | InlineTypeDescriptor;
28
+ type: FieldType;
29
+ unique?: boolean;
30
+ }
31
+ type FieldType = "unknown" | "string" | "number" | "integer" | "decimal" | "boolean" | "array" | "enum" | "object" | "record" | "union" | "composite" | "geometry" | "bytes";
32
+ interface IndexCondition {
33
+ field: string;
34
+ operator: ComparisonOperator;
35
+ value: unknown;
36
+ }
37
+ interface IndexConditionGroup {
38
+ conditions: IndexConditionUnion[];
39
+ operator: LogicalOperatorEnum;
40
+ }
41
+ type IndexConditionUnion = IndexCondition | IndexConditionGroup;
42
+ interface IndexDefinition {
43
+ condition?: IndexCondition | IndexConditionGroup;
44
+ description?: string;
45
+ fields: String[];
46
+ name: string;
47
+ order?: IndexOrder;
48
+ type: IndexType;
49
+ unique?: boolean;
50
+ }
51
+ type IndexOrder = "asc" | "desc";
52
+ type IndexType = "normal" | "unique" | "primary" | "spatial" | "fulltext";
53
+ interface InlineTypeDescriptor {
54
+ type: InlineTypeKind;
55
+ values?: Unknown[];
56
+ }
57
+ type InlineTypeKind = "string" | "number" | "integer" | "decimal" | "boolean" | "bytes" | "unknown" | "record";
58
+ type LogicalOperatorEnum = "and" | "or" | "not" | "nor" | "xor" | "nand" | "xnor";
59
+ interface NestedSchemaDefinition {
60
+ concrete?: boolean;
61
+ constraints?: Record<string, Constraint>;
62
+ default?: unknown;
63
+ description?: string;
64
+ fields?: Record<string, FieldDefinition>;
65
+ indexes?: Record<string, IndexDefinition>;
66
+ metadata?: unknown;
67
+ name: string;
68
+ schema?: SchemaReference | SchemaReferenceArray | InlineTypeDescriptor;
69
+ type?: FieldType;
70
+ values?: Unknown[];
71
+ }
72
+ interface SchemaReference {
73
+ constraints?: Record<string, Constraint>;
74
+ id: string;
75
+ indexes?: Record<string, IndexDefinition>;
76
+ }
77
+ type SchemaReferenceArray = SchemaReference[];
78
+ type String = string;
79
+ type Unknown = unknown;
80
+ /** Meta-schema defining the structure of schema definitions */
81
+ interface SchemaDefinition {
82
+ constraints?: Record<string, Constraint>;
83
+ description?: string;
84
+ fields?: Record<string, FieldDefinition>;
85
+ indexes?: Record<string, IndexDefinition>;
86
+ metadata?: unknown;
87
+ name: string;
88
+ schemas?: Record<string, NestedSchemaDefinition>;
89
+ version: string;
90
+ }
91
+ //#endregion
92
+ //#region src/schema/types.d.ts
93
+ /** FieldDefinition plus Go-supported field-level enum `values`. */
94
+ type FieldDef = FieldDefinition & {
95
+ values?: unknown[];
96
+ };
97
+ /**
98
+ * Parsed literal wrapper — mirrors Go LiteralValue zero/null semantics:
99
+ * absent key → "zero", explicit JSON null → "null".
100
+ */
101
+ declare class Literal {
102
+ readonly kind: "zero" | "null" | "string" | "integer" | "float" | "boolean" | "object" | "array";
103
+ readonly value: unknown;
104
+ constructor(kind: "zero" | "null" | "string" | "integer" | "float" | "boolean" | "object" | "array", value: unknown);
105
+ isZero(): boolean;
106
+ isNull(): boolean;
107
+ static fromJSON(v: unknown): Literal;
108
+ }
109
+ declare function parseSchema(data: string | SchemaDefinition | Record<string, unknown>): SchemaDefinition;
110
+ //#endregion
111
+ //#region src/schema/compile.d.ts
112
+ /** Canonical field-type union, straight from the meta schema. */
113
+ type FieldType$2 = FieldType;
114
+ interface ResolvedEnum {
115
+ lookup: Map<string, unknown>;
116
+ complex: unknown[];
117
+ expectNumeric: boolean;
118
+ }
119
+ interface ResolvedNested {
120
+ id: string;
121
+ name: string;
122
+ effectiveType: FieldType$2;
123
+ fields: ResolvedField[];
124
+ isRecursive: boolean;
125
+ values?: unknown[];
126
+ enumDef?: ResolvedEnum;
127
+ }
128
+ interface ResolvedContainer {
129
+ itemSchema?: ResolvedNested;
130
+ itemType?: FieldType$2;
131
+ itemEnum?: ResolvedEnum;
132
+ record: boolean;
133
+ }
134
+ type ResolvedKind = {
135
+ tag: "scalar";
136
+ } | {
137
+ tag: "enum";
138
+ enumDef: ResolvedEnum;
139
+ } | {
140
+ tag: "object";
141
+ schema: ResolvedNested;
142
+ } | {
143
+ tag: "container";
144
+ c: ResolvedContainer;
145
+ } | {
146
+ tag: "union";
147
+ variants: ResolvedNested[];
148
+ } | {
149
+ tag: "composite";
150
+ parts: ResolvedNested[];
151
+ } | {
152
+ tag: "recursive";
153
+ schemaId: string;
154
+ };
155
+ interface ResolvedField {
156
+ id: string;
157
+ name: string;
158
+ path: string;
159
+ type: FieldType$2;
160
+ required: boolean;
161
+ deprecated: boolean;
162
+ unique: boolean;
163
+ nullable: boolean;
164
+ hasDefault: boolean;
165
+ kind: ResolvedKind;
166
+ }
167
+ declare class Compiler {
168
+ readonly source: SchemaDefinition;
169
+ private readonly nested;
170
+ private readonly building;
171
+ constructor(source: SchemaDefinition);
172
+ compile(): {
173
+ root: ResolvedField[];
174
+ schemas: Map<string, ResolvedNested>;
175
+ };
176
+ private compileNested;
177
+ private compileFields;
178
+ private compileField;
179
+ private resolve;
180
+ private require;
181
+ private synthesizeInline;
182
+ }
183
+ declare function buildEnum(values: unknown[], t?: FieldType$2): ResolvedEnum;
184
+ //#endregion
185
+ //#region src/schema/link.d.ts
186
+ declare const FD_NO_CHILD = 63;
187
+ declare const MAX_SCHEMA_SLOTS = 63;
188
+ declare const MULTI_STEP_BASE: number;
189
+ type FieldKind = 0 | 1 | 2 | 3;
190
+ interface FieldDescriptor {
191
+ raw: number;
192
+ dt: number;
193
+ kind: FieldKind;
194
+ schemaIdx: number;
195
+ fieldIdx: number;
196
+ childSchemaIdx: number;
197
+ terminal: boolean;
198
+ required: boolean;
199
+ hasDefault: boolean;
200
+ deprecated: boolean;
201
+ unique: boolean;
202
+ nullable: boolean;
203
+ recursive: boolean;
204
+ }
205
+ /** Internal DataPoint (side-table identity) — compiled.go:186 formula. */
206
+ declare function internalDP(fd: FieldDescriptor): number;
207
+ declare function makeDescriptor(dt: number, kind: FieldKind, schemaIdx: number, fieldIdx: number, o: {
208
+ required: boolean;
209
+ hasDefault: boolean;
210
+ deprecated: boolean;
211
+ unique: boolean;
212
+ terminal: boolean;
213
+ nullable: boolean;
214
+ recursive: boolean;
215
+ child: number;
216
+ }): FieldDescriptor;
217
+ declare function unpackDescriptor(raw: number): FieldDescriptor;
218
+ interface Slot {
219
+ fieldStart: number;
220
+ fieldCount: number;
221
+ footprint: number;
222
+ }
223
+ interface FieldMeta {
224
+ name: string;
225
+ path: string;
226
+ }
227
+ /** A linked field: everything the wire codec needs. */
228
+ interface LinkedField {
229
+ meta: FieldMeta;
230
+ fd: FieldDescriptor;
231
+ /** Canonical user-data DataPoint written by the Sparse format. */
232
+ dp: number;
233
+ /** Absolute descriptor index across all slots. */
234
+ abs: number;
235
+ /** For array_object fields: the linked child slot's fields. */
236
+ child?: LinkedSlot;
237
+ }
238
+ interface LinkedSlot {
239
+ idx: number;
240
+ slot: Slot;
241
+ fields: LinkedField[];
242
+ }
243
+ interface LinkResult {
244
+ slots: Slot[];
245
+ metas: FieldMeta[];
246
+ descriptors: FieldDescriptor[];
247
+ localOffsets: number[];
248
+ fieldTypes: FieldType$2[];
249
+ root: LinkedSlot;
250
+ /** abs index of each root-level array_object field's linked child */
251
+ childrenByPath: Map<string, LinkedSlot>;
252
+ }
253
+ /**
254
+ * Address computation (address.go computeAddress).
255
+ * steps = [(schemaIdx,fieldIdx), ...] with the LAST step being the leaf.
256
+ */
257
+ declare function addressForSteps(slots: Slot[], descriptors: FieldDescriptor[], localOffsets: number[], steps: Array<[number, number]>): number;
258
+ /** Canonical Sparse DataPoint for an addressed leaf. */
259
+ declare function userDataDP(dt: number, addr: number): number;
260
+ declare function link(source: SchemaDefinition): LinkResult;
261
+ interface ManifestField {
262
+ /** Field's declared name (relative to its own slot). */
263
+ name: string;
264
+ /** Full dotted mount path from the document root ("address.street"). */
265
+ path: string;
266
+ /** container.DataType name tag. */
267
+ t: string;
268
+ /** Canonical Sparse DataPoint. */
269
+ dp: number;
270
+ /** TypeArrayObject element fields (full mount paths). */
271
+ child?: ManifestField[];
272
+ }
273
+ /** Build the language-neutral wire manifest from linked tables. */
274
+ declare function buildManifest(l: LinkResult): ManifestField[];
275
+ //#endregion
276
+ //#region src/schema/dt.d.ts
277
+ declare const container: {
278
+ readonly TypeUnknown: 0;
279
+ readonly TypeInt: 1;
280
+ readonly TypeFloat: 2;
281
+ readonly TypeString: 3;
282
+ readonly TypeBool: 4;
283
+ readonly TypeBytes: 5;
284
+ readonly TypeGeometry: 6;
285
+ readonly TypeRecord: 7;
286
+ readonly TypeArrayUnknown: 8;
287
+ readonly TypeArrayInt: 9;
288
+ readonly TypeArrayFloat: 10;
289
+ readonly TypeArrayString: 11;
290
+ readonly TypeArrayBool: 12;
291
+ readonly TypeArrayBytes: 13;
292
+ readonly TypeArrayObject: 14;
293
+ readonly TypeArrayGeometry: 15;
294
+ };
295
+ //#endregion
296
+ //#region src/wire/packet.d.ts
297
+ declare const FLAG_COMPRESSED = 4;
298
+ declare const FLAG_ENCRYPTED = 64;
299
+ declare const FLAG_HASH_PRESENT = 128;
300
+ type EncodeKind = "auto" | "dense" | "sparse";
301
+ declare function encodeDocument(fields: ManifestField[], doc: Record<string, unknown>, fullVersion?: number, kind?: EncodeKind): Uint8Array;
302
+ declare function decodeDocument(data: Uint8Array, fields: ManifestField[]): {
303
+ version: number;
304
+ doc: Record<string, unknown>;
305
+ };
306
+ declare function encodeBatchRows(fields: ManifestField[], docs: Record<string, unknown>[], fullVersion?: number): Uint8Array;
307
+ declare function encodeBatchColumnar(fields: ManifestField[], docs: Record<string, unknown>[], fullVersion?: number): Uint8Array;
308
+ declare function decodeBatch(data: Uint8Array, fields: ManifestField[]): {
309
+ version: number;
310
+ docs: Record<string, unknown>[];
311
+ };
312
+ //#endregion
313
+ //#region src/wire/transforms.d.ts
314
+ interface EncodeTransforms {
315
+ /** Compress the packet body (flags bit 2). */
316
+ compression?: boolean;
317
+ /** Embed BLAKE3-truncated digest over the plaintext body (bit 7). */
318
+ integrity?: boolean;
319
+ /** Seal with AES-256-GCM under this 32-byte key (bit 6). */
320
+ encryptionKey?: Uint8Array;
321
+ }
322
+ interface DecodeTransforms {
323
+ decryptionKey?: Uint8Array;
324
+ }
325
+ /** Full-duplex single-document encode with transforms. */
326
+ declare function encodeAnansiPacket(fields: ManifestField[], doc: Record<string, unknown>, fullVersion?: number, opts?: EncodeTransforms & {
327
+ kind?: EncodeKind;
328
+ }): Promise<Uint8Array>;
329
+ /** Full-duplex single-document decode with transforms. */
330
+ declare function decodeAnansiPacket(data: Uint8Array, fields: ManifestField[], opts?: DecodeTransforms): Promise<{
331
+ version: number;
332
+ doc: Record<string, unknown>;
333
+ }>;
334
+ /** Batch row-oriented encode with transforms. */
335
+ declare function encodeAnansiBatchRows(fields: ManifestField[], docs: Record<string, unknown>[], fullVersion?: number, opts?: EncodeTransforms): Promise<Uint8Array>;
336
+ /**
337
+ * Columnar batch encode. Transforms are supported only on the row paths —
338
+ * columnar ENCODE parity is still pending in TS; pass empty options to emit
339
+ * a plain packet (decoding transformed columnar packets IS supported).
340
+ */
341
+ /** Columnar batch encode with transforms — full duplex. */
342
+ declare function encodeAnansiBatchColumnar(fields: ManifestField[], docs: Record<string, unknown>[], fullVersion?: number, opts?: EncodeTransforms): Promise<Uint8Array>;
343
+ /** Full-duplex batch decode (row dense/sparse and columnar) with transforms. */
344
+ declare function decodeAnansiBatch(data: Uint8Array, fields: ManifestField[], opts?: DecodeTransforms): Promise<{
345
+ version: number;
346
+ docs: Record<string, unknown>[];
347
+ }>;
348
+ //#endregion
349
+ //#region src/codec.d.ts
350
+ interface AnansiCodecOptions extends EncodeTransforms {
351
+ /** Schema version stamped into outgoing packets (0–1023). */
352
+ fullVersion?: number;
353
+ /** Force Dense/Sparse instead of the density heuristic. */
354
+ kind?: EncodeKind;
355
+ /** Key used to decrypt incoming packets (if the server encrypts). */
356
+ decryptionKey?: Uint8Array;
357
+ }
358
+ declare class AnansiCodec {
359
+ readonly linked: LinkResult;
360
+ readonly fields: ManifestField[];
361
+ readonly fullVersion: number;
362
+ private readonly kind;
363
+ private readonly enc;
364
+ private readonly dec;
365
+ private constructor();
366
+ /**
367
+ * Compile a schema definition and bind it to a codec instance.
368
+ *
369
+ * ```ts
370
+ * const codec = await AnansiCodec.create(schemaJSON); // plain
371
+ * const codec = await AnansiCodec.create(schemaJSON, {
372
+ * fullVersion: 7,
373
+ * transforms: { compression: true, integrity: true },
374
+ * });
375
+ * ```
376
+ *
377
+ * Instances are immutable; cache one per schema version (or per endpoint)
378
+ * and share it freely across requests.
379
+ */
380
+ static create(schema: string | SchemaDefinition | Record<string, unknown>, opts?: AnansiCodecOptions): Promise<AnansiCodec>;
381
+ /** Encode a single document (Dense/Sparse per configured strategy). */
382
+ encode(doc: Record<string, unknown>): Promise<Uint8Array>;
383
+ /** Decode a single-document packet. Accepts plain and transformed frames. */
384
+ decode(data: Uint8Array): Promise<{
385
+ version: number;
386
+ doc: Record<string, unknown>;
387
+ }>;
388
+ /** Encode many documents as one row-oriented batch. */
389
+ encodeBatch(docs: Record<string, unknown>[]): Promise<Uint8Array>;
390
+ /** Decode any batch packet (row dense/sparse, columnar, transformed). */
391
+ decodeBatch(data: Uint8Array): Promise<{
392
+ version: number;
393
+ docs: Record<string, unknown>[];
394
+ }>;
395
+ /**
396
+ * Columnar batch encode. Note: columnar output with transforms enabled is
397
+ * pending in TypeScript — with transforms unset this emits plain packets.
398
+ */
399
+ encodeColumnar(docs: Record<string, unknown>[]): Promise<Uint8Array>;
400
+ }
401
+ //#endregion
402
+ //#region src/validation/types/hints.d.ts
8
403
  /**
9
404
  * hints.ts
10
405
  *
@@ -15,142 +410,142 @@ import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
15
410
  * Hints for generating a file input control.
16
411
  */
17
412
  type FileHint = {
18
- type: "file";
19
- subtype: "video" | "audio" | "image" | "pdf" | "doc" | "txt";
20
- label?: string;
21
- embed?: boolean;
22
- mimes?: string | string[];
23
- preview?: boolean;
24
- size?: {
25
- max?: number;
26
- min?: number;
27
- };
28
- dimensions?: {
29
- width: number;
30
- height: number;
31
- };
32
- group?: string;
33
- ignore?: boolean;
413
+ type: "file";
414
+ subtype: "video" | "audio" | "image" | "pdf" | "doc" | "txt";
415
+ label?: string;
416
+ embed?: boolean;
417
+ mimes?: string | string[];
418
+ preview?: boolean;
419
+ size?: {
420
+ max?: number;
421
+ min?: number;
422
+ };
423
+ dimensions?: {
424
+ width: number;
425
+ height: number;
426
+ };
427
+ group?: string;
428
+ ignore?: boolean;
34
429
  };
35
430
  /**
36
431
  * Hints for generating a text-based input control.
37
432
  */
38
433
  type TextHint = {
39
- type: "text" | "email" | "tel" | "url" | "textarea";
40
- label?: string;
41
- placeholder?: string;
42
- group?: string;
43
- ignore?: boolean;
434
+ type: "text" | "email" | "tel" | "url" | "textarea";
435
+ label?: string;
436
+ placeholder?: string;
437
+ group?: string;
438
+ ignore?: boolean;
44
439
  };
45
440
  /**
46
441
  * Hints for generating a secret input control (e.g., passwords, API keys).
47
442
  */
48
443
  type SecretHint = {
49
- type: "secret";
50
- label?: string;
51
- placeholder?: string;
52
- password?: boolean;
53
- group?: string;
54
- ignore?: boolean;
444
+ type: "secret";
445
+ label?: string;
446
+ placeholder?: string;
447
+ password?: boolean;
448
+ group?: string;
449
+ ignore?: boolean;
55
450
  };
56
451
  /**
57
452
  * Hints for generating a number-based input control.
58
453
  */
59
454
  type NumberHint = {
60
- type: "number" | "range";
61
- label?: string;
62
- step?: number;
63
- group?: string;
64
- ignore?: boolean;
455
+ type: "number" | "range" | "integer" | "decimal";
456
+ label?: string;
457
+ step?: number;
458
+ group?: string;
459
+ ignore?: boolean;
65
460
  };
66
461
  /**
67
462
  * Hints for generating a boolean input control.
68
463
  */
69
464
  type BooleanHint = {
70
- type: "checkbox" | "radio";
71
- label?: string;
72
- radioLabels?: {
73
- true: string;
74
- false: string;
75
- };
76
- group?: string;
77
- ignore?: boolean;
465
+ type: "checkbox" | "radio";
466
+ label?: string;
467
+ radioLabels?: {
468
+ true: string;
469
+ false: string;
470
+ };
471
+ group?: string;
472
+ ignore?: boolean;
78
473
  };
79
474
  /**
80
475
  * Hints for generating an enum input control.
81
476
  */
82
477
  type EnumHint = {
83
- type: "select" | "radio";
84
- label?: string;
85
- group?: string;
86
- ignore?: boolean;
87
- options?: Array<{
88
- value: string | number;
89
- label: string;
90
- }>;
478
+ type: "select" | "radio";
479
+ label?: string;
480
+ group?: string;
481
+ ignore?: boolean;
482
+ options?: Array<{
483
+ value: string | number;
484
+ label: string;
485
+ }>;
91
486
  };
92
487
  /**
93
488
  * Hints for generating an array input control.
94
489
  */
95
490
  type ArrayHint = {
96
- type: "list";
97
- label?: string;
98
- itemHint?: {
99
- type: string;
100
- };
101
- group?: string;
102
- ignore?: boolean;
491
+ type: "list";
492
+ label?: string;
493
+ itemHint?: {
494
+ type: string;
495
+ };
496
+ group?: string;
497
+ ignore?: boolean;
103
498
  };
104
499
  /**
105
500
  * Hints for generating a set input control.
106
501
  */
107
502
  type SetHint = {
108
- type: "tags";
109
- label?: string;
110
- itemHint?: {
111
- type: string;
112
- };
113
- group?: string;
114
- ignore?: boolean;
503
+ type: "tags";
504
+ label?: string;
505
+ itemHint?: {
506
+ type: string;
507
+ };
508
+ group?: string;
509
+ ignore?: boolean;
115
510
  };
116
511
  /**
117
512
  * Hints for generating an object input control.
118
513
  */
119
514
  type ObjectHint = {
120
- type: "group";
121
- label?: string;
122
- collapsible?: boolean;
123
- group?: string;
124
- ignore?: boolean;
515
+ type: "group";
516
+ label?: string;
517
+ collapsible?: boolean;
518
+ group?: string;
519
+ ignore?: boolean;
125
520
  };
126
521
  /**
127
522
  * Hints for generating a date input control.
128
523
  */
129
524
  type DateHint = {
130
- type: "date" | "datetime" | "time";
131
- label?: string;
132
- placeholder?: string;
133
- min?: string;
134
- max?: string;
135
- group?: string;
136
- ignore?: boolean;
525
+ type: "date" | "datetime" | "time";
526
+ label?: string;
527
+ placeholder?: string;
528
+ min?: string;
529
+ max?: string;
530
+ group?: string;
531
+ ignore?: boolean;
137
532
  };
138
533
  /**
139
534
  * Hints for generating a code input control (e.g., for code snippets or scripts).
140
535
  */
141
536
  type CodeHint = {
142
- type: "code";
143
- label?: string;
144
- language?: string;
145
- placeholder?: string;
146
- readonly?: boolean;
147
- editorOptions?: {
148
- lineNumbers?: boolean;
149
- wordWrap?: boolean;
150
- minimap?: boolean;
151
- };
152
- group?: string;
153
- ignore?: boolean;
537
+ type: "code";
538
+ label?: string;
539
+ language?: string;
540
+ placeholder?: string;
541
+ readonly?: boolean;
542
+ editorOptions?: {
543
+ lineNumbers?: boolean;
544
+ wordWrap?: boolean;
545
+ minimap?: boolean;
546
+ };
547
+ group?: string;
548
+ ignore?: boolean;
154
549
  };
155
550
  /**
156
551
  * Union type for all possible input hints.
@@ -161,2187 +556,526 @@ type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | E
161
556
  * Defines metadata for a group of inputs at the schema level.
162
557
  */
163
558
  type GroupDefinition = {
164
- name: string;
165
- label?: string;
166
- description?: string;
559
+ name: string;
560
+ label?: string;
561
+ description?: string;
167
562
  };
168
563
  /**
169
564
  * Defines hints at the schema level, including group metadata.
170
565
  */
171
566
  type SchemaHint = {
172
- groups?: GroupDefinition[];
567
+ groups?: GroupDefinition[];
173
568
  };
174
-
569
+ //#endregion
570
+ //#region src/validation/types/schema-definition.d.ts
175
571
  /**
176
572
  * Basic field types supported by the schema system.
573
+ * Matches the `FieldTypeEnum` in the meta‑schema.
177
574
  */
178
- type FieldType = "string" | "number" | "boolean" | "array" | "set" | "enum" | "object" | "record" | "union" | "dynamic";
575
+ type FieldType$1 = "unknown" | "string" | "number" | "integer" | "decimal" | "boolean" | "array" | "set" | "enum" | "object" | "record" | "union" | "composite" | "geometry" | "bytes";
179
576
  /**
180
577
  * Index types for optimizing different query patterns.
578
+ * Matches the `IndexTypeEnum` in the meta‑schema.
181
579
  */
182
- type IndexType = "normal" | "unique" | "btree" | "hash" | "spatial" | "fulltext" | "gi" | "expression" | "composite";
580
+ type IndexType$1 = "normal" | "unique" | "primary" | "spatial" | "fulltext";
183
581
  /**
184
- * Defines a predicate function for data validation, mapped to a PredicateMap at runtime.
185
- *
186
- * @example
187
- * ```typescript
188
- * const isEmail: Predicate = ({ data, field, arguments: regex }) => {
189
- * if (field && typeof data[field] === 'string') {
190
- * return regex.test(data[field]);
191
- * }
192
- * return false;
193
- * };
194
- * ```
582
+ * Logical operators used in constraint groups and index condition groups.
583
+ * Matches the `LogicalOperatorEnum` in the meta‑schema.
195
584
  */
196
- type Predicate = <T, K extends FieldType = any>(params: {
197
- data: T;
198
- field?: keyof T;
199
- arguments: PredicateParameters<K>;
200
- }) => boolean;
585
+ type LogicalOperatorEnum$1 = "and" | "or" | "not" | "nor" | "xor" | "nand" | "xnor";
201
586
  /**
202
- * A map of predicate names to their validation functions, implemented by the runtime environment.
203
- *
204
- * @example
205
- * ```typescript
206
- * const predicateMap: PredicateMap = {
207
- * isEmail: isEmail,
208
- * isPositive: ({ data, field, arguments: min }) => {
209
- * if (field && typeof data[field] === 'number'){
210
- * return data[field] > min;
211
- * }
212
- * return false;
213
- * }
214
- * };
215
- * ```
587
+ * Comparison operators for index conditions.
588
+ * Matches the `ComparisonOperatorEnum` in the meta‑schema.
216
589
  */
217
- type PredicateMap = Record<string, Predicate>;
590
+ type ComparisonOperator$1 = "eq" | "neq" | "lt" | "lte" | "gt" | "gte" | "in" | "nin" | "contains" | "ncontains" | "exists" | "nexists";
218
591
  /**
219
- * A map of function names to generic functions, used elsewhere in the system.
220
- *
221
- * @example
222
- * ```typescript
223
- * const functionMap: FunctionMap = {
224
- * calculateTotal: (items: { price: number; quantity: number }[]) => {
225
- * return items.reduce((acc, item) => acc + item.price * item.quantity, 0);
226
- * }
227
- * };
228
- * ```
229
- */
230
- type FunctionMap = Record<string, Function>;
231
- /** @deprecated Use PredicateMap instead. */
232
- type ConstraintsMap = Record<string, Predicate>;
233
- /**
234
- * Names of supported predicates, derived from a PredicateMap.
235
- *
236
- * @example
237
- * ```typescript
238
- * type AvailablePredicates = PredicateName<typeof predicateMap>; // "isEmail" | "isPositive"
239
- * ```
592
+ * Inline type descriptor kinds.
593
+ * Matches the `InlineTypeEnum` in the meta‑schema.
240
594
  */
241
- type PredicateName<T extends PredicateMap = any> = keyof T;
595
+ type InlineTypeKind$1 = "string" | "number" | "integer" | "decimal" | "boolean" | "bytes" | "unknown" | "record";
242
596
  /**
243
- * Parameters for predicates, tailored to each field type.
244
- *
245
- * @example
246
- * ```typescript
247
- * type StringParams = PredicateParameters<"string">; // string | string[] | RegExp | { field: string }
248
- * type NumberParams = PredicateParameters<"number">; // number | number[] | { precision: number; scale?: number } | { field: string }
249
- * ```
597
+ * Sort order for index fields.
598
+ * Matches the `IndexOrderEnum` in the meta‑schema.
250
599
  */
251
- type PredicateParameters<T extends FieldType> = T extends "string" ? string | string[] | RegExp | {
252
- field: string;
253
- } : T extends "number" ? number | number[] | {
254
- precision: number;
255
- scale?: number;
256
- } | {
257
- field: string;
258
- } : T extends "boolean" ? boolean : T extends "array" | "set" ? number | {
259
- minItems: number;
260
- maxItems: number;
261
- } : T extends "enum" ? string[] | number[] | {
262
- field: string;
263
- } : T extends "object" ? {
264
- schema: Record<string, unknown>;
265
- } : T extends "record" ? Record<string, unknown> : T extends "dynamic" ? any : never;
266
- /** @deprecated Use PredicateParameters instead. */
267
- type ConstraintParameters<T extends FieldType> = PredicateParameters<T>;
600
+ type IndexOrder$1 = "asc" | "desc";
268
601
  /**
269
- * Defines a constraint on a field or schema, using a predicate for validation.
270
- *
271
- * @example
272
- * ```typescript
273
- * const emailConstraint: Constraint<"string"> = {
274
- * name: "email",
275
- * predicate: "isEmail",
276
- * parameters: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
277
- * errorMessage: "Must be a valid email address."
278
- * };
279
- * ```
602
+ * Shared metadata properties for most schema components.
280
603
  */
281
- type Constraint<T extends FieldType> = {
282
- type?: "schema";
283
- predicate: string;
284
- field?: keyof any;
285
- parameters?: PredicateParameters<T>;
286
- name: string;
287
- description?: string;
288
- errorMessage?: string;
289
- };
290
- /**
291
- * Groups multiple constraints with a logical operator for complex validation logic.
292
- *
293
- * @example
294
- * ```typescript
295
- * const compositeConstraint: ConstraintGroup<"number"> = {
296
- * name: "positiveAndLessThan100",
297
- * operator: "and",
298
- * rules: [
299
- * { name: "positive", predicate: "isPositive", parameters: 0 },
300
- * { name: "lessThan100", predicate: "isLessThan", parameters: 100 }
301
- * ]
302
- * };
303
- * ```
304
- */
305
- interface ConstraintGroup<T extends FieldType> {
306
- name: string;
307
- operator: LogicalOperator;
308
- rules: Array<Constraint<T> | ConstraintGroup<T>>;
604
+ interface BaseMetadata extends Record<string, any> {
605
+ description?: string;
606
+ /** Arbitrary key‑value pairs for implementation‑specific metadata. */
607
+ metadata?: Record<string, unknown>;
309
608
  }
310
609
  /**
311
- * Collection of constraints or groups applied at the schema or nested level.
312
- *
313
- * @example
314
- * ```typescript
315
- * const schemaConstraints: SchemaConstraint<"number"> = [
316
- * { name: "positive", predicate: "isPositive", parameters: 0 },
317
- * compositeConstraint
318
- * ];
319
- * ```
610
+ * Metadata for components that also have a human‑readable name.
320
611
  */
321
- type SchemaConstraint<T extends FieldType> = Array<Constraint<T> | ConstraintGroup<T>>;
322
- /** Reference to a nested schema (mini-SchemaDefinition) with optional overrides. */
323
- interface FieldSchema {
324
- id: string;
325
- constraints?: SchemaConstraint<any>;
326
- indexes?: IndexDefinition[];
612
+ interface NamedMetadata extends BaseMetadata {
613
+ name: string;
327
614
  }
328
615
  /**
329
- * Defines a field within a schema, including its type, constraints, and nesting.
330
- *
331
- * @example
332
- * ```typescript
333
- * const ageField: FieldDefinition<number> = {
334
- * name: "age",
335
- * type: "number",
336
- * required: true,
337
- * constraints: [{ name: "positive", predicate: "isPositive", parameters: 0 }],
338
- * default: 25,
339
- * hint: {
340
- * input: {
341
- * min : 0,
342
- * max : 100
343
- * }
344
- * }
345
- * };
346
- * ```
616
+ * Reference to another schema (e.g., for `object`, `array`, `union` types).
617
+ * May include local overrides for indexes and constraints.
347
618
  */
348
- interface FieldDefinition<T> {
349
- name: string;
350
- type: FieldType;
351
- required?: boolean;
352
- constraints?: Array<Constraint<any> | ConstraintGroup<any>>;
353
- default?: T;
354
- /** For type 'enum', specifies the allowed values. */
355
- values?: Array<string | number>;
356
- /** For type 'union', specifies the array of allowed schemas.
357
- * For type 'object' specifies the schema of the object
358
- * */
359
- schema?: FieldSchema | Array<FieldSchema>;
360
- itemsType?: FieldType;
361
- nestedSchema?: FieldSchema;
362
- deprecated?: boolean;
363
- reference?: {
364
- schema: string;
365
- field: string;
366
- };
367
- description?: string;
368
- unique?: boolean;
369
- hint?: {
370
- input: InputHint;
371
- };
619
+ interface SchemaReference$1 extends BaseMetadata {
620
+ id: string;
621
+ indexes?: Record<string, IndexDefinition$1>;
622
+ constraints?: Record<string, Constraint$1 | ConstraintGroup$1>;
372
623
  }
373
624
  /**
374
- * Condition for partial indexes, allowing conditional indexing based on field values.
375
- *
376
- * @example
377
- * ```typescript
378
- * const activeCondition: PartialIndexCondition = {
379
- * operator: "and",
380
- * field: "isActive",
381
- * value: true
382
- * };
383
- * ```
625
+ * Inline type descriptor used when a simple type is defined directly
626
+ * without a separate schema reference.
384
627
  */
385
- interface PartialIndexCondition {
386
- operator: LogicalOperator;
387
- field: string;
388
- value?: any;
389
- conditions?: PartialIndexCondition[];
628
+ interface InlineTypeDescriptor$1 extends BaseMetadata {
629
+ type: InlineTypeKind$1;
630
+ values?: Array<string | number>;
390
631
  }
391
632
  /**
392
- * Defines an index for optimizing queries or enforcing uniqueness.
393
- *
394
- * @example
395
- * ```typescript
396
- * const nameIndex: IndexDefinition = {
397
- * name: "nameIndex",
398
- * fields: ["firstName", "lastName"],
399
- * type: "composite",
400
- * unique: true
401
- * };
402
- * ```
403
- */
404
- interface IndexDefinition {
405
- fields: string[];
406
- type: IndexType;
407
- unique?: boolean;
408
- partial?: PartialIndexCondition;
409
- description?: string;
410
- order?: "asc" | "desc";
411
- name: string;
633
+ * Defines a field within a schema.
634
+ * Matches the `Field` schema in the meta‑schema.
635
+ */
636
+ interface FieldDefinition$1<T = unknown> extends NamedMetadata {
637
+ type: FieldType$1;
638
+ required?: boolean;
639
+ nullable?: boolean;
640
+ deprecated?: boolean;
641
+ unique?: boolean;
642
+ default?: T;
643
+ /**
644
+ * The `schema` property is used for complex types:
645
+ * - For `array`/`set`: a single `SchemaReference` pointing to the item schema.
646
+ * - For `object`: a single `SchemaReference` pointing to the object schema.
647
+ * - For `union`: an array of `SchemaReference`s.
648
+ * - For `enum`: an `InlineTypeDescriptor` (or `values` on the field itself).
649
+ * - For primitive overrides: an `InlineTypeDescriptor`.
650
+ */
651
+ schema?: SchemaReference$1 | SchemaReference$1[] | InlineTypeDescriptor$1;
652
+ /** @deprecated Use `schema` instead. */
653
+ nestedSchema?: SchemaReference$1;
654
+ hint?: {
655
+ input: InputHint;
656
+ };
412
657
  }
413
658
  /**
414
- * Defines a reusable nested schema structure.
415
- * This can represent either a complex object with defined fields, or a direct primitive literal (string, number, boolean).
416
- * Nested schemas are stored in the `nestedSchemas` map of a `SchemaDefinition` and referenced by their `id`.
417
- * They facilitate schema reusability, modularity, and the definition of polymorphic structures.
418
- *
419
- */
420
- type NestedSchemaDefinition<T = any> = {
421
- /**
422
- * The unique name or identifier of the nested schema within the parent schema's `nestedSchemas` map.
423
- * This `name` is used by `FieldDefinition.schema.id` to reference this nested schema.
424
- * @example "AddressSchema" or "EmailString"
425
- */
426
- name: string;
427
- /**
428
- * A clear and concise description of the nested schema's purpose, structure, or expected data.
429
- * This is crucial for documentation and understanding the schema's intent.
430
- */
431
- description?: string;
432
- /**
433
- * Defines database indexes for the fields within this nested schema.
434
- * This is primarily applicable when `concrete` is `true`, indicating that the schema
435
- * maps directly to a persistent data store table. Indexes help optimize data retrieval.
436
- */
437
- indexes?: IndexDefinition[];
438
- /**
439
- * Optional generic metadata associated with the structured schema.
440
- * This can store any additional information relevant to tooling, UI generation,
441
- * or specific domain requirements that are not covered by other properties.
442
- * @example `{ graphqlType: "Address", apiEndpoint: "/api/addresses" }`
443
- */
444
- metadata?: Record<string, any>;
445
- } & ({
446
- /**
447
- * Optional constraints for additional validation rules that apply to the entire structured schema.
448
- * These constraints provide an extra layer of data integrity beyond basic type checking.
449
- * They are less strictly necessary when using discriminated field sets (`fields` as an array),
450
- * as much of the variant logic can be enforced structurally through the `when` clauses.
451
- */
452
- constraints?: SchemaConstraint<any>;
453
- /**
454
- * Indicates whether this schema represents a standalone entity (`true`) or is embedded (`false`).
455
- * - When `true` (`concrete: true`), the schema is treated as a distinct, fixed-structure entity,
456
- * often suitable for direct mapping to RDBMS tables. In this case, `fields` *must* be a
457
- * `Record<string, FieldDefinition<any>>` to ensure a consistent, non-polymorphic structure.
458
- * - When `false` (`concrete: false` or omitted), the schema is considered embedded or polymorphic.
459
- * `fields` can be either a `Record<string, FieldDefinition<any>>` (for a fixed embedded object)
460
- * or an `Array<{ fields: Record<string, FieldDefinition<any>>; when?: { field: string; value: any } }>`,
461
- * allowing discriminated field sets based on a specific field's value (e.g., a 'type' field).
462
- * The array form enables defining variants within a single schema without imposing strict concrete
463
- * constraints, but is not supported for `concrete: true` schemas to maintain simplicity in RDBMS table mappings.
464
- * @default false
465
- */
466
- concrete?: boolean;
467
- /**
468
- * Defines the fields (properties) that constitute this nested schema.
469
- * The structure of `fields` depends on the `concrete` property:
470
- * - If `concrete` is `true`, `fields` must be a `Record<string, FieldDefinition<any>>`
471
- * to define a fixed set of named fields (e.g., for a database table).
472
- * - If `concrete` is `false` (or omitted), `fields` can be:
473
- * - A `Record<string, FieldDefinition<any>>` for a simple, embedded object.
474
- * - An `Array<{ fields: Record<string, FieldDefinition<any>>; when?: { field: string; value: any } }>`
475
- * to define a discriminated union or polymorphic structure. Each object in the array defines a
476
- * set of fields that apply `when` a specified `field` (within this schema's own fields)
477
- * has a particular `value`. This allows for variant-specific fields.
478
- */
479
- fields: Record<string, FieldDefinition<any>> | Array<{
480
- /**
481
- * A set of field definitions that apply when the `when` condition is met.
482
- */
483
- fields: Record<string, FieldDefinition<any>>;
484
- /**
485
- * An optional condition that makes this set of fields active.
486
- * This object specifies a `field` (its name within this schema) and a `value`.
487
- * When the specified `field` in the data matches this `value`, these `fields` are considered active.
488
- * Used for discriminated unions or polymorphic structures (e.g., `when: { field: "type", value: "car" }`).
489
- * If `when` is omitted for an entry in the array, those fields are always present in the union's base,
490
- * or it acts as a fallback if no other `when` condition matches.
491
- */
492
- when?: {
493
- field: string;
494
- value: any;
495
- };
496
- }>;
497
- } | (Pick<FieldDefinition<T>, "name" | "default" | "schema" | "itemsType" | "constraints"> & {
498
- /**
499
- * The basic primitive type that this literal schema represents.
500
- */
501
- type: "string" | "number" | "boolean" | "array" | "set" | "enum" | "record";
502
- }));
503
- /**
504
- * Defines a complete schema, intended as an atomic unit within a larger domain model.
505
- *
506
- * @example
507
- * ```typescript
508
- * const userSchema: SchemaDefinition = {
509
- * name: "user",
510
- * version: "1.0.0",
511
- * fields: {
512
- * id: { name: "id", type: "string", required: true },
513
- * name: { name: "name", type: "string" },
514
- * address: { name: "address", type: "object", schema: { id: "address" } }
515
- * },
516
- * nestedSchemas: {
517
- * address: addressSchema
518
- * },
519
- * indexes: [{ name: "nameIndex", fields: ["name"], type: "normal" }],
520
- * mock: (faker) => {
521
- * return {
522
- * id: faker.string.uuid(),
523
- * name: faker.person.fullName(),
524
- * address: {
525
- * street: faker.location.streetAddress(),
526
- * city: faker.location.city(),
527
- * zip: faker.location.zipCode()
528
- * }
529
- * };
530
- * }
531
- * };
532
- * ```
659
+ * A single index condition (leaf node).
660
+ * Matches the `IndexCondition` schema in the meta‑schema.
533
661
  */
534
- interface SchemaDefinition {
535
- name: string;
536
- version: string;
537
- description?: string;
538
- fields: Record<string, FieldDefinition<any>>;
539
- /** Reusable nested schema definitions, now as mini-SchemaDefinitions. */
540
- nestedSchemas?: Record<string, NestedSchemaDefinition<any>>;
541
- indexes?: IndexDefinition[];
542
- constraints?: SchemaConstraint<any>;
543
- metadata?: Record<string, any>;
544
- /** @deprecated Use dependencies in DomainModel instead. */
545
- dependencies?: string[];
546
- migrations?: Array<Migration<any>>;
547
- hint?: SchemaHint;
548
- mock?: <T>(faker: typeof _faker_js_faker) => Generator<T, void, unknown>;
662
+ interface IndexCondition$1 extends BaseMetadata {
663
+ operator: ComparisonOperator$1;
664
+ field: string;
665
+ value: unknown;
549
666
  }
550
667
  /**
551
- * Defines a change that can be made to a schema during migration.
552
- * Updated to support the new NestedSchemaDefinition structure.
553
- *
554
- * @example
555
- * ```typescript
556
- * const addEmailField: SchemaChange<string> = {
557
- * type: "addField",
558
- * id: "email",
559
- * definition: { name: "email", type: "string" }
560
- * };
561
- *
562
- * const modifyAddressSchema: SchemaChange<any> = {
563
- * type: "modifyNestedSchema",
564
- * id: "address",
565
- * changes: {
566
- * fields: {
567
- * country: {name: "country", type: "string"}
568
- * }
569
- * }
570
- * }
571
- * ```
668
+ * A group of index conditions combined with a logical operator.
669
+ * Matches the `IndexConditionGroup` schema in the meta‑schema.
572
670
  */
573
- type SchemaChange<T> = {
574
- type: "modifyProperty";
575
- id: keyof Omit<SchemaDefinition, "fields" | "indexes" | "constraints" | "nestedSchemas">;
576
- changes: Partial<Omit<SchemaDefinition, "fields" | "indexes" | "constraints" | "nestedSchemas">>;
577
- } | {
578
- type: "addField";
579
- id: string;
580
- definition: FieldDefinition<T>;
581
- } | {
582
- type: "removeField";
583
- id: string;
584
- } | {
585
- type: "modifyField";
586
- id: string;
587
- changes: Partial<FieldDefinition<T>>;
588
- nestedSchemaChanges?: {
589
- id?: string;
590
- constraints?: SchemaConstraint<any>;
591
- indexes?: IndexDefinition[];
592
- };
593
- } | {
594
- type: "addIndex";
595
- definition: IndexDefinition;
596
- } | {
597
- type: "removeIndex";
598
- name: string;
599
- } | {
600
- type: "modifyIndex";
601
- name: string;
602
- changes: Partial<IndexDefinition>;
603
- } | {
604
- type: "addConstraint";
605
- constraint: Constraint<any> | ConstraintGroup<any>;
606
- } | {
607
- type: "removeConstraint";
608
- name: string;
609
- } | {
610
- type: "modifyConstraint";
611
- name: string;
612
- changes: Partial<SchemaConstraint<any> | Constraint<any>>;
613
- } | {
614
- type: "deprecateField";
615
- id: string;
616
- } | {
617
- type: "addNestedSchema";
618
- id: string;
619
- definition: NestedSchemaDefinition<any>;
620
- } | {
621
- type: "removeNestedSchema";
622
- id: string;
623
- } | {
624
- type: "modifyNestedSchema";
625
- id: string;
626
- changes: Partial<NestedSchemaDefinition<any>>;
627
- };
671
+ interface IndexConditionGroup$1 extends BaseMetadata {
672
+ operator: LogicalOperatorEnum$1;
673
+ conditions: Array<IndexCondition$1 | IndexConditionGroup$1>;
674
+ }
628
675
  /**
629
- * Defines a transform function for data migration between schema versions.
630
- *
631
- * @example
632
- * ```typescript
633
- * const transformEmail: TransformFunction<{ oldEmail: string }, { email: string }> = (data) => {
634
- * return { email: data.oldEmail };
635
- * };
636
- * ```
637
- */
638
- type TransformFunction<Initial, Next> = (data: Initial) => Next | Promise<Next>;
676
+ * Defines an index for optimizing queries or enforcing uniqueness.
677
+ * Matches the `Index` schema in the meta‑schema.
678
+ */
679
+ interface IndexDefinition$1 extends NamedMetadata {
680
+ unique?: boolean;
681
+ type: IndexType$1;
682
+ fields: string[];
683
+ order?: IndexOrder$1;
684
+ condition?: IndexCondition$1 | IndexConditionGroup$1;
685
+ }
639
686
  /**
640
- * Represents a pair of transformations for bidirectional data migration.
641
- *
642
- * @example
643
- * ```typescript
644
- * const emailMigration: DataTransform<{ oldEmail: string }, { email: string }> = {
645
- * forward: transformEmail,
646
- * backward: (data) => ({ oldEmail: data.email })
647
- * };
648
- * ```
687
+ * A predicate‑based constraint rule.
688
+ * Matches the `ConstraintRule` schema in the meta‑schema.
649
689
  */
650
- interface DataTransform<Initial, Next> {
651
- forward: TransformFunction<Initial, Next>;
652
- backward: TransformFunction<Next, Initial>;
690
+ interface ConstraintRule$1 extends NamedMetadata {
691
+ predicate: string;
692
+ parameters?: unknown;
693
+ fields?: string[];
653
694
  }
654
695
  /**
655
- * Defines a migration, consisting of schema changes and data transforms.
656
- *
657
- * @example
658
- * ```typescript
659
- * const emailMigration: Migration<string> = {
660
- * id: "emailMigration",
661
- * schemaVersion: "2.0.0",
662
- * changes: [addEmailField],
663
- * description: "Adds email field",
664
- * status: "pending",
665
- * transform: emailMigration,
666
- * createdAt: new Date().toISOString(),
667
- * checksum: "someChecksum"
668
- * };
669
- * ```
696
+ * A group of constraints combined with a logical operator.
697
+ * Matches the `ConstraintGroup` schema in the meta‑schema.
670
698
  */
671
- interface Migration<T> {
672
- id: string;
673
- schemaVersion: string;
674
- changes: SchemaChange<T>[];
675
- description: string;
676
- status: "pending" | "applied" | "failed";
677
- rollback?: SchemaChange<T>[];
678
- transform: string | DataTransform<any, any>;
679
- createdAt: string;
680
- /** @deprecated Use dependencies in DomainModel instead. */
681
- dependencies?: string[];
682
- checksum: string;
699
+ interface ConstraintGroup$1 extends NamedMetadata {
700
+ operator: LogicalOperatorEnum$1;
701
+ rules: Array<ConstraintRule$1 | ConstraintGroup$1>;
683
702
  }
684
703
  /**
685
- * Generator type for mock data functions (used with Faker).
686
- *
687
- * @example
688
- * ```typescript
689
- * const mockGenerator: Generator<{ name: string }, void, unknown> = function* (faker) {
690
- * yield { name: faker.person.fullName() };
691
- * };
692
- * ```
704
+ * A constraint can be either a single rule or a logical group of rules.
705
+ * Matches the `Constraint` composite in the meta‑schema.
693
706
  */
694
- type Generator<T, TReturn, TNext> = Iterator<T, TReturn, TNext>;
695
-
707
+ type Constraint$1 = ConstraintRule$1 | ConstraintGroup$1;
696
708
  /**
697
- * Defines the interface for a migration engine.
698
- * The migration engine is responsible for applying, rolling back, and tracking schema migrations.
709
+ * A reusable nested schema definition.
710
+ * Matches the `NestedSchema` schema in the meta‑schema.
711
+ *
712
+ * A nested schema can be either:
713
+ * - An **object schema** (with `fields`, and optionally `indexes`, `constraints`),
714
+ * - A **primitive type alias** (with `type` and optionally `default`, `values`, `schema`).
699
715
  */
700
- interface MigrationEngineInterface<T> {
701
- /**
702
- * Applies all pending migrations.
703
- * @returns A promise that resolves when all migrations are applied.
704
- */
705
- applyMigrations(): Promise<void>;
706
- /**
707
- * Rolls back the most recently applied migration.
708
- * @returns A promise that resolves when the migration is rolled back.
709
- */
710
- rollbackLastMigration(): Promise<void>;
711
- /**
712
- * Rolls back all migrations to a specific version.
713
- * @param targetVersion The version to roll back to.
714
- * @returns A promise that resolves when the rollback is complete.
715
- */
716
- rollbackToVersion(targetVersion: string): Promise<void>;
717
- /**
718
- * Returns the current schema version.
719
- * @returns A promise that resolves to the current schema version.
720
- */
721
- getCurrentVersion(): Promise<string>;
722
- /**
723
- * Returns the list of applied migrations.
724
- * @returns A promise that resolves to an array of applied migrations.
725
- */
726
- getAppliedMigrations(): Promise<Migration<T>[]>;
727
- /**
728
- * Returns the list of pending migrations.
729
- * @returns A promise that resolves to an array of pending migrations.
730
- */
731
- getPendingMigrations(): Promise<Migration<T>[]>;
732
- /**
733
- * Validates the integrity of all migrations.
734
- * @returns A promise that resolves to `true` if all migrations are valid, otherwise `false`.
735
- */
736
- validateMigrations(): Promise<boolean>;
737
- /**
738
- * Adds a new migration to the migration registry.
739
- * @param migration The migration to add.
740
- * @returns A promise that resolves when the migration is added.
741
- */
742
- addMigration(migration: Migration<T>): Promise<void>;
743
- /**
744
- * Removes a migration from the migration registry.
745
- * @param migrationId The ID of the migration to remove.
746
- * @returns A promise that resolves when the migration is removed.
747
- */
748
- removeMigration(migrationId: string): Promise<void>;
716
+ type NestedSchemaDefinition$1<T = unknown> = NamedMetadata & {
717
+ indexes?: Record<string, IndexDefinition$1>;
718
+ constraints?: Record<string, Constraint$1>;
719
+ } & ({
720
+ /**
721
+ * Object schema: defines the fields of the nested object.
722
+ * The `fields` record maps field IDs to `FieldDefinition`s.
723
+ */
724
+ fields: Record<string, FieldDefinition$1>;
725
+ } | {
726
+ /**
727
+ * Primitive type alias.
728
+ * The `type` must not be `"object"``.
729
+ */
730
+ type: Exclude<FieldType$1, "object">;
731
+ default?: T;
732
+ values?: Array<string | number>;
733
+ schema?: SchemaReference$1 | SchemaReference$1[];
734
+ });
735
+ /**
736
+ * Defines a complete schema.
737
+ * Matches the top‑level `Schema` structure in the meta‑schema.
738
+ */
739
+ interface SchemaDefinition$1 extends NamedMetadata {
740
+ version: string;
741
+ /** Map of field IDs to field definitions. */
742
+ fields: Record<string, FieldDefinition$1>;
743
+ /** Map of index IDs to index definitions. */
744
+ indexes?: Record<string, IndexDefinition$1>;
745
+ /** Map of constraint IDs to constraint definitions. */
746
+ constraints?: Record<string, Constraint$1>;
747
+ /** Map of nested schema IDs to nested schema definitions. */
748
+ schemas?: Record<string, NestedSchemaDefinition$1>;
749
+ /**
750
+ * Optional data migration definitions.
751
+ * @extension
752
+ */
753
+ migrations?: Array<Migration>;
754
+ /**
755
+ * UI/input hints.
756
+ * @extension
757
+ */
758
+ hints?: SchemaHint;
759
+ /**
760
+ * Mock data generator.
761
+ * @extension
762
+ */
763
+ mock?: <T>(
764
+ /** Lazy-typed: @faker-js/faker is a dev-only peer; kept out of bundle. */
765
+ faker: unknown) => Generator<T, void, unknown>;
766
+ /**
767
+ * Domain dependencies.
768
+ * @extension
769
+ */
770
+ dependencies?: string[];
771
+ /** @deprecated Use `schemas` instead. */
772
+ nestedSchemas?: Record<string, NestedSchemaDefinition$1>;
773
+ /** @deprecated Use top‑level `indexes`, `constraints`, `schemas` directly. */
774
+ registry?: {
775
+ schemas?: Record<string, NestedSchemaDefinition$1>;
776
+ constraints?: Record<string, Constraint$1>;
777
+ indexes?: Record<string, IndexDefinition$1>;
778
+ };
749
779
  }
750
-
751
- /**
752
- * @module JsonPatch
753
- * @description A library for creating and applying JSON Patch operations according to RFC 6902
754
- * @note This implementation includes an additional non-standard 'removeValue' operation that removes all instances of a value from an array.
755
- */
756
-
757
780
  /**
758
- * Represents a single JSON Patch operation as defined in RFC 6902
759
- */
760
- type PatchOperation = {
761
- op: "add";
762
- path: string;
763
- value: any;
781
+ * Implements Partial Update Semantics:
782
+ * - `undefined`: No change to the property.
783
+ * - `null`: Clear/remove the property (if allowed by NonNullable).
784
+ * - `value`: Set the property to the provided value.
785
+ */
786
+ type Patch<T, NonNullable extends keyof T = never> = { [K in keyof T]?: K extends NonNullable ? T[K] : T[K] | null; };
787
+ type FieldPatch = Patch<FieldDefinition$1, "name" | "type">;
788
+ type ConstraintPatch = Patch<Constraint$1, "name">;
789
+ type IndexPatch = Patch<IndexDefinition$1, "name">;
790
+ type SchemaChange = {
791
+ type: "modifyProperty";
792
+ id: keyof NamedMetadata | "version";
793
+ value: any;
764
794
  } | {
765
- op: "remove";
766
- path: string;
795
+ type: "addField";
796
+ id: string;
797
+ definition: FieldDefinition$1;
767
798
  } | {
768
- op: "removeValue";
769
- path: string;
770
- value: any;
799
+ type: "removeField";
800
+ id: string;
771
801
  } | {
772
- op: "replace";
773
- path: string;
774
- value: any;
802
+ type: "modifyField";
803
+ id: string;
804
+ changes: FieldPatch;
775
805
  } | {
776
- op: "test";
777
- path: string;
778
- value: any;
806
+ type: "addIndex";
807
+ id: string;
808
+ definition: IndexDefinition$1;
779
809
  } | {
780
- op: "copy";
781
- from: string;
782
- path: string;
810
+ type: "removeIndex";
811
+ id: string;
783
812
  } | {
784
- op: "move";
785
- from: string;
786
- path: string;
787
- };
788
- /**
789
- * Error thrown when JSON Patch operations fail
790
- * @extends Error
791
- */
792
- declare class JsonPatchError extends Error {
793
- operation?: PatchOperation | undefined;
794
- constructor(message: string, operation?: PatchOperation | undefined);
795
- }
796
- /**
797
- * Converts a path string from dot notation to JSON Pointer notation
798
- * @param {string} path - Path in either dot notation (e.g., 'a.b.c') or slash notation (e.g., '/a/b/c')
799
- * @returns {string} Path in JSON Pointer notation
800
- * @throws {JsonPatchError} If the path is invalid
801
- */
802
- declare function normalizePath(path: string): string;
803
- /**
804
- * Applies a sequence of JSON Patch operations to an object
805
- * @template T
806
- * @param {T} target - Target object
807
- * @param {PatchOperation[]} patches - Array of patch operations
808
- * @returns {T} Modified object
809
- * @throws {JsonPatchError} If any operation fails
810
- */
811
- declare function applyPatch<T>(target: T, patches: PatchOperation[]): T;
812
- /**
813
- * Creates a sequence of JSON Patch operations that transform one object into another
814
- * @param {any} oldObj - Source object
815
- * @param {any} newObj - Target object
816
- * @returns {PatchOperation[]} Array of patch operations
817
- */
818
- declare function createPatch(oldObj: any, newObj: any): PatchOperation[];
819
- /**
820
- * Converts a schema change to JSON Patch operations
821
- * @param change The schema change to convert
822
- * @param schema The current schema definition
823
- * @returns Array of JSON Patch operations
824
- */
825
- declare function schemaChangeToPatch(change: SchemaChange<any>, schema: SchemaDefinition): PatchOperation[];
826
-
827
- /**
828
- * Schema event types.
829
- */
830
- type SchemaEventType = SchemaEvent["type"];
831
- /**
832
- * Represents a schema event.
833
- */
834
- type SchemaEvent = {
835
- type: "migration:started";
836
- description: string;
837
- currentVersion: string;
838
- changes: SchemaChange<any>[];
839
- dryRun?: boolean;
813
+ type: "modifyIndex";
814
+ id: string;
815
+ changes: IndexPatch;
816
+ } | {
817
+ type: "addConstraint";
818
+ id: string;
819
+ constraint: Constraint$1;
840
820
  } | {
841
- type: "migration:committed";
842
- currentVersion: string;
843
- previousVersion: string;
844
- changes: SchemaChange<any>[];
845
- dryRun?: boolean;
821
+ type: "removeConstraint";
822
+ id: string;
846
823
  } | {
847
- type: "migration:rollingBack";
848
- currentVersion: string;
849
- targetVersion: string;
850
- changes: SchemaChange<any>[];
851
- dryRun?: boolean;
824
+ type: "modifyConstraint";
825
+ id: string;
826
+ changes: ConstraintPatch;
852
827
  } | {
853
- type: "migration:rolledBack";
854
- currentVersion: string;
855
- previousVersion: string;
856
- changes: SchemaChange<any>[];
857
- dryRun?: boolean;
828
+ type: "addSchema";
829
+ id: string;
830
+ definition: NestedSchemaDefinition$1;
858
831
  } | {
859
- type: "migration:ended";
860
- currentVersion: string;
861
- status: "committed" | "rolledBack";
832
+ type: "removeSchema";
833
+ id: string;
834
+ } | {
835
+ type: "modifySchema";
836
+ id: string;
837
+ changes: Array<SchemaChange>;
862
838
  };
863
- /**
864
- * Schema interface for managing schema evolution.
865
- * @template T The type of data associated with the schema.
866
- */
867
- interface Schema<T = any> {
868
- /**
869
- * Subscribes to schema events. The listener will be called for each event.
870
- * @param event The type of schema event to subscribe to.
871
- * @param listener The listener function that receives the schema event.
872
- * @returns A function that, when called, unsubscribes the listener.
873
- */
874
- subscribe(event: SchemaEventType, listener: (event: SchemaEvent) => void): () => void;
875
- /**
876
- * Returns a read-only copy of the schema definition.
877
- * @returns A read-only version of the current schema definition.
878
- */
879
- definition(): Readonly<SchemaDefinition>;
880
- /**
881
- * Returns a promise that resolves to a read-only copy of the migration history.
882
- * @returns A promise that resolves to a read-only array of migrations.
883
- */
884
- migrations(): Promise<Readonly<Migration<any>[]>>;
885
- /**
886
- * Exports the schema state (definition and migrations) as a JSON string.
887
- * @returns A JSON string representation of the schema state.
888
- */
889
- export(): string;
890
- /**
891
- * Imports the schema state (definition and migrations) from a JSON string.
892
- * @param json The JSON string representing the schema state to import.
893
- * @throws Error if the imported state is invalid.
894
- */
895
- import(json: string): void;
896
- /**
897
- * Creates a migration from a list of changes.
898
- * @param description A description of the migration.
899
- * @param changes A list of schema changes to apply.
900
- * @param dryRun Indicates whether the migration should actually be executed
901
- * @throws Error if the changes are not valid.
902
- * @returns A promise that resolves when the migration is complete.
903
- */
904
- migrate(description: string, changes: SchemaChange<T>[], dryRun?: boolean): Promise<void>;
905
- /**
906
- * Rolls back a migration.
907
- * @param version The version to rollback from. If not specified, rolls back the last migration.
908
- * @throws Error if the rollback cannot be performed.
909
- * @returns A promise that resolves when the rollback is complete.
910
- */
911
- rollback(version?: string): Promise<void>;
912
- /**
913
- * Creates a migration helper to assist in creating a migration.
914
- * @param description A description of the migration.
915
- * @returns A `SchemaMigrationHelper` instance to build the migration.
916
- */
917
- migrationHelper(description: string): SchemaMigrationHelper;
918
- }
919
- /**
920
- * Helper for building schema migrations.
921
- * @template T The type of data associated with the schema.
922
- */
923
- interface SchemaMigrationHelper {
924
- /**
925
- * Adds a new field to the schema.
926
- * @param fieldName The name of the field to add.
927
- * @param fieldDefinition The definition of the field to add.
928
- */
929
- addField(fieldName: string, fieldDefinition: FieldDefinition<any>): void;
930
- /**
931
- * Removes a field from the schema. This marks the field as deprecated and scheduled for removal.
932
- * @param fieldName The name of the field to deprecate.
933
- */
934
- removeField(fieldName: string): void;
935
- /**
936
- * Deprecates a field.
937
- * @param {string} fieldName - The name of the field to deprecate.
938
- */
939
- deprecateField(fieldName: string): void;
940
- /**
941
- * Modifies an existing field in the schema.
942
- * @param fieldName The name of the field to modify.
943
- * @param changes The changes to apply to the field.
944
- */
945
- modifyField(fieldName: string, changes: Partial<FieldDefinition<any>>): void;
946
- /**
947
- * Adds a new index to the schema.
948
- * @param indexDefinition The definition of the index to add.
949
- */
950
- addIndex(indexDefinition: IndexDefinition): void;
951
- /**
952
- * Removes an index from the schema.
953
- * @param indexName The name of the index to remove.
954
- */
955
- removeIndex(indexName: string): void;
956
- /**
957
- * Modifies an existing index in the schema.
958
- * @param indexName The name of the index to modify.
959
- * @param changes The changes to apply to the index.
960
- */
961
- modifyIndex(indexName: string, changes: Partial<IndexDefinition>): void;
962
- /**
963
- * Adds a new constraint to the schema.
964
- * @param constraint The constraint to add.
965
- */
966
- addConstraint(constraint: Constraint<any> | ConstraintGroup<any>): void;
967
- /**
968
- * Removes a constraint from the schema.
969
- * @param constraintName The name of the constraint to remove.
970
- */
971
- removeConstraint(constraintName: string): void;
972
- /**
973
- * Modifies an existing constraint in the schema.
974
- * @param constraintName The name of the constraint to modify.
975
- * @param changes The changes to apply to the constraint.
976
- */
977
- modifyConstraint(constraintName: string, changes: Partial<Constraint<any>>): void;
978
- /**
979
- * Adds a new nested schema to the schema.
980
- * @param {string} schemaId - The ID of the nested schema to add.
981
- * @param {NestedSchemaDefinition} nestedDefinition - The definition of the nested schema to add.
982
- */
983
- addNestedSchema(schemaId: string, nestedDefinition: NestedSchemaDefinition<any>): void;
984
- /**
985
- * Removes a nested schema from the schema.
986
- * @param {string} schemaId - The ID of the nested schema to remove.
987
- */
988
- removeNestedSchema(schemaId: string): void;
989
- /**
990
- * Modifies an existing nested schema in the schema.
991
- * @param {string} schemaId - The ID of the nested schema to modify.
992
- * @param {Partial<NestedSchemaDefinition>} changes - The changes to apply to the nested schema.
993
- */
994
- modifyNestedSchema(schemaId: string, changes: Partial<NestedSchemaDefinition<any>>): void;
995
- /**
996
- * Returns the list of changes made through this helper.
997
- * @returns An array of schema changes.
998
- */
999
- changes(): {
1000
- migrate: SchemaChange<any>[];
1001
- rollback: SchemaChange<any>[];
1002
- };
1003
- }
1004
-
1005
- /**
1006
- * Defines the possible event types for persistence operations.
1007
- */
1008
- type PersistenceEventType = "create:start" | "create:success" | "create:failed" | "read:start" | "read:success" | "read:failed" | "migrate:start" | "migrate:success" | "migrate:failed" | "rollback:start" | "rollback:success" | "rollback:failed" | "update:start" | "update:success" | "update:failed" | "delete:start" | "delete:success" | "delete:failed" | "transaction:start" | "transaction:success" | "transaction:failed" | "telemetry" | "collection:create:start" | "collection:create:success" | "collection:create:failed" | "collection:delete:start" | "collection:delete:success" | "collection:delete:failed" | "subscription:register" | "subscription:unregister" | "trigger:register" | "trigger:unregister" | "trigger:execute" | "trigger:failed" | "task:register" | "task:unregister" | "task:start" | "task:success" | "task:failed" | "metadata:called";
1009
- /**
1010
- * Interface representing events emitted during persistence operations.
1011
- */
1012
- interface PersistenceEvent<DataType> {
1013
- /** The type of event (e.g., 'create:start', 'trigger:execute'). */
1014
- type: PersistenceEventType;
1015
- /** Timestamp when the event occurred. */
1016
- timestamp: number;
1017
- /** The operation being performed (e.g., 'create', 'trigger'). */
1018
- operation: string;
1019
- /** Name of the collection affected by the operation (if applicable). */
1020
- collection?: string;
1021
- /** Data passed to the operation (if applicable). */
1022
- input?: any;
1023
- /** Data returned by the operation (if applicable). */
1024
- output?: any;
1025
- /** Error object if the operation failed (if applicable). */
1026
- error?: Error;
1027
- /** Issues that caused the operation to fail (if applicable). */
1028
- issues?: Array<StandardSchemaV1.Issue>;
1029
- /** Query used in the operation (if applicable). */
1030
- query?: QueryDSL<DataType, any>;
1031
- /** Identifier for the transaction (if part of one). */
1032
- transactionId?: string;
1033
- /** Duration of the operation in milliseconds. */
1034
- duration?: number;
1035
- /** Additional context or metadata specific to the operation. */
1036
- context?: Record<string, any>;
1037
- }
1038
- /**
1039
- * Describes a subscription configuration.
1040
- */
1041
- interface SubscriptionInfo {
1042
- /** The event subscribed to. */
1043
- event: PersistenceEventType;
1044
- /** Unique identifier for the callback. */
1045
- callbackId: string;
1046
- /** Optional short identifier (max 50 chars, unique within scope). */
1047
- label?: string;
1048
- /** Optional description of the subscription's purpose (max 500 chars). */
1049
- description?: string;
839
+ type TransformFunction<Initial, Next> = (ctx: any, data: Initial) => Next | Promise<Next>;
840
+ interface DataTransform<Initial, Next> {
841
+ forward: TransformFunction<Initial, Next>;
842
+ backward: TransformFunction<Next, Initial>;
1050
843
  }
1051
- /**
1052
- * Describes a trigger configuration.
1053
- */
1054
- interface TriggerInfo<T, FunctionMap = Record<string, any>> {
1055
- /** The event(s) or pattern triggering the callback. */
1056
- event: PersistenceEventType | PersistenceEventType[] | `${string}:*`;
1057
- /** Optional condition for the trigger. */
1058
- condition?: QueryFilter<T, FunctionMap>;
1059
- /** Unique identifier for the callback. */
1060
- callbackId: string;
1061
- /** Whether the trigger executes synchronously. */
1062
- isSync: boolean;
1063
- /** Short identifier (max 50 chars, unique within scope). */
1064
- label: string;
1065
- /** Description of the trigger's purpose (max 500 chars). */
1066
- description: string;
844
+ interface Migration<Initial = any, Next = any> {
845
+ id: string;
846
+ version: {
847
+ source: string;
848
+ target?: string;
849
+ };
850
+ changes: SchemaChange[];
851
+ description: string;
852
+ rollback?: SchemaChange[];
853
+ transform: string | DataTransform<Initial, Next>;
854
+ createdAt: string;
855
+ dependencies?: string[];
856
+ checksum: string;
1067
857
  }
1068
- /**
1069
- * Describes a scheduled task configuration.
1070
- */
1071
- interface TaskInfo {
1072
- /** Unique identifier for the task. */
1073
- id: string;
1074
- /** Schedule for task execution. */
1075
- schedule: TaskSchedule;
1076
- /** Unique identifier for the callback. */
1077
- callbackId: string;
1078
- /** Whether the task executes synchronously. */
1079
- isSync: boolean;
1080
- /** Optional metadata for logging or telemetry. */
1081
- metadata?: Record<string, any>;
1082
- /** Short identifier (max 50 chars, unique within scope). */
1083
- label: string;
1084
- /** Description of the task's purpose (max 500 chars). */
1085
- description: string;
858
+ //#endregion
859
+ //#region src/validation/types/validator.d.ts
860
+ /** A single validation failure produced by a node. */
861
+ interface Issue {
862
+ /** Machine-readable error code (e.g. "TYPE_MISMATCH", "REQUIRED_FIELD_MISSING"). */
863
+ code: string;
864
+ /** Human-readable description. */
865
+ message: string;
866
+ /** Dot-separated path to the offending value (e.g. "user.address.street"). */
867
+ path: string;
1086
868
  }
1087
869
  /**
1088
- * Filter criteria for metadata queries.
1089
- */
1090
- interface MetadataFilter {
1091
- /** Filter for subscriptions. */
1092
- subscriptions?: {
1093
- event?: PersistenceEventType | PersistenceEventType[];
1094
- label?: string;
1095
- };
1096
- /** Filter for triggers. */
1097
- triggers?: {
1098
- event?: PersistenceEventType | PersistenceEventType[] | `${string}:*`;
1099
- label?: string;
1100
- };
1101
- /** Filter for tasks. */
1102
- tasks?: {
1103
- id?: string;
1104
- metadata?: Record<string, any>;
1105
- label?: string;
1106
- };
1107
- /** Filter for schemas. */
1108
- schemas?: {
1109
- id?: string;
1110
- };
870
+ * Controls how strictly the validator interprets missing / unexpected fields.
871
+ *
872
+ * - `strict` — full validation; required, unexpected, type, and constraint issues are all reported.
873
+ * - `partialStrict` — missing-required issues are suppressed; everything else is reported.
874
+ * - `loose` — missing-required *and* unexpected-field issues are both suppressed.
875
+ */
876
+ type ValidationMode = "strict" | "partialStrict" | "loose";
877
+ interface ValidationConfig {
878
+ /** Maximum nesting depth before aborting recursive traversal. Default: 20. */
879
+ maxDepth: number;
880
+ /** Validation strictness mode. Default: "strict". */
881
+ mode: ValidationMode;
1111
882
  }
1112
- /**
1113
- * Metadata for a single collection.
1114
- */
1115
- interface CollectionMetadata<T, FunctionMap = Record<string, any>> {
1116
- /** Collection identifier. */
1117
- id: string;
1118
- /** Active subscriptions for the collection. */
1119
- subscriptions: SubscriptionInfo[];
1120
- /** Active triggers for the collection. */
1121
- triggers: TriggerInfo<T, FunctionMap>[];
1122
- /** Scheduled tasks for the collection. */
1123
- tasks: TaskInfo[];
1124
- /** Number of records in the collection. */
1125
- recordCount: number;
1126
- /** Storage used by the collection in bytes. */
1127
- dataSizeBytes: number;
1128
- /** Schema definition for the collection. */
1129
- schema: SchemaDefinition;
1130
- /** Timestamp of the last operation on the collection. */
1131
- lastModified: number;
883
+ declare function defaultValidationConfig(): ValidationConfig;
884
+ /** Parameters passed to every predicate invocation. */
885
+ interface PredicateParams {
886
+ /** The original top-level document (never changes across recursive calls). */
887
+ root: Record<string, unknown>;
888
+ /**
889
+ * The data being validated at the current scope.
890
+ * For global constraints this is the full root; for recursive/nested constraints
891
+ * this is the sub-document at the constraint's base path.
892
+ */
893
+ data: unknown;
894
+ /** Resolved field keys (relative to `data`) that the predicate should inspect. */
895
+ keys: string[];
896
+ /** Arbitrary predicate-specific parameters declared in the schema. */
897
+ parameters?: unknown;
1132
898
  }
1133
899
  /**
1134
- * Metadata for Persistence or PersistenceCollection.
900
+ * A predicate function.
901
+ * Returns an array of Issues (empty = success).
902
+ * May be synchronous or asynchronous.
1135
903
  */
1136
- interface Metadata<T, FunctionMap = Record<string, any>> {
1137
- /** Active subscriptions. */
1138
- subscriptions: SubscriptionInfo[];
1139
- /** Active triggers. */
1140
- triggers: TriggerInfo<T, FunctionMap>[];
1141
- /** Scheduled tasks. */
1142
- tasks: TaskInfo[];
1143
- /** Number of collections (Persistence only). */
1144
- collectionCount?: number;
1145
- /** Total storage used by all collections in bytes (Persistence only). */
1146
- storageUsageBytes?: number;
1147
- /** Database connection status (Persistence only). */
1148
- connectionStatus?: "connected" | "disconnected" | "error";
1149
- /** Database connection error, if any (Persistence only). */
1150
- connectionError?: string | null;
1151
- /** Schema definitions for all collections, if requested (Persistence only). */
1152
- schemas?: SchemaDefinition[];
1153
- /** Per-collection metadata, if requested (Persistence only). */
1154
- collections?: CollectionMetadata<any, FunctionMap>[];
1155
- /** Number of records in the collection (PersistenceCollection only). */
1156
- recordCount?: number;
1157
- /** Storage used by the collection in bytes (PersistenceCollection only). */
1158
- dataSizeBytes?: number;
1159
- /** Schema definition for the collection (PersistenceCollection only). */
1160
- schema?: SchemaDefinition;
1161
- /** Timestamp of the last operation on the collection (PersistenceCollection only). */
1162
- lastModified?: number;
1163
- }
904
+ type PredicateFn = (params: PredicateParams) => Issue[] | Promise<Issue[]>;
905
+ /** Map of predicate name → predicate function. */
906
+ type PredicateMap = Record<string, PredicateFn>;
1164
907
  /**
1165
- * Interface for querying observability data.
908
+ * A leaf constraint: a named predicate with optional field paths and parameters.
909
+ * Mirrors Go's `ConstraintRule`.
1166
910
  */
1167
- interface ObservabilityInterface<T, FunctionMap = Record<string, any>> {
1168
- /**
1169
- * Returns metadata about active subscriptions, triggers, tasks, and system state.
1170
- * @param filter Optional filter to limit returned data (e.g., by event or label).
1171
- * @param includeCollections For Persistence, whether to include per-collection metadata.
1172
- * @param includeSchemas For Persistence, whether to include schema definitions.
1173
- * @param forceRefresh Whether to force real-time queries for storageUsageBytes and dataSizeBytes.
1174
- * @returns Metadata object containing observability data.
1175
- * @example
1176
- * // Collection metadata with label filter
1177
- * const metadata = collection.metadata({ triggers: { label: "user-*" } });
1178
- * console.log(metadata.triggers); // Triggers with label "user-*"
1179
- * console.log(metadata.dataSizeBytes); // Storage used
1180
- *
1181
- * // Persistence metadata
1182
- * const globalMetadata = persistence.metadata({ includeCollections: true });
1183
- * console.log(globalMetadata.storageUsageBytes); // Total storage
1184
- * console.log(globalMetadata.collections); // Per-collection metadata
1185
- */
1186
- metadata(filter?: MetadataFilter, includeCollections?: boolean, includeSchemas?: boolean, forceRefresh?: boolean): Metadata<T, FunctionMap>;
911
+ interface ValidatorConstraintRule {
912
+ kind: "rule";
913
+ name: string;
914
+ description: string | undefined;
915
+ predicate: string;
916
+ parameters: unknown;
917
+ fields: string[];
1187
918
  }
1188
919
  /**
1189
- * Interface for event handling and task scheduling.
920
+ * A logical group of constraints combined with a `LogicalOperator`.
921
+ * Mirrors Go's `ConstraintGroup`.
1190
922
  */
1191
- interface EventTaskInterface<T, FunctionMap = Record<string, any>> {
1192
- /**
1193
- * Subscribes to persistence events.
1194
- * @param event The event to subscribe to.
1195
- * @param callback The callback to handle the event.
1196
- * @param options Optional label and description for the subscription.
1197
- * @returns A function to unsubscribe from the event.
1198
- * @example
1199
- * const unsubscribe = persistence.subscribe("telemetry", (event) => {
1200
- * console.log(event);
1201
- * }, { label: "telemetry-log", description: "Logs telemetry events" });
1202
- * unsubscribe();
1203
- */
1204
- subscribe(event: PersistenceEventType, callback: (payload: PersistenceEvent<T>) => void, options?: {
1205
- label?: string;
1206
- description?: string;
1207
- }): () => void;
1208
- /**
1209
- * Registers a trigger callback for specific events.
1210
- * @param config Configuration including event, callback, label, description, and options.
1211
- * @returns A function to unsubscribe the trigger.
1212
- * @example
1213
- * collection.trigger("create:success",
1214
- * ({ collection, results }) => {
1215
- * console.log(`Created: ${results.id}`);
1216
- * },
1217
- * {
1218
- * label: "user-create-hook",
1219
- * description: "Syncs new users with CRM",
1220
- * sync: true
1221
- * });
1222
- */
1223
- trigger(event: PersistenceEventType | PersistenceEventType[] | `${string}:*`, callback: (context: TriggerContext<T, FunctionMap>) => void | Promise<void>, options: {
1224
- condition?: QueryFilter<T, FunctionMap>;
1225
- sync?: boolean;
1226
- label: string;
1227
- description: string;
1228
- }): () => void;
1229
- /**
1230
- * Schedules a task to run at specified times or intervals.
1231
- * @param config Configuration including ID, schedule, callback, label, description, and options.
1232
- * @returns A function to cancel the scheduled task.
1233
- * @example
1234
- * collection.schedule({
1235
- * id: "cleanup-inactive",
1236
- * label: "inactive-cleanup",
1237
- * description: "Deletes inactive records hourly",
1238
- * schedule: { cron: "0 * * * *" },
1239
- * callback: ({ collection }) => {
1240
- * collection.delete({ query: { filter: { status: { $eq: "inactive" } } } });
1241
- * }
1242
- * });
1243
- */
1244
- schedule(config: {
1245
- id: string;
1246
- schedule: TaskSchedule;
1247
- callback: (context: TaskContext<T, FunctionMap>) => void | Promise<void>;
1248
- sync?: boolean;
1249
- metadata?: Record<string, any>;
1250
- label: string;
1251
- description: string;
1252
- }): () => void;
923
+ interface ValidatorConstraintGroup {
924
+ kind: "group";
925
+ name: string;
926
+ description: string | undefined;
927
+ operator: string;
928
+ rules: ValidatorConstraint[];
1253
929
  }
1254
- /**
1255
- * Interface defining persistence operations for data management.
1256
- */
1257
- interface Persistence<FunctionMap = Record<string, any>> extends ObservabilityInterface<any, FunctionMap>, EventTaskInterface<any, FunctionMap> {
1258
- /**
1259
- * Returns a list of all collection names.
1260
- * @returns A promise that resolves to an array of collection names.
1261
- */
1262
- collections(): Promise<Array<string>>;
1263
- /**
1264
- * Creates a new collection with the specified schema.
1265
- * @param schema The schema definition for the new collection.
1266
- * @returns A promise that resolves to the created PersistenceCollection.
1267
- */
1268
- create<T>(schema: SchemaDefinition): Promise<PersistenceCollection<T, FunctionMap>>;
1269
- /**
1270
- * Deletes the specified collection.
1271
- * @param id The ID of the collection to delete.
1272
- * @returns A promise that resolves indicating whether the collection was deleted.
1273
- */
1274
- delete(id: string): Promise<boolean>;
1275
- /**
1276
- * Retrieves the schema definition for the specified collection.
1277
- * @param id The ID of the collection.
1278
- * @returns A promise that resolves to the schema definition.
1279
- */
1280
- schema(id: string): Promise<SchemaDefinition>;
1281
- /**
1282
- * Returns a PersistenceCollection instance for interacting with a collection.
1283
- * @param id The ID of the collection.
1284
- * @returns The PersistenceCollection instance.
1285
- */
1286
- collection<T>(id: string): PersistenceCollection<T, FunctionMap>;
1287
- /**
1288
- * Executes a transaction with multiple operations.
1289
- * @param callback A function that receives a PersistenceTransaction object.
1290
- * @returns A promise that resolves to the transaction result.
1291
- */
1292
- transact<ReturnType>(callback: (tx: PersistenceTransaction<FunctionMap>) => Promise<ReturnType>): Promise<ReturnType>;
930
+ /** A constraint is either a single rule or a logical group of rules. */
931
+ type ValidatorConstraint = ValidatorConstraintRule | ValidatorConstraintGroup;
932
+ /** Keyed map of constraint ID → ValidatorConstraint. */
933
+ type SchemaConstraintMap = Record<string, ValidatorConstraint>;
934
+ interface NodeResult {
935
+ issues: Issue[];
936
+ success: boolean;
937
+ skipped: boolean;
1293
938
  }
1294
- /**
1295
- * Transaction interface, omitting subscribe, trigger, schedule, and transact methods.
1296
- */
1297
- type PersistenceTransaction<F> = Omit<Persistence<F>, "subscribe" | "trigger" | "schedule" | "transact">;
1298
- /**
1299
- * Interface for managing a single collection's data operations.
1300
- */
1301
- interface PersistenceCollection<T, FunctionMap = Record<string, any>> extends ObservabilityInterface<T, FunctionMap>, EventTaskInterface<T, FunctionMap> {
1302
- /**
1303
- * Creates a new record or multiple records in the collection.
1304
- * @param params The data to create.
1305
- * @returns A promise that resolves to the created record(s).
1306
- */
1307
- create(params: {
1308
- data: T | T[];
1309
- }): Promise<T | T[]>;
1310
- /**
1311
- * Retrieves one or more records from the collection.
1312
- * @param params The query defining the filter, sort, pagination, and projection.
1313
- * @returns A promise that resolves to the matching record or array of records.
1314
- */
1315
- read(params: {
1316
- query: QueryDSL<T, FunctionMap>;
1317
- }): Promise<T | Array<T>>;
1318
- /**
1319
- * Updates one or more records in the collection.
1320
- * @param params The updated data, patch, or query.
1321
- * @returns A promise that resolves to the updated records.
1322
- */
1323
- update(params: {
1324
- data?: Partial<T>;
1325
- patch?: PatchOperation | Array<PatchOperation>;
1326
- filter: QueryFilter<T, FunctionMap>;
1327
- }): Promise<Array<T>>;
1328
- /**
1329
- * Deletes one or more records from the collection.
1330
- * @param params The query defining which records to delete.
1331
- * @returns A promise that resolves to the number of deleted records.
1332
- */
1333
- delete(params: {
1334
- query: QueryFilter<T, FunctionMap>;
1335
- }): Promise<number>;
1336
- /**
1337
- * Validates an object against the collection's schema.
1338
- * @param data The object to validate.
1339
- * @returns Validation results.
1340
- */
1341
- validate(data: any): {
1342
- valid: boolean;
1343
- issues: ReadonlyArray<StandardSchemaV1.Issue> | null;
1344
- };
1345
- /**
1346
- * Rolls back the collection to a previous schema version.
1347
- * @param version The version to roll back to (optional).
1348
- * @param dryRun Whether to simulate the rollback.
1349
- * @returns A promise that resolves to the new schema and data preview, or undefined.
1350
- */
1351
- rollback(version?: string, dryRun?: boolean): Promise<{
1352
- schema: SchemaDefinition;
1353
- preview: ReadableStream<any>;
1354
- } | undefined>;
1355
- /**
1356
- * Applies a schema migration to the collection.
1357
- * @param description A description of the migration.
1358
- * @param cb A callback defining the transformation logic.
1359
- * @param dryRun Whether to simulate the migration.
1360
- * @returns A promise that resolves to the new schema and data preview, or undefined.
1361
- */
1362
- migrate(description: string, cb: (h: Omit<SchemaMigrationHelper, "changes">) => DataTransform<any, any> | undefined, dryRun?: boolean): Promise<{
1363
- schema: SchemaDefinition;
1364
- preview: ReadableStream<any>;
1365
- } | undefined>;
1366
- }
1367
- /**
1368
- * Context for collection-specific triggers.
1369
- */
1370
- type CollectionTriggerContext<T, FunctionMap = Record<string, any>> = {
1371
- event: PersistenceEvent<T> & {
1372
- type: "create:start";
1373
- operation: "create";
1374
- };
1375
- persistence: Persistence<FunctionMap>;
1376
- collection: PersistenceCollection<T, FunctionMap>;
1377
- params: {
1378
- data: T | T[];
1379
- };
1380
- results: undefined;
1381
- } | {
1382
- event: PersistenceEvent<T> & {
1383
- type: "create:success";
1384
- operation: "create";
1385
- };
1386
- persistence: Persistence<FunctionMap>;
1387
- collection: PersistenceCollection<T, FunctionMap>;
1388
- params: {
1389
- data: T | T[];
1390
- };
1391
- results: T | T[];
1392
- } | {
1393
- event: PersistenceEvent<T> & {
1394
- type: "create:failed";
1395
- operation: "create";
1396
- };
1397
- persistence: Persistence<FunctionMap>;
1398
- collection: PersistenceCollection<T, FunctionMap>;
1399
- params: {
1400
- data: T | T[];
1401
- };
1402
- results: undefined;
1403
- } | {
1404
- event: PersistenceEvent<T> & {
1405
- type: "read:start";
1406
- operation: "read";
1407
- };
1408
- persistence: Persistence<FunctionMap>;
1409
- collection: PersistenceCollection<T, FunctionMap>;
1410
- params: {
1411
- query: QueryDSL<T, FunctionMap>;
1412
- };
1413
- results: undefined;
1414
- } | {
1415
- event: PersistenceEvent<T> & {
1416
- type: "read:success";
1417
- operation: "read";
1418
- };
1419
- persistence: Persistence<FunctionMap>;
1420
- collection: PersistenceCollection<T, FunctionMap>;
1421
- params: {
1422
- query: QueryDSL<T, FunctionMap>;
1423
- };
1424
- results: T | T[];
1425
- } | {
1426
- event: PersistenceEvent<T> & {
1427
- type: "read:failed";
1428
- operation: "read";
1429
- };
1430
- persistence: Persistence<FunctionMap>;
1431
- collection: PersistenceCollection<T, FunctionMap>;
1432
- params: {
1433
- query: QueryDSL<T, FunctionMap>;
1434
- };
1435
- results: undefined;
1436
- } | {
1437
- event: PersistenceEvent<T> & {
1438
- type: "update:start";
1439
- operation: "update";
1440
- };
1441
- persistence: Persistence<FunctionMap>;
1442
- collection: PersistenceCollection<T, FunctionMap>;
1443
- params: {
1444
- data?: Partial<T>;
1445
- patch?: PatchOperation | Array<PatchOperation>;
1446
- query: QueryFilter<T, FunctionMap>;
1447
- };
1448
- results: undefined;
1449
- } | {
1450
- event: PersistenceEvent<T> & {
1451
- type: "update:success";
1452
- operation: "update";
1453
- };
1454
- persistence: Persistence<FunctionMap>;
1455
- collection: PersistenceCollection<T, FunctionMap>;
1456
- params: {
1457
- data?: Partial<T>;
1458
- patch?: PatchOperation | Array<PatchOperation>;
1459
- query: QueryFilter<T, FunctionMap>;
1460
- };
1461
- results: Array<T>;
1462
- } | {
1463
- event: PersistenceEvent<T> & {
1464
- type: "update:failed";
1465
- operation: "update";
1466
- };
1467
- persistence: Persistence<FunctionMap>;
1468
- collection: PersistenceCollection<T, FunctionMap>;
1469
- params: {
1470
- data?: Partial<T>;
1471
- patch?: PatchOperation | Array<PatchOperation>;
1472
- query: QueryFilter<T, FunctionMap>;
1473
- };
1474
- results: undefined;
1475
- } | {
1476
- event: PersistenceEvent<T> & {
1477
- type: "delete:start";
1478
- operation: "delete";
1479
- };
1480
- persistence: Persistence<FunctionMap>;
1481
- collection: PersistenceCollection<T, FunctionMap>;
1482
- params: {
1483
- query: QueryFilter<T, FunctionMap>;
1484
- };
1485
- results: undefined;
1486
- } | {
1487
- event: PersistenceEvent<T> & {
1488
- type: "delete:success";
1489
- operation: "delete";
1490
- };
1491
- persistence: Persistence<FunctionMap>;
1492
- collection: PersistenceCollection<T, FunctionMap>;
1493
- params: {
1494
- query: QueryFilter<T, FunctionMap>;
1495
- };
1496
- results: number;
1497
- } | {
1498
- event: PersistenceEvent<T> & {
1499
- type: "delete:failed";
1500
- operation: "delete";
1501
- };
1502
- persistence: Persistence<FunctionMap>;
1503
- collection: PersistenceCollection<T, FunctionMap>;
1504
- params: {
1505
- query: QueryFilter<T, FunctionMap>;
1506
- };
1507
- results: undefined;
1508
- } | {
1509
- event: PersistenceEvent<T> & {
1510
- type: "migrate:start";
1511
- operation: "migrate";
1512
- };
1513
- persistence: Persistence<FunctionMap>;
1514
- collection: PersistenceCollection<T, FunctionMap>;
1515
- params: {
1516
- description: string;
1517
- dryRun?: boolean;
1518
- };
1519
- results: undefined;
1520
- } | {
1521
- event: PersistenceEvent<T> & {
1522
- type: "migrate:success";
1523
- operation: "migrate";
1524
- };
1525
- persistence: Persistence<FunctionMap>;
1526
- collection: PersistenceCollection<T, FunctionMap>;
1527
- params: {
1528
- description: string;
1529
- dryRun?: boolean;
1530
- };
1531
- results: {
1532
- schema: SchemaDefinition;
1533
- preview: ReadableStream<any>;
1534
- } | undefined;
1535
- } | {
1536
- event: PersistenceEvent<T> & {
1537
- type: "migrate:failed";
1538
- operation: "migrate";
1539
- };
1540
- persistence: Persistence<FunctionMap>;
1541
- collection: PersistenceCollection<T, FunctionMap>;
1542
- params: {
1543
- description: string;
1544
- dryRun?: boolean;
1545
- };
1546
- results: undefined;
1547
- } | {
1548
- event: PersistenceEvent<T> & {
1549
- type: "rollback:start";
1550
- operation: "rollback";
1551
- };
1552
- persistence: Persistence<FunctionMap>;
1553
- collection: PersistenceCollection<T, FunctionMap>;
1554
- params: {
1555
- version?: string;
1556
- dryRun?: boolean;
1557
- };
1558
- results: undefined;
1559
- } | {
1560
- event: PersistenceEvent<T> & {
1561
- type: "rollback:success";
1562
- operation: "rollback";
1563
- };
1564
- persistence: Persistence<FunctionMap>;
1565
- collection: PersistenceCollection<T, FunctionMap>;
1566
- params: {
1567
- version?: string;
1568
- dryRun?: boolean;
1569
- };
1570
- results: {
1571
- schema: SchemaDefinition;
1572
- preview: ReadableStream<any>;
1573
- } | undefined;
1574
- } | {
1575
- event: PersistenceEvent<T> & {
1576
- type: "rollback:failed";
1577
- operation: "rollback";
1578
- };
1579
- persistence: Persistence<FunctionMap>;
1580
- collection: PersistenceCollection<T, FunctionMap>;
1581
- params: {
1582
- version?: string;
1583
- dryRun?: boolean;
1584
- };
1585
- results: undefined;
1586
- };
1587
- /**
1588
- * Context for global triggers (Persistence-level, non-collection-specific).
1589
- */
1590
- type GlobalTriggerContext<T, FunctionMap = Record<string, any>> = {
1591
- event: PersistenceEvent<T> & {
1592
- type: "transaction:start" | "transaction:success" | "transaction:failed" | "collection:create:start" | "collection:create:success" | "collection:create:failed" | "collection:delete:start" | "collection:delete:success" | "collection:delete:failed" | "telemetry";
1593
- operation: "transaction" | "collection:create" | "collection:delete";
1594
- };
1595
- persistence: Persistence<FunctionMap>;
1596
- collection?: undefined;
1597
- params: any;
1598
- results: any;
1599
- };
1600
- /**
1601
- * Union of trigger contexts.
1602
- */
1603
- type TriggerContext<T, FunctionMap = Record<string, any>> = CollectionTriggerContext<T, FunctionMap> | GlobalTriggerContext<T, FunctionMap>;
1604
- /**
1605
- * Defines a schedule for a task.
1606
- */
1607
- type TaskSchedule = {
1608
- cron: string;
1609
- } | {
1610
- at: string;
1611
- } | {
1612
- interval: number;
1613
- };
1614
- /**
1615
- * Context provided to task callbacks.
1616
- */
1617
- type TaskContext<T, FunctionMap = Record<string, any>> = {
1618
- persistence: Persistence<FunctionMap>;
1619
- collection: PersistenceCollection<T, FunctionMap>;
1620
- taskId: string;
1621
- executionTime: number;
1622
- metadata?: Record<string, any>;
1623
- label: string;
1624
- description: string;
1625
- } | {
1626
- persistence: Persistence<FunctionMap>;
1627
- collection?: undefined;
1628
- taskId: string;
1629
- executionTime: number;
1630
- metadata?: Record<string, any>;
1631
- label: string;
1632
- description: string;
1633
- };
1634
-
1635
- type SchemaIndex = {
1636
- schema: string;
1637
- version: string;
1638
- history: Array<SchemaVersion>;
1639
- migrations: Record<string, MigrationMetadata>;
1640
- };
1641
- type SchemaVersion = {
1642
- version: string;
1643
- hash: string;
1644
- date: string;
1645
- description: string;
1646
- migrations?: string[];
1647
- predicates?: string[];
1648
- changelog: string[];
1649
- };
1650
- type MigrationMetadata = {
1651
- hash: string;
1652
- checksum: string;
1653
- };
1654
- type RegistryMetadata = {
1655
- schemas: Record<string, SchemaMetadata>;
1656
- created: string;
1657
- updated: string;
1658
- };
1659
- type SchemaMetadata = {
1660
- name: string;
1661
- version: string;
1662
- description: string;
1663
- created: string;
1664
- updated: string;
1665
- };
1666
- type RegistryLock = {
1667
- updated: string;
1668
- hashes: [filepath: string, filehash: string][];
1669
- };
1670
- interface SchemaRegistryInterface {
1671
- /** Initializes the repository **/
1672
- init(): Promise<void>;
1673
- /** Create a new schema version */
1674
- create(_: {
1675
- schema: SchemaDefinition;
1676
- }): Promise<void>;
1677
- /** Update an existing schema version */
1678
- update(_: {
1679
- schema: SchemaDefinition;
1680
- }): Promise<void>;
1681
- /** Delete a schema and its associated branch */
1682
- delete(_: {
1683
- name: string;
1684
- }): Promise<void>;
1685
- /** List all schemas with their latest version */
1686
- list(): Promise<{
1687
- name: string;
1688
- version: string;
1689
- }[]>;
1690
- /** Retrieve schema definition for a specific version (or latest if no version is provided) */
1691
- schema(_: {
1692
- name: string;
1693
- version?: string;
1694
- migrations?: boolean;
1695
- }): Promise<SchemaDefinition | null>;
1696
- /** Get schema statistics (returns the full SchemaIndex) */
1697
- stats(_: {
1698
- schema?: string;
1699
- }): Promise<SchemaIndex | RegistryMetadata>;
1700
- /** Regenerate index & lockfile, then push changes */
1701
- sync(): Promise<void>;
1702
- /** Retrieve all migrations for a specific schema version (or latest if no version is provided) */
1703
- migrations(_: {
1704
- name: string;
1705
- version?: string;
1706
- }): Promise<Array<Migration<any>>>;
1707
- /** Retrieve the full history of a schema */
1708
- history(_: {
1709
- name: string;
1710
- }): Promise<SchemaDefinition[]>;
939
+ interface ValidationContext {
940
+ /** The original top-level document; never changes. */
941
+ originalRoot: Record<string, unknown>;
942
+ /** The current root being validated (may be a sub-document for recursive schemas). */
943
+ rootData: unknown;
944
+ /** Alias for rootData kept for parity with Go. */
945
+ data: unknown;
946
+ /** The predicate function registry. */
947
+ functionMap: PredicateMap;
948
+ /** Maximum allowed nesting depth. */
949
+ maxDepth: number;
950
+ /** Validation strictness. */
951
+ mode: ValidationMode;
952
+ /**
953
+ * Per-node success state. Index = node ID, value = success (true) | failure (false) | absent (undefined).
954
+ * Used by the traversal loop to propagate skipping when a dependency failed.
955
+ */
956
+ visited: Map<number, boolean>;
957
+ /** Accumulated issues for this traversal. */
958
+ issues: Issue[];
1711
959
  }
1712
-
1713
- /**
1714
- * Interface for interacting with a remotely hosted repository (e.g., GitHub, GitLab).
1715
- */
1716
- interface RemoteRepository {
1717
- /**
1718
- * Creates a new repository on the remote service.
1719
- * @param options.name - The name of the repository.
1720
- * @param options.private - Whether the repository should be private (default: false).
1721
- * @returns A promise resolving to the repository's authenticated URL (e.g., "https://username:token@github.com/username/repo.git").
1722
- * @param options
1723
- */
1724
- create(options: {
1725
- name: string;
1726
- private?: boolean;
1727
- }): Promise<RemoteRepository>;
1728
- /**
1729
- * Checks if a repository exists on the remote service.
1730
- * @param options - Repository lookup details.
1731
- * @param options.name - The name of the repository.
1732
- * @returns A promise resolving to true if the repository exists, false otherwise.
1733
- */
1734
- exists({ name }: {
1735
- name: string;
1736
- }): Promise<boolean>;
1737
- /**
1738
- * Deletes a repository on the remote service.
1739
- */
1740
- remove(): Promise<void>;
1741
- /**
1742
- * Returns a properly formatted authenticated URL for a specific repository.
1743
- * @returns A string representing the auth-enabled URL (e.g., "https://username:token@github.com/username/repo.git").
1744
- */
1745
- authURL(): string;
1746
- /**
1747
- * Returns the plain URL to this repository.
1748
- * @returns A string representing the repository URL (e.g., "https://github.com/username/repo.git").
1749
- * @throws RemoteRepositoryError if no repository is set.
1750
- */
1751
- url(): string;
1752
- credentials(): {
1753
- username: string;
1754
- password: string;
1755
- };
960
+ //#endregion
961
+ //#region src/validation/nodes.d.ts
962
+ interface ValidationNode {
963
+ execute(ctx: ValidationContext): Promise<NodeResult>;
964
+ getDependencies(): number[];
965
+ getID(): number;
966
+ getPath(): string;
967
+ getPathParts(): string[];
1756
968
  }
1757
-
1758
- declare function createGitSchemaRegistry(rootDir?: string, options?: {
1759
- remote?: RemoteRepository;
1760
- mainBranch?: string;
1761
- createRemote?: boolean;
1762
- author?: {
1763
- name: string;
1764
- email: string;
1765
- };
1766
- proxy?: string;
1767
- cacheTtl?: number;
1768
- }): Promise<SchemaRegistryInterface>;
1769
-
1770
- /**
1771
- * Implementation of a schema registry using an in-memory LightningFS.
1772
- * Combines refined filesystem management with original serialization for functions and mocks.
1773
- */
1774
- declare class SchemaRegistry implements SchemaRegistryInterface {
1775
- /** In-memory filesystem instance for storing registry data. */
1776
- fs: LightningFS;
1777
- /** Promise-based API for asynchronous filesystem operations. */
1778
- fsp: LightningFS.PromisifiedFS;
1779
- /** Root directory path in the filesystem (e.g., '/registry'). */
1780
- rootDir: string;
1781
- /**
1782
- * Constructs a new SchemaRegistryImpl instance.
1783
- * @param rootDir - The root directory for the registry (defaults to '/registry').
1784
- */
1785
- constructor(rootDir?: string);
1786
- /**
1787
- * Ensures the registry is initialized with base files if they don't exist.
1788
- * Implements refined conditional initialization for idempotency.
1789
- */
1790
- init(): Promise<void>;
1791
- /**
1792
- * Creates a new schema in the registry.
1793
- * @param params - Object containing the schema definition.
1794
- * @throws Error if schema name or version is missing, or if schema already exists.
1795
- */
1796
- create({ schema }: {
1797
- schema: SchemaDefinition;
1798
- }): Promise<void>;
1799
- /**
1800
- * Updates an existing schema in the registry.
1801
- * @param params - Object containing the updated schema definition.
1802
- * @throws Error if schema name or version is missing, or if schema doesn't exist.
1803
- */
1804
- update({ schema }: {
1805
- schema: SchemaDefinition;
1806
- }): Promise<void>;
1807
- /**
1808
- * Saves a schema (create or update) with serialization and metadata updates.
1809
- * @param schema - The schema definition to save.
1810
- * @param action - Whether this is a create or update operation.
1811
- * @private - Internal method to reduce duplication in create/update.
1812
- */
1813
- private saveSchema;
1814
- /**
1815
- * Deletes a schema and all its associated data from the registry.
1816
- * Implements refined full filesystem cleanup.
1817
- * @param params - Object containing the schema name to delete.
1818
- * @throws Error if schema doesn't exist.
1819
- */
1820
- delete({ name }: {
1821
- name: string;
1822
- }): Promise<void>;
1823
- /**
1824
- * Lists all schemas in the registry with their latest versions.
1825
- * @returns Array of schema names and versions.
1826
- */
1827
- list(): Promise<{
1828
- name: string;
1829
- version: string;
1830
- }[]>;
1831
- /**
1832
- * Retrieves a schema definition, optionally with a specific version and migrations.
1833
- * Incorporates original serialization for mocks.
1834
- * @param params - Object with schema name, optional version, and migrations flag.
1835
- * @returns Schema definition or null if not found.
1836
- */
1837
- schema({ name, version, migrations, }: {
1838
- name: string;
1839
- version?: string;
1840
- migrations?: boolean;
1841
- }): Promise<SchemaDefinition | null>;
1842
- /**
1843
- * Retrieves statistics for a specific schema or the entire registry.
1844
- * @param params - Optional schema name to get SchemaIndex instead of RegistryMetadata.
1845
- * @returns SchemaIndex or RegistryMetadata.
1846
- * @throws Error if specific schema stats requested but schema not found.
1847
- */
1848
- stats({ schema, }: {
1849
- schema?: string;
1850
- }): Promise<SchemaIndex | RegistryMetadata>;
1851
- /**
1852
- * Synchronizes the registry by updating the lockfile with current file hashes.
1853
- * Implements refined sync behavior.
1854
- */
1855
- sync(): Promise<void>;
1856
- /**
1857
- * Retrieves migrations for a schema up to a specified version.
1858
- * Incorporates original serialization for migration transforms.
1859
- * @param params - Object with schema name and optional version.
1860
- * @returns Array of migrations, sorted by version.
1861
- */
1862
- migrations({ name, version, }: {
1863
- name: string;
1864
- version?: string;
1865
- }): Promise<Array<Migration<any>>>;
1866
- /**
1867
- * Retrieves the version history of a schema.
1868
- * Incorporates original serialization for mocks and migrations.
1869
- * @param params - Object with schema name.
1870
- * @returns Array of schema definitions for each version.
1871
- */
1872
- history({ name }: {
1873
- name: string;
1874
- }): Promise<SchemaDefinition[]>;
1875
- /**
1876
- * Processes and stores migrations with serialization of transforms.
1877
- * Adopts original's approach to handling executable transforms.
1878
- * @param schemaDir - Directory path for the schema.
1879
- * @param schema - Schema definition containing migrations.
1880
- * @returns Array of migration metadata.
1881
- * @private
1882
- */
1883
- private processAndStoreMigrations;
1884
- /**
1885
- * Serializes a schema definition, handling mocks as per original.
1886
- * @param schema - Schema definition to serialize.
1887
- * @returns JSON string of serialized schema.
1888
- * @private
1889
- */
1890
- private serializeSchema;
1891
- /**
1892
- * Deserializes a schema content object, restoring mocks as per original.
1893
- * @param schemaContent - Raw schema content from JSON.
1894
- * @returns Deserialized schema definition.
1895
- * @private
1896
- */
1897
- private deserializeSchema;
1898
- /**
1899
- * Deserializes a migration content object, restoring transforms as per original.
1900
- * @param content - Raw migration content from JSON.
1901
- * @returns Deserialized migration object.
1902
- * @private
1903
- */
1904
- private deserializeMigration;
1905
- /**
1906
- * Writes the schema file to the filesystem.
1907
- * @param schemaDir - Directory path for the schema.
1908
- * @param content - Serialized schema content.
1909
- * @returns Path to the written schema file.
1910
- * @private
1911
- */
1912
- private writeSchemaFile;
1913
- /**
1914
- * Updates the schema index with new version history and migrations.
1915
- * @param schemaDir - Directory path for the schema.
1916
- * @param schema - Schema definition being saved.
1917
- * @param schemaHash - Hash of the schema content.
1918
- * @param migrations - Processed migration metadata.
1919
- * @param action - Whether this is a create or update operation.
1920
- * @private
1921
- */
1922
- private updateIndex;
1923
- /**
1924
- * Updates the registry metadata with schema information.
1925
- * @param schema - Schema definition being saved.
1926
- * @param action - Whether this is a create or update operation.
1927
- * @private
1928
- */
1929
- private updateRegistryMetadata;
1930
- /**
1931
- * Reads the registry metadata from the filesystem.
1932
- * @returns Parsed RegistryMetadata object.
1933
- * @private
1934
- */
1935
- private readRegistryMetadata;
1936
- /**
1937
- * Writes the registry metadata to the filesystem.
1938
- * @param metadata - RegistryMetadata object to write.
1939
- * @private
1940
- */
1941
- private writeRegistryMetadata;
1942
- /**
1943
- * Reads the schema index from the filesystem.
1944
- * @param name - Name of the schema.
1945
- * @returns Parsed SchemaIndex object.
1946
- * @throws Error if schema index not found.
1947
- * @private
1948
- */
1949
- private readSchemaIndex;
1950
- /**
1951
- * Checks if a file exists in the filesystem.
1952
- * @param path - Path to check.
1953
- * @returns True if file exists, false otherwise.
1954
- * @private
1955
- */
1956
- fileExists(path: string): Promise<boolean>;
1957
- /**
1958
- * Recursively removes a directory and its contents.
1959
- * @param path - Directory path to remove.
1960
- * @private
1961
- */
1962
- private rmdirRecursive;
1963
- /**
1964
- * Lists all files recursively in a directory.
1965
- * @param path - Directory path to scan.
1966
- * @returns Array of file paths.
1967
- * @private
1968
- */
1969
- private listFilesRecursive;
969
+ //#endregion
970
+ //#region src/validation/graph.d.ts
971
+ declare class BuildContext {
972
+ /** Ref-count of schemas currently being built. */
973
+ private readonly buildingSchemas;
974
+ /** Cache of pre-built recursive graphs keyed by schemaID + constraint hash. */
975
+ private readonly recursiveGraphCache;
976
+ isRecursive(schemaID: string): boolean;
977
+ markBuilding(schemaID: string): void;
978
+ unmarkBuilding(schemaID: string): void;
979
+ makeGraphCacheKey(schemaID: string, constraints: SchemaConstraintMap): string;
980
+ getOrBuildRecursiveGraph(schemaID: string, schemaDef: NestedSchemaDefinition$1, instanceConstraints: SchemaConstraintMap, topLevelSchema: SchemaDefinition$1): Promise<ValidationGraph>;
1970
981
  }
1971
-
1972
- /**
1973
- * @fileoverview
1974
- * Provides a MigrationEngine class that handles schema migrations,
1975
- * including validation, checksum generation, and migration application.
1976
- * @author Saidimu
1977
- */
1978
-
1979
- /**
1980
- * @class MigrationError
1981
- * @extends Error
1982
- * @param {string} message - The error message
1983
- * @param {MigrationErrorCode} code - The error code
1984
- * @param {string} [migrationId] - The ID of the migration that caused the error
1985
- * @param {Error} [cause] - The underlying error that caused this error
1986
- */
1987
- declare class MigrationError extends Error {
1988
- readonly code: MigrationErrorCode;
1989
- readonly migrationId?: string | undefined;
1990
- readonly cause?: Error | undefined;
1991
- constructor(message: string, code: MigrationErrorCode, migrationId?: string | undefined, cause?: Error | undefined);
982
+ /** Internal tracking node used only during graph construction. */
983
+ interface TrackNode {
984
+ id: number;
985
+ deps: number[];
1992
986
  }
1993
- /**
1994
- * @enum MigrationErrorCode
1995
- * @description Error codes for migration-related errors
1996
- */
1997
- declare enum MigrationErrorCode {
1998
- INVALID_SCHEMA = "INVALID_SCHEMA",
1999
- INVALID_MIGRATION = "INVALID_MIGRATION",
2000
- CHECKSUM_MISMATCH = "CHECKSUM_MISMATCH",
2001
- TIMEOUT = "TIMEOUT",
2002
- MEMORY_LIMIT = "MEMORY_LIMIT",
2003
- CONCURRENT_OPERATION = "CONCURRENT_OPERATION",
2004
- TRANSFORM_ERROR = "TRANSFORM_ERROR",
2005
- VERSION_NOT_FOUND = "VERSION_NOT_FOUND",
2006
- CIRCULAR_DEPENDENCY = "CIRCULAR_DEPENDENCY",
2007
- STREAM_ERROR = "STREAM_ERROR",
2008
- ROLLBACK_ERROR = "ROLLBACK_ERROR",
2009
- MISSING_TRANSFORM = "MISSING_TRANSFORM"
987
+ declare class ValidationGraph {
988
+ private nodes;
989
+ private dependencies;
990
+ private visitedState;
991
+ private executionOrder;
992
+ private nextNodeID;
993
+ /** Paths explicitly marked nullable:true (null is a legal value). */
994
+ readonly nullablePaths: Set<string>;
995
+ buildNodeID(): number;
996
+ addNode(node: ValidationNode): void;
997
+ private createUnexpectedFieldsNode;
998
+ private createRequiredFieldNode;
999
+ private createTypeCheckNode;
1000
+ private createCompletionNode;
1001
+ finalize(): void;
1002
+ traverse(fmap: PredicateMap, document: Record<string, unknown>, mode: ValidationMode, maxDepth: number, originalRoot: Record<string, unknown>): Promise<Issue[]>;
1003
+ /**
1004
+ * Builds the validation graph from a SchemaDefinition.
1005
+ * Returns the root TrackNodes (for wiring dependencies).
1006
+ * Mirrors Go's `graph.buildFromSchema`.
1007
+ */
1008
+ buildFromSchema(schema: SchemaDefinition$1, basePath: string, baseParts: string[], addedConstraints: Map<string, boolean>, nsd: NestedSchemaDefinition$1 | null, schemaRefConstraints: SchemaConstraintMap, topLevelSchema: SchemaDefinition$1, buildCtx: BuildContext, skipUnexpectedCheck: boolean, skipUnexpectedForObjects: boolean): Promise<TrackNode[]>;
1009
+ private buildFieldNodes;
1010
+ private buildFieldTypeNodes;
1011
+ private buildObjectFieldNodes;
1012
+ /**
1013
+ * Mirrors Go's `buildContainerNode`.
1014
+ * Returns an ArrayValidationNode or RecordValidationNode depending on `itemKind`.
1015
+ */
1016
+ private buildContainerNode;
1017
+ private buildEnumNode;
1018
+ private buildUnionNode;
1019
+ private buildCompositeNode;
1020
+ private buildFromEffectiveConstraints;
1021
+ private buildFromConstraintRuleWithScope;
1022
+ /**
1023
+ * Creates a standalone ValidationGraph for a single field, used by array /
1024
+ * record / union / composite nodes.
1025
+ * Mirrors Go's `graph.createSubGraph`.
1026
+ */
1027
+ createSubGraph(rootFieldName: string, rootFieldDef: FieldDefinition$1, basePath: string, originalTopLevelSchema: SchemaDefinition$1, buildCtx: BuildContext, skipUnexpectedCheck: boolean, skipUnexpectedForObjects: boolean): Promise<ValidationGraph>;
2010
1028
  }
2011
- /**
2012
- * @class MigrationEngine
2013
- * @param {SchemaDefinition} currentSchema - The current schema definition
2014
- * @param {Array<Migration<any>>} [migrations] - Optional array of migrations
2015
- * @throws {MigrationError} If the initial schema or migrations are invalid
2016
- */
2017
- declare class MigrationEngine {
2018
- private currentSchema;
2019
- private history;
2020
- private migrations;
2021
- private isProcessing;
2022
- /**
2023
- * @constructor
2024
- * @param {SchemaDefinition} currentSchema - The current schema definition
2025
- * @param {Array<Migration<any>>} [migrations] - Optional array of migrations
2026
- */
2027
- constructor(currentSchema: SchemaDefinition, migrations?: Array<Migration<any>>, history?: Array<SchemaDefinition>);
2028
- /**
2029
- * Gets the current state of the migration helper
2030
- * @returns {Object} Current state containing schema, history, and migrations
2031
- * @example
2032
- * ```javascript
2033
- * const state = migrationEngine.data();
2034
- * // state contains currentSchema, history, and migrations
2035
- * ```
2036
- */
2037
- data(): {
2038
- schema: SchemaDefinition;
2039
- history: SchemaDefinition[];
2040
- migrations: Migration<any>[];
2041
- };
2042
- /**
2043
- * Generates a SHA-256 checksum for a migration
2044
- * @private
2045
- * @param {Omit<Migration<any>, "checksum">} migration - The migration object
2046
- * @returns {Promise<string>} The generated checksum
2047
- * @throws {MigrationError} If checksum generation fails
2048
- */
2049
- private generateChecksum;
2050
- /**
2051
- * Adds a new migration to the engine
2052
- * @async
2053
- * @param {Object} opts - Options for the new migration
2054
- * @param {SchemaChange<any>[]} opts.changes - Array of schema changes
2055
- * @param {string} opts.description - Description of the migration
2056
- * @param {SchemaChange<any>[]} [opts.rollback] - Optional rollback changes
2057
- * @param {DataTransform<any, any>} [opts.transform] - Optional data transform
2058
- * @throws {MigrationError} If adding the migration fails
2059
- */
2060
- add(opts: {
2061
- changes: SchemaChange<any>[];
2062
- description: string;
2063
- rollback?: SchemaChange<any>[];
2064
- transform?: string | DataTransform<any, any>;
2065
- }): Promise<void>;
2066
- /**
2067
- * Performs a dry run of the migration
2068
- * @async
2069
- * @param {ReadableStream<any>} input - Input data stream
2070
- * @param {"forward" | "backward"} direction - Direction of migration
2071
- * @param {version} version - Version to rollback to
2072
- * @returns {Promise<Object>} Object containing newSchema and dataPreview
2073
- * @throws {MigrationError} If dry run fails
2074
- */
2075
- dryRun(input: ReadableStream<any>, direction: "forward" | "backward", version?: string): Promise<{
2076
- newSchema: SchemaDefinition;
2077
- dataPreview: ReadableStream<any>;
2078
- }>;
2079
- /**
2080
- * Gets relevant migrations based on direction
2081
- * @private
2082
- * @param {"forward" | "backward"} direction - Direction of migration
2083
- * @returns {Array<Migration<any>>} Relevant migrations
2084
- */
2085
- private getRelevantMigrations;
2086
- /**
2087
- * Applies schema changes to a given schema
2088
- * @private
2089
- * @param {SchemaDefinition} schema - The schema to modify
2090
- * @param {SchemaChange<any>[]} changes - Array of schema changes
2091
- * @param {string} [migrationId] - ID of the migration
2092
- * @returns {SchemaDefinition} Modified schema
2093
- * @throws {MigrationError} If applying changes fails
2094
- */
2095
- private applySchemaChanges;
2096
- /**
2097
- * Prepares the list of pending migrations for application
2098
- * @async
2099
- * @returns {Promise<Array<Migration<any>>} List of pending migrations
2100
- * @throws {MigrationError} If preparation fails
2101
- */
2102
- prepareMigration(): Promise<Array<Migration<any>>>;
2103
- /**
2104
- * Applies pending migrations
2105
- * @async
2106
- * @param {ReadableStream<any>} input - Input data stream
2107
- * @returns {Promise<ReadableStream<any>>} Transformed data stream
2108
- * @throws {MigrationError} If migration fails
2109
- */
2110
- migrate(input: ReadableStream<any>): Promise<ReadableStream<any>>;
2111
- /**
2112
- * Validates migrations by checking their checksums
2113
- * @private
2114
- * @async
2115
- * @param {Array<Migration<any>>} migrations - Migrations to validate
2116
- * @throws {MigrationError} If validation fails
2117
- */
2118
- private validateMigrations;
2119
- /**
2120
- * Marks migrations as applied
2121
- * @private
2122
- * @param {Array<Migration<any>>} migrations - Migrations to mark as applied
2123
- */
2124
- private markMigrationsApplied;
2125
- /**
2126
- * Rolls back the last applied migration
2127
- * @async
2128
- * @param {ReadableStream<any>} input - Input data stream
2129
- * @returns {Promise<ReadableStream<any>>} Transformed data stream
2130
- */
2131
- rollback(input: ReadableStream<any>): Promise<ReadableStream<any>>;
2132
- /**
2133
- * Rolls back to a specific schema version
2134
- * @async
2135
- * @param {string} targetVersion - Target schema version
2136
- * @param {ReadableStream<any>} input - Input data stream
2137
- * @returns {Promise<ReadableStream<any>>} Transformed data stream
2138
- * @throws {Error} If target version is not found
2139
- */
2140
- rollbackToVersion(targetVersion: string, input: ReadableStream<any>): Promise<ReadableStream<any>>;
2141
- /**
2142
- * Processes a list of migrations on a data stream, applying transformations
2143
- * in the specified direction (forward or backward).
2144
- *
2145
- * @static
2146
- * @async
2147
- * @param {ReadableStream<any>} input - The input data stream to process
2148
- * @param {"forward" | "backward"} direction - Direction of migration (either "forward" or "backward")
2149
- * @param {Array<Migration<any>>} migrations - Array of Migration objects to process
2150
- * @returns {Promise<ReadableStream<any>>} Transformed data stream
2151
- * @throws {MigrationError} If any migration processing fails
2152
- */
2153
- static processMigrationList(input: ReadableStream<any>, direction: "forward" | "backward", migrations: Migration<any>[]): Promise<ReadableStream<any>>;
2154
- /**
2155
- * Resolves the transform function for a given migration in the specified direction.
2156
- *
2157
- * @private
2158
- * @async
2159
- * @param {Migration<any>} migration - The migration to resolve the transform for
2160
- * @param {"forward" | "backward"} direction - Direction of migration
2161
- * @returns {Promise<TransformFunction<any, any>>} Resolved transform function
2162
- * @throws {MigrationError} If transform resolution fails
2163
- */
2164
- private static resolveTransform;
2165
- /**
2166
- * Resolves a transform function from a remote URL.
2167
- *
2168
- * @private
2169
- * @async
2170
- * @param {string} url - URL of the transform module
2171
- * @param {"forward" | "backward"} direction - Direction of migration
2172
- * @returns {Promise<TransformFunction<any, any>>} Resolved transform function
2173
- * @throws {MigrationError} If resolution fails
2174
- */
2175
- private static resolveRemoteTransform;
2176
- /**
2177
- * Resolves a transform function from a local module path.
2178
- *
2179
- * @private
2180
- * @async
2181
- * @param {string} path - Local module path
2182
- * @param {"forward" | "backward"} direction - Direction of migration
2183
- * @returns {Promise<TransformFunction<any, any>>} Resolved transform function
2184
- * @throws {MigrationError} If resolution fails
2185
- */
2186
- private static resolveLocalTransform;
2187
- /**
2188
- * Transforms the schema either forward or backward
2189
- * @private
2190
- * @param {"forward" | "backward"} direction - Direction of transformation
2191
- * @throws {Error} If transformation fails
2192
- */
2193
- private transformSchema;
1029
+ //#endregion
1030
+ //#region src/validation/validator.d.ts
1031
+ declare class DocumentValidator {
1032
+ private readonly fmap;
1033
+ private readonly graph;
1034
+ private readonly config;
1035
+ protected constructor(graph: ValidationGraph, fmap: PredicateMap, config: ValidationConfig);
1036
+ /**
1037
+ * Full validation: reports missing required fields, unexpected fields,
1038
+ * type mismatches, and constraint violations.
1039
+ */
1040
+ validate(document: Record<string, unknown>): Promise<Issue[]>;
1041
+ /**
1042
+ * Partial-strict validation: suppresses REQUIRED_FIELD_MISSING issues.
1043
+ * Use when validating partial updates (e.g. PATCH payloads).
1044
+ */
1045
+ validatePartial(document: Record<string, unknown>): Promise<Issue[]>;
1046
+ /**
1047
+ * Loose validation: suppresses both REQUIRED_FIELD_MISSING and
1048
+ * UNEXPECTED_FIELD issues. Validates only present fields for type and
1049
+ * constraints.
1050
+ */
1051
+ validateLoose(document: Record<string, unknown>): Promise<Issue[]>;
1052
+ /**
1053
+ * Builds a DocumentValidator from a SchemaDefinition.
1054
+ *
1055
+ * This compiles the schema into a validation DAG exactly once; subsequent
1056
+ * calls to `validate()` / `validatePartial()` / `validateLoose()` traverse
1057
+ * the pre-compiled graph and are fast.
1058
+ *
1059
+ * Throws if the schema contains structural errors that prevent graph construction
1060
+ * (e.g. dangling schema references, composite parts with unsupported types).
1061
+ */
1062
+ static create(schema: SchemaDefinition$1, fmap: PredicateMap, config?: ValidationConfig): Promise<DocumentValidator>;
2194
1063
  }
2195
-
2196
- /**
2197
- * Helper for building schema migrations with forward and rollback changes.
2198
- * @template T The type of data associated with the schema.
2199
- * @param {Readonly<SchemaDefinition>} schema - The original schema to base the migration on.
2200
- * @returns {SchemaMigrationHelper} An object with methods to build migration changes and retrieve the changes.
2201
- */
2202
- declare const createSchemaMigrationHelper: <T>(schema: Readonly<SchemaDefinition>) => SchemaMigrationHelper;
2203
-
2204
- /**
2205
- * Validates a migration object against the standard schema.
2206
- * @template T The expected type of the migration data.
2207
- * @param change The object to validate.
2208
- * @returns A type guard indicating whether the object conforms to Migration<T>.
2209
- * @throws {SchemaValidationError} If validation fails due to an unexpected error.
2210
- */
2211
- declare function validateMigration<T>(change: unknown): change is Migration<T>;
2212
- /**
2213
- * Validates a schema change object against the standard schema.
2214
- * @template T The expected type of the schema change data.
2215
- * @param change The object to validate.
2216
- * @returns A type guard indicating whether the object conforms to SchemaChange<T>.
2217
- * @throws {SchemaValidationError} If validation fails due to an unexpected error.
2218
- */
2219
- declare function validateSchemaChange<T>(change: unknown): change is SchemaChange<T>;
2220
- /**
2221
- * Validates a schema definition object against the standard schema.
2222
- * @param schema The object to validate.
2223
- * @returns A type guard indicating whether the object conforms to SchemaDefinition.
2224
- * @throws {SchemaValidationError} If validation fails due to an unexpected error.
2225
- */
2226
- declare function validateSchemaDefinition(schema: unknown): schema is SchemaDefinition;
2227
- /**
2228
- * Alias for validateSchemaDefinition, provided for convenience.
2229
- */
2230
- declare const validate: typeof validateSchemaDefinition;
2231
-
2232
- /**
2233
- * Represents a group of field definitions with optional metadata.
2234
- */
2235
- interface FieldGroup {
2236
- name: string;
2237
- label: string;
2238
- description?: string;
2239
- fields: FieldDefinition<any>[];
1064
+ //#endregion
1065
+ //#region src/validation/schema-validator.d.ts
1066
+ /**
1067
+ * A dedicated validator for ensuring schema definitions themselves
1068
+ * conform to the meta-schema rules.
1069
+ */
1070
+ declare class SchemaValidator {
1071
+ private static validator;
1072
+ /**
1073
+ * Validates a schema definition against the meta-schema rules.
1074
+ */
1075
+ static validate(schemaDef: SchemaDefinition$1): Promise<Issue[]>;
2240
1076
  }
2241
- /**
2242
- * Extracts all field definitions from a schema, organized into groups based on hint.input.group,
2243
- * including those in nested schemas, with proper path prefixing to represent the field hierarchy.
2244
- * The 'required' property of each field is adjusted to be true only if the field and all its parent
2245
- * fields are required, ensuring alignment with validation behavior.
2246
- *
2247
- * @param schema - The schema definition to extract fields from
2248
- * @returns Array of field groups, each containing grouped field definitions
2249
- */
2250
- declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[];
2251
- /**
2252
- * Generates a default data object from a schema definition, ensuring all fields have values.
2253
- * Fields with explicit defaults use those values; otherwise, type-based defaults are applied.
2254
- * An optional resolver can override type-based defaults for fields without explicit defaults.
2255
- *
2256
- * @param schema - The schema definition to generate defaults from
2257
- * @param options - Optional configuration for custom defaults and discriminators
2258
- * @returns A fully populated default object conforming to the schema’s structure
2259
- */
2260
- declare function schemaDefaults<T>(schema: SchemaDefinition, options?: {
2261
- resolver?: (field: FieldDefinition<any>) => any;
2262
- discriminator?: Record<string, any>;
2263
- }): T;
2264
-
2265
- /**
2266
- * Generates a SHA-256 hash of the input string.
2267
- *
2268
- * @param input - The string to hash.
2269
- * @returns A promise that resolves to the hexadecimal hash string.
2270
- */
2271
- declare const generateSHA256Hash: (input: string) => Promise<string>;
2272
-
2273
- /**
2274
- * Deeply merges a partial update into a target object
2275
- * @param target The complete target object
2276
- * @param update The partial update to apply
2277
- * @returns Updated object of type T
2278
- */
2279
- declare function deepMerge<T extends object>(target: T, update: Partial<T>): T;
2280
-
2281
- /**
2282
- * Converts a SchemaDefinition to TypeScript type definitions
2283
- *
2284
- * Analyzes a schema definition and generates TypeScript type declarations for the main schema,
2285
- * nested schemas, and union types for enum fields and constraints. Uses field.name as-is for field names,
2286
- * capitalized nestedSchema.name for type names, and handles required/optional fields, new types (enum,
2287
- * record, union), discriminated unions with common fields, primitives, arrays, sets, references, and nested
2288
- * structures with strict type safety. Introduces unique generics for each record field and adjusts object
2289
- * fields referencing concrete schemas to use a string | NestedType union.
2290
- *
2291
- * @param schema - The schema definition to convert
2292
- * @param includeComments - Whether to include JSDoc comments (default: true)
2293
- * @param exportTypes - Whether to export the generated types (default: true)
2294
- * @returns TypeScript type definitions as a string
2295
- */
2296
- declare function schemaToTypes(schema: SchemaDefinition, includeComments?: boolean, exportTypes?: boolean): string;
2297
-
2298
- /**
2299
- * Serializes constraint parameters for error messages, handling special types like RegExp.
2300
- *
2301
- * @param params - The parameters to serialize.
2302
- * @returns A string representation for error messages.
2303
- */
2304
- declare function serializeParams(params: any): string;
2305
- /**
2306
- * Creates a validator conforming to StandardSchemaV1 based on a schema definition.
2307
- *
2308
- * @template T - The type of the data object being validated.
2309
- * @param schema - The schema definition.
2310
- * @param constraintsMap - A map of predicate names to validation functions.
2311
- * @returns A StandardSchemaV1 validator.
2312
- */
2313
- declare function createStandardSchemaValidator<T extends Record<string, any>>(schema: SchemaDefinition, constraintsMap: PredicateMap): StandardSchemaV1<T, T>;
2314
- /**
2315
- * Adapts a StandardSchemaV1 validator to React Hook Form's resolver interface.
2316
- */
2317
- declare function formResolver<TFieldValues extends FieldValues>(validator: ReturnType<typeof createStandardSchemaValidator>["~standard"]): (values: TFieldValues, context: unknown, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
2318
-
2319
- /**
2320
- * Calculates the next version number based on schema changes.
2321
- * @param currentVersion - Current semantic version string
2322
- * @param changes - List of schema changes to apply
2323
- * @param currentSchema - Current schema for context
2324
- * @returns Next semantic version string
2325
- * @throws {Error} If version format is invalid or changes are invalid
2326
- */
2327
- declare function calculateNextVersion(currentVersion: string, changes: SchemaChange<any>[], currentSchema?: SchemaDefinition): string;
2328
- /**
2329
- * compareSemanticVersions(a: string, b: string): number
2330
- * Compares two semantic version strings.
2331
- * @param {string} a - The first version string.
2332
- * @param {string} b - The second version string.
2333
- * @returns {number} - A negative number if `a` is smaller, a positive number if `b` is smaller, or 0 if they are equal.
2334
- */
2335
- declare function compareSemanticVersions(a: string, b: string): number;
2336
- /**
2337
- * Sorts an array of semantic version strings in ascending order.
2338
- * @param {string[]} vars - The array of version strings to sort.
2339
- * @returns {string[]} - The sorted array of version strings.
2340
- */
2341
- declare function sortSemanticVars(vars: string[]): string[];
2342
-
2343
- declare function docgen(schema: SchemaDefinition, options?: {
2344
- faker?: Faker;
2345
- }): string;
2346
-
2347
- export { type ArrayHint, type BooleanHint, type CodeHint, type CollectionMetadata, type CollectionTriggerContext, type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type DateHint, type EnumHint, type EventTaskInterface, type FieldDefinition, type FieldGroup, type FieldSchema, type FieldType, type FileHint, type FunctionMap, type GlobalTriggerContext, type GroupDefinition, type IndexDefinition, type IndexType, type InputHint, JsonPatchError, type Metadata, type MetadataFilter, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type NumberHint, type ObjectHint, type ObservabilityInterface, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaHint, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type SecretHint, type SetHint, type SubscriptionInfo, type TaskContext, type TaskInfo, type TaskSchedule, type TextHint, type TransformFunction, type TriggerContext, type TriggerInfo, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, formResolver, generateSHA256Hash, normalizePath, schemaChangeToPatch, schemaDefaults, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
1077
+ //#endregion
1078
+ //#region src/validation/predicates.d.ts
1079
+ declare const metaSchemaPredicateMap: PredicateMap;
1080
+ //#endregion
1081
+ export { AnansiCodec, type AnansiCodecOptions, ComparisonOperator, Compiler, Constraint, ConstraintGroup, ConstraintMetadata, ConstraintRule, ConstraintUnion, container as DataTypes, type DecodeTransforms, DocumentValidator, type EncodeKind, type EncodeTransforms, FD_NO_CHILD, FLAG_COMPRESSED, FLAG_ENCRYPTED, FLAG_HASH_PRESENT, FieldDef, FieldDefinition, type FieldDescriptor, FieldType, IndexCondition, IndexConditionGroup, IndexConditionUnion, IndexDefinition, IndexOrder, IndexType, InlineTypeDescriptor, InlineTypeKind, type Issue, type LinkResult, type LinkedField, type LinkedSlot, Literal, LogicalOperatorEnum, MAX_SCHEMA_SLOTS, MULTI_STEP_BASE, type ManifestField, NestedSchemaDefinition, type PredicateMap, type ResolvedEnum, type ResolvedField, type ResolvedNested, SchemaDefinition, SchemaReference, SchemaReferenceArray, SchemaValidator, type Slot, String, Unknown, type ValidationConfig, addressForSteps, buildEnum, buildManifest, decodeAnansiBatch, decodeAnansiPacket, decodeBatch, decodeDocument, defaultValidationConfig, encodeAnansiBatchColumnar, encodeAnansiBatchRows, encodeAnansiPacket, encodeBatchColumnar, encodeBatchRows, encodeDocument, internalDP, link, makeDescriptor, metaSchemaPredicateMap, parseSchema, unpackDescriptor, userDataDP };