Compare commits

..

No commits in common. "main" and "v0.1.5" have entirely different histories.
main ... v0.1.5

49 changed files with 4928 additions and 2787 deletions

View file

@ -6,4 +6,3 @@ indent_size = 4
charset = utf-8 charset = utf-8
trim_trailing_whitespace = true trim_trailing_whitespace = true
insert_final_newline = true insert_final_newline = true
end_of_line = lf

1
.eslintignore Normal file
View file

@ -0,0 +1 @@
node_modules

23
.eslintrc Normal file
View file

@ -0,0 +1,23 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "prettier"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:react/recommended",
"plugin:prettier/recommended"
],
"settings": {
"react": {
"pragma": "createElement"
}
},
"rules": {
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/ban-types": "off",
"react/prop-types": "off",
"react/jsx-key": "off"
}
}

View file

@ -1,38 +0,0 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
jobs:
check:
runs-on: node-24
steps:
- uses: https://code.forgejo.org/actions/checkout@v4
- name: Cache npm dependencies
uses: https://code.forgejo.org/actions/cache@v4
with:
path: ~/.npm
key: node-24-${{ hashFiles('**/package-lock.json') }}
- run: npm ci
- run: npm run check
build:
needs: check
strategy:
matrix:
node: [22, 24]
runs-on: node-${{ matrix.node }}
steps:
- uses: https://code.forgejo.org/actions/checkout@v4
- name: Cache npm dependencies
uses: https://code.forgejo.org/actions/cache@v4
with:
path: ~/.npm
key: node-${{ matrix.node }}-${{ hashFiles('**/package-lock.json') }}
- run: npm ci
- run: npm run build
- run: npm test

2
.gitattributes vendored
View file

@ -1,2 +0,0 @@
# Ensure that git uses lf line-endings for text files.
* text=auto eol=lf

2
.nvmrc
View file

@ -1 +1 @@
18 lts/erbium

10
.travis.yml Normal file
View file

