@regle/schemas 1.3.1 → 1.4.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.
@@ -1919,7 +1919,7 @@ type DefaultValidators = {
1919
1919
  numeric: RegleRuleDefinition<string | number, [], false, boolean, string | number>;
1920
1920
  oneOf: RegleRuleDefinition<string | number, [options: (string | number)[]], false, boolean, string | number>;
1921
1921
  regex: RegleRuleWithParamsDefinition<string, [regexp: RegExp], false, boolean>;
1922
- required: RegleRuleDefinition<unknown, []>;
1922
+ required: RegleRuleDefinition<unknown, [], false, boolean, unknown>;
1923
1923
  sameAs: RegleRuleWithParamsDefinition<unknown, [target: unknown, otherName?: string], false, boolean>;
1924
1924
  string: RegleRuleDefinition<unknown, [], false, boolean, any, unknown>;
1925
1925
  type: RegleRuleDefinition<unknown, [], false, boolean, unknown, unknown>;
@@ -2000,21 +2000,6 @@ type InlineRuleDeclaration<TValue extends any = any, TParams extends any[] = any
2000
2000
  * Regroup inline and registered rules
2001
2001
  * */
2002
2002
  type FormRuleDeclaration<TValue extends any = unknown, TParams extends any[] = any[], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition> = RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition>, TMetadata extends RegleRuleMetadataDefinition = (TReturn extends Promise<infer M> ? M : TReturn), TAsync extends boolean = boolean> = InlineRuleDeclaration<TValue, TParams, TReturn> | RegleRuleDefinition<TValue, TParams, TAsync, TMetadata> | RegleRuleWithParamsDefinitionInput<TValue, [param?: any], TAsync, TMetadata> | RegleRuleWithParamsDefinitionInput<TValue, [param?: any, ...any[]], TAsync, TMetadata>;
2003
- //#endregion
2004
- //#region src/types/rules/rule.errors.types.d.ts
2005
- type RegleErrorTree<TState = MaybeRef<Record<string, any> | any[]>> = { readonly [K in keyof JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>]: RegleValidationErrors<JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>[K], false> };
2006
- type RegleExternalErrorTree<TState = MaybeRef<Record<string, any> | any[]>> = { readonly [K in keyof JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>]?: RegleValidationErrors<JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>[K], true> };
2007
- type RegleValidationErrors<TState extends Record<string, any> | any[] | unknown = never, TExternal extends boolean = false> = NonNullable<TState> extends Array<infer U extends Record<string, any>> ? ExtendOnlyRealRecord<U> extends true ? TExternal extends false ? RegleCollectionErrors<U> : RegleExternalCollectionErrors<U> : string[] : NonNullable<TState> extends Date | File ? string[] : NonNullable<TState> extends Record<string, any> ? TExternal extends false ? RegleErrorTree<TState> : RegleExternalErrorTree<TState> : string[];
2008
- type RegleCollectionErrors<TState extends Record<string, any>> = {
2009
- readonly $self: string[];
2010
- readonly $each: RegleValidationErrors<TState, false>[];
2011
- };
2012
- type RegleExternalCollectionErrors<TState extends Record<string, any>> = {
2013
- readonly $self?: string[];
2014
- readonly $each?: RegleValidationErrors<TState, true>[];
2015
- };
2016
- /** @internal */
2017
-
2018
2003
  //#endregion
2019
2004
  //#region src/types/rules/rule.status.types.d.ts
2020
2005
  /**
@@ -2058,6 +2043,13 @@ type InferRegleStatusType<TRule extends RegleCollectionRuleDecl | RegleRuleDecl
2058
2043
  * @reference {@link InferRegleStatusType}
2059
2044
  */
2060
2045
 
2046
+ interface RegleFieldIssue {
2047
+ $property: string;
2048
+ $rule: string;
2049
+ $type?: string;
2050
+ $message: string;
2051
+ [x: string]: unknown;
2052
+ }
2061
2053
  /**
2062
2054
  * @public
2063
2055
  */
@@ -2072,6 +2064,10 @@ type RegleFieldStatus<TState extends any = any, TRules extends RegleFormProperty
2072
2064
  readonly $errors: string[];
2073
2065
  /** Collection of all the error messages, collected for all children properties and nested forms. */
2074
2066
  readonly $silentErrors: string[];
2067
+ /**
2068
+ * Collect all metadata of validators, including the error message
2069
+ */
2070
+ readonly $issues: RegleFieldIssue[];
2075
2071
  /** Stores external errors of the current field */
2076
2072
  readonly $externalErrors: string[];
2077
2073
  /** Stores active tooltips messages of the current field */
@@ -2085,7 +2081,7 @@ type RegleFieldStatus<TState extends any = any, TRules extends RegleFormProperty
2085
2081
  /** This is reactive tree containing all the declared rules of your field. To know more about the rule properties check the rules properties section */
2086
2082
  readonly $rules: IsEmptyObject$1<TRules> extends true ? {
2087
2083
  readonly [x: string]: RegleRuleStatus<TState, any[], any>;
2088
- } : { readonly [TRuleKey in keyof Omit<TRules, '$each' | keyof FieldRegleBehaviourOptions>]: RegleRuleStatus<TState, TRules[TRuleKey] extends RegleRuleDefinition<any, infer TParams, any> ? TParams : [], TRules[TRuleKey] extends RegleRuleDefinition<any, any, any, infer TMetadata> ? TMetadata : TRules[TRuleKey] extends InlineRuleDeclaration<any, any[], infer TMetadata> ? TMetadata extends Promise<infer P> ? P : TMetadata : any> };
2084
+ } : { readonly [TRuleKey in keyof Omit<TRules, '$each' | keyof FieldRegleBehaviourOptions>]: RegleRuleStatus<TState, TRules[TRuleKey] extends RegleRuleDefinition<any, infer TParams, any> ? TParams : [], TRules[TRuleKey] extends RegleRuleDefinition<any, any, any, infer TMetadata> ? TMetadata : TRules[TRuleKey] extends InlineRuleDeclaration<any, any[], infer TMetadata> ? TMetadata extends Promise<infer P> ? P : TMetadata : boolean> };
2089
2085
  } & ([TShortcuts['fields']] extends [never] ? {} : { [K in keyof TShortcuts['fields']]: ReturnType<NonNullable<TShortcuts['fields']>[K]> });
