Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 10 additions & 84 deletions bin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
}

Expand Down
35 changes: 33 additions & 2 deletions docs/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <path>`, `-s <path>` | Source directory to receive the defaults (default: `src`). |
| `--language <language>` | Eject `js` (default) or `ts` files. |
| `--css <preset>` | Global CSS preset: `mine` (default), `tailwind`, or `none`. |

| `--framework <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

Expand All @@ -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.

Expand All @@ -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`
Expand Down
13 changes: 13 additions & 0 deletions eject-deps/README.md
Original file line number Diff line number Diff line change
@@ -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`.
16 changes: 16 additions & 0 deletions eject-deps/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions lib/cli/args.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions lib/cli/banner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/** Shared, unstyled DOMStack ASCII header for CLI output. */
export const domstackBanner = ` +##.
.:. ###
####. :+ ###
:#####. .:+. .: :. :: :+. +##. :+. .+: ###.:.
:#####+ :#####+ :##+########: .+#####.#####. +####. .+#### ######:
.##: ###.###:###.+###+######## +##:###..###. :#####+ #####+ ###:###:
.##: ###.##+ :##. ### +##..### ### .#+ ### #:.##+ ###.. ###.##:
.##: ###.##+ :##. ### +##. ### +######: ### #::##+ ### #####+
.##: ###.##+ :##. ### +##..### .###:##+ ### #####+ ### ######.
:### ###.###.:##. ### +##..### +#: ##+ ### .+##:##+ ###+. ###.##+
.######+ ####### .### ###: ###:.######: ###+.#######:+####+.### ####
:##+. :##+. +#+ .##. :##. :##+. :##: .##++#+ :###. +#: .##:`
75 changes: 75 additions & 0 deletions lib/cli/eject-features.js
Original file line number Diff line number Diff line change
@@ -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<string, string>} */
const files = {
'globals/global.css': css === 'mine'
? mineStyle
: css === 'tailwind' ? '@import "tailwindcss" source("../");\n' : '/* No global styles. */\n',
}
/** @type {Record<string, string>} */
const dependencies = { fragtml: pkg.dependencies.fragtml }
/** @type {Record<string, string>} */
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' : ''
Comment thread
bcomnes marked this conversation as resolved.
Resolved
files[`globals/esbuild.settings.${extension}`] = `${typeImport}${pluginImport}
${annotation}export default function esbuildSettingsOverride (${parameter})${returnType} {
${jsxSettings}${pluginSettings} return settings
}
`
}

return { files, dependencies, devDependencies }
}
Loading