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

chore: add eslint #22

Merged
merged 7 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,6 @@ jobs:

- name: Run e2e tests
run: bun run test.e2e

- name: Run lint
run: bun run lint
10 changes: 10 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"printWidth": 99,
"semi": true,
"useTabs": false,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true,
"arrowParens": "always",
"quoteProps": "preserve"
}
Binary file modified bun.lockb
Binary file not shown.
24 changes: 24 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import globals from 'globals';
import pluginJs from '@eslint/js';
import pluginPrettier from 'eslint-plugin-prettier/recommended';

export default [
{
files: ['**/*.js'],
languageOptions: {
globals: {
...globals.node,
...globals.browser,
Bun: 'readonly',
},
parserOptions: {
ecmaVersion: 'latest',
},
},
},
pluginJs.configs.recommended,
pluginPrettier,
{
ignores: ['node_modules/*', 'dist/*'],
},
];
13 changes: 11 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,28 @@
"author": "Ghostery GmbH.",
"description": "Converts urlfilters to DNR format",
"license": "GPL-3.0",
"type": "module",
"scripts": {
"build": "bun ./scripts/build.js",
"serve": "bun --watch scripts/serve.js",
"test.unit": "bun test test/unit",
"test.e2e": "playwright test test/e2e/index.spec.js"
"test.e2e": "playwright test test/e2e/index.spec.js",
"lint": "eslint"
},
"dependencies": {
"@adguard/scriptlets": "^1.12.1",
"@adguard/tsurlfilter": "2.2.23",
"@eyeo/webext-ad-filtering-solution": "1.5.0"
},
"devDependencies": {
"@eslint/js": "^9.13.0",
"@ghostery/trackerdb": "^1.0.208",
"@playwright/test": "^1.45.3"
"@playwright/test": "^1.45.3",
"@types/bun": "^1.1.11",
"eslint": "^9.13.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
"globals": "^15.11.0",
"prettier": "^3.3.3"
}
}
2 changes: 1 addition & 1 deletion scripts/build.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import build from "./helpers/build.js";
import build from './helpers/build.js';

const startAt = Date.now();

Expand Down
20 changes: 8 additions & 12 deletions scripts/helpers/build.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,27 @@
import fs from "node:fs";
import path from "node:path";
import fs from 'node:fs';
import path from 'node:path';

import { SOURCE_PATH, DIST_PATH } from "./paths.js";
import { SOURCE_PATH, DIST_PATH } from './paths.js';

export default async function build({ debug = false } = {}) {
fs.rmSync(DIST_PATH, { recursive: true, force: true });
fs.mkdirSync(DIST_PATH);
fs.copyFileSync(
path.join(SOURCE_PATH, "index.html"),
path.join(DIST_PATH, "index.html")
);
fs.copyFileSync(path.join(SOURCE_PATH, 'index.html'), path.join(DIST_PATH, 'index.html'));

const result = await Bun.build({
entrypoints: [path.join(SOURCE_PATH, "index.js")],
entrypoints: [path.join(SOURCE_PATH, 'index.js')],
outdir: DIST_PATH,
target: "browser",
target: 'browser',
minify: !debug,
sourcemap: debug ? "inline" : "external",
sourcemap: debug ? 'inline' : 'external',
});

if (!result.success) {
console.error("Build failed");
console.error('Build failed');
for (const message of result.logs) {
// Bun will pretty print the message object
console.error(message);
}
throw new Error(result.logs.join('\n'));
}
}

8 changes: 4 additions & 4 deletions scripts/helpers/paths.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from "node:path";
import path from 'node:path';

export const ROOT_PATH = path.join(import.meta.dir, "..", "..");
export const DIST_PATH = path.join(ROOT_PATH, "dist");
export const SOURCE_PATH = path.join(ROOT_PATH, "src");
export const ROOT_PATH = path.join(import.meta.dir, '..', '..');
export const DIST_PATH = path.join(ROOT_PATH, 'dist');
export const SOURCE_PATH = path.join(ROOT_PATH, 'src');
35 changes: 16 additions & 19 deletions scripts/serve.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,30 @@
import { watch } from "node:fs";
import path from "node:path";
import { watch } from 'node:fs';
import path from 'node:path';

import build from "./helpers/build.js";
import { SOURCE_PATH, DIST_PATH } from "./helpers/paths.js";
import build from './helpers/build.js';
import { SOURCE_PATH, DIST_PATH } from './helpers/paths.js';

const PORT = 3000;

await build();

