Skip to content

Commit

Permalink
fix linting
Browse files Browse the repository at this point in the history
  • Loading branch information
thescientist13 committed Oct 27, 2023
1 parent 1ef8a36 commit 6a598a3
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 95 deletions.
4 changes: 2 additions & 2 deletions packages/cli/src/commands/develop.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ const runDevServer = async (compilation) => {
const { basePath, devServer } = compilation.config;
const { port } = devServer;
const postfixSlash = basePath === '' ? '' : '/';

(await getDevServer(compilation)).listen(port, () => {

console.info(`Started local development server at http://localhost:${port}${basePath}${postfixSlash}`);

const servers = [...compilation.config.plugins.filter((plugin) => {
Expand Down
134 changes: 47 additions & 87 deletions packages/cli/src/lifecycles/bundle.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable max-depth, max-len */
import fs from 'fs/promises';
import { getRollupConfigForApis, getRollupConfigForScriptResources, getRollupConfigForSsr } from '../config/rollup.config.js';
import { getAppTemplate, getPageTemplate, getUserScripts } from '../lib/templating-utils.js';
import { hashString } from '../lib/hashing-utils.js';
import { checkResourceExists, mergeResponse, normalizePathnameForWindows } from '../lib/resource-utils.js';
import path from 'path';
Expand All @@ -11,8 +12,6 @@ async function emitResources(compilation) {
const { resources, graph } = compilation;

// https://stackoverflow.com/a/56150320/417806
// TODO put into a util
// https://github.com/ProjectEvergreen/greenwood/issues/1008
await fs.writeFile(new URL('./resources.json', outputDir), JSON.stringify(resources, (key, value) => {
if (value instanceof Map) {
return {
Expand Down Expand Up @@ -91,7 +90,7 @@ async function bundleStyleResources(compilation, resourcePlugins) {
if (src) {
const basename = path.basename(srcPath);
const basenamePieces = path.basename(srcPath).split('.');
const fileNamePieces = srcPath.split('/').filter(piece => piece !== ''); // normalize by removing any leading /'s
const fileNamePieces = srcPath.split('/').filter(piece => piece !== ''); // normalize by removing any leading /'s

optimizedFileName = srcPath.indexOf('/node_modules') >= 0
? `${basenamePieces[0]}.${hashString(contents)}.css`
Expand Down Expand Up @@ -174,108 +173,68 @@ async function bundleApiRoutes(compilation) {

async function bundleSsrPages(compilation) {
// https://rollupjs.org/guide/en/#differences-to-the-javascript-api
const { outputDir, pagesDir } = compilation.context;
// TODO context plugins for SSR ?
// https://github.com/ProjectEvergreen/greenwood/issues/1008
// const contextPlugins = compilation.config.plugins.filter((plugin) => {
// return plugin.type === 'context';
// }).map((plugin) => {
// return plugin.provider(compilation);
// });

const hasSSRPages = compilation.graph.filter(page => page.isSSR).length > 0;
const input = [];

if (!compilation.config.prerender) {
if (!compilation.config.prerender && hasSSRPages) {
const htmlOptimizer = compilation.config.plugins.find(plugin => plugin.name === 'plugin-standard-html').provider(compilation);
const { executeModuleUrl } = compilation.config.plugins.find(plugin => plugin.type === 'renderer').provider();
const { executeRouteModule } = await import(executeModuleUrl);
const { pagesDir, scratchDir } = compilation.context;

for (const page of compilation.graph) {
if (page.isSSR && !page.data.static) {
const { filename, path: pagePath } = page;
const scratchUrl = new URL(`./${filename}`, outputDir);

// better way to write out inline code like this?
await fs.writeFile(scratchUrl, `
import { Worker } from 'worker_threads';
import { getAppTemplate, getPageTemplate, getUserScripts } from '@greenwood/cli/src/lib/templating-utils.js';
export async function handler(request, compilation) {
const routeModuleLocationUrl = new URL('./_${filename}', '${outputDir}');
const routeWorkerUrl = '${compilation.config.plugins.find(plugin => plugin.type === 'renderer').provider().workerUrl}';
const htmlOptimizer = compilation.config.plugins.find(plugin => plugin.name === 'plugin-standard-html').provider(compilation);
let body = '';
let html = '';
let frontmatter;
let template;
let templateType = 'page';
let title = '';
let imports = [];
await new Promise((resolve, reject) => {
const worker = new Worker(new URL(routeWorkerUrl));
worker.on('message', (result) => {
if (result.body) {
body = result.body;
}
if (result.template) {
template = result.template;
}
if (result.frontmatter) {
frontmatter = result.frontmatter;
if (frontmatter.title) {
title = frontmatter.title;
}
if (frontmatter.template) {
templateType = frontmatter.template;
}
if (frontmatter.imports) {
imports = imports.concat(frontmatter.imports);
}
}
resolve();
});
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(\`Worker stopped with exit code \${code}\`));
}
});
worker.postMessage({
moduleUrl: routeModuleLocationUrl.href,
compilation: \`${JSON.stringify(compilation)}\`,
route: '${pagePath}'
});
});
html = template ? template : await getPageTemplate('', compilation.context, templateType, []);
html = await getAppTemplate(html, compilation.context, imports, [], false, title, ${compilation.config.basePath});
html = await getUserScripts(html, compilation.context);
html = html.replace(\/\<content-outlet>(.*)<\\/content-outlet>\/s, body);
html = await (await htmlOptimizer.optimize(new URL(request.url), new Response(html))).text();
const { filename, imports, route, template, title } = page;
const entryFileUrl = new URL(`./_${filename}`, scratchDir);
const moduleUrl = new URL(`./${filename}`, pagesDir);
// TODO getTemplate has to be static (for now?)
// https://github.com/ProjectEvergreen/greenwood/issues/955
const data = await executeRouteModule({ moduleUrl, compilation, page, prerender: false, htmlContents: null, scripts: [] });
let staticHtml = '';

staticHtml = data.template ? data.template : await getPageTemplate(staticHtml, compilation.context, template, []);
staticHtml = await getAppTemplate(staticHtml, compilation.context, imports, [], false, title);
staticHtml = await getUserScripts(staticHtml, compilation.context);
staticHtml = await (await htmlOptimizer.optimize(new URL(`http://localhost:8080${route}`), new Response(staticHtml))).text();
staticHtml = staticHtml.replace(/[`\\$]/g, '\\$&'); // https://stackoverflow.com/a/75688937/417806

// better way to write out this inline code?
await fs.writeFile(entryFileUrl, `
import { executeRouteModule } from '${normalizePathnameForWindows(executeModuleUrl)}';
export async function handler(request) {
const compilation = JSON.parse('${JSON.stringify(compilation)}');
const page = JSON.parse('${JSON.stringify(page)}');
const moduleUrl = '___GWD_ENTRY_FILE_URL=${filename}___';
const data = await executeRouteModule({ moduleUrl, compilation, page });
let staticHtml = \`${staticHtml}\`;
if (data.body) {
staticHtml = staticHtml.replace(\/\<content-outlet>(.*)<\\/content-outlet>\/s, data.body);
}
return new Response(html);
return new Response(staticHtml, {
headers: {
'Content-Type': 'text/html'
}
});
}
`);

input.push(normalizePathnameForWindows(new URL(`./${filename}`, pagesDir)));
input.push(normalizePathnameForWindows(moduleUrl));
input.push(normalizePathnameForWindows(entryFileUrl));
}
}

const [rollupConfig] = await getRollupConfigForSsr(compilation, input);

if (rollupConfig.input.length > 0) {
const { userTemplatesDir, outputDir } = compilation.context;

if (await checkResourceExists(userTemplatesDir)) {
await fs.cp(userTemplatesDir, new URL('./_templates/', outputDir), { recursive: true });
}

const bundle = await rollup(rollupConfig);
await bundle.write(rollupConfig.output);
}
Expand Down Expand Up @@ -309,13 +268,14 @@ const bundleCompilation = async (compilation) => {

await Promise.all([
await bundleApiRoutes(compilation),
await bundleSsrPages(compilation),
await bundleScriptResources(compilation),
await bundleStyleResources(compilation, optimizeResourcePlugins)
]);

console.info('optimizing static pages....');
// bundleSsrPages depends on bundleScriptResources having run first
await bundleSsrPages(compilation);

console.info('optimizing static pages....');
await optimizeStaticPages(compilation, optimizeResourcePlugins);
await cleanUpResources(compilation);
await emitResources(compilation);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ describe('Develop Greenwood With: ', function() {
describe(LABEL, function() {

before(async function() {

await runner.setup(outputPath, [
...getSetupFiles(outputPath)
]);
Expand Down Expand Up @@ -86,7 +86,7 @@ describe('Develop Greenwood With: ', function() {

response = res;
dom = new JSDOM(body);

resolve();
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ describe('Serve Greenwood With: ', function() {
before(async function() {
await runner.setup(outputPath, getSetupFiles(outputPath));
await runner.runCommand(cliPath, 'build');

return new Promise(async (resolve) => {
setTimeout(() => {
resolve();
Expand Down Expand Up @@ -85,7 +85,7 @@ describe('Serve Greenwood With: ', function() {

response = res;
dom = new JSDOM(body);

resolve();
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import { fileURLToPath } from 'url';

const expect = chai.expect;

describe('Serve Greenwood With: ', function() {
describe.only('Serve Greenwood With: ', function() {
const LABEL = 'A Server Rendered Application (SSR) with API Routes importing TypeScript';
const cliPath = path.join(process.cwd(), 'packages/cli/src/index.js');
const outputPath = fileURLToPath(new URL('.', import.meta.url));
Expand Down Expand Up @@ -73,7 +73,6 @@ describe('Serve Greenwood With: ', function() {
reject();
}

console.log({ body });
response = res;
response.body = body;
fragmentsApiDom = new JSDOM(body);
Expand Down

0 comments on commit 6a598a3

Please sign in to comment.