@regle/schemas 1.2.3 → 1.3.0-beta.1

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,290 @@
1
+ import { createScopedUseRegle, useRootStorage } from "@regle/core";
2
+ import { computed, isRef, ref, unref, watch } from "vue";
3
+
4
+ //#region ../shared/utils/symbol.ts
5
+ const RegleRuleSymbol = Symbol("regle-rule");
6
+
7
+ //#endregion
8
+ //#region ../shared/utils/cloneDeep.ts
9
+ function getRegExpFlags(regExp) {
10
+ if (typeof regExp.source.flags == "string") return regExp.source.flags;
11
+ else {
12
+ let flags = [];
13
+ regExp.global && flags.push("g");
14
+ regExp.ignoreCase && flags.push("i");
15
+ regExp.multiline && flags.push("m");
16
+ regExp.sticky && flags.push("y");
17
+ regExp.unicode && flags.push("u");
18
+ return flags.join("");
19
+ }
20
+ }
21
+ function cloneDeep(obj) {
22
+ let result = obj;
23
+ let type = {}.toString.call(obj).slice(8, -1);
24
+ if (type == "Set") result = new Set([...obj].map((value) => cloneDeep(value)));
25
+ if (type == "Map") result = new Map([...obj].map((kv) => [cloneDeep(kv[0]), cloneDeep(kv[1])]));
26
+ if (type == "Date") result = new Date(obj.getTime());
27
+ if (type == "RegExp") result = RegExp(obj.source, getRegExpFlags(obj));
28
+ if (type == "Array" || type == "Object") {
29
+ result = Array.isArray(obj) ? [] : {};
30
+ for (let key in obj) result[key] = cloneDeep(obj[key]);
31
+ }
32
+ return result;
33
+ }
34
+
35
+ //#endregion
36
+ //#region ../shared/utils/object.utils.ts
37
+ function isObject(obj) {
38
+ if (obj && (obj instanceof Date || obj.constructor.name == "File" || obj.constructor.name == "FileList")) return false;
39
+ return typeof obj === "object" && obj !== null && !Array.isArray(obj);
40
+ }
41
+ function setObjectError(obj, propsArg, value, isArray) {
42
+ var props, lastProp;
43
+ if (Array.isArray(propsArg)) props = propsArg.slice(0);
44
+ if (typeof propsArg == "string") props = propsArg.split(".");
45
+ if (typeof propsArg == "symbol") props = [propsArg];
46
+ if (!Array.isArray(props)) throw new Error("props arg must be an array, a string or a symbol");
47
+ lastProp = props.pop();
48
+ if (!lastProp) return false;
49
+ prototypeCheck(lastProp);
50
+ var thisProp;
51
+ while (thisProp = props.shift()) {
52
+ prototypeCheck(thisProp);
53
+ if (!isNaN(parseInt(thisProp))) {
54
+ (obj.$each ??= [])[thisProp] = {};
55
+ obj = obj.$each[thisProp];
56
+ } else {
57
+ if (typeof obj[thisProp] == "undefined") obj[thisProp] = {};
58
+ obj = obj[thisProp];
59
+ }
60
+ if (!obj || typeof obj != "object") return false;
61
+ }
62
+ if (isArray) if (!obj[lastProp]) obj[lastProp] = {
63
+ ...obj[lastProp],
64
+ $self: value
65
+ };
66
+ else obj[lastProp].$self = (obj[lastProp].$self ??= []).concat(value);
67
+ else if (Array.isArray(obj[lastProp])) obj[lastProp] = obj[lastProp].concat(value);
68
+ else obj[lastProp] = value;
69
+ return true;
70
+ }
71
+ function getDotPath(obj, propsArg, defaultValue) {
72
+ if (!obj) return defaultValue;
73
+ var props, prop;
74
+ if (Array.isArray(propsArg)) props = propsArg.slice(0);
75
+ if (typeof propsArg == "string") props = propsArg.split(".");
76
+ if (typeof propsArg == "symbol") props = [propsArg];
77
+ if (!Array.isArray(props)) throw new Error("props arg must be an array, a string or a symbol");
78
+ while (props.length) {
79
+ prop = props.shift();
80
+ if (!obj) return defaultValue;
81
+ if (!prop) return defaultValue;
82
+ obj = obj[prop];
83
+ if (obj === void 0) return defaultValue;
84
+ }
85
+ return obj;
86
+ }
87
+ function prototypeCheck(prop) {
88
+ if (prop == "__proto__" || prop == "constructor" || prop == "prototype") throw new Error("setting of prototype values not supported");
89
+ }
90
+ function merge(obj1, ...objs) {
91
+ var args = [].slice.call(arguments);
92
+ var arg;
93
+ var i = args.length;
94
+ while (arg = args[i - 1], i--) if (!arg || typeof arg != "object" && typeof arg != "function") throw new Error("expected object, got " + arg);
95
+ var result = args[0];
96
+ var extenders = args.slice(1);
97
+ var len = extenders.length;
98
+ for (var i = 0; i < len; i++) {
99
+ var extender = extenders[i];
100
+ for (var key in extender) result[key] = extender[key];
101
+ }
102
+ return result;
103
+ }
104
+
105
+ //#endregion
106
+ //#region src/core/useRegleSchema.ts
107
+ function createUseRegleSchemaComposable(options, shortcuts) {
108
+ const globalOptions = {
109
+ autoDirty: options?.autoDirty,
110
+ lazy: options?.lazy,
111
+ rewardEarly: options?.rewardEarly,
112
+ clearExternalErrorsOnChange: options?.clearExternalErrorsOnChange
113
+ };
114
+ function useRegleSchema$1(state, schema, options$1) {
115
+ const computedSchema = computed(() => unref(schema));
116
+ const { syncState = {
117
+ onUpdate: false,
118
+ onValidate: false
119
+ },...defaultOptions } = options$1 ?? {};
120
+ const { onUpdate: syncOnUpdate = false, onValidate: syncOnValidate = false } = syncState;
121
+ const resolvedOptions = {
122
+ ...globalOptions,
123
+ ...defaultOptions
124
+ };
125
+ const isSingleField = computed(() => !isObject(processedState.value));
126
+ const processedState = isRef(state) ? state : ref(state);
127
+ const initialState = ref(isObject(processedState.value) ? { ...cloneDeep(processedState.value) } : cloneDeep(processedState.value));
128
+ const customErrors = ref({});
129
+ let onValidate = void 0;
130
+ if (!computedSchema.value?.["~standard"]) throw new Error(`Only "standard-schema" compatible libraries are supported`);
131
+ function issuesToRegleErrors(result) {
132
+ const output = {};
133
+ if (result.issues) {
134
+ const errors = result.issues.map((issue) => {
135
+ const path = issue.path?.map((item) => typeof item === "object" ? item.key : item.toString()).join(".") ?? "";
136
+ const lastItem = issue.path?.[issue.path.length - 1];
137
+ const isArray = (typeof lastItem === "object" && "value" in lastItem ? Array.isArray(lastItem.value) : false) || ("type" in issue ? issue.type === "array" : false) || Array.isArray(getDotPath(processedState.value, path));
138
+ return {
139
+ path,
140
+ message: issue.message,
141
+ isArray
142
+ };
143
+ });
144
+ errors.forEach((error) => {
145
+ setObjectError(output, error.path, [error.message], error.isArray);
146
+ });
147
+ }
148
+ return output;
149
+ }
150
+ async function computeErrors(isValidate = false) {
151
+ let result = computedSchema.value["~standard"].validate(processedState.value);
152
+ if (result instanceof Promise) result = await result;
153
+ if (isSingleField.value) customErrors.value = result.issues?.map((issue) => issue.message) ?? [];
154
+ else customErrors.value = issuesToRegleErrors(result);
155
+ if (!result.issues) {
156
+ if (isValidate && syncOnValidate || !isValidate && syncOnUpdate) {
157
+ unWatchState?.();
158
+ if (isObject(processedState.value)) processedState.value = merge(processedState.value, result.value);
159
+ else processedState.value = result.value;
160
+ defineWatchState();
161
+ }
162
+ }
163
+ return result;
164
+ }
165
+ let unWatchState;
166
+ function defineWatchState() {
167
+ unWatchState = watch([processedState, computedSchema], () => computeErrors(), { deep: true });
168
+ }
169
+ defineWatchState();
170
+ computeErrors();
171
+ onValidate = async () => {
172
+ try {
173
+ const result = await computeErrors(true);
174
+ return {
175
+ valid: !result.issues?.length,
176
+ data: processedState.value
177
+ };
178
+ } catch (e) {
179
+ return Promise.reject(e);
180
+ }
181
+ };
182
+ const regle = useRootStorage({
183
+ scopeRules: computed(() => ({})),
184
+ state: processedState,
185
+ options: resolvedOptions,
186
+ schemaErrors: customErrors,
187
+ initialState,
188
+ shortcuts,
189
+ schemaMode: true,
190
+ onValidate
191
+ });
192
+ return { r$: regle.regle };
193
+ }
194
+ return useRegleSchema$1;
195
+ }
196
+ /**
197
+ * useRegle serves as the foundation for validation logic.
198
+ *
199
+ * It accepts the following inputs:
200
+ *
201
+ * @param state - This can be a plain object, a ref, a reactive object, or a structure containing nested refs.
202
+ * @param schema - These should align with the structure of your state.
203
+ * @param modifiers - customize regle behaviour
204
+ *
205
+ * ```ts
206
+ * import { useRegleSchema } from '@regle/schemas';
207
+ import * as v from 'valibot';
208
+
209
+ const { r$ } = useRegleSchema({ name: '' }, v.object({
210
+ name: v.pipe(v.string(), v.minLength(3))
211
+ }))
212
+ * ```
213
+ * Docs: {@link https://reglejs.dev/integrations/valibot#usage}
214
+ */
215
+ const useRegleSchema = createUseRegleSchemaComposable();
216
+
217
+ //#endregion
218
+ //#region src/core/withDeps.ts
219
+ /**
220
+ *
221
+ * Force dependency on any RPC schema
222
+ * ```ts
223
+ * const foo = ref('');
224
+ *
225
+ * const schema = computed(() => v.object({
226
+ * name: withDeps(
227
+ * v.pipe(v.string(), v.check((value) => value === foo.value)),
228
+ * [foo.value]
229
+ * )
230
+ * }))
231
+ *
232
+ * useRegleSchema({name: ''}, schema)
233
+ * ```
234
+ */
235
+ function withDeps(schema, depsArray) {
236
+ return schema;
237
+ }
238
+
239
+ //#endregion
240
+ //#region src/core/inferSchema.ts
241
+ function createInferSchemaHelper() {
242
+ function inferSchema$1(state, rulesFactory) {
243
+ return rulesFactory;
244
+ }
245
+ return inferSchema$1;
246
+ }
247
+ /**
248
+ * Rule type helper to provide autocomplete and typecheck to your form rules or part of your form rules
249
+ * It will just return the rules without any processing.
250
+ *
251
+ * @param state - The state reference
252
+ * @param schema - Your schema
253
+ */
254
+ const inferSchema = createInferSchemaHelper();
255
+
256
+ //#endregion
257
+ //#region src/core/defineRegleSchemaConfig.ts
258
+ /**
259
+ * Define a global regle configuration, where you can:
260
+ * - Define global modifiers
261
+ * - Define shortcuts
262
+ *
263
+ * It will return:
264
+ *
265
+ * - a `useRegleSchema` composable that can typecheck your custom rules
266
+ * - an `inferSchema` helper that can typecheck your custom rules
267
+ */
268
+ function defineRegleSchemaConfig({ modifiers, shortcuts }) {
269
+ const useRegleSchema$1 = createUseRegleSchemaComposable(modifiers, shortcuts);
270
+ const inferSchema$1 = createInferSchemaHelper();
271
+ return {
272
+ useRegleSchema: useRegleSchema$1,
273
+ inferSchema: inferSchema$1
274
+ };
275
+ }
276
+
277
+ //#endregion
278
+ //#region src/core/createScopedUseRegleSchema.ts
279
+ const { useCollectScope: useCollectSchemaScope, useScopedRegle: useScopedRegleSchema } = createScopedUseRegle({ customUseRegle: useRegleSchema });
280
+ const createScopedUseRegleSchema = (options) => {
281
+ const { customStore, customUseRegle = useRegleSchema, asRecord = false } = options ?? {};
282
+ return createScopedUseRegle({
283
+ customStore,
284
+ customUseRegle,
285
+ asRecord
286
+ });
287
+ };
288
+
289
+ //#endregion
290
+ export { createScopedUseRegleSchema, defineRegleSchemaConfig, inferSchema, useCollectSchemaScope, useRegleSchema, useScopedRegleSchema, withDeps };
@@ -0,0 +1 @@
1
+ import{createScopedUseRegle as e,useRootStorage as t}from"@regle/core";import{computed as n,isRef as r,ref as i,unref as a,watch as o}from"vue";const s=Symbol(`regle-rule`);function c(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 l(e){let t=e,n={}.toString.call(e).slice(8,-1);if(n==`Set`&&(t=new Set([...e].map(e=>l(e)))),n==`Map`&&(t=new Map([...e].map(e=>[l(e[0]),l(e[1])]))),n==`Date`&&(t=new Date(e.getTime())),n==`RegExp`&&(t=RegExp(e.source,c(e))),n==`Array`||n==`Object`)for(let n in t=Array.isArray(e)?[]:{},e)t[n]=l(e[n]);return t}function u(e){return e&&(e instanceof Date||e.constructor.name==`File`||e.constructor.name==`FileList`)?!1:typeof e==`object`&&!!e&&!Array.isArray(e)}function d(e,t,n,r){var i,a;if(Array.isArray(t)&&(i=t.slice(0)),typeof t==`string`&&(i=t.split(`.`)),typeof t==`symbol`&&(i=[t]),!Array.isArray(i))throw Error(`props arg must be an array, a string or a symbol`);if(a=i.pop(),!a)return!1;p(a);for(var o;o=i.shift();)if(p(o),isNaN(parseInt(o))?(e[o]===void 0&&(e[o]={}),e=e[o]):((e.$each??=[])[o]={},e=e.$each[o]),!e||typeof e!=`object`)return!1;return r?e[a]?e[a].$self=(e[a].$self??=[]).concat(n):e[a]={...e[a],$self:n}:Array.isArray(e[a])?e[a]=e[a].concat(n):e[a]=n,!0}function f(e,t,n){if(!e)return n;var r,i;if(Array.isArray(t)&&(r=t.slice(0)),typeof t==`string`&&(r=t.split(`.`)),typeof t==`symbol`&&(r=[t]),!Array.isArray(r))throw Error(`props arg must be an array, a string or a symbol`);for(;r.length;)if(i=r.shift(),!e||!i||(e=e[i],e===void 0))return n;return e}function p(e){if(e==`__proto__`||e==`constructor`||e==`prototype`)throw Error(`setting of prototype values not supported`)}function m(e,...t){for(var n=[].slice.call(arguments),r,i=n.length;r=n[i-1],i--;)if(!r||typeof r!=`object`&&typeof r!=`function`)throw Error(`expected object, got `+r);for(var a=n[0],o=n.slice(1),s=o.length,i=0;i<s;i++){var c=o[i];for(var l in c)a[l]=c[l]}return a}function h(e,s){let c={autoDirty:e?.autoDirty,lazy:e?.lazy,rewardEarly:e?.rewardEarly,clearExternalErrorsOnChange:e?.clearExternalErrorsOnChange};function p(e,p,h){let g=n(()=>a(p)),{syncState:_={onUpdate:!1,onValidate:!1},...v}=h??{},{onUpdate:y=!1,onValidate:b=!1}=_,x={...c,...v},S=n(()=>!u(C.value)),C=r(e)?e:i(e),w=i(u(C.value)?{...l(C.value)}:l(C.value)),T=i({}),E;if(!g.value?.[`~standard`])throw Error(`Only "standard-schema" compatible libraries are supported`);function D(e){let t={};if(e.issues){let n=e.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e.toString()).join(`.`)??``,n=e.path?.[e.path.length-1],r=(typeof n==`object`&&`value`in n?Array.isArray(n.value):!1)||(`type`in e?e.type===`array`:!1)||Array.isArray(f(C.value,t));return{path:t,message:e.message,isArray:r}});n.forEach(e=>{d(t,e.path,[e.message],e.isArray)})}return t}async function O(e=!1){let t=g.value[`~standard`].validate(C.value);return t instanceof Promise&&(t=await t),S.value?T.value=t.issues?.map(e=>e.message)??[]:T.value=D(t),t.issues||(e&&b||!e&&y)&&(k?.(),u(C.value)?C.value=m(C.value,t.value):C.value=t.value,A()),t}let k;function A(){k=o([C,g],()=>O(),{deep:!0})}A(),O(),E=async()=>{try{let e=await O(!0);return{valid:!e.issues?.length,data:C.value}}catch(e){return Promise.reject(e)}};let j=t({scopeRules:n(()=>({})),state:C,options:x,schemaErrors:T,initialState:w,shortcuts:s,schemaMode:!0,onValidate:E});return{r$:j.regle}}return p}const g=h();function _(e,t){return e}function v(){function e(e,t){return t}return e}const y=v();function b({modifiers:e,shortcuts:t}){let n=h(e,t),r=v();return{useRegleSchema:n,inferSchema:r}}const{useCollectScope:x,useScopedRegle:S}=e({customUseRegle:g}),C=t=>{let{customStore:n,customUseRegle:r=g,asRecord:i=!1}=t??{};return e({customStore:n,customUseRegle:r,asRecord:i})};export{C as createScopedUseRegleSchema,b as defineRegleSchemaConfig,y as inferSchema,x as useCollectSchemaScope,g as useRegleSchema,S as useScopedRegleSchema,_ as withDeps};
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@regle/schemas",
3
- "version": "1.2.3",
3
+ "version": "1.3.0-beta.1",
4
4
  "description": "Schemas adapter for Regle",