const watcher = watch(
SOURCE_PATH,
{ recursive: true },
async (event, filename) => {
console.log(`Detected ${event} in ${filename}`);
try {
await build({ debug: true });
} catch (e) {
// no need to do anything as build logs errors already
}
const watcher = watch(SOURCE_PATH, { recursive: true }, async (event, filename) => {
console.log(`Detected ${event} in ${filename}`);
try {
await build({ debug: true });
// eslint-disable-next-line no-unused-vars
} catch (e) {
// no need to do anything as build logs errors already
}
);
});

Bun.serve({
port: PORT,
development: true,
async fetch(req) {
let filePath = new URL(req.url).pathname;
if (filePath === "/") {
filePath += "index.html";
if (filePath === '/') {
filePath += 'index.html';
}
const file = Bun.file(path.join(DIST_PATH, filePath));
return new Response(file);
Expand All @@ -39,9 +36,9 @@ Bun.serve({

console.log(`Starting dev server at port: ${PORT}`);

process.on("SIGINT", () => {
process.on('SIGINT', () => {
// close watcher when Ctrl-C is pressed
console.log("Closing server...");
console.log('Closing server...');
watcher.close();

process.exit(0);
Expand Down
27 changes: 11 additions & 16 deletions scripts/update.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { writeFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { writeFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

import adguardDialects from "@adguard/scriptlets/dist/redirects.json" with { type: "json" };
import adguardDialects from '@adguard/scriptlets/dist/redirects.json';

const CWD = dirname(fileURLToPath(import.meta.url));

async function downloadResource(resourceName) {
console.log("Downloading resources...");
console.log('Downloading resources...');

const { revisions } = await fetch(
`https://cdn.ghostery.com/adblocker/resources/${resourceName}/metadata.json`,
Expand All @@ -24,22 +24,17 @@ async function downloadResource(resourceName) {
`https://cdn.ghostery.com/adblocker/resources/${resourceName}/${latestRevision}/list.txt`,
).then((result) => {
if (!result.ok) {
throw new Error(
`Failed to fetch ${resourceName}: ${result.status}: ${result.statusText}`,
);
throw new Error(`Failed to fetch ${resourceName}: ${result.status}: ${result.statusText}`);
}
return result.text();
});
}

function extractRedirects(data) {
console.log("Extracting resources...");
console.log('Extracting resources...');

const resources = JSON.parse(data);
const mappings = resources.redirects.map((redirect) => [
redirect.name,
redirect.aliases ?? [],
]);
const mappings = resources.redirects.map((redirect) => [redirect.name, redirect.aliases ?? []]);

// Integrate adguard mappings
for (const dialect of adguardDialects) {
Expand Down Expand Up @@ -77,7 +72,7 @@ function extractRedirects(data) {
}

writeFileSync(
join(CWD, "..", "src", "mappings.json"),
extractRedirects(await downloadResource("ublock-resources-json")),
"utf-8",
join(CWD, '..', 'src', 'mappings.json'),
extractRedirects(await downloadResource('ublock-resources-json')),
'utf-8',
);
11 changes: 7 additions & 4 deletions src/converters/abp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { FilterParsingError, normalize } from "@eyeo/webext-ad-filtering-solution/adblockpluscore/lib/filters/index.js";
import { createConverter } from "@eyeo/webext-ad-filtering-solution/adblockpluscore/lib/dnr/index.js";
import { normalizeFilter, normalizeRule, DEFAULT_PARAM_MAPPING } from "./helpers";
import {
FilterParsingError,
normalize,
} from '@eyeo/webext-ad-filtering-solution/adblockpluscore/lib/filters/index.js';
import { createConverter } from '@eyeo/webext-ad-filtering-solution/adblockpluscore/lib/dnr/index.js';
import { normalizeFilter, normalizeRule, DEFAULT_PARAM_MAPPING } from './helpers';

const PARAM_MAPPING = {
...DEFAULT_PARAM_MAPPING,
Expand All @@ -27,7 +30,7 @@ export default async function convert(filters) {
rules.push(rule);
}
} else {
throw new Error("Unknown problem");
throw new Error('Unknown problem');
}
} catch (e) {
errors.push(`Error: "${e.message}" in rule: "${filter}"`);
Expand Down
16 changes: 5 additions & 11 deletions src/converters/adguard.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import { DeclarativeFilterConverter, Filter } from "@adguard/tsurlfilter/es/declarative-converter";
import { normalizeFilter, normalizeRule } from "./helpers.js";
import { DeclarativeFilterConverter, Filter } from '@adguard/tsurlfilter/es/declarative-converter';
import { normalizeFilter, normalizeRule } from './helpers.js';

const converter = new DeclarativeFilterConverter();

const createFilter = (
rules,
filterId = 0,
) => {
return new Filter(
filterId,
{ getContent: async () => rules },
);
const createFilter = (rules, filterId = 0) => {
return new Filter(filterId, { getContent: async () => rules });
};

export default async function convert(rules, { resourcesPath } = {}) {
Expand All @@ -19,7 +13,7 @@ export default async function convert(rules, { resourcesPath } = {}) {
const declarativeRules = await conversionResult.ruleSet.getDeclarativeRules();

return {
rules: declarativeRules.map(rule => normalizeRule(rule)),
rules: declarativeRules.map((rule) => normalizeRule(rule)),
errors: conversionResult.errors,
limitations: conversionResult.limitations,
};
Expand Down
Loading
Loading