Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eslint, uitls Tests #2

Merged
merged 17 commits into from
Aug 10, 2020
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build/**
46 changes: 37 additions & 9 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,44 @@
module.exports = {
root: true,
env: {
browser: true,
es2020: true,
'jest/globals': true,
},
extends: ['airbnb-base', 'plugin:jest/recommended', 'prettier/@typescript-eslint', 'plugin:prettier/recommended'],
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.ts'],
},
},
},
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'prettier'],
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'],

parserOptions: {
ecmaVersion: 11,
sourceType: 'module',
},
plugins: ['@typescript-eslint', 'jest', 'prettier'],
rules: {
'prettier/prettier': 'error',
semi: ['error', 'always'],
'no-var': ['error'],
// do not require ext. when importing file
'import/extensions': [
'error',
'ignorePackages',
{
ts: 'never',
},
],

// avoid having warnings when we import types and they are detected as unused imports
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': ['error'],

// <temporarily allowed until fixed>
'no-param-reassign': ['warn'],
'global-require': ['warn'],

// -- OVERRIDES by choice --
// allow console logs
'no-console': ['off'],
'no-unused-vars': ['warn'],
'no-mixed-spaces-and-tabs': ['warn'],
'node/no-unpublished-require': ['off'],
},
};
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/node_modules/
/coverage/

.DS_store
94 changes: 46 additions & 48 deletions build/Elder.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,49 @@ exports.build = build_1.default;
const partialHydration_1 = __importDefault(require("./partialHydration/partialHydration"));
exports.partialHydration = partialHydration_1.default;
const utils_1 = require("./utils");
const createReadOnlyProxy_1 = require("./utils/createReadOnlyProxy");
const createReadOnlyProxy_1 = __importDefault(require("./utils/createReadOnlyProxy"));
const getElderConfig = utils_1.getConfig;
exports.getElderConfig = getElderConfig;
async function workerBuild({ bootstrapComplete, workerRequests }) {
const { settings, query, helpers, data, runHook, routes, errors, customProps } = await bootstrapComplete;
// potential issue that since builds are split across processes,
// some plugins may need all requests of the same category to be passed at the same time.
process.send(['start', workerRequests.length]);
let i = 0;
let errs = 0;
const bTimes = [];
const bErrors = [];
await utils_1.asyncForEach(workerRequests, async (request) => {
const page = new utils_1.Page({
allRequests: workerRequests,
request,
settings,
query,
helpers,
data,
route: routes[request.route],
runHook,
routes,
errors,
customProps,
});
const { errors: buildErrors, timings } = await page.build();
i += 1;
bTimes.push(timings);
const response = ['html', i];
if (buildErrors && buildErrors.length > 0) {
errs += 1;
response.push(errs);
response.push({ request, errors: buildErrors });
bErrors.push({ request, errors: buildErrors });
}
else {
response.push(errs);
}
process.send(response);
});
return bTimes;
}
class Elder {
constructor({ context, worker = false }) {
this.bootstrapComplete = new Promise((resolve) => {
Expand Down Expand Up @@ -77,7 +117,7 @@ class Elder {
plugin.init({
...plugin,
config: lodash_defaultsdeep_1.default(pluginConfigFromConfig, plugin.config),
settings: createReadOnlyProxy_1.createReadOnlyProxy(this.settings, 'Settings', 'plugin init()'),
settings: createReadOnlyProxy_1.default(this.settings, 'Settings', 'plugin init()'),
}) || plugin;
const validatedPlugin = utils_1.validatePlugin(plugin);
if (!validatedPlugin)
Expand Down Expand Up @@ -224,10 +264,8 @@ class Elder {
}
}
}
else {
if (this.settings.debug.automagic) {
console.log(`No luck finding that hooks file. You can add one at ${hookSrcPath}`);
}
else if (this.settings.debug.automagic) {
console.log(`No luck finding that hooks file. You can add one at ${hookSrcPath}`);
}
}
else {
Expand Down Expand Up @@ -322,8 +360,8 @@ class Elder {
});
if (this.allRequests.length !== new Set(this.allRequests.map((r) => r.permalink)).size) {
// useful error logging for when there are duplicate permalinks.
for (let i = 0, l = this.allRequests.length; i < l; i++) {
for (let ii = 0, li = this.allRequests.length; ii < li; ii++) {
for (let i = 0, l = this.allRequests.length; i < l; i += 1) {
for (let ii = 0, li = this.allRequests.length; ii < li; ii += 1) {
if (i !== ii && this.allRequests[i].permalink === this.allRequests[ii].permalink) {
throw new Error(`Duplicate permalinks detected. Here are the relevant requests: ${JSON.stringify(this.allRequests[i])} and ${JSON.stringify(this.allRequests[ii])}`);
}
Expand All @@ -344,43 +382,3 @@ class Elder {
}
}
exports.Elder = Elder;
async function workerBuild({ bootstrapComplete, workerRequests }) {
const { settings, query, helpers, data, runHook, routes, errors, customProps } = await bootstrapComplete;
// potential issue that since builds are split across processes,
// some plugins may need all requests of the same category to be passed at the same time.
process.send(['start', workerRequests.length]);
let i = 0;
let errs = 0;
const bTimes = [];
const bErrors = [];
await utils_1.asyncForEach(workerRequests, async (request) => {
const page = new utils_1.Page({
allRequests: workerRequests,
request,
settings,
query,
helpers,
data,
route: routes[request.route],
runHook,
routes,
errors,
customProps,
});
const { errors: buildErrors, timings } = await page.build();
i += 1;
bTimes.push(timings);
const response = ['html', i];
if (buildErrors && buildErrors.length > 0) {
errs += 1;
response.push(errs);
response.push({ request, errors: buildErrors });
bErrors.push({ request, errors: buildErrors });
}
else {
response.push(errs);
}
process.send(response);
});
return bTimes;
}
6 changes: 3 additions & 3 deletions build/build/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const cli_progress_1 = __importDefault(require("cli-progress"));
const os_1 = __importDefault(require("os"));
const cluster_1 = __importDefault(require("cluster"));
const Elder_1 = require("../Elder");
const shuffleArray_1 = require("../utils/shuffleArray");
const shuffleArray_1 = __importDefault(require("../utils/shuffleArray"));
function getWorkerCounts(counts) {
return Object.keys(counts).reduce((out, cv) => {
out.count += counts[cv].count;
Expand Down Expand Up @@ -119,15 +119,15 @@ async function build() {
totalRequests = mElderResults.allRequests.length;
let requestsToSplit = [...mElderResults.allRequests];
if (settings.build.shuffleRequests) {
requestsToSplit = shuffleArray_1.shuffleArray(requestsToSplit);
requestsToSplit = shuffleArray_1.default(requestsToSplit);
}
let requestsPerWorker = Math.ceil(requestsToSplit.length / numberOfWorkers);
if (requestsPerWorker < 100)
requestsPerWorker = 100;
numberOfWorkers = Math.ceil(totalRequests / requestsPerWorker);
if (numberOfWorkers > maxNumberOfWorkers)
numberOfWorkers = maxNumberOfWorkers;
for (let i = 0; i < numberOfWorkers; i++) {
for (let i = 0; i < numberOfWorkers; i += 1) {
cluster_1.default.fork();
}
const counts = {};
Expand Down
2 changes: 1 addition & 1 deletion build/hookInterface/hookInterface.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { HookInterface } from './types';
import type { HookInterface } from './types';
export declare const hookInterface: Array<HookInterface>;
export default hookInterface;
3 changes: 1 addition & 2 deletions build/partialHydration/partialHydration.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
declare const partialHydration: {
markup: ({ content, filename }: {
markup: ({ content }: {
content: any;
filename: any;
}) => Promise<{
code: any;
}>;
Expand Down
2 changes: 1 addition & 1 deletion build/partialHydration/partialHydration.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const partialHydration = {
markup: async ({ content, filename }) => {
markup: async ({ content /* , filename */ }) => {
// there are limitations to this regex. Like you can't have an object {key:{key:val}} as a prop.
const matches = content.matchAll(/<([a-zA-Z]+)\s+hydrate-client={([^]*?})}/gim);
for (const match of matches) {
Expand Down
2 changes: 1 addition & 1 deletion build/routes/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HookOptions } from '../hooks/types';
import type { HookOptions } from '../hooks/types';
export declare type RouteOptions = {
template?: string;
templateComponent?: (string: any) => Object;
Expand Down
12 changes: 6 additions & 6 deletions build/utils/Page.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true });
const getUniqueId_1 = __importDefault(require("./getUniqueId"));
const perf_1 = __importDefault(require("./perf"));
const prepareProcessStack_1 = require("./prepareProcessStack");
const createReadOnlyProxy_1 = require("./createReadOnlyProxy");
const prepareProcessStack_1 = __importDefault(require("./prepareProcessStack"));
const createReadOnlyProxy_1 = __importDefault(require("./createReadOnlyProxy"));
const buildPage = async (page) => {
try {
page.perf.end('initToBuildGap');
Expand All @@ -27,11 +27,11 @@ const buildPage = async (page) => {
data: page.data,
query: page.query,
helpers: page.helpers,
settings: createReadOnlyProxy_1.createReadOnlyProxy(page.settings, 'settings', 'data.js'),
request: createReadOnlyProxy_1.createReadOnlyProxy(page.request, 'request', 'data.js'),
settings: createReadOnlyProxy_1.default(page.settings, 'settings', 'data.js'),
request: createReadOnlyProxy_1.default(page.request, 'request', 'data.js'),
errors: page.errors,
perf: page.perf,
allRequests: createReadOnlyProxy_1.createReadOnlyProxy(page.allRequests, 'allRequests', 'data.js'),
allRequests: createReadOnlyProxy_1.default(page.allRequests, 'allRequests', 'data.js'),
});
if (dataResponse) {
page.data = dataResponse;
Expand Down Expand Up @@ -129,7 +129,7 @@ class Page {
this.routes = routes;
this.customProps = customProps;
this.htmlString = '';
this.processStack = prepareProcessStack_1.prepareProcessStack(this);
this.processStack = prepareProcessStack_1.default(this);
this.runHook('modifyCustomProps', this);
this.perf.end('constructor');
this.perf.start('initToBuildGap');
Expand Down
7 changes: 0 additions & 7 deletions build/utils/asyncForEach.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,2 @@
/**
* Helper function that makes sure the array is indeed processed async.
*
* @async
* @param {*} array
* @param {*} callback
*/
declare function asyncForEach(array: any, callback: any): Promise<void>;
export default asyncForEach;
11 changes: 3 additions & 8 deletions build/utils/asyncForEach.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Helper function that makes sure the array is indeed processed async.
*
* @async
* @param {*} array
* @param {*} callback
*/
// helper function that makes sure the array is indeed processed async
async function asyncForEach(array, callback) {
let index = 0;
const ar = array.length;
for (; index < ar; index++) {
for (; index < ar; index += 1) {
// eslint-disable-next-line no-await-in-loop
await callback(array[index], index, array);
}
}
Expand Down
8 changes: 1 addition & 7 deletions build/utils/capitalizeFirstLetter.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,2 @@
/**
* Capitalizes the first letter in a string.
*
* @param {*} string
* @returns
*/
declare function capitalizeFirstLetter(string: any): any;
declare function capitalizeFirstLetter(s: any): string;
export default capitalizeFirstLetter;
10 changes: 2 additions & 8 deletions build/utils/capitalizeFirstLetter.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Capitalizes the first letter in a string.
*
* @param {*} string
* @returns
*/
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
function capitalizeFirstLetter(s) {
return `${s.charAt(0).toUpperCase()}${s.slice(1)}`;
}
exports.default = capitalizeFirstLetter;
3 changes: 2 additions & 1 deletion build/utils/createReadOnlyProxy.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export declare function createReadOnlyProxy(obj: object, objName: string, location: string): object;
declare function createReadOnlyProxy(obj: object, objName: string, location: string): object;
export default createReadOnlyProxy;
5 changes: 2 additions & 3 deletions build/utils/createReadOnlyProxy.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createReadOnlyProxy = void 0;
function createReadOnlyProxy(obj, objName, location) {
// proxies only work on objects/arrays.
try {
if (typeof obj !== 'object' && !Array.isArray(obj))
return obj;
return new Proxy(obj, {
set(target, prop, val) {
set() {
console.log(`Object ${objName} is not mutable from ${location}. Check the error below for the hook/plugin that is attempting to mutate properties outside of the rules in hookInterface.ts or in other restricted areas.`);
return false;
},
Expand All @@ -17,4 +16,4 @@ function createReadOnlyProxy(obj, objName, location) {
return obj;
}
}
exports.createReadOnlyProxy = createReadOnlyProxy;
exports.default = createReadOnlyProxy;
6 changes: 2 additions & 4 deletions build/utils/getConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,8 @@ function getConfig(context) {
console.log(`debug.automagic:: Automatically setting your location.buildFolder = "${config.locations.buildFolder} 'in your elder.config.js file as we detected it from your tsconfig.json`);
}
}
else {
if (config.debug.automagic && (!context || context !== 'build')) {
console.log(`debug.automagic:: Unable to automatically set your build folder from your tsconfig. Please add it to your elder.config.js. We saw ${tsConfig.compilerOptions.outDir} and didn't know how to parse it as we're still typescript newbies. Want to help us? We'd love a PR to make this more robust.`);
}
else if (config.debug.automagic && (!context || context !== 'build')) {
console.log(`debug.automagic:: Unable to automatically set your build folder from your tsconfig. Please add it to your elder.config.js. We saw ${tsConfig.compilerOptions.outDir} and didn't know how to parse it as we're still typescript newbies. Want to help us? We'd love a PR to make this more robust.`);
}
}
}
Expand Down
8 changes: 3 additions & 5 deletions build/utils/getHashedSvelteComponents.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ let ready = false;
const getHashedSvelteCompontents = (config) => {
if (!ready) {
ready = true;
const ssrFiles = glob_1.default.sync(path_1.default.resolve(process.cwd(), config.locations.svelte.ssrComponents) + '/*.js', {});
const clientFiles = glob_1.default.sync(path_1.default.resolve(process.cwd(), config.locations.svelte.clientComponents) + '/*.js', {});
const ssrFiles = glob_1.default.sync(`${path_1.default.resolve(process.cwd(), config.locations.svelte.ssrComponents)}/*.js`, {});
const clientFiles = glob_1.default.sync(`${path_1.default.resolve(process.cwd(), config.locations.svelte.clientComponents)}/*.js`, {});
// get an array with jus the file name before .js;
// CityResults.js => CityResults
const ssr = ssrFiles.map((s) => s.split('/').pop().split('.')[0]);
Expand All @@ -32,8 +32,6 @@ const getHashedSvelteCompontents = (config) => {
}, {});
return results;
}
else {
return results;
}
return results;
};
exports.default = getHashedSvelteCompontents;
Loading