Skip to content

Commit

Permalink
Merge pull request #3902 from naturalcrit/updateToES6Modules
Browse files Browse the repository at this point in the history
Upgrade server-side code to ESM (import vs require)
  • Loading branch information
calculuschild authored Nov 21, 2024
2 parents b7c4921 + e562443 commit 2e49bf4
Show file tree
Hide file tree
Showing 49 changed files with 239 additions and 227 deletions.
2 changes: 1 addition & 1 deletion client/homebrew/brewRenderer/brewRenderer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { useState, useRef, useCallback, useMemo } = React;
const _ = require('lodash');

const MarkdownLegacy = require('naturalcrit/markdownLegacy.js');
const Markdown = require('naturalcrit/markdown.js');
import Markdown from 'naturalcrit/markdown.js';
const ErrorBar = require('./errorBar/errorBar.jsx');
const ToolBar = require('./toolBar/toolBar.jsx');

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
require('./notificationPopup.less');
import React, { useEffect, useState } from 'react';
const request = require('../../utils/request-middleware.js');
import request from '../../utils/request-middleware.js';

import Dialog from '../../../components/dialog.jsx';

Expand Down
2 changes: 1 addition & 1 deletion client/homebrew/editor/editor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const React = require('react');
const createClass = require('create-react-class');
const _ = require('lodash');
const dedent = require('dedent-tabs').default;
const Markdown = require('../../../shared/naturalcrit/markdown.js');
import Markdown from '../../../shared/naturalcrit/markdown.js';

const CodeEditor = require('naturalcrit/codeEditor/codeEditor.jsx');
const SnippetBar = require('./snippetbar/snippetbar.jsx');
Expand Down
2 changes: 1 addition & 1 deletion client/homebrew/editor/metadataEditor/metadataEditor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ require('./metadataEditor.less');
const React = require('react');
const createClass = require('create-react-class');
const _ = require('lodash');
const request = require('../../utils/request-middleware.js');
import request from '../../utils/request-middleware.js';
const Nav = require('naturalcrit/nav/nav.jsx');
const Combobox = require('client/components/combobox.jsx');
const TagInput = require('../tagInput/tagInput.jsx');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ require('./brewItem.less');
const React = require('react');
const createClass = require('create-react-class');
const moment = require('moment');
const request = require('../../../../utils/request-middleware.js');
import request from '../../../../utils/request-middleware.js';

const googleDriveIcon = require('../../../../googleDrive.svg');
const homebreweryIcon = require('../../../../thumbnail.png');
Expand Down
4 changes: 2 additions & 2 deletions client/homebrew/pages/editPage/editPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const React = require('react');
const _ = require('lodash');
const createClass = require('create-react-class');

const request = require('../../utils/request-middleware.js');
import request from '../../utils/request-middleware.js';
const { Meta } = require('vitreum/headtags');

const Nav = require('naturalcrit/nav/nav.jsx');
Expand All @@ -23,7 +23,7 @@ const BrewRenderer = require('../../brewRenderer/brewRenderer.jsx');

const LockNotification = require('./lockNotification/lockNotification.jsx');

const Markdown = require('naturalcrit/markdown.js');
import Markdown from 'naturalcrit/markdown.js';

const { DEFAULT_BREW_LOAD } = require('../../../../server/brewDefaults.js');
const { printCurrentBrew, fetchThemeBundle } = require('../../../../shared/helpers.js');
Expand Down
2 changes: 1 addition & 1 deletion client/homebrew/pages/errorPage/errorPage.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
require('./errorPage.less');
const React = require('react');
const UIPage = require('../basePages/uiPage/uiPage.jsx');
const Markdown = require('../../../../shared/naturalcrit/markdown.js');
import Markdown from '../../../../shared/naturalcrit/markdown.js';
const ErrorIndex = require('./errors/errorIndex.js');