@ -0,0 +1,10 @@
language: node_js
os:
- linux
- osx
- windows
node_js:
- node
- lts/*
- 12
- 10

View file

@ -1,15 +1,5 @@
# Changelog # Changelog
## [0.2.0](https://github.com/websnacksjs/websnacks/releases/tag/v0.2.0) (2021-02-28)
### Features
- add dangerouslySetInnerHTML attr ([#15](https://github.com/websnacksjs/websnacks/issues/15), [3f356dd](https://github.com/websnacksjs/websnacks/commit/3f356ddfeeb38e8a60c32d26c3e9e8715d0246c3))
### Misc
- **BREAKING CHANGE** update node-watch optional dep to major v0.7.1
## [0.1.5](https://github.com/websnacksjs/websnacks/releases/tag/v0.1.5) (2020-06-14) ## [0.1.5](https://github.com/websnacksjs/websnacks/releases/tag/v0.1.5) (2020-06-14)
### Bugfixes ### Bugfixes

View file

@ -1,9 +1,20 @@
# websnacks: Minimal Dependency Server-Side JSX for Static Sites # websnacks: Minimal Dependency Server-Side JSX for Static Sites
[![NPM release](https://badges.git.theinnerlimit.ch/npm/v/@websnacksjs/websnacks?style=flat-square)](https://www.npmjs.com/package/@websnacksjs/websnacks "NPM release") <div>
[![NPM](https://badges.git.theinnerlimit.ch/npm/l/@websnacksjs/websnacks?style=flat-square)](https://www.mozilla.org/en-US/MPL/2.0/FAQ/ "License info")
[![Build status](https://git.theinnerlimit.ch/websnacksjs/websnacks/badges/workflows/ci.yml/badge.svg?event=push&label=ci&style=flat-square)](https://git.theinnerlimit.ch/websnacksjs/websnacks/actions?workflow=ci.yml "CI status for main branch") [![NPM release](https://img.shields.io/npm/v/@websnacksjs/websnacks?style=flat-square)](https://www.npmjs.com/package/@websnacksjs/websnacks "NPM release")
![Dependency status](https://badges.git.theinnerlimit.ch/librariesio/release/npm/%40websnacksjs%2Fwebsnacks?style=flat-square) [![NPM](https://img.shields.io/npm/l/@websnacksjs/websnacks?style=flat-square)](https://www.mozilla.org/en-US/MPL/2.0/FAQ/ "License info")
[![Build status](https://img.shields.io/travis/com/websnacksjs/websnacks/master?style=flat-square)](https://travis-ci.com/websnacksjs/websnacks "Build status for master branch")
</div>
<div>
[![Dependency status](https://img.shields.io/david/websnacksjs/websnacks?style=flat-square)](https://david-dm.org/websnacksjs/websnacks "Dependency status")
[![Optional dependency status](https://img.shields.io/david/optional/websnacksjs/websnacks?style=flat-square)](https://david-dm.org/websnacksjs/websnacks?type=optional "Optional dependency status")
[![Dev dependency status](https://img.shields.io/david/dev/websnacksjs/websnacks?style=flat-square)](https://david-dm.org/websnacksjs/websnacks?type=dev "Dev dependency status")
</div>
Develop fully static websites using typesafe JSX templates on the server without the complex build system and dependency management of server-side rendered React frameworks. Develop fully static websites using typesafe JSX templates on the server without the complex build system and dependency management of server-side rendered React frameworks.

View file

@ -1,41 +0,0 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.14/schema.json",
"files": {
"includes": ["**", "!dist", "!node_modules", "!.temp"]
},
"assist": {
"enabled": true,
"actions": {
"source": {
"organizeImports": "on"
}
}
},
"formatter": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"style": {
"useShorthandFunctionType": "off"
},
"correctness": {
"useJsxKeyInIterable": "off"
}
}
},
"overrides": [
{
"includes": ["test/**"],
"linter": {
"rules": {
"a11y": {
"useHtmlLang": "off"
}
}
}
}
]
}

View file

@ -1,9 +1,5 @@
import { stylesheet } from "typestyle"; import { stylesheet } from "typestyle";
import { import { Component, createElement } from "websnacks";
type Component,
// biome-ignore lint/correctness/noUnusedImports: required to support JSX
createElement,
} from "websnacks";
const styles = stylesheet({ const styles = stylesheet({
header: { header: {

View file

@ -1,10 +1,6 @@
import { normalize } from "csstips"; import { normalize } from "csstips";
import { stylesheet } from "typestyle"; import { stylesheet } from "typestyle";
import { import { Component, createElement } from "websnacks";
type Component,
// biome-ignore lint/correctness/noUnusedImports: required to support JSX
createElement,
} from "websnacks";
import { stylesheetPath } from "../config"; import { stylesheetPath } from "../config";
import { Header } from "./header"; import { Header } from "./header";
@ -50,7 +46,10 @@ export const Layout: Component<LayoutProps> = ({ children, headline }) => (
{headline && ` | ${headline}`} {headline && ` | ${headline}`}
</title> </title>
<meta name="description" content="" /> <meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta
name="viewport"
content="width=device-width, initial-scale=1"
/>
<link rel="stylesheet" href={stylesheetPath} /> <link rel="stylesheet" href={stylesheetPath} />
</head> </head>

View file

@ -1,9 +1,5 @@
import { stylesheet } from "typestyle"; import { stylesheet } from "typestyle";
import { import { Component, createElement } from "websnacks";
type Component,
// biome-ignore lint/correctness/noUnusedImports: required to support JSX
createElement,
} from "websnacks";
const styles = stylesheet({ const styles = stylesheet({
navbar: { navbar: {

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,5 @@
{ {
"name": "websnacks-example-personal-site", "name": "websnacks-example-personal-site",
"type": "module",
"scripts": { "scripts": {
"build": "websnacks -r ts-node/register build", "build": "websnacks -r ts-node/register build",
"dev": "websnacks -r ts-node/register dev" "dev": "websnacks -r ts-node/register dev"

View file

@ -1,25 +1,22 @@
import { import { Component, createElement } from "websnacks";
type Component,
// biome-ignore lint/correctness/noUnusedImports: required to support JSX
createElement,
} from "websnacks";
import { Layout } from "../components/layout"; import { Layout } from "../components/layout";
export const page: Component = () => ( export const page: Component = () => (
<Layout> <Layout>
<p> <p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur dapibus Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur
condimentum mauris et egestas. Quisque orci nulla, consequat at erat dapibus condimentum mauris et egestas. Quisque orci nulla, consequat
laoreet, malesuada sodales nisi. Sed in lorem semper lorem placerat at erat laoreet, malesuada sodales nisi. Sed in lorem semper lorem
fermentum a id arcu. Curabitur non aliquam tellus, sed auctor lacus. Nunc placerat fermentum a id arcu. Curabitur non aliquam tellus, sed
sit amet lectus ultrices, sodales nisl sit amet, luctus nisl. Nunc mollis auctor lacus. Nunc sit amet lectus ultrices, sodales nisl sit amet,
imperdiet quam, eget sollicitudin leo tincidunt vel. Duis felis dui, luctus nisl. Nunc mollis imperdiet quam, eget sollicitudin leo
imperdiet aliquam bibendum sed, auctor et dolor. Vivamus odio ipsum, tincidunt vel. Duis felis dui, imperdiet aliquam bibendum sed,
venenatis in felis sed, aliquam dictum turpis. Pellentesque pellentesque auctor et dolor. Vivamus odio ipsum, venenatis in felis sed, aliquam
consequat neque, id imperdiet diam molestie nec. Nullam ut vestibulum est. dictum turpis. Pellentesque pellentesque consequat neque, id
Pellentesque orci urna, porta vel porta quis, semper ut enim. Donec sit imperdiet diam molestie nec. Nullam ut vestibulum est. Pellentesque
amet urna arcu. Nam tincidunt fermentum ligula a pharetra.{" "} orci urna, porta vel porta quis, semper ut enim. Donec sit amet urna
arcu. Nam tincidunt fermentum ligula a pharetra.{" "}
</p> </p>
</Layout> </Layout>
); );

View file

@ -1,9 +1,5 @@
import { stylesheet } from "typestyle"; import { stylesheet } from "typestyle";
import { import { Component, createElement } from "websnacks";
type Component,
// biome-ignore lint/correctness/noUnusedImports: required to support JSX
createElement,
} from "websnacks";
import { Layout } from "../components/layout"; import { Layout } from "../components/layout";

View file

@ -1,10 +1,10 @@
import { promises as fs } from "node:fs"; import { promises as fs } from "fs";
import * as path from "node:path"; import * as path from "path";
import type { Config } from "websnacks"; import { Config } from "websnacks";
import { stylesheetPath } from "./config"; import { stylesheetPath } from "./config";
const _config: Config = { const config: Config = {
// Watch additional files and folders for changes when the dev server is // Watch additional files and folders for changes when the dev server is
// running. // running.
watch: ["components/", "config.ts"], watch: ["components/", "config.ts"],
@ -23,3 +23,4 @@ const _config: Config = {
}, },
}, },
}; };
export = config;

2009
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,15 +1,14 @@
{ {
"name": "@websnacksjs/websnacks", "name": "@websnacksjs/websnacks",
"description": "Minimal dependency server-side JSX for static sites", "description": "Minimal dependency server-side JSX for static sites",
"version": "0.2.0", "version": "0.1.5",
"author": { "author": {
"name": "M. George Hansen", "name": "M. George Hansen",
"email": "mgeorge@technopolitica.com" "email": "mgeorge@technopolitica.com"
}, },
"license": "MPL-2.0", "license": "MPL-2.0",
"repository": "github:websnacksjs/websnacks",
"engines": { "engines": {
"node": ">=18" "node": ">=10"
}, },
"main": "dist/index.js", "main": "dist/index.js",
"types": "types.d.ts", "types": "types.d.ts",
@ -24,7 +23,6 @@
], ],
"scripts": { "scripts": {
"build": "tsc", "build": "tsc",
"check": "biome check .",
"clean": "ts-node scripts/clean.ts", "clean": "ts-node scripts/clean.ts",
"prepublishOnly": "npm run reset && npm test", "prepublishOnly": "npm run reset && npm test",
"pretest": "npm run build", "pretest": "npm run build",
@ -36,14 +34,20 @@
"test:e2e": "cd test && ts-node --script-mode ./run-e2e.ts" "test:e2e": "cd test && ts-node --script-mode ./run-e2e.ts"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "2.4.14", "@types/node": "~10",
"@types/node": "~18", "@types/ws": "^7.2.4",
"@types/ws": "^8.18.1", "@typescript-eslint/eslint-plugin": "^3.0.2",
"ts-node": "^10.9.2", "@typescript-eslint/parser": "^3.0.2",
"typescript": "~4.9.5" "eslint": "^7.1.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.3",
"eslint-plugin-react": "^7.20.0",
"prettier": "^2.0.5",
"ts-node": "^8.10.2",
"typescript": "~3.9.3"
}, },
"optionalDependencies": { "optionalDependencies": {
"node-watch": "^0.7.4", "node-watch": "^0.6.4",
"ws": "^8.20.0" "ws": "^7.3.0"
} }
} }

View file

@ -3,8 +3,8 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import * as fs from "node:fs"; import * as fs from "fs";
import * as path from "node:path"; import * as path from "path";
const ROOT_DIR = path.resolve(__dirname, ".."); const ROOT_DIR = path.resolve(__dirname, "..");
const DIST_DIR = path.join(ROOT_DIR, "dist"); const DIST_DIR = path.join(ROOT_DIR, "dist");

View file

@ -3,10 +3,10 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { promises as fs } from "node:fs"; import { promises as fs } from "fs";
import * as path from "node:path"; import * as path from "path";
import type { Config, ConfigPaths } from "./config"; import { Config, ConfigPaths } from "./config";
import { renderPage } from "./render"; import { renderPage } from "./render";
import { decacheModule, walkDir } from "./utils"; import { decacheModule, walkDir } from "./utils";
@ -27,14 +27,16 @@ const renderPagesToHtml = async ({
const pageSrc = require(srcPath); const pageSrc = require(srcPath);
if (!("page" in pageSrc)) { if (!("page" in pageSrc)) {
throw new Error( throw new Error(
`page source at ${srcPath} does not export a "page" variable`, `page source at ${srcPath} does not export a "page" variable`
); );
} }
let compiledHtml: string; let compiledHtml;
try { try {
compiledHtml = renderPage(pageSrc.page()); compiledHtml = renderPage(pageSrc.page());
} catch (error) { } catch (error) {
throw new Error(`failed to compile ${srcPath}: ${error}`); throw new Error(
`failed to compile ${srcPath}: ${error.stack ?? error}`
);
} }
const relPath = path.relative(pagesDir, path.dirname(srcPath)); const relPath = path.relative(pagesDir, path.dirname(srcPath));
let baseName = path.basename(srcPath, ".tsx"); let baseName = path.basename(srcPath, ".tsx");
@ -46,7 +48,7 @@ const renderPagesToHtml = async ({
(async () => { (async () => {
await fs.mkdir(path.dirname(destPath), { recursive: true }); await fs.mkdir(path.dirname(destPath), { recursive: true });
await fs.writeFile(destPath, compiledHtml); await fs.writeFile(destPath, compiledHtml);
})(), })()
); );
} }
await Promise.all(deferred); await Promise.all(deferred);
@ -58,7 +60,7 @@ const copyStaticAssets = async ({
}: ConfigPaths): Promise<void> => { }: ConfigPaths): Promise<void> => {
try { try {
await fs.access(staticAssetsDir); await fs.access(staticAssetsDir);
} catch (_error) { } catch (error) {
// Static assets folder doesn't exist, so no-op. // Static assets folder doesn't exist, so no-op.
return; return;
} }
@ -71,7 +73,7 @@ const copyStaticAssets = async ({
(async () => { (async () => {
await fs.mkdir(path.dirname(destPath), { recursive: true }); await fs.mkdir(path.dirname(destPath), { recursive: true });
await fs.copyFile(assetPath, destPath); await fs.copyFile(assetPath, destPath);
})(), })()
); );
} }
await Promise.all(deferred); await Promise.all(deferred);

View file

@ -5,7 +5,7 @@
import { renderSite } from "../../build"; import { renderSite } from "../../build";
import { loadConfig } from "../../config"; import { loadConfig } from "../../config";
import { type Command, UsageError } from "../types"; import { Command, UsageError } from "../types";
const helpText = `\ const helpText = `\
Usage: websnacks build [ROOT_DIR] Usage: websnacks build [ROOT_DIR]

View file

@ -3,14 +3,14 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { existsSync, promises as fs, watch } from "node:fs"; import { existsSync, promises as fs, watch } from "fs";
import * as http from "node:http"; import * as http from "http";
import * as path from "node:path"; import * as net from "net";
import * as path from "path";
import { renderSite } from "../../build"; import { renderSite } from "../../build";
import { type Config, loadConfig } from "../../config"; import { Config, loadConfig } from "../../config";
import { isErrnoException } from "../../utils/error"; import { Command, UsageError } from "../types";
import { type Command, UsageError } from "../types";
const DEFAULT_SERVER_PORT = 8080; const DEFAULT_SERVER_PORT = 8080;
@ -26,11 +26,11 @@ const injectLiveReloadScript = (htmlContents: string, port: number): string =>
}; };
</script> </script>
</html> </html>
`, `
); );
const guessMimeType = (ext: string): string => { const guessMimeType = (ext: string): string => {
let mimeType: string; let mimeType;
switch (ext) { switch (ext) {
case ".apng": case ".apng":
mimeType = "image/apng"; mimeType = "image/apng";
@ -119,16 +119,14 @@ const guessMimeType = (ext: string): string => {
return mimeType; return mimeType;
}; };
const portFromServer = ( const portFromServer = (server: Pick<net.Server, "address">): number => {
addrInfo: { port: number } | object | string | undefined | null, const addrInfo = server.address();
): number => { if (addrInfo == null) {
if ( throw new Error(`server address is null (this should never happen!)`);
typeof addrInfo !== "object" || }
addrInfo == null || if (typeof addrInfo === "string") {
!("port" in addrInfo)
) {
throw new Error( throw new Error(
"server address does not have a valid port (this should never happen!)", `server address is a string (this should never happen!)`
); );
} }
return addrInfo.port; return addrInfo.port;
@ -149,10 +147,10 @@ const startHttpServer = async (publicDir: string): Promise<http.Server> => {
reqExt = ".html"; reqExt = ".html";
} }
let contents: Buffer | string; let contents;
try { try {
contents = await fs.readFile(path.join(publicDir, reqPath)); contents = await fs.readFile(path.join(publicDir, reqPath));
} catch (_error) { } catch (error) {
console.error(`unable to load file ${reqPath}`); console.error(`unable to load file ${reqPath}`);
res.writeHead(404); res.writeHead(404);
res.end(); res.end();
@ -160,7 +158,7 @@ const startHttpServer = async (publicDir: string): Promise<http.Server> => {
} }
const mimeType = guessMimeType(reqExt); const mimeType = guessMimeType(reqExt);
if (mimeType === "text/html") { if (mimeType === "text/html") {
const port = portFromServer(req.socket.address()); const port = portFromServer(req.socket);
contents = injectLiveReloadScript(contents.toString("utf8"), port); contents = injectLiveReloadScript(contents.toString("utf8"), port);
} }
res.writeHead(200, { res.writeHead(200, {
@ -168,7 +166,7 @@ const startHttpServer = async (publicDir: string): Promise<http.Server> => {
}); });
res.end(contents); res.end(contents);
}); });
const listen = async (port?: number): Promise<void> => const listen = async (port?: number): Promise<string> =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
httpServer httpServer
.once("error", (error) => reject(error)) .once("error", (error) => reject(error))
@ -178,33 +176,25 @@ const startHttpServer = async (publicDir: string): Promise<http.Server> => {
try { try {
await listen(DEFAULT_SERVER_PORT); await listen(DEFAULT_SERVER_PORT);
} catch (error) { } catch (error) {
if ( if (error.code !== "EADDRINUSE") {
error instanceof Error &&
isErrnoException(error) &&
error.code !== "EADDRINUSE"
) {
throw error; throw error;
} }
await listen(); await listen();
} }
const port = portFromServer(httpServer.address()); const port = portFromServer(httpServer);
console.log(`Listening at http://127.0.0.1:${port}`); console.log(`Listening at http://127.0.0.1:${port}`);
return httpServer; return httpServer;
}; };
const startWebSocketServer = async ( const startWebSocketServer = async (
httpServer: http.Server, httpServer: http.Server
): Promise<import("ws").Server | undefined> => { ): Promise<import("ws").Server | undefined> => {
// Attempt to load the ws module, aborting if it isn't available. // Attempt to load the ws module, aborting if it isn't available.
let ws: typeof import("ws"); let ws;
try { try {
ws = await import("ws"); ws = await import("ws");
} catch (error) { } catch (error) {
if ( if (error.code !== "MODULE_NOT_FOUND") {
error instanceof Error &&
isErrnoException(error) &&
error.code !== "MODULE_NOT_FOUND"
) {
throw error; throw error;
} }
console.warn(`'ws' module not found, live-reloading will be disabled`); console.warn(`'ws' module not found, live-reloading will be disabled`);
@ -219,7 +209,7 @@ const startWebSocketServer = async (
const watchFolders = async ( const watchFolders = async (
folders: string[], folders: string[],
listener: (eventType?: "update" | "remove", fileName?: string) => void, listener: (eventType: "update" | "remove", fileName: string) => void
): Promise<void> => { ): Promise<void> => {
// Try to load node-watch, falling back to fs watch if node-watch isn't // Try to load node-watch, falling back to fs watch if node-watch isn't
// available. // available.
@ -228,23 +218,19 @@ const watchFolders = async (
nodeWatch.default(folders, { recursive: true }, listener); nodeWatch.default(folders, { recursive: true }, listener);
return; return;
} catch (error) { } catch (error) {
if ( if (error.code !== "MODULE_NOT_FOUND") {
error instanceof Error &&
isErrnoException(error) &&
error.code !== "MODULE_NOT_FOUND"
) {
throw error; throw error;
} }
console.warn( console.warn(
`'node-watch' module not found, falling back to fs.watch (may ` + `'node-watch' module not found, falling back to fs.watch (may ` +
"result in file watch issues on some OSes)", `result in file watch issues on some OSes)`
); );
} }
// NOTE: fs.watch has significant cross-platform issues, including // NOTE: fs.watch has significant cross-platform issues, including
// triggering duplicate file events on some systems. // triggering duplicate file events on some systems.
for (const folder of folders) { for (const folder of folders) {
watch(folder, { recursive: true }, (_, fileName) => { watch(folder, { recursive: true }, (_, fileName) => {
listener("update", fileName || undefined); listener("update", fileName);
}); });
} }
}; };
@ -293,15 +279,13 @@ const devCommand: Command = {
const httpServer = await startHttpServer(outDir); const httpServer = await startHttpServer(outDir);
const wsServer = await startWebSocketServer(httpServer); const wsServer = await startWebSocketServer(httpServer);
const watchedFolders = config.watch.filter((filePath) => const watchedFolders = config.watch.filter((filePath) =>
existsSync(filePath), existsSync(filePath)
); );
await watchFolders(watchedFolders, async (event, filePath) => { await watchFolders(watchedFolders, async (event, filePath) => {
const filePathForLog = filePath || "<UNKNOWN_FILE>"; console.log(`${filePath}:${event} triggering rebuild...`);
const eventForLog = event || "<UNKNOWN_EVENT>";
console.log(`${filePathForLog}:${eventForLog} triggering rebuild...`);
await rebuild(); await rebuild();
if (wsServer != null) { if (wsServer != null) {
console.log("rebuild finished, reloading browsers..."); console.log(`rebuild finished, reloading browsers...`);
for (const ws of wsServer.clients) { for (const ws of wsServer.clients) {
ws.send("reload"); ws.send("reload");
} }

View file

@ -3,7 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { type Command, UsageError } from "./types"; import { Command, UsageError } from "./types";
const globalHelpText = `\ const globalHelpText = `\
Usage: websnacks [...globalOptions] <command> Usage: websnacks [...globalOptions] <command>
@ -24,7 +24,7 @@ interface Options {
} }
const parseArgs = ( const parseArgs = (
args: string[], args: string[]
): { options: Options; commandName?: string; commandArgs: string[] } => { ): { options: Options; commandName?: string; commandArgs: string[] } => {
const options: Options = { const options: Options = {
showHelp: false, showHelp: false,
@ -45,8 +45,8 @@ const parseArgs = (
const moduleName = args.shift(); const moduleName = args.shift();
if (moduleName == null) { if (moduleName == null) {
throw new UsageError( throw new UsageError(
"-r requires a valid module name", `-r requires a valid module name`,
globalHelpText, globalHelpText
); );
} }
options.require.push(moduleName); options.require.push(moduleName);
@ -67,7 +67,7 @@ const _main = async (args: string[]): Promise<void> => {
return; return;
} }
if (commandName == null) { if (commandName == null) {
throw new UsageError("must specify a valid command", globalHelpText); throw new UsageError(`must specify a valid command`, globalHelpText);
} }
for (const moduleName of options.require) { for (const moduleName of options.require) {
await import(moduleName); await import(moduleName);
@ -82,7 +82,10 @@ const _main = async (args: string[]): Promise<void> => {
command = await import("./commands/dev"); command = await import("./commands/dev");
break; break;
default: default:
throw new UsageError(`unknown command ${commandName}`, globalHelpText); throw new UsageError(
`unknown command ${commandName}`,
globalHelpText
);
} }
// NOTE: Should this just delegate to the command? // NOTE: Should this just delegate to the command?
for (const arg of commandArgs) { for (const arg of commandArgs) {

View file

@ -37,15 +37,15 @@ export type Element =
/** /**
* Custom HTMLElement factory that can be parameterized by props. * Custom HTMLElement factory that can be parameterized by props.
*/ */
export interface Component<P extends object = Record<string, unknown>> { export interface Component<P extends object = {}> {
( (
props: P & { props: P & {
children?: Element[]; children?: Element[];
}, }
): HTMLElement; ): HTMLElement;
} }
export const Fragment: Component = ({ children }) => ({ export const Fragment: Component<{}> = ({ children }) => ({
tag: "#fragment", tag: "#fragment",
attributes: {}, attributes: {},
children: children || [], children: children || [],

View file

@ -3,7 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import * as path from "node:path"; import * as path from "path";
import { decacheModule } from "./utils"; import { decacheModule } from "./utils";
@ -58,7 +58,7 @@ const noop = () => {};
* @return Fully-realized configuration. * @return Fully-realized configuration.
*/ */
export const loadConfig = async (rootDir: string): Promise<Config> => { export const loadConfig = async (rootDir: string): Promise<Config> => {
let configPath = ""; let configPath;
let userConfig: UserConfig = {}; let userConfig: UserConfig = {};
// Attempt to load a websnacks.ts/js file in rootDir. // Attempt to load a websnacks.ts/js file in rootDir.
try { try {
@ -66,7 +66,7 @@ export const loadConfig = async (rootDir: string): Promise<Config> => {
decacheModule(configPath); decacheModule(configPath);
// TODO: validate user config. // TODO: validate user config.
userConfig = await import(configPath); userConfig = await import(configPath);
} catch (_error) { } catch (error) {
// Use default config; // Use default config;
} }
const outDir = path.join(rootDir, "public"); const outDir = path.join(rootDir, "public");
@ -74,7 +74,7 @@ export const loadConfig = async (rootDir: string): Promise<Config> => {
const staticAssetsDir = path.join(rootDir, "static"); const staticAssetsDir = path.join(rootDir, "static");
const watch = [pagesDir, staticAssetsDir]; const watch = [pagesDir, staticAssetsDir];
if (configPath) { if (configPath != null) {
watch.push(path.relative(rootDir, configPath)); watch.push(path.relative(rootDir, configPath));
} }
if (userConfig.watch != null) { if (userConfig.watch != null) {
@ -97,5 +97,3 @@ export const loadConfig = async (rootDir: string): Promise<Config> => {
watch, watch,
}; };
}; };
export const defineConfig = (userConfig: UserConfig): UserConfig => userConfig;

View file

@ -3,8 +3,8 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import type { Component, Element, HTMLElement } from "./component"; import { Component, Element, HTMLElement } from "./component";
import type { HTMLAttributes } from "./jsx"; import { HTMLAttributes } from "./jsx";
import { flatDeep } from "./utils"; import { flatDeep } from "./utils";
/** /**
@ -38,7 +38,8 @@ export function createElement(
...children: Element[] ...children: Element[]
): HTMLElement; ): HTMLElement;
export function createElement( export function createElement(
type: string | Component, // eslint-disable-next-line @typescript-eslint/no-explicit-any
type: string | Component<any>,
props: object | null, props: object | null,
...children: Element[] ...children: Element[]
): HTMLElement { ): HTMLElement {
@ -53,21 +54,14 @@ export function createElement(
} }
const attrs: Record<string, string | number | boolean> = {}; const attrs: Record<string, string | number | boolean> = {};
for (const [key, value] of Object.entries(props || {})) { for (const [key, value] of Object.entries(props || {})) {
if (key === "dangerouslySetInnerHTML") {
if (children.length > 0) {
throw new Error(
'An element with children may not have a "dangerouslySetInnerHTML" prop since children would be overriden',
);
}
attrs[key] = value.__html;
continue;
}
if ( if (
typeof value !== "string" && typeof value !== "string" &&
typeof value !== "number" && typeof value !== "number" &&
typeof value !== "boolean" typeof value !== "boolean"
) { ) {
console.warn(`non-primitive attribute ${key} = ${JSON.stringify(value)}`); console.warn(
`non-primitive attribute ${key} = ${JSON.stringify(value)}`
);
continue; continue;
} }
attrs[key] = value; attrs[key] = value;

View file

@ -3,7 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
export { Component, Fragment, HTMLElement } from "./component"; export { HTMLElement, Component, Fragment } from "./component";
export { defineConfig, UserConfig as Config } from "./config"; export { UserConfig as Config } from "./config";
export { createElement } from "./create-element"; export { createElement } from "./create-element";
export * from "./jsx"; export * from "./jsx";

View file

@ -4,7 +4,7 @@
*/ */
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
import type { HTMLElement } from "./component"; import { HTMLElement } from "./component";
export interface RdfaAttributes { export interface RdfaAttributes {
about?: string; about?: string;
@ -25,14 +25,7 @@ export interface MicrodataAttributes {
itemRef?: string; itemRef?: string;
} }
export interface SetInnerHtmlAttributes { export interface HTMLAttributes extends RdfaAttributes, MicrodataAttributes {
dangerouslySetInnerHTML?: { __html: string };
}
export interface HTMLAttributes
extends RdfaAttributes,
MicrodataAttributes,
SetInnerHtmlAttributes {
accept?: string; accept?: string;
acceptCharset?: string; acceptCharset?: string;
accessKey?: string; accessKey?: string;

View file

@ -3,7 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import type { Element, HTMLElement } from "./component"; import { Element, HTMLElement } from "./component";
const HTML_ESCAPES: { [char: string]: string } = { const HTML_ESCAPES: { [char: string]: string } = {
"&": "&amp;", "&": "&amp;",
@ -34,13 +34,9 @@ const renderElement = (elem: Element): string => {
let output = ""; let output = "";
output += startTag(elem); output += startTag(elem);
if (elem.attributes.dangerouslySetInnerHTML != null) {
output += elem.attributes.dangerouslySetInnerHTML;
} else {
for (const child of elem.children) { for (const child of elem.children) {
output += renderElement(child); output += renderElement(child);
} }
}
output += endTag(elem); output += endTag(elem);
return output; return output;
}; };
@ -59,11 +55,6 @@ const startTag = (elem: HTMLElement): string => {
continue; continue;
} }
// Ignore the special attr for setting raw inner HTML.
if (attrName === "dangerouslySetInnerHTML") {
continue;
}
let normalizedAttrName = escapeHtml(attrName.toLowerCase()); let normalizedAttrName = escapeHtml(attrName.toLowerCase());
if (normalizedAttrName === "classname") { if (normalizedAttrName === "classname") {
normalizedAttrName = "class"; normalizedAttrName = "class";
@ -71,7 +62,9 @@ const startTag = (elem: HTMLElement): string => {
if (attrValue === true) { if (attrValue === true) {
output += ` ${normalizedAttrName}=""`; output += ` ${normalizedAttrName}=""`;
} else { } else {
output += ` ${normalizedAttrName}="${escapeAttr(attrValue.toString())}"`; output += ` ${normalizedAttrName}="${escapeAttr(
attrValue.toString()
)}"`;
} }
} }
@ -95,19 +88,19 @@ const endTag = (elem: HTMLElement): string => {
* @return Fully rendered HTML document as a string. * @return Fully rendered HTML document as a string.
*/ */
export const renderPage = (rootElem: Element): string => { export const renderPage = (rootElem: Element): string => {
if (rootElem == null) { if (rootElem == undefined) {
throw new Error("root page element cannot be null"); throw new Error(`root page element cannot be null`);
} }
if (typeof rootElem !== "object" || !("tag" in rootElem)) { if (typeof rootElem !== "object" || !("tag" in rootElem)) {
throw new Error( throw new Error(
`root page element must be a valid HTMLElement, got ${JSON.stringify( `root page element must be a valid HTMLElement, got ${JSON.stringify(
rootElem, rootElem
)}`, )}`
); );
} }
if (rootElem.tag.toLowerCase() !== "html") { if (rootElem.tag.toLowerCase() !== "html") {
throw new Error( throw new Error(
`attempted to render page with non-HTML root element ${rootElem.tag}`, `attempted to render page with non-HTML root element ${rootElem.tag}`
); );
} }

View file

@ -3,17 +3,11 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { isErrnoException } from "./error";
const resolveModulePath = (importPath: string): string | undefined => { const resolveModulePath = (importPath: string): string | undefined => {
try { try {
return require.resolve(importPath); return require.resolve(importPath);
} catch (error) { } catch (error) {
if ( if (error.code === "MODULE_NOT_FOUND") {
error instanceof Error &&
isErrnoException(error) &&
error.code === "MODULE_NOT_FOUND"
) {
return; return;
} }
throw error; throw error;

View file

@ -1,3 +0,0 @@
export const isErrnoException = (
error: Error,
): error is NodeJS.ErrnoException => "code" in error;

View file

@ -3,8 +3,8 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { promises as fs } from "node:fs"; import { promises as fs } from "fs";
import * as path from "node:path"; import * as path from "path";
export { decacheModule } from "./decache-module"; export { decacheModule } from "./decache-module";
@ -16,7 +16,7 @@ export { decacheModule } from "./decache-module";
* @return Generator that yields the files found while walking the directory. * @return Generator that yields the files found while walking the directory.
*/ */
export const walkDir = async function* ( export const walkDir = async function* (
dirPath: string, dirPath: string
): AsyncGenerator<string> { ): AsyncGenerator<string> {
const dirEnts = await fs.readdir(dirPath, { withFileTypes: true }); const dirEnts = await fs.readdir(dirPath, { withFileTypes: true });
for (const dirEnt of dirEnts) { for (const dirEnt of dirEnts) {

View file

@ -3,15 +3,11 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { promises as fs } from "node:fs"; import { promises as fs } from "fs";
import * as path from "node:path"; import * as path from "path";
import { import {
npmCmd, npmCmd, runCommand, WEBSNACKS_BIN_PATH, WEBSNACKS_REPO_ROOT, withTempDir
runCommand,
WEBSNACKS_BIN_PATH,
WEBSNACKS_REPO_ROOT,
withTempDir,
} from "../helpers/e2e"; } from "../helpers/e2e";
import { testSuite } from "../lib"; import { testSuite } from "../lib";
@ -39,7 +35,7 @@ testSuite("build command", ({ test }) => {
}), }),
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
await fs.writeFile( await fs.writeFile(
path.join(tempDirPath, "websnacks.ts"), path.join(tempDirPath, "websnacks.ts"),
@ -52,7 +48,7 @@ testSuite("build command", ({ test }) => {
`, `,
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
const pagesPath = path.join(tempDirPath, "pages"); const pagesPath = path.join(tempDirPath, "pages");
await fs.mkdir(pagesPath); await fs.mkdir(pagesPath);
@ -64,7 +60,7 @@ testSuite("build command", ({ test }) => {
`, `,
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
await fs.writeFile( await fs.writeFile(
path.join(tempDirPath, "package.json"), path.join(tempDirPath, "package.json"),
@ -73,7 +69,7 @@ testSuite("build command", ({ test }) => {
websnacks: `file:${WEBSNACKS_REPO_ROOT}`, websnacks: `file:${WEBSNACKS_REPO_ROOT}`,
}, },
}), }),
{ encoding: "utf8" }, { encoding: "utf8" }
); );
await runCommand(npmCmd, ["install", "--silent"], { await runCommand(npmCmd, ["install", "--silent"], {
cwd: tempDirPath, cwd: tempDirPath,
@ -83,7 +79,7 @@ testSuite("build command", ({ test }) => {
[WEBSNACKS_BIN_PATH, "-r", "ts-node/register", "build"], [WEBSNACKS_BIN_PATH, "-r", "ts-node/register", "build"],
{ {
cwd: tempDirPath, cwd: tempDirPath,
}, }
); );
await cmd.complete; await cmd.complete;
}); });
@ -112,7 +108,7 @@ testSuite("build command", ({ test }) => {
}), }),
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
const pagesPath = path.join(tempDirPath, "pages"); const pagesPath = path.join(tempDirPath, "pages");
await fs.mkdir(pagesPath); await fs.mkdir(pagesPath);
@ -124,7 +120,7 @@ testSuite("build command", ({ test }) => {
`, `,
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
await fs.writeFile( await fs.writeFile(
path.join(tempDirPath, "package.json"), path.join(tempDirPath, "package.json"),
@ -133,7 +129,7 @@ testSuite("build command", ({ test }) => {
websnacks: `file:${WEBSNACKS_REPO_ROOT}`, websnacks: `file:${WEBSNACKS_REPO_ROOT}`,
}, },
}), }),
{ encoding: "utf8" }, { encoding: "utf8" }
); );
await runCommand(npmCmd, ["install", "--silent"], { await runCommand(npmCmd, ["install", "--silent"], {
cwd: tempDirPath, cwd: tempDirPath,
@ -143,7 +139,7 @@ testSuite("build command", ({ test }) => {
[WEBSNACKS_BIN_PATH, "-r", "ts-node/register", "build"], [WEBSNACKS_BIN_PATH, "-r", "ts-node/register", "build"],
{ {
cwd: tempDirPath, cwd: tempDirPath,
}, }
); );
await cmd.complete; await cmd.complete;
}); });

View file

@ -3,16 +3,11 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { promises as fs } from "node:fs"; import { promises as fs } from "fs";
import * as path from "node:path"; import * as path from "path";
import { import {
npmCmd, npmCmd, runCommand, wait, WEBSNACKS_BIN_PATH, WEBSNACKS_REPO_ROOT, withTempDir
runCommand,
WEBSNACKS_BIN_PATH,
WEBSNACKS_REPO_ROOT,
wait,
withTempDir,
} from "../helpers/e2e"; } from "../helpers/e2e";
import { testSuite } from "../lib"; import { testSuite } from "../lib";
@ -40,7 +35,7 @@ testSuite("dev command", ({ test, expect }) => {
}), }),
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
await fs.writeFile( await fs.writeFile(
path.join(tempDirPath, "websnacks.ts"), path.join(tempDirPath, "websnacks.ts"),
@ -53,7 +48,7 @@ testSuite("dev command", ({ test, expect }) => {
`, `,
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
const pagesPath = path.join(tempDirPath, "pages"); const pagesPath = path.join(tempDirPath, "pages");
await fs.mkdir(pagesPath); await fs.mkdir(pagesPath);
@ -65,7 +60,7 @@ testSuite("dev command", ({ test, expect }) => {
`, `,
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
await fs.writeFile( await fs.writeFile(
path.join(tempDirPath, "package.json"), path.join(tempDirPath, "package.json"),
@ -74,7 +69,7 @@ testSuite("dev command", ({ test, expect }) => {
websnacks: `file:${WEBSNACKS_REPO_ROOT}`, websnacks: `file:${WEBSNACKS_REPO_ROOT}`,
}, },
}), }),
{ encoding: "utf8" }, { encoding: "utf8" }
); );
await runCommand(npmCmd, ["install", "--silent"], { await runCommand(npmCmd, ["install", "--silent"], {
cwd: tempDirPath, cwd: tempDirPath,
@ -84,7 +79,7 @@ testSuite("dev command", ({ test, expect }) => {
[WEBSNACKS_BIN_PATH, "-r", "ts-node/register", "dev"], [WEBSNACKS_BIN_PATH, "-r", "ts-node/register", "dev"],
{ {
cwd: tempDirPath, cwd: tempDirPath,
}, }
); );
// FIXME: This test is a bit brittle due to relying on timeouts. // FIXME: This test is a bit brittle due to relying on timeouts.
await wait(10_000); await wait(10_000);
@ -117,7 +112,7 @@ testSuite("dev command", ({ test, expect }) => {
}), }),
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
const pagesPath = path.join(tempDirPath, "pages"); const pagesPath = path.join(tempDirPath, "pages");
await fs.mkdir(pagesPath); await fs.mkdir(pagesPath);
@ -129,7 +124,7 @@ testSuite("dev command", ({ test, expect }) => {
`, `,
{ {
encoding: "utf8", encoding: "utf8",
}, }
); );
await fs.writeFile( await fs.writeFile(
path.join(tempDirPath, "package.json"), path.join(tempDirPath, "package.json"),
@ -138,7 +133,7 @@ testSuite("dev command", ({ test, expect }) => {
websnacks: `file:${WEBSNACKS_REPO_ROOT}`, websnacks: `file:${WEBSNACKS_REPO_ROOT}`,
}, },
}), }),
{ encoding: "utf8" }, { encoding: "utf8" }
); );
await runCommand(npmCmd, ["install", "--silent"], { await runCommand(npmCmd, ["install", "--silent"], {
cwd: tempDirPath, cwd: tempDirPath,
@ -148,7 +143,7 @@ testSuite("dev command", ({ test, expect }) => {
[WEBSNACKS_BIN_PATH, "-r", "ts-node/register", "dev"], [WEBSNACKS_BIN_PATH, "-r", "ts-node/register", "dev"],
{ {
cwd: tempDirPath, cwd: tempDirPath,
}, }
); );
// FIXME: This test is a bit brittle due to relying on timeouts. // FIXME: This test is a bit brittle due to relying on timeouts.
await wait(10_000); await wait(10_000);

View file

@ -3,10 +3,10 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { type ChildProcess, spawn } from "node:child_process"; import { ChildProcess, spawn } from "child_process";
import { promises as fs } from "node:fs"; import { promises as fs } from "fs";
import * as os from "node:os"; import * as os from "os";
import * as path from "node:path"; import * as path from "path";
/** /**
* Set a timeout and wait for at least the specified number of milliseconds, * Set a timeout and wait for at least the specified number of milliseconds,
@ -36,7 +36,7 @@ const TEMP_PATH = path.resolve(__dirname, "..", "..", ".temp");
* directory path as its only argument. * directory path as its only argument.
*/ */
export const withTempDir = async ( export const withTempDir = async (
op: (tempDirPath: string) => Promise<void> | void, op: (tempDirPath: string) => Promise<void> | void
): Promise<void> => { ): Promise<void> => {
await fs.mkdir(TEMP_PATH, { recursive: true }); await fs.mkdir(TEMP_PATH, { recursive: true });
const tempDirPath = await fs.mkdtemp(`${TEMP_PATH}/`); const tempDirPath = await fs.mkdtemp(`${TEMP_PATH}/`);
@ -57,7 +57,7 @@ export const WEBSNACKS_REPO_ROOT = path.resolve(__dirname, "..", "..");
export const WEBSNACKS_BIN_PATH = path.join( export const WEBSNACKS_BIN_PATH = path.join(
WEBSNACKS_REPO_ROOT, WEBSNACKS_REPO_ROOT,
"bin", "bin",
"websnacks.js", "websnacks.js"
); );
/** /**
@ -113,7 +113,7 @@ const DEFAULT_CLI_OPTIONS = {
export const runCommand = ( export const runCommand = (
command: string, command: string,
args: string[] = [], args: string[] = [],
options?: CliOptions, options?: CliOptions
): AsyncCommand => { ): AsyncCommand => {
const optionsWithDefaults = { ...DEFAULT_CLI_OPTIONS, ...options }; const optionsWithDefaults = { ...DEFAULT_CLI_OPTIONS, ...options };
const process = spawn(command, args, { const process = spawn(command, args, {
@ -137,7 +137,9 @@ export const runCommand = (
threwError = true; threwError = true;
process.kill(); process.kill();
reject( reject(
new Error(`max timeout of ${optionsWithDefaults.timeoutMs}ms reached`), new Error(
`max timeout of ${optionsWithDefaults.timeoutMs}ms reached`
)
); );
}, optionsWithDefaults.timeoutMs); }, optionsWithDefaults.timeoutMs);
process.on("exit", (code) => { process.on("exit", (code) => {

View file

@ -10,7 +10,7 @@ class ExpectError extends Error {
super( super(
`${reason}\n` + `${reason}\n` +
`\texpected: ${displayValue(expected)}\n` + `\texpected: ${displayValue(expected)}\n` +
`\tactual : ${displayValue(actual)}`, `\tactual : ${displayValue(actual)}`
); );
} }
} }
@ -48,9 +48,9 @@ export class Expect<T> {
public toEqual(expected: T): void { public toEqual(expected: T): void {
if (!areEqual(this.value, expected)) { if (!areEqual(this.value, expected)) {
throw new ExpectError( throw new ExpectError(
"value does not equal expected", `value does not equal expected`,
expected, expected,
this.value, this.value
); );
} }
} }
@ -71,9 +71,9 @@ export class StringExpect extends Expect<string> {
public toMatch(pattern: RegExp): void { public toMatch(pattern: RegExp): void {
if (!this.value.match(pattern)) { if (!this.value.match(pattern)) {
throw new ExpectError( throw new ExpectError(
"value does not match expected pattern", `value does not match expected pattern`,
pattern, pattern,
this.value, this.value
); );
} }
} }
@ -89,9 +89,9 @@ export class StringExpect extends Expect<string> {
public toStartWith(prefix: string): void { public toStartWith(prefix: string): void {
if (!this.value.startsWith(prefix)) { if (!this.value.startsWith(prefix)) {
throw new ExpectError( throw new ExpectError(
"value does not start with expected prefix", `value does not start with expected prefix`,
prefix, prefix,
this.value, this.value
); );
} }
} }
@ -107,9 +107,9 @@ export class StringExpect extends Expect<string> {
public toEndWith(suffix: string): void { public toEndWith(suffix: string): void {
if (!this.value.endsWith(suffix)) { if (!this.value.endsWith(suffix)) {
throw new ExpectError( throw new ExpectError(
"value does not end with expected suffix", `value does not end with expected suffix`,
suffix, suffix,
this.value, this.value
); );
} }
} }
@ -135,21 +135,25 @@ export class FunctionExpect<T> extends Expect<() => T> {
this.value(); this.value();
} catch (error) { } catch (error) {
if (!(error instanceof Error)) { if (!(error instanceof Error)) {
throw new ExpectError("function threw non-Error value", pattern, error); throw new ExpectError(
`function threw non-Error value`,
pattern,
error
);
} }
if (!matches(error.message, pattern)) { if (!matches(error.message, pattern)) {
throw new ExpectError( throw new ExpectError(
`thrown Error's message does not match pattern`, `thrown Error's message does not match pattern`,
pattern, pattern,
error.message, error.message
); );
} }
return; return;
} }
throw new ExpectError( throw new ExpectError(
"function did not throw expected error", `function did not throw expected error`,
pattern, pattern,
null, null
); );
} }
} }

View file

@ -39,7 +39,9 @@ const runTest = async (test: Test): Promise<TestResult> => {
error: error:
error instanceof Error error instanceof Error
? error ? error
: new Error(`threw non-error object: ${displayValue(error)}`), : new Error(
`threw non-error object: ${displayValue(error)}`
),
}; };
} }
return result; return result;
@ -84,7 +86,7 @@ export interface TestSuiteContext {
*/ */
export const testSuite = ( export const testSuite = (
suiteName: string, suiteName: string,
def: (ctx: TestSuiteContext) => void, def: (ctx: TestSuiteContext) => void
): void => { ): void => {
const tests: Test[] = []; const tests: Test[] = [];
const test = (name: string, runTest: () => void | Promise<void>): void => { const test = (name: string, runTest: () => void | Promise<void>): void => {
@ -102,14 +104,14 @@ export const testSuite = (
if (testResult.result === "fail") { if (testResult.result === "fail") {
console.error( console.error(
`[TEST FAILURE] "${suiteName}": "${testResult.testName}": ` + `[TEST FAILURE] "${suiteName}": "${testResult.testName}": ` +
`${testResult.error.stack}\n`, `${testResult.error.stack}\n`
); );
continue; continue;
} }
passed += 1; passed += 1;
} }
console.info( console.info(
`[TEST] suite "${suiteName}": ${passed} of ${tests.length} succeeded\n\n`, `[TEST] suite "${suiteName}": ${passed} of ${tests.length} succeeded\n\n`
); );
if (passed < tests.length) { if (passed < tests.length) {
process.exitCode = 1; process.exitCode = 1;

View file

@ -20,7 +20,7 @@ export const shuffle = <T>(arr: T[]): void => {
}; };
const areArraysEqual = <T>(a: T[], b: T[]): boolean => { const areArraysEqual = <T>(a: T[], b: T[]): boolean => {
if (a.length !== b.length) { if (a.length != b.length) {
return false; return false;
} }
for (let i = 0; i < a.length; i++) { for (let i = 0; i < a.length; i++) {
@ -33,7 +33,7 @@ const areArraysEqual = <T>(a: T[], b: T[]): boolean => {
const areObjectsEqual = <T extends Record<string, unknown>>( const areObjectsEqual = <T extends Record<string, unknown>>(
a: T, a: T,
b: T, b: T
): boolean => { ): boolean => {
const aKeys = Object.keys(a) as Array<keyof T>; const aKeys = Object.keys(a) as Array<keyof T>;
const bKeys = Object.keys(b) as Array<keyof T>; const bKeys = Object.keys(b) as Array<keyof T>;
@ -67,7 +67,7 @@ export const areEqual = <T>(a: T, b: T): boolean => {
if (typeof a === "object" && typeof b === "object") { if (typeof a === "object" && typeof b === "object") {
return areObjectsEqual( return areObjectsEqual(
a as Record<string, unknown>, a as Record<string, unknown>,
b as Record<string, unknown>, b as Record<string, unknown>
); );
} }
return a === b; return a === b;

View file

@ -3,9 +3,9 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { fork } from "node:child_process"; import { fork } from "child_process";
import * as fs from "node:fs"; import * as fs from "fs";
import * as path from "node:path"; import * as path from "path";
import { shuffle } from "./lib/utils"; import { shuffle } from "./lib/utils";

View file

@ -3,9 +3,9 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { fork } from "node:child_process"; import { fork } from "child_process";
import * as fs from "node:fs"; import * as fs from "fs";
import * as path from "node:path"; import * as path from "path";
import { shuffle } from "./lib/utils"; import { shuffle } from "./lib/utils";

View file

@ -3,14 +3,14 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { type Component, createElement, Fragment } from "../../dist"; import { Component, createElement, Fragment } from "../../dist";
import { renderPage } from "../../dist/render"; import { renderPage } from "../../dist/render";
import { testSuite } from "../lib"; import { testSuite } from "../lib";
testSuite("renderPage", ({ test, expect }) => { testSuite("renderPage", ({ test, expect }) => {
test("throws an Error when root elem is not html tag", () => { test("throws an Error when root elem is not html tag", () => {
expect(() => renderPage(<div />)).toThrowErrorMatching( expect(() => renderPage(<div />)).toThrowErrorMatching(
"attempted to render page with non-HTML root element div", "attempted to render page with non-HTML root element div"
); );
}); });
@ -20,9 +20,11 @@ testSuite("renderPage", ({ test, expect }) => {
}); });
test("escapes HTML in tag names", () => { test("escapes HTML in tag names", () => {
const html = renderPage(<html>{createElement("div></div", null)}</html>); const html = renderPage(
<html>{createElement("div></div", null)}</html>
);
expect(html).toEqual( expect(html).toEqual(
"<!DOCTYPE html><html><div&gt;&lt;/div></div&gt;&lt;/div></html>", "<!DOCTYPE html><html><div&gt;&lt;/div></div&gt;&lt;/div></html>"
); );
}); });
@ -30,10 +32,10 @@ testSuite("renderPage", ({ test, expect }) => {
const html = renderPage( const html = renderPage(
<html> <html>
<div className="test" id="1" /> <div className="test" id="1" />
</html>, </html>
); );
expect(html).toEqual( expect(html).toEqual(
'<!DOCTYPE html><html><div class="test" id="1"></div></html>', '<!DOCTYPE html><html><div class="test" id="1"></div></html>'
); );
}); });
@ -46,16 +48,18 @@ testSuite("renderPage", ({ test, expect }) => {
<body> <body>
<div /> <div />
</body> </body>
</html>, </html>
); );
expect(html).toEqual( expect(html).toEqual(
"<!DOCTYPE html><html><head><title></title></head><body><div></div></body></html>", "<!DOCTYPE html><html><head><title></title></head><body><div></div></body></html>"
); );
}); });
test("renders text nodes", () => { test("renders text nodes", () => {
const html = renderPage(<html>There are three lights!</html>); const html = renderPage(<html>There are three lights!</html>);
expect(html).toEqual("<!DOCTYPE html><html>There are three lights!</html>"); expect(html).toEqual(
"<!DOCTYPE html><html>There are three lights!</html>"
);
}); });
test("renders spliced number nodes", () => { test("renders spliced number nodes", () => {
@ -76,10 +80,10 @@ testSuite("renderPage", ({ test, expect }) => {
<Light lightN={lightN} /> <Light lightN={lightN} />
))}{" "} ))}{" "}
lights! lights!
</html>, </html>
); );
expect(html).toEqual( expect(html).toEqual(
"<!DOCTYPE html><html>There are <div>1</div><div>2</div><div>3</div> lights!</html>", "<!DOCTYPE html><html>There are <div>1</div><div>2</div><div>3</div> lights!</html>"
); );
}); });
@ -93,10 +97,10 @@ testSuite("renderPage", ({ test, expect }) => {
const html = renderPage( const html = renderPage(
<html> <html>
There are <Light nLights={3} />! There are <Light nLights={3} />!
</html>, </html>
); );
expect(html).toEqual( expect(html).toEqual(
"<!DOCTYPE html><html>There are <div>3 lights</div>!</html>", "<!DOCTYPE html><html>There are <div>3 lights</div>!</html>"
); );
}); });
@ -107,43 +111,10 @@ testSuite("renderPage", ({ test, expect }) => {
<div>test of</div> <div>test of</div>
<div>fragments</div> <div>fragments</div>
</Fragment> </Fragment>
</html>, </html>
); );
expect(html).toEqual( expect(html).toEqual(
"<!DOCTYPE html><html><div>test of</div><div>fragments</div></html>", "<!DOCTYPE html><html><div>test of</div><div>fragments</div></html>"
);
});
test("renders unescaped HTML via dangerouslySetInnerHTML", () => {
const html = renderPage(
<html>
<div
dangerouslySetInnerHTML={{
__html: "<div>red alert!</div>",
}}
/>
</html>,
);
expect(html).toEqual(
"<!DOCTYPE html><html><div><div>red alert!</div></div></html>",
);
});
test("throws error when both dangerouslySetInnerHTML and children prop present", () => {
expect(() =>
renderPage(
<html>
<div
dangerouslySetInnerHTML={{
__html: "<div>set phasers to kill</div>",
}}
>
<div>set phasers to stun</div>
</div>
</html>,
),
).toThrowErrorMatching(
'An element with children may not have a "dangerouslySetInnerHTML" prop since children would be overriden',
); );
}); });
}); });