@regle/schemas 0.7.4 → 0.7.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/regle-schemas.cjs +282 -110
- package/dist/regle-schemas.d.cts +8 -5
- package/dist/regle-schemas.d.ts +8 -5
- package/dist/regle-schemas.min.cjs +1 -1
- package/dist/regle-schemas.min.mjs +1 -1
- package/dist/regle-schemas.mjs +282 -87
- package/package.json +17 -7
package/dist/regle-schemas.cjs
CHANGED
|
@@ -3,31 +3,6 @@
|
|
|
3
3
|
var core = require('@regle/core');
|
|
4
4
|
var vue = require('vue');
|
|
5
5
|
var rules = require('@regle/rules');
|
|
6
|
-
var v3 = require('valibot');
|
|
7
|
-
var z = require('zod');
|
|
8
|
-
|
|
9
|
-
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
10
|
-
|
|
11
|
-
function _interopNamespace(e) {
|
|
12
|
-
if (e && e.__esModule) return e;
|
|
13
|
-
var n = Object.create(null);
|
|
14
|
-
if (e) {
|
|
15
|
-
Object.keys(e).forEach(function (k) {
|
|
16
|
-
if (k !== 'default') {
|
|
17
|
-
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
18
|
-
Object.defineProperty(n, k, d.get ? d : {
|
|
19
|
-
enumerable: true,
|
|
20
|
-
get: function () { return e[k]; }
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
});
|
|
24
|
-
}
|
|
25
|
-
n.default = e;
|
|
26
|
-
return Object.freeze(n);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
var v3__namespace = /*#__PURE__*/_interopNamespace(v3);
|
|
30
|
-
var z__default = /*#__PURE__*/_interopDefault(z);
|
|
31
6
|
|
|
32
7
|
// src/core/useRegleSchema.ts
|
|
33
8
|
|
|
@@ -130,7 +105,7 @@ function transformValibotAdapter(schema) {
|
|
|
130
105
|
if (result instanceof Promise) {
|
|
131
106
|
return result;
|
|
132
107
|
}
|
|
133
|
-
if (result.
|
|
108
|
+
if (!result.issues) {
|
|
134
109
|
return {
|
|
135
110
|
$valid: true,
|
|
136
111
|
$issues: []
|
|
@@ -151,8 +126,8 @@ function trySafeTransform(schema, value) {
|
|
|
151
126
|
try {
|
|
152
127
|
if (schema.async) {
|
|
153
128
|
return new Promise(async (resolve) => {
|
|
154
|
-
const result = await
|
|
155
|
-
if (result.
|
|
129
|
+
const result = await schema["~standard"].validate(value);
|
|
130
|
+
if (!result.issues) {
|
|
156
131
|
resolve({
|
|
157
132
|
$valid: true,
|
|
158
133
|
$issues: []
|
|
@@ -165,7 +140,7 @@ function trySafeTransform(schema, value) {
|
|
|
165
140
|
}
|
|
166
141
|
});
|
|
167
142
|
} else {
|
|
168
|
-
const result =
|
|
143
|
+
const result = schema["~standard"].validate(value);
|
|
169
144
|
return result;
|
|
170
145
|
}
|
|
171
146
|
} catch (e) {
|
|
@@ -183,8 +158,6 @@ function isObjectSchema(schema) {
|
|
|
183
158
|
function isWrappedType(schema) {
|
|
184
159
|
return "wrapped" in schema;
|
|
185
160
|
}
|
|
186
|
-
|
|
187
|
-
// src/core/converters/valibot/validators/valibotObjectToRegle.ts
|
|
188
161
|
function getNestedValibotObjectSchema(schema) {
|
|
189
162
|
if (isIntersectSchema(schema)) {
|
|
190
163
|
const allEntries = schema.options.reduce(
|
|
@@ -200,7 +173,7 @@ function getNestedValibotObjectSchema(schema) {
|
|
|
200
173
|
},
|
|
201
174
|
{}
|
|
202
175
|
);
|
|
203
|
-
return
|
|
176
|
+
return { entries: allEntries, type: "object", kind: "schema", async: false };
|
|
204
177
|
} else if (isObjectSchema(schema)) {
|
|
205
178
|
return schema;
|
|
206
179
|
} else if (isWrappedType(schema)) {
|
|
@@ -274,7 +247,10 @@ function valibotVariantToRegle(schema, state) {
|
|
|
274
247
|
function extractIssuesMessages() {
|
|
275
248
|
return (metadata) => {
|
|
276
249
|
const issueMessages = metadata.$issues?.map((issue) => issue.message);
|
|
277
|
-
|
|
250
|
+
if (issueMessages?.length) {
|
|
251
|
+
return issueMessages.length ? issueMessages : "Error";
|
|
252
|
+
}
|
|
253
|
+
return [];
|
|
278
254
|
};
|
|
279
255
|
}
|
|
280
256
|
|
|
@@ -316,10 +292,13 @@ function valibotArrayToRegle(schema, state) {
|
|
|
316
292
|
let filteredSelfSchema = {};
|
|
317
293
|
if ("pipe" in schema) {
|
|
318
294
|
schema.pipe.filter((f) => f.kind === "validation").forEach((validation) => {
|
|
319
|
-
filteredSelfSchema[validation.type] = rules.withMessage(
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
295
|
+
filteredSelfSchema[validation.type] = rules.withMessage((value) => {
|
|
296
|
+
const result = validation["~run"]({ value, typed: true }, {});
|
|
297
|
+
return {
|
|
298
|
+
$valid: !result.issues,
|
|
299
|
+
$issues: result.issues
|
|
300
|
+
};
|
|
301
|
+
}, extractIssuesMessages());
|
|
323
302
|
});
|
|
324
303
|
}
|
|
325
304
|
return {
|
|
@@ -327,9 +306,16 @@ function valibotArrayToRegle(schema, state) {
|
|
|
327
306
|
...filteredSelfSchema
|
|
328
307
|
};
|
|
329
308
|
}
|
|
330
|
-
function transformZodValidatorAdapter(schema) {
|
|
309
|
+
function transformZodValidatorAdapter(schema, additionalIssues) {
|
|
331
310
|
const isAsync = hasAsyncRefinement(schema);
|
|
332
|
-
|
|
311
|
+
function validatorFn(value) {
|
|
312
|
+
if (additionalIssues?.value?.length) {
|
|
313
|
+
return {
|
|
314
|
+
$valid: false,
|
|
315
|
+
// additionalIssues should already contain field error if there is a refinement in a parent
|
|
316
|
+
$issues: additionalIssues.value
|
|
317
|
+
};
|
|
318
|
+
}
|
|
333
319
|
const result = trySafeTransform2(schema, value);
|
|
334
320
|
if (result instanceof Promise) {
|
|
335
321
|
return result;
|
|
@@ -342,38 +328,43 @@ function transformZodValidatorAdapter(schema) {
|
|
|
342
328
|
} else {
|
|
343
329
|
return {
|
|
344
330
|
$valid: false,
|
|
345
|
-
|
|
331
|
+
// additionalIssues should already contain field error if there is a refinement in a parent
|
|
332
|
+
$issues: result.error?.issues ?? []
|
|
346
333
|
};
|
|
347
334
|
}
|
|
348
|
-
}
|
|
349
|
-
if ("__depsArray" in schema && Array.isArray(schema.__depsArray) && schema.__depsArray.length) {
|
|
335
|
+
}
|
|
336
|
+
if (schema && "__depsArray" in schema && Array.isArray(schema.__depsArray) && schema.__depsArray.length) {
|
|
350
337
|
return isAsync ? rules.withAsync(validatorFn, schema.__depsArray) : rules.withParams(validatorFn, schema.__depsArray);
|
|
351
338
|
}
|
|
352
339
|
return isAsync ? rules.withAsync(validatorFn) : validatorFn;
|
|
353
340
|
}
|
|
354
341
|
function trySafeTransform2(schema, value) {
|
|
355
|
-
|
|
356
|
-
const result = schema.safeParse(value);
|
|
357
|
-
return result;
|
|
358
|
-
} catch (e) {
|
|
342
|
+
if (schema) {
|
|
359
343
|
try {
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
344
|
+
const result = schema.safeParse(value);
|
|
345
|
+
return result;
|
|
346
|
+
} catch (e) {
|
|
347
|
+
try {
|
|
348
|
+
return new Promise(async (resolve) => {
|
|
349
|
+
const result = await schema.safeParseAsync(value);
|
|
350
|
+
if (result.success) {
|
|
351
|
+
resolve({
|
|
352
|
+
$valid: true,
|
|
353
|
+
$issues: []
|
|
354
|
+
});
|
|
355
|
+
} else {
|
|
356
|
+
resolve({
|
|
357
|
+
$valid: false,
|
|
358
|
+
$issues: result.error?.issues
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
} catch (e2) {
|
|
363
|
+
return {};
|
|
364
|
+
}
|
|
376
365
|
}
|
|
366
|
+
} else {
|
|
367
|
+
return { success: true, data: {} };
|
|
377
368
|
}
|
|
378
369
|
}
|
|
379
370
|
function isAsyncFunctionOrPromiseReturning(fn) {
|
|
@@ -415,7 +406,7 @@ function hasAsyncRefinement(schema) {
|
|
|
415
406
|
}
|
|
416
407
|
return false;
|
|
417
408
|
}
|
|
418
|
-
function zodDiscriminatedUnionToRegle(schema, state) {
|
|
409
|
+
function zodDiscriminatedUnionToRegle(schema, state, additionalIssues) {
|
|
419
410
|
const scope = vue.effectScope();
|
|
420
411
|
const scopeState = scope.run(() => {
|
|
421
412
|
const zodRule = vue.ref({});
|
|
@@ -428,7 +419,14 @@ function zodDiscriminatedUnionToRegle(schema, state) {
|
|
|
428
419
|
zodRule.value = Object.fromEntries(
|
|
429
420
|
Object.entries(selectedDiscriminant._def.shape()).map(([key, shape]) => {
|
|
430
421
|
if (typeof shape === "object" && "_def" in shape) {
|
|
431
|
-
return [
|
|
422
|
+
return [
|
|
423
|
+
key,
|
|
424
|
+
processZodTypeDef({
|
|
425
|
+
schema: shape,
|
|
426
|
+
state: vue.toRef(isObject(state.value) ? state.value : {}),
|
|
427
|
+
additionalIssues
|
|
428
|
+
})
|
|
429
|
+
];
|
|
432
430
|
}
|
|
433
431
|
return [key, {}];
|
|
434
432
|
})
|
|
@@ -453,13 +451,7 @@ function zodDiscriminatedUnionToRegle(schema, state) {
|
|
|
453
451
|
}
|
|
454
452
|
|
|
455
453
|
// src/core/converters/zod/processZodTypeDef.ts
|
|
456
|
-
var typesWithInnerTypes = [
|
|
457
|
-
z__default.default.ZodFirstPartyTypeKind.ZodDefault,
|
|
458
|
-
z__default.default.ZodFirstPartyTypeKind.ZodCatch,
|
|
459
|
-
z__default.default.ZodFirstPartyTypeKind.ZodNullable,
|
|
460
|
-
z__default.default.ZodFirstPartyTypeKind.ZodOptional,
|
|
461
|
-
z__default.default.ZodFirstPartyTypeKind.ZodReadonly
|
|
462
|
-
];
|
|
454
|
+
var typesWithInnerTypes = ["ZodDefault", "ZodCatch", "ZodNullable", "ZodOptional", "ZodReadonly"];
|
|
463
455
|
function isDefWithInnerType(schema) {
|
|
464
456
|
if (schema._def && typeof schema._def === "object" && "typeName" in schema._def) {
|
|
465
457
|
return typesWithInnerTypes.includes(schema._def.typeName);
|
|
@@ -484,17 +476,39 @@ function getNestedInnerType2(schema) {
|
|
|
484
476
|
}
|
|
485
477
|
return undefined;
|
|
486
478
|
}
|
|
487
|
-
function processZodTypeDef(
|
|
479
|
+
function processZodTypeDef({
|
|
480
|
+
schema,
|
|
481
|
+
state,
|
|
482
|
+
additionalIssues
|
|
483
|
+
}) {
|
|
488
484
|
const schemaDef = getNestedInnerType2(schema);
|
|
489
485
|
if (schemaDef?._def && "typeName" in schemaDef._def) {
|
|
490
|
-
if (schemaDef._def.typeName ===
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
486
|
+
if (schemaDef._def.typeName === "ZodArray" || schemaDef._def.typeName === "ZodTuple") {
|
|
487
|
+
const schemaRef = zodArrayToRegle(schema, state, additionalIssues);
|
|
488
|
+
return schemaRef.zodRule;
|
|
489
|
+
} else if (schemaDef._def.typeName === "ZodObject" || schemaDef._def.typeName === "ZodIntersection") {
|
|
490
|
+
const schemaRef = zodObjectToRegle(
|
|
491
|
+
schemaDef,
|
|
492
|
+
state,
|
|
493
|
+
additionalIssues
|
|
494
|
+
);
|
|
495
|
+
return schemaRef.zodRule;
|
|
496
|
+
} else if (schemaDef._def.typeName === "ZodDiscriminatedUnion") {
|
|
497
|
+
const schemaRef = zodDiscriminatedUnionToRegle(
|
|
498
|
+
schemaDef,
|
|
499
|
+
state,
|
|
500
|
+
additionalIssues
|
|
501
|
+
);
|
|
502
|
+
return schemaRef.zodRule;
|
|
497
503
|
} else {
|
|
504
|
+
if (additionalIssues) {
|
|
505
|
+
return {
|
|
506
|
+
[schemaDef.constructor.name]: rules.withMessage(
|
|
507
|
+
rules.withParams(transformZodValidatorAdapter(schema, additionalIssues), [state]),
|
|
508
|
+
extractIssuesMessages()
|
|
509
|
+
)
|
|
510
|
+
};
|
|
511
|
+
}
|
|
498
512
|
return {
|
|
499
513
|
[schemaDef.constructor.name]: rules.withMessage(
|
|
500
514
|
transformZodValidatorAdapter(schema),
|
|
@@ -507,52 +521,190 @@ function processZodTypeDef(schema, state) {
|
|
|
507
521
|
}
|
|
508
522
|
|
|
509
523
|
// src/core/converters/zod/validators/zodArrayToRegle.ts
|
|
510
|
-
function
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
}
|
|
524
|
+
function getNestedZodArraySchema(schema, effects = []) {
|
|
525
|
+
if (schema._def && "typeName" in schema._def) {
|
|
526
|
+
if (schema._def.typeName === "ZodEffects") {
|
|
527
|
+
return getNestedZodArraySchema(
|
|
528
|
+
schema._def.schema,
|
|
529
|
+
effects.concat([schema._def.effect])
|
|
530
|
+
);
|
|
531
|
+
} else {
|
|
532
|
+
return { nestedSchema: schema, nestedEffects: effects };
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return { nestedSchema: undefined };
|
|
536
|
+
}
|
|
537
|
+
function zodArrayToRegle(schema, state, rootAdditionalIssues) {
|
|
538
|
+
const { nestedSchema, nestedEffects } = getNestedZodArraySchema(schema);
|
|
539
|
+
const zodRule = vue.ref({});
|
|
540
|
+
if (nestedSchema) {
|
|
541
|
+
const arrayValidators = nestedSchema._def.typeName === "ZodArray" ? {
|
|
542
|
+
...!!nestedSchema._def.minLength && { minLength: rules.minLength(nestedSchema._def.minLength?.value) },
|
|
543
|
+
...!!nestedSchema._def.maxLength && { maxLength: rules.maxLength(nestedSchema._def.maxLength?.value) },
|
|
544
|
+
...!!nestedSchema._def.exactLength && { exactLength: rules.exactLength(nestedSchema._def.exactLength?.value) }
|
|
545
|
+
} : {};
|
|
546
|
+
if (nestedEffects?.length) {
|
|
547
|
+
const scope = vue.effectScope();
|
|
548
|
+
scope.run(() => {
|
|
549
|
+
const localAdditionalIssues = vue.ref([]);
|
|
550
|
+
const additionalIssues = vue.computed(() => {
|
|
551
|
+
return localAdditionalIssues.value.concat(rootAdditionalIssues?.value ?? []);
|
|
552
|
+
});
|
|
553
|
+
if (!rootAdditionalIssues) {
|
|
554
|
+
vue.watch(
|
|
555
|
+
state,
|
|
556
|
+
() => {
|
|
557
|
+
if (nestedSchema) {
|
|
558
|
+
localAdditionalIssues.value = schema.safeParse(state.value).error?.issues.filter((f) => f.code === "custom") ?? [];
|
|
559
|
+
}
|
|
560
|
+
},
|
|
561
|
+
{ deep: true, immediate: true }
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
if (nestedSchema) {
|
|
565
|
+
const items = nestedSchema._def.typeName === "ZodArray" ? nestedSchema._def.type : nestedSchema._def.items;
|
|
566
|
+
const selfAdditionalIssues = vue.computed(() => additionalIssues.value.filter((f) => !f.path.length));
|
|
567
|
+
zodRule.value = {
|
|
568
|
+
$each: (_, index) => {
|
|
569
|
+
const fieldIssues = vue.computed(() => {
|
|
570
|
+
return additionalIssues.value?.filter((f) => f.code === "custom")?.filter((f) => f.path[0] === index.toString()).map((m) => {
|
|
571
|
+
const [first, ...rest] = m.path;
|
|
572
|
+
return {
|
|
573
|
+
...m,
|
|
574
|
+
path: rest
|
|
575
|
+
};
|
|
576
|
+
});
|
|
577
|
+
});
|
|
578
|
+
return processZodTypeDef({ schema: items, state, additionalIssues: fieldIssues });
|
|
579
|
+
},
|
|
580
|
+
selfValidator: rules.withMessage(
|
|
581
|
+
rules.withParams(transformZodValidatorAdapter(undefined, selfAdditionalIssues), [
|
|
582
|
+
state,
|
|
583
|
+
selfAdditionalIssues
|
|
584
|
+
]),
|
|
585
|
+
extractIssuesMessages()
|
|
586
|
+
)
|
|
587
|
+
};
|
|
588
|
+
} else {
|
|
589
|
+
zodRule.value = {};
|
|
590
|
+
}
|
|
591
|
+
vue.onScopeDispose(() => {
|
|
592
|
+
scope.stop();
|
|
593
|
+
});
|
|
594
|
+
});
|
|
595
|
+
} else {
|
|
596
|
+
const items = nestedSchema._def.typeName === "ZodArray" ? nestedSchema._def.type : nestedSchema._def.items;
|
|
597
|
+
zodRule.value = {
|
|
598
|
+
$each: processZodTypeDef({ schema: items, state, additionalIssues: rootAdditionalIssues }),
|
|
599
|
+
...arrayValidators
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return vue.reactive({ zodRule });
|
|
521
604
|
}
|
|
522
|
-
function getNestedZodObjectSchema(schema) {
|
|
605
|
+
function getNestedZodObjectSchema(schema, effects = []) {
|
|
523
606
|
if (schema._def && "typeName" in schema._def) {
|
|
524
|
-
if (schema._def.typeName ===
|
|
525
|
-
return getNestedZodObjectSchema(
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
607
|
+
if (schema._def.typeName === "ZodEffects") {
|
|
608
|
+
return getNestedZodObjectSchema(
|
|
609
|
+
schema._def.schema,
|
|
610
|
+
effects.concat([schema._def.effect])
|
|
611
|
+
);
|
|
612
|
+
} else if (schema._def.typeName === "ZodIntersection") {
|
|
613
|
+
const { nestedSchema: leftObject, nestedEffects: leftEffects = [] } = getNestedZodObjectSchema(
|
|
614
|
+
schema._def.left
|
|
615
|
+
);
|
|
616
|
+
const { nestedSchema: rightObject, nestedEffects: rightEffects = [] } = getNestedZodObjectSchema(
|
|
617
|
+
schema._def.right
|
|
618
|
+
);
|
|
529
619
|
if (leftObject && rightObject) {
|
|
530
|
-
return getNestedZodObjectSchema(
|
|
620
|
+
return getNestedZodObjectSchema(
|
|
621
|
+
leftObject.merge(rightObject),
|
|
622
|
+
effects.concat(leftEffects).concat(rightEffects)
|
|
623
|
+
);
|
|
531
624
|
}
|
|
532
|
-
return undefined;
|
|
625
|
+
return { nestedSchema: undefined };
|
|
533
626
|
} else {
|
|
534
|
-
return schema;
|
|
627
|
+
return { nestedSchema: schema, nestedEffects: effects };
|
|
535
628
|
}
|
|
536
629
|
}
|
|
537
|
-
return undefined;
|
|
630
|
+
return { nestedSchema: undefined };
|
|
538
631
|
}
|
|
539
|
-
function zodObjectToRegle(schema, state) {
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
632
|
+
function zodObjectToRegle(schema, state, rootAdditionalIssues) {
|
|
633
|
+
const { nestedSchema, nestedEffects } = getNestedZodObjectSchema(schema);
|
|
634
|
+
const zodRule = vue.ref({});
|
|
635
|
+
if (nestedSchema) {
|
|
636
|
+
if (nestedEffects?.length) {
|
|
637
|
+
const scope = vue.effectScope();
|
|
638
|
+
scope.run(() => {
|
|
639
|
+
const localAdditionalIssues = vue.ref([]);
|
|
640
|
+
const additionalIssues = vue.computed(() => {
|
|
641
|
+
return localAdditionalIssues.value.concat(rootAdditionalIssues?.value ?? []);
|
|
642
|
+
});
|
|
643
|
+
vue.watch(
|
|
644
|
+
state,
|
|
645
|
+
() => {
|
|
646
|
+
if (nestedSchema?._def?.typeName === "ZodObject") {
|
|
647
|
+
localAdditionalIssues.value = (rootAdditionalIssues?.value ?? []).concat(
|
|
648
|
+
schema.safeParse(state.value).error?.issues.filter((f) => f.code === "custom") ?? []
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
},
|
|
652
|
+
{ deep: true, flush: "sync", immediate: true }
|
|
653
|
+
);
|
|
654
|
+
if (nestedSchema?._def?.typeName === "ZodObject") {
|
|
655
|
+
zodRule.value = Object.fromEntries(
|
|
656
|
+
Object.entries(nestedSchema._def.shape()).map(([key, shape]) => {
|
|
657
|
+
if (shape && typeof shape === "object" && "_def" in shape) {
|
|
658
|
+
const childState = vue.toRef(isObject(state.value) ? state.value : {}, key);
|
|
659
|
+
const fieldIssues = vue.computed(() => {
|
|
660
|
+
return additionalIssues.value?.filter((f) => f.path[0] === key).map((m) => {
|
|
661
|
+
const [_, ...rest] = m.path;
|
|
662
|
+
return {
|
|
663
|
+
...m,
|
|
664
|
+
path: rest
|
|
665
|
+
};
|
|
666
|
+
});
|
|
667
|
+
});
|
|
668
|
+
return [
|
|
669
|
+
key,
|
|
670
|
+
processZodTypeDef({
|
|
671
|
+
schema: shape,
|
|
672
|
+
state: childState,
|
|
673
|
+
additionalIssues: fieldIssues
|
|
674
|
+
}),
|
|
675
|
+
[state]
|
|
676
|
+
];
|
|
677
|
+
}
|
|
678
|
+
return [key, {}];
|
|
679
|
+
})
|
|
680
|
+
);
|
|
681
|
+
} else {
|
|
682
|
+
zodRule.value = {};
|
|
683
|
+
}
|
|
684
|
+
vue.onScopeDispose(() => {
|
|
685
|
+
scope.stop();
|
|
686
|
+
});
|
|
687
|
+
});
|
|
688
|
+
} else {
|
|
689
|
+
zodRule.value = Object.fromEntries(
|
|
544
690
|
Object.entries(nestedSchema._def.shape()).map(([key, shape]) => {
|
|
545
691
|
if (shape && typeof shape === "object" && "_def" in shape) {
|
|
546
692
|
const childState = vue.toRef(isObject(state.value) ? state.value : {}, key);
|
|
547
|
-
return [
|
|
693
|
+
return [
|
|
694
|
+
key,
|
|
695
|
+
processZodTypeDef({
|
|
696
|
+
schema: shape,
|
|
697
|
+
state: childState,
|
|
698
|
+
additionalIssues: rootAdditionalIssues
|
|
699
|
+
})
|
|
700
|
+
];
|
|
548
701
|
}
|
|
549
702
|
return [key, {}];
|
|
550
703
|
})
|
|
551
704
|
);
|
|
552
705
|
}
|
|
553
|
-
return {};
|
|
554
706
|
}
|
|
555
|
-
return {};
|
|
707
|
+
return vue.reactive({ zodRule });
|
|
556
708
|
}
|
|
557
709
|
|
|
558
710
|
// src/core/useRegleSchema.ts
|
|
@@ -581,9 +733,16 @@ function createUseRegleSchemaComposable(options, shortcuts) {
|
|
|
581
733
|
() => {
|
|
582
734
|
if (computedSchema.value && typeof computedSchema.value === "object") {
|
|
583
735
|
if (computedSchema.value["~standard"].vendor === "zod") {
|
|
584
|
-
|
|
736
|
+
const objectResult = zodObjectToRegle(computedSchema.value, processedState);
|
|
737
|
+
convertedRules.value = objectResult.zodRule;
|
|
585
738
|
} else if (computedSchema.value["~standard"].vendor === "valibot") {
|
|
586
739
|
convertedRules.value = vue.reactive(valibotObjectToRegle(computedSchema.value, processedState));
|
|
740
|
+
} else if (computedSchema.value?.["~standard"]?.vendor) {
|
|
741
|
+
console.warn(
|
|
742
|
+
`This RPC library "${computedSchema.value["~standard"].vendor}" is not supported yet in 'rules' mode, switch to the "schema" mode option`
|
|
743
|
+
);
|
|
744
|
+
} else {
|
|
745
|
+
console.warn(`Only "standard-schema" compatible libraries are supported`);
|
|
587
746
|
}
|
|
588
747
|
}
|
|
589
748
|
},
|
|
@@ -609,6 +768,9 @@ function createUseRegleSchemaComposable(options, shortcuts) {
|
|
|
609
768
|
}
|
|
610
769
|
return output;
|
|
611
770
|
};
|
|
771
|
+
if (!computedSchema.value?.["~standard"]) {
|
|
772
|
+
throw new Error(`Only "standard-schema" compatible libraries are supported`);
|
|
773
|
+
}
|
|
612
774
|
const emptySkeleton = computedSchema.value["~standard"].validate(initialState.value);
|
|
613
775
|
customErrors.value = issuesToRegleErrors2(emptySkeleton);
|
|
614
776
|
vue.watch(
|
|
@@ -650,7 +812,17 @@ function createUseRegleSchemaComposable(options, shortcuts) {
|
|
|
650
812
|
}
|
|
651
813
|
var useRegleSchema = createUseRegleSchemaComposable();
|
|
652
814
|
function withDeps(schema, depsArray) {
|
|
653
|
-
|
|
815
|
+
if (!Object.hasOwn(schema, "__depsArray")) {
|
|
816
|
+
Object.defineProperties(schema, {
|
|
817
|
+
__depsArray: {
|
|
818
|
+
value: depsArray,
|
|
819
|
+
enumerable: false,
|
|
820
|
+
configurable: false,
|
|
821
|
+
writable: false
|
|
822
|
+
}
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
return schema;
|
|
654
826
|
}
|
|
655
827
|
function createInferValibotSchemaHelper() {
|
|
656
828
|
function inferRules(state, rulesFactory) {
|
package/dist/regle-schemas.d.cts
CHANGED
|
@@ -329,7 +329,7 @@ type RegleSchemaCollectionStatus<TSchema extends Record<string, any>, TState ext
|
|
|
329
329
|
[K in keyof TShortcuts['collections']]: ReturnType<NonNullable<TShortcuts['collections']>[K]>;
|
|
330
330
|
});
|
|
331
331
|
|
|
332
|
-
type useRegleSchemaFn<TShortcuts extends RegleShortcutDefinition<any> = never> = <TState extends Record<string, any>, TSchema extends StandardSchemaV1<Record<string, any>> & TValid, TMode extends RegleSchemaMode = never, TValid =
|
|
332
|
+
type useRegleSchemaFn<TShortcuts extends RegleShortcutDefinition<any> = never> = <TState extends Record<string, any>, TSchema extends StandardSchemaV1<Record<string, any>> & TValid, TMode extends RegleSchemaMode = never, TValid = StandardSchemaV1.InferInput<TSchema> extends PartialDeep<UnwrapNestedRefs<TState>, {
|
|
333
333
|
recurseIntoArrays: true;
|
|
334
334
|
}> ? {} : MismatchInfo<UnwrapNestedRefs<TState>, PartialDeep<StandardSchemaV1.InferInput<TSchema>, {
|
|
335
335
|
recurseIntoArrays: true;
|
|
@@ -363,10 +363,13 @@ declare const useRegleSchema: useRegleSchemaFn<RegleShortcutDefinition<any>>;
|
|
|
363
363
|
* Force dependency on any RPC schema
|
|
364
364
|
* ```ts
|
|
365
365
|
* const foo = ref('');
|
|
366
|
-
*
|
|
367
|
-
*
|
|
368
|
-
*
|
|
369
|
-
* )
|
|
366
|
+
*
|
|
367
|
+
* useRegleSchema({name: ''}, v.object({
|
|
368
|
+
* name: withDeps(
|
|
369
|
+
* v.pipe(v.string(), v.check((value) => value === foo.value)),
|
|
370
|
+
* [foo]
|
|
371
|
+
* )
|
|
372
|
+
* }))
|
|
370
373
|
* ```
|
|
371
374
|
*/
|
|
372
375
|
declare function withDeps<TSchema extends StandardSchemaV1, TParams extends (Ref<unknown> | (() => unknown))[] = []>(schema: TSchema, depsArray: [...TParams]): TSchema & {
|
package/dist/regle-schemas.d.ts
CHANGED
|
@@ -329,7 +329,7 @@ type RegleSchemaCollectionStatus<TSchema extends Record<string, any>, TState ext
|
|
|
329
329
|
[K in keyof TShortcuts['collections']]: ReturnType<NonNullable<TShortcuts['collections']>[K]>;
|
|
330
330
|
});
|
|
331
331
|
|
|
332
|
-
type useRegleSchemaFn<TShortcuts extends RegleShortcutDefinition<any> = never> = <TState extends Record<string, any>, TSchema extends StandardSchemaV1<Record<string, any>> & TValid, TMode extends RegleSchemaMode = never, TValid =
|
|
332
|
+
type useRegleSchemaFn<TShortcuts extends RegleShortcutDefinition<any> = never> = <TState extends Record<string, any>, TSchema extends StandardSchemaV1<Record<string, any>> & TValid, TMode extends RegleSchemaMode = never, TValid = StandardSchemaV1.InferInput<TSchema> extends PartialDeep<UnwrapNestedRefs<TState>, {
|
|
333
333
|
recurseIntoArrays: true;
|
|
334
334
|
}> ? {} : MismatchInfo<UnwrapNestedRefs<TState>, PartialDeep<StandardSchemaV1.InferInput<TSchema>, {
|
|
335
335
|
recurseIntoArrays: true;
|
|
@@ -363,10 +363,13 @@ declare const useRegleSchema: useRegleSchemaFn<RegleShortcutDefinition<any>>;
|
|
|
363
363
|
* Force dependency on any RPC schema
|
|
364
364
|
* ```ts
|
|
365
365
|
* const foo = ref('');
|
|
366
|
-
*
|
|
367
|
-
*
|
|
368
|
-
*
|
|
369
|
-
* )
|
|
366
|
+
*
|
|
367
|
+
* useRegleSchema({name: ''}, v.object({
|
|
368
|
+
* name: withDeps(
|
|
369
|
+
* v.pipe(v.string(), v.check((value) => value === foo.value)),
|
|
370
|
+
* [foo]
|
|
371
|
+
* )
|
|
372
|
+
* }))
|
|
370
373
|
* ```
|
|
371
374
|
*/
|
|
372
375
|
declare function withDeps<TSchema extends StandardSchemaV1, TParams extends (Ref<unknown> | (() => unknown))[] = []>(schema: TSchema, depsArray: [...TParams]): TSchema & {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var core=require('@regle/core'),vue=require('vue'),rules=require('@regle/rules'),R=require('valibot'),l=require('zod');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var R__namespace=/*#__PURE__*/_interopNamespace(R);var l__default=/*#__PURE__*/_interopDefault(l);function ue(e){if(typeof e.source.flags=="string")return e.source.flags;{let t=[];return e.global&&t.push("g"),e.ignoreCase&&t.push("i"),e.multiline&&t.push("m"),e.sticky&&t.push("y"),e.unicode&&t.push("u"),t.join("")}}function d(e){let t=e,r={}.toString.call(e).slice(8,-1);if(r=="Set"&&(t=new Set([...e].map(n=>d(n)))),r=="Map"&&(t=new Map([...e].map(n=>[d(n[0]),d(n[1])]))),r=="Date"&&(t=new Date(e.getTime())),r=="RegExp"&&(t=RegExp(e.source,ue(e))),r=="Array"||r=="Object"){t=Array.isArray(e)?[]:{};for(let n in e)t[n]=d(e[n]);}return t}function f(e){return e&&(e instanceof Date||e.constructor.name=="File"||e.constructor.name=="FileList")?false:typeof e=="object"&&e!==null&&!Array.isArray(e)}function L(e,t,r,n){var a,o;if(Array.isArray(t)&&(a=t.slice(0)),typeof t=="string"&&(a=t.split(".")),typeof t=="symbol"&&(a=[t]),!Array.isArray(a))throw new Error("props arg must be an array, a string or a symbol");if(o=a.pop(),!o)return false;B(o);for(var i;i=a.shift();)if(B(i),isNaN(parseInt(i))?(typeof e[i]>"u"&&(e[i]={}),e=e[i]):((e.$each??=[])[i]={},e=e.$each[i]),!e||typeof e!="object")return false;return n?e[o]={...e[o],$self:r}:e[o]=r,true}function B(e){if(e=="__proto__"||e=="constructor"||e=="prototype")throw new Error("setting of prototype values not supported")}function A(e){let t=e.async,r=n=>{let a=de(e,n);return a instanceof Promise?a:a.success?{$valid:true,$issues:[]}:{$valid:false,$issues:a.issues}};return "__depsArray"in e&&Array.isArray(e.__depsArray)&&e.__depsArray.length?t?rules.withAsync(r,e.__depsArray):rules.withParams(r,e.__depsArray):t?rules.withAsync(r):r}function de(e,t){try{return e.async?new Promise(async r=>{let n=await R__namespace.safeParseAsync(e,t);n.success?r({$valid:!0,$issues:[]}):r({$valid:!1,$issues:n.issues});}):R__namespace.safeParse(e,t)}catch{return {}}}function C(e){return e.type==="intersect"}function D(e){return e.type==="object"}function x(e){return "wrapped"in e}function v(e){if(C(e)){let t=e.options.reduce((r,n)=>{let a=v(n);return a&&(r={...r,...a.entries}),r},{});return R__namespace.object({...t})}else return D(e)?e:x(e)?v(e.wrapped):undefined}function Z(e,t){let r=v(e);return r?Object.fromEntries(Object.entries(r.entries).map(([n,a])=>{if(typeof a=="object"){let o=vue.toRef(f(t.value)?t.value:{},n);return [n,m(a,o)]}return [n,{}]})):{}}function be(e){return e?.type==="literal"}function W(e,t){let r=vue.effectScope();return r.run(()=>{let a=vue.ref({});return vue.watch(t,()=>{if(f(t.value)&&t.value[e.key]){let o=e.options.find(i=>{let s=v(i)?.entries[e.key];return be(s)&&f(t.value)?s.literal===t.value[e.key]:false});o&&D(o)?a.value=Object.fromEntries(Object.entries(o.entries).map(([i,c])=>[i,m(c,vue.toRef(f(t.value)?t.value:{},i))])):a.value={};}else a.value={[e.key]:{required:rules.required}};},{deep:true,flush:"pre",immediate:true}),vue.onScopeDispose(()=>{r.stop();}),{valibotRule:a}})}function S(){return e=>{let t=e.$issues?.map(r=>r.message);return t.length?t:"Error"}}function _e(e){return e.type==="array"}function Ae(e){return e.type==="object"}function De(e){return e.type==="variant"}function q(e){return x(e)?q(e.wrapped):e}function m(e,t){let r=q(e);return _e(r)?H(r,t):Ae(r)?Z(r,t):De(r)?W(r,t).valibotRule:{[r.type]:rules.withMessage(A(r),S())}}function H(e,t){let r={};return "pipe"in e&&e.pipe.filter(n=>n.kind==="validation").forEach(n=>{r[n.type]=rules.withMessage(A(R__namespace.pipe(R__namespace.array(R__namespace.any()),n)),S());}),{$each:m(e.item,t),...r}}function Q(e){let t=g(e),r=n=>{let a=Oe(e,n);return a instanceof Promise?a:a.success?{$valid:true,$issues:[]}:{$valid:false,$issues:a.error.issues}};return "__depsArray"in e&&Array.isArray(e.__depsArray)&&e.__depsArray.length?t?rules.withAsync(r,e.__depsArray):rules.withParams(r,e.__depsArray):t?rules.withAsync(r):r}function Oe(e,t){try{return e.safeParse(t)}catch{try{return new Promise(async n=>{let a=await e.safeParseAsync(t);a.success?n({$valid:!0,$issues:[]}):n({$valid:!1,$issues:a.error.issues});})}catch{return {}}}}function J(e){if(typeof e!="function")return false;if(e.constructor.name==="AsyncFunction")return true;try{return e()instanceof Promise}catch{return false}}function g(e){if(e?._def){if(e._def.typeName==="ZodEffects"){let t=e._def.effect;return J(t.refinement||t.transform)}if(e._def.typeName==="ZodObject")return Object.values(e._def.shape()).some(t=>g(t));if(e._def.typeName==="ZodUnion"||e._def.typeName==="ZodIntersection")return e._def.options.some(g);if(e._def.typeName==="ZodArray")return g(e._def.type);if(e._def.typeName==="ZodOptional"||e._def.typeName==="ZodNullable")return g(e._def.innerType);if(e._def.typeName==="ZodTuple")return e._def.items.some(g);if(e._def.typeName==="ZodString"||e._def.typeName==="ZodNumber"||e._def.typeName==="ZodDate")return e._def.checks?.some(t=>J(t.refinement))}return false}function X(e,t){let r=vue.effectScope();return r.run(()=>{let a=vue.ref({});return vue.watch(t,()=>{if(f(t.value)&&t.value[e._def.discriminator]){let o=e._def.optionsMap.get(t.value[e._def.discriminator]);o?a.value=Object.fromEntries(Object.entries(o._def.shape()).map(([i,c])=>typeof c=="object"&&"_def"in c?[i,h(c,vue.toRef(f(t.value)?t.value:{},i))]:[i,{}])):a.value={};}else a.value={[e._def.discriminator]:{required:rules.required}};},{deep:true,flush:"pre",immediate:true}),vue.onScopeDispose(()=>{r.stop();}),{zodRule:a}})}var ze=[l__default.default.ZodFirstPartyTypeKind.ZodDefault,l__default.default.ZodFirstPartyTypeKind.ZodCatch,l__default.default.ZodFirstPartyTypeKind.ZodNullable,l__default.default.ZodFirstPartyTypeKind.ZodOptional,l__default.default.ZodFirstPartyTypeKind.ZodReadonly];function Fe(e){return e._def&&typeof e._def=="object"&&"typeName"in e._def?ze.includes(e._def.typeName):false}function Ee(e){return e._def&&typeof e._def=="object"&&"typeName"in e._def?"schema"in e._def:false}function k(e){if(e?._def&&typeof e._def=="object"&&"typeName"in e._def)return Fe(e)?k(e._def.innerType):Ee(e)?k(e._def.schema):e}function h(e,t){let r=k(e);return r?._def&&"typeName"in r._def?r._def.typeName===l__default.default.ZodFirstPartyTypeKind.ZodArray||r._def.typeName===l__default.default.ZodFirstPartyTypeKind.ZodTuple?Y(e,t):r._def.typeName===l__default.default.ZodFirstPartyTypeKind.ZodObject||r._def.typeName===l__default.default.ZodFirstPartyTypeKind.ZodIntersection?O(r,t):r._def.typeName===l__default.default.ZodFirstPartyTypeKind.ZodDiscriminatedUnion?X(r,t).zodRule:{[r.constructor.name]:rules.withMessage(Q(e),S())}:{}}function Y(e,t){let r=e._def.typeName===l.z.ZodFirstPartyTypeKind.ZodArray?{...!!e._def.minLength&&{minLength:rules.minLength(e._def.minLength?.value)},...!!e._def.maxLength&&{maxLength:rules.maxLength(e._def.maxLength?.value)},...!!e._def.exactLength&&{exactLength:rules.exactLength(e._def.exactLength?.value)}}:{},n=e._def.typeName===l.z.ZodFirstPartyTypeKind.ZodArray?e._def.type:e._def.items;return {$each:h(n,t),...r}}function T(e){if(e._def&&"typeName"in e._def){if(e._def.typeName===l.z.ZodFirstPartyTypeKind.ZodEffects)return T(e._def.schema);if(e._def.typeName===l.z.ZodFirstPartyTypeKind.ZodIntersection){let t=T(e._def.left),r=T(e._def.right);return t&&r?T(t.merge(r)):undefined}else return e}}function O(e,t){if(e&&"_def"in e&&"typeName"in e._def){let r=T(e);return r?._def?.typeName===l.z.ZodFirstPartyTypeKind.ZodObject?Object.fromEntries(Object.entries(r._def.shape()).map(([n,a])=>{if(a&&typeof a=="object"&&"_def"in a){let o=vue.toRef(f(t.value)?t.value:{},n);return [n,h(a,o)]}return [n,{}]})):{}}return {}}function V(e,t){let r={autoDirty:e?.autoDirty,lazy:e?.lazy,rewardEarly:e?.rewardEarly,clearExternalErrorsOnChange:e?.clearExternalErrorsOnChange};function n(a,o,i){let c=vue.ref({}),s=vue.computed(()=>vue.unref(o)),{mode:z="rules",...se}=i??{},fe={...r,...se},y=vue.isRef(a)?a:vue.ref(a),F=vue.ref({...d(y.value)}),b=vue.ref({}),E;if(z==="rules")vue.watch(s,()=>{s.value&&typeof s.value=="object"&&(s.value["~standard"].vendor==="zod"?c.value=vue.reactive(O(s.value,y)):s.value["~standard"].vendor==="valibot"&&(c.value=vue.reactive(Z(s.value,y))));},{deep:true,immediate:true,flush:"post"});else {let w=function(u){let $={};return u.issues&&u.issues.map(p=>{let pe=p.path?.map(I=>typeof I=="object"?I.key:I).join("."),P=p.path?.[p.path.length-1],le=(typeof P=="object"&&"value"in P?Array.isArray(P.value):false)||("type"in p?p.type==="array":false);return {path:pe,message:p.message,isArray:le}}).forEach(p=>{L($,p.path,[p.message],p.isArray);}),$};let ce=s.value["~standard"].validate(F.value);b.value=w(ce),vue.watch([y,s],async()=>{let u=await s.value["~standard"].validate(y.value);b.value=w(u);},{deep:true,immediate:true,flush:"post"}),E=async()=>{try{let u=await s.value["~standard"].validate(y.value);return b.value=w(u),{result:!u.issues?.length,data:y.value}}catch(u){return Promise.reject(u)}};}return {r$:core.useRootStorage({scopeRules:c,state:y,options:fe,schemaErrors:b,initialState:F,shortcuts:t,schemaMode:z==="schema",onValidate:E}).regle}}return n}var ne=V();function ae(e,t){return {...e,__depsArray:t}}function j(){function e(t,r){return r}return e}var oe=j();function ie({modifiers:e,shortcuts:t}){let r=V(e,t),n=j();return {useRegleSchema:r,inferSchema:n}}exports.defineRegleSchemaConfig=ie;exports.inferSchema=oe;exports.useRegleSchema=ne;exports.withDeps=ae;
|
|
1
|
+
'use strict';var core=require('@regle/core'),vue=require('vue'),rules=require('@regle/rules');function ye(e){if(typeof e.source.flags=="string")return e.source.flags;{let t=[];return e.global&&t.push("g"),e.ignoreCase&&t.push("i"),e.multiline&&t.push("m"),e.sticky&&t.push("y"),e.unicode&&t.push("u"),t.join("")}}function b(e){let t=e,n={}.toString.call(e).slice(8,-1);if(n=="Set"&&(t=new Set([...e].map(r=>b(r)))),n=="Map"&&(t=new Map([...e].map(r=>[b(r[0]),b(r[1])]))),n=="Date"&&(t=new Date(e.getTime())),n=="RegExp"&&(t=RegExp(e.source,ye(e))),n=="Array"||n=="Object"){t=Array.isArray(e)?[]:{};for(let r in e)t[r]=b(e[r]);}return t}function l(e){return e&&(e instanceof Date||e.constructor.name=="File"||e.constructor.name=="FileList")?false:typeof e=="object"&&e!==null&&!Array.isArray(e)}function C(e,t,n,r){var a,o;if(Array.isArray(t)&&(a=t.slice(0)),typeof t=="string"&&(a=t.split(".")),typeof t=="symbol"&&(a=[t]),!Array.isArray(a))throw new Error("props arg must be an array, a string or a symbol");if(o=a.pop(),!o)return false;L(o);for(var i;i=a.shift();)if(L(i),isNaN(parseInt(i))?(typeof e[i]>"u"&&(e[i]={}),e=e[i]):((e.$each??=[])[i]={},e=e.$each[i]),!e||typeof e!="object")return false;return r?e[o]={...e[o],$self:n}:e[o]=n,true}function L(e){if(e=="__proto__"||e=="constructor"||e=="prototype")throw new Error("setting of prototype values not supported")}function W(e){let t=e.async,n=r=>{let a=Se(e,r);return a instanceof Promise?a:a.issues?{$valid:false,$issues:a.issues}:{$valid:true,$issues:[]}};return "__depsArray"in e&&Array.isArray(e.__depsArray)&&e.__depsArray.length?t?rules.withAsync(n,e.__depsArray):rules.withParams(n,e.__depsArray):t?rules.withAsync(n):n}function Se(e,t){try{return e.async?new Promise(async n=>{let r=await e["~standard"].validate(t);r.issues?n({$valid:!1,$issues:r.issues}):n({$valid:!0,$issues:[]});}):e["~standard"].validate(t)}catch{return {}}}function q(e){return e.type==="intersect"}function Z(e){return e.type==="object"}function x(e){return "wrapped"in e}function _(e){return q(e)?{entries:e.options.reduce((n,r)=>{let a=_(r);return a&&(n={...n,...a.entries}),n},{}),type:"object",kind:"schema",async:false}:Z(e)?e:x(e)?_(e.wrapped):undefined}function z(e,t){let n=_(e);return n?Object.fromEntries(Object.entries(n.entries).map(([r,a])=>{if(typeof a=="object"){let o=vue.toRef(l(t.value)?t.value:{},r);return [r,T(a,o)]}return [r,{}]})):{}}function _e(e){return e?.type==="literal"}function H(e,t){let n=vue.effectScope();return n.run(()=>{let a=vue.ref({});return vue.watch(t,()=>{if(l(t.value)&&t.value[e.key]){let o=e.options.find(i=>{let s=_(i)?.entries[e.key];return _e(s)&&l(t.value)?s.literal===t.value[e.key]:false});o&&Z(o)?a.value=Object.fromEntries(Object.entries(o.entries).map(([i,f])=>[i,T(f,vue.toRef(l(t.value)?t.value:{},i))])):a.value={};}else a.value={[e.key]:{required:rules.required}};},{deep:true,flush:"pre",immediate:true}),vue.onScopeDispose(()=>{n.stop();}),{valibotRule:a}})}function h(){return e=>{let t=e.$issues?.map(n=>n.message);return t?.length?t.length?t:"Error":[]}}function Oe(e){return e.type==="array"}function De(e){return e.type==="object"}function Ze(e){return e.type==="variant"}function K(e){return x(e)?K(e.wrapped):e}function T(e,t){let n=K(e);return Oe(n)?G(n,t):De(n)?z(n,t):Ze(n)?H(n,t).valibotRule:{[n.type]:rules.withMessage(W(n),h())}}function G(e,t){let n={};return "pipe"in e&&e.pipe.filter(r=>r.kind==="validation").forEach(r=>{n[r.type]=rules.withMessage(a=>{let o=r["~run"]({value:a,typed:true},{});return {$valid:!o.issues,$issues:o.issues}},h());}),{$each:T(e.item,t),...n}}function A(e,t){let n=w(e);function r(a){if(t?.value?.length)return {$valid:false,$issues:t.value};let o=Ie(e,a);return o instanceof Promise?o:o.success?{$valid:true,$issues:[]}:{$valid:false,$issues:o.error?.issues??[]}}return e&&"__depsArray"in e&&Array.isArray(e.__depsArray)&&e.__depsArray.length?n?rules.withAsync(r,e.__depsArray):rules.withParams(r,e.__depsArray):n?rules.withAsync(r):r}function Ie(e,t){if(e)try{return e.safeParse(t)}catch{try{return new Promise(async r=>{let a=await e.safeParseAsync(t);a.success?r({$valid:!0,$issues:[]}):r({$valid:!1,$issues:a.error?.issues});})}catch{return {}}}else return {success:true,data:{}}}function Q(e){if(typeof e!="function")return false;if(e.constructor.name==="AsyncFunction")return true;try{return e()instanceof Promise}catch{return false}}function w(e){if(e?._def){if(e._def.typeName==="ZodEffects"){let t=e._def.effect;return Q(t.refinement||t.transform)}if(e._def.typeName==="ZodObject")return Object.values(e._def.shape()).some(t=>w(t));if(e._def.typeName==="ZodUnion"||e._def.typeName==="ZodIntersection")return e._def.options.some(w);if(e._def.typeName==="ZodArray")return w(e._def.type);if(e._def.typeName==="ZodOptional"||e._def.typeName==="ZodNullable")return w(e._def.innerType);if(e._def.typeName==="ZodTuple")return e._def.items.some(w);if(e._def.typeName==="ZodString"||e._def.typeName==="ZodNumber"||e._def.typeName==="ZodDate")return e._def.checks?.some(t=>Q(t.refinement))}return false}function X(e,t,n){let r=vue.effectScope();return r.run(()=>{let o=vue.ref({});return vue.watch(t,()=>{if(l(t.value)&&t.value[e._def.discriminator]){let i=e._def.optionsMap.get(t.value[e._def.discriminator]);i?o.value=Object.fromEntries(Object.entries(i._def.shape()).map(([f,s])=>typeof s=="object"&&"_def"in s?[f,R({schema:s,state:vue.toRef(l(t.value)?t.value:{}),additionalIssues:n})]:[f,{}])):o.value={};}else o.value={[e._def.discriminator]:{required:rules.required}};},{deep:true,flush:"pre",immediate:true}),vue.onScopeDispose(()=>{r.stop();}),{zodRule:o}})}var $e=["ZodDefault","ZodCatch","ZodNullable","ZodOptional","ZodReadonly"];function Be(e){return e._def&&typeof e._def=="object"&&"typeName"in e._def?$e.includes(e._def.typeName):false}function Fe(e){return e._def&&typeof e._def=="object"&&"typeName"in e._def?"schema"in e._def:false}function k(e){if(e?._def&&typeof e._def=="object"&&"typeName"in e._def)return Be(e)?k(e._def.innerType):Fe(e)?k(e._def.schema):e}function R({schema:e,state:t,additionalIssues:n}){let r=k(e);return r?._def&&"typeName"in r._def?r._def.typeName==="ZodArray"||r._def.typeName==="ZodTuple"?ee(e,t,n).zodRule:r._def.typeName==="ZodObject"||r._def.typeName==="ZodIntersection"?I(r,t,n).zodRule:r._def.typeName==="ZodDiscriminatedUnion"?X(r,t,n).zodRule:n?{[r.constructor.name]:rules.withMessage(rules.withParams(A(e,n),[t]),h())}:{[r.constructor.name]:rules.withMessage(A(e),h())}:{}}function re(e,t=[]){return e._def&&"typeName"in e._def?e._def.typeName==="ZodEffects"?re(e._def.schema,t.concat([e._def.effect])):{nestedSchema:e,nestedEffects:t}:{nestedSchema:undefined}}function ee(e,t,n){let{nestedSchema:r,nestedEffects:a}=re(e),o=vue.ref({});if(r){let i=r._def.typeName==="ZodArray"?{...!!r._def.minLength&&{minLength:rules.minLength(r._def.minLength?.value)},...!!r._def.maxLength&&{maxLength:rules.maxLength(r._def.maxLength?.value)},...!!r._def.exactLength&&{exactLength:rules.exactLength(r._def.exactLength?.value)}}:{};if(a?.length){let f=vue.effectScope();f.run(()=>{let s=vue.ref([]),u=vue.computed(()=>s.value.concat(n?.value??[]));if(n||vue.watch(t,()=>{r&&(s.value=e.safeParse(t.value).error?.issues.filter(d=>d.code==="custom")??[]);},{deep:true,immediate:true}),r){let d=r._def.typeName==="ZodArray"?r._def.type:r._def.items,v=vue.computed(()=>u.value.filter(c=>!c.path.length));o.value={$each:(c,m)=>{let g=vue.computed(()=>u.value?.filter(p=>p.code==="custom")?.filter(p=>p.path[0]===m.toString()).map(p=>{let[le,...B]=p.path;return {...p,path:B}}));return R({schema:d,state:t,additionalIssues:g})},selfValidator:rules.withMessage(rules.withParams(A(undefined,v),[t,v]),h())};}else o.value={};vue.onScopeDispose(()=>{f.stop();});});}else {let f=r._def.typeName==="ZodArray"?r._def.type:r._def.items;o.value={$each:R({schema:f,state:t,additionalIssues:n}),...i};}}return vue.reactive({zodRule:o})}function O(e,t=[]){if(e._def&&"typeName"in e._def){if(e._def.typeName==="ZodEffects")return O(e._def.schema,t.concat([e._def.effect]));if(e._def.typeName==="ZodIntersection"){let{nestedSchema:n,nestedEffects:r=[]}=O(e._def.left),{nestedSchema:a,nestedEffects:o=[]}=O(e._def.right);return n&&a?O(n.merge(a),t.concat(r).concat(o)):{nestedSchema:undefined}}else return {nestedSchema:e,nestedEffects:t}}return {nestedSchema:undefined}}function I(e,t,n){let{nestedSchema:r,nestedEffects:a}=O(e),o=vue.ref({});if(r)if(a?.length){let i=vue.effectScope();i.run(()=>{let f=vue.ref([]),s=vue.computed(()=>f.value.concat(n?.value??[]));vue.watch(t,()=>{r?._def?.typeName==="ZodObject"&&(f.value=(n?.value??[]).concat(e.safeParse(t.value).error?.issues.filter(u=>u.code==="custom")??[]));},{deep:true,flush:"sync",immediate:true}),r?._def?.typeName==="ZodObject"?o.value=Object.fromEntries(Object.entries(r._def.shape()).map(([u,d])=>{if(d&&typeof d=="object"&&"_def"in d){let v=vue.toRef(l(t.value)?t.value:{},u),c=vue.computed(()=>s.value?.filter(m=>m.path[0]===u).map(m=>{let[g,...p]=m.path;return {...m,path:p}}));return [u,R({schema:d,state:v,additionalIssues:c}),[t]]}return [u,{}]})):o.value={},vue.onScopeDispose(()=>{i.stop();});});}else o.value=Object.fromEntries(Object.entries(r._def.shape()).map(([i,f])=>{if(f&&typeof f=="object"&&"_def"in f){let s=vue.toRef(l(t.value)?t.value:{},i);return [i,R({schema:f,state:s,additionalIssues:n})]}return [i,{}]}));return vue.reactive({zodRule:o})}function V(e,t){let n={autoDirty:e?.autoDirty,lazy:e?.lazy,rewardEarly:e?.rewardEarly,clearExternalErrorsOnChange:e?.clearExternalErrorsOnChange};function r(a,o,i){let f=vue.ref({}),s=vue.computed(()=>vue.unref(o)),{mode:u="rules",...d}=i??{},v={...n,...d},c=vue.isRef(a)?a:vue.ref(a),m=vue.ref({...b(c.value)}),g=vue.ref({}),p;if(u==="rules")vue.watch(s,()=>{if(s.value&&typeof s.value=="object")if(s.value["~standard"].vendor==="zod"){let N=I(s.value,c);f.value=N.zodRule;}else s.value["~standard"].vendor==="valibot"?f.value=vue.reactive(z(s.value,c)):s.value?.["~standard"]?.vendor?console.warn(`This RPC library "${s.value["~standard"].vendor}" is not supported yet in 'rules' mode, switch to the "schema" mode option`):console.warn('Only "standard-schema" compatible libraries are supported');},{deep:true,immediate:true,flush:"post"});else {let D=function(S){let F={};return S.issues&&S.issues.map(y=>{let pe=y.path?.map(j=>typeof j=="object"?j.key:j).join("."),P=y.path?.[y.path.length-1],de=(typeof P=="object"&&"value"in P?Array.isArray(P.value):false)||("type"in y?y.type==="array":false);return {path:pe,message:y.message,isArray:de}}).forEach(y=>{C(F,y.path,[y.message],y.isArray);}),F};if(!s.value?.["~standard"])throw new Error('Only "standard-schema" compatible libraries are supported');let N=s.value["~standard"].validate(m.value);g.value=D(N),vue.watch([c,s],async()=>{let S=await s.value["~standard"].validate(c.value);g.value=D(S);},{deep:true,immediate:true,flush:"post"}),p=async()=>{try{let S=await s.value["~standard"].validate(c.value);return g.value=D(S),{result:!S.issues?.length,data:c.value}}catch(S){return Promise.reject(S)}};}return {r$:core.useRootStorage({scopeRules:f,state:c,options:v,schemaErrors:g,initialState:m,shortcuts:t,schemaMode:u==="schema",onValidate:p}).regle}}return r}var ie=V();function fe(e,t){return Object.hasOwn(e,"__depsArray")||Object.defineProperties(e,{__depsArray:{value:t,enumerable:false,configurable:false,writable:false}}),e}function $(){function e(t,n){return n}return e}var ce=$();function ue({modifiers:e,shortcuts:t}){let n=V(e,t),r=$();return {useRegleSchema:n,inferSchema:r}}exports.defineRegleSchemaConfig=ue;exports.inferSchema=ce;exports.useRegleSchema=ie;exports.withDeps=fe;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {useRootStorage}from'@regle/core';import {ref,computed,unref,isRef,watch,reactive,toRef,effectScope,onScopeDispose}from'vue';import {withMessage,withAsync,withParams,required,minLength,maxLength,exactLength}from'@regle/rules';import*as R from'valibot';import l,{z}from'zod';function ue(e){if(typeof e.source.flags=="string")return e.source.flags;{let t=[];return e.global&&t.push("g"),e.ignoreCase&&t.push("i"),e.multiline&&t.push("m"),e.sticky&&t.push("y"),e.unicode&&t.push("u"),t.join("")}}function d(e){let t=e,r={}.toString.call(e).slice(8,-1);if(r=="Set"&&(t=new Set([...e].map(n=>d(n)))),r=="Map"&&(t=new Map([...e].map(n=>[d(n[0]),d(n[1])]))),r=="Date"&&(t=new Date(e.getTime())),r=="RegExp"&&(t=RegExp(e.source,ue(e))),r=="Array"||r=="Object"){t=Array.isArray(e)?[]:{};for(let n in e)t[n]=d(e[n]);}return t}function f(e){return e&&(e instanceof Date||e.constructor.name=="File"||e.constructor.name=="FileList")?false:typeof e=="object"&&e!==null&&!Array.isArray(e)}function L(e,t,r,n){var a,o;if(Array.isArray(t)&&(a=t.slice(0)),typeof t=="string"&&(a=t.split(".")),typeof t=="symbol"&&(a=[t]),!Array.isArray(a))throw new Error("props arg must be an array, a string or a symbol");if(o=a.pop(),!o)return false;B(o);for(var i;i=a.shift();)if(B(i),isNaN(parseInt(i))?(typeof e[i]>"u"&&(e[i]={}),e=e[i]):((e.$each??=[])[i]={},e=e.$each[i]),!e||typeof e!="object")return false;return n?e[o]={...e[o],$self:r}:e[o]=r,true}function B(e){if(e=="__proto__"||e=="constructor"||e=="prototype")throw new Error("setting of prototype values not supported")}function A(e){let t=e.async,r=n=>{let a=de(e,n);return a instanceof Promise?a:a.success?{$valid:true,$issues:[]}:{$valid:false,$issues:a.issues}};return "__depsArray"in e&&Array.isArray(e.__depsArray)&&e.__depsArray.length?t?withAsync(r,e.__depsArray):withParams(r,e.__depsArray):t?withAsync(r):r}function de(e,t){try{return e.async?new Promise(async r=>{let n=await R.safeParseAsync(e,t);n.success?r({$valid:!0,$issues:[]}):r({$valid:!1,$issues:n.issues});}):R.safeParse(e,t)}catch{return {}}}function C(e){return e.type==="intersect"}function D(e){return e.type==="object"}function x(e){return "wrapped"in e}function v(e){if(C(e)){let t=e.options.reduce((r,n)=>{let a=v(n);return a&&(r={...r,...a.entries}),r},{});return R.object({...t})}else return D(e)?e:x(e)?v(e.wrapped):undefined}function Z(e,t){let r=v(e);return r?Object.fromEntries(Object.entries(r.entries).map(([n,a])=>{if(typeof a=="object"){let o=toRef(f(t.value)?t.value:{},n);return [n,m(a,o)]}return [n,{}]})):{}}function be(e){return e?.type==="literal"}function W(e,t){let r=effectScope();return r.run(()=>{let a=ref({});return watch(t,()=>{if(f(t.value)&&t.value[e.key]){let o=e.options.find(i=>{let s=v(i)?.entries[e.key];return be(s)&&f(t.value)?s.literal===t.value[e.key]:false});o&&D(o)?a.value=Object.fromEntries(Object.entries(o.entries).map(([i,c])=>[i,m(c,toRef(f(t.value)?t.value:{},i))])):a.value={};}else a.value={[e.key]:{required:required}};},{deep:true,flush:"pre",immediate:true}),onScopeDispose(()=>{r.stop();}),{valibotRule:a}})}function S(){return e=>{let t=e.$issues?.map(r=>r.message);return t.length?t:"Error"}}function _e(e){return e.type==="array"}function Ae(e){return e.type==="object"}function De(e){return e.type==="variant"}function q(e){return x(e)?q(e.wrapped):e}function m(e,t){let r=q(e);return _e(r)?H(r,t):Ae(r)?Z(r,t):De(r)?W(r,t).valibotRule:{[r.type]:withMessage(A(r),S())}}function H(e,t){let r={};return "pipe"in e&&e.pipe.filter(n=>n.kind==="validation").forEach(n=>{r[n.type]=withMessage(A(R.pipe(R.array(R.any()),n)),S());}),{$each:m(e.item,t),...r}}function Q(e){let t=g(e),r=n=>{let a=Oe(e,n);return a instanceof Promise?a:a.success?{$valid:true,$issues:[]}:{$valid:false,$issues:a.error.issues}};return "__depsArray"in e&&Array.isArray(e.__depsArray)&&e.__depsArray.length?t?withAsync(r,e.__depsArray):withParams(r,e.__depsArray):t?withAsync(r):r}function Oe(e,t){try{return e.safeParse(t)}catch{try{return new Promise(async n=>{let a=await e.safeParseAsync(t);a.success?n({$valid:!0,$issues:[]}):n({$valid:!1,$issues:a.error.issues});})}catch{return {}}}}function J(e){if(typeof e!="function")return false;if(e.constructor.name==="AsyncFunction")return true;try{return e()instanceof Promise}catch{return false}}function g(e){if(e?._def){if(e._def.typeName==="ZodEffects"){let t=e._def.effect;return J(t.refinement||t.transform)}if(e._def.typeName==="ZodObject")return Object.values(e._def.shape()).some(t=>g(t));if(e._def.typeName==="ZodUnion"||e._def.typeName==="ZodIntersection")return e._def.options.some(g);if(e._def.typeName==="ZodArray")return g(e._def.type);if(e._def.typeName==="ZodOptional"||e._def.typeName==="ZodNullable")return g(e._def.innerType);if(e._def.typeName==="ZodTuple")return e._def.items.some(g);if(e._def.typeName==="ZodString"||e._def.typeName==="ZodNumber"||e._def.typeName==="ZodDate")return e._def.checks?.some(t=>J(t.refinement))}return false}function X(e,t){let r=effectScope();return r.run(()=>{let a=ref({});return watch(t,()=>{if(f(t.value)&&t.value[e._def.discriminator]){let o=e._def.optionsMap.get(t.value[e._def.discriminator]);o?a.value=Object.fromEntries(Object.entries(o._def.shape()).map(([i,c])=>typeof c=="object"&&"_def"in c?[i,h(c,toRef(f(t.value)?t.value:{},i))]:[i,{}])):a.value={};}else a.value={[e._def.discriminator]:{required:required}};},{deep:true,flush:"pre",immediate:true}),onScopeDispose(()=>{r.stop();}),{zodRule:a}})}var ze=[l.ZodFirstPartyTypeKind.ZodDefault,l.ZodFirstPartyTypeKind.ZodCatch,l.ZodFirstPartyTypeKind.ZodNullable,l.ZodFirstPartyTypeKind.ZodOptional,l.ZodFirstPartyTypeKind.ZodReadonly];function Fe(e){return e._def&&typeof e._def=="object"&&"typeName"in e._def?ze.includes(e._def.typeName):false}function Ee(e){return e._def&&typeof e._def=="object"&&"typeName"in e._def?"schema"in e._def:false}function k(e){if(e?._def&&typeof e._def=="object"&&"typeName"in e._def)return Fe(e)?k(e._def.innerType):Ee(e)?k(e._def.schema):e}function h(e,t){let r=k(e);return r?._def&&"typeName"in r._def?r._def.typeName===l.ZodFirstPartyTypeKind.ZodArray||r._def.typeName===l.ZodFirstPartyTypeKind.ZodTuple?Y(e,t):r._def.typeName===l.ZodFirstPartyTypeKind.ZodObject||r._def.typeName===l.ZodFirstPartyTypeKind.ZodIntersection?O(r,t):r._def.typeName===l.ZodFirstPartyTypeKind.ZodDiscriminatedUnion?X(r,t).zodRule:{[r.constructor.name]:withMessage(Q(e),S())}:{}}function Y(e,t){let r=e._def.typeName===z.ZodFirstPartyTypeKind.ZodArray?{...!!e._def.minLength&&{minLength:minLength(e._def.minLength?.value)},...!!e._def.maxLength&&{maxLength:maxLength(e._def.maxLength?.value)},...!!e._def.exactLength&&{exactLength:exactLength(e._def.exactLength?.value)}}:{},n=e._def.typeName===z.ZodFirstPartyTypeKind.ZodArray?e._def.type:e._def.items;return {$each:h(n,t),...r}}function T(e){if(e._def&&"typeName"in e._def){if(e._def.typeName===z.ZodFirstPartyTypeKind.ZodEffects)return T(e._def.schema);if(e._def.typeName===z.ZodFirstPartyTypeKind.ZodIntersection){let t=T(e._def.left),r=T(e._def.right);return t&&r?T(t.merge(r)):undefined}else return e}}function O(e,t){if(e&&"_def"in e&&"typeName"in e._def){let r=T(e);return r?._def?.typeName===z.ZodFirstPartyTypeKind.ZodObject?Object.fromEntries(Object.entries(r._def.shape()).map(([n,a])=>{if(a&&typeof a=="object"&&"_def"in a){let o=toRef(f(t.value)?t.value:{},n);return [n,h(a,o)]}return [n,{}]})):{}}return {}}function V(e,t){let r={autoDirty:e?.autoDirty,lazy:e?.lazy,rewardEarly:e?.rewardEarly,clearExternalErrorsOnChange:e?.clearExternalErrorsOnChange};function n(a,o,i){let c=ref({}),s=computed(()=>unref(o)),{mode:z="rules",...se}=i??{},fe={...r,...se},y=isRef(a)?a:ref(a),F=ref({...d(y.value)}),b=ref({}),E;if(z==="rules")watch(s,()=>{s.value&&typeof s.value=="object"&&(s.value["~standard"].vendor==="zod"?c.value=reactive(O(s.value,y)):s.value["~standard"].vendor==="valibot"&&(c.value=reactive(Z(s.value,y))));},{deep:true,immediate:true,flush:"post"});else {let w=function(u){let $={};return u.issues&&u.issues.map(p=>{let pe=p.path?.map(I=>typeof I=="object"?I.key:I).join("."),P=p.path?.[p.path.length-1],le=(typeof P=="object"&&"value"in P?Array.isArray(P.value):false)||("type"in p?p.type==="array":false);return {path:pe,message:p.message,isArray:le}}).forEach(p=>{L($,p.path,[p.message],p.isArray);}),$};let ce=s.value["~standard"].validate(F.value);b.value=w(ce),watch([y,s],async()=>{let u=await s.value["~standard"].validate(y.value);b.value=w(u);},{deep:true,immediate:true,flush:"post"}),E=async()=>{try{let u=await s.value["~standard"].validate(y.value);return b.value=w(u),{result:!u.issues?.length,data:y.value}}catch(u){return Promise.reject(u)}};}return {r$:useRootStorage({scopeRules:c,state:y,options:fe,schemaErrors:b,initialState:F,shortcuts:t,schemaMode:z==="schema",onValidate:E}).regle}}return n}var ne=V();function ae(e,t){return {...e,__depsArray:t}}function j(){function e(t,r){return r}return e}var oe=j();function ie({modifiers:e,shortcuts:t}){let r=V(e,t),n=j();return {useRegleSchema:r,inferSchema:n}}export{ie as defineRegleSchemaConfig,oe as inferSchema,ne as useRegleSchema,ae as withDeps};
|
|
1
|
+
import {useRootStorage}from'@regle/core';import {ref,computed,unref,isRef,watch,reactive,toRef,effectScope,onScopeDispose}from'vue';import {withMessage,withAsync,withParams,required,minLength,maxLength,exactLength}from'@regle/rules';function ye(e){if(typeof e.source.flags=="string")return e.source.flags;{let t=[];return e.global&&t.push("g"),e.ignoreCase&&t.push("i"),e.multiline&&t.push("m"),e.sticky&&t.push("y"),e.unicode&&t.push("u"),t.join("")}}function b(e){let t=e,n={}.toString.call(e).slice(8,-1);if(n=="Set"&&(t=new Set([...e].map(r=>b(r)))),n=="Map"&&(t=new Map([...e].map(r=>[b(r[0]),b(r[1])]))),n=="Date"&&(t=new Date(e.getTime())),n=="RegExp"&&(t=RegExp(e.source,ye(e))),n=="Array"||n=="Object"){t=Array.isArray(e)?[]:{};for(let r in e)t[r]=b(e[r]);}return t}function l(e){return e&&(e instanceof Date||e.constructor.name=="File"||e.constructor.name=="FileList")?false:typeof e=="object"&&e!==null&&!Array.isArray(e)}function C(e,t,n,r){var a,o;if(Array.isArray(t)&&(a=t.slice(0)),typeof t=="string"&&(a=t.split(".")),typeof t=="symbol"&&(a=[t]),!Array.isArray(a))throw new Error("props arg must be an array, a string or a symbol");if(o=a.pop(),!o)return false;L(o);for(var i;i=a.shift();)if(L(i),isNaN(parseInt(i))?(typeof e[i]>"u"&&(e[i]={}),e=e[i]):((e.$each??=[])[i]={},e=e.$each[i]),!e||typeof e!="object")return false;return r?e[o]={...e[o],$self:n}:e[o]=n,true}function L(e){if(e=="__proto__"||e=="constructor"||e=="prototype")throw new Error("setting of prototype values not supported")}function W(e){let t=e.async,n=r=>{let a=Se(e,r);return a instanceof Promise?a:a.issues?{$valid:false,$issues:a.issues}:{$valid:true,$issues:[]}};return "__depsArray"in e&&Array.isArray(e.__depsArray)&&e.__depsArray.length?t?withAsync(n,e.__depsArray):withParams(n,e.__depsArray):t?withAsync(n):n}function Se(e,t){try{return e.async?new Promise(async n=>{let r=await e["~standard"].validate(t);r.issues?n({$valid:!1,$issues:r.issues}):n({$valid:!0,$issues:[]});}):e["~standard"].validate(t)}catch{return {}}}function q(e){return e.type==="intersect"}function Z(e){return e.type==="object"}function x(e){return "wrapped"in e}function _(e){return q(e)?{entries:e.options.reduce((n,r)=>{let a=_(r);return a&&(n={...n,...a.entries}),n},{}),type:"object",kind:"schema",async:false}:Z(e)?e:x(e)?_(e.wrapped):undefined}function z(e,t){let n=_(e);return n?Object.fromEntries(Object.entries(n.entries).map(([r,a])=>{if(typeof a=="object"){let o=toRef(l(t.value)?t.value:{},r);return [r,T(a,o)]}return [r,{}]})):{}}function _e(e){return e?.type==="literal"}function H(e,t){let n=effectScope();return n.run(()=>{let a=ref({});return watch(t,()=>{if(l(t.value)&&t.value[e.key]){let o=e.options.find(i=>{let s=_(i)?.entries[e.key];return _e(s)&&l(t.value)?s.literal===t.value[e.key]:false});o&&Z(o)?a.value=Object.fromEntries(Object.entries(o.entries).map(([i,f])=>[i,T(f,toRef(l(t.value)?t.value:{},i))])):a.value={};}else a.value={[e.key]:{required:required}};},{deep:true,flush:"pre",immediate:true}),onScopeDispose(()=>{n.stop();}),{valibotRule:a}})}function h(){return e=>{let t=e.$issues?.map(n=>n.message);return t?.length?t.length?t:"Error":[]}}function Oe(e){return e.type==="array"}function De(e){return e.type==="object"}function Ze(e){return e.type==="variant"}function K(e){return x(e)?K(e.wrapped):e}function T(e,t){let n=K(e);return Oe(n)?G(n,t):De(n)?z(n,t):Ze(n)?H(n,t).valibotRule:{[n.type]:withMessage(W(n),h())}}function G(e,t){let n={};return "pipe"in e&&e.pipe.filter(r=>r.kind==="validation").forEach(r=>{n[r.type]=withMessage(a=>{let o=r["~run"]({value:a,typed:true},{});return {$valid:!o.issues,$issues:o.issues}},h());}),{$each:T(e.item,t),...n}}function A(e,t){let n=w(e);function r(a){if(t?.value?.length)return {$valid:false,$issues:t.value};let o=Ie(e,a);return o instanceof Promise?o:o.success?{$valid:true,$issues:[]}:{$valid:false,$issues:o.error?.issues??[]}}return e&&"__depsArray"in e&&Array.isArray(e.__depsArray)&&e.__depsArray.length?n?withAsync(r,e.__depsArray):withParams(r,e.__depsArray):n?withAsync(r):r}function Ie(e,t){if(e)try{return e.safeParse(t)}catch{try{return new Promise(async r=>{let a=await e.safeParseAsync(t);a.success?r({$valid:!0,$issues:[]}):r({$valid:!1,$issues:a.error?.issues});})}catch{return {}}}else return {success:true,data:{}}}function Q(e){if(typeof e!="function")return false;if(e.constructor.name==="AsyncFunction")return true;try{return e()instanceof Promise}catch{return false}}function w(e){if(e?._def){if(e._def.typeName==="ZodEffects"){let t=e._def.effect;return Q(t.refinement||t.transform)}if(e._def.typeName==="ZodObject")return Object.values(e._def.shape()).some(t=>w(t));if(e._def.typeName==="ZodUnion"||e._def.typeName==="ZodIntersection")return e._def.options.some(w);if(e._def.typeName==="ZodArray")return w(e._def.type);if(e._def.typeName==="ZodOptional"||e._def.typeName==="ZodNullable")return w(e._def.innerType);if(e._def.typeName==="ZodTuple")return e._def.items.some(w);if(e._def.typeName==="ZodString"||e._def.typeName==="ZodNumber"||e._def.typeName==="ZodDate")return e._def.checks?.some(t=>Q(t.refinement))}return false}function X(e,t,n){let r=effectScope();return r.run(()=>{let o=ref({});return watch(t,()=>{if(l(t.value)&&t.value[e._def.discriminator]){let i=e._def.optionsMap.get(t.value[e._def.discriminator]);i?o.value=Object.fromEntries(Object.entries(i._def.shape()).map(([f,s])=>typeof s=="object"&&"_def"in s?[f,R({schema:s,state:toRef(l(t.value)?t.value:{}),additionalIssues:n})]:[f,{}])):o.value={};}else o.value={[e._def.discriminator]:{required:required}};},{deep:true,flush:"pre",immediate:true}),onScopeDispose(()=>{r.stop();}),{zodRule:o}})}var $e=["ZodDefault","ZodCatch","ZodNullable","ZodOptional","ZodReadonly"];function Be(e){return e._def&&typeof e._def=="object"&&"typeName"in e._def?$e.includes(e._def.typeName):false}function Fe(e){return e._def&&typeof e._def=="object"&&"typeName"in e._def?"schema"in e._def:false}function k(e){if(e?._def&&typeof e._def=="object"&&"typeName"in e._def)return Be(e)?k(e._def.innerType):Fe(e)?k(e._def.schema):e}function R({schema:e,state:t,additionalIssues:n}){let r=k(e);return r?._def&&"typeName"in r._def?r._def.typeName==="ZodArray"||r._def.typeName==="ZodTuple"?ee(e,t,n).zodRule:r._def.typeName==="ZodObject"||r._def.typeName==="ZodIntersection"?I(r,t,n).zodRule:r._def.typeName==="ZodDiscriminatedUnion"?X(r,t,n).zodRule:n?{[r.constructor.name]:withMessage(withParams(A(e,n),[t]),h())}:{[r.constructor.name]:withMessage(A(e),h())}:{}}function re(e,t=[]){return e._def&&"typeName"in e._def?e._def.typeName==="ZodEffects"?re(e._def.schema,t.concat([e._def.effect])):{nestedSchema:e,nestedEffects:t}:{nestedSchema:undefined}}function ee(e,t,n){let{nestedSchema:r,nestedEffects:a}=re(e),o=ref({});if(r){let i=r._def.typeName==="ZodArray"?{...!!r._def.minLength&&{minLength:minLength(r._def.minLength?.value)},...!!r._def.maxLength&&{maxLength:maxLength(r._def.maxLength?.value)},...!!r._def.exactLength&&{exactLength:exactLength(r._def.exactLength?.value)}}:{};if(a?.length){let f=effectScope();f.run(()=>{let s=ref([]),u=computed(()=>s.value.concat(n?.value??[]));if(n||watch(t,()=>{r&&(s.value=e.safeParse(t.value).error?.issues.filter(d=>d.code==="custom")??[]);},{deep:true,immediate:true}),r){let d=r._def.typeName==="ZodArray"?r._def.type:r._def.items,v=computed(()=>u.value.filter(c=>!c.path.length));o.value={$each:(c,m)=>{let g=computed(()=>u.value?.filter(p=>p.code==="custom")?.filter(p=>p.path[0]===m.toString()).map(p=>{let[le,...B]=p.path;return {...p,path:B}}));return R({schema:d,state:t,additionalIssues:g})},selfValidator:withMessage(withParams(A(undefined,v),[t,v]),h())};}else o.value={};onScopeDispose(()=>{f.stop();});});}else {let f=r._def.typeName==="ZodArray"?r._def.type:r._def.items;o.value={$each:R({schema:f,state:t,additionalIssues:n}),...i};}}return reactive({zodRule:o})}function O(e,t=[]){if(e._def&&"typeName"in e._def){if(e._def.typeName==="ZodEffects")return O(e._def.schema,t.concat([e._def.effect]));if(e._def.typeName==="ZodIntersection"){let{nestedSchema:n,nestedEffects:r=[]}=O(e._def.left),{nestedSchema:a,nestedEffects:o=[]}=O(e._def.right);return n&&a?O(n.merge(a),t.concat(r).concat(o)):{nestedSchema:undefined}}else return {nestedSchema:e,nestedEffects:t}}return {nestedSchema:undefined}}function I(e,t,n){let{nestedSchema:r,nestedEffects:a}=O(e),o=ref({});if(r)if(a?.length){let i=effectScope();i.run(()=>{let f=ref([]),s=computed(()=>f.value.concat(n?.value??[]));watch(t,()=>{r?._def?.typeName==="ZodObject"&&(f.value=(n?.value??[]).concat(e.safeParse(t.value).error?.issues.filter(u=>u.code==="custom")??[]));},{deep:true,flush:"sync",immediate:true}),r?._def?.typeName==="ZodObject"?o.value=Object.fromEntries(Object.entries(r._def.shape()).map(([u,d])=>{if(d&&typeof d=="object"&&"_def"in d){let v=toRef(l(t.value)?t.value:{},u),c=computed(()=>s.value?.filter(m=>m.path[0]===u).map(m=>{let[g,...p]=m.path;return {...m,path:p}}));return [u,R({schema:d,state:v,additionalIssues:c}),[t]]}return [u,{}]})):o.value={},onScopeDispose(()=>{i.stop();});});}else o.value=Object.fromEntries(Object.entries(r._def.shape()).map(([i,f])=>{if(f&&typeof f=="object"&&"_def"in f){let s=toRef(l(t.value)?t.value:{},i);return [i,R({schema:f,state:s,additionalIssues:n})]}return [i,{}]}));return reactive({zodRule:o})}function V(e,t){let n={autoDirty:e?.autoDirty,lazy:e?.lazy,rewardEarly:e?.rewardEarly,clearExternalErrorsOnChange:e?.clearExternalErrorsOnChange};function r(a,o,i){let f=ref({}),s=computed(()=>unref(o)),{mode:u="rules",...d}=i??{},v={...n,...d},c=isRef(a)?a:ref(a),m=ref({...b(c.value)}),g=ref({}),p;if(u==="rules")watch(s,()=>{if(s.value&&typeof s.value=="object")if(s.value["~standard"].vendor==="zod"){let N=I(s.value,c);f.value=N.zodRule;}else s.value["~standard"].vendor==="valibot"?f.value=reactive(z(s.value,c)):s.value?.["~standard"]?.vendor?console.warn(`This RPC library "${s.value["~standard"].vendor}" is not supported yet in 'rules' mode, switch to the "schema" mode option`):console.warn('Only "standard-schema" compatible libraries are supported');},{deep:true,immediate:true,flush:"post"});else {let D=function(S){let F={};return S.issues&&S.issues.map(y=>{let pe=y.path?.map(j=>typeof j=="object"?j.key:j).join("."),P=y.path?.[y.path.length-1],de=(typeof P=="object"&&"value"in P?Array.isArray(P.value):false)||("type"in y?y.type==="array":false);return {path:pe,message:y.message,isArray:de}}).forEach(y=>{C(F,y.path,[y.message],y.isArray);}),F};if(!s.value?.["~standard"])throw new Error('Only "standard-schema" compatible libraries are supported');let N=s.value["~standard"].validate(m.value);g.value=D(N),watch([c,s],async()=>{let S=await s.value["~standard"].validate(c.value);g.value=D(S);},{deep:true,immediate:true,flush:"post"}),p=async()=>{try{let S=await s.value["~standard"].validate(c.value);return g.value=D(S),{result:!S.issues?.length,data:c.value}}catch(S){return Promise.reject(S)}};}return {r$:useRootStorage({scopeRules:f,state:c,options:v,schemaErrors:g,initialState:m,shortcuts:t,schemaMode:u==="schema",onValidate:p}).regle}}return r}var ie=V();function fe(e,t){return Object.hasOwn(e,"__depsArray")||Object.defineProperties(e,{__depsArray:{value:t,enumerable:false,configurable:false,writable:false}}),e}function $(){function e(t,n){return n}return e}var ce=$();function ue({modifiers:e,shortcuts:t}){let n=V(e,t),r=$();return {useRegleSchema:n,inferSchema:r}}export{ue as defineRegleSchemaConfig,ce as inferSchema,ie as useRegleSchema,fe as withDeps};
|
package/dist/regle-schemas.mjs
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { useRootStorage } from '@regle/core';
|
|
2
2
|
import { ref, computed, unref, isRef, watch, reactive, toRef, effectScope, onScopeDispose } from 'vue';
|
|
3
3
|
import { withMessage, withAsync, withParams, required, minLength, maxLength, exactLength } from '@regle/rules';
|
|
4
|
-
import * as v3 from 'valibot';
|
|
5
|
-
import z, { z as z$1 } from 'zod';
|
|
6
4
|
|
|
7
5
|
// src/core/useRegleSchema.ts
|
|
8
6
|
|
|
@@ -105,7 +103,7 @@ function transformValibotAdapter(schema) {
|
|
|
105
103
|
if (result instanceof Promise) {
|
|
106
104
|
return result;
|
|
107
105
|
}
|
|
108
|
-
if (result.
|
|
106
|
+
if (!result.issues) {
|
|
109
107
|
return {
|
|
110
108
|
$valid: true,
|
|
111
109
|
$issues: []
|
|
@@ -126,8 +124,8 @@ function trySafeTransform(schema, value) {
|
|
|
126
124
|
try {
|
|
127
125
|
if (schema.async) {
|
|
128
126
|
return new Promise(async (resolve) => {
|
|
129
|
-
const result = await
|
|
130
|
-
if (result.
|
|
127
|
+
const result = await schema["~standard"].validate(value);
|
|
128
|
+
if (!result.issues) {
|
|
131
129
|
resolve({
|
|
132
130
|
$valid: true,
|
|
133
131
|
$issues: []
|
|
@@ -140,7 +138,7 @@ function trySafeTransform(schema, value) {
|
|
|
140
138
|
}
|
|
141
139
|
});
|
|
142
140
|
} else {
|
|
143
|
-
const result =
|
|
141
|
+
const result = schema["~standard"].validate(value);
|
|
144
142
|
return result;
|
|
145
143
|
}
|
|
146
144
|
} catch (e) {
|
|
@@ -158,8 +156,6 @@ function isObjectSchema(schema) {
|
|
|
158
156
|
function isWrappedType(schema) {
|
|
159
157
|
return "wrapped" in schema;
|
|
160
158
|
}
|
|
161
|
-
|
|
162
|
-
// src/core/converters/valibot/validators/valibotObjectToRegle.ts
|
|
163
159
|
function getNestedValibotObjectSchema(schema) {
|
|
164
160
|
if (isIntersectSchema(schema)) {
|
|
165
161
|
const allEntries = schema.options.reduce(
|
|
@@ -175,7 +171,7 @@ function getNestedValibotObjectSchema(schema) {
|
|
|
175
171
|
},
|
|
176
172
|
{}
|
|
177
173
|
);
|
|
178
|
-
return
|
|
174
|
+
return { entries: allEntries, type: "object", kind: "schema", async: false };
|
|
179
175
|
} else if (isObjectSchema(schema)) {
|
|
180
176
|
return schema;
|
|
181
177
|
} else if (isWrappedType(schema)) {
|
|
@@ -249,7 +245,10 @@ function valibotVariantToRegle(schema, state) {
|
|
|
249
245
|
function extractIssuesMessages() {
|
|
250
246
|
return (metadata) => {
|
|
251
247
|
const issueMessages = metadata.$issues?.map((issue) => issue.message);
|
|
252
|
-
|
|
248
|
+
if (issueMessages?.length) {
|
|
249
|
+
return issueMessages.length ? issueMessages : "Error";
|
|
250
|
+
}
|
|
251
|
+
return [];
|
|
253
252
|
};
|
|
254
253
|
}
|
|
255
254
|
|
|
@@ -291,10 +290,13 @@ function valibotArrayToRegle(schema, state) {
|
|
|
291
290
|
let filteredSelfSchema = {};
|
|
292
291
|
if ("pipe" in schema) {
|
|
293
292
|
schema.pipe.filter((f) => f.kind === "validation").forEach((validation) => {
|
|
294
|
-
filteredSelfSchema[validation.type] = withMessage(
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
293
|
+
filteredSelfSchema[validation.type] = withMessage((value) => {
|
|
294
|
+
const result = validation["~run"]({ value, typed: true }, {});
|
|
295
|
+
return {
|
|
296
|
+
$valid: !result.issues,
|
|
297
|
+
$issues: result.issues
|
|
298
|
+
};
|
|
299
|
+
}, extractIssuesMessages());
|
|
298
300
|
});
|
|
299
301
|
}
|
|
300
302
|
return {
|
|
@@ -302,9 +304,16 @@ function valibotArrayToRegle(schema, state) {
|
|
|
302
304
|
...filteredSelfSchema
|
|
303
305
|
};
|
|
304
306
|
}
|
|
305
|
-
function transformZodValidatorAdapter(schema) {
|
|
307
|
+
function transformZodValidatorAdapter(schema, additionalIssues) {
|
|
306
308
|
const isAsync = hasAsyncRefinement(schema);
|
|
307
|
-
|
|
309
|
+
function validatorFn(value) {
|
|
310
|
+
if (additionalIssues?.value?.length) {
|
|
311
|
+
return {
|
|
312
|
+
$valid: false,
|
|
313
|
+
// additionalIssues should already contain field error if there is a refinement in a parent
|
|
314
|
+
$issues: additionalIssues.value
|
|
315
|
+
};
|
|
316
|
+
}
|
|
308
317
|
const result = trySafeTransform2(schema, value);
|
|
309
318
|
if (result instanceof Promise) {
|
|
310
319
|
return result;
|
|
@@ -317,38 +326,43 @@ function transformZodValidatorAdapter(schema) {
|
|
|
317
326
|
} else {
|
|
318
327
|
return {
|
|
319
328
|
$valid: false,
|
|
320
|
-
|
|
329
|
+
// additionalIssues should already contain field error if there is a refinement in a parent
|
|
330
|
+
$issues: result.error?.issues ?? []
|
|
321
331
|
};
|
|
322
332
|
}
|
|
323
|
-
}
|
|
324
|
-
if ("__depsArray" in schema && Array.isArray(schema.__depsArray) && schema.__depsArray.length) {
|
|
333
|
+
}
|
|
334
|
+
if (schema && "__depsArray" in schema && Array.isArray(schema.__depsArray) && schema.__depsArray.length) {
|
|
325
335
|
return isAsync ? withAsync(validatorFn, schema.__depsArray) : withParams(validatorFn, schema.__depsArray);
|
|
326
336
|
}
|
|
327
337
|
return isAsync ? withAsync(validatorFn) : validatorFn;
|
|
328
338
|
}
|
|
329
339
|
function trySafeTransform2(schema, value) {
|
|
330
|
-
|
|
331
|
-
const result = schema.safeParse(value);
|
|
332
|
-
return result;
|
|
333
|
-
} catch (e) {
|
|
340
|
+
if (schema) {
|
|
334
341
|
try {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
342
|
+
const result = schema.safeParse(value);
|
|
343
|
+
return result;
|
|
344
|
+
} catch (e) {
|
|
345
|
+
try {
|
|
346
|
+
return new Promise(async (resolve) => {
|
|
347
|
+
const result = await schema.safeParseAsync(value);
|
|
348
|
+
if (result.success) {
|
|
349
|
+
resolve({
|
|
350
|
+
$valid: true,
|
|
351
|
+
$issues: []
|
|
352
|
+
});
|
|
353
|
+
} else {
|
|
354
|
+
resolve({
|
|
355
|
+
$valid: false,
|
|
356
|
+
$issues: result.error?.issues
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
} catch (e2) {
|
|
361
|
+
return {};
|
|
362
|
+
}
|
|
351
363
|
}
|
|
364
|
+
} else {
|
|
365
|
+
return { success: true, data: {} };
|
|
352
366
|
}
|
|
353
367
|
}
|
|
354
368
|
function isAsyncFunctionOrPromiseReturning(fn) {
|
|
@@ -390,7 +404,7 @@ function hasAsyncRefinement(schema) {
|
|
|
390
404
|
}
|
|
391
405
|
return false;
|
|
392
406
|
}
|
|
393
|
-
function zodDiscriminatedUnionToRegle(schema, state) {
|
|
407
|
+
function zodDiscriminatedUnionToRegle(schema, state, additionalIssues) {
|
|
394
408
|
const scope = effectScope();
|
|
395
409
|
const scopeState = scope.run(() => {
|
|
396
410
|
const zodRule = ref({});
|
|
@@ -403,7 +417,14 @@ function zodDiscriminatedUnionToRegle(schema, state) {
|
|
|
403
417
|
zodRule.value = Object.fromEntries(
|
|
404
418
|
Object.entries(selectedDiscriminant._def.shape()).map(([key, shape]) => {
|
|
405
419
|
if (typeof shape === "object" && "_def" in shape) {
|
|
406
|
-
return [
|
|
420
|
+
return [
|
|
421
|
+
key,
|
|
422
|
+
processZodTypeDef({
|
|
423
|
+
schema: shape,
|
|
424
|
+
state: toRef(isObject(state.value) ? state.value : {}),
|
|
425
|
+
additionalIssues
|
|
426
|
+
})
|
|
427
|
+
];
|
|
407
428
|
}
|
|
408
429
|
return [key, {}];
|
|
409
430
|
})
|
|
@@ -428,13 +449,7 @@ function zodDiscriminatedUnionToRegle(schema, state) {
|
|
|
428
449
|
}
|
|
429
450
|
|
|
430
451
|
// src/core/converters/zod/processZodTypeDef.ts
|
|
431
|
-
var typesWithInnerTypes = [
|
|
432
|
-
z.ZodFirstPartyTypeKind.ZodDefault,
|
|
433
|
-
z.ZodFirstPartyTypeKind.ZodCatch,
|
|
434
|
-
z.ZodFirstPartyTypeKind.ZodNullable,
|
|
435
|
-
z.ZodFirstPartyTypeKind.ZodOptional,
|
|
436
|
-
z.ZodFirstPartyTypeKind.ZodReadonly
|
|
437
|
-
];
|
|
452
|
+
var typesWithInnerTypes = ["ZodDefault", "ZodCatch", "ZodNullable", "ZodOptional", "ZodReadonly"];
|
|
438
453
|
function isDefWithInnerType(schema) {
|
|
439
454
|
if (schema._def && typeof schema._def === "object" && "typeName" in schema._def) {
|
|
440
455
|
return typesWithInnerTypes.includes(schema._def.typeName);
|
|
@@ -459,17 +474,39 @@ function getNestedInnerType2(schema) {
|
|
|
459
474
|
}
|
|
460
475
|
return undefined;
|
|
461
476
|
}
|
|
462
|
-
function processZodTypeDef(
|
|
477
|
+
function processZodTypeDef({
|
|
478
|
+
schema,
|
|
479
|
+
state,
|
|
480
|
+
additionalIssues
|
|
481
|
+
}) {
|
|
463
482
|
const schemaDef = getNestedInnerType2(schema);
|
|
464
483
|
if (schemaDef?._def && "typeName" in schemaDef._def) {
|
|
465
|
-
if (schemaDef._def.typeName ===
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
484
|
+
if (schemaDef._def.typeName === "ZodArray" || schemaDef._def.typeName === "ZodTuple") {
|
|
485
|
+
const schemaRef = zodArrayToRegle(schema, state, additionalIssues);
|
|
486
|
+
return schemaRef.zodRule;
|
|
487
|
+
} else if (schemaDef._def.typeName === "ZodObject" || schemaDef._def.typeName === "ZodIntersection") {
|
|
488
|
+
const schemaRef = zodObjectToRegle(
|
|
489
|
+
schemaDef,
|
|
490
|
+
state,
|
|
491
|
+
additionalIssues
|
|
492
|
+
);
|
|
493
|
+
return schemaRef.zodRule;
|
|
494
|
+
} else if (schemaDef._def.typeName === "ZodDiscriminatedUnion") {
|
|
495
|
+
const schemaRef = zodDiscriminatedUnionToRegle(
|
|
496
|
+
schemaDef,
|
|
497
|
+
state,
|
|
498
|
+
additionalIssues
|
|
499
|
+
);
|
|
500
|
+
return schemaRef.zodRule;
|
|
472
501
|
} else {
|
|
502
|
+
if (additionalIssues) {
|
|
503
|
+
return {
|
|
504
|
+
[schemaDef.constructor.name]: withMessage(
|
|
505
|
+
withParams(transformZodValidatorAdapter(schema, additionalIssues), [state]),
|
|
506
|
+
extractIssuesMessages()
|
|
507
|
+
)
|
|
508
|
+
};
|
|
509
|
+
}
|
|
473
510
|
return {
|
|
474
511
|
[schemaDef.constructor.name]: withMessage(
|
|
475
512
|
transformZodValidatorAdapter(schema),
|
|
@@ -482,52 +519,190 @@ function processZodTypeDef(schema, state) {
|
|
|
482
519
|
}
|
|
483
520
|
|
|
484
521
|
// src/core/converters/zod/validators/zodArrayToRegle.ts
|
|
485
|
-
function
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
}
|
|
522
|
+
function getNestedZodArraySchema(schema, effects = []) {
|
|
523
|
+
if (schema._def && "typeName" in schema._def) {
|
|
524
|
+
if (schema._def.typeName === "ZodEffects") {
|
|
525
|
+
return getNestedZodArraySchema(
|
|
526
|
+
schema._def.schema,
|
|
527
|
+
effects.concat([schema._def.effect])
|
|
528
|
+
);
|
|
529
|
+
} else {
|
|
530
|
+
return { nestedSchema: schema, nestedEffects: effects };
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return { nestedSchema: undefined };
|
|
496
534
|
}
|
|
497
|
-
function
|
|
535
|
+
function zodArrayToRegle(schema, state, rootAdditionalIssues) {
|
|
536
|
+
const { nestedSchema, nestedEffects } = getNestedZodArraySchema(schema);
|
|
537
|
+
const zodRule = ref({});
|
|
538
|
+
if (nestedSchema) {
|
|
539
|
+
const arrayValidators = nestedSchema._def.typeName === "ZodArray" ? {
|
|
540
|
+
...!!nestedSchema._def.minLength && { minLength: minLength(nestedSchema._def.minLength?.value) },
|
|
541
|
+
...!!nestedSchema._def.maxLength && { maxLength: maxLength(nestedSchema._def.maxLength?.value) },
|
|
542
|
+
...!!nestedSchema._def.exactLength && { exactLength: exactLength(nestedSchema._def.exactLength?.value) }
|
|
543
|
+
} : {};
|
|
544
|
+
if (nestedEffects?.length) {
|
|
545
|
+
const scope = effectScope();
|
|
546
|
+
scope.run(() => {
|
|
547
|
+
const localAdditionalIssues = ref([]);
|
|
548
|
+
const additionalIssues = computed(() => {
|
|
549
|
+
return localAdditionalIssues.value.concat(rootAdditionalIssues?.value ?? []);
|
|
550
|
+
});
|
|
551
|
+
if (!rootAdditionalIssues) {
|
|
552
|
+
watch(
|
|
553
|
+
state,
|
|
554
|
+
() => {
|
|
555
|
+
if (nestedSchema) {
|
|
556
|
+
localAdditionalIssues.value = schema.safeParse(state.value).error?.issues.filter((f) => f.code === "custom") ?? [];
|
|
557
|
+
}
|
|
558
|
+
},
|
|
559
|
+
{ deep: true, immediate: true }
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
if (nestedSchema) {
|
|
563
|
+
const items = nestedSchema._def.typeName === "ZodArray" ? nestedSchema._def.type : nestedSchema._def.items;
|
|
564
|
+
const selfAdditionalIssues = computed(() => additionalIssues.value.filter((f) => !f.path.length));
|
|
565
|
+
zodRule.value = {
|
|
566
|
+
$each: (_, index) => {
|
|
567
|
+
const fieldIssues = computed(() => {
|
|
568
|
+
return additionalIssues.value?.filter((f) => f.code === "custom")?.filter((f) => f.path[0] === index.toString()).map((m) => {
|
|
569
|
+
const [first, ...rest] = m.path;
|
|
570
|
+
return {
|
|
571
|
+
...m,
|
|
572
|
+
path: rest
|
|
573
|
+
};
|
|
574
|
+
});
|
|
575
|
+
});
|
|
576
|
+
return processZodTypeDef({ schema: items, state, additionalIssues: fieldIssues });
|
|
577
|
+
},
|
|
578
|
+
selfValidator: withMessage(
|
|
579
|
+
withParams(transformZodValidatorAdapter(undefined, selfAdditionalIssues), [
|
|
580
|
+
state,
|
|
581
|
+
selfAdditionalIssues
|
|
582
|
+
]),
|
|
583
|
+
extractIssuesMessages()
|
|
584
|
+
)
|
|
585
|
+
};
|
|
586
|
+
} else {
|
|
587
|
+
zodRule.value = {};
|
|
588
|
+
}
|
|
589
|
+
onScopeDispose(() => {
|
|
590
|
+
scope.stop();
|
|
591
|
+
});
|
|
592
|
+
});
|
|
593
|
+
} else {
|
|
594
|
+
const items = nestedSchema._def.typeName === "ZodArray" ? nestedSchema._def.type : nestedSchema._def.items;
|
|
595
|
+
zodRule.value = {
|
|
596
|
+
$each: processZodTypeDef({ schema: items, state, additionalIssues: rootAdditionalIssues }),
|
|
597
|
+
...arrayValidators
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
return reactive({ zodRule });
|
|
602
|
+
}
|
|
603
|
+
function getNestedZodObjectSchema(schema, effects = []) {
|
|
498
604
|
if (schema._def && "typeName" in schema._def) {
|
|
499
|
-
if (schema._def.typeName ===
|
|
500
|
-
return getNestedZodObjectSchema(
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
605
|
+
if (schema._def.typeName === "ZodEffects") {
|
|
606
|
+
return getNestedZodObjectSchema(
|
|
607
|
+
schema._def.schema,
|
|
608
|
+
effects.concat([schema._def.effect])
|
|
609
|
+
);
|
|
610
|
+
} else if (schema._def.typeName === "ZodIntersection") {
|
|
611
|
+
const { nestedSchema: leftObject, nestedEffects: leftEffects = [] } = getNestedZodObjectSchema(
|
|
612
|
+
schema._def.left
|
|
613
|
+
);
|
|
614
|
+
const { nestedSchema: rightObject, nestedEffects: rightEffects = [] } = getNestedZodObjectSchema(
|
|
615
|
+
schema._def.right
|
|
616
|
+
);
|
|
504
617
|
if (leftObject && rightObject) {
|
|
505
|
-
return getNestedZodObjectSchema(
|
|
618
|
+
return getNestedZodObjectSchema(
|
|
619
|
+
leftObject.merge(rightObject),
|
|
620
|
+
effects.concat(leftEffects).concat(rightEffects)
|
|
621
|
+
);
|
|
506
622
|
}
|
|
507
|
-
return undefined;
|
|
623
|
+
return { nestedSchema: undefined };
|
|
508
624
|
} else {
|
|
509
|
-
return schema;
|
|
625
|
+
return { nestedSchema: schema, nestedEffects: effects };
|
|
510
626
|
}
|
|
511
627
|
}
|
|
512
|
-
return undefined;
|
|
628
|
+
return { nestedSchema: undefined };
|
|
513
629
|
}
|
|
514
|
-
function zodObjectToRegle(schema, state) {
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
630
|
+
function zodObjectToRegle(schema, state, rootAdditionalIssues) {
|
|
631
|
+
const { nestedSchema, nestedEffects } = getNestedZodObjectSchema(schema);
|
|
632
|
+
const zodRule = ref({});
|
|
633
|
+
if (nestedSchema) {
|
|
634
|
+
if (nestedEffects?.length) {
|
|
635
|
+
const scope = effectScope();
|
|
636
|
+
scope.run(() => {
|
|
637
|
+
const localAdditionalIssues = ref([]);
|
|
638
|
+
const additionalIssues = computed(() => {
|
|
639
|
+
return localAdditionalIssues.value.concat(rootAdditionalIssues?.value ?? []);
|
|
640
|
+
});
|
|
641
|
+
watch(
|
|
642
|
+
state,
|
|
643
|
+
() => {
|
|
644
|
+
if (nestedSchema?._def?.typeName === "ZodObject") {
|
|
645
|
+
localAdditionalIssues.value = (rootAdditionalIssues?.value ?? []).concat(
|
|
646
|
+
schema.safeParse(state.value).error?.issues.filter((f) => f.code === "custom") ?? []
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
},
|
|
650
|
+
{ deep: true, flush: "sync", immediate: true }
|
|
651
|
+
);
|
|
652
|
+
if (nestedSchema?._def?.typeName === "ZodObject") {
|
|
653
|
+
zodRule.value = Object.fromEntries(
|
|
654
|
+
Object.entries(nestedSchema._def.shape()).map(([key, shape]) => {
|
|
655
|
+
if (shape && typeof shape === "object" && "_def" in shape) {
|
|
656
|
+
const childState = toRef(isObject(state.value) ? state.value : {}, key);
|
|
657
|
+
const fieldIssues = computed(() => {
|
|
658
|
+
return additionalIssues.value?.filter((f) => f.path[0] === key).map((m) => {
|
|
659
|
+
const [_, ...rest] = m.path;
|
|
660
|
+
return {
|
|
661
|
+
...m,
|
|
662
|
+
path: rest
|
|
663
|
+
};
|
|
664
|
+
});
|
|
665
|
+
});
|
|
666
|
+
return [
|
|
667
|
+
key,
|
|
668
|
+
processZodTypeDef({
|
|
669
|
+
schema: shape,
|
|
670
|
+
state: childState,
|
|
671
|
+
additionalIssues: fieldIssues
|
|
672
|
+
}),
|
|
673
|
+
[state]
|
|
674
|
+
];
|
|
675
|
+
}
|
|
676
|
+
return [key, {}];
|
|
677
|
+
})
|
|
678
|
+
);
|
|
679
|
+
} else {
|
|
680
|
+
zodRule.value = {};
|
|
681
|
+
}
|
|
682
|
+
onScopeDispose(() => {
|
|
683
|
+
scope.stop();
|
|
684
|
+
});
|
|
685
|
+
});
|
|
686
|
+
} else {
|
|
687
|
+
zodRule.value = Object.fromEntries(
|
|
519
688
|
Object.entries(nestedSchema._def.shape()).map(([key, shape]) => {
|
|
520
689
|
if (shape && typeof shape === "object" && "_def" in shape) {
|
|
521
690
|
const childState = toRef(isObject(state.value) ? state.value : {}, key);
|
|
522
|
-
return [
|
|
691
|
+
return [
|
|
692
|
+
key,
|
|
693
|
+
processZodTypeDef({
|
|
694
|
+
schema: shape,
|
|
695
|
+
state: childState,
|
|
696
|
+
additionalIssues: rootAdditionalIssues
|
|
697
|
+
})
|
|
698
|
+
];
|
|
523
699
|
}
|
|
524
700
|
return [key, {}];
|
|
525
701
|
})
|
|
526
702
|
);
|
|
527
703
|
}
|
|
528
|
-
return {};
|
|
529
704
|
}
|
|
530
|
-
return {};
|
|
705
|
+
return reactive({ zodRule });
|
|
531
706
|
}
|
|
532
707
|
|
|
533
708
|
// src/core/useRegleSchema.ts
|
|
@@ -556,9 +731,16 @@ function createUseRegleSchemaComposable(options, shortcuts) {
|
|
|
556
731
|
() => {
|
|
557
732
|
if (computedSchema.value && typeof computedSchema.value === "object") {
|
|
558
733
|
if (computedSchema.value["~standard"].vendor === "zod") {
|
|
559
|
-
|
|
734
|
+
const objectResult = zodObjectToRegle(computedSchema.value, processedState);
|
|
735
|
+
convertedRules.value = objectResult.zodRule;
|
|
560
736
|
} else if (computedSchema.value["~standard"].vendor === "valibot") {
|
|
561
737
|
convertedRules.value = reactive(valibotObjectToRegle(computedSchema.value, processedState));
|
|
738
|
+
} else if (computedSchema.value?.["~standard"]?.vendor) {
|
|
739
|
+
console.warn(
|
|
740
|
+
`This RPC library "${computedSchema.value["~standard"].vendor}" is not supported yet in 'rules' mode, switch to the "schema" mode option`
|
|
741
|
+
);
|
|
742
|
+
} else {
|
|
743
|
+
console.warn(`Only "standard-schema" compatible libraries are supported`);
|
|
562
744
|
}
|
|
563
745
|
}
|
|
564
746
|
},
|
|
@@ -584,6 +766,9 @@ function createUseRegleSchemaComposable(options, shortcuts) {
|
|
|
584
766
|
}
|
|
585
767
|
return output;
|
|
586
768
|
};
|
|
769
|
+
if (!computedSchema.value?.["~standard"]) {
|
|
770
|
+
throw new Error(`Only "standard-schema" compatible libraries are supported`);
|
|
771
|
+
}
|
|
587
772
|
const emptySkeleton = computedSchema.value["~standard"].validate(initialState.value);
|
|
588
773
|
customErrors.value = issuesToRegleErrors2(emptySkeleton);
|
|
589
774
|
watch(
|
|
@@ -625,7 +810,17 @@ function createUseRegleSchemaComposable(options, shortcuts) {
|
|
|
625
810
|
}
|
|
626
811
|
var useRegleSchema = createUseRegleSchemaComposable();
|
|
627
812
|
function withDeps(schema, depsArray) {
|
|
628
|
-
|
|
813
|
+
if (!Object.hasOwn(schema, "__depsArray")) {
|
|
814
|
+
Object.defineProperties(schema, {
|
|
815
|
+
__depsArray: {
|
|
816
|
+
value: depsArray,
|
|
817
|
+
enumerable: false,
|
|
818
|
+
configurable: false,
|
|
819
|
+
writable: false
|
|
820
|
+
}
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
return schema;
|
|
629
824
|
}
|
|
630
825
|
function createInferValibotSchemaHelper() {
|
|
631
826
|
function inferRules(state, rulesFactory) {
|
package/package.json
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@regle/schemas",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.6",
|
|
4
4
|
"description": "Schemas adapter for Regle",
|
|
5
5
|
"dependencies": {
|
|
6
|
-
"@standard-schema/spec": "1.0.0
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
|
|
6
|
+
"@standard-schema/spec": "1.0.0",
|
|
7
|
+
"@regle/core": "0.7.6",
|
|
8
|
+
"@regle/rules": "0.7.6"
|
|
9
|
+
},
|
|
10
|
+
"peerDependencies": {
|
|
11
|
+
"valibot": "^1.0.0-beta.11",
|
|
12
|
+
"zod": "^3.24.0"
|
|
13
|
+
},
|
|
14
|
+
"peerDependenciesMeta": {
|
|
15
|
+
"valibot": {
|
|
16
|
+
"optional": true
|
|
17
|
+
},
|
|
18
|
+
"zod": {
|
|
19
|
+
"optional": true
|
|
20
|
+
}
|
|
11
21
|
},
|
|
12
22
|
"devDependencies": {
|
|
13
23
|
"@total-typescript/ts-reset": "0.6.1",
|
|
@@ -25,7 +35,7 @@
|
|
|
25
35
|
"tsup": "8.3.5",
|
|
26
36
|
"type-fest": "4.28.0",
|
|
27
37
|
"typescript": "5.6.3",
|
|
28
|
-
"valibot": "1.0.0-beta.
|
|
38
|
+
"valibot": "1.0.0-beta.14",
|
|
29
39
|
"vitest": "2.1.8",
|
|
30
40
|
"vue": "3.5.13",
|
|
31
41
|
"vue-eslint-parser": "9.4.3",
|