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
12 changes: 8 additions & 4 deletions bin.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { basename, resolve, relative } from 'node:path'
import process from 'process'
import tree from 'pretty-tree'
import { inspect } from 'util'
import { createServer } from '@domstack/sync'
import { createServer, parseOptions as parseSyncOptions } from '@domstack/sync'

import { DomStack } from './index.js'
import { DestinationConflictError } from './lib/destination-claim.js'
Expand All @@ -24,6 +24,7 @@ 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'
import { showWatchSessions } from './lib/cli/sessions.js'

const __dirname = import.meta.dirname

Expand All @@ -35,7 +36,7 @@ async function getPkg (pkgPath = resolve(__dirname, './package.json')) {
}

async function run () {
const { command, values: argv, helpCommand } = parseCliArgs(process.argv.slice(2))
const { command, values: argv, helpCommand, sessionId } = parseCliArgs(process.argv.slice(2))
if (argv['version']) {
const pkg = await getPkg()
console.log(pkg.version)
Expand All @@ -48,6 +49,8 @@ async function run () {

process.exit(0)
}
if (command === 'sessions') return showWatchSessions(sessionId, Boolean(argv['json']))

const cwd = process.cwd()
const src = resolve(cwd, String(argv['src']))

Expand Down Expand Up @@ -85,7 +88,7 @@ async function run () {
let buildWork
let quitting = false

const servePort = argv['port'] ? Number(argv['port']) : undefined
const preferredPort = argv['port'] ? Number(argv['port']) : undefined

process.once('SIGINT', quit)
process.once('SIGTERM', quit)
Expand Down Expand Up @@ -121,7 +124,7 @@ async function run () {
server: dest,
files: basename(dest),
logger: logger.child({ component: 'sync', logPrefix: '[domstack-sync]' }),
...(servePort ? { port: servePort } : {}),
port: preferredPort ?? parseSyncOptions().port,
snippet: false,
})
logger.info(`Serving ${relative(cwd, dest)} without watching. Press Ctrl-C to stop.`)
Expand All @@ -142,6 +145,7 @@ async function run () {
} else {
await domStack.watch({
serve: !argv['no-serve'],
port: preferredPort,
onInitialBuild: (initialResults) => {
logger.info(tree(generateTreeData(cwd, src, dest, initialResults)))
logWarnings(logger, initialResults?.warnings)
Expand Down
13 changes: 13 additions & 0 deletions docs/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,19 @@ Watch sessions retain their claim until their writes drain on shutdown; use sepa
This does not guard writes outside the configured destination or writes from tools that do not take DOMStack claims.
The `DomStackOpts` and `Results` types are available from the type-only `@domstack/static/types.js` entry.

## Watch sessions

`await site.watch({ port: 8080 })` starts a watcher and returns its initial build report.
`port` is a preference; read `site.watchInfo` for the actual bound port and URL rather than assuming the requested port was available.
Use `watch({ serve: false })` to build and watch without a server.

`watchInfo` is a fresh read-only snapshot of the current session, or `null` while idle.
It includes the session ID, process ID, start time, lifecycle state, project and build paths, and actual site and UI addresses when serving.
During early startup, the ID may still be `null`; when no server is running the addresses and ports are `null`.
The `WatchInfo` and `WatchOptions` types are exported from `@domstack/static/types.js`.
Discovery failures do not stop the watcher or prevent reading its in-process snapshot.
Call `await site.stopWatching()` to finish cleanup and remove the session from discovery.

## Test builds

Use the top-level `testBuild` helper to build into a temporary directory from tests without managing setup and cleanup yourself.
Expand Down
24 changes: 21 additions & 3 deletions docs/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ It can be used outside of this context, but it works best within it.
| `domstack` or `domstack build` | Build once and exit. |
| `domstack watch` | Build, watch for changes, and serve with live reload. |
| `domstack serve` | Build once, then serve production output without watching or live reload. |
| `domstack sessions [id]` | List active local watch sessions or inspect one by ID. |
| `domstack eject` | Extract the default layout, global styles, and client files into the source directory and update dependencies in `package.json`. |
| `domstack help [command]` | Show root or command-specific help. |

Expand Down Expand Up @@ -67,7 +68,7 @@ Watch mode uses stable bundle filenames rather than production hashes.

```sh
domstack watch
domstack watch --src site --dest public
domstack watch --src site --dest public --port 8080
domstack watch --no-serve
```

Expand All @@ -82,12 +83,29 @@ domstack watch --no-serve
| `--copy <path>` | Copy and watch an additional directory in the destination; repeat for multiple directories. |
| `--verbose` | Show debug logs, including individual copy operations. |
| `--no-serve` | Watch and rebuild without starting a server. |
| `--port <port>` | Prefer this site port when serving (default: `3000`). |
| `--help`, `-h` | Show watch help. |
| `--version`, `-v` | Show the installed version. |

Normal output includes the initial build tree, rebuild summaries, static asset startup, and server URLs.
Normal output includes the initial build tree, rebuild summaries, static asset startup, the session ID, and actual server URLs.
If the preferred port is already in use, watch uses an available port assigned by the OS.
With `--no-serve`, the port preference has no effect.
Build failures retain their full diagnostics at either verbosity level.
`--port` is not available on this command.

## `domstack sessions [id]`

List DOMStack watch sessions for the current user on this machine, including sessions started with `--no-serve`.
Run this from any directory; it does not need a project in the current working directory.

```sh
domstack sessions
domstack sessions --json
domstack sessions <id> --json
```

JSON output is an array for a list and an object for a lookup, with an ID, process and lifecycle information, project and build paths, and actual site and UI ports and URLs when serving.
An empty list is successful; an unknown or inactive ID exits nonzero.
A non-default discovery directory set through `DOMSTACK_SESSION_DIR` must be shared by the watchers and commands that list them.

## `domstack serve`

Expand Down
12 changes: 8 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
/**
* @import { DomStackOpts, Results } from './lib/builder.js'
* @import { TestBuildResult } from './types.js'
* @import { WatchOptions } from './lib/watch/index.js'

*/
import { mkdtemp, readFile, rm } from 'node:fs/promises'
Expand Down Expand Up @@ -83,6 +84,11 @@ export class DomStack {
return this.#watcher.watching
}

/** Metadata for the current session, or null when idle. */
get watchInfo () {
return this.#watcher.watchInfo
}

build () {
return builder(this.#src, this.#dest, { static: true, ...this.opts })
}
Expand All @@ -93,12 +99,10 @@ export class DomStack {
* Stopping during startup still returns the initial build report, but does not
* activate watch events. Await stopWatching() for completed resource cleanup.
*
* @param {object} [params]
* @param {boolean} params.serve
* @param {(results: Results) => void | Promise<void>} [params.onInitialBuild]
* @param {WatchOptions} [params]
* @return {Promise<Results>}
*/
async watch (params = { serve: true }) {
async watch (params) {
return this.#watcher.watch(params)
}

Expand Down
9 changes: 7 additions & 2 deletions lib/cli/args.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @import { ArgscloptsParseArgsOptionsConfig } from 'argsclopts'
* @import { CommandName } from './options.js'
* @typedef {Record<string, string | boolean | (string | boolean)[] | undefined>} CliValues
* @typedef {{ command: CommandName, values: CliValues, helpCommand: CommandName | null }} CliArgs
* @typedef {{ command: CommandName, values: CliValues, helpCommand: CommandName | null, sessionId?: string | undefined }} CliArgs
*/

import { parseArgs } from 'node:util'
Expand Down Expand Up @@ -86,7 +86,12 @@ export function parseCliArgs (args) {

/** @type {ArgscloptsParseArgsOptionsConfig} */
const options = commands[command].options
const { values } = parseArgs({ args: commandArgs, options, strict: true, allowPositionals: false })
const { values, positionals } = parseArgs({ args: commandArgs, options, strict: true, allowPositionals: command === 'sessions' })
if (command === 'sessions') {
if (positionals.length > 1) throw new Error('Expected at most one session ID')
const [sessionId] = positionals
return { command, values, helpCommand, sessionId }
}
if (!values['help'] && !values['version']) validateValues(command, values)
return { command, values, helpCommand }
} catch (error) {
Expand Down
14 changes: 12 additions & 2 deletions lib/cli/args.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ for (const args of [
['--src', 'site', 'watch'], ['build', 'extra'], ['--', 'watch'], ['--', '--watch'],
['build', '--language', 'ts'], ['build', '--yes'], ['build', '--watch'],
['eject', '--dest', 'public'], ['eject', '--port', '3000'], ['eject', '--verbose'],
['watch', '--port', '3000'], ['serve', '--no-serve'], ['--no-serve'],
['watch', '--port', '0'], ['serve', '--no-serve'], ['--no-serve'],
['sessions', 'one', 'two'], ['sessions', '--src', 'site'], ['build', '--json'],
['--language', 'ts'], ['--yes'], ['--eject', '--dest', 'public'],
['--serve', '--watch'], ['--eject', '--watch'], ['--watch', '--watch-only'], ['-ew'],
['--watch-only', '--serve'], ['--port', '3000'], ['--serve', '--port'],
Expand All @@ -80,13 +81,22 @@ for (const args of [
})
}

test('accept port boundaries and legacy serve options', () => {
test('accept port boundaries for serve and watch', () => {
for (const port of ['1', '3000', '65535']) {
assert.equal(parseCliArgs(['serve', '--port', port]).values['port'], port)
assert.equal(parseCliArgs(['--port', port, '--serve']).values['port'], port)
assert.equal(parseCliArgs(['watch', '--port', port]).values['port'], port)
}
})

test('sessions accepts one optional ID and no build defaults', () => {
const listing = parseCliArgs(['sessions', '--json'])
assert.deepEqual({ ...listing.values }, { json: true })
assert.equal(listing.sessionId, undefined)
assert.equal(parseCliArgs(['sessions', 'example', '--json']).sessionId, 'example')
assert.throws(() => parseCliArgs(['sessions', 'a', 'b']), /at most one session ID/)
})

test('usage errors point to the selected command', () => {
for (const args of [['eject', '--dest', 'public'], ['--eject', '--dest', 'public']]) {
assert.throws(() => parseCliArgs(args), error => error instanceof CliUsageError && error.command === 'eject')
Expand Down
2 changes: 1 addition & 1 deletion lib/cli/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export async function formatCliHelp (command, version) {
version,
options: definition.options,
headerFn: () => command
? `Usage: domstack ${command} [options]\n\n${definition.description}\n`
? `Usage: domstack ${command}${command === 'sessions' ? ' [id]' : ''} [options]\n\n${definition.description}\n`
: [
'Usage: domstack [command] [options]',
'',
Expand Down
12 changes: 12 additions & 0 deletions lib/cli/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ export const commands = {
type: 'boolean',
help: 'watch and build without serving',
},
port: {
type: 'string',
help: 'preferred site port, between 1 and 65535 (default: 3000)',
},
...commonOptions,
},
},
Expand All @@ -96,6 +100,14 @@ export const commands = {
...commonOptions,
},
},
sessions: {
description: 'List local DOMStack watch sessions or inspect one by ID.',
example: 'domstack sessions --json',
options: {
json: { type: 'boolean', help: 'output JSON for automation' },
...commonOptions,
},
},
eject: {
description: 'Extract the default layout, styles, and client, and add their dependencies.\nWarning: overwrites the target files.',
example: 'domstack eject --language ts --src src',
Expand Down
38 changes: 38 additions & 0 deletions lib/cli/sessions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { createSessionRegistry } from '@domstack/sync'

/** @param {string | undefined} id @param {boolean} json */
export async function showWatchSessions (id, json) {
const registry = createSessionRegistry()
try {
if (id !== undefined) {
const record = await registry.get(id)
if (record?.kind !== 'domstack-watch') {
console.error(`domstack: No active watch session: ${id}`)
process.exitCode = 1
return
}
if (json) console.log(JSON.stringify(record))
else {
console.log(`Watch session ${record.id} (${record.state}, PID ${record.pid})`)
console.log(`Started: ${new Date(record.startedAt).toISOString()}`)
console.log(`Project: ${record.cwd}`)
console.log(`Source: ${record.source}`)
console.log(`Destination: ${record.destination}`)
console.log(`Site: ${record.url ?? 'not serving'}`)
console.log(`UI: ${record.uiUrl ?? 'not serving'}`)
}
return
}
const records = (await registry.list()).filter(record => record.kind === 'domstack-watch')
if (json) console.log(JSON.stringify(records))
else if (records.length === 0) console.log('No active DOMStack watch sessions.')
else {
for (const record of records) {
console.log(`${record.id} ${record.state} ${record.source} → ${record.destination} ${record.url ?? '(no server)'}`)
}
}
} catch (error) {
console.error(`domstack: Could not read watch sessions: ${error instanceof Error ? error.message : String(error)}`)
process.exitCode = 1
}
}
Loading
Loading