2090
2086
  /**
2091
2087
  * @internal
@@ -2180,7 +2176,7 @@ type RegleRuleStatus<TValue = any, TParams extends any[] = any[], TMetadata exte
2180
2176
  * @reference {@link RegleRuleStatus}
2181
2177
  */
2182
2178
  interface $InternalRegleRuleStatus {
2183
- $type: string;
2179
+ $type?: string;
2184
2180
  $message: string | string[];
2185
2181
  $tooltip: string | string[];
2186
2182
  $active: boolean;
@@ -2232,6 +2228,21 @@ type RegleCollectionStatus<TState extends any[] = any[], TRules extends ReglePar
2232
2228
  * @reference {@link RegleCollectionStatus}
2233
2229
  */
2234
2230
 
2231
+ //#endregion
2232
+ //#region src/types/rules/rule.errors.types.d.ts
2233
+ type RegleErrorTree<TState = MaybeRef<Record<string, any> | any[]>> = { readonly [K in keyof JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>]: RegleValidationErrors<JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>[K], false> };
2234
+ type RegleExternalErrorTree<TState = MaybeRef<Record<string, any> | any[]>> = { readonly [K in keyof JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>]?: RegleValidationErrors<JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>[K], true> };
2235
+ type RegleValidationErrors<TState extends Record<string, any> | any[] | unknown = never, TExternal extends boolean = false, TIssue extends boolean = false> = NonNullable<TState> extends Array<infer U extends Record<string, any>> ? ExtendOnlyRealRecord<U> extends true ? TExternal extends false ? RegleCollectionErrors<U> : RegleExternalCollectionErrors<U> : TIssue extends true ? RegleFieldIssue[] : string[] : NonNullable<TState> extends Date | File ? TIssue extends true ? RegleFieldIssue[] : string[] : NonNullable<TState> extends Record<string, any> ? TExternal extends false ? RegleErrorTree<TState> : RegleExternalErrorTree<TState> : TIssue extends true ? RegleFieldIssue[] : string[];
2236
+ type RegleCollectionErrors<TState extends Record<string, any>, TIssue extends boolean = false> = {
2237
+ readonly $self: string[];
2238
+ readonly $each: RegleValidationErrors<TState, false, TIssue>[];
2239
+ };
2240
+ type RegleExternalCollectionErrors<TState extends Record<string, any>, TIssue extends boolean = false> = {
2241
+ readonly $self?: string[];
2242
+ readonly $each?: RegleValidationErrors<TState, true, TIssue>[];
2243
+ };
2244
+ /** @internal */
2245
+
2235
2246
  /** Supports both core Regle and schemas Regle for Zod/Valibot */
2236
2247
  type SuperCompatibleRegleRoot = SuperCompatibleRegleStatus & {
2237
2248
  $groups?: {
@@ -131,20 +131,23 @@ function createUseRegleSchemaComposable(options, shortcuts) {
131
131
  function issuesToRegleErrors(result) {
132
132
  const output = {};
133
133
  if (result.issues) {
134
- const errors = result.issues.map((issue) => {
134
+ const issues = result.issues.map((issue) => {
135
135
  let path = issue.path?.map((item) => typeof item === "object" ? item.key : item.toString()).join(".") ?? "";
136
136
  const lastItem = issue.path?.[issue.path.length - 1];
137
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
138
  const isPrimitivesArray = !isArray && typeof (typeof lastItem === "object" ? lastItem.key : lastItem) === "number";
139
139
  if (isPrimitivesArray) path = issue.path?.slice(0, issue.path.length - 1)?.map((item) => typeof item === "object" ? item.key : item.toString()).join(".") ?? "";
140
140
  return {
141
+ ...issue,
141
142
  path,
142
- message: issue.message,
143
- isArray
143
+ isArray,
144
+ $property: lastItem,
145
+ $rule: "schema",
146
+ $message: issue.message
144
147
  };
145
148
  });
146
- errors.forEach((error) => {
147
- setObjectError(output, error.path, [error.message], error.isArray);
149
+ issues.forEach(({ isArray, path,...issue }) => {
150
+ setObjectError(output, path, [issue], isArray);
148
151
  });
149
152
  }
150
153
  return output;
@@ -152,7 +155,12 @@ function createUseRegleSchemaComposable(options, shortcuts) {
152
155
  async function computeErrors(isValidate = false) {
153
156
  let result = computedSchema.value["~standard"].validate(processedState.value);
154
157
  if (result instanceof Promise) result = await result;
155
- if (isSingleField.value) customErrors.value = result.issues?.map((issue) => issue.message) ?? [];
158
+ if (isSingleField.value) customErrors.value = result.issues?.map((issue) => ({
159
+ $message: issue.message,
160
+ $property: issue.path?.[issue.path.length - 1]?.toString() ?? "-",
161
+ $rule: "schema",
162
+ ...issue
163
+ })) ?? [];
156
164
  else customErrors.value = issuesToRegleErrors(result);
157
165
  if (!result.issues) {
158
166
  if (isValidate && syncOnValidate || !isValidate && syncOnUpdate) {
@@ -1 +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)),i=!r&&typeof(typeof n==`object`?n.key:n)==`number`;return i&&(t=e.path?.slice(0,e.path.length-1)?.map(e=>typeof e==`object`?e.key:e.toString()).join(`.`)??``),{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};
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)),i=!r&&typeof(typeof n==`object`?n.key:n)==`number`;return i&&(t=e.path?.slice(0,e.path.length-1)?.map(e=>typeof e==`object`?e.key:e.toString()).join(`.`)??``),{...e,path:t,isArray:r,$property:n,$rule:`schema`,$message:e.message}});n.forEach(({isArray:e,path:n,...r})=>{d(t,n,[r],e)})}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=>({$message:e.message,$property:e.path?.[e.path.length-1]?.toString()??`-`,$rule:`schema`,...e}))??[]: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.3.1",
3
+ "version": "1.4.0-beta.1",
4
4
  "description": "Schemas adapter for Regle",
5
5
  "dependencies": {
6
6
  "@standard-schema/spec": "1.0.0",
7
- "@regle/rules": "1.3.1",
8
- "@regle/core": "1.3.1"
7
+ "@regle/core": "1.4.0-beta.1",
8
+ "@regle/rules": "1.4.0-beta.1"
9
9
  },
10
10
  "peerDependencies": {
11
11
  "valibot": "^1.0.0",