diff --git a/bin.js b/bin.js index d79b6872..6440e22e 100755 --- a/bin.js +++ b/bin.js @@ -7,25 +7,22 @@ * @import { BsInstance } from '@domstack/sync' */ -import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { readFile } from 'node:fs/promises' import { basename, resolve, join, relative } from 'node:path' -import readline from 'node:readline' import process from 'process' import tree from 'pretty-tree' import { inspect } from 'util' import { createServer } from '@domstack/sync' -import { packageDirectory } from 'package-directory' -import { copyFile } from './lib/helpers/copy-file.js' -import { addPackageDependencies } from './lib/helpers/add-package-dependencies.js' import { DomStack } from './index.js' import { DomStackAggregateError } from './lib/helpers/domstack-aggregate-error.js' import { generateTreeData } from './lib/helpers/generate-tree-data.js' -import { askYesNo } from './lib/helpers/cli-prompt.js' + import { createDomStackLogger } from './lib/logger.js' import { CliUsageError, parseCliArgs } from './lib/cli/args.js' import { formatCliHelp } from './lib/cli/help.js' +import { eject } from './lib/cli/eject.js' const __dirname = import.meta.dirname @@ -54,84 +51,13 @@ async function run () { const src = resolve(join(cwd, String(argv['src']))) if (command === 'eject') { - const language = argv['language'] - - const localPkg = await packageDirectory({ cwd: src }) - - if (!localPkg) { - console.error('Can\'t locate package.json, exiting without making changes') - process.exit(1) - } - - const localPkgJson = join(localPkg, 'package.json') - const localPkgJsonContents = await getPkg(localPkgJson) - const targetIsModule = localPkgJsonContents.type === 'module' - - const relativeSrc = relative(process.cwd(), src) - const relativePkg = relative(process.cwd(), localPkgJson) - - const extension = language === 'ts' ? (targetIsModule ? 'ts' : 'mts') : targetIsModule ? 'js' : 'mjs' - const targetLayoutPath = `layouts/root.layout.${extension}` - const targetGlobalStylePath = 'globals/global.css' - const targetGlobalClientPath = `globals/global.client.${language === 'ts' ? 'ts' : extension}` - - const tbPkgContents = await getPkg() - const mineVersion = tbPkgContents?.['dependencies']?.['mine.css'] - const fragtmlVersion = tbPkgContents?.['dependencies']?.['fragtml'] - const highlightVersion = tbPkgContents?.['dependencies']?.['highlight.js'] - - if (!mineVersion || !fragtmlVersion || !highlightVersion) { - console.error('Unable to resolve ejected dependency versions. Exiting...') - process.exit(1) - } - - console.log(` -domstack eject actions: - - Write ${join(relativeSrc, targetLayoutPath)} - - Write ${join(relativeSrc, targetGlobalStylePath)} - - Write ${join(relativeSrc, targetGlobalClientPath)} - - Add mine.css@${mineVersion} to ${relativePkg} - - Add fragtml@${fragtmlVersion} to ${relativePkg} - - Add highlight.js@${highlightVersion} to ${relativePkg} -`) - if (!argv['yes']) { - const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) - let answer - try { - answer = await askYesNo(rl, 'Continue?') - } finally { - rl.close() - } - if (!answer) { - console.log('No action taken. Exiting.') - process.exit(0) - } - } - - const defaultLayoutPath = join(__dirname, `lib/defaults/default.root.layout.${language}`) - const defaultGlobalStylePath = join(__dirname, 'lib/defaults/default.style.css') - const defaultGlobalClientPath = join(__dirname, 'lib/defaults/default.client.js') - - const layoutSource = await readFile(defaultLayoutPath, 'utf8') - const layout = language === 'ts' - ? layoutSource.replace("from '#types'", "from '@domstack/static/types.js'") - : layoutSource - await mkdir(join(src, 'layouts'), { recursive: true }) - await Promise.all([ - writeFile(join(src, targetLayoutPath), layout), - copyFile(defaultGlobalStylePath, join(src, targetGlobalStylePath)), - copyFile(defaultGlobalClientPath, join(src, targetGlobalClientPath)), - ]) - - await addPackageDependencies( - localPkgJson, - { - 'mine.css': mineVersion, - fragtml: fragtmlVersion, - 'highlight.js': highlightVersion, - }) - - console.log('Done ejecting files!') + await eject({ + src, + yes: Boolean(argv['yes']), + language: /** @type {'js' | 'ts'} */ (argv['language']), + framework: /** @type {'none' | 'preact' | 'react'} */ (argv['framework']), + css: /** @type {'mine' | 'tailwind' | 'none'} */ (argv['css']), + }) process.exit(0) } diff --git a/docs/cli/README.md b/docs/cli/README.md index d38151c0..6fa027e7 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -125,18 +125,28 @@ This allows you to fully customize these files while maintaining the same functi domstack eject domstack eject --language ts domstack eject --language ts --yes --src src +domstack eject --css tailwind --framework preact +domstack eject --css tailwind --framework react --language ts +domstack eject --css none --src website ``` | Option | Description | | --- | --- | | `--src `, `-s ` | Source directory to receive the defaults (default: `src`). | | `--language ` | Eject `js` (default) or `ts` files. | +| `--css ` | Global CSS preset: `mine` (default), `tailwind`, or `none`. | + +| `--framework ` | JSX integration: `none` (default), `preact`, or `react`. | | `--yes` | Skip confirmation before writing files and updating dependencies. | | `--help`, `-h` | Show eject help. | | `--version`, `-v` | Show the installed version. | Without `--yes`, eject asks for confirmation before writing files or updating dependencies. -Eject overwrites its target files, so review or back up existing customizations before proceeding. +Eject overwrites its default layout, global CSS, and client target files, so review or back up existing customizations before proceeding. +Existing dependencies and settings are not removed when switching presets. +When a preset needs esbuild settings, eject refuses conflicting settings anywhere under the source directory before changing any files or package metadata. +An identical generated settings file at the expected path can be reused; other locations or extensions must be reconciled manually to avoid duplicate settings. +Plain eject does not generate or change settings. ### Ejecting the defaults @@ -156,7 +166,7 @@ When you run `domstack eject`, it will: Use `domstack eject --language ts` to write `layouts/root.layout.ts` and `globals/global.client.ts` instead. For packages without `"type": "module"`, the TypeScript layout uses `.mts` so Node loads it as ESM without changing your package type. -The CSS and added dependencies are the same for both languages. +The CSS preset is independent of the selected language. JavaScript remains the default (`--language js`), with `.js` files in module packages and `.mjs` files otherwise. Only `ts` and `js` are accepted language values. @@ -166,6 +176,27 @@ The TypeScript output uses the public type-only `@domstack/static/types.js` entr Keep `@domstack/static` installed for those types; no runtime type import or separate TypeScript compilation step is needed. The client is currently comment-only, but receives a `.ts` extension when TypeScript is selected. +### CSS and framework presets + +`--css mine` copies the bundled `default.style.css` and adds `mine.css`, `highlight.js`, and `fragtml` as dependencies. +This is the default and preserves the behavior of plain `domstack eject`. + +`--css tailwind` writes `@import "tailwindcss" source("../");` to `globals/global.css` and adds `esbuild-plugin-tailwindcss` as a development dependency. +The source path is relative to the generated CSS file, so it scans your source directory even with a custom `--src`. +It does not add `mine.css` or `highlight.js`. + +`--css none` writes a comment-only `globals/global.css` to suppress bundled global styling without adding CSS dependencies. +All presets add `fragtml`, which the ejected root layout requires. + +`--framework preact` adds `preact`; `--framework react` adds `react` and `react-dom`. +React with `--language ts` also adds `@types/react` and `@types/react-dom` as development dependencies. +Both frameworks configure esbuild's automatic JSX transform and the matching JSX import source; they do not generate sample components or a TypeScript configuration. + +Eject generates `globals/esbuild.settings.js` only when selecting a framework or Tailwind. +The settings use `.ts` with `--language ts`, or `.mjs`/`.mts` for packages without `"type": "module"`. +The Tailwind integration appends its plugin without dropping other build plugins. +Eject updates `package.json` but does not install packages or update your lockfile; run your package manager's install command afterward. + It is recommended to eject early in your project so that you can customize the root layout as you see fit, and decouple yourself from potential unwanted changes in the default layout as new versions of DOMStack are released. ## `domstack help` diff --git a/eject-deps/README.md b/eject-deps/README.md new file mode 100644 index 00000000..b17347b5 --- /dev/null +++ b/eject-deps/README.md @@ -0,0 +1,13 @@ +# Eject dependencies + +This private npm workspace holds the dependency ranges for DOMStack's optional ejected integrations: React, Preact, their types, and the Tailwind esbuild plugin. +Dependabot maintains these ranges through the root npm workspace configuration. + +`npm run build:defaults` extracts the declared ranges into `lib/defaults/eject-deps.json`, rather than inspecting installed packages. +The generated JSON is checked in so a fresh checkout works without a build, and the test, build, and release flows regenerate it from this workspace. +Run `npm run build:defaults` after changing the ranges; do not edit the generated JSON directly. + +`lib/cli/eject-features.js` reads the generated JSON so eject and `create-domstack-app` use the same metadata. +Only that data file ships in the DOMStack tarball; this workspace's `package.json` is not included, and the workspace is not published separately. + +Dependencies used by the bundled defaults, including `fragtml`, `mine.css`, and `highlight.js`, remain sourced from DOMStack's root `package.json`. diff --git a/eject-deps/package.json b/eject-deps/package.json new file mode 100644 index 00000000..4f41ab0c --- /dev/null +++ b/eject-deps/package.json @@ -0,0 +1,16 @@ +{ + "name": "@domstack/eject-dependencies", + "version": "0.0.0", + "private": true, + "description": "Dependency ranges for DOMStack's ejected integrations; not a runtime package.", + "dependencies": { + "preact": "^10.29.6", + "react": "^19.1.1", + "react-dom": "^19.1.1" + }, + "devDependencies": { + "@types/react": "^19.1.10", + "@types/react-dom": "^19.1.7", + "esbuild-plugin-tailwindcss": "2.2.0" + } +} diff --git a/index.js b/index.js index d1536d62..4bb58e39 100644 --- a/index.js +++ b/index.js @@ -13,6 +13,7 @@ import { builder } from './lib/builder.js' import { createDomStackLogger } from './lib/logger.js' import { DomStackWatcher } from './lib/watch/index.js' +export { domstackBanner } from './lib/cli/banner.js' export { PageData } from './lib/build-pages/page/page-data.js' export { DOMSTACK_MANIFEST_SCHEMA_ID, diff --git a/lib/cli/args.js b/lib/cli/args.js index 7bffc1f5..f62188cb 100644 --- a/lib/cli/args.js +++ b/lib/cli/args.js @@ -106,6 +106,14 @@ function validateValues (command, values) { if (command === 'eject' && values['language'] !== 'js' && values['language'] !== 'ts') { throw new Error('--language must be ts or js') } + if (command === 'eject') { + if (!['mine', 'tailwind', 'none'].includes(String(values['css']))) { + throw new Error('--css must be mine, tailwind or none') + } + if (!['none', 'preact', 'react'].includes(String(values['framework']))) { + throw new Error('--framework must be none, preact or react') + } + } if (values['port'] !== undefined) { const port = Number(values['port']) if (!Number.isInteger(port) || port < 1 || port > 65535) { diff --git a/lib/cli/banner.js b/lib/cli/banner.js new file mode 100644 index 00000000..a3ea8481 --- /dev/null +++ b/lib/cli/banner.js @@ -0,0 +1,13 @@ +/** Shared, unstyled DOMStack ASCII header for CLI output. */ +export const domstackBanner = ` +##. +.:. ### +####. :+ ### +:#####. .:+. .: :. :: :+. +##. :+. .+: ###.:. + :#####+ :#####+ :##+########: .+#####.#####. +####. .+#### ######: +.##: ###.###:###.+###+######## +##:###..###. :#####+ #####+ ###:###: +.##: ###.##+ :##. ### +##..### ### .#+ ### #:.##+ ###.. ###.##: +.##: ###.##+ :##. ### +##. ### +######: ### #::##+ ### #####+ +.##: ###.##+ :##. ### +##..### .###:##+ ### #####+ ### ######. +:### ###.###.:##. ### +##..### +#: ##+ ### .+##:##+ ###+. ###.##+ +.######+ ####### .### ###: ###:.######: ###+.#######:+####+.### #### + :##+. :##+. +#+ .##. :##. :##+. :##: .##++#+ :###. +#: .##:` diff --git a/lib/cli/eject-features.js b/lib/cli/eject-features.js new file mode 100644 index 00000000..5d1ff38b --- /dev/null +++ b/lib/cli/eject-features.js @@ -0,0 +1,75 @@ +/** + * @typedef {'js' | 'ts'} Language + * @typedef {'none' | 'preact' | 'react'} Framework + * @typedef {'mine' | 'tailwind' | 'none'} Css + * @typedef {{ language?: Language, framework?: Framework, css?: Css, module?: boolean }} EjectFeaturesOptions + */ + +import { readFileSync } from 'node:fs' + +const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) +const mineStyle = readFileSync(new URL('../defaults/default.style.css', import.meta.url), 'utf8') + +// Generated at build time from the Dependabot-maintained eject-deps workspace. +const versions = JSON.parse(readFileSync(new URL('../defaults/eject-deps.json', import.meta.url), 'utf8')) + +/** + * Generate source-relative integration files without writing or installing anything. + * `module` defaults to true; false selects .mjs/.mts settings for non-ESM packages. + * @param {EjectFeaturesOptions} [options] + */ +export function ejectFeatures ({ language = 'js', framework = 'none', css = 'mine', module = true } = {}) { + if (!['js', 'ts'].includes(language)) throw new Error('--language must be ts or js') + if (!['none', 'preact', 'react'].includes(framework)) throw new Error('--framework must be none, preact or react') + if (!['mine', 'tailwind', 'none'].includes(css)) throw new Error('--css must be mine, tailwind or none') + + /** @type {Record} */ + const files = { + 'globals/global.css': css === 'mine' + ? mineStyle + : css === 'tailwind' ? '@import "tailwindcss" source("../");\n' : '/* No global styles. */\n', + } + /** @type {Record} */ + const dependencies = { fragtml: pkg.dependencies.fragtml } + /** @type {Record} */ + const devDependencies = {} + + if (css === 'mine') { + dependencies['mine.css'] = pkg.dependencies['mine.css'] + dependencies['highlight.js'] = pkg.dependencies['highlight.js'] + } + if (framework === 'preact') dependencies['preact'] = versions.preact + if (framework === 'react') { + dependencies['react'] = versions.react + dependencies['react-dom'] = versions['react-dom'] + if (language === 'ts') { + devDependencies['@types/react'] = versions['@types/react'] + devDependencies['@types/react-dom'] = versions['@types/react-dom'] + } + } + if (css === 'tailwind') devDependencies['esbuild-plugin-tailwindcss'] = versions['esbuild-plugin-tailwindcss'] + + if (framework !== 'none' || css === 'tailwind') { + const extension = module ? language : language === 'ts' ? 'mts' : 'mjs' + const typeImport = language === 'ts' + ? "import type { BuildOptions } from '@domstack/static/types.js'\n" + : "/** @import { BuildOptions } from '@domstack/static/types.js' */\n" + const pluginImport = css === 'tailwind' ? "import tailwindPlugin from 'esbuild-plugin-tailwindcss'\n" : '' + const annotation = language === 'js' ? '/** @param {BuildOptions} settings */\n' : '' + const parameter = language === 'ts' ? 'settings: BuildOptions' : 'settings' + const returnType = language === 'ts' ? ': BuildOptions' : '' + const jsxSettings = framework === 'none' + ? '' + : ` settings.jsx = 'automatic' + settings.jsxImportSource = '${framework}' +` + const pluginSettings = css === 'tailwind' ? ' settings.plugins = [...(settings.plugins ?? []), tailwindPlugin()]\n' : '' + files[`globals/esbuild.settings.${extension}`] = `${typeImport}${pluginImport} +${annotation}export default function esbuildSettingsOverride (${parameter})${returnType} { +${jsxSettings}${pluginSettings} return settings +} +` + } + + return { files, dependencies, devDependencies } +} diff --git a/lib/cli/eject-features.test.js b/lib/cli/eject-features.test.js new file mode 100644 index 00000000..509ddc3a --- /dev/null +++ b/lib/cli/eject-features.test.js @@ -0,0 +1,95 @@ +/** + * @import { Language, Framework, Css } from './eject-features.js' + */ + +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import { test } from 'node:test' +import { ESLint } from 'eslint' +import { neostandard } from 'neostandard' +import { CliUsageError, parseCliArgs } from './args.js' +import { ejectFeatures } from './eject-features.js' + +const integrationManifest = JSON.parse(await readFile(new URL('../../eject-deps/package.json', import.meta.url), 'utf8')) +const versions = { ...integrationManifest.dependencies, ...integrationManifest.devDependencies } + +const eslint = new ESLint({ overrideConfigFile: true, overrideConfig: neostandard({ ts: true, filesTs: ['**/*.{ts,mts}'] }) }) + +for (const language of /** @type {Language[]} */ (['js', 'ts'])) { + for (const framework of /** @type {Framework[]} */ (['none', 'preact', 'react'])) { + for (const css of /** @type {Css[]} */ (['mine', 'tailwind', 'none'])) { + for (const module of [true, false]) { + test(`pure eject features: ${language}, ${framework}, ${css}, module=${module}`, async () => { + const options = { language, framework, css, module } + const result = ejectFeatures(options) + assert.deepEqual(result, ejectFeatures(options)) + const { files, dependencies, devDependencies } = result + assert.ok(dependencies['fragtml']) + assert.equal(Boolean(dependencies['mine.css']), css === 'mine') + assert.equal(Boolean(dependencies['highlight.js']), css === 'mine') + assert.equal(dependencies['preact'], framework === 'preact' ? versions.preact : undefined) + assert.equal(dependencies['react'], framework === 'react' ? versions.react : undefined) + assert.equal(dependencies['react-dom'], framework === 'react' ? versions['react-dom'] : undefined) + assert.equal(devDependencies['@types/react'], framework === 'react' && language === 'ts' ? versions['@types/react'] : undefined) + assert.equal(devDependencies['@types/react-dom'], framework === 'react' && language === 'ts' ? versions['@types/react-dom'] : undefined) + assert.equal(devDependencies['esbuild-plugin-tailwindcss'], css === 'tailwind' ? versions['esbuild-plugin-tailwindcss'] : undefined) + if (css === 'mine') { + assert.equal(files['globals/global.css'], await readFile(new URL('../defaults/default.style.css', import.meta.url), 'utf8')) + } else if (css === 'tailwind') { + assert.equal(files['globals/global.css'], '@import "tailwindcss" source("../");\n') + } else { + assert.equal(files['globals/global.css'], '/* No global styles. */\n') + } + const extension = module ? language : language === 'ts' ? 'mts' : 'mjs' + const settings = files[`globals/esbuild.settings.${extension}`] + assert.equal(Boolean(settings), framework !== 'none' || css === 'tailwind') + if (settings) { + if (framework !== 'none') assert.match(settings, new RegExp(`settings.jsxImportSource = '${framework}'`)) + if (css === 'tailwind') assert.match(settings, /settings.plugins = \[\.\.\.\(settings.plugins \?\? \[\]\), tailwindPlugin\(\)\]/) + const results = await eslint.lintText(settings, { filePath: `esbuild.settings.${extension}` }) + assert.deepEqual(results.flatMap(result => result.messages), []) + } + }) + } + } + } +} + +test('eject CSS choices and defaults work for explicit and legacy commands', () => { + for (const mode of ['eject', '--eject']) { + assert.equal(parseCliArgs([mode]).values['css'], 'mine') + assert.equal(parseCliArgs([mode]).values['framework'], 'none') + for (const css of ['mine', 'tailwind', 'none']) { + assert.equal(parseCliArgs([mode, '--css', css]).values['css'], css) + } + assert.throws(() => parseCliArgs([mode, '--tailwind']), /Unknown option/) + for (const args of [ + ['--css', 'invalid'], ['--framework', 'vue'], ['--css', ''], ['--framework', ''], + + ]) { + assert.throws(() => parseCliArgs([mode, ...args]), CliUsageError) + } + } + for (const command of ['build', 'watch', 'serve']) { + for (const args of [['--tailwind'], ['--css', 'mine'], ['--framework', 'react']]) { + assert.throws(() => parseCliArgs([command, ...args]), CliUsageError) + } + } +}) + +test('integration ranges come from a private workspace without publishing its manifest', async () => { + const pkg = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8')) + assert.equal(integrationManifest.private, true) + assert.ok(pkg.workspaces.includes('eject-deps')) + assert.ok(!pkg.files.includes('eject-deps/package.json')) + assert.ok(pkg.files.includes('lib/**/*.json')) + const generated = JSON.parse(await readFile(new URL('../defaults/eject-deps.json', import.meta.url), 'utf8')) + assert.deepEqual(generated, versions) +}) + +test('pure features reject unsupported presets', () => { + for (const options of [{ language: 'tsx' }, { framework: 'vue' }, { css: 'bootstrap' }]) { + // @ts-expect-error deliberately invalid options + assert.throws(() => ejectFeatures(options)) + } +}) diff --git a/lib/cli/eject.js b/lib/cli/eject.js new file mode 100644 index 00000000..9f67e31b --- /dev/null +++ b/lib/cli/eject.js @@ -0,0 +1,100 @@ +/** @import { EjectFeaturesOptions } from './eject-features.js' */ + +import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises' +import { dirname, join, relative, resolve } from 'node:path' +import readline from 'node:readline' +import { packageDirectory } from 'package-directory' +import { addPackageDependencies } from '../helpers/add-package-dependencies.js' +import { askYesNo } from '../helpers/cli-prompt.js' +import { CliUsageError } from './args.js' +import { ejectFeatures } from './eject-features.js' + +/** + * Check all settings locations, not just the generated filename: DOMStack finds + * these files anywhere under src and otherwise warns and picks the first one. + * @param {string} src + * @param {string} target + * @param {string} content + */ +async function checkSettings (src, target, content) { + /** @param {string} directory */ + async function visit (directory) { + let entries + try { + entries = await readdir(directory, { withFileTypes: true }) + } catch (error) { + if (/** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT') return + throw error + } + for (const entry of entries) { + const path = join(directory, entry.name) + if (entry.isDirectory()) { + if (entry.name !== 'node_modules' && entry.name !== '.git') await visit(path) + } else if (/^esbuild\.settings\.(?:[mc]?[jt]s)$/.test(entry.name)) { + if (path !== target || await readFile(path, 'utf8') !== content) { + throw new CliUsageError(`Existing esbuild settings conflict at ${path}. Move or reconcile them before ejecting; no files were changed.`, 'eject') + } + } + } + } + await visit(src) +} + +/** + * @param {EjectFeaturesOptions & { src: string, yes?: boolean }} options + */ +export async function eject ({ src, yes = false, language = 'js', framework = 'none', css = 'mine' }) { + src = resolve(src) + const packageRoot = await packageDirectory({ cwd: src }) + if (!packageRoot) throw new CliUsageError("Can't locate package.json, exiting without making changes", 'eject') + const packagePath = join(packageRoot, 'package.json') + const pkg = JSON.parse((await readFile(packagePath, 'utf8')).replace(/^\uFEFF/, '')) + const isModule = pkg.type === 'module' + const { files, dependencies, devDependencies } = ejectFeatures({ language, framework, css, module: isModule }) + const extension = isModule ? language : language === 'ts' ? 'mts' : 'mjs' + const layoutSource = await readFile(new URL(`../defaults/default.root.layout.${language}`, import.meta.url), 'utf8') + files[`layouts/root.layout.${extension}`] = language === 'ts' + ? layoutSource.replace("from '#types'", "from '@domstack/static/types.js'") + : layoutSource + files[`globals/global.client.${language === 'ts' ? 'ts' : extension}`] = await readFile(new URL('../defaults/default.client.js', import.meta.url), 'utf8') + + const settings = Object.entries(files).find(([path]) => path.startsWith('globals/esbuild.settings.')) + if (settings) await checkSettings(src, join(src, settings[0]), settings[1]) + + console.log(`\ndomstack eject actions:\n${[ + ...Object.keys(files).map(path => ` - Write ${relative(process.cwd(), join(src, path))}`), + ...Object.entries(dependencies).map(([name, version]) => ` - Add ${name}@${version} to ${relative(process.cwd(), packagePath)}`), + ...Object.entries(devDependencies).map(([name, version]) => ` - Add ${name}@${version} to devDependencies in ${relative(process.cwd(), packagePath)}`), + ].join('\n')}\n`) + + if (!yes) { + const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) + let answer + try { + answer = await askYesNo(rl, 'Continue?') + } finally { + rl.close() + } + if (!answer) { + console.log('No action taken. Exiting.') + return + } + } + + for (const [path, content] of Object.entries(files)) { + const target = join(src, path) + await mkdir(dirname(target), { recursive: true }) + // Settings are never overwritten, even if they appear after preflight. + if (path.startsWith('globals/esbuild.settings.')) { + try { + await writeFile(target, content, { flag: 'wx' }) + } catch (error) { + if (/** @type {NodeJS.ErrnoException} */ (error).code !== 'EEXIST' || await readFile(target, 'utf8') !== content) throw error + } + } else { + await writeFile(target, content) + } + } + await addPackageDependencies(packagePath, dependencies, devDependencies) + console.log('Done ejecting files!') +} diff --git a/lib/cli/help.js b/lib/cli/help.js index ea1d519d..fa4d17f9 100644 --- a/lib/cli/help.js +++ b/lib/cli/help.js @@ -1,6 +1,8 @@ /** @import { CommandName } from './options.js' */ +import { styleText } from 'node:util' import { formatHelpText } from 'argsclopts' +import { domstackBanner } from './banner.js' import { commands } from './options.js' /** @@ -9,7 +11,7 @@ import { commands } from './options.js' */ export async function formatCliHelp (command, version) { const definition = commands[command ?? 'build'] - return formatHelpText({ + const help = await formatHelpText({ name: 'domstack', version, options: definition.options, @@ -34,4 +36,5 @@ export async function formatCliHelp (command, version) { `domstack (v${version})`, ].join('\n'), }) + return `${styleText('cyan', domstackBanner)}\n\n${help}` } diff --git a/lib/cli/help.test.js b/lib/cli/help.test.js new file mode 100644 index 00000000..c1c93961 --- /dev/null +++ b/lib/cli/help.test.js @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict' +import { stripVTControlCharacters } from 'node:util' +import test from 'node:test' +import { domstackBanner } from './banner.js' +import { domstackBanner as publicBanner } from '../../index.js' +import { formatCliHelp } from './help.js' + +test('exports an unstyled shared DOMStack banner', () => { + assert.equal(publicBanner, domstackBanner) + assert.equal(domstackBanner, stripVTControlCharacters(domstackBanner)) + assert.equal(domstackBanner.split('\n').length, 12) +}) + +for (const command of /** @type {const} */ ([null, 'build', 'watch', 'serve', 'eject'])) { + test(`includes the shared banner in ${command ?? 'root'} help`, async () => { + const help = stripVTControlCharacters(await formatCliHelp(command, '1.2.3')) + assert.ok(help.startsWith(`${domstackBanner}\n\n`)) + assert.equal(help.split(domstackBanner).length, 2) + assert.ok(help.includes(command ? `Usage: domstack ${command} [options]` : 'Usage: domstack [command] [options]')) + assert.ok(help.includes('domstack (v1.2.3)')) + if (command === 'eject') { + assert.ok(help.includes('js (JavaScript) or ts (TypeScript)')) + assert.ok(help.includes('mine (default, mine.css and syntax themes)')) + assert.ok(help.includes('tailwind (Tailwind CSS and esbuild plugin)')) + assert.ok(help.includes('none (no global styles)')) + assert.ok(help.includes('none (no integration), preact, or react')) + assert.ok(!help.includes('--tailwind')) + } + }) +} diff --git a/lib/cli/options.js b/lib/cli/options.js index 652b0c51..95d80c48 100644 --- a/lib/cli/options.js +++ b/lib/cli/options.js @@ -101,10 +101,24 @@ export const commands = { example: 'domstack eject --language ts --src src', options: { ...sourceOptions, + /** Source language: 'js' | 'ts'. Both outputs are ready to use without compilation. */ language: { type: 'string', default: 'js', - help: 'language for ejected files: js or ts', + help: 'source language: js (JavaScript) or ts (TypeScript)', + }, + /** CSS preset: 'mine' | 'tailwind' | 'none'. */ + css: { + type: 'string', + default: 'mine', + help: 'global CSS preset: mine (default, mine.css and syntax themes), tailwind (Tailwind CSS and esbuild plugin), or none (no global styles)', + }, + + /** Browser JSX runtime: 'none' | 'preact' | 'react'. Does not generate example components. */ + framework: { + type: 'string', + default: 'none', + help: 'browser JSX runtime: none (no integration), preact, or react; adds runtime dependencies and automatic JSX settings', }, yes: { type: 'boolean', diff --git a/lib/cli/tests/eject.test.js b/lib/cli/tests/eject.test.js index 93925637..8d96b637 100644 --- a/lib/cli/tests/eject.test.js +++ b/lib/cli/tests/eject.test.js @@ -1,6 +1,8 @@ +/** @import { TestContext } from 'node:test' */ + import assert from 'node:assert/strict' import { execFile, spawnSync } from 'node:child_process' -import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { mkdtemp, mkdir, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { promisify } from 'node:util' @@ -9,6 +11,115 @@ import { test } from 'node:test' const exec = promisify(execFile) const project = resolve(import.meta.dirname, '../../..') const bin = join(project, 'bin.js') +const integrationManifest = JSON.parse(await readFile(join(project, 'eject-deps/package.json'), 'utf8')) + +/** @param {TestContext} t */ +async function presetSite (t, type = 'module', source = 'src') { + const cwd = await mkdtemp(join(tmpdir(), 'domstack-eject-preset-')) + t.after(() => rm(cwd, { recursive: true, force: true })) + const src = join(cwd, source) + await mkdir(src, { recursive: true }) + await writeFile(join(cwd, 'package.json'), JSON.stringify({ type, dependencies: { retained: '1.0.0' }, devDependencies: { retainedDev: '2.0.0' } })) + await writeFile(join(src, 'page.html'), '

