Repository: fnando/cpf Branch: master Commit: 9accc215515a Files: 17 Total size: 21.4 KB Directory structure: gitextract_upeq_h5x/ ├── .eslintrc.js ├── .gitignore ├── .prettierrc.js ├── .tool-versions ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── commonjs/ │ └── index.js ├── es/ │ ├── index.d.ts │ └── index.js ├── jest.config.js ├── package.json ├── src/ │ └── index.ts ├── test/ │ └── cpf.test.ts └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintrc.js ================================================ module.exports = { extends: ["@fnando/codestyle/javascript", "@fnando/codestyle/typescript"], }; ================================================ FILE: .gitignore ================================================ /node_modules /tmp *.log ================================================ FILE: .prettierrc.js ================================================ module.exports = require("@fnando/codestyle/prettier.json"); ================================================ FILE: .tool-versions ================================================ nodejs 12.16.1 ================================================ FILE: .travis.yml ================================================ --- sudo: false language: node_js notifications: email: false node_js: - "13" - "12" ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at me@fnando.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Once you've made your great commits (include tests, please): 1. Fork this repository 2. Create a topic branch - `git checkout -b my_branch` 3. Push to your branch - `git push origin my_branch` 4. Create a pull request That's it! Please respect the indentation rules and code style. And use 2 spaces, not tabs. And don't touch the version thing or distribution files; this will be made when a new version is going to be released. ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 Nando Vieira Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # CPF [![Build Status](https://travis-ci.org/fnando/cpf.svg?branch=master)](https://travis-ci.org/fnando/cpf) [![NPM package version](https://img.shields.io/npm/v/@fnando/cpf.svg)](https://www.npmjs.com/package/@fnando/cpf) ![License: MIT](https://img.shields.io/npm/l/@fnando/cpf.svg) ![Minified size](http://img.badgesize.io/fnando/cpf/master/web/cpf.min.js.svg?label=cpf+min+size) ![Minified+Gzip size](http://img.badgesize.io/fnando/cpf/master/web/cpf.min.js.svg?compression=gzip&label=cpf+min%2Bgzip+size) This package does some [CPF](http://en.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas) magic. It allows you to create, validate and format CPF documents. **HINT:** Check out the CNPJ counter part available at . ## Installation This lib is available as a NPM package. To install it, use the following command: ``` npm install @fnando/cpf --save ``` If you're using Yarn (and you should): ``` yarn add @fnando/cpf ``` ## Usage ```js // Node.js-specific const cpf = require("@fnando/cpf/commonjs"); // @import import * as cpf from "@fnando/cpf"; // import the whole library import { isValid as isValidCpf } from "@fnando/cpf"; // import just one function // import via cpf.isValid("532.820.857-96"); //=> true cpf.isValid("53282085796"); //=> true cpf.strip("532.820.857-96"); //=> 53282085796 cpf.format("53282085796"); //=> 532.820.857-96 cpf.generate(true); // generate formatted number //=> 838.684.734-40 cpf.generate(); // generate unformatted number //=> 72777632898 ``` On the web, without transformation, just use `web/cpf.min.js`. ### Strict Validation By default, validations will strip any characters you provide. This means that the following is valid, because only numbers will be considered: ```js cpf.isValid("101#688!!!!!!542......36"); //=> true cpf.strip("101#688!!!!!!542......36"); //=> 10168854236 ``` If you want to strict validate strings, use the following signature: ```js cpf.isValid(number, strict); ``` The same example would now return `false`: ```js cpf.isValid("101#688!!!!!!542......36", true); //=> false ``` ================================================ FILE: commonjs/index.js ================================================ !function(r,e){for(var t in e)r[t]=e[t]}(exports,function(r){var e={};function t(n){if(e[n])return e[n].exports;var u=e[n]={i:n,l:!1,exports:{}};return r[n].call(u.exports,u,u.exports,t),u.l=!0,u.exports}return t.m=r,t.c=e,t.d=function(r,e,n){t.o(r,e)||Object.defineProperty(r,e,{enumerable:!0,get:n})},t.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},t.t=function(r,e){if(1&e&&(r=t(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var u in r)t.d(n,u,function(e){return r[e]}.bind(null,u));return n},t.n=function(r){var e=r&&r.__esModule?function(){return r.default}:function(){return r};return t.d(e,"a",e),e},t.o=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},t.p="",t(t.s=0)}([function(r,e,t){"use strict";e.__esModule=!0,e.generate=e.isValid=e.strip=e.format=e.verifierDigit=void 0;var n=["00000000000","11111111111","22222222222","33333333333","44444444444","55555555555","66666666666","77777777777","88888888888","99999999999"],u=/[.-]/g,o=/[^\d]/g;function i(r){var e=r.split("").map((function(r){return parseInt(r,10)})),t=e.length+1,n=e.map((function(r,e){return r*(t-e)})).reduce((function(r,e){return r+e}))%11;return n<2?0:11-n}function f(r){return a(r).replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/,"$1.$2.$3-$4")}function a(r,e){void 0===e&&(e=!1);var t=e?u:o;return(r||"").toString().replace(t,"")}e.verifierDigit=i,e.format=f,e.strip=a,e.isValid=function(r,e){void 0===e&&(e=!1);var t=a(r,e);if(!t)return!1;if(11!==t.length)return!1;if(n.includes(t))return!1;var u=t.substr(0,9);return u+=i(u),(u+=i(u)).substr(-2)===t.substr(-2)},e.generate=function(r){void 0===r&&(r=!1);for(var e="",t=0;t<9;t+=1)e+=Math.floor(9*Math.random());return e+=i(e),e+=i(e),r?f(e):e}}])); //# sourceMappingURL=index.js.map ================================================ FILE: es/index.d.ts ================================================ /** * Compute the Verifier Digit (or "Dígito Verificador (DV)" in PT-BR). * * You can learn more about the algorithm on [wikipedia (pt-br)](https://pt.wikipedia.org/wiki/D%C3%ADgito_verificador) * * @export * @param {string} numbers a string with only numbers. * @returns {number} the verifier digit. */ export declare function verifierDigit(numbers: string): number; /** * Transform the input into a pretty CPF format. * * Example: * ``` * format('12345678901'); * // Result: '123.456.789-01' * ``` * * @export * @param {string} cpf the CPF. * @returns {string} the formatted CPF. */ export declare function format(cpf: string): string; /** * Remove some characters from the `number` input. * * Example: * ``` * strip('29537995593'); // Result: '29537995593' * strip('295.379.955-93'); // Result: '29537995593' * strip('295a379b9c5d59e3'); // Result: '29537995593' * strip('295a379b9c5d59e3', true); // Result: '295a379b9c5d59e3' - Attention! * ``` * * @export * @param {string} cpf the CPF text. * @param {boolean} [isStrict] if `true`, it will remove only `.` and `-` characters. * Otherwise, it will remove all non-digit (`[^\d]`) characters. Optional. * @returns {string} the stripped CPF. */ export declare function strip(cpf: string, isStrict?: boolean): string; /** * Validate the CPF. * * @export * @param {string} cpf the CPF number. * @param {boolean} [isStrict] if `true`, it will accept only `digits`, `.` and `-` characters. Optional. * @returns {boolean} `true` if CPF is valid. Otherwise, `false`. */ export declare function isValid(cpf: string, isStrict?: boolean): boolean; /** * Generate a random CPF. * * @export * @param {boolean} [useFormat] if `true`, it will format using `.` and `-`. Optional. * @returns {string} the CPF. */ export declare function generate(useFormat?: boolean): string; ================================================ FILE: es/index.js ================================================ "use strict"; exports.__esModule = true; exports.generate = exports.isValid = exports.strip = exports.format = exports.verifierDigit = void 0; // Reject common values. var REJECT_LIST = [ "00000000000", "11111111111", "22222222222", "33333333333", "44444444444", "55555555555", "66666666666", "77777777777", "88888888888", "99999999999", ]; var STRICT_STRIP_REGEX = /[.-]/g; var LOOSE_STRIP_REGEX = /[^\d]/g; /** * Compute the Verifier Digit (or "Dígito Verificador (DV)" in PT-BR). * * You can learn more about the algorithm on [wikipedia (pt-br)](https://pt.wikipedia.org/wiki/D%C3%ADgito_verificador) * * @export * @param {string} numbers a string with only numbers. * @returns {number} the verifier digit. */ function verifierDigit(numbers) { var numberList = numbers.split("").map(function (number) { return parseInt(number, 10); }); var modulus = numberList.length + 1; var multiplied = numberList.map(function (number, index) { return number * (modulus - index); }); var mod = multiplied.reduce(function (buffer, number) { return buffer + number; }) % 11; return mod < 2 ? 0 : 11 - mod; } exports.verifierDigit = verifierDigit; /** * Transform the input into a pretty CPF format. * * Example: * ``` * format('12345678901'); * // Result: '123.456.789-01' * ``` * * @export * @param {string} cpf the CPF. * @returns {string} the formatted CPF. */ function format(cpf) { return strip(cpf).replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/, "$1.$2.$3-$4"); } exports.format = format; /** * Remove some characters from the `number` input. * * Example: * ``` * strip('29537995593'); // Result: '29537995593' * strip('295.379.955-93'); // Result: '29537995593' * strip('295a379b9c5d59e3'); // Result: '29537995593' * strip('295a379b9c5d59e3', true); // Result: '295a379b9c5d59e3' - Attention! * ``` * * @export * @param {string} cpf the CPF text. * @param {boolean} [isStrict] if `true`, it will remove only `.` and `-` characters. * Otherwise, it will remove all non-digit (`[^\d]`) characters. Optional. * @returns {string} the stripped CPF. */ function strip(cpf, isStrict) { if (isStrict === void 0) { isStrict = false; } var regex = isStrict ? STRICT_STRIP_REGEX : LOOSE_STRIP_REGEX; return (cpf || "").toString().replace(regex, ""); } exports.strip = strip; /** * Validate the CPF. * * @export * @param {string} cpf the CPF number. * @param {boolean} [isStrict] if `true`, it will accept only `digits`, `.` and `-` characters. Optional. * @returns {boolean} `true` if CPF is valid. Otherwise, `false`. */ function isValid(cpf, isStrict) { if (isStrict === void 0) { isStrict = false; } var stripped = strip(cpf, isStrict); // CPF must be defined if (!stripped) { return false; } // CPF must have 11 chars if (stripped.length !== 11) { return false; } if (REJECT_LIST.includes(stripped)) { return false; } var numbers = stripped.substr(0, 9); numbers += verifierDigit(numbers); numbers += verifierDigit(numbers); return numbers.substr(-2) === stripped.substr(-2); } exports.isValid = isValid; /** * Generate a random CPF. * * @export * @param {boolean} [useFormat] if `true`, it will format using `.` and `-`. Optional. * @returns {string} the CPF. */ function generate(useFormat) { if (useFormat === void 0) { useFormat = false; } var numbers = ""; for (var i = 0; i < 9; i += 1) { numbers += Math.floor(Math.random() * 9); } numbers += verifierDigit(numbers); numbers += verifierDigit(numbers); return useFormat ? format(numbers) : numbers; } exports.generate = generate; ================================================ FILE: jest.config.js ================================================ module.exports = require("@fnando/codestyle/jest"); ================================================ FILE: package.json ================================================ { "name": "@fnando/cpf", "version": "1.0.2", "description": "Validate, generate and format CPF numbers", "main": "es/index.js", "module": "es/index.js", "types": "es/index.d.ts", "scripts": { "lint": "yarn eslint src", "test": "yarn jest", "js:dist": "tsc", "js:dist:web": "webpack --entry ./es/index.js --output ./web/cpf.min.js --mode production --target web --output-library-export var --output-library CPF --devtool source-map", "js:dist:node": "webpack --entry ./es/index.js --output ./commonjs/index.js --mode production --target node --output-library-target commonjs --devtool source-map", "dist": "rm -rf {es,commonjs,web} && yarn test && yarn js:dist && yarn js:dist:web && yarn js:dist:node" }, "repository": { "type": "git", "url": "https://github.com/fnando/cpf.git" }, "keywords": [ "cpf", "document" ], "author": "Nando Vieira ", "license": "MIT", "bugs": { "url": "https://github.com/fnando/cpf/issues" }, "devDependencies": { "@babel/types": "*", "@fnando/codestyle": "*", "@fnando/eslint-config-codestyle": "*", "@types/jest": "*", "eslint": "*", "eslint-config-prettier": "*", "eslint-plugin-prettier": "*", "jest": "*", "jest-filename-transform": "*", "ts-jest": "*", "typescript": "*", "webpack": "*", "webpack-cli": "*" } } ================================================ FILE: src/index.ts ================================================ // Reject common values. const REJECT_LIST = [ "00000000000", "11111111111", "22222222222", "33333333333", "44444444444", "55555555555", "66666666666", "77777777777", "88888888888", "99999999999", ]; const STRICT_STRIP_REGEX = /[.-]/g; const LOOSE_STRIP_REGEX = /[^\d]/g; /** * Compute the Verifier Digit (or "Dígito Verificador (DV)" in PT-BR). * * You can learn more about the algorithm on [wikipedia (pt-br)](https://pt.wikipedia.org/wiki/D%C3%ADgito_verificador) * * @export * @param {string} numbers a string with only numbers. * @returns {number} the verifier digit. */ export function verifierDigit(numbers: string): number { const numberList = numbers.split("").map((number) => parseInt(number, 10)); const modulus = numberList.length + 1; const multiplied = numberList.map( (number, index) => number * (modulus - index), ); const mod = multiplied.reduce((buffer, number) => buffer + number) % 11; return mod < 2 ? 0 : 11 - mod; } /** * Transform the input into a pretty CPF format. * * Example: * ``` * format('12345678901'); * // Result: '123.456.789-01' * ``` * * @export * @param {string} cpf the CPF. * @returns {string} the formatted CPF. */ export function format(cpf: string): string { return strip(cpf).replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/, "$1.$2.$3-$4"); } /** * Remove some characters from the `number` input. * * Example: * ``` * strip('29537995593'); // Result: '29537995593' * strip('295.379.955-93'); // Result: '29537995593' * strip('295a379b9c5d59e3'); // Result: '29537995593' * strip('295a379b9c5d59e3', true); // Result: '295a379b9c5d59e3' - Attention! * ``` * * @export * @param {string} cpf the CPF text. * @param {boolean} [isStrict] if `true`, it will remove only `.` and `-` characters. * Otherwise, it will remove all non-digit (`[^\d]`) characters. Optional. * @returns {string} the stripped CPF. */ export function strip(cpf: string, isStrict = false): string { const regex = isStrict ? STRICT_STRIP_REGEX : LOOSE_STRIP_REGEX; return (cpf || "").toString().replace(regex, ""); } /** * Validate the CPF. * * @export * @param {string} cpf the CPF number. * @param {boolean} [isStrict] if `true`, it will accept only `digits`, `.` and `-` characters. Optional. * @returns {boolean} `true` if CPF is valid. Otherwise, `false`. */ export function isValid(cpf: string, isStrict: boolean = false): boolean { const stripped = strip(cpf, isStrict); // CPF must be defined if (!stripped) { return false; } // CPF must have 11 chars if (stripped.length !== 11) { return false; } if (REJECT_LIST.includes(stripped)) { return false; } let numbers = stripped.substr(0, 9); numbers += verifierDigit(numbers); numbers += verifierDigit(numbers); return numbers.substr(-2) === stripped.substr(-2); } /** * Generate a random CPF. * * @export * @param {boolean} [useFormat] if `true`, it will format using `.` and `-`. Optional. * @returns {string} the CPF. */ export function generate(useFormat: boolean = false): string { let numbers = ""; for (let i = 0; i < 9; i += 1) { numbers += Math.floor(Math.random() * 9); } numbers += verifierDigit(numbers); numbers += verifierDigit(numbers); return useFormat ? format(numbers) : numbers; } ================================================ FILE: test/cpf.test.ts ================================================ import * as cpf from "../src/index"; it("rejects common numbers", () => { expect(cpf.isValid("00000000000")).toBeFalsy(); expect(cpf.isValid("11111111111")).toBeFalsy(); expect(cpf.isValid("22222222222")).toBeFalsy(); expect(cpf.isValid("33333333333")).toBeFalsy(); expect(cpf.isValid("44444444444")).toBeFalsy(); expect(cpf.isValid("55555555555")).toBeFalsy(); expect(cpf.isValid("66666666666")).toBeFalsy(); expect(cpf.isValid("77777777777")).toBeFalsy(); expect(cpf.isValid("88888888888")).toBeFalsy(); expect(cpf.isValid("99999999999")).toBeFalsy(); }); it("rejects falsy values", () => { expect(cpf.isValid("")).toBeFalsy(); expect(cpf.isValid(null)).toBeFalsy(); expect(cpf.isValid(undefined)).toBeFalsy(); }); it("validates formatted strings", () => { expect(cpf.isValid("295.379.955-93")).toBeTruthy(); }); it("validates unformatted strings", () => { expect(cpf.isValid("29537995593")).toBeTruthy(); }); it("validates messed strings", () => { expect(cpf.isValid("295$379\n955...93")).toBeTruthy(); expect(cpf.isValid(" 295$379 955\ns93 ")).toBeTruthy(); }); it("strictly validates strings", () => { expect(cpf.isValid("295$379\n955...93", true)).toBeFalsy(); expect(cpf.isValid("295.379.955-93", true)).toBeTruthy(); expect(cpf.isValid("29537995593", true)).toBeTruthy(); }); it("returns stripped number", () => { expect(cpf.strip("295.379.955-93")).toEqual("29537995593"); expect(cpf.strip("295a379b955c93")).toEqual("29537995593"); expect(cpf.strip("295a379b955c93", true)).not.toEqual("29537995593"); }); it("returns formatted number", () => { const number = cpf.format("29537995593"); expect(number).toEqual("295.379.955-93"); }); it("generates formatted number", () => { const number = cpf.generate(true); expect(number).toMatch(/^\d{3}\.\d{3}\.\d{3}-\d{2}$/); expect(cpf.isValid(number)).toBeTruthy(); }); it("generates unformatted number", () => { const number = cpf.generate(); expect(number).toMatch(/^\d{3}\d{3}\d{3}\d{2}$/); expect(cpf.isValid(number)).toBeTruthy(); }); ================================================ FILE: tsconfig.json ================================================ { "extends": "@fnando/codestyle/package", "include": ["src"], "compilerOptions": { "moduleResolution": "node", "lib": ["esnext"], "declaration": true, "declarationDir": "es", "outDir": "es" } }