@stacksjs/validation 0.75.443 → 0.75.447
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/README.md +13 -0
- package/dist/conditional.d.ts +3 -3
- package/dist/input.js +1 -1
- package/dist/validator.js +1 -1
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -128,3 +128,16 @@ Timestamp strings validate their written calendar before parsing. SQL timestamps
|
|
|
128
128
|
offsets, minute precision, expanded years and the exact 24:00 midnight notation remain
|
|
129
129
|
supported. File byte limits require nonnegative safe integers; invalid configuration
|
|
130
130
|
throws immediately.
|
|
131
|
+
|
|
132
|
+
## Conditional and input contracts
|
|
133
|
+
|
|
134
|
+
Actions, model writes and partial model input validation apply conditional rules
|
|
135
|
+
against supplied siblings before evaluating a field. Model contexts recognize both
|
|
136
|
+
attribute and column aliases; creates also include declared defaults. Partial updates
|
|
137
|
+
check supplied fields without fetching stored siblings. Conditions and custom messages
|
|
138
|
+
use the effective rule while leaving the declared schema reusable.
|
|
139
|
+
|
|
140
|
+
Numeric input rejects unsafe whole numbers even when fractions are allowed. Infinite
|
|
141
|
+
range endpoints explicitly mean unbounded; NaN, inverted ranges and ranges containing
|
|
142
|
+
no finite numbers are configuration errors. Text limits require nonnegative safe
|
|
143
|
+
integers. Configuration errors throw RangeError even for absent optional values.
|
package/dist/conditional.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export declare function withConditionals<V extends Validator<any>>(validator: V)
|
|
|
21
21
|
* should be applied). Pure function — no side effects, safe to call
|
|
22
22
|
* during introspection too.
|
|
23
23
|
*/
|
|
24
|
-
export declare function shouldApplyConditional(record: ConditionalRecord<
|
|
24
|
+
export declare function shouldApplyConditional<V>(record: ConditionalRecord<V>, parent: Record<string, unknown> | null | undefined): boolean;
|
|
25
25
|
/**
|
|
26
26
|
* Apply every matching conditional on `base` against `parent`, in
|
|
27
27
|
* registration order. Returns the (possibly refined) validator that
|
|
@@ -35,13 +35,13 @@ export declare function shouldApplyConditional(record: ConditionalRecord<Validat
|
|
|
35
35
|
* {@link cloneValidator} produces an isolated instance the refine
|
|
36
36
|
* pipeline can safely mutate without polluting the schema definition.
|
|
37
37
|
*/
|
|
38
|
-
export declare function applyConditionals<V extends
|
|
38
|
+
export declare function applyConditionals<V extends object>(base: V, parent: Record<string, unknown> | null | undefined): V;
|
|
39
39
|
/**
|
|
40
40
|
* A single `.when()` clause attached to a field validator. Multiple
|
|
41
41
|
* `.when()` calls stack — they're evaluated in registration order and
|
|
42
42
|
* each matching one further refines the base validator.
|
|
43
43
|
*/
|
|
44
|
-
export declare interface ConditionalRecord<V
|
|
44
|
+
export declare interface ConditionalRecord<V> {
|
|
45
45
|
field: string
|
|
46
46
|
match: unknown | ((value: unknown) => boolean)
|
|
47
47
|
refine: (validator: V) => V
|
package/dist/input.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class InputValidationError extends Error{status=422}export async function readJsonObject(request){let body;try{body=await request.json()}catch{throw new InputValidationError("Send a valid JSON object")}if(!body||typeof body!=="object"||Array.isArray(body))throw new InputValidationError("Send a JSON object");return body}export function parsePositiveId(value){if(typeof value!=="string"&&typeof value!=="number")throw new InputValidationError("Invalid identifier");if(typeof value==="string"&&!/^\d+$/.test(value.trim()))throw new InputValidationError("Invalid identifier");const id=Number(value);if(!Number.isSafeInteger(id)||id<=0)throw new InputValidationError("Invalid identifier");return id}export function parseTextInput(value,field,required=!1,maxLength){if(value==null&&!required)return null;if(typeof value!=="string")throw new InputValidationError(`${field} must be text`);const text=value.trim();if(maxLength!==void 0&&[...text].length>maxLength)throw new InputValidationError(`${field} is too long`);if(!text&&required)throw new InputValidationError(`${field} is required`);return text||null}export function parseNumberInput(value,field,min,max,integer=!1){if(value==null||value==="")return null;if(typeof value!=="number"&&typeof value!=="string"||typeof value==="string"&&!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(value.trim()))throw new InputValidationError(`${field} must be a number`);const number=Number(value);if(!Number.isFinite(number)||number<min||number>max||
|
|
1
|
+
import{applyConditionals}from"./conditional";export class InputValidationError extends Error{status=422}export async function readJsonObject(request){let body;try{body=await request.json()}catch{throw new InputValidationError("Send a valid JSON object")}if(!body||typeof body!=="object"||Array.isArray(body))throw new InputValidationError("Send a JSON object");return body}export function parsePositiveId(value){if(typeof value!=="string"&&typeof value!=="number")throw new InputValidationError("Invalid identifier");if(typeof value==="string"&&!/^\d+$/.test(value.trim()))throw new InputValidationError("Invalid identifier");const id=Number(value);if(!Number.isSafeInteger(id)||id<=0)throw new InputValidationError("Invalid identifier");return id}export function parseTextInput(value,field,required=!1,maxLength){if(maxLength!==void 0&&(!Number.isSafeInteger(maxLength)||maxLength<0))throw RangeError("Text length must be a non-negative safe integer");if(value==null&&!required)return null;if(typeof value!=="string")throw new InputValidationError(`${field} must be text`);const text=value.trim();if(maxLength!==void 0&&[...text].length>maxLength)throw new InputValidationError(`${field} is too long`);if(!text&&required)throw new InputValidationError(`${field} is required`);return text||null}export function parseNumberInput(value,field,min,max,integer=!1){if(typeof min!=="number"||typeof max!=="number"||Number.isNaN(min)||Number.isNaN(max)||min>max||min===1/0||max===-1/0)throw RangeError("Invalid numeric bounds");if(value==null||value==="")return null;if(typeof value!=="number"&&typeof value!=="string"||typeof value==="string"&&!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(value.trim()))throw new InputValidationError(`${field} must be a number`);const number=Number(value);if(!Number.isFinite(number)||number<min||number>max||Number.isInteger(number)&&!Number.isSafeInteger(number)||integer&&!Number.isInteger(number))throw new InputValidationError(`${field} is out of range`);return number}export function parseBooleanInput(value,field){if(value===void 0)return;if(value===!0||value==="true"||value===1||value==="1"||value==="on")return!0;if(value===!1||value==="false"||value===0||value==="0"||value==="off")return!1;throw new InputValidationError(`${field} must be a boolean`)}export function validateModelInput(model,values){const attributes=model.getDefinition().attributes??{},context=Object.assign(Object.create(null),values);for(const field of Object.keys(attributes)){const column=field.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase();if(Object.hasOwn(values,field)||Object.hasOwn(values,column))context[field]=context[column]=Object.hasOwn(values,field)?values[field]:values[column]}for(const[field,value]of Object.entries(values)){const attribute=Object.prototype.hasOwnProperty.call(attributes,field)?field:Object.keys(attributes).find((key)=>key===field||key.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()===field),rule=attribute?attributes[attribute]?.validation?.rule:void 0;if(rule&&!applyConditionals(rule,context).validate(value).valid)throw new InputValidationError(`Invalid ${field.replaceAll("_"," ")}`)}}export function isEnumInput(value,choices){return typeof value==="string"&&choices.includes(value)}export function parseEnumInput(value,field,choices){if(!isEnumInput(value,choices))throw new InputValidationError(`${field} must be ${choices.join(", ")}`);return value}export function parseEnumListInput(value,field,choices,minItems=1,maxItems=100){if(!Number.isSafeInteger(minItems)||!Number.isSafeInteger(maxItems)||minItems<0||maxItems<minItems)throw RangeError("Invalid enum list bounds");if(!Array.isArray(value)||value.length<minItems||value.length>maxItems)throw new InputValidationError(`${field} must contain ${minItems} to ${maxItems} entries`);const unique=[...new Set(Array.from(value,(item)=>parseEnumInput(item,field,choices)))];if(unique.length<minItems)throw new InputValidationError(`${field} must contain at least ${minItems} distinct entries`);return unique}export function parseObjectInput(value,field){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw new InputValidationError(`${field} must be a JSON object`);return value}export function parseArrayInput(value,field,minItems=0,maxItems=100){if(!Number.isSafeInteger(minItems)||!Number.isSafeInteger(maxItems)||minItems<0||maxItems<minItems)throw RangeError("Invalid array bounds");if(!Array.isArray(value)||value.length<minItems||value.length>maxItems)throw new InputValidationError(`${field} must contain ${minItems} to ${maxItems} entries`);return value}export function parsePositiveIdListInput(value,field,minItems=1,maxItems=100){const items=parseArrayInput(value,field,minItems,maxItems);let ids;try{ids=Array.from(items,parsePositiveId)}catch(error){if(error instanceof InputValidationError)throw new InputValidationError(`${field} contains an invalid identifier`);throw error}const unique=[...new Set(ids)];if(unique.length<minItems)throw new InputValidationError(`${field} must contain at least ${minItems} distinct entries`);return unique}export function storedBoolean(value,fallback){if(value==null)return fallback;try{return parseBooleanInput(value,"Stored value")??fallback}catch(error){if(error instanceof InputValidationError)return fallback;throw error}}export function positiveIdOrNull(value){try{return parsePositiveId(value)}catch(error){if(error instanceof InputValidationError)return null;throw error}}
|
package/dist/validator.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename,relative}from"node:path";import{existsSync}from"node:fs";import{HttpError}from"@stacksjs/error-handling/http-error";import{path}from"@stacksjs/path";import{snakeCase}from"@stacksjs/strings/case";import{getErrorMessage}from"@stacksjs/utils/errors";import{applyFieldMessages}from"./messages";import{beginValidation,reportError}from"./reporter";import{schema}from"./schema";export{validate}from"./request-validator";function globSync(patterns,options={}){const results=[];for(const pattern of patterns){const slash=pattern.startsWith("/")?pattern.lastIndexOf("/"):-1,wildcardAt=pattern.indexOf("*"),splitAt=wildcardAt===-1?slash:pattern.lastIndexOf("/",wildcardAt),cwd=splitAt>0?pattern.slice(0,splitAt):".",rel=splitAt>0?pattern.slice(splitAt+1):pattern;if(!existsSync(cwd))continue;const glob=new Bun.Glob(rel);for(const match of glob.scanSync({cwd,onlyFiles:!0}))results.push(options.absolute?`${cwd}/${match}`:match)}return results}export function isObjectNotEmpty(obj){if(obj===void 0)return!1;return Object.keys(obj).length>0}function toMessageObjects(errors,params){const valueFor=(field)=>{const value=params[field];return value===void 0||value===null?"":String(value)};if(Array.isArray(errors))return errors.map((error)=>({message:error.message,value:"",field:""}));return Object.entries(errors).flatMap(([field,fieldErrors])=>fieldErrors.map((error)=>({message:error.message,value:valueFor(field),field})))}export async function validateField(modelFile,params){beginValidation();const name=modelFile.replace(/\\/g,"/").replace(/\.ts$/,"");if(!name||name.startsWith("/")||name.split("/").some((segment)=>!segment||segment==="."||segment===".."))throw new HttpError(404,"Model not found");const files=new Map;for(const root of[path.userModelsPath(),path.defaultsPath("app/Models")])for(const file of globSync([`${root}/**/*.ts`],{absolute:!0})){const key=relative(root,file).replace(/\\/g,"/");if(!files.has(key))files.set(key,file)}const exact=files.get(`${name}.ts`),matches=exact?[exact]:name.includes("/")?[]:[...files.values()].filter((file)=>basename(file)===`${name}.ts`);if(matches.length>1)throw new HttpError(500,`Model ${name} is ambiguous; use its qualified path`);const modelPath=matches[0];if(!modelPath)throw new HttpError(404,`Model ${name} not found`);const attributes=(await import(modelPath)).default.attributes,input=Object.assign(Object.create(null),params),ruleObject=Object.create(null),messages=Object.create(null);for(const key in attributes)if(Object.prototype.hasOwnProperty.call(attributes,key)){const attributeKey=attributes[key];if(!attributeKey)continue;const isRequired="isRequired"in(attributeKey.validation?.rule??{})?(attributeKey.validation?.rule).isRequired:!1,field=snakeCase(key);if(Object.hasOwn(params,key))input[field]=params[key];if(attributeKey.default!==void 0&&isRequired===!1&&!Object.hasOwn(input,field))continue;ruleObject[snakeCase(key)]=attributeKey.validation?.rule;const validatorMessages=attributeKey.validation?.message;if(validatorMessages)messages[snakeCase(key)]=validatorMessages}try{const result=await schema.object(ruleObject).validate(input);applyMessages(result,ruleObject,messages,input);if(!result.valid){reportError(toMessageObjects(result.errors,input));throw new HttpError(422,"Validation failed",{errors:result.errors})}return result}catch(error){if(isHttpErrorLike(error))throw error;throw new HttpError(500,getErrorMessage(error)||"An unexpected validation error occurred")}}const customRuleRegistry=new Map;export function registerRule(name,rule){customRuleRegistry.set(name,rule)}export function getCustomRule(name){return customRuleRegistry.get(name)}export function unique(table,column,exceptId){return async(value)=>{const{db}=await import("@stacksjs/database/runtime");let query=db.selectFrom(table).where(column,"=",value);if(exceptId!==void 0)query=query.where("id","!=",exceptId);return await query.selectAll().executeTakeFirst()?`The ${column} has already been taken`:!0}}export function exists(table,column){return async(value)=>{const{db}=await import("@stacksjs/database/runtime");return await db.selectFrom(table).where(column,"=",value).selectAll().executeTakeFirst()?!0:`The selected ${column} does not exist`}}export async function validateFieldAsync(modelFile,params,asyncRules){const syncResult=await validateField(modelFile,params);if(asyncRules&&Object.keys(asyncRules).length>0){const asyncErrors=Object.create(null);await Promise.all(Object.entries(asyncRules).map(async([field,validator])=>{const result=await validator(params[field],params);if(result!==!0)asyncErrors[field]=typeof result==="string"?result:`${field} validation failed`}));if(Object.keys(asyncErrors).length>0){reportError(Object.entries(asyncErrors).map(([field,message])=>({field,message,value:String(params[field]??"")})));throw new HttpError(422,"Validation failed",{errors:asyncErrors})}}return syncResult}export async function customValidate(attributes,params){beginValidation();const ruleObject=Object.create(null),messages=Object.create(null);for(const key in attributes)if(Object.prototype.hasOwnProperty.call(attributes,key)){const rule=attributes[key]?.rule;if(rule)ruleObject[key]=rule;const validatorMessages=attributes[key]?.message;if(validatorMessages)messages[key]=validatorMessages}try{const result=await schema.object().shape(ruleObject).validate(params);applyMessages(result,ruleObject,messages,params);if(!result.valid)throw new HttpError(422,"Validation failed",{errors:result.errors});return result}catch(error){if(isHttpErrorLike(error))throw error;throw new HttpError(500,getErrorMessage(error)||"An unexpected validation error occurred")}}function applyMessages(result,rules,messages,params){if(result.valid||!result.errors||Array.isArray(result.errors))return;applyFieldMessages(result.errors,rules,messages,params)}function isHttpErrorLike(error){return error instanceof HttpError||error instanceof Error&&typeof error.status==="number"}
|
|
1
|
+
import{basename,relative}from"node:path";import{existsSync}from"node:fs";import{HttpError}from"@stacksjs/error-handling/http-error";import{path}from"@stacksjs/path";import{snakeCase}from"@stacksjs/strings/case";import{getErrorMessage}from"@stacksjs/utils/errors";import{applyFieldMessages}from"./messages";import{beginValidation,reportError}from"./reporter";import{schema}from"./schema";export{validate}from"./request-validator";function globSync(patterns,options={}){const results=[];for(const pattern of patterns){const slash=pattern.startsWith("/")?pattern.lastIndexOf("/"):-1,wildcardAt=pattern.indexOf("*"),splitAt=wildcardAt===-1?slash:pattern.lastIndexOf("/",wildcardAt),cwd=splitAt>0?pattern.slice(0,splitAt):".",rel=splitAt>0?pattern.slice(splitAt+1):pattern;if(!existsSync(cwd))continue;const glob=new Bun.Glob(rel);for(const match of glob.scanSync({cwd,onlyFiles:!0}))results.push(options.absolute?`${cwd}/${match}`:match)}return results}export function isObjectNotEmpty(obj){if(obj===void 0)return!1;return Object.keys(obj).length>0}function toMessageObjects(errors,params){const valueFor=(field)=>{const value=params[field];return value===void 0||value===null?"":String(value)};if(Array.isArray(errors))return errors.map((error)=>({message:error.message,value:"",field:""}));return Object.entries(errors).flatMap(([field,fieldErrors])=>fieldErrors.map((error)=>({message:error.message,value:valueFor(field),field})))}export async function validateField(modelFile,params){beginValidation();const name=modelFile.replace(/\\/g,"/").replace(/\.ts$/,"");if(!name||name.startsWith("/")||name.split("/").some((segment)=>!segment||segment==="."||segment===".."))throw new HttpError(404,"Model not found");const files=new Map;for(const root of[path.userModelsPath(),path.defaultsPath("app/Models")])for(const file of globSync([`${root}/**/*.ts`],{absolute:!0})){const key=relative(root,file).replace(/\\/g,"/");if(!files.has(key))files.set(key,file)}const exact=files.get(`${name}.ts`),matches=exact?[exact]:name.includes("/")?[]:[...files.values()].filter((file)=>basename(file)===`${name}.ts`);if(matches.length>1)throw new HttpError(500,`Model ${name} is ambiguous; use its qualified path`);const modelPath=matches[0];if(!modelPath)throw new HttpError(404,`Model ${name} not found`);const attributes=(await import(modelPath)).default.attributes,input=Object.assign(Object.create(null),params),ruleObject=Object.create(null),messages=Object.create(null);for(const key in attributes)if(Object.prototype.hasOwnProperty.call(attributes,key)){const attributeKey=attributes[key];if(!attributeKey)continue;const isRequired="isRequired"in(attributeKey.validation?.rule??{})?(attributeKey.validation?.rule).isRequired:!1,field=snakeCase(key);if(Object.hasOwn(params,key))input[field]=params[key];if(Object.hasOwn(input,field))input[key]=input[field];if(attributeKey.default!==void 0&&isRequired===!1&&!Object.hasOwn(input,field))continue;ruleObject[snakeCase(key)]=attributeKey.validation?.rule;const validatorMessages=attributeKey.validation?.message;if(validatorMessages)messages[snakeCase(key)]=validatorMessages}try{const result=await schema.object(ruleObject).validate(input);applyMessages(result,ruleObject,messages,input);if(!result.valid){reportError(toMessageObjects(result.errors,input));throw new HttpError(422,"Validation failed",{errors:result.errors})}return result}catch(error){if(isHttpErrorLike(error))throw error;throw new HttpError(500,getErrorMessage(error)||"An unexpected validation error occurred")}}const customRuleRegistry=new Map;export function registerRule(name,rule){customRuleRegistry.set(name,rule)}export function getCustomRule(name){return customRuleRegistry.get(name)}export function unique(table,column,exceptId){return async(value)=>{const{db}=await import("@stacksjs/database/runtime");let query=db.selectFrom(table).where(column,"=",value);if(exceptId!==void 0)query=query.where("id","!=",exceptId);return await query.selectAll().executeTakeFirst()?`The ${column} has already been taken`:!0}}export function exists(table,column){return async(value)=>{const{db}=await import("@stacksjs/database/runtime");return await db.selectFrom(table).where(column,"=",value).selectAll().executeTakeFirst()?!0:`The selected ${column} does not exist`}}export async function validateFieldAsync(modelFile,params,asyncRules){const syncResult=await validateField(modelFile,params);if(asyncRules&&Object.keys(asyncRules).length>0){const asyncErrors=Object.create(null);await Promise.all(Object.entries(asyncRules).map(async([field,validator])=>{const result=await validator(params[field],params);if(result!==!0)asyncErrors[field]=typeof result==="string"?result:`${field} validation failed`}));if(Object.keys(asyncErrors).length>0){reportError(Object.entries(asyncErrors).map(([field,message])=>({field,message,value:String(params[field]??"")})));throw new HttpError(422,"Validation failed",{errors:asyncErrors})}}return syncResult}export async function customValidate(attributes,params){beginValidation();const ruleObject=Object.create(null),messages=Object.create(null);for(const key in attributes)if(Object.prototype.hasOwnProperty.call(attributes,key)){const rule=attributes[key]?.rule;if(rule)ruleObject[key]=rule;const validatorMessages=attributes[key]?.message;if(validatorMessages)messages[key]=validatorMessages}try{const result=await schema.object().shape(ruleObject).validate(params);applyMessages(result,ruleObject,messages,params);if(!result.valid)throw new HttpError(422,"Validation failed",{errors:result.errors});return result}catch(error){if(isHttpErrorLike(error))throw error;throw new HttpError(500,getErrorMessage(error)||"An unexpected validation error occurred")}}function applyMessages(result,rules,messages,params){if(result.valid||!result.errors||Array.isArray(result.errors))return;applyFieldMessages(result.errors,rules,messages,params)}function isHttpErrorLike(error){return error instanceof HttpError||error instanceof Error&&typeof error.status==="number"}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/validation",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.447",
|
|
6
6
|
"description": "The Stacks Validation ways.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -64,18 +64,18 @@
|
|
|
64
64
|
"prepublishOnly": "bun run build"
|
|
65
65
|
},
|
|
66
66
|
"dependencies": {
|
|
67
|
-
"@stacksjs/error-handling": "0.75.
|
|
68
|
-
"@stacksjs/path": "0.75.
|
|
69
|
-
"@stacksjs/strings": "0.75.
|
|
70
|
-
"@stacksjs/ts-validation": "^0.5.
|
|
71
|
-
"@stacksjs/types": "0.75.
|
|
72
|
-
"@stacksjs/utils": "0.75.
|
|
67
|
+
"@stacksjs/error-handling": "0.75.447",
|
|
68
|
+
"@stacksjs/path": "0.75.447",
|
|
69
|
+
"@stacksjs/strings": "0.75.447",
|
|
70
|
+
"@stacksjs/ts-validation": "^0.5.7",
|
|
71
|
+
"@stacksjs/types": "0.75.447",
|
|
72
|
+
"@stacksjs/utils": "0.75.447"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"better-dx": "^0.2.24"
|
|
76
76
|
},
|
|
77
77
|
"peerDependencies": {
|
|
78
|
-
"@stacksjs/database": "0.75.
|
|
78
|
+
"@stacksjs/database": "0.75.447"
|
|
79
79
|
},
|
|
80
80
|
"peerDependenciesMeta": {
|
|
81
81
|
"@stacksjs/database": {
|