Skip to content

Commit

Permalink
Setup eslint and prettier (#33)
Browse files Browse the repository at this point in the history
* Adds eslint and an npm script npm run lint:js and npm run lint:js:fix
* Adds prettier and an npm script npm run format
* Adds a husky pre-commit hook to run linting and formatting
* Lints and formats the files in the repository
  • Loading branch information
adamziel authored Oct 14, 2022
1 parent 2b75825 commit 25161d6
Show file tree
Hide file tree
Showing 25 changed files with 1,233 additions and 1,091 deletions.
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
src/node/wordpress/**/*
node-php.js
10 changes: 10 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ module.exports = {
browser: true,
es2021: true,
},
settings: {
'react': {
'version': '999.99.99' // Prevent eslint from complaining (we don't use react).
}
},
extends: [
'eslint:recommended',
'plugin:@wordpress/eslint-plugin/recommended',
Expand All @@ -21,6 +26,11 @@ module.exports = {
'no-inner-declaration': 0,
'no-use-before-define': 'off',
'react/prop-types': 0,
'no-console': 0,
'no-empty': 0,
'no-async-promise-executor': 0,
'no-constant-condition': 0,
'no-nested-ternary': 0,
'jsx-a11y/click-events-have-key-events': 0,
'jsx-a11y/no-static-element-interactions': 0,
},
Expand Down
5 changes: 5 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx lint-staged
npx lint-staged
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
src/node/wordpress/**/*
node-php.js
70 changes: 43 additions & 27 deletions dist-web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
}

// src/web/library.js
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, 50));
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function runWordPress({
wasmWorkerBackend: wasmWorkerBackend2,
wasmWorkerUrl: wasmWorkerUrl2,
Expand All @@ -64,31 +64,37 @@
async function registerServiceWorker({ url, onRequest, scope }) {
if (!navigator.serviceWorker) {
alert("Service workers are not supported in this browser.");
throw new Exception("Service workers are not supported in this browser.");
throw new Error("Service workers are not supported in this browser.");
}
await navigator.serviceWorker.register(url);
const serviceWorkerChannel = new BroadcastChannel(`wordpress-service-worker`);
serviceWorkerChannel.addEventListener("message", async function onMessage(event) {
if (scope && event.data.scope !== scope) {
return;
}
console.debug(`[Main] "${event.data.type}" message received from a service worker`);
let result;
if (event.data.type === "request" || event.data.type === "httpRequest") {
result = await onRequest(event.data.request);
} else {
throw new Error(`[Main] Unexpected message received from the service-worker: "${event.data.type}"`);
}
if (event.data.messageId) {
serviceWorkerChannel.postMessage(
responseTo(
event.data.messageId,
result
)
serviceWorkerChannel.addEventListener(
"message",
async function onMessage(event) {
if (scope && event.data.scope !== scope) {
return;
}
console.debug(
`[Main] "${event.data.type}" message received from a service worker`
);
let result;
if (event.data.type === "request" || event.data.type === "httpRequest") {
result = await onRequest(event.data.request);
} else {
throw new Error(
`[Main] Unexpected message received from the service-worker: "${event.data.type}"`
);
}
if (event.data.messageId) {
serviceWorkerChannel.postMessage(
responseTo(event.data.messageId, result)
);
}
console.debug(`[Main] "${event.data.type}" message processed`, {
result
});
}
console.debug(`[Main] "${event.data.type}" message processed`, { result });
});
);
navigator.serviceWorker.startMessages();
await sleep(0);
const wordPressDomain = new URL(url).origin;
Expand All @@ -98,7 +104,11 @@
window.location.reload();
}
}
async function createWordPressWorker({ backend, wordPressSiteUrl: wordPressSiteUrl2, scope }) {
async function createWordPressWorker({
backend,
wordPressSiteUrl: wordPressSiteUrl2,
scope
}) {
while (true) {
try {
await backend.sendMessage({ type: "is_alive" }, 50);
Expand Down Expand Up @@ -135,14 +145,16 @@
const backend = backends[key];
if (!backend) {
const availableKeys = Object.keys(backends).join(", ");
throw new Error(`Unknown worker backend: "${key}". Choices: ${availableKeys}`);
throw new Error(
`Unknown worker backend: "${key}". Choices: ${availableKeys}`
);
}
return backend(url);
}
function webWorkerBackend(workerURL) {
const worker = new Worker(workerURL);
return {
sendMessage: async function(message, timeout = DEFAULT_REPLY_TIMEOUT) {
async sendMessage(message, timeout = DEFAULT_REPLY_TIMEOUT) {
const messageId = postMessageExpectReply(worker, message);
const response = await awaitReply(worker, messageId, timeout);
return response;
Expand All @@ -153,7 +165,7 @@
const worker = new SharedWorker(workerURL);
worker.port.start();
return {
sendMessage: async function(message, timeout = DEFAULT_REPLY_TIMEOUT) {
async sendMessage(message, timeout = DEFAULT_REPLY_TIMEOUT) {
const messageId = postMessageExpectReply(worker.port, message);
const response = await awaitReply(worker.port, messageId, timeout);
return response;
Expand All @@ -166,8 +178,12 @@
iframe.style.display = "none";
document.body.appendChild(iframe);
return {
sendMessage: async function(message, timeout = DEFAULT_REPLY_TIMEOUT) {
const messageId = postMessageExpectReply(iframe.contentWindow, message, "*");
async sendMessage(message, timeout = DEFAULT_REPLY_TIMEOUT) {
const messageId = postMessageExpectReply(
iframe.contentWindow,
message,
"*"
);
const response = await awaitReply(window, messageId, timeout);
return response;
}
Expand Down
10 changes: 4 additions & 6 deletions dist-web/iframe-worker.html
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
<!DOCTYPE html>
<html>
<head>
</head>
<body style="padding: 0; margin: 0">
<script src="wasm-worker.js"></script>
</body>
<head> </head>
<body style="padding: 0; margin: 0">
<script src="wasm-worker.js"></script>
</body>
</html>

27 changes: 17 additions & 10 deletions dist-web/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@
event.preventDefault();
return event.respondWith(
new Promise(async (accept) => {
console.log(`[ServiceWorker] Serving request: ${url.pathname}?${url.search}`);
console.log(
`[ServiceWorker] Serving request: ${url.pathname}?${url.search}`
);
console.log({ isWpOrgRequest, isPHPRequest });
const post = await parsePost(event.request);
const requestHeaders = {};
Expand All @@ -67,20 +69,23 @@
headers: requestHeaders
}
};
console.log("[ServiceWorker] Forwarding a request to the main app", { message });
console.log("[ServiceWorker] Forwarding a request to the main app", {
message
});
const messageId = postMessageExpectReply(broadcastChannel, message);
wpResponse = await awaitReply(broadcastChannel, messageId);
console.log("[ServiceWorker] Response received from the main app", { wpResponse });
console.log("[ServiceWorker] Response received from the main app", {
wpResponse
});
} catch (e) {
console.error(e);
throw e;
}
accept(new Response(
wpResponse.body,
{
accept(
new Response(wpResponse.body, {
headers: wpResponse.headers
}
));
})
);
})
);
}
Expand All @@ -89,7 +94,9 @@
const scopedUrl = url + "";
url.pathname = "/" + url.pathname.split("/").slice(2).join("/");
const serverUrl = url + "";
console.log(`[ServiceWorker] Rerouting static request from ${scopedUrl} to ${serverUrl}`);
console.log(
`[ServiceWorker] Rerouting static request from ${scopedUrl} to ${serverUrl}`
);
event.preventDefault();
return event.respondWith(
new Promise(async (accept) => {
Expand All @@ -103,7 +110,7 @@
console.log(`[ServiceWorker] Ignoring a request to ${event.request.url}`);
});
async function cloneRequest(request, overrides) {
const body = ["GET", "HEAD"].includes(request.method) || "body" in overrides ? void 0 : await r.blob();
const body = ["GET", "HEAD"].includes(request.method) || "body" in overrides ? void 0 : await request.blob();
return new Request(overrides.url || request.url, {
body,
method: request.method,
Expand Down
57 changes: 28 additions & 29 deletions dist-web/wasm-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -462,13 +462,19 @@ ADMIN;
this.setCookies(response.headers["set-cookie"]);
}
if (this.config.handleRedirects && response.headers.location && redirects < this.config.maxRedirects) {
const parsedUrl = new URL(response.headers.location[0], this.wp.ABSOLUTE_URL);
return this.request({
path: parsedUrl.pathname,
method: "GET",
_GET: parsedUrl.search,
headers: {}
}, redirects + 1);
const parsedUrl = new URL(
response.headers.location[0],
this.wp.ABSOLUTE_URL
);
return this.request(
{
path: parsedUrl.pathname,
method: "GET",
_GET: parsedUrl.search,
headers: {}
},
redirects + 1
);
}
return response;
}
Expand Down Expand Up @@ -533,20 +539,14 @@ ADMIN;
} else if (IS_WEBWORKER) {
phpLoaderScriptName = "/php-webworker.js";
onmessage = (event) => {
handleMessageEvent(
event,
postMessage
);
handleMessageEvent(event, postMessage);
};
} else if (IS_SHARED_WORKER) {
phpLoaderScriptName = "/php-webworker.js";
self.onconnect = (e) => {
const port = e.ports[0];
port.addEventListener("message", (event) => {
handleMessageEvent(
event,
(r) => port.postMessage(r)
);
handleMessageEvent(event, (r) => port.postMessage(r));
});
port.start();
};
Expand All @@ -555,12 +555,7 @@ ADMIN;
console.debug(`[WASM Worker] "${event.data.type}" event received`, event);
const result = await generateResponseForMessage(event.data);
if (event.data.messageId) {
respond(
responseTo(
event.data.messageId,
result
)
);
respond(responseTo(event.data.messageId, result));
}
console.debug(`[WASM Worker] "${event.data.type}" event processed`);
}
Expand All @@ -584,7 +579,9 @@ ADMIN;
_GET: parsedUrl.search
});
}
console.debug(`[WASM Worker] "${message.type}" event has no handler, short-circuiting`);
console.debug(
`[WASM Worker] "${message.type}" event has no handler, short-circuiting`
);
}
async function initWPBrowser(siteUrl) {
console.log("[WASM Worker] Before wp.init()");
Expand All @@ -602,13 +599,15 @@ ADMIN;
importScripts("/wp.js");
});
PHPModule.FS.mkdirTree("/usr/local/etc");
PHPModule.FS.writeFile("/usr/local/etc/php.ini", `[PHP]
error_reporting = E_ERROR | E_PARSE
display_errors = 1
html_errors = 1
display_startup_errors = On
`);
PHPModule.FS.writeFile(
"/usr/local/etc/php.ini",
`[PHP]
error_reporting = E_ERROR | E_PARSE
display_errors = 1
html_errors = 1
display_startup_errors = On
`
);
const wp = new WordPress(php);
await wp.init(siteUrl);
console.log("[WASM Worker] After wp.init()");
Expand Down
18 changes: 10 additions & 8 deletions dist-web/wordpress.html
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<title>WordPress code embed!</title>
</head>
<body style="padding: 0; margin: 0">
<iframe id="wp" style="width: 100vw; height: 100vh; border: 0; margin: 0; padding: 0;"></iframe>
<script src="app.js"></script>
</body>
<head>
<title>WordPress code embed!</title>
</head>
<body style="padding: 0; margin: 0">
<iframe
id="wp"
style="width: 100vw; height: 100vh; border: 0; margin: 0; padding: 0"
></iframe>
<script src="app.js"></script>
</body>
</html>

17 changes: 15 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,17 @@
"clean": "npm-run-all --parallel clean:*",
"clean:php": "rm -rf dist-web/wasm-build/php/docker-output/*",
"clean:wp": "rm -rf dist-web/wasm-build/wordpress/docker-output/* dist-web/wasm-build/wordpress/preload/*",
"test": "echo \"Error: no test specified\" && exit 1"
"format": "prettier --write src",
"lint:js": "eslint \"./src/**/*.{js,mjs,ts}\"",
"lint:js:fix": "npm run lint:js -- --fix",
"test": "echo \"Error: no test specified\" && exit 1",
"prepare": "husky install"
},
"lint-staged": {
"src/**/*": [
"npx prettier --write --ignore-unknown",
"npx eslint --fix"
]
},
"author": "Adam Zielinski",
"license": "ISC",
Expand All @@ -45,7 +55,10 @@
"eslint-plugin-jsx-a11y": "^6.6.1",
"eslint-plugin-react": "^7.31.1",
"eslint-plugin-react-hooks": "^4.6.0",
"husky": "^8.0.1",
"lint-staged": "^13.0.3",
"live-server": "^1.2.2",
"npm-run-all": "^4.1.5"
"npm-run-all": "^4.1.5",
"prettier": "^2.7.1"
}
}
Loading

0 comments on commit 25161d6

Please sign in to comment.