5
5
  "dependencies": {
6
6
  "@standard-schema/spec": "1.0.0",
7
- "@regle/core": "1.2.3",
8
- "@regle/rules": "1.2.3"
7
+ "@regle/core": "1.3.0-beta.1",
8
+ "@regle/rules": "1.3.0-beta.1"
9
9
  },
10
10
  "peerDependencies": {
11
11
  "valibot": "^1.0.0",
@@ -33,15 +33,15 @@
33
33
  "eslint-config-prettier": "9.1.0",
34
34
  "eslint-plugin-vue": "9.33.0",
35
35
  "prettier": "3.5.3",
36
- "tsup": "8.4.0",
36
+ "tsdown": "0.12.3",
37
37
  "type-fest": "4.40.1",
38
38
  "typescript": "5.8.3",
39
- "valibot": "1.0.0",
39
+ "valibot": "1.1.0",
40
40
  "vitest": "3.1.2",
41
41
  "vue": "3.5.13",
42
42
  "vue-eslint-parser": "10.1.3",
43
43
  "vue-tsc": "2.2.10",
44
- "zod": "3.24.3"
44
+ "zod": "3.25.30"
45
45
  },
46
46
  "type": "module",
47
47
  "exports": {
@@ -49,18 +49,18 @@
49
49
  "types": "./dist/regle-schemas.d.ts",
50
50
  "node": {
51
51
  "import": {
52
- "production": "./dist/regle-schemas.min.mjs",
53
- "development": "./dist/regle-schemas.mjs",
54
- "default": "./dist/regle-schemas.mjs"
52
+ "production": "./dist/regle-schemas.min.js",
53
+ "development": "./dist/regle-schemas.js",
54
+ "default": "./dist/regle-schemas.js"
55
55
  }
56
56
  },
57
- "import": "./dist/regle-schemas.mjs"
57
+ "import": "./dist/regle-schemas.js"
58
58
  },