Preset site

') + await symlink(join(project, 'node_modules'), join(cwd, 'node_modules'), 'dir') + return { cwd, src } +} + +for (const type of ['module', 'commonjs']) { + for (const language of ['js', 'ts']) { + for (const framework of ['none', 'preact', 'react']) { + for (const css of ['mine', 'none', 'tailwind']) { + test(`preset build: ${type}, ${language}, ${framework}, ${css}, custom src`, async t => { + const source = 'website/content' + const { cwd, src } = await presetSite(t, type, source) + const args = [bin, 'eject', '--yes', '--src', source, '--language', language, '--framework', framework, '--css', css] + await exec(process.execPath, args, { cwd, timeout: 30000 }) + const extension = type === 'module' ? language : language === 'ts' ? 'mts' : 'mjs' + const settingsPath = join(src, `globals/esbuild.settings.${extension}`) + if (framework !== 'none' || css === 'tailwind') { + assert.match(await readFile(settingsPath, 'utf8'), /export default function esbuildSettingsOverride/) + // Identical generated settings are safe to reuse. + await exec(process.execPath, args, { cwd, timeout: 30000 }) + } else { + await assert.rejects(readFile(settingsPath), { code: 'ENOENT' }) + } + if (framework !== 'none') { + const clientExtension = language === 'ts' ? 'tsx' : 'jsx' + const entry = framework === 'react' ? "import { createRoot } from 'react-dom/client'\n" : "import { render } from 'preact'\n" + const mount = framework === 'react' ? 'createRoot(container).render()' : 'render(, container)' + await writeFile(join(src, `client.${clientExtension}`), `${entry} +function Counter () { return } +const container = document.getElementById('counter') +if (container) ${mount} +`) + } + const pkg = JSON.parse(await readFile(join(cwd, 'package.json'), 'utf8')) + assert.equal(pkg.dependencies.retained, '1.0.0') + assert.equal(pkg.devDependencies.retainedDev, '2.0.0') + assert.ok(pkg.dependencies.fragtml) + assert.equal(Boolean(pkg.dependencies['mine.css']), css === 'mine') + assert.equal(Boolean(pkg.dependencies['highlight.js']), css === 'mine') + assert.equal(pkg.devDependencies['esbuild-plugin-tailwindcss'], css === 'tailwind' ? integrationManifest.devDependencies['esbuild-plugin-tailwindcss'] : undefined) + await exec(process.execPath, [bin, 'build', '--src', source], { cwd, timeout: 30000 }) + const html = await readFile(join(cwd, 'public/index.html'), 'utf8') + assert.match(html, /Preset site/) + assert.doesNotMatch(html, /dom-stack-defaults|default\.style/) + const outputs = await readdir(join(cwd, 'public'), { recursive: true }) + const styles = (await Promise.all(outputs.filter(path => path.endsWith('.css')).map(path => readFile(join(cwd, 'public', path), 'utf8')))).join('\n') + if (css === 'tailwind') assert.match(styles, /\.text-red-500/) + else if (css === 'mine') assert.match(styles, /mine-layout/) + else assert.equal(styles.replace(/\/\*[\s\S]*?\*\//g, '').trim(), '') + if (framework !== 'none') { + const scripts = (await Promise.all(outputs.filter(path => path.endsWith('.js')).map(path => readFile(join(cwd, 'public', path), 'utf8')))).join('\n') + assert.match(scripts, /Preset counter/) + } + }) + } + } + } +} + +for (const location of ['globals/esbuild.settings.js', 'esbuild.settings.mjs', 'nested/esbuild.settings.cts']) { + test(`settings conflict at ${location} fails before any mutations`, async t => { + const { cwd, src } = await presetSite(t) + const settingsPath = join(src, location) + await mkdir(join(settingsPath, '..'), { recursive: true }) + await writeFile(settingsPath, 'export default settings => settings\n') + await mkdir(join(src, 'layouts'), { recursive: true }) + await mkdir(join(src, 'globals'), { recursive: true }) + const sentinels = ['layouts/root.layout.js', 'globals/global.css', 'globals/global.client.js'] + for (const path of sentinels) await writeFile(join(src, path), 'Keep this customization') + const pkg = await readFile(join(cwd, 'package.json'), 'utf8') + await assert.rejects(exec(process.execPath, [bin, 'eject', '--yes', '--framework', 'preact'], { cwd, timeout: 30000 }), /Existing esbuild settings conflict/) + assert.equal(await readFile(join(cwd, 'package.json'), 'utf8'), pkg) + assert.equal(await readFile(settingsPath, 'utf8'), 'export default settings => settings\n') + for (const path of sentinels) assert.equal(await readFile(join(src, path), 'utf8'), 'Keep this customization') + if (location !== 'globals/esbuild.settings.js') await assert.rejects(readFile(join(src, 'globals/esbuild.settings.js')), { code: 'ENOENT' }) + }) +} + +test('plain eject retains settings and dependencies from previous integrations', async t => { + const { cwd, src } = await presetSite(t) + await mkdir(join(src, 'globals')) + const settings = 'export default settings => settings\n' + await writeFile(join(src, 'globals/esbuild.settings.js'), settings) + await writeFile(join(cwd, 'package.json'), JSON.stringify({ type: 'module', dependencies: { react: '^19.0.0' }, devDependencies: { 'esbuild-plugin-tailwindcss': '2.2.0' } })) + await exec(process.execPath, [bin, 'eject', '--yes'], { cwd, timeout: 30000 }) + assert.equal(await readFile(join(src, 'globals/esbuild.settings.js'), 'utf8'), settings) + const pkg = JSON.parse(await readFile(join(cwd, 'package.json'), 'utf8')) + assert.equal(pkg.dependencies.react, '^19.0.0') + assert.equal(pkg.devDependencies['esbuild-plugin-tailwindcss'], '2.2.0') +}) + +for (const args of [['--css', 'invalid'], ['--framework', 'vue'], ['--tailwind']]) { + test(`invalid preset leaves project unchanged: ${args.join(' ')}`, async t => { + const { cwd, src } = await presetSite(t) + const pkg = await readFile(join(cwd, 'package.json'), 'utf8') + await assert.rejects(exec(process.execPath, [bin, 'eject', '--yes', ...args], { cwd, timeout: 30000 })) + assert.equal(await readFile(join(cwd, 'package.json'), 'utf8'), pkg) + assert.deepEqual(await readdir(src), ['page.html']) + }) +} for (const mode of ['eject', '--eject']) { for (const type of ['module', 'commonjs']) { diff --git a/lib/defaults/default.root.layout.js b/lib/defaults/default.root.layout.js index a87badde..cd665ded 100644 --- a/lib/defaults/default.root.layout.js +++ b/lib/defaults/default.root.layout.js @@ -1,13 +1,9 @@ // Generated from default.root.layout.ts by npm run build:defaults. Do not edit. -var __freeze = Object.freeze; -var __defProp = Object.defineProperty; -var __template = (cooked, raw2) => __freeze(__defProp(cooked, "raw", { value: __freeze(raw2 || cooked.slice()) })); -var _a; -import { html, raw, render } from "fragtml"; -function defaultRootLayout({ +import { html, raw, render } from 'fragtml' +function defaultRootLayout ({ vars: { title, - siteName = "domstack", + siteName = 'domstack', basePath /* defaultStyle = true Set this to false in global or page to disable the default style in the default layout */ }, @@ -22,18 +18,18 @@ function defaultRootLayout({ - ${title ? `${title}` : ""}${title && siteName ? " | " : ""}${siteName} + ${title ? `${title}` : ''}${title && siteName ? ' | ' : ''}${siteName} - ${scripts ? scripts.map((script) => html(_a || (_a = __template(['`) : null} + ${styles ? styles.map((style) => html``) : null} -
${typeof children === "string" ? raw(children) : children}
+
${typeof children === 'string' ? raw(children) : children}
- `); + `) } export { defaultRootLayout as default -}; +} diff --git a/lib/defaults/default.root.layout.test.js b/lib/defaults/default.root.layout.test.js index 28571254..8968d561 100644 --- a/lib/defaults/default.root.layout.test.js +++ b/lib/defaults/default.root.layout.test.js @@ -1,7 +1,9 @@ import assert from 'node:assert/strict' import { test } from 'node:test' import { readFile } from 'node:fs/promises' -import { transform } from 'esbuild' +import { ESLint } from 'eslint' +import { neostandard } from 'neostandard' +import { generateDefaultRootLayout } from '../../scripts/build-defaults.js' import canonicalRootLayout from './default.root.layout.ts' import { load } from 'cheerio' import { html, raw, render } from 'fragtml' @@ -10,9 +12,41 @@ import defaultRootLayout from './default.root.layout.js' test('checked-in JavaScript matches the canonical TypeScript build', async () => { const source = await readFile(new URL('./default.root.layout.ts', import.meta.url), 'utf8') const generated = await readFile(new URL('./default.root.layout.js', import.meta.url), 'utf8') - const { code } = await transform(source, { loader: 'ts', format: 'esm', target: 'es2022', legalComments: 'inline' }) - assert.equal(generated, `// Generated from default.root.layout.ts by npm run build:defaults. Do not edit.\n${code}`) + assert.equal(generated, await generateDefaultRootLayout(source)) assert.doesNotMatch(generated, /#types|import type|@domstack\/static\/types/) + assert.match(generated, /html`