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

Update reveal-md to ES modules and updated all dependencies #465

Merged
merged 3 commits into from
Nov 5, 2023
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
7 changes: 7 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
root = true

[*]
charset = utf-8
indent_size = 2
indent_style = space
insert_final_newline = true
22 changes: 12 additions & 10 deletions bin/reveal-md.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
#!/usr/bin/env node

const argsParser = require('yargs-parser');
const updater = require('update-notifier');
const path = require('path');
const fs = require('fs-extra');
const open = require('open');
const pkg = require('../package.json');
const startServer = require('../lib/server');
const writeStatic = require('../lib/static');
const exportPDF = require('../lib/print');
import argsParser from 'yargs-parser';
import updater from 'update-notifier';
import path from 'path';
import { readFile } from 'node:fs/promises';
import open from 'open';
import startServer from '../lib/server.js';
import writeStatic from '../lib/static.js';
import exportPDF from '../lib/print.js';
import pkg from '../package.json' assert { type: 'json' };

const __dirname = new URL('.', import.meta.url).pathname;

const alias = {
h: 'help',
Expand Down Expand Up @@ -56,7 +58,7 @@ updater({ pkg }).notify();
process.exit(1);
}
} else {
const help = await fs.readFile(path.join(__dirname, './help.txt'));
const help = await readFile(path.join(__dirname, './help.txt'));
console.log(help.toString());
}
})();
111 changes: 73 additions & 38 deletions lib/config.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,44 @@
const path = require('path');
const _ = require('lodash');
const fs = require('fs-extra');
const defaults = require('./defaults.json');
const parseArgs = require('yargs-parser');
const url = require('url');
const glob = require('glob');
const { isDirectory, isFile, isAbsoluteURL, tryReadJson5Configs } = require('./util');
import path from 'node:path';
import _ from 'lodash';
import { readFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import * as fs from 'fs-extra';
import parseArgs from 'yargs-parser';
import url from 'node:url';
import { globSync } from 'glob';
import defaultsJson from './defaults.json' assert { type: 'json' };
import { isDirectory, isFile, isAbsoluteURL, tryReadJson5Configs } from './util.js';

const __filename = new URL('', import.meta.url).pathname;
const __dirname = new URL('.', import.meta.url).pathname;

export const defaults = defaultsJson;

let localConfig = undefined;
try {
localConfig = JSON.parse(readFileSync(path.join(process.cwd(), 'reveal-md.json')));
} catch (e) {
if (e.code !== 'ENOENT') {
console.log(e);
}
}

let revealConfig = undefined;
try {
revealConfig = JSON.parse(readFileSync(path.join(process.cwd(), 'reveal.json')));
} catch (e) {
if (e.code !== 'ENOENT') {
console.log(e);
}
}

export const revealBasePath = path.resolve(new URL(import.meta.resolve('reveal.js')).pathname, '..', '..');
export const highlightThemePath = path.resolve(
new URL(import.meta.resolve('highlight.js')).pathname,
'..',
'..',
'styles'
);

const localConfig = tryReadJson5Configs(
path.join(process.cwd(), 'reveal-md.json5'),
Expand All @@ -31,42 +64,42 @@ const cliConfig = parseArgs(process.argv.slice(2), {

const mergedConfig = _.defaults({}, cliConfig, localConfig, defaults);

const revealThemes = glob.sync('dist/theme/*.css', { cwd: revealBasePath });
const revealThemes = globSync('dist/theme/*.css', { cwd: revealBasePath });

const getAssetPath = (asset, assetsDir = defaults.assetsDir, base) =>
isAbsoluteURL(asset) ? asset : `${base || ''}/${assetsDir}/${asset}`;

const getAssetPaths = (assets, assetsDir, base) =>
(typeof assets === 'string' ? assets.split(',') : assets).map(assetPath => getAssetPath(assetPath, assetsDir, base));

const getPath = () => cliConfig._[0] || '.';
// Exports ---------------------------------------------------------------------

const getInitialDir = async () => {
export const getPath = () => cliConfig._[0] || '.';

export const getInitialDir = async () => {
const dir = path.resolve(getPath());
return (await isDirectory(dir)) ? dir : path.dirname(dir);
};

module.exports.getPath = getPath;
module.exports.getInitialDir = getInitialDir;
module.exports.getInitialPath = async () => path.relative(await getInitialDir(), getPath());
module.exports.getAssetsDir = () => mergedConfig.assetsDir;
module.exports.getStaticDir = () => (mergedConfig.static === true ? mergedConfig.staticDir : mergedConfig.static);
module.exports.getHost = () => mergedConfig.host;
module.exports.getPort = () => mergedConfig.port;
module.exports.getWatch = () => Boolean(mergedConfig.watch);
module.exports.getFilesGlob = () => mergedConfig.glob;
export const getInitialPath = async () => path.relative(await getInitialDir(), getPath());
export const getAssetsDir = () => mergedConfig.assetsDir;
export const getStaticDir = () => (mergedConfig.static === true ? mergedConfig.staticDir : mergedConfig.static);
export const getHost = () => mergedConfig.host;
export const getPort = () => mergedConfig.port;
export const getWatch = () => Boolean(mergedConfig.watch);
export const getFilesGlob = () => mergedConfig.glob;

module.exports.getOptions = () => mergedConfig;
export const getOptions = () => mergedConfig;

module.exports.getSlideOptions = options => {
export const getSlideOptions = options => {
return _.defaults({}, cliConfig, options, localConfig, defaults);
};

module.exports.getRevealOptions = options => {
export const getRevealOptions = options => {
return _.defaults({}, options, revealConfig);
};

module.exports.getThemeUrl = (theme, assetsDir, base) => {
export const getThemeUrl = (theme, assetsDir, base) => {
const parsedUrl = url.parse(theme);
if (parsedUrl.host) {
return theme;
Expand All @@ -78,46 +111,48 @@ module.exports.getThemeUrl = (theme, assetsDir, base) => {
}
};

module.exports.getHighlightThemeUrl = highlightTheme => '/css/highlight/' + highlightTheme + '.css';
export const getHighlightThemeUrl = highlightTheme => '/css/highlight/' + highlightTheme + '.css';

module.exports.getScriptPaths = (scripts, assetsDir, base) => getAssetPaths(scripts, assetsDir, base);
module.exports.getCssPaths = (css, assetsDir, base) => getAssetPaths(css, assetsDir, base);
export const getScriptPaths = (scripts, assetsDir, base) => getAssetPaths(scripts, assetsDir, base);
export const getCssPaths = (css, assetsDir, base) => getAssetPaths(css, assetsDir, base);

module.exports.getTemplate = async template => {
export const getTemplate = async template => {
const base = defaults.template === template ? __dirname : process.cwd();
const contents = await fs.readFile(path.join(base, template));
const contents = await readFile(path.join(base, template));
return contents.toString();
};

module.exports.getListingTemplate = async template => {
export const getListingTemplate = async template => {
const base = defaults.listingTemplate === template ? __dirname : process.cwd();
const contents = await fs.readFile(path.join(base, template));
const contents = await readFile(path.join(base, template));
return contents.toString();
};

module.exports.getFaviconPath = async () => {
export const getFaviconPath = async () => {
const initialDir = await getInitialDir();
const faviconPath = path.join(initialDir, 'favicon.ico');
const hasFavicon = (await fs.pathExists(faviconPath)) && isFile(faviconPath);
return hasFavicon ? faviconPath : path.join(__dirname, 'favicon.ico');
};

module.exports.getPreprocessor = preprocessor => {
if (preprocessor && !path.isAbsolute(preprocessor)) {
preprocessor = path.join(process.cwd(), preprocessor);
export const getPreprocessor = async preprocessor => {
if (preprocessor) {
const { default: defaultFunc } = await import(preprocessor);
return defaultFunc;
}
return preprocessor ? require(preprocessor) : _.identity;

return _.identity;
};

module.exports.getPuppeteerLaunchConfig = () => {
export const getPuppeteerLaunchConfig = () => {
const { puppeteerLaunchArgs, puppeteerChromiumExecutable } = mergedConfig;
return {
args: puppeteerLaunchArgs ? puppeteerLaunchArgs.split(' ') : [],
executablePath: puppeteerChromiumExecutable || null
};
};

module.exports.getPageOptions = printSize => {
export const getPageOptions = printSize => {
if (printSize) {
const dimensions = printSize.match(/^([\d.]+)x([\d.]+)([a-z]*)$/);
if (dimensions) {
Expand Down
4 changes: 0 additions & 4 deletions lib/constants.js

This file was deleted.

15 changes: 9 additions & 6 deletions lib/featured-slide.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
/* eslint-disable no-console */
const _ = require('lodash');
const debug = require('debug')('reveal-md');
const { getHost, getPort, getOptions, getPuppeteerLaunchConfig } = require('./config');
import _ from 'lodash';
import createDebug from 'debug';
import { getHost, getPort, getOptions, getPuppeteerLaunchConfig } from './config.js';

const debug = createDebug('reveal-md');

const host = getHost();
const port = getPort();

let puppeteer;

try {
puppeteer = require('puppeteer');
puppeteer = await import('puppeteer');
} catch (err) {
console.warn(`Puppeteer unavailable, unable to create featured slide image for OpenGraph metadata.`);
debug(err);
Expand All @@ -20,7 +21,9 @@ const getSlideAnchor = featuredSlide => {
return `${isNaN(slide) ? '' : '#/' + slide + (isNaN(subslide) ? '' : '/' + subslide)}`;
};

module.exports = async (initialUrl, targetDir) => {
// Exports ---------------------------------------------------------------------

export default async (initialUrl, targetDir) => {
const { featuredSlide } = getOptions();

if (!featuredSlide || !puppeteer) {
Expand Down
23 changes: 12 additions & 11 deletions lib/listing.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
const Mustache = require('mustache');
const path = require('path');
const { getInitialDir, getOptions, getListingTemplate, getThemeUrl, getFilesGlob } = require('./config');
const { getFilePaths, parseYamlFrontMatter } = require('./util');
const fs = require('fs-extra');
import Mustache from 'mustache';
import path from 'node:path';
import { getInitialDir, getOptions, getListingTemplate, getThemeUrl, getFilesGlob } from './config.js';
import { getFilePaths, parseYamlFrontMatter } from './util.js';
import { readFile } from 'node:fs/promises';

const getFileMeta = async filePath => {
const baseDir = await getInitialDir();
const markdownFilePath = path.join(baseDir, filePath).replace(/\.html$/, '.md');
let yamlOptions = {};
try {
const markdown = (await fs.readFile(markdownFilePath)).toString();
const markdown = (await readFile(markdownFilePath)).toString();
yamlOptions = parseYamlFrontMatter(markdown).yamlOptions;
} catch (error) {
console.error(error);
Expand All @@ -24,11 +24,14 @@ const getFileMeta = async filePath => {
);
};

const renderListFile = async filePaths => {
// Exports ---------------------------------------------------------------------

export const renderListFile = async filePaths => {
const { title, listingTemplate, theme, assetsDir } = getOptions();
const template = await getListingTemplate(listingTemplate);
const themeUrl = getThemeUrl(theme, assetsDir, '.');
const files = await Promise.all(filePaths.map(getFileMeta));
let files = await Promise.all(filePaths.map(getFileMeta));
files.sort((a, b) => a.fileName.localeCompare(b.fileName));
return Mustache.render(template, {
base: '',
themeUrl,
Expand All @@ -38,11 +41,9 @@ const renderListFile = async filePaths => {
});
};

module.exports = async (req, res) => {
export default async (req, res) => {
const list = getFilePaths(await getInitialDir(), getFilesGlob());
const markup = await renderListFile(list);

res.send(markup);
};

module.exports.renderListFile = renderListFile;
17 changes: 10 additions & 7 deletions lib/print.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
/* eslint-disable no-console */
const path = require('path');
const debug = require('debug')('reveal-md');
const { revealBasePath } = require('./constants');
const { getPuppeteerLaunchConfig, getPageOptions } = require('./config');
let puppeteer;
import path from 'node:path';
import createDebug from 'debug';
import { getPuppeteerLaunchConfig, getPageOptions, revealBasePath } from './config.js';

const debug = createDebug('reveal-md');

let puppeteer;
try {
puppeteer = require('puppeteer');
puppeteer = await import('puppeteer');
} catch (err) {
console.warn(`Puppeteer unavailable, unable to generate PDF file.`);
debug(err);
}

module.exports = async (initialUrl, print, printSize) => {
// Exports ---------------------------------------------------------------------

export default async (initialUrl, print, printSize) => {
if (!puppeteer) {
return;
}
Expand Down
Loading