59
59
  "./package.json": "./package.json",
60
60
  "./dist/*": "./dist/*"
61
61
  },
62
- "main": "./dist/regle-schemas.mjs",
63
- "module": "./dist/regle-schemas.mjs",
62
+ "main": "./dist/regle-schemas.js",
63
+ "module": "./dist/regle-schemas.js",
64
64
  "types": "./dist/regle-schemas.d.ts",
65
65
  "files": [
66
66
  "dist",
@@ -82,10 +82,10 @@
82
82
  "license": "MIT",
83
83
  "scripts": {
84
84
  "typecheck": "tsc --noEmit",
85
- "build": "tsup",
86
- "build:dev": "tsup --config=tsup.dev.ts",
87
- "build:sourcemaps": "tsup --config=tsup.sourcemap.ts",
88
- "dev": "tsup --config=tsup.dev.ts --watch",
85
+ "build": "tsdown",
86
+ "build:dev": "tsdown --config=tsdown.dev.ts",
87
+ "build:sourcemaps": "tsdown --config=tsdown.sourcemap.ts",
88
+ "dev": "tsdown --config=tsdown.dev.ts --watch",
89
89
  "test": "echo 'no tests'"
90
90
  }
91
91
  }
@@ -1 +0,0 @@
1
- import {createScopedUseRegle,useRootStorage}from'@regle/core';import {computed,unref,ref,isRef,watch}from'vue';function J(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 p(e){let t=e,r={}.toString.call(e).slice(8,-1);if(r=="Set"&&(t=new Set([...e].map(n=>p(n)))),r=="Map"&&(t=new Map([...e].map(n=>[p(n[0]),p(n[1])]))),r=="Date"&&(t=new Date(e.getTime())),r=="RegExp"&&(t=RegExp(e.source,J(e))),r=="Array"||r=="Object"){t=Array.isArray(e)?[]:{};for(let n in e)t[n]=p(e[n]);}return t}function m(e){return e&&(e instanceof Date||e.constructor.name=="File"||e.constructor.name=="FileList")?false:typeof e=="object"&&e!==null&&!Array.isArray(e)}function E(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;C(o);for(var s;s=a.shift();)if(C(s),isNaN(parseInt(s))?(typeof e[s]>"u"&&(e[s]={}),e=e[s]):((e.$each??=[])[s]={},e=e.$each[s]),!e||typeof e!="object")return false;return n?e[o]?e[o].$self=(e[o].$self??=[]).concat(r):e[o]={...e[o],$self:r}:Array.isArray(e[o])?e[o]=e[o].concat(r):e[o]=r,true}function U(e,t,r){if(!e)return r;var n,a;if(Array.isArray(t)&&(n=t.slice(0)),typeof t=="string"&&(n=t.split(".")),typeof t=="symbol"&&(n=[t]),!Array.isArray(n))throw new Error("props arg must be an array, a string or a symbol");for(;n.length;)if(a=n.shift(),!e||!a||(e=e[a],e===void 0))return r;return e}function C(e){if(e=="__proto__"||e=="constructor"||e=="prototype")throw new Error("setting of prototype values not supported")}function N(e,...t){for(var r=[].slice.call(arguments),n,a=r.length;n=r[a-1],a--;)if(!n||typeof n!="object"&&typeof n!="function")throw new Error("expected object, got "+n);for(var o=r[0],s=r.slice(1),f=s.length,a=0;a<f;a++){var y=s[a];for(var S in y)o[S]=y[S];}return o}function v(e,t){let r={autoDirty:e?.autoDirty,lazy:e?.lazy,rewardEarly:e?.rewardEarly,clearExternalErrorsOnChange:e?.clearExternalErrorsOnChange};function n(a,o,s){let f=computed(()=>unref(o)),{syncState:y={onUpdate:false,onValidate:false},...S}=s??{},{onUpdate:L=false,onValidate:H=false}=y,z={...r,...S},W=computed(()=>!m(i.value)),i=isRef(a)?a:ref(a),_=ref(m(i.value)?{...p(i.value)}:p(i.value)),h=ref({}),w;if(!f.value?.["~standard"])throw new Error('Only "standard-schema" compatible libraries are supported');function q(u){let c={};return u.issues&&u.issues.map(l=>{let P=l.path?.map(T=>typeof T=="object"?T.key:T.toString()).join(".")??"",R=l.path?.[l.path.length-1],G=(typeof R=="object"&&"value"in R?Array.isArray(R.value):false)||("type"in l?l.type==="array":false)||Array.isArray(U(i.value,P));return {path:P,message:l.message,isArray:G}}).forEach(l=>{E(c,l.path,[l.message],l.isArray);}),c}async function g(u=false){let c=f.value["~standard"].validate(i.value);return c instanceof Promise&&(c=await c),W.value?h.value=c.issues?.map(b=>b.message)??[]:h.value=q(c),c.issues||(u&&H||!u&&L)&&(F?.(),m(i.value)?i.value=N(i.value,c.value):i.value=c.value,A()),c}let F;function A(){F=watch([i,f],()=>g(),{deep:true});}return A(),g(),w=async()=>{try{return {valid:!(await g(!0)).issues?.length,data:i.value}}catch(u){return Promise.reject(u)}},{r$:useRootStorage({scopeRules:computed(()=>({})),state:i,options:z,schemaErrors:h,initialState:_,shortcuts:t,schemaMode:true,onValidate:w}).regle}}return n}var d=v();function I(e,t){return e}function D(){function e(t,r){return r}return e}var M=D();function B({modifiers:e,shortcuts:t}){let r=v(e,t),n=D();return {useRegleSchema:r,inferSchema:n}}var {useCollectScope:k,useScopedRegle:$}=createScopedUseRegle({customUseRegle:d}),j=e=>{let{customStore:t,customUseRegle:r=d,asRecord:n=false}=e??{};return createScopedUseRegle({customStore:t,customUseRegle:r,asRecord:n})};export{j as createScopedUseRegleSchema,B as defineRegleSchemaConfig,M as inferSchema,k as useCollectSchemaScope,d as useRegleSchema,$ as useScopedRegleSchema,I as withDeps};
@@ -1,289 +0,0 @@
1
- import { createScopedUseRegle, useRootStorage } from '@regle/core';
2
- import { computed, unref, ref, isRef, watch } from 'vue';
3
-
4
- // src/core/useRegleSchema.ts
5
-
6
- // ../shared/utils/cloneDeep.ts
7
- function getRegExpFlags(regExp) {
8
- if (typeof regExp.source.flags == "string") {
9
- return regExp.source.flags;
10
- } else {
11
- let flags = [];
12
- regExp.global && flags.push("g");
13
- regExp.ignoreCase && flags.push("i");
14
- regExp.multiline && flags.push("m");
15
- regExp.sticky && flags.push("y");
16
- regExp.unicode && flags.push("u");
17
- return flags.join("");
18
- }
19
- }
20
- function cloneDeep(obj) {
21
- let result = obj;
22
- let type = {}.toString.call(obj).slice(8, -1);
23
- if (type == "Set") {
24
- result = new Set([...obj].map((value) => cloneDeep(value)));
25
- }
26
- if (type == "Map") {
27
- result = new Map([...obj].map((kv) => [cloneDeep(kv[0]), cloneDeep(kv[1])]));
28
- }
29
- if (type == "Date") {
30
- result = new Date(obj.getTime());
31
- }
32
- if (type == "RegExp") {
33
- result = RegExp(obj.source, getRegExpFlags(obj));
34
- }
35
- if (type == "Array" || type == "Object") {
36
- result = Array.isArray(obj) ? [] : {};
37
- for (let key in obj) {
38
- result[key] = cloneDeep(obj[key]);
39
- }
40
- }
41
- return result;
42
- }
43
-
44
- // ../shared/utils/object.utils.ts
45
- function isObject(obj) {
46
- if (obj && (obj instanceof Date || obj.constructor.name == "File" || obj.constructor.name == "FileList")) {
47
- return false;
48
- }
49
- return typeof obj === "object" && obj !== null && !Array.isArray(obj);
50
- }
51
- function setObjectError(obj, propsArg, value, isArray) {
52
- var props, lastProp;
53
- if (Array.isArray(propsArg)) {
54
- props = propsArg.slice(0);
55
- }
56
- if (typeof propsArg == "string") {
57
- props = propsArg.split(".");
58
- }
59
- if (typeof propsArg == "symbol") {
60
- props = [propsArg];
61
- }
62
- if (!Array.isArray(props)) {
63
- throw new Error("props arg must be an array, a string or a symbol");
64
- }
65
- lastProp = props.pop();
66
- if (!lastProp) {
67
- return false;
68
- }
69
- prototypeCheck(lastProp);
70
- var thisProp;
71
- while (thisProp = props.shift()) {
72
- prototypeCheck(thisProp);
73
- if (!isNaN(parseInt(thisProp))) {
74
- (obj.$each ??= [])[thisProp] = {};
75
- obj = obj.$each[thisProp];
76
- } else {
77
- if (typeof obj[thisProp] == "undefined") {
78
- obj[thisProp] = {};
79
- }
80
- obj = obj[thisProp];
81
- }
82
- if (!obj || typeof obj != "object") {
83
- return false;
84
- }
85
- }
86
- if (isArray) {
87
- if (!obj[lastProp]) {
88
- obj[lastProp] = { ...obj[lastProp], $self: value };
89
- } else {
90
- obj[lastProp].$self = (obj[lastProp].$self ??= []).concat(value);
91
- }
92
- } else {
93
- if (Array.isArray(obj[lastProp])) {
94
- obj[lastProp] = obj[lastProp].concat(value);
95
- } else {
96
- obj[lastProp] = value;
97
- }
98
- }
99
- return true;
100
- }
101
- function getDotPath(obj, propsArg, defaultValue) {
102
- if (!obj) {
103
- return defaultValue;
104
- }
105
- var props, prop;
106
- if (Array.isArray(propsArg)) {
107
- props = propsArg.slice(0);
108
- }
109
- if (typeof propsArg == "string") {
110
- props = propsArg.split(".");
111
- }
112
- if (typeof propsArg == "symbol") {
113
- props = [propsArg];
114
- }
115
- if (!Array.isArray(props)) {
116
- throw new Error("props arg must be an array, a string or a symbol");
117
- }
118
- while (props.length) {
119
- prop = props.shift();
120
- if (!obj) {
121
- return defaultValue;
122
- }
123
- if (!prop) {
124
- return defaultValue;
125
- }
126
- obj = obj[prop];
127
- if (obj === void 0) {
128
- return defaultValue;
129
- }
130
- }
131
- return obj;
132
- }
133
- function prototypeCheck(prop) {
134
- if (prop == "__proto__" || prop == "constructor" || prop == "prototype") {
135
- throw new Error("setting of prototype values not supported");
136
- }
137
- }
138
- function merge(obj1, ...objs) {
139
- var args = [].slice.call(arguments);
140
- var arg;
141
- var i = args.length;
142
- while (arg = args[i - 1], i--) {
143
- if (!arg || typeof arg != "object" && typeof arg != "function") {
144
- throw new Error("expected object, got " + arg);
145
- }
146
- }
147
- var result = args[0];
148
- var extenders = args.slice(1);
149
- var len = extenders.length;
150
- for (var i = 0; i < len; i++) {
151
- var extender = extenders[i];
152
- for (var key in extender) {
153
- result[key] = extender[key];
154
- }
155
- }
156
- return result;
157
- }
158
-
159
- // src/core/useRegleSchema.ts
160
- function createUseRegleSchemaComposable(options, shortcuts) {
161
- const globalOptions = {
162
- autoDirty: options?.autoDirty,
163
- lazy: options?.lazy,
164
- rewardEarly: options?.rewardEarly,
165
- clearExternalErrorsOnChange: options?.clearExternalErrorsOnChange
166
- };
167
- function useRegleSchema2(state, schema, options2) {
168
- const computedSchema = computed(() => unref(schema));
169
- const { syncState = { onUpdate: false, onValidate: false }, ...defaultOptions } = options2 ?? {};
170
- const { onUpdate: syncOnUpdate = false, onValidate: syncOnValidate = false } = syncState;
171
- const resolvedOptions = {
172
- ...globalOptions,
173
- ...defaultOptions
174
- };
175
- const isSingleField = computed(() => !isObject(processedState.value));
176
- const processedState = isRef(state) ? state : ref(state);
177
- const initialState = ref(
178
- isObject(processedState.value) ? { ...cloneDeep(processedState.value) } : cloneDeep(processedState.value)
179
- );
180
- const customErrors = ref({});
181
- let onValidate = void 0;
182
- if (!computedSchema.value?.["~standard"]) {
183
- throw new Error(`Only "standard-schema" compatible libraries are supported`);
184
- }
185
- function issuesToRegleErrors(result) {
186
- const output = {};
187
- if (result.issues) {
188
- const errors = result.issues.map((issue) => {
189
- const path = issue.path?.map((item) => typeof item === "object" ? item.key : item.toString()).join(".") ?? "";
190
- const lastItem = issue.path?.[issue.path.length - 1];
191
- const isArray = (typeof lastItem === "object" && "value" in lastItem ? Array.isArray(lastItem.value) : false) || ("type" in issue ? issue.type === "array" : false) || Array.isArray(getDotPath(processedState.value, path));
192
- return {
193
- path,
194
- message: issue.message,
195
- isArray
196
- };
197
- });
198
- errors.forEach((error) => {
199
- setObjectError(output, error.path, [error.message], error.isArray);
200
- });
201
- }
202
- return output;
203
- }
204
- async function computeErrors(isValidate = false) {
205
- let result = computedSchema.value["~standard"].validate(processedState.value);
206
- if (result instanceof Promise) {
207
- result = await result;
208
- }
209
- if (isSingleField.value) {
210
- customErrors.value = result.issues?.map((issue) => issue.message) ?? [];
211
- } else {
212
- customErrors.value = issuesToRegleErrors(result);
213
- }
214
- if (!result.issues) {
215
- if (isValidate && syncOnValidate || !isValidate && syncOnUpdate) {
216
- unWatchState?.();
217
- if (isObject(processedState.value)) {
218
- processedState.value = merge(processedState.value, result.value);
219
- } else {
220
- processedState.value = result.value;
221
- }
222
- defineWatchState();
223
- }
224
- }
225
- return result;
226
- }
227
- let unWatchState;
228
- function defineWatchState() {
229
- unWatchState = watch([processedState, computedSchema], () => computeErrors(), { deep: true });
230
- }
231
- defineWatchState();
232
- computeErrors();
233
- onValidate = async () => {
234
- try {
235
- const result = await computeErrors(true);
236
- return {
237
- valid: !result.issues?.length,
238
- data: processedState.value
239
- };
240
- } catch (e) {
241
- return Promise.reject(e);
242
- }
243
- };
244
- const regle = useRootStorage({
245
- scopeRules: computed(() => ({})),
246
- state: processedState,
247
- options: resolvedOptions,
248
- schemaErrors: customErrors,
249
- initialState,
250
- shortcuts,
251
- schemaMode: true,
252
- onValidate
253
- });
254
- return {
255
- r$: regle.regle
256
- };
257
- }
258
- return useRegleSchema2;
259
- }
260
- var useRegleSchema = createUseRegleSchemaComposable();
261
- function withDeps(schema, depsArray) {
262
- return schema;
263
- }
264
- function createInferSchemaHelper() {
265
- function inferSchema2(state, rulesFactory) {
266
- return rulesFactory;
267
- }
268
- return inferSchema2;
269
- }
270
- var inferSchema = createInferSchemaHelper();
271
-
272
- // src/core/defineRegleSchemaConfig.ts
273
- function defineRegleSchemaConfig({
274
- modifiers,
275
- shortcuts
276
- }) {
277
- const useRegleSchema2 = createUseRegleSchemaComposable(modifiers, shortcuts);
278
- const inferSchema2 = createInferSchemaHelper();
279
- return { useRegleSchema: useRegleSchema2, inferSchema: inferSchema2 };
280
- }
281
- var { useCollectScope: useCollectSchemaScope, useScopedRegle: useScopedRegleSchema } = createScopedUseRegle({
282
- customUseRegle: useRegleSchema
283
- });
284
- var createScopedUseRegleSchema = (options) => {
285
- const { customStore, customUseRegle = useRegleSchema, asRecord = false } = options ?? {};
286
- return createScopedUseRegle({ customStore, customUseRegle, asRecord });
287
- };
288
-
289
- export { createScopedUseRegleSchema, defineRegleSchemaConfig, inferSchema, useCollectSchemaScope, useRegleSchema, useScopedRegleSchema, withDeps };