const ErrorPage = ({ brew })=>{
Expand Down
2 changes: 1 addition & 1 deletion client/homebrew/pages/homePage/homePage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ require('./homePage.less');
const React = require('react');
const createClass = require('create-react-class');
const cx = require('classnames');
const request = require('../../utils/request-middleware.js');
import request from '../../utils/request-middleware.js';
const { Meta } = require('vitreum/headtags');

const Nav = require('naturalcrit/nav/nav.jsx');
Expand Down
4 changes: 2 additions & 2 deletions client/homebrew/pages/newPage/newPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
require('./newPage.less');
const React = require('react');
const createClass = require('create-react-class');
const request = require('../../utils/request-middleware.js');
import request from '../../utils/request-middleware.js';

const Markdown = require('naturalcrit/markdown.js');
import Markdown from 'naturalcrit/markdown.js';

const Nav = require('naturalcrit/nav/nav.jsx');
const PrintNavItem = require('../../navbar/print.navitem.jsx');
Expand Down
2 changes: 1 addition & 1 deletion client/homebrew/pages/vaultPage/vaultPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const BrewItem = require('../basePages/listPage/brewItem/brewItem.jsx');
const SplitPane = require('../../../../shared/naturalcrit/splitPane/splitPane.jsx');
const ErrorIndex = require('../errorPage/errors/errorIndex.js');

const request = require('../../utils/request-middleware.js');
import request from '../../utils/request-middleware.js';

const VaultPage = (props)=>{
const [pageState, setPageState] = useState(parseInt(props.query.page) || 1);
Expand Down
4 changes: 2 additions & 2 deletions client/homebrew/utils/request-middleware.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const request = require('superagent');
import request from 'superagent';

const addHeader = (request)=>request.set('Homebrewery-Version', global.version);

Expand All @@ -9,4 +9,4 @@ const requestMiddleware = {
delete : (path)=>addHeader(request.delete(path)),
};

module.exports = requestMiddleware;
export default requestMiddleware;
6 changes: 4 additions & 2 deletions client/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ const template = async function(name, title='', props = {}){
});
const ogMetaTags = ogTags.join('\n');

const ssrModule = await import(`../build/${name}/ssr.cjs`);

return `<!DOCTYPE html>
<html>
<head>
Expand All @@ -21,12 +23,12 @@ const template = async function(name, title='', props = {}){
<title>${title.length ? `${title} - The Homebrewery`: 'The Homebrewery - NaturalCrit'}</title>
</head>
<body>
<main id="reactRoot">${require(`../build/${name}/ssr.js`)(props)}</main>
<main id="reactRoot">${ssrModule.default(props)}</main>
<script src=${`/${name}/bundle.js`}></script>
<script>start_app(${JSON.stringify(props)})</script>
</body>
</html>
`;
};

module.exports = template;
export default template;
23 changes: 23 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "homebrewery",
"description": "Create authentic looking D&D homebrews using only markdown",
"version": "3.16.0",
"type": "module",
"engines": {
"npm": "^10.2.x",
"node": "^20.18.x"
Expand Down Expand Up @@ -83,7 +84,8 @@
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-transform-runtime"
"@babel/plugin-transform-runtime",
"babel-plugin-transform-import-meta"
]
},
"dependencies": {
Expand Down Expand Up @@ -129,6 +131,7 @@
},
"devDependencies": {
"@stylistic/stylelint-plugin": "^3.1.1",
"babel-plugin-transform-import-meta": "^2.2.1",
"eslint": "^9.14.0",
"eslint-plugin-jest": "^28.9.0",
"eslint-plugin-react": "^7.37.2",
Expand Down
17 changes: 9 additions & 8 deletions scripts/buildAdmin.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
const fs = require('fs-extra');
const Proj = require('./project.json');

const { pack } = require('vitreum');
const isDev = !!process.argv.find((arg)=>arg=='--dev');
import fs from 'fs-extra';
import Proj from './project.json' with { type: 'json' };
import vitreum from 'vitreum';
const { pack } = vitreum;

import lessTransform from 'vitreum/transforms/less.js';
import assetTransform from 'vitreum/transforms/asset.js';

const lessTransform = require('vitreum/transforms/less.js');
const assetTransform = require('vitreum/transforms/asset.js');
//const Meta = require('vitreum/headtags');
const isDev = !!process.argv.find((arg)=>arg=='--dev');

const transforms = {
'.less' : lessTransform,
Expand All @@ -17,7 +18,7 @@ const build = async ({ bundle, render, ssr })=>{
const css = await lessTransform.generate({ paths: './shared' });
await fs.outputFile('./build/admin/bundle.css', css);
await fs.outputFile('./build/admin/bundle.js', bundle);
await fs.outputFile('./build/admin/ssr.js', ssr);
await fs.outputFile('./build/admin/ssr.cjs', ssr);
};

fs.emptyDirSync('./build/admin');
Expand Down
29 changes: 15 additions & 14 deletions scripts/buildHomebrew.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
const fs = require('fs-extra');
const zlib = require('zlib');
const Proj = require('./project.json');
import fs from 'fs-extra';
import zlib from 'zlib';
import Proj from './project.json' with { type: 'json' };
import vitreum from 'vitreum';
const { pack, watchFile, livereload } = vitreum;

const { pack, watchFile, livereload } = require('vitreum');
const isDev = !!process.argv.find((arg)=>arg=='--dev');
import lessTransform from 'vitreum/transforms/less.js';
import assetTransform from 'vitreum/transforms/asset.js';
import babel from '@babel/core';
import less from 'less';

const lessTransform = require('vitreum/transforms/less.js');
const assetTransform = require('vitreum/transforms/asset.js');
const babel = require('@babel/core');
const less = require('less');
const isDev = !!process.argv.find((arg) => arg === '--dev');

const babelify = async (code)=>(await babel.transformAsync(code, { presets: [['@babel/preset-env', { 'exclude': ['proposal-dynamic-import'] }], '@babel/preset-react'], plugins: ['@babel/plugin-transform-runtime'] })).code;

Expand All @@ -24,7 +25,7 @@ const build = async ({ bundle, render, ssr })=>{
//css = `@layer bundle {\n${css}\n}`;
await fs.outputFile('./build/homebrew/bundle.css', css);
await fs.outputFile('./build/homebrew/bundle.js', bundle);
await fs.outputFile('./build/homebrew/ssr.js', ssr);
await fs.outputFile('./build/homebrew/ssr.cjs', ssr);

await fs.copy('./client/homebrew/favicon.ico', './build/assets/favicon.ico');

Expand All @@ -51,7 +52,7 @@ fs.emptyDirSync('./build');
const themes = { Legacy: {}, V3: {} };

let themeFiles = fs.readdirSync('./themes/Legacy');
for (dir of themeFiles) {
for (let dir of themeFiles) {
const themeData = JSON.parse(fs.readFileSync(`./themes/Legacy/${dir}/settings.json`).toString());
themeData.path = dir;
themes.Legacy[dir] = (themeData);
Expand All @@ -68,7 +69,7 @@ fs.emptyDirSync('./build');
}

themeFiles = fs.readdirSync('./themes/V3');
for (dir of themeFiles) {
for (let dir of themeFiles) {
const themeData = JSON.parse(fs.readFileSync(`./themes/V3/${dir}/settings.json`).toString());
themeData.path = dir;
themes.V3[dir] = (themeData);
Expand Down Expand Up @@ -104,14 +105,14 @@ fs.emptyDirSync('./build');
const editorThemesBuildDir = './build/homebrew/cm-themes';
await fs.copy('./node_modules/codemirror/theme', editorThemesBuildDir);
await fs.copy('./themes/codeMirror/customThemes', editorThemesBuildDir);
editorThemeFiles = fs.readdirSync(editorThemesBuildDir);
const editorThemeFiles = fs.readdirSync(editorThemesBuildDir);

const editorThemeFile = './themes/codeMirror/editorThemes.json';
if(fs.existsSync(editorThemeFile)) fs.rmSync(editorThemeFile);
const stream = fs.createWriteStream(editorThemeFile, { flags: 'a' });
stream.write('[\n"default"');

for (themeFile of editorThemeFiles) {
for (let themeFile of editorThemeFiles) {
stream.write(`,\n"${themeFile.slice(0, -4)}"`);
}
stream.write('\n]\n');
Expand Down
8 changes: 4 additions & 4 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
const DB = require('./server/db.js');
const server = require('./server/app.js');
const config = require('./server/config.js');
import DB from './server/db.js';
import server from './server/app.js';
import config from './server/config.js';

DB.connect(config).then(()=>{
// Ensure that we have successfully connected to the database
// before launching server
const PORT = process.env.PORT || config.get('web_port') || 8000;
server.app.listen(PORT, ()=>{
server.listen(PORT, ()=>{
const reset = '\x1b[0m'; // Reset to default style
const bright = '\x1b[1m'; // Bright (bold) style
const cyan = '\x1b[36m'; // Cyan color
Expand Down
22 changes: 12 additions & 10 deletions server/admin.api.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
const HomebrewModel = require('./homebrew.model.js').model;
const NotificationModel = require('./notifications.model.js').model;
const router = require('express').Router();
const Moment = require('moment');
const templateFn = require('../client/template.js');
const zlib = require('zlib');
import {model as HomebrewModel } from './homebrew.model.js';
import {model as NotificationModel } from './notifications.model.js';
import express from 'express';
import Moment from 'moment';
import zlib from 'zlib';
import templateFn from '../client/template.js';

const HomebrewAPI = require('./homebrew.api.js');
const asyncHandler = require('express-async-handler');
const { splitTextStyleAndMetadata } = require('../shared/helpers.js');
import HomebrewAPI from './homebrew.api.js';
import asyncHandler from 'express-async-handler';
import { splitTextStyleAndMetadata } from '../shared/helpers.js';

const router = express.Router();

process.env.ADMIN_USER = process.env.ADMIN_USER || 'admin';
process.env.ADMIN_PASS = process.env.ADMIN_PASS || 'password3';
Expand Down Expand Up @@ -190,4 +192,4 @@ router.get('/admin', mw.adminOnly, (req, res)=>{
});
});

module.exports = router;
export default router;
9 changes: 5 additions & 4 deletions server/admin.api.spec.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
const supertest = require('supertest');
import supertest from 'supertest';
import HBApp from './app.js';
import {model as NotificationModel } from './notifications.model.js';

const app = supertest.agent(require('app.js').app)
.set('X-Forwarded-Proto', 'https');

const NotificationModel = require('./notifications.model.js').model;
// Mimic https responses to avoid being redirected all the time
const app = supertest.agent(HBApp).set('X-Forwarded-Proto', 'https');

describe('Tests for admin api', ()=>{
afterEach(()=>{
Expand Down
Loading

0 comments on commit 2e49bf4

Please sign in to comment.