@arkyn/server 3.0.1-beta.73 → 3.0.1-beta.74
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/bundle.js +407 -240
- package/dist/bundle.umd.cjs +9 -9
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -0
- package/dist/validations/validateCep.d.ts +24 -0
- package/dist/validations/validateCep.d.ts.map +1 -0
- package/dist/validations/validateCep.js +33 -0
- package/dist/validations/validateCnpj.d.ts +22 -0
- package/dist/validations/validateCnpj.d.ts.map +1 -0
- package/dist/validations/validateCnpj.js +52 -0
- package/dist/validations/validateCpf.d.ts +24 -0
- package/dist/validations/validateCpf.d.ts.map +1 -0
- package/dist/validations/validateCpf.js +54 -0
- package/dist/validations/validateDate.d.ts +34 -0
- package/dist/validations/validateDate.d.ts.map +1 -0
- package/dist/validations/validateDate.js +73 -0
- package/dist/validations/validateEmail.d.ts +22 -0
- package/dist/validations/validateEmail.d.ts.map +1 -0
- package/dist/validations/validateEmail.js +121 -0
- package/dist/validations/validatePassword.d.ts +21 -0
- package/dist/validations/validatePassword.d.ts.map +1 -0
- package/dist/validations/validatePassword.js +34 -0
- package/dist/validations/validatePhone.d.ts +29 -0
- package/dist/validations/validatePhone.d.ts.map +1 -0
- package/dist/validations/validatePhone.js +44 -0
- package/dist/validations/validateRg.d.ts +22 -0
- package/dist/validations/validateRg.d.ts.map +1 -0
- package/dist/validations/validateRg.js +31 -0
- package/package.json +4 -3
package/dist/bundle.umd.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`;
|
|
3
|
-
`}),console.log(
|
|
4
|
-
`).map(i=>i.trim()),r=
|
|
5
|
-
`),r.push(`Caller Function: ${
|
|
6
|
-
`),r.push(`Caller Location: ${
|
|
1
|
+
(function(u,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("zod"),require("@arkyn/shared"),require("@arkyn/templates")):typeof define=="function"&&define.amd?define(["exports","zod","@arkyn/shared","@arkyn/templates"],d):(u=typeof globalThis<"u"?globalThis:u||self,d(u["@arkyn/server"]={},null,u.shared,u.templates))})(this,function(u,d,m,M){"use strict";var Us=Object.defineProperty;var ks=(u,d,m)=>d in u?Us(u,d,{enumerable:!0,configurable:!0,writable:!0,value:m}):u[d]=m;var o=(u,d,m)=>ks(u,typeof d!="symbol"?d+"":d,m);function T(e){var s;if(process.env.NODE_ENV==="development"||((s=process.env)==null?void 0:s.SHOW_ERRORS_IN_CONSOLE)==="true"){const a=`${{yellow:"\x1B[33m",cyan:"\x1B[36m",red:"\x1B[31m",green:"\x1B[32m"}[e.scheme]}[${e.name}]\x1B[0m`;let h=`
|
|
2
|
+
`;e.debugs.forEach(l=>{h+=`${a} ${l.trim()}
|
|
3
|
+
`}),console.log(h)}}const $={};class D{static setIgnoreFile(t){this.ignoreFiles.push(t)}static clearIgnoreFiles(){this.ignoreFiles=[]}}o(D,"ignoreFiles",[]);function N(){const e=process.cwd(),n=(new Error().stack||"").split(`
|
|
4
|
+
`).map(i=>i.trim()),r=D.ignoreFiles;let a=2;for(;a<n.length&&(n[a].includes("node:internal")||n[a].includes("/node_modules/"));)a++;if(r.length>0)for(;a<n.length&&r.some(i=>n[a].includes(i));)a++;const h=n[a]||"";let l="Unknown function",c="Unknown caller";const f=h.match(/at\s+([^(\s]+)\s+\(([^)]+)\)/);if(f)l=f[1],c=f[2];else{const i=h.match(/at\s+(.+)/);if(i){c=i[1];const g=c.match(/at\s+([^(\s]+)\s+/);g&&g[1]!=="new"&&(l=g[1])}}c.includes("(")&&(c=c.substring(c.indexOf("(")+1,c.lastIndexOf(")"))),c=c.split(":").slice(0,-2).join(":");try{c=$.relative(e,c)}catch{}return{functionName:l,callerInfo:c}}class p{onDebug(t){const{name:s,body:n,cause:r,message:a}=t,h=[],{callerInfo:l,functionName:c}=N();h.push(`${s} initialized`),h.push(`Caller Function: ${c}`),h.push(`Caller Location: ${l}`),a&&h.push(`Message: ${a}`),n&&h.push(`Body: ${JSON.stringify(n,null,2)}`),r&&h.push(`Cause: ${JSON.stringify(r,null,2)}`),T({scheme:"red",name:"ARKYN-BAD-RESPONSE-DEBUG",debugs:h})}}class C extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",502);o(this,"statusText");this.body={name:"BadGateway",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"BadGateway",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class S extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",400);o(this,"statusText");this.body={name:"BadRequest",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"BadRequest",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class O extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",409);o(this,"statusText");this.body={name:"Conflict",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"Conflict",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class U extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",403);o(this,"statusText");this.body={name:"Forbidden",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"Forbidden",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class k extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",404);o(this,"statusText");this.body={name:"NotFound",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"NotFound",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class A extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",501);o(this,"statusText");this.body={name:"NotImplemented",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"NotImplemented",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class E extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",500);o(this,"statusText");this.body={name:"ServerError",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"ServerError",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class w extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",401);o(this,"statusText");this.body={name:"Unauthorized",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"Unauthorized",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class v extends p{constructor(s){super();o(this,"body");o(this,"status",422);o(this,"statusText");this.statusText=s.message||"Unprocessable Entity",this.body={name:"UnprocessableEntity",message:s.message||null,data:s.data,fieldErrors:s.fieldErrors,fields:s.fields},this.onDebug({name:"UnprocessableEntity",cause:s.fieldErrors,message:s.message})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class R{onDebug(t,s,n){const r=[],{callerInfo:a,functionName:h}=N();r.push(`${t} initialized
|
|
5
|
+
`),r.push(`Caller Function: ${h}
|
|
6
|
+
`),r.push(`Caller Location: ${a}
|
|
7
7
|
`),r.push(`Body: ${JSON.stringify(s,null,2)}
|
|
8
|
-
`),
|
|
9
|
-
`),
|
|
10
|
-
`)}class
|
|
8
|
+
`),n&&r.push(`Cause: ${JSON.stringify(n,null,2)}
|
|
9
|
+
`),T({scheme:"green",name:"ARKYN-SUCCESS-RESPONSE-DEBUG",debugs:r})}}class j extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||201,this.statusText=(n==null?void 0:n.statusText)||"Resource created successfully",this.onDebug("Created",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class J extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||302,this.statusText=(n==null?void 0:n.statusText)||"Found",this.onDebug("Found",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class L extends R{constructor(s){super();o(this,"headers");o(this,"status");o(this,"statusText");this.headers=(s==null?void 0:s.headers)||{},this.status=(s==null?void 0:s.status)||204,this.statusText=(s==null?void 0:s.statusText)??"No content",this.onDebug("No content",null)}toResponse(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return new Response(null,s)}}class B extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||200,this.statusText=(n==null?void 0:n.statusText)??"OK",this.onDebug("Success",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class q extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||200,this.statusText=(n==null?void 0:n.statusText)||"Resource updated successfully",this.onDebug("Updated",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class Y{static mapHeaders(t){return t instanceof Headers?Object.fromEntries(t.entries()):typeof t=="object"?Object.entries(t).reduce((s,[n,r])=>(typeof r=="string"?s[n]=r:Array.isArray(r)?s[n]=r.join(", "):s[n]=JSON.stringify(r),s),{}):{}}static mapQueryParams(t){const s={};return t.forEach((n,r)=>{s[r]=n}),s}static handle(t){return{rawUrl:t.url,status:t.status,method:t.method,token:null,elapsedTime:t.elapsedTime,requestHeaders:this.mapHeaders(t.requestHeaders),requestBody:t.requestBody||null,queryParams:this.mapQueryParams(t.queryParams),responseHeaders:this.mapHeaders(t.responseHeaders),responseBody:t.responseBody||null}}}class I{static setArkynConfig(t){if(this.arkynConfig)return;let n=t.arkynLogBaseApiUrl||"https://logs-arkyn-flow-logs.vw6wo7.easypanel.host";n=n+"/http-traffic-records/:trafficSourceId",this.arkynConfig={arkynTrafficSourceId:t.arkynTrafficSourceId,arkynUserToken:t.arkynUserToken,arkynApiUrl:n}}static getArkynConfig(){return this.arkynConfig}static resetArkynConfig(){this.arkynConfig=void 0}}o(I,"arkynConfig");async function _(e){const t=I.getArkynConfig();if(!t)return;const{arkynUserToken:s,arkynApiUrl:n}=t,{elapsedTime:r,method:a,queryParams:h,requestBody:l,requestHeaders:c,responseBody:f,responseHeaders:i,status:g,token:Cs,rawUrl:y}=e;if(process.env.NODE_ENV!=="development")try{const b=new URL(y);let z="HTTPS";b.protocol==="http:"&&(z="HTTP");const Os=JSON.stringify({domainUrl:b.protocol+"//"+b.host,pathnameUrl:b.pathname,status:g,protocol:z,method:a,trafficUserId:null,elapsedTime:r,requestHeaders:c,requestBody:l,queryParams:h,responseHeaders:i,responseBody:f});await fetch(n.replace(":trafficSourceId",t.arkynTrafficSourceId),{method:"POST",body:Os,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(b){T({debugs:[`Error sending request: ${b}`],name:"ARKYN_LOG_ERROR",scheme:"red"})}}async function x(e,t,s={},n){const r={POST:"Resource created successfully",PUT:"Resource updated successfully",DELETE:"Resource deleted successfully",PATCH:"Resource patched successfully",GET:"Request successful"};try{const a=performance.now(),h={...s,"Content-Type":"application/json"},l=await fetch(t,{method:e,headers:h,body:n?JSON.stringify(n):void 0}),c=performance.now()-a,f=l.status;let i=null;try{i=await l.json()}catch{i=null}const g=Y.handle({elapsedTime:c,method:e,queryParams:new URL(t).searchParams,requestHeaders:h,requestBody:n,responseBody:i,responseHeaders:l.headers,status:f,url:t});return _(g),l.ok?{success:!0,status:f,message:(i==null?void 0:i.message)||r[e],response:i,cause:null}:{success:!1,status:f,message:(i==null?void 0:i.message)||l.statusText||"Request failed",response:i,cause:null}}catch(a){return T({debugs:[`Network error or request failed: ${a}`],name:"ARKYN_MAKE_REQUEST_ERROR",scheme:"red"}),{success:!1,status:0,message:"Network error or request failed",response:null,cause:a instanceof Error?a.message:String(a)}}}async function V(e,t={},s){return x("DELETE",e,t,s)}async function G(e,t={}){return x("GET",e,t)}async function Z(e,t={},s){return x("PATCH",e,t,s)}async function W(e,t={},s){return x("POST",e,t,s)}async function K(e,t={},s){return x("PUT",e,t,s)}class Q{constructor(t){o(this,"baseUrl");o(this,"baseHeaders");o(this,"baseToken");o(this,"enableDebug");this.baseUrl=t.baseUrl,this.baseHeaders=t.baseHeaders||void 0,this.baseToken=t.baseToken||void 0,this.enableDebug=t.enableDebug||!1}onDebug(t,s,n){if(this.enableDebug){const r=[];r.push(`Base URL: ${this.baseUrl}`),r.push(`Endpoint: ${t}`),r.push(`Method: ${s}`),n[0]&&r.push(`Headers: ${JSON.stringify(n[0])}`),n[1]&&r.push(`Body: ${JSON.stringify(n[1])}`),T({debugs:r,name:"ARKYN-API-DEBUG",scheme:"yellow"})}}generateURL(t){return this.baseUrl+t}generateHeaders(t,s){let n={};return this.baseToken&&(n={Authorization:`Bearer ${this.baseToken}`}),this.baseHeaders&&(n={...n,...this.baseHeaders}),t&&(n={...n,...t}),s&&(n={...n,Authorization:`Bearer ${s}`}),n}async get(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token);return this.onDebug(t,"get",[r]),await G(n,r)}async post(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(t,"post",[r,a]),await W(n,r,a)}async put(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(t,"put",[r,a]),await K(n,r,a)}async patch(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(t,"patch",[r,a]),await Z(n,r,a)}async delete(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(t,"delete",[r,a]),await V(n,r,a)}}function X(e,t){var s,n,r;return e!=null&&e.message&&typeof(e==null?void 0:e.message)=="string"?e==null?void 0:e.message:e!=null&&e.error&&typeof(e==null?void 0:e.error)=="string"?e==null?void 0:e.error:(s=e==null?void 0:e.error)!=null&&s.message&&typeof((n=e==null?void 0:e.error)==null?void 0:n.message)=="string"?(r=e==null?void 0:e.error)==null?void 0:r.message:t!=null&&t.statusText&&typeof(t==null?void 0:t.statusText)=="string"?t==null?void 0:t.statusText:"Missing error message"}const ss=async e=>{let t;const s=await e.arrayBuffer(),n=new TextDecoder().decode(s);try{t=JSON.parse(n)}catch{try{if(n.includes("=")){const a=new URLSearchParams(n);t=Object.fromEntries(a.entries())}else throw new S("Invalid URLSearchParams format")}catch{throw new S("Failed to extract data from request")}}return t};function es(e){switch(!0){case e instanceof Response:return e;case e instanceof J:return e.toResponse();case e instanceof j:return e.toResponse();case e instanceof q:return e.toResponse();case e instanceof B:return e.toResponse();case e instanceof L:return e.toResponse()}switch(!0){case e instanceof C:return e.toResponse();case e instanceof S:return e.toResponse();case e instanceof O:return e.toResponse();case e instanceof U:return e.toResponse();case e instanceof k:return e.toResponse();case e instanceof A:return e.toResponse();case e instanceof E:return e.toResponse();case e instanceof w:return e.toResponse();case e instanceof v:return e.toResponse()}return new E("Server error",e).toResponse()}function F([e,t]){const s=t.safeParse(e);if(s.success===!1){const n=Object.fromEntries(s.error.issues.map(r=>[r.path.join("."),r.message]));return{success:s.success,fieldErrors:n,fields:e}}else return{success:s.success,data:s.data}}const ts=(e,t="")=>{const s=new URL(e.url);if(t==="")return s.searchParams;const n=Array.from(s.searchParams.entries()).filter(([r])=>r.startsWith(`${t}:`)).map(([r,a])=>[r.replace(`${t}:`,""),a]);return new URLSearchParams(n)};function ns(e){const t="Error validating:",s=e.issues.map(({path:n,message:r})=>`-> ${n.join(".")}: ${r}`);return[t,...s].join(`
|
|
10
|
+
`)}class rs{constructor(t){o(this,"functionName");o(this,"callerInfo");this.schema=t;const{callerInfo:s,functionName:n}=N();this.callerInfo=s,this.functionName=n}isValid(t){return this.schema.safeParse(t).success}safeValidate(t){return this.schema.safeParse(t)}validate(t){try{return this.schema.parse(t)}catch(s){throw new E(ns(s))}}formValidate(t,s){const n=F([t,this.schema]);if(!n.success){const r=Object.keys(n.fieldErrors)[0];throw new v({fields:n.fields,fieldErrors:n.fieldErrors,data:{scrollTo:r},message:s})}return n.data}}const os=e=>{if(!e||!/^[0-9-]+$/.test(e))return!1;const s=m.removeNonNumeric(e),n=8,r=/^\d{8}$/.test(s);return s.length===n&&r};function as(e){return e.length!==14}function us(e){const[t]=e;return[...e].every(s=>s===t)}function H(e,t){let s=0;for(let r=0;r<t.length;r++)s+=parseInt(e[r])*t[r];const n=s%11;return n<2?0:11-n}function is(e){return e.slice(12)}const cs=e=>{if(!e)return!1;const t=m.removeNonNumeric(e);if(as(t)||us(t))return!1;const s=t.slice(0,12),n=H(s,[5,4,3,2,9,8,7,6,5,4,3,2]),r=H(s+n,[6,5,4,3,2,9,8,7,6,5,4,3,2]);return is(t)===`${n}${r}`};function hs(e){return e.length!==11}function ls(e){const[t]=e;return[...e].every(s=>s===t)}function P(e,t){let s=0;for(const r of e)t>1&&(s+=parseInt(r)*t--);const n=s%11;return n<2?0:11-n}function fs(e){return e.slice(9)}const ds=e=>{if(!e)return!1;const t=m.removeNonNumeric(e);if(hs(t)||ls(t))return!1;const s=P(t,10),n=P(t,11);return fs(t)===`${s}${n}`},ys=(e,t)=>{let s,n,r;const a=(t==null?void 0:t.inputFormat)||"DD/MM/YYYY",h=(t==null?void 0:t.minYear)||1900,l=(t==null?void 0:t.maxYear)||3e3;if(a==="DD/MM/YYYY"){const y=/^(\d{2})\/(\d{2})\/(\d{4})$/;if(!y.test(e))return!1;[,s,n,r]=e.match(y)||[]}else if(a==="MM-DD-YYYY"){const y=/^(\d{2})-(\d{2})-(\d{4})$/;if(!y.test(e))return!1;[,n,s,r]=e.match(y)||[]}else if(a==="YYYY-MM-DD"){const y=/^(\d{4})-(\d{2})-(\d{2})$/;if(!y.test(e))return!1;[,r,n,s]=e.match(y)||[]}else throw new Error("Invalid date format");const c=parseInt(s,10),f=parseInt(n,10),i=parseInt(r,10);if(c<1||c>31||f<1||f>12)return!1;const g=[31,28,31,30,31,30,31,31,30,31,30,31];if(f===2){const y=i%4===0&&i%100!==0||i%400===0;if(c>(y?29:28))return!1}else if(c>g[f-1])return!1;return i<h||i>l?!1:new Date(i,f-1,c).getDate()===c},ps=$.promises.resolve;function gs(e){return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(e)}function ms(e){return!(e.length===0||e.length>64||e.startsWith(".")||e.endsWith(".")||e.includes("..")||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+$/.test(e))}function Ts(e){return!(e.length===0||e.length>63||e.startsWith("-")||e.endsWith("-")||!/^[a-zA-Z0-9-]+$/.test(e))}function bs(e){if(e.length===0||e.length>253||e.startsWith(".")||e.endsWith(".")||e.startsWith("-")||e.endsWith("-"))return!1;const t=e.split(".");if(t.length<2)return!1;for(const n of t)if(!Ts(n))return!1;const s=t[t.length-1];return!(s.length<2||!/^[a-zA-Z]+$/.test(s))}function Rs(e){const t=e.split("@");if(t.length!==2)return!1;const[s,n]=t;return!(!ms(s)||!bs(n))}function xs(e){const t=e.split("@");return t.length===2?t[1].toLowerCase():null}const Ns=["MX","A","AAAA"];async function Ss(e,t){try{return await ps(e,t),!0}catch{return!1}}async function Es(e){for(const t of Ns)if(await Ss(e,t))return!0;return!1}const Ds=async e=>{if(!e||typeof e!="string")return!1;const t=e.trim();if(!gs(t)||!Rs(t))return!1;const s=xs(t);return s?await Es(s):!1},vs=e=>{if(!e)return!1;const t=e.length>=8,s=/[A-Z]/.test(e),n=/[a-z]/.test(e),r=/\d/.test(e),a=/[!@#$%^&*(),.?":{}|<>_\-+=~`[\]\\\/]/.test(e);return[t,s,n,r,a].every(h=>h)},Is=e=>{for(const t of M.countries){const s=t.code,n=t.prefix?`-${t.prefix}`:"",r=t.mask.replace(/[^_]/g,"").length;if(t.iso==="BR"){if(new RegExp(`^\\${s} \\d{2}9?\\d{8}$`).test(e))return!0;continue}if(new RegExp(`^\\${s}${n} \\d{${r}}$`).test(e))return!0}return!1},$s=e=>{if(!e||!/^[0-9a-zA-Z.-]+$/.test(e))return!1;const s=e.replace(/[^a-zA-Z0-9]/g,"");return s.length<7||s.length>9?!1:/^[0-9]{7,8}[0-9Xx]?$/.test(s)};u.ApiService=Q,u.ArkynLogService=I,u.BadGateway=C,u.BadRequest=S,u.Conflict=O,u.Created=j,u.DebugService=D,u.Forbidden=U,u.Found=J,u.NoContent=L,u.NotFound=k,u.NotImplemented=A,u.SchemaValidator=rs,u.ServerError=E,u.Success=B,u.Unauthorized=w,u.UnprocessableEntity=v,u.Updated=q,u.decodeErrorMessageFromRequest=X,u.decodeRequestBody=ss,u.errorHandler=es,u.flushDebugLogs=T,u.formParse=F,u.getCaller=N,u.getScopedParams=ts,u.validateCep=os,u.validateCnpj=cs,u.validateCpf=ds,u.validateDate=ys,u.validateEmail=Ds,u.validatePassword=vs,u.validatePhone=Is,u.validateRg=$s,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
|
package/dist/index.d.ts
CHANGED
|
@@ -23,4 +23,12 @@ export { formParse } from "./services/formParse";
|
|
|
23
23
|
export { getCaller } from "./services/getCaller";
|
|
24
24
|
export { getScopedParams } from "./services/getScopedParams";
|
|
25
25
|
export { SchemaValidator } from "./services/schemaValidator";
|
|
26
|
+
export { validateCep } from "./validations/validateCep";
|
|
27
|
+
export { validateCnpj } from "./validations/validateCnpj";
|
|
28
|
+
export { validateCpf } from "./validations/validateCpf";
|
|
29
|
+
export { validateDate } from "./validations/validateDate";
|
|
30
|
+
export { validateEmail } from "./validations/validateEmail";
|
|
31
|
+
export { validatePassword } from "./validations/validatePassword";
|
|
32
|
+
export { validatePhone } from "./validations/validatePhone";
|
|
33
|
+
export { validateRg } from "./validations/validateRg";
|
|
26
34
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAG9E,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAG1D,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,6BAA6B,EAAE,MAAM,0CAA0C,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAG9E,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAG1D,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,6BAA6B,EAAE,MAAM,0CAA0C,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAG7D,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -26,3 +26,12 @@ export { formParse } from "./services/formParse";
|
|
|
26
26
|
export { getCaller } from "./services/getCaller";
|
|
27
27
|
export { getScopedParams } from "./services/getScopedParams";
|
|
28
28
|
export { SchemaValidator } from "./services/schemaValidator";
|
|
29
|
+
// validates
|
|
30
|
+
export { validateCep } from "./validations/validateCep";
|
|
31
|
+
export { validateCnpj } from "./validations/validateCnpj";
|
|
32
|
+
export { validateCpf } from "./validations/validateCpf";
|
|
33
|
+
export { validateDate } from "./validations/validateDate";
|
|
34
|
+
export { validateEmail } from "./validations/validateEmail";
|
|
35
|
+
export { validatePassword } from "./validations/validatePassword";
|
|
36
|
+
export { validatePhone } from "./validations/validatePhone";
|
|
37
|
+
export { validateRg } from "./validations/validateRg";
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
type ValidateCepFunction = (rawCep: string) => boolean;
|
|
2
|
+
/**
|
|
3
|
+
* Removes all non-digit characters from the CEP.
|
|
4
|
+
* @param cep - Raw CEP string.
|
|
5
|
+
* @returns Only numeric characters.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Validates a Brazilian CEP (Código de Endereçamento Postal).
|
|
9
|
+
*
|
|
10
|
+
* A valid CEP has 8 numeric digits.
|
|
11
|
+
*
|
|
12
|
+
* @param rawCep - CEP string, may include formatting (e.g., "12345-678").
|
|
13
|
+
* @returns `true` if the CEP is valid, otherwise `false`.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* validateCep("12345-678"); // true
|
|
18
|
+
* validateCep("12345678"); // true
|
|
19
|
+
* validateCep("ABCDE-123"); // false
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
declare const validateCep: ValidateCepFunction;
|
|
23
|
+
export { validateCep };
|
|
24
|
+
//# sourceMappingURL=validateCep.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateCep.d.ts","sourceRoot":"","sources":["../../src/validations/validateCep.ts"],"names":[],"mappings":"AAEA,KAAK,mBAAmB,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC;AAEvD;;;;GAIG;AAEH;;;;;;;;;;;;;;GAcG;AAEH,QAAA,MAAM,WAAW,EAAE,mBAYlB,CAAC;AAEF,OAAO,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { removeNonNumeric } from "@arkyn/shared";
|
|
2
|
+
/**
|
|
3
|
+
* Removes all non-digit characters from the CEP.
|
|
4
|
+
* @param cep - Raw CEP string.
|
|
5
|
+
* @returns Only numeric characters.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Validates a Brazilian CEP (Código de Endereçamento Postal).
|
|
9
|
+
*
|
|
10
|
+
* A valid CEP has 8 numeric digits.
|
|
11
|
+
*
|
|
12
|
+
* @param rawCep - CEP string, may include formatting (e.g., "12345-678").
|
|
13
|
+
* @returns `true` if the CEP is valid, otherwise `false`.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* validateCep("12345-678"); // true
|
|
18
|
+
* validateCep("12345678"); // true
|
|
19
|
+
* validateCep("ABCDE-123"); // false
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
const validateCep = (rawCep) => {
|
|
23
|
+
if (!rawCep)
|
|
24
|
+
return false;
|
|
25
|
+
const validFormat = /^[0-9-]+$/.test(rawCep);
|
|
26
|
+
if (!validFormat)
|
|
27
|
+
return false;
|
|
28
|
+
const cep = removeNonNumeric(rawCep);
|
|
29
|
+
const CEP_LENGTH = 8;
|
|
30
|
+
const isOnlyDigits = /^\d{8}$/.test(cep);
|
|
31
|
+
return cep.length === CEP_LENGTH && isOnlyDigits;
|
|
32
|
+
};
|
|
33
|
+
export { validateCep };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
type ValidateCnpjFunction = (rawCnpj: string) => boolean;
|
|
2
|
+
/**
|
|
3
|
+
* Validates a Brazilian CNPJ (Cadastro Nacional da Pessoa Jurídica) number.
|
|
4
|
+
*
|
|
5
|
+
* This function performs:
|
|
6
|
+
* - Sanitization (removes non-digit characters).
|
|
7
|
+
* - Length check (must be 14 digits).
|
|
8
|
+
* - Repeating digits check (invalid if all digits are the same).
|
|
9
|
+
* - Verifies the two check digits with the proper weights.
|
|
10
|
+
*
|
|
11
|
+
* @param rawCnpj - CNPJ string, possibly formatted.
|
|
12
|
+
* @returns `true` if valid, otherwise `false`.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* validateCnpj("12.345.678/0001-95"); // false
|
|
17
|
+
* validateCnpj("11.444.777/0001-61"); // true
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
declare const validateCnpj: ValidateCnpjFunction;
|
|
21
|
+
export { validateCnpj };
|
|
22
|
+
//# sourceMappingURL=validateCnpj.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateCnpj.d.ts","sourceRoot":"","sources":["../../src/validations/validateCnpj.ts"],"names":[],"mappings":"AAEA,KAAK,oBAAoB,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC;AAyBzD;;;;;;;;;;;;;;;;;GAiBG;AAEH,QAAA,MAAM,YAAY,EAAE,oBAgBnB,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { removeNonNumeric } from "@arkyn/shared";
|
|
2
|
+
function isInvalidLength(cnpj) {
|
|
3
|
+
const CNPJ_LENGTH = 14;
|
|
4
|
+
return cnpj.length !== CNPJ_LENGTH;
|
|
5
|
+
}
|
|
6
|
+
function hasAllDigitsEqual(cnpj) {
|
|
7
|
+
const [firstDigit] = cnpj;
|
|
8
|
+
return [...cnpj].every((digit) => digit === firstDigit);
|
|
9
|
+
}
|
|
10
|
+
function calculateDigit(cnpj, multipliers) {
|
|
11
|
+
let total = 0;
|
|
12
|
+
for (let i = 0; i < multipliers.length; i++) {
|
|
13
|
+
total += parseInt(cnpj[i]) * multipliers[i];
|
|
14
|
+
}
|
|
15
|
+
const rest = total % 11;
|
|
16
|
+
return rest < 2 ? 0 : 11 - rest;
|
|
17
|
+
}
|
|
18
|
+
function extractDigit(cnpj) {
|
|
19
|
+
return cnpj.slice(12);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Validates a Brazilian CNPJ (Cadastro Nacional da Pessoa Jurídica) number.
|
|
23
|
+
*
|
|
24
|
+
* This function performs:
|
|
25
|
+
* - Sanitization (removes non-digit characters).
|
|
26
|
+
* - Length check (must be 14 digits).
|
|
27
|
+
* - Repeating digits check (invalid if all digits are the same).
|
|
28
|
+
* - Verifies the two check digits with the proper weights.
|
|
29
|
+
*
|
|
30
|
+
* @param rawCnpj - CNPJ string, possibly formatted.
|
|
31
|
+
* @returns `true` if valid, otherwise `false`.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* validateCnpj("12.345.678/0001-95"); // false
|
|
36
|
+
* validateCnpj("11.444.777/0001-61"); // true
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
const validateCnpj = (rawCnpj) => {
|
|
40
|
+
if (!rawCnpj)
|
|
41
|
+
return false;
|
|
42
|
+
const cnpj = removeNonNumeric(rawCnpj);
|
|
43
|
+
if (isInvalidLength(cnpj))
|
|
44
|
+
return false;
|
|
45
|
+
if (hasAllDigitsEqual(cnpj))
|
|
46
|
+
return false;
|
|
47
|
+
const base = cnpj.slice(0, 12);
|
|
48
|
+
const digit1 = calculateDigit(base, [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]);
|
|
49
|
+
const digit2 = calculateDigit(base + digit1, [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]);
|
|
50
|
+
return extractDigit(cnpj) === `${digit1}${digit2}`;
|
|
51
|
+
};
|
|
52
|
+
export { validateCnpj };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
type ValidateCpfFunction = (rawCpf: string) => boolean;
|
|
2
|
+
/**
|
|
3
|
+
* Validates a Brazilian CPF (Cadastro de Pessoas Físicas) number.
|
|
4
|
+
*
|
|
5
|
+
* The CPF is a unique identifier assigned to Brazilian citizens and residents.
|
|
6
|
+
* This function checks if the provided CPF is valid by performing the following steps:
|
|
7
|
+
* - Removes any non-digit characters from the input.
|
|
8
|
+
* - Verifies if the CPF has the correct length (11 digits).
|
|
9
|
+
* - Ensures that all digits are not the same (e.g., "111.111.111-11" is invalid).
|
|
10
|
+
* - Calculates the first and second verification digits using the CPF algorithm.
|
|
11
|
+
* - Compares the calculated verification digits with the ones provided in the CPF.
|
|
12
|
+
*
|
|
13
|
+
* @param rawCpf - The raw CPF string, which may include formatting characters (e.g., dots or dashes).
|
|
14
|
+
* @returns `true` if the CPF is valid, otherwise `false`.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* validateCpf("123.456.789-09"); // false
|
|
19
|
+
* validateCpf("111.444.777-35"); // true
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
declare const validateCpf: ValidateCpfFunction;
|
|
23
|
+
export { validateCpf };
|
|
24
|
+
//# sourceMappingURL=validateCpf.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateCpf.d.ts","sourceRoot":"","sources":["../../src/validations/validateCpf.ts"],"names":[],"mappings":"AAEA,KAAK,mBAAmB,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC;AAyBvD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,QAAA,MAAM,WAAW,EAAE,mBAWlB,CAAC;AAEF,OAAO,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { removeNonNumeric } from "@arkyn/shared";
|
|
2
|
+
function isInvalidLength(cpf) {
|
|
3
|
+
const CPF_LENGTH = 11;
|
|
4
|
+
return cpf.length !== CPF_LENGTH;
|
|
5
|
+
}
|
|
6
|
+
function hasAllDigitsEqual(cpf) {
|
|
7
|
+
const [firstCpfDigit] = cpf;
|
|
8
|
+
return [...cpf].every((digit) => digit === firstCpfDigit);
|
|
9
|
+
}
|
|
10
|
+
function calculateDigit(cpf, factor) {
|
|
11
|
+
let total = 0;
|
|
12
|
+
for (const digit of cpf) {
|
|
13
|
+
if (factor > 1)
|
|
14
|
+
total += parseInt(digit) * factor--;
|
|
15
|
+
}
|
|
16
|
+
const rest = total % 11;
|
|
17
|
+
return rest < 2 ? 0 : 11 - rest;
|
|
18
|
+
}
|
|
19
|
+
function extractDigit(cpf) {
|
|
20
|
+
return cpf.slice(9);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Validates a Brazilian CPF (Cadastro de Pessoas Físicas) number.
|
|
24
|
+
*
|
|
25
|
+
* The CPF is a unique identifier assigned to Brazilian citizens and residents.
|
|
26
|
+
* This function checks if the provided CPF is valid by performing the following steps:
|
|
27
|
+
* - Removes any non-digit characters from the input.
|
|
28
|
+
* - Verifies if the CPF has the correct length (11 digits).
|
|
29
|
+
* - Ensures that all digits are not the same (e.g., "111.111.111-11" is invalid).
|
|
30
|
+
* - Calculates the first and second verification digits using the CPF algorithm.
|
|
31
|
+
* - Compares the calculated verification digits with the ones provided in the CPF.
|
|
32
|
+
*
|
|
33
|
+
* @param rawCpf - The raw CPF string, which may include formatting characters (e.g., dots or dashes).
|
|
34
|
+
* @returns `true` if the CPF is valid, otherwise `false`.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* validateCpf("123.456.789-09"); // false
|
|
39
|
+
* validateCpf("111.444.777-35"); // true
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
const validateCpf = (rawCpf) => {
|
|
43
|
+
if (!rawCpf)
|
|
44
|
+
return false;
|
|
45
|
+
const cpf = removeNonNumeric(rawCpf);
|
|
46
|
+
if (isInvalidLength(cpf))
|
|
47
|
+
return false;
|
|
48
|
+
if (hasAllDigitsEqual(cpf))
|
|
49
|
+
return false;
|
|
50
|
+
const digit1 = calculateDigit(cpf, 10);
|
|
51
|
+
const digit2 = calculateDigit(cpf, 11);
|
|
52
|
+
return extractDigit(cpf) === `${digit1}${digit2}`;
|
|
53
|
+
};
|
|
54
|
+
export { validateCpf };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
type ValidateDateConfig = {
|
|
2
|
+
inputFormat?: "DD/MM/YYYY" | "MM-DD-YYYY" | "YYYY-MM-DD";
|
|
3
|
+
minYear?: number;
|
|
4
|
+
maxYear?: number;
|
|
5
|
+
};
|
|
6
|
+
type ValidateDateFunction = (rawDate: string, config?: ValidateDateConfig) => boolean;
|
|
7
|
+
/**
|
|
8
|
+
* Validates a date string based on the provided format and configuration.
|
|
9
|
+
*
|
|
10
|
+
* @param rawDate - The date string to validate.
|
|
11
|
+
* @param config - Optional configuration object to customize validation.
|
|
12
|
+
* @param config.inputFormat - The expected format of the input date.
|
|
13
|
+
* Supported formats are "DD/MM/YYYY", "MM-DD-YYYY", and "YYYY-MM-DD".
|
|
14
|
+
* Defaults to "DD/MM/YYYY".
|
|
15
|
+
* @param config.minYear - The minimum allowed year for the date. Defaults to 1900.
|
|
16
|
+
* @param config.maxYear - The maximum allowed year for the date. Defaults to 3000.
|
|
17
|
+
*
|
|
18
|
+
* @returns `true` if the date is valid according to the specified format and configuration, otherwise `false`.
|
|
19
|
+
*
|
|
20
|
+
* @throws {Error} If an invalid date format is provided in the configuration.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* validateDate("31/12/2023"); // true
|
|
25
|
+
* validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" }); // true
|
|
26
|
+
* validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD", minYear: 2000, maxYear: 2100 }); // true
|
|
27
|
+
* validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" }); // true (leap year)
|
|
28
|
+
* validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" }); // false (not a leap year)
|
|
29
|
+
* validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" }); // false (April has 30 days)
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
declare const validateDate: ValidateDateFunction;
|
|
33
|
+
export { validateDate };
|
|
34
|
+
//# sourceMappingURL=validateDate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateDate.d.ts","sourceRoot":"","sources":["../../src/validations/validateDate.ts"],"names":[],"mappings":"AAAA,KAAK,kBAAkB,GAAG;IACxB,WAAW,CAAC,EAAE,YAAY,GAAG,YAAY,GAAG,YAAY,CAAC;IACzD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,KAAK,oBAAoB,GAAG,CAC1B,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,kBAAkB,KACxB,OAAO,CAAC;AAEb;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,QAAA,MAAM,YAAY,EAAE,oBA8CnB,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validates a date string based on the provided format and configuration.
|
|
3
|
+
*
|
|
4
|
+
* @param rawDate - The date string to validate.
|
|
5
|
+
* @param config - Optional configuration object to customize validation.
|
|
6
|
+
* @param config.inputFormat - The expected format of the input date.
|
|
7
|
+
* Supported formats are "DD/MM/YYYY", "MM-DD-YYYY", and "YYYY-MM-DD".
|
|
8
|
+
* Defaults to "DD/MM/YYYY".
|
|
9
|
+
* @param config.minYear - The minimum allowed year for the date. Defaults to 1900.
|
|
10
|
+
* @param config.maxYear - The maximum allowed year for the date. Defaults to 3000.
|
|
11
|
+
*
|
|
12
|
+
* @returns `true` if the date is valid according to the specified format and configuration, otherwise `false`.
|
|
13
|
+
*
|
|
14
|
+
* @throws {Error} If an invalid date format is provided in the configuration.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* validateDate("31/12/2023"); // true
|
|
19
|
+
* validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" }); // true
|
|
20
|
+
* validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD", minYear: 2000, maxYear: 2100 }); // true
|
|
21
|
+
* validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" }); // true (leap year)
|
|
22
|
+
* validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" }); // false (not a leap year)
|
|
23
|
+
* validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" }); // false (April has 30 days)
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
const validateDate = (rawDate, config) => {
|
|
27
|
+
let day, month, year;
|
|
28
|
+
const inputFormat = config?.inputFormat || "DD/MM/YYYY";
|
|
29
|
+
const minYear = config?.minYear || 1900;
|
|
30
|
+
const maxYear = config?.maxYear || 3000;
|
|
31
|
+
if (inputFormat === "DD/MM/YYYY") {
|
|
32
|
+
const dateRegex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
|
|
33
|
+
if (!dateRegex.test(rawDate))
|
|
34
|
+
return false;
|
|
35
|
+
[, day, month, year] = rawDate.match(dateRegex) || [];
|
|
36
|
+
}
|
|
37
|
+
else if (inputFormat === "MM-DD-YYYY") {
|
|
38
|
+
const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
|
|
39
|
+
if (!dateRegex.test(rawDate))
|
|
40
|
+
return false;
|
|
41
|
+
[, month, day, year] = rawDate.match(dateRegex) || [];
|
|
42
|
+
}
|
|
43
|
+
else if (inputFormat === "YYYY-MM-DD") {
|
|
44
|
+
const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
45
|
+
if (!dateRegex.test(rawDate))
|
|
46
|
+
return false;
|
|
47
|
+
[, year, month, day] = rawDate.match(dateRegex) || [];
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
throw new Error("Invalid date format");
|
|
51
|
+
}
|
|
52
|
+
const dayNum = parseInt(day, 10);
|
|
53
|
+
const monthNum = parseInt(month, 10);
|
|
54
|
+
const yearNum = parseInt(year, 10);
|
|
55
|
+
if (dayNum < 1 || dayNum > 31)
|
|
56
|
+
return false;
|
|
57
|
+
if (monthNum < 1 || monthNum > 12)
|
|
58
|
+
return false;
|
|
59
|
+
const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
60
|
+
if (monthNum === 2) {
|
|
61
|
+
const isLeapYear = (yearNum % 4 === 0 && yearNum % 100 !== 0) || yearNum % 400 === 0;
|
|
62
|
+
if (dayNum > (isLeapYear ? 29 : 28))
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
else if (dayNum > daysInMonth[monthNum - 1]) {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
if (yearNum < minYear || yearNum > maxYear)
|
|
69
|
+
return false;
|
|
70
|
+
const isValidDate = new Date(yearNum, monthNum - 1, dayNum).getDate() === dayNum;
|
|
71
|
+
return isValidDate;
|
|
72
|
+
};
|
|
73
|
+
export { validateDate };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
type ValidateEmailFunction = (rawEmail: string) => Promise<boolean>;
|
|
2
|
+
/**
|
|
3
|
+
* Validates if an email address is valid in all possible ways, including DNS validation.
|
|
4
|
+
*
|
|
5
|
+
* This function performs comprehensive email validation by:
|
|
6
|
+
* - Checking basic email format and syntax
|
|
7
|
+
* - Validating advanced RFC 5322 compliance rules
|
|
8
|
+
* - Verifying that the domain has valid MX or A records in DNS
|
|
9
|
+
*
|
|
10
|
+
* @param rawEmail - The email address string to validate
|
|
11
|
+
* @returns A promise that resolves to `true` if the email is valid (including DNS), otherwise `false`
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* await validateEmail("user@gmail.com"); // true
|
|
16
|
+
* await validateEmail("user@gmil.com"); // false (invalid domain)
|
|
17
|
+
* await validateEmail("invalid-email"); // false (invalid format)
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
declare const validateEmail: ValidateEmailFunction;
|
|
21
|
+
export { validateEmail };
|
|
22
|
+
//# sourceMappingURL=validateEmail.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateEmail.d.ts","sourceRoot":"","sources":["../../src/validations/validateEmail.ts"],"names":[],"mappings":"AAEA,KAAK,qBAAqB,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAmGpE;;;;;;;;;;;;;;;;;GAiBG;AAEH,QAAA,MAAM,aAAa,EAAE,qBAWpB,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,CAAC"}
|