Skip to content

Commit

Permalink
Start changing to es6 modules (#1530)
Browse files Browse the repository at this point in the history
* start changing to es6 modules

* change more files

* use e6s in more files.

* finish changing all the files under lib/ and tools/

* make npm run start & npm run live running

* make test using es6

* remove experimental flag, add function importJSON() in util.js

* Update app.js

Co-authored-by: Denis Ah-Kang <[email protected]>

Co-authored-by: Denis Ah-Kang <[email protected]>
  • Loading branch information
jennyliang220 and deniak authored Mar 16, 2022
1 parent 2716876 commit c418588
Show file tree
Hide file tree
Showing 169 changed files with 2,416 additions and 2,013 deletions.
3 changes: 3 additions & 0 deletions .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"badterms",
"Beihang",
"blocklist",
"capi",
"Çelik",
"charmod",
"CRYD",
Expand All @@ -14,6 +15,7 @@
"dcterms",
"deniak",
"DNOTE",
"doasync",
"doctypes",
"dvcs",
"ERCIM",
Expand All @@ -38,6 +40,7 @@
"linkchecker",
"mediacapture",
"memsub",
"metaviewport",
"middot",
"minami",
"nodate",
Expand Down
14 changes: 12 additions & 2 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
"global-require": "off",
"no-restricted-syntax": "warn",
"guard-for-in": "warn",
"prefer-destructuring": "warn"
"prefer-destructuring": "warn",
"import/prefer-default-export": "off",
"import/extensions": "off"
},
"overrides": [
{
Expand All @@ -25,6 +27,10 @@
{
"files": ["app.js", "lib/**/*.js", "tools/**/*.js"],
"plugins": ["node"],
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"extends": ["plugin:node/recommended", "plugin:jsdoc/recommended"]
},
{
Expand All @@ -36,7 +42,11 @@
"node/no-unpublished-require": "off"
},
"plugins": ["node"],
"extends": "plugin:node/recommended"
"extends": "plugin:node/recommended",
"parserOptions": {
"ecmaVersion": 2022,
"sourceType": "module"
}
}
]
}
52 changes: 23 additions & 29 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,21 @@
* Main runnable file.
*/

'use strict';
import compression from 'compression';
import cors from 'cors';
import express from 'express';
import http from 'http';
import insafe from 'insafe';
import morgan from 'morgan';
import { Server } from 'socket.io';
import * as api from './lib/api.js';
import * as l10n from './lib/l10n.js';
import { Sink } from './lib/sink.js';
import { allProfiles, importJSON } from './lib/util.js';
import { Specberus } from './lib/validator.js';
import * as views from './lib/views.js';

const { version } = importJSON('./package.json', import.meta.url);

// Settings:
const DEFAULT_PORT = 80;
Expand All @@ -19,33 +33,13 @@ if (!process.env.BASE_URI || process.env.BASE_URI.length < 1) {
);
}

// Native packages:
const http = require('http');

// External packages:
const compression = require('compression');
const express = require('express');
const insafe = require('insafe');
const morgan = require('morgan');
const socket = require('socket.io');
// Internal packages:
const self = require('./package.json');
const l10n = require('./lib/l10n');
const sink = require('./lib/sink');
const validator = require('./lib/validator');
const views = require('./lib/views');
const util = require('./lib/util');
const api = require('./lib/api');

const app = express();
const server = http.createServer(app);
const io = socket(server);
const { Sink } = sink;
const { version } = self;
const io = new Server(server);
// Middleware:
app.use(morgan('combined'));
app.use(compression());
app.use('/badterms.json', require('cors')());
app.use('/badterms.json', cors());

app.use(express.static('public'));
api.setUp(app, process.env.W3C_API_KEY);
Expand All @@ -61,7 +55,7 @@ io.on('connection', socket => {
socket.on('extractMetadata', data => {
if (!data.url)
return socket.emit('exception', { message: 'URL not provided.' });
const specberus = new validator.Specberus(process.env.W3C_API_KEY);
const specberus = new Specberus(process.env.W3C_API_KEY);
const handler = new Sink();
handler.on('err', (type, data) => {
try {
Expand Down Expand Up @@ -105,26 +99,26 @@ io.on('connection', socket => {
events: handler,
});
});
socket.on('validate', data => {
socket.on('validate', async data => {
if (!data.url)
return socket.emit('exception', { message: 'URL not provided.' });
if (!data.profile)
return socket.emit('exception', {
message: 'Profile not provided.',
});
const profilePath = util.allProfiles.find(p =>
const profilePath = allProfiles.find(p =>
p.endsWith(`/${data.profile}.js`)
);
let profile;
try {
// eslint-disable-next-line import/no-dynamic-require
profile = require(`./lib/profiles/${profilePath}`);
// eslint-disable-next-line node/no-unsupported-features/es-syntax
profile = await import(`./lib/profiles/${profilePath}`);
} catch (err) {
return socket.emit('exception', {
message: 'Profile does not exist.',
});
}
const specberus = new validator.Specberus(process.env.W3C_API_KEY);
const specberus = new Specberus(process.env.W3C_API_KEY);
const handler = new Sink();
const profileCode = profile.name;
socket.emit('start', {
Expand Down
29 changes: 13 additions & 16 deletions lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@
*/

// Internal packages:
const self = require('../package.json');
const sink = require('./sink');
const util = require('./util');
const validator = require('./validator');
import { Sink } from './sink.js';
import { buildJSONresult, importJSON, processParams } from './util.js';
import { Specberus } from './validator.js';

const { version } = importJSON('../package.json', import.meta.url);

const { Sink } = sink;
const { version } = self;
/**
* Send the JSON result to the client.
*
Expand All @@ -21,7 +20,7 @@ const { version } = self;
*/

const sendJSONresult = function (err, warn, inf, res, metadata) {
const wrapper = util.buildJSONresult(err, warn, inf, metadata);
const wrapper = buildJSONresult(err, warn, inf, metadata);
res.status(wrapper.success ? 200 : 400).json(wrapper);
};

Expand All @@ -30,7 +29,7 @@ const sendJSONresult = function (err, warn, inf, res, metadata) {
*
* @param {string} apiKey
*/
const processRequest = apiKey => (req, res) => {
const processRequest = apiKey => async (req, res) => {
if (req.path === '/api/version') {
res.status(200).send(version);
} else if (req.path === '/api/metadata' || req.path === '/api/validate') {
Expand All @@ -48,7 +47,7 @@ const processRequest = apiKey => (req, res) => {
let handler;
let handler2;
try {
options = util.processParams(req.query, undefined, {
options = await processParams(req.query, undefined, {
required: validate ? ['profile'] : [],
forbidden: ['document', 'source'],
});
Expand All @@ -57,7 +56,7 @@ const processRequest = apiKey => (req, res) => {
}
if (validate && options.profile === 'auto') {
errors = [];
v = new validator.Specberus(apiKey);
v = new Specberus(apiKey);
handler = new Sink(
(...data) => {
errors.push(Object.assign({}, ...data));
Expand All @@ -70,7 +69,7 @@ const processRequest = apiKey => (req, res) => {
if (options.url) meta.url = options.url;
else meta.file = options.file;
try {
options2 = util.processParams(meta, undefined, {
options2 = processParams(meta, undefined, {
allowUnknownParams: true,
});
} catch (err) {
Expand All @@ -86,7 +85,7 @@ const processRequest = apiKey => (req, res) => {
errors2 = [];
warnings2 = [];
info2 = [];
v2 = new validator.Specberus(apiKey);
v2 = new Specberus(apiKey);
handler2 = new Sink(
(...data2) => {
errors2.push(Object.assign({}, ...data2));
Expand Down Expand Up @@ -136,7 +135,7 @@ const processRequest = apiKey => (req, res) => {
errors = [];
warnings = [];
info = [];
v = new validator.Specberus(apiKey);
v = new Specberus(apiKey);
handler = new Sink(
(...data) => {
errors.push(Object.assign({}, ...data));
Expand Down Expand Up @@ -169,8 +168,6 @@ const processRequest = apiKey => (req, res) => {
}
};

const setUp = function (app, apiKey) {
export const setUp = function (app, apiKey) {
app.get('/api/*', processRequest(apiKey));
};

exports.setUp = setUp;
8 changes: 4 additions & 4 deletions lib/exceptions.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const records = require('./exceptions.json');
import { importJSON } from './util.js';

const records = importJSON('./exceptions.json', import.meta.url);

/**
* @param data
Expand Down Expand Up @@ -36,7 +38,7 @@ function findSet(shortname) {
return recursiveFindSet(shortname);
}

const Exceptions = function () {};
export const Exceptions = function () {};

Exceptions.prototype.has = function (shortname, rule, key, extra) {
const set = findSet(shortname);
Expand All @@ -58,5 +60,3 @@ Exceptions.prototype.has = function (shortname, rule, key, extra) {
}
return false;
};

exports.Exceptions = Exceptions;
2 changes: 1 addition & 1 deletion lib/l10n-en_GB.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable no-template-curly-in-string */
exports.messages = {
export const messages = {
// Generic
'generic.sotd.not-found':
'No <em>&ldquo;status of this document&rdquo;</em> section found. Some errors related to this one will be omitted from the output, but most likely this will cause further problems along the line.',
Expand Down
32 changes: 22 additions & 10 deletions lib/l10n.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
*/

// Internal packages:
const originalRules = require('./rules.json');
const english = require('./l10n-en_GB');
import { messages } from './l10n-en_GB.js';
import { importJSON } from './util.js';

const originalRules = importJSON('./rules.json', import.meta.url);

// Constants:
const enGB = english.messages;
const enGB = messages;

// Variables:
let lang;
Expand All @@ -24,7 +27,10 @@ for (const t in originalRules)
* @param {string} language - locale, expressed as a string, eg <code>en_GB</code>.
*/

exports.setLanguage = function (language) {
/**
* @param language
*/
export function setLanguage(language) {
if (!language)
throw new Error(
'l10n.setLanguage() invoked without passing a language code as parameter'
Expand All @@ -34,15 +40,15 @@ exports.setLanguage = function (language) {
throw new Error(
'Language code passed to l10n.setLanguage() is not valid'
);
};
}

/**
* @param profileCode
* @param rule
* @param key
* @param extra
*/
exports.assembleData = function (profileCode, rule, key, extra) {
export function assembleData(profileCode, rule, key, extra) {
const messageData = {};
// Corner case: if the profile is unknown, let's assume 'WD' (most common).
const profile = profileCode ? profileCode.replace('-Echidna', '') : 'WD';
Expand Down Expand Up @@ -81,11 +87,17 @@ to let developers examine the problem (you can submit it as is; no additional in
messageData.profile = profile;
return messageData;
}
};
}

exports.message = function (profileCode, rule, key, extra) {
/**
* @param profileCode
* @param rule
* @param key
* @param extra
*/
export function message(profileCode, rule, key, extra) {
const result = {};
const messageData = exports.assembleData(profileCode, rule, key, extra);
const messageData = assembleData(profileCode, rule, key, extra);
if (!messageData) return;
result.message =
messageData.message && messageData.message.length
Expand Down Expand Up @@ -158,4 +170,4 @@ ${selector}&labels=from-template">file this issue on GitHub</a> to help develope
if (messageData.additionalMessage)
result.message += messageData.additionalMessage;
return result;
};
}
13 changes: 5 additions & 8 deletions lib/profiles/SUBM.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
// Base profile for all Submissions
import * as submLogo from '../rules/headers/subm-logo.js';
import { rules as baseRules } from './base.js';
import { insertAfter } from './profileUtil.js';

exports.name = 'Submission';
export const name = 'Submission';

const profileUtil = require('./profileUtil');

exports.rules = profileUtil.insertAfter(
require('./base').rules,
'headers.logo',
require('../rules/headers/subm-logo')
);
export const rules = insertAfter(baseRules, 'headers.logo', submLogo);
Loading

0 comments on commit c418588

Please sign in to comment.