@shuvi/eslint-plugin-shuvi 1.0.23

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/lib/index.d.ts ADDED
File without changes
package/lib/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ module.exports = {
3
+ rules: {
4
+ 'no-head-element': require('./rules/no-head-element').default,
5
+ 'no-html-link-for-pages': require('./rules/no-html-link-for-pages').default,
6
+ 'no-typos': require('./rules/no-typos').default
7
+ },
8
+ configs: {
9
+ recommended: {
10
+ rules: {
11
+ // warnings
12
+ '@shuvi/shuvi/no-head-element': 'warn',
13
+ '@shuvi/shuvi/no-typos': 'error',
14
+ // errors
15
+ '@shuvi/shuvi/no-html-link-for-pages': 'error'
16
+ }
17
+ }
18
+ }
19
+ };
@@ -0,0 +1,2 @@
1
+ declare const _default: import("eslint").Rule.RuleModule;
2
+ export default _default;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const define_rule_1 = require("../utils/define-rule");
4
+ exports.default = (0, define_rule_1.defineRule)({
5
+ meta: {
6
+ docs: {
7
+ description: 'Prevent usage of `<head>` element.',
8
+ category: 'HTML',
9
+ recommended: true
10
+ },
11
+ type: 'problem',
12
+ schema: []
13
+ },
14
+ create(context) {
15
+ return {
16
+ JSXOpeningElement(node) {
17
+ const filePath = context.getFilename();
18
+ if (filePath && filePath.endsWith('document.ejs')) {
19
+ return;
20
+ }
21
+ // Only lint the <head> element in pages directory
22
+ if (node.name.name !== 'head') {
23
+ return;
24
+ }
25
+ context.report({
26
+ node,
27
+ message: `Do not use \`<head>\` element. Use \`<Head />\` from \`shuvi/runtime\` instead.`
28
+ });
29
+ }
30
+ };
31
+ }
32
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("eslint").Rule.RuleModule;
2
+ export default _default;
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ const define_rule_1 = require("../utils/define-rule");
27
+ const path = __importStar(require("path"));
28
+ const fs = __importStar(require("fs"));
29
+ const router_1 = require("@shuvi/router");
30
+ const url_1 = require("../utils/url");
31
+ const pagesDirWarning = (0, url_1.execOnce)(pagesDirs => {
32
+ console.warn(`Pages directory cannot be found at ${pagesDirs.join(' or ')}. ` +
33
+ 'If using a custom path, please configure with the `no-html-link-for-pages` rule in your eslint config file.');
34
+ });
35
+ // Cache for fs.existsSync lookup.
36
+ // Prevent multiple blocking IO requests that have already been calculated.
37
+ const fsExistsSyncCache = {};
38
+ exports.default = (0, define_rule_1.defineRule)({
39
+ meta: {
40
+ docs: {
41
+ description: 'Prevent usage of `<a>` elements to navigate to internal Shuvi.js pages.',
42
+ category: 'HTML',
43
+ recommended: true
44
+ },
45
+ type: 'problem',
46
+ schema: [
47
+ {
48
+ oneOf: [
49
+ {
50
+ type: 'string'
51
+ },
52
+ {
53
+ type: 'array',
54
+ uniqueItems: true,
55
+ items: {
56
+ type: 'string'
57
+ }
58
+ }
59
+ ]
60
+ }
61
+ ]
62
+ },
63
+ /**
64
+ * Creates an ESLint rule listener.
65
+ */
66
+ create(context) {
67
+ const ruleOptions = context.options;
68
+ const [customPagesDirectory] = ruleOptions;
69
+ const rootDirs = [context.getCwd()];
70
+ const pagesDirs = (customPagesDirectory
71
+ ? [customPagesDirectory]
72
+ : rootDirs.map(dir => [path.join(dir, 'src', 'routes')])).flat();
73
+ const foundPagesDirs = pagesDirs.filter(dir => {
74
+ if (fsExistsSyncCache[dir] === undefined) {
75
+ fsExistsSyncCache[dir] = fs.existsSync(dir);
76
+ }
77
+ return fsExistsSyncCache[dir];
78
+ });
79
+ // warn if there are no pages directories
80
+ if (foundPagesDirs.length === 0) {
81
+ pagesDirWarning(pagesDirs);
82
+ return {};
83
+ }
84
+ const pageUrls = (0, url_1.getUrlFromPagesDirectories)('/', foundPagesDirs);
85
+ return {
86
+ JSXOpeningElement(node) {
87
+ if (node.name.name !== 'a') {
88
+ return;
89
+ }
90
+ if (node.attributes.length === 0) {
91
+ return;
92
+ }
93
+ const target = node.attributes.find(attr => attr.type === 'JSXAttribute' && attr.name.name === 'target');
94
+ if (target && target.value.value === '_blank') {
95
+ return;
96
+ }
97
+ const href = node.attributes.find(attr => attr.type === 'JSXAttribute' && attr.name.name === 'href');
98
+ if (!href || (href.value && href.value.type !== 'Literal')) {
99
+ return;
100
+ }
101
+ const hasDownloadAttr = node.attributes.find(attr => attr.type === 'JSXAttribute' && attr.name.name === 'download');
102
+ if (hasDownloadAttr) {
103
+ return;
104
+ }
105
+ const value = href.value.value;
106
+ const hrefPath = (0, url_1.normalizeURL)(value);
107
+ if (!hrefPath) {
108
+ return;
109
+ }
110
+ // Outgoing links are ignored
111
+ if (/^(https?:\/\/|\/\/)/.test(hrefPath)) {
112
+ return;
113
+ }
114
+ const match = (0, router_1.matchRoutes)(pageUrls, hrefPath);
115
+ if (match) {
116
+ context.report({
117
+ node,
118
+ message: `Do not use an \`<a>\` element to navigate to \`${hrefPath}\`. Use \`<Link />\` from \`shuvi/runtime\` instead.`
119
+ });
120
+ }
121
+ }
122
+ };
123
+ }
124
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("eslint").Rule.RuleModule;
2
+ export default _default;
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const define_rule_1 = require("../utils/define-rule");
4
+ const EXPORT_FUNCTIONS = ['loader'];
5
+ const PAGEREG = /routes\/.*page\.(j|t)sx?$/;
6
+ // 0 is the exact match
7
+ const THRESHOLD = 1;
8
+ // the minimum number of operations required to convert string a to string b.
9
+ function minDistance(a, b) {
10
+ const m = a.length;
11
+ const n = b.length;
12
+ if (m < n) {
13
+ return minDistance(b, a);
14
+ }
15
+ if (n === 0) {
16
+ return m;
17
+ }
18
+ let previousRow = Array.from({ length: n + 1 }, (_, i) => i);
19
+ for (let i = 0; i < m; i++) {
20
+ const s1 = a[i];
21
+ let currentRow = [i + 1];
22
+ for (let j = 0; j < n; j++) {
23
+ const s2 = b[j];
24
+ const insertions = previousRow[j + 1] + 1;
25
+ const deletions = currentRow[j] + 1;
26
+ const substitutions = previousRow[j] + Number(s1 !== s2);
27
+ currentRow.push(Math.min(insertions, deletions, substitutions));
28
+ }
29
+ previousRow = currentRow;
30
+ }
31
+ return previousRow[previousRow.length - 1];
32
+ }
33
+ /* eslint-disable eslint-plugin/require-meta-docs-url */
34
+ exports.default = (0, define_rule_1.defineRule)({
35
+ meta: {
36
+ docs: {
37
+ description: 'Prevent common typos in Shuvi.js data fetching functions.',
38
+ recommended: true
39
+ },
40
+ type: 'problem',
41
+ schema: []
42
+ },
43
+ create(context) {
44
+ function checkTypos(node, name) {
45
+ if (EXPORT_FUNCTIONS.includes(name)) {
46
+ return;
47
+ }
48
+ const potentialTypos = EXPORT_FUNCTIONS.map(o => ({
49
+ option: o,
50
+ distance: minDistance(o, name)
51
+ }))
52
+ .filter(({ distance }) => distance <= THRESHOLD && distance > 0)
53
+ .sort((a, b) => a.distance - b.distance);
54
+ if (potentialTypos.length) {
55
+ context.report({
56
+ node,
57
+ message: `${name} may be a typo. Did you mean ${potentialTypos[0].option}?`
58
+ });
59
+ }
60
+ }
61
+ return {
62
+ ExportNamedDeclaration(node) {
63
+ var _a;
64
+ const fileName = context.getFilename();
65
+ if (!fileName || !PAGEREG.test(fileName)) {
66
+ return;
67
+ }
68
+ const decl = node.declaration;
69
+ if (!decl) {
70
+ return;
71
+ }
72
+ switch (decl.type) {
73
+ case 'FunctionDeclaration': {
74
+ checkTypos(node, (_a = decl.id) === null || _a === void 0 ? void 0 : _a.name);
75
+ break;
76
+ }
77
+ case 'VariableDeclaration': {
78
+ decl.declarations.forEach(d => {
79
+ if (d.id.type !== 'Identifier') {
80
+ return;
81
+ }
82
+ checkTypos(node, d.id.name);
83
+ });
84
+ break;
85
+ }
86
+ default: {
87
+ break;
88
+ }
89
+ }
90
+ return;
91
+ }
92
+ };
93
+ }
94
+ });
@@ -0,0 +1,2 @@
1
+ import type { Rule } from 'eslint';
2
+ export declare const defineRule: (rule: Rule.RuleModule) => Rule.RuleModule;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defineRule = void 0;
4
+ const defineRule = (rule) => rule;
5
+ exports.defineRule = defineRule;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Takes a URL and does the following things.
3
+ * - Replaces `index.html` with `/`
4
+ * - Makes sure all URLs are have a trailing `/`
5
+ * - Removes query string
6
+ */
7
+ export declare function normalizeURL(url: string): string | undefined;
8
+ /**
9
+ * Gets the possible URLs from a directory.
10
+ */
11
+ export declare function getUrlFromPagesDirectories(urlPrefix: string, directories: string[]): {
12
+ path: string;
13
+ }[];
14
+ export declare function execOnce<TArgs extends any[], TResult extends unknown>(fn: (...args: TArgs) => TResult): (...args: TArgs) => TResult;
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.execOnce = exports.getUrlFromPagesDirectories = exports.normalizeURL = void 0;
27
+ const path = __importStar(require("path"));
28
+ const fs = __importStar(require("fs"));
29
+ const helpers_1 = require("@shuvi/platform-shared/node/route/helpers");
30
+ const router_1 = require("@shuvi/router");
31
+ // Cache for fs.lstatSync lookup.
32
+ // Prevent multiple blocking IO requests that have already been calculated.
33
+ const fsLstatSyncCache = {};
34
+ const fsLstatSync = (source) => {
35
+ fsLstatSyncCache[source] = fsLstatSyncCache[source] || fs.lstatSync(source);
36
+ return fsLstatSyncCache[source];
37
+ };
38
+ /**
39
+ * Checks if the source is a directory.
40
+ */
41
+ function isDirectory(source) {
42
+ return fsLstatSync(source).isDirectory();
43
+ }
44
+ /**
45
+ * Checks if the source is a directory.
46
+ */
47
+ function isSymlink(source) {
48
+ return fsLstatSync(source).isSymbolicLink();
49
+ }
50
+ // Cache for fs.readdirSync lookup.
51
+ // Prevent multiple blocking IO requests that have already been calculated.
52
+ const fsReadDirSyncCache = {};
53
+ /**
54
+ * Recursively parse directory for page URLs.
55
+ */
56
+ function parseUrlForPages(urlprefix, directory) {
57
+ fsReadDirSyncCache[directory] =
58
+ fsReadDirSyncCache[directory] || fs.readdirSync(directory);
59
+ const res = [];
60
+ fsReadDirSyncCache[directory].forEach(fname => {
61
+ // TODO: this should account for all page extensions
62
+ // not just js(x) and ts(x)
63
+ if (/(\.(j|t)sx?)$/.test(fname)) {
64
+ if (/^page(\.(j|t)sx?)$/.test(fname)) {
65
+ res.push(`${urlprefix}${fname.replace(/^(page\.(j|t)sx?)$/, '')}`);
66
+ }
67
+ res.push(`${urlprefix}${fname.replace(/(page\.(j|t)sx?)$/, '')}`);
68
+ }
69
+ else {
70
+ const dirPath = path.join(directory, fname);
71
+ if (isDirectory(dirPath) && !isSymlink(dirPath)) {
72
+ res.push(...parseUrlForPages(urlprefix + fname + '/', dirPath));
73
+ }
74
+ }
75
+ });
76
+ return res;
77
+ }
78
+ /**
79
+ * Takes a URL and does the following things.
80
+ * - Replaces `index.html` with `/`
81
+ * - Makes sure all URLs are have a trailing `/`
82
+ * - Removes query string
83
+ */
84
+ function normalizeURL(url) {
85
+ if (!url) {
86
+ return;
87
+ }
88
+ url = url.split('?')[0];
89
+ url = url.split('#')[0];
90
+ url = url = url.replace(/(\/index\.html)$/, '/');
91
+ // Empty URLs should not be trailed with `/`, e.g. `#heading`
92
+ if (url === '') {
93
+ return url;
94
+ }
95
+ url = url.endsWith('/') ? url : url + '/';
96
+ return url;
97
+ }
98
+ exports.normalizeURL = normalizeURL;
99
+ /**
100
+ * Gets the possible URLs from a directory.
101
+ */
102
+ function getUrlFromPagesDirectories(urlPrefix, directories) {
103
+ const routes = Array.from(
104
+ // De-duplicate similar pages across multiple directories.
105
+ new Set(directories
106
+ .map(directory => parseUrlForPages(urlPrefix, directory))
107
+ .flat())).map(urlReg => {
108
+ return (0, helpers_1.normalizeRoutePath)(urlReg);
109
+ });
110
+ return (0, router_1.rankRouteBranches)(routes.map(str => [str]))
111
+ .flat()
112
+ .map(str => ({ path: str }));
113
+ }
114
+ exports.getUrlFromPagesDirectories = getUrlFromPagesDirectories;
115
+ function execOnce(fn) {
116
+ let used = false;
117
+ let result;
118
+ return (...args) => {
119
+ if (!used) {
120
+ used = true;
121
+ result = fn(...args);
122
+ }
123
+ return result;
124
+ };
125
+ }
126
+ exports.execOnce = execOnce;
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@shuvi/eslint-plugin-shuvi",
3
+ "version": "1.0.23",
4
+ "description": "ESLint plugin for Shuvi.",
5
+ "main": "lib/index.js",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/shuvijs/shuvi.git",
10
+ "directory": "packages/eslint-plugin-shuvi"
11
+ },
12
+ "files": [
13
+ "lib"
14
+ ],
15
+ "scripts": {
16
+ "dev": "tsc -p tsconfig.json -w",
17
+ "prebuild": "rimraf lib",
18
+ "build": "tsc -p tsconfig.json"
19
+ },
20
+ "dependencies": {
21
+ "@shuvi/router": "1.0.23",
22
+ "@shuvi/platform-shared": "1.0.23"
23
+ },
24
+ "devDependencies": {
25
+ "@types/eslint": "7.28.0",
26
+ "eslint": "7.28.0"
27
+ }
28
+ }