@manassandhu/mint 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Mint - Schema Validation Library
3
+ * Validation context for tracking parsing state and issues.
4
+ */
5
+
6
+ import { createIssue } from "../errors/MintError.js";
7
+
8
+ export class ParseContext {
9
+ constructor({
10
+ path = [],
11
+ issues = [],
12
+ data,
13
+ parent = null,
14
+ } = {}) {
15
+ this.path = [...path];
16
+ this.issues = issues;
17
+ this.data = data;
18
+ this.parent = parent;
19
+ }
20
+
21
+ get hasIssues() {
22
+ return this.issues.length > 0;
23
+ }
24
+
25
+ get issueCount() {
26
+ return this.issues.length;
27
+ }
28
+
29
+ addIssue(issue) {
30
+ const normalizedIssue = createIssue({
31
+ ...issue,
32
+ path: issue.path ?? this.path,
33
+ });
34
+
35
+ this.issues.push(normalizedIssue);
36
+
37
+ return normalizedIssue;
38
+ }
39
+
40
+ child(segment, data) {
41
+ return new ParseContext({
42
+ path: [...this.path, segment],
43
+ issues: this.issues,
44
+ data,
45
+ parent: this,
46
+ });
47
+ }
48
+
49
+ fork({
50
+ path = this.path,
51
+ data = this.data,
52
+ } = {}) {
53
+ return new ParseContext({
54
+ path,
55
+ issues: this.issues,
56
+ data,
57
+ parent: this,
58
+ });
59
+ }
60
+
61
+ getIssuesSince(index = 0) {
62
+ return this.issues.slice(index);
63
+ }
64
+
65
+ checkpoint() {
66
+ return this.issues.length;
67
+ }
68
+
69
+ hasIssuesSince(checkpoint) {
70
+ return this.issues.length > checkpoint;
71
+ }
72
+
73
+ mergeIssues(issues) {
74
+ for (const issue of issues) {
75
+ this.issues.push(issue);
76
+ }
77
+ }
78
+
79
+ clearIssues() {
80
+ this.issues.length = 0;
81
+ }
82
+ }
@@ -0,0 +1,513 @@
1
+ /**
2
+ * Mint - Schema Validation Library
3
+ * Core schema abstraction and schema wrappers.
4
+ */
5
+
6
+ import { MintError } from "../errors/MintError.js";
7
+ import { ParseContext } from "./ParseContext.js";
8
+
9
+ export class Schema {
10
+ constructor(definition = {}) {
11
+ this._def = Object.freeze({ ...definition });
12
+ }
13
+
14
+ _parse(context, value) {
15
+ throw new Error(
16
+ `${this.constructor.name} must implement _parse().`
17
+ );
18
+ }
19
+
20
+ /**
21
+ * Async parsing hook.
22
+ * Schemas without async behavior can reuse their synchronous parser.
23
+ */
24
+ async _parseAsync(context, value) {
25
+ return this._parse(context, value);
26
+ }
27
+
28
+ parse(value) {
29
+ const context = new ParseContext({ data: value });
30
+ const result = this._parse(context, value);
31
+
32
+ if (isPromise(result)) {
33
+ throw new Error(
34
+ "Asynchronous validation detected. Use parseAsync() instead."
35
+ );
36
+ }
37
+
38
+ if (context.hasIssues) {
39
+ throw new MintError(context.issues);
40
+ }
41
+
42
+ return result;
43
+ }
44
+
45
+ safeParse(value) {
46
+ try {
47
+ const context = new ParseContext({ data: value });
48
+ const result = this._parse(context, value);
49
+
50
+ if (isPromise(result)) {
51
+ throw new Error(
52
+ "Asynchronous validation detected. Use safeParseAsync() instead."
53
+ );
54
+ }
55
+
56
+ if (context.hasIssues) {
57
+ return {
58
+ success: false,
59
+ error: new MintError(context.issues),
60
+ };
61
+ }
62
+
63
+ return {
64
+ success: true,
65
+ data: result,
66
+ };
67
+ } catch (error) {
68
+ if (error instanceof MintError) {
69
+ return {
70
+ success: false,
71
+ error,
72
+ };
73
+ }
74
+
75
+ throw error;
76
+ }
77
+ }
78
+
79
+ async parseAsync(value) {
80
+ const context = new ParseContext({ data: value });
81
+ const result = await this._parseAsync(context, value);
82
+
83
+ if (context.hasIssues) {
84
+ throw new MintError(context.issues);
85
+ }
86
+
87
+ return result;
88
+ }
89
+
90
+ async safeParseAsync(value) {
91
+ try {
92
+ const context = new ParseContext({ data: value });
93
+ const result = await this._parseAsync(context, value);
94
+
95
+ if (context.hasIssues) {
96
+ return {
97
+ success: false,
98
+ error: new MintError(context.issues),
99
+ };
100
+ }
101
+
102
+ return {
103
+ success: true,
104
+ data: result,
105
+ };
106
+ } catch (error) {
107
+ if (error instanceof MintError) {
108
+ return {
109
+ success: false,
110
+ error,
111
+ };
112
+ }
113
+
114
+ throw error;
115
+ }
116
+ }
117
+
118
+ optional() {
119
+ return new OptionalSchema(this);
120
+ }
121
+
122
+ nullable() {
123
+ return new NullableSchema(this);
124
+ }
125
+
126
+ nullish() {
127
+ return this.nullable().optional();
128
+ }
129
+
130
+ default(value) {
131
+ return new DefaultSchema(this, value);
132
+ }
133
+
134
+ refine(predicate, options = {}) {
135
+ return new RefinementSchema(this, predicate, options);
136
+ }
137
+
138
+ transform(transformer) {
139
+ return new TransformSchema(this, transformer);
140
+ }
141
+
142
+ pipe(schema) {
143
+ return new PipeSchema(this, schema);
144
+ }
145
+
146
+ describe(description) {
147
+ return new MetadataSchema(this, { description });
148
+ }
149
+
150
+ meta(metadata = {}) {
151
+ return new MetadataSchema(this, metadata);
152
+ }
153
+
154
+ get description() {
155
+ return this._def.description;
156
+ }
157
+
158
+ get metadata() {
159
+ return this._def.metadata ?? {};
160
+ }
161
+
162
+ get type() {
163
+ return this._def.type ?? "unknown";
164
+ }
165
+ }
166
+
167
+ /* ================================================
168
+ Wrapper Schemas
169
+ ================================================ */
170
+
171
+ /**
172
+ * Accepts undefined.
173
+ */
174
+ export class OptionalSchema extends Schema {
175
+ constructor(schema) {
176
+ super({
177
+ type: "optional",
178
+ innerType: schema,
179
+ });
180
+
181
+ this.schema = schema;
182
+ }
183
+
184
+ _parse(context, value) {
185
+ if (value === undefined) {
186
+ return undefined;
187
+ }
188
+
189
+ return this.schema._parse(context, value);
190
+ }
191
+
192
+ async _parseAsync(context, value) {
193
+ if (value === undefined) {
194
+ return undefined;
195
+ }
196
+
197
+ return this.schema._parseAsync(context, value);
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Accepts null.
203
+ */
204
+ export class NullableSchema extends Schema {
205
+ constructor(schema) {
206
+ super({
207
+ type: "nullable",
208
+ innerType: schema,
209
+ });
210
+
211
+ this.schema = schema;
212
+ }
213
+
214
+ _parse(context, value) {
215
+ if (value === null) {
216
+ return null;
217
+ }
218
+
219
+ return this.schema._parse(context, value);
220
+ }
221
+
222
+ async _parseAsync(context, value) {
223
+ if (value === null) {
224
+ return null;
225
+ }
226
+
227
+ return this.schema._parseAsync(context, value);
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Applies a fallback for undefined input.
233
+ */
234
+ export class DefaultSchema extends Schema {
235
+ constructor(schema, defaultValue) {
236
+ super({
237
+ type: "default",
238
+ innerType: schema,
239
+ defaultValue,
240
+ });
241
+
242
+ this.schema = schema;
243
+ this.defaultValue = defaultValue;
244
+ }
245
+
246
+ _getDefault() {
247
+ return typeof this.defaultValue === "function"
248
+ ? this.defaultValue()
249
+ : this.defaultValue;
250
+ }
251
+
252
+ _parse(context, value) {
253
+ const resolvedValue =
254
+ value === undefined
255
+ ? this._getDefault()
256
+ : value;
257
+
258
+ return this.schema._parse(context, resolvedValue);
259
+ }
260
+
261
+ async _parseAsync(context, value) {
262
+ const resolvedValue =
263
+ value === undefined
264
+ ? this._getDefault()
265
+ : value;
266
+
267
+ return this.schema._parseAsync(context, resolvedValue);
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Adds custom validation.
273
+ */
274
+ export class RefinementSchema extends Schema {
275
+ constructor(schema, predicate, options = {}) {
276
+ super({
277
+ type: "refinement",
278
+ innerType: schema,
279
+ options,
280
+ });
281
+
282
+ this.schema = schema;
283
+ this.predicate = predicate;
284
+ this.options = options;
285
+ }
286
+
287
+ _parse(context, value) {
288
+ const checkpoint = context.checkpoint();
289
+ const parsedValue = this.schema._parse(context, value);
290
+
291
+ if (isPromise(parsedValue)) {
292
+ throw new Error(
293
+ "Asynchronous refinement detected. Use parseAsync()."
294
+ );
295
+ }
296
+
297
+ if (context.hasIssuesSince(checkpoint)) {
298
+ return parsedValue;
299
+ }
300
+
301
+ const valid = this.predicate(parsedValue);
302
+
303
+ if (isPromise(valid)) {
304
+ throw new Error(
305
+ "Asynchronous refinement detected. Use parseAsync()."
306
+ );
307
+ }
308
+
309
+ if (!valid) {
310
+ context.addIssue({
311
+ code: this.options.code ?? "custom",
312
+ message:
313
+ this.options.message ??
314
+ "Custom validation failed",
315
+ path: this.options.path
316
+ ? [...context.path, ...this.options.path]
317
+ : context.path,
318
+ });
319
+ }
320
+
321
+ return parsedValue;
322
+ }
323
+
324
+ async _parseAsync(context, value) {
325
+ const checkpoint = context.checkpoint();
326
+
327
+ const parsedValue = await this.schema._parseAsync(
328
+ context,
329
+ value
330
+ );
331
+
332
+ if (context.hasIssuesSince(checkpoint)) {
333
+ return parsedValue;
334
+ }
335
+
336
+ const valid = await this.predicate(parsedValue);
337
+
338
+ if (!valid) {
339
+ context.addIssue({
340
+ code: this.options.code ?? "custom",
341
+ message:
342
+ this.options.message ??
343
+ "Custom validation failed",
344
+ path: this.options.path
345
+ ? [...context.path, ...this.options.path]
346
+ : context.path,
347
+ });
348
+ }
349
+
350
+ return parsedValue;
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Transforms validated data.
356
+ */
357
+ export class TransformSchema extends Schema {
358
+ constructor(schema, transformer) {
359
+ super({
360
+ type: "transform",
361
+ innerType: schema,
362
+ });
363
+
364
+ this.schema = schema;
365
+ this.transformer = transformer;
366
+ }
367
+
368
+ _parse(context, value) {
369
+ const checkpoint = context.checkpoint();
370
+ const parsedValue = this.schema._parse(context, value);
371
+
372
+ if (isPromise(parsedValue)) {
373
+ throw new Error(
374
+ "Asynchronous transformation detected. Use parseAsync()."
375
+ );
376
+ }
377
+
378
+ if (context.hasIssuesSince(checkpoint)) {
379
+ return parsedValue;
380
+ }
381
+
382
+ const transformedValue = this.transformer(parsedValue);
383
+
384
+ if (isPromise(transformedValue)) {
385
+ throw new Error(
386
+ "Asynchronous transformation detected. Use parseAsync()."
387
+ );
388
+ }
389
+
390
+ return transformedValue;
391
+ }
392
+
393
+ async _parseAsync(context, value) {
394
+ const checkpoint = context.checkpoint();
395
+
396
+ const parsedValue = await this.schema._parseAsync(
397
+ context,
398
+ value
399
+ );
400
+
401
+ if (context.hasIssuesSince(checkpoint)) {
402
+ return parsedValue;
403
+ }
404
+
405
+ return await this.transformer(parsedValue);
406
+ }
407
+ }
408
+
409
+ /**
410
+ * Pipes output into another schema.
411
+ */
412
+ export class PipeSchema extends Schema {
413
+ constructor(firstSchema, secondSchema) {
414
+ super({
415
+ type: "pipe",
416
+ inputType: firstSchema,
417
+ outputType: secondSchema,
418
+ });
419
+
420
+ this.firstSchema = firstSchema;
421
+ this.secondSchema = secondSchema;
422
+ }
423
+
424
+ _parse(context, value) {
425
+ const checkpoint = context.checkpoint();
426
+
427
+ const intermediateValue = this.firstSchema._parse(
428
+ context,
429
+ value
430
+ );
431
+
432
+ if (isPromise(intermediateValue)) {
433
+ throw new Error(
434
+ "Asynchronous piping detected. Use parseAsync()."
435
+ );
436
+ }
437
+
438
+ if (context.hasIssuesSince(checkpoint)) {
439
+ return intermediateValue;
440
+ }
441
+
442
+ return this.secondSchema._parse(
443
+ context,
444
+ intermediateValue
445
+ );
446
+ }
447
+
448
+ async _parseAsync(context, value) {
449
+ const checkpoint = context.checkpoint();
450
+
451
+ const intermediateValue = await this.firstSchema._parseAsync(
452
+ context,
453
+ value
454
+ );
455
+
456
+ if (context.hasIssuesSince(checkpoint)) {
457
+ return intermediateValue;
458
+ }
459
+
460
+ return this.secondSchema._parseAsync(
461
+ context,
462
+ intermediateValue
463
+ );
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Adds metadata to schemas.
469
+ */
470
+ export class MetadataSchema extends Schema {
471
+ constructor(schema, metadata = {}) {
472
+ const mergedMetadata = {
473
+ ...schema.metadata,
474
+ ...metadata,
475
+ };
476
+
477
+ super({
478
+ type: "metadata",
479
+ innerType: schema,
480
+ metadata: mergedMetadata,
481
+ description:
482
+ metadata.description ??
483
+ schema.description,
484
+ });
485
+
486
+ this.schema = schema;
487
+ this._metadata = Object.freeze(mergedMetadata);
488
+ }
489
+
490
+ _parse(context, value) {
491
+ return this.schema._parse(context, value);
492
+ }
493
+
494
+ async _parseAsync(context, value) {
495
+ return this.schema._parseAsync(context, value);
496
+ }
497
+
498
+ get description() {
499
+ return this._def.description;
500
+ }
501
+
502
+ get metadata() {
503
+ return this._metadata;
504
+ }
505
+ }
506
+
507
+ function isPromise(value) {
508
+ return (
509
+ value !== null &&
510
+ (typeof value === "object" || typeof value === "function") &&
511
+ typeof value.then === "function"
512
+ );
513
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Mint - Schema Validation Library
3
+ * Re-exports wrapper schema classes.
4
+ */
5
+
6
+ export {
7
+ OptionalSchema,
8
+ NullableSchema,
9
+ DefaultSchema,
10
+ RefinementSchema,
11
+ TransformSchema,
12
+ PipeSchema,
13
+ MetadataSchema,
14
+ } from "./Schema.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Mint - Core exports.
3
+ */
4
+
5
+ export { Schema } from "./Schema.js";
6
+
7
+ export {
8
+ OptionalSchema,
9
+ NullableSchema,
10
+ DefaultSchema,
11
+ RefinementSchema,
12
+ TransformSchema,
13
+ PipeSchema,
14
+ MetadataSchema,
15
+ } from "./WrapperSchemas.js";
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Mint - Schema Validation Library
3
+ * Core validation error system.
4
+ */
5
+
6
+ export class MintError extends Error {
7
+ constructor(issues, message = "Validation failed") {
8
+ super(message);
9
+
10
+ this.name = "MintError";
11
+ this.issues = issues;
12
+
13
+ if (Error.captureStackTrace) {
14
+ Error.captureStackTrace(this, MintError);
15
+ }
16
+ }
17
+
18
+ get errors() {
19
+ return this.issues;
20
+ }
21
+
22
+ format() {
23
+ const formatted = {};
24
+
25
+ for (const issue of this.issues) {
26
+ let current = formatted;
27
+
28
+ for (const segment of issue.path) {
29
+ const key = String(segment);
30
+
31
+ if (!current[key]) {
32
+ current[key] = {};
33
+ }
34
+
35
+ current = current[key];
36
+ }
37
+
38
+ if (!current._errors) {
39
+ current._errors = [];
40
+ }
41
+
42
+ current._errors.push(issue.message);
43
+ }
44
+
45
+ return formatted;
46
+ }
47
+
48
+ flatten() {
49
+ const fieldErrors = {};
50
+ const formErrors = [];
51
+
52
+ for (const issue of this.issues) {
53
+ if (issue.path.length === 0) {
54
+ formErrors.push(issue.message);
55
+ continue;
56
+ }
57
+
58
+ const field = String(issue.path[0]);
59
+
60
+ if (!fieldErrors[field]) {
61
+ fieldErrors[field] = [];
62
+ }
63
+
64
+ fieldErrors[field].push(issue.message);
65
+ }
66
+
67
+ return {
68
+ formErrors,
69
+ fieldErrors,
70
+ };
71
+ }
72
+
73
+ toString() {
74
+ return this.issues
75
+ .map((issue) => {
76
+ const path =
77
+ issue.path.length > 0
78
+ ? issue.path.join(".")
79
+ : "(root)";
80
+
81
+ return `${path}: ${issue.message}`;
82
+ })
83
+ .join("\n");
84
+ }
85
+ }
86
+
87
+ export function createIssue({
88
+ code,
89
+ path = [],
90
+ message,
91
+ ...metadata
92
+ }) {
93
+ return {
94
+ code,
95
+ path: [...path],
96
+ message,
97
+ ...metadata,
98
+ };
99
+ }
100
+
101
+ export function formatIssue(issue) {
102
+ const path =
103
+ issue.path.length > 0
104
+ ? issue.path.join(".")
105
+ : "(root)";
106
+
107
+ return `${path}: ${issue.message}`;
108
+ }