diff --git a/bin.js b/bin.js index e671eeff..1d0f4d36 100755 --- a/bin.js +++ b/bin.js @@ -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' @@ -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 @@ -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) @@ -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'])) @@ -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) @@ -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.`) @@ -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) diff --git a/docs/api/README.md b/docs/api/README.md index a9a50909..9c2ea0a5 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -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. diff --git a/docs/cli/README.md b/docs/cli/README.md index b995a340..0dfcb847 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -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. | @@ -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 ``` @@ -82,12 +83,29 @@ domstack watch --no-serve | `--copy ` | 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 ` | 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 --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` diff --git a/index.js b/index.js index 4bb58e39..3d83b00f 100644 --- a/index.js +++ b/index.js @@ -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' @@ -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 }) } @@ -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} [params.onInitialBuild] + * @param {WatchOptions} [params] * @return {Promise} */ - async watch (params = { serve: true }) { + async watch (params) { return this.#watcher.watch(params) } diff --git a/lib/cli/args.js b/lib/cli/args.js index f62188cb..238ba3d4 100644 --- a/lib/cli/args.js +++ b/lib/cli/args.js @@ -2,7 +2,7 @@ * @import { ArgscloptsParseArgsOptionsConfig } from 'argsclopts' * @import { CommandName } from './options.js' * @typedef {Record} 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' @@ -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) { diff --git a/lib/cli/args.test.js b/lib/cli/args.test.js index b0db7338..1e3194c6 100644 --- a/lib/cli/args.test.js +++ b/lib/cli/args.test.js @@ -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'], @@ -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') diff --git a/lib/cli/help.js b/lib/cli/help.js index fa4d17f9..65cb11fd 100644 --- a/lib/cli/help.js +++ b/lib/cli/help.js @@ -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]', '', diff --git a/lib/cli/options.js b/lib/cli/options.js index 95d80c48..f44bfcdc 100644 --- a/lib/cli/options.js +++ b/lib/cli/options.js @@ -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, }, }, @@ -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', diff --git a/lib/cli/sessions.js b/lib/cli/sessions.js new file mode 100644 index 00000000..c48876f4 --- /dev/null +++ b/lib/cli/sessions.js @@ -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 + } +} diff --git a/lib/cli/tests/commands.test.js b/lib/cli/tests/commands.test.js index b0e6f306..647493d5 100644 --- a/lib/cli/tests/commands.test.js +++ b/lib/cli/tests/commands.test.js @@ -3,16 +3,19 @@ */ import assert from 'node:assert/strict' import { spawn, spawnSync } from 'node:child_process' -import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises' import { get } from 'node:http' import { createServer } from 'node:net' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import test from 'node:test' import { setTimeout as delay } from 'node:timers/promises' +import { createSessionRegistry } from '@domstack/sync' + +/** @import { SessionInfo } from '@domstack/sync' */ const bin = resolve(import.meta.dirname, '../../../bin.js') -const commands = ['build', 'watch', 'serve', 'eject'] +const commands = ['build', 'watch', 'serve', 'eject', 'sessions'] /** @type {Array<[string, string]>} */ const legacyModes = [ ['--eject', 'eject'], ['-e', 'eject'], @@ -30,10 +33,11 @@ async function workspace (t) { /** * @param {string} cwd * @param {string[]} args + * @param {NodeJS.ProcessEnv} [env] */ -function cli (cwd, args) { +function cli (cwd, args, env = process.env) { const result = spawnSync(process.execPath, [bin, ...args], { - cwd, encoding: 'utf8', input: '', timeout: 15_000, killSignal: 'SIGKILL', + cwd, env, encoding: 'utf8', input: '', timeout: 15_000, killSignal: 'SIGKILL', }) assert.ifError(result.error) assert.equal(result.signal, null, result.stdout + result.stderr) @@ -94,6 +98,12 @@ test('command help aliases and legacy help use the target command options withou assert.equal(text, help(cwd, ['help', command])) assert.equal(text, help(cwd, [command, '-h'])) const options = optionListing(text) + if (command === 'sessions') { + assert.match(text, /sessions \[id\]/) + assert.match(options, /--json\b/) + assert.doesNotMatch(options, /--(?:src|dest|port)\b/) + continue + } assert.match(options, /--src\b/) if (command === 'eject') { assert.match(options, /--language\b/) @@ -105,7 +115,7 @@ test('command help aliases and legacy help use the target command options withou } if (command === 'watch') assert.match(options, /--no-serve\b/) else assert.doesNotMatch(options, /--no-serve\b/) - if (command === 'serve') assert.match(options, /--port\b/) + if (command === 'serve' || command === 'watch') assert.match(options, /--port\b/) else assert.doesNotMatch(options, /--port\b/) } for (const [flag, command] of legacyModes) { @@ -144,13 +154,14 @@ test('options are strict, command-specific, and commands must come first', async ['--unknown'], ['build', '--unknown'], ['--language', 'js'], ['--yes'], ['--port', '3000'], ['--no-serve'], ['build', '--language', 'js'], ['watch', '--yes'], ['serve', '--language', 'ts'], - ['build', '--port', '3000'], ['watch', '--port', '3000'], + ['build', '--port', '3000'], ['watch', '--port', '0'], + ['sessions', 'one', 'two'], ['sessions', '--dest', 'public'], ['build', '--no-serve'], ['serve', '--no-serve'], ['build', '--src'], ['serve', '--port'], ['serve', '--port', '0'], ['serve', '--port', '65536'], ['serve', '--port', 'abc'], ['--src', 'src', 'build'], ['build', 'watch'], ['build', '--watch'], ['watch', '--watch-only'], ['serve', '--serve'], ['eject', '--eject'], - ['--watch', '--port', '3000'], ['-w', '--yes'], + ['--watch', '--port', '65536'], ['-w', '--yes'], ['--watch-only', '--language', 'js'], ['--serve', '--no-serve'], ] for (const args of cases) { @@ -205,10 +216,11 @@ for (const explicit of [false, true]) { /** * @param {string} cwd * @param {string[]} args + * @param {NodeJS.ProcessEnv} [env] */ -function startCli (cwd, args) { +function startCli (cwd, args, env = process.env) { const child = spawn(process.execPath, [bin, ...args], { - cwd, stdio: ['ignore', 'pipe', 'pipe'], timeout: 25_000, killSignal: 'SIGKILL', + cwd, env, stdio: ['ignore', 'pipe', 'pipe'], timeout: 25_000, killSignal: 'SIGKILL', }) let output = '' let exited = false @@ -290,6 +302,74 @@ function requestHtml (port) { }) } +test('sessions discovers served and unserved watchers across projects', { timeout: 30_000 }, async t => { + const cwd = await workspace(t) + const directory = join(cwd, 'registry') + const env = { ...process.env, DOMSTACK_SESSION_DIR: directory } + const list = () => { + const result = cli(cwd, ['sessions', '--json'], env) + assert.equal(result.status, 0, result.stderr) + assert.equal(result.stderr, '') + return /** @type {SessionInfo[]} */ (JSON.parse(result.stdout)) + } + assert.deepEqual(list(), []) + const sync = await createSessionRegistry({ directory }).register({ kind: 'domstack-sync', state: 'watching', cwd }) + t.after(() => sync.dispose()) + const port = await availablePort() + const projects = ['first', 'second', 'unserved'] + for (const name of projects) { + await mkdir(join(cwd, name, 'src'), { recursive: true }) + await writeFile(join(cwd, name, 'src', 'page.html'), `

${name}

`) + } + const watchers = projects.map(name => startCli(join(cwd, name), name === 'unserved' + ? ['watch', '--no-serve'] + : ['watch', '--port', String(port)], env)) + try { + for (const watcher of watchers) { + await until(watcher, async () => /Watch session [a-f\d-]+ ready/.test(watcher.output()), 'session readiness') + } + const records = list() + assert.equal(records.length, 3) + assert.equal(records.filter(record => record.port === port).length, 1) + const root = await realpath(cwd) + assert.equal(new Set(records.flatMap(record => [record.port, record.uiPort]).filter(Boolean)).size, 4) + for (const name of projects) { + const record = records.find(record => record.source === join(root, name, 'src')) + assert.ok(record) + assert.equal(record.state, 'watching') + assert.ok(record.destination?.endsWith(join(name, 'public'))) + const detail = cli(cwd, ['sessions', record.id, '--json'], env) + assert.equal(detail.status, 0, detail.stderr) + assert.deepEqual(JSON.parse(detail.stdout), record) + assert.doesNotMatch(detail.stdout, /token|socketUrl/) + if (name === 'unserved') assert.equal(record.url, null) + else { + assert.equal(record.url, `http://localhost:${record.port}`) + assert.ok(record.port) + assert.match((await requestHtml(record.port)).body, new RegExp(`

${name}

`)) + } + } + const first = watchers[0] + assert.ok(first) + await writeFile(join(cwd, 'first', 'src', 'page.html'), '

first changed

') + await until(first, async () => (await outputHtml(join(cwd, 'first', 'public', 'index.html'))).includes('first changed'), 'first rebuild') + assert.match(await outputHtml(join(cwd, 'second', 'public', 'index.html')), /

second<\/h1>/) + assert.deepEqual(await stopCli(first), { code: 0, signal: null }, first.output()) + assert.equal(list().length, 2) + const second = watchers[1] + assert.ok(second) + await writeFile(join(cwd, 'second', 'src', 'page.html'), '

second changed

') + await until(second, async () => (await outputHtml(join(cwd, 'second', 'public', 'index.html'))).includes('second changed'), 'second rebuild after first watcher stops') + const missing = cli(cwd, ['sessions', sync.id, '--json'], env) + assert.equal(missing.status, 1) + assert.equal(missing.stdout, '') + assert.match(missing.stderr, /No active watch session/) + } finally { + await Promise.all(watchers.map(stopCli)) + } + assert.deepEqual(list(), []) +}) + test('watch --no-serve rebuilds and cleans up on SIGTERM', { timeout: 30_000 }, async t => { const cwd = await workspace(t) await mkdir(join(cwd, 'src')) diff --git a/lib/watch/index.js b/lib/watch/index.js index bb5c92b1..0926abc5 100644 --- a/lib/watch/index.js +++ b/lib/watch/index.js @@ -4,7 +4,7 @@ * @import { DomStackOpts, Results, SiteData } from '../builder.js' * @import { FSWatcher } from 'chokidar' * @import { PageBuildStepResult } from '../build-pages/index.js' - * @import { BsInstance } from '@domstack/sync' + * @import { BsInstance, SessionRegistration } from '@domstack/sync' * @import { Logger as PinoLogger } from 'pino' * @import { DisposableBuildContext } from '../build-esbuild/index.js' * @import { WatchDependencyState } from '../build-pages/global-data/watch-dependencies.js' @@ -20,12 +20,35 @@ * @property {Promise} startupWork - The current resource-acquiring startup phase; never the user callback. * @property {Promise | null} shutdown - Shared by explicit stops and startup failure cleanup. * @property {DestinationClaim | null} claim + * @property {SessionRegistration | null} registration + * @property {string | null} id + * @property {number} startedAt + * @property {string} cwd * @property {WatchEvent[]} pendingEvents * @property {boolean} drainScheduled * @property {GlobalDataBaseline | null} globalDataBaseline * @property {MarkdownPreparationState | null} markdownPreparation + * + * @typedef {object} WatchInfo + * @property {string | null} id - Assigned during startup. + * @property {number} pid + * @property {number} startedAt - Epoch milliseconds. + * @property {'starting' | 'watching' | 'stopping'} state + * @property {string} cwd + * @property {string} source + * @property {string} destination + * @property {number | null} port + * @property {number | null} uiPort + * @property {string | null} url + * @property {string | null} uiUrl + * + * @typedef {object} WatchOptions + * @property {boolean} [serve=true] + * @property {number | undefined} [port] - Preferred site port when serving. + * @property {(results: Results) => void | Promise} [onInitialBuild] */ import { once } from 'events' +import { randomUUID } from 'node:crypto' import { setImmediate } from 'node:timers/promises' import chokidar from 'chokidar' @@ -34,7 +57,7 @@ import { basename, isAbsolute, relative, resolve, sep } from 'node:path' import ignore from 'ignore' import { watch as cpxWatch } from 'cpx2' -import { createServer } from '@domstack/sync' +import { createServer, createSessionRegistry, parseOptions as parseSyncOptions } from '@domstack/sync' import { getCopyGlob } from '../build-static/index.js' import { getCopyDirs } from '../build-copy/index.js' @@ -106,23 +129,39 @@ export class DomStackWatcher { return this.#watchSession !== null } + /** @returns {Readonly | null} */ + get watchInfo () { + const session = this.#watchSession + if (!session) return null + return { + id: session.id, + pid: process.pid, + startedAt: session.startedAt, + state: session.state, + cwd: session.cwd, + source: resolve(session.cwd, this.#src), + destination: session.claim?.destination ?? resolve(session.cwd, this.#dest), + port: this.#syncServer?.port ?? null, + uiPort: this.#syncServer?.uiPort ?? null, + url: this.#syncServer?.url ?? null, + uiUrl: this.#syncServer?.uiUrl ?? null, + } + } + /** * Build and watch a domstack build * * 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} [params.onInitialBuild] + * @param {WatchOptions} [params] * @return {Promise} */ async watch ({ - serve, + serve = true, + port, onInitialBuild, - } = { - serve: true, - }) { + } = {}) { if (this.watching) throw new Error('Already watching.') /** @type {WatchSession} */ const session = { @@ -131,6 +170,10 @@ export class DomStackWatcher { startupWork: Promise.resolve(), shutdown: null, claim: null, + registration: null, + id: null, + startedAt: Date.now(), + cwd: process.cwd(), pendingEvents: [], drainScheduled: false, globalDataBaseline: null, @@ -139,7 +182,7 @@ export class DomStackWatcher { this.#watchSession = session this.#dependencies.clearAnalysis() try { - return await this.#startWatch(session, { serve, onInitialBuild }) + return await this.#startWatch(session, serve, port, onInitialBuild) } catch (error) { try { await this.#stopWatchSession(session) @@ -158,9 +201,11 @@ export class DomStackWatcher { * The user callback is outside the acquisition phases so it can await a stop. * * @param {WatchSession} session - * @param {{ serve: boolean, onInitialBuild: ((results: Results) => void | Promise) | undefined }} params + * @param {boolean} serve + * @param {number | undefined} port + * @param {WatchOptions['onInitialBuild']} onInitialBuild */ - async #startWatch (session, { serve, onInitialBuild }) { + async #startWatch (session, serve, port, onInitialBuild) { const { signal } = session.cancellation const preparation = this.#prepareWatch(session) session.startupWork = preparation @@ -171,13 +216,20 @@ export class DomStackWatcher { if (signal.aborted) return report if (serve) { - session.startupWork = this.#startWatchServer() + session.startupWork = this.#startWatchServer(port) await session.startupWork if (signal.aborted) return report } session.state = 'watching' - this.#scheduleWatchBatch(session) + session.startupWork = this.#publishWatchState(session) + await session.startupWork + if (!signal.aborted) { + const { url, uiUrl } = this.watchInfo ?? {} + const addresses = [url, uiUrl].filter(Boolean).join(', ') + this.#logger.info(`Watch session ${session.id} ready${addresses ? ` (${addresses})` : ' (no server)'}`) + this.#scheduleWatchBatch(session) + } return report } @@ -186,6 +238,7 @@ export class DomStackWatcher { async #prepareWatch (session) { const { signal } = session.cancellation session.claim = await claimDestination(this.#dest) + await this.#registerWatchSession(session) // Establish observation before discovery. Initial scan adds are not edits; // subsequent events stay buffered until startup and the user callback finish. await this.#createSourceWatcher(session) @@ -359,8 +412,10 @@ export class DomStackWatcher { } } - async #startWatchServer () { + /** @param {number | undefined} port */ + async #startWatchServer (port) { this.#syncServer = await createServer({ + port: port ?? parseSyncOptions().port, server: this.#dest, files: basename(this.#dest), ignore: ['**/domstack-esbuild-meta.json'], @@ -368,6 +423,40 @@ export class DomStackWatcher { }) } + /** @param {unknown} error */ + #warnSessionRegistry (error) { + this.#logger.warn({ err: error }, 'Watch session discovery unavailable') + } + + /** @param {WatchSession} session */ + async #registerWatchSession (session) { + const info = this.watchInfo + if (!info) return + try { + const registry = createSessionRegistry({ onRefreshError: error => this.#warnSessionRegistry(error) }) + session.registration = await registry.register({ + kind: 'domstack-watch', + state: info.state, + cwd: info.cwd, + source: info.source, + destination: info.destination, + }) + session.id = session.registration.id + } catch (error) { + session.id = randomUUID() + this.#warnSessionRegistry(error) + } + } + + /** @param {WatchSession} session */ + async #publishWatchState (session) { + await session.registration?.update({ + state: session.state, + port: this.#syncServer?.port ?? null, + uiPort: this.#syncServer?.uiPort ?? null, + }).catch(error => this.#warnSessionRegistry(error)) + } + /** * Full rebuild: re-identify pages, restart esbuild, rebuild all pages, rebuild maps. * Used for structural changes (add/unlink), global.vars.*, esbuild.settings.*. @@ -614,6 +703,7 @@ export class DomStackWatcher { // 1. Drain resource acquisition. No new startup phase may begin after a stop. // watch() reports startup errors; shutdown still releases partial resources. await session.startupWork.catch(() => {}) + await this.#publishWatchState(session) // 2. Stop filesystem producers. The session state already rejects new and // queued rebuilds, including callbacks retained by a previous watch session. @@ -638,6 +728,7 @@ export class DomStackWatcher { const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []) if ([...copyDrains, esbuildDrain].some(result => result.status === 'rejected')) { // Keep the session and claim when a writer could not be shut down safely. + await session.registration?.dispose().catch(error => this.#warnSessionRegistry(error)) throw new AggregateError(errors, 'Watch cleanup failed; destination remains claimed until process exit') } try { @@ -645,6 +736,7 @@ export class DomStackWatcher { } catch (error) { errors.push(error) } + await session.registration?.dispose().catch(error => this.#warnSessionRegistry(error)) session.pendingEvents = [] session.globalDataBaseline = null session.markdownPreparation = null diff --git a/lib/watch/lifecycle-tests/index.test.js b/lib/watch/lifecycle-tests/index.test.js index b9c7d196..6ddfd184 100644 --- a/lib/watch/lifecycle-tests/index.test.js +++ b/lib/watch/lifecycle-tests/index.test.js @@ -13,6 +13,7 @@ import { Server } from 'node:net' import { join, resolve } from 'node:path' import { setImmediate, setTimeout as delay } from 'node:timers/promises' import chokidar from 'chokidar' +import { createSessionRegistry } from '@domstack/sync' import { DomStack } from '../../../index.js' /** @@ -147,6 +148,71 @@ for (const kind of ['static', 'extra']) { }) } +/** @param {TestContext} t @param {string} directory */ +function useRegistry (t, directory) { + const previous = process.env['DOMSTACK_SESSION_DIR'] + process.env['DOMSTACK_SESSION_DIR'] = directory + t.after(() => { + if (previous === undefined) delete process.env['DOMSTACK_SESSION_DIR'] + else process.env['DOMSTACK_SESSION_DIR'] = previous + }) + return createSessionRegistry({ directory }) +} + +test('watchInfo exposes lifecycle without replacing the initial build report', async t => { + const site = await fixture(t) + const registry = useRegistry(t, join(site.dest, '..', 'registry')) + const watchInfo = () => site.dom.watchInfo + assert.equal(watchInfo(), null) + let initial + const report = await site.dom.watch({ + serve: false, + port: undefined, + async onInitialBuild (result) { + initial = result + const info = watchInfo() + assert.ok(info?.id) + assert.equal(info.state, 'starting') + assert.equal((await registry.get(info.id))?.state, 'starting') + }, + }) + assert.equal(report, initial) + const info = watchInfo() + assert.ok(info?.id) + assert.equal(info.state, 'watching') + assert.equal(info.port, null) + assert.equal(info.url, null) + assert.equal((await registry.get(info.id))?.state, 'watching') + const stopping = site.dom.stopWatching() + assert.equal(watchInfo()?.state, 'stopping') + await stopping + assert.equal(watchInfo(), null) + assert.equal(await registry.get(info.id), null) +}) + +test('watch closes discovery on startup failure', async t => { + const site = await fixture(t) + const registry = useRegistry(t, join(site.dest, '..', 'registry')) + await assert.rejects(site.dom.watch({ + serve: false, + onInitialBuild () { throw new Error('initial callback failed') }, + }), /initial callback failed/) + assert.equal(site.dom.watchInfo, null) + assert.deepEqual(await registry.list(), []) +}) + +test('watchInfo survives an unavailable registry', async t => { + const site = await fixture(t) + const directory = join(site.dest, '..', 'registry') + await writeFile(directory, 'not a directory') + useRegistry(t, directory) + await site.dom.watch({ serve: false }) + assert.ok(site.dom.watchInfo?.id) + assert.equal(site.dom.watchInfo.state, 'watching') + await site.dom.stopWatching() + assert.equal(site.dom.watchInfo, null) +}) + test('idle facade reports no watch session before startup and after shutdown', { timeout: 15_000 }, async t => { const site = await fixture(t) assert.equal(site.dom.watching, false) @@ -212,6 +278,7 @@ test('shutdown cancels watcher readiness without waiting for a ready event', { t } t.mock.method(watcher, 'emit', emitWithoutReady) }) + const registry = useRegistry(t, join(site.dest, '..', 'registry')) let callbacks = 0 const starting = site.dom.watch({ serve: false, @@ -219,6 +286,7 @@ test('shutdown cancels watcher readiness without waiting for a ready event', { t }) await reachedReady.promise await Promise.all([site.dom.stopWatching(), starting]) + assert.deepEqual(await registry.list(), []) assert.equal(callbacks, 0) assert.equal(site.dom.watching, false) assert.equal(site.watcher().closed, true) diff --git a/package.json b/package.json index d73a5f24..7a4c20b2 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ }, "dependencies": { "@11ty/dependency-tree": "5.0.0-alpha.3", - "@domstack/sync": "^0.0.8", + "@domstack/sync": "^0.1.0", "argsclopts": "^1.0.4", "async-folder-walker": "^3.0.5", "chokidar": "^6.0.0", diff --git a/plans/multiple-watch-builds.md b/plans/multiple-watch-builds.md index 15b777a6..08a86360 100644 --- a/plans/multiple-watch-builds.md +++ b/plans/multiple-watch-builds.md @@ -2,7 +2,13 @@ Issue: [bcomnes/domstack#352](https://github.com/bcomnes/domstack/issues/352) -## Progress +## Phase 1 — Implement and verify end to end locally + +Finish the full feature set in the local stack with `npm link` builds of `cpx2` and `@domstack/sync`. +Keep the published dependency ranges unchanged and the existing upstream PRs open; do not open the DOMStack PRs, merge branches, or publish packages during this phase. +The release sequence is at the [bottom of this plan](#phase-2--open-merge-and-publish-after-local-sign-off). + +### Progress | Step | Repository | PR | Status | | --- | --- | --- | --- | @@ -10,21 +16,17 @@ Issue: [bcomnes/domstack#352](https://github.com/bcomnes/domstack/issues/352) | [2. Local session discovery](#pr-2--sync-local-session-discovery) | `domstack-sync` | [#43](https://github.com/bcomnes/domstack-sync/pull/43) | Open for review; stacked on #42 | | [3a. Copy lifecycle prerequisite](#pr-3a--cpx2-drain-copy-writes) | `cpx2` | [#199](https://github.com/bcomnes/cpx2/pull/199) | Open for review; linked locally | | [3. Destination ownership](#pr-3--domstack-destination-ownership) | `domstack` | — | Validated with local links; Linux CI pending | -| [4. Watch introspection](#pr-4--domstack-watch-introspection) | `domstack` | — | Not started | +| [4. Watch introspection](#pr-4--domstack-watch-introspection) | `domstack` | — | Validated locally on `feat/watch-introspection` | | [5. Delegated rebuilds](#pr-5--domstack-delegated-rebuilds) | `domstack` | — | Not started | | [6. Explicit watcher replacement](#pr-6--domstack-explicit-watcher-replacement) | `domstack` | — | Not started | -Update this table when work starts, a PR opens, or a PR merges. +Update this table when work starts, a local branch is validated, or its review status changes. Check off refactoring, implementation, and verification separately; record the test command or CI run and any unresolved gate in the relevant PR section. Start each PR by running or adding focused coverage for the behavior being moved, then keep behavior-preserving refactors reviewable separately from feature changes within that PR. Refactor only the code needed by the current PR; leave broader cleanup out of the stack unless it blocks a stated exit criterion. Make focused checkpoint commits as each coherent change is validated, and check the Git status in each touched repository before pausing or handing off. Leave the index and working tree clean at checkpoints, without staging unrelated user changes or temporary dependency links. -Use GitHub's `gh stack` extension to create and manage a native stack in each repository, not just a chain of PR base branches. -Use `gh stack init` or `gh stack add` locally and `gh stack submit` to publish; land the PRs bottom-up. -The Sync PRs are linked in native GitHub stack `#44`. -Do not merge or release upstream packages during local end-to-end development. -Use `npm link` with local builds of `cpx2` and `@domstack/sync` to work through the DOMStack stack, and leave published dependency ranges unchanged until the release phase. +Use `gh stack init` and `gh stack add` to track the stack locally, one branch per implementation step. ### Local linked setup @@ -33,13 +35,16 @@ Use `npm link` with local builds of `cpx2` and `@domstack/sync` to work through - Verify module resolution before integration tests, especially after an install, because `npm install` can replace the links. - The full DOMStack Node suite and TypeScript passed with both links in place. - A subprocess smoke test verified two DOMStack watchers serve different ports, standalone Sync is discoverable through the linked registry, a build conflicts while its watcher owns the destination, and it succeeds after that watcher stops without affecting the other site. -- DOMStack watch discovery, delegation, and replacement are still separate implementation steps; add those to the local smoke test as PRs 4–6 land. +- DOMStack watch discovery passed its linked subprocess test in PR 4; add delegation and replacement to the local smoke test as PRs 5–6 land. -### Review checkpoints +### Local sign-off checklist -- [x] **After PRs 1–2:** Pause for review of Sync's port binding and public registry API before proceeding with the DOMStack work. -- [ ] **After PR 3:** Pause for review of destination ownership, crash recovery, and write-draining evidence before proceeding to PRs 4–6. -- After both reviews, work through PRs 4–6 in order without a scheduled pause; stop if a validation gate fails or implementation requires a design change. +- [x] Run against both linked upstream packages and verify port fallback, discovery from another project, and separate outputs for simultaneous watchers, including `--no-serve` discovery. +- [x] Verify local ownership blocks overlapping builds, stays held during write draining, and releases after a crashed lock holder exits. +- [ ] From the top of the stack, run plain `domstack build` against a matching watcher and verify it delegates, reports the real rebuild result, and leaves the watcher running. +- [ ] Run `domstack build --replace-watch` against a matching watcher and verify it drains, transfers ownership, cleans the destination, and builds locally without interrupting an unrelated watcher. +- [ ] Run the relevant upstream suites and DOMStack's full Node suite and type checks against the final linked stack, and record the results here. +- [ ] Review the local end-to-end result and the ownership, crash-recovery, and write-draining evidence before starting Phase 2. ## Agreed behavior and boundaries @@ -101,14 +106,14 @@ The registry is usable without an HTTP listener, so DOMStack can register build- - [x] Test same-PID and cross-process registration, lookup by ID, empty or malformed records, crash expiry, and credential-free JSON with an isolated registry directory. - [x] Document discovery in the Sync README. -- [ ] After review and merge, release a Sync version containing PRs 1 and 2 for DOMStack to adopt in PR 4. + Validation: `node --test --test-timeout=15000` passed 173 tests; `npm run test:playwright` passed 31 Chromium tests; `npm run test:tsc` and `npm run test:lint` passed. The subprocess discovery and signal tests ran on macOS; Windows access controls and signal behavior were not verified. ## PR 3a — cpx2: Drain copy writes -Use the linked upstream prerequisite for local validation; release and adopt it only when ready to merge the DOMStack stack. +Use the linked upstream prerequisite for local validation. DOMStack can prototype locking in parallel, but it must not rely on claim release until the copy drain guarantees are verified. **Refactor first** @@ -130,7 +135,7 @@ DOMStack can prototype locking in parallel, but it must not rely on claim releas - [x] Fail one file in a one-shot batch while a sibling write is gated, and exercise a stream error with an open output; verify that rejection waits for writers and output handles to finish closing. - [x] Run focused and full `cpx2` tests and type/lint checks, then test DOMStack with a temporary local build without committing the dependency reference. - [x] Open the upstream PR: [bcomnes/cpx2#199](https://github.com/bcomnes/cpx2/pull/199). -- [ ] Record the released `cpx2` version here and update DOMStack's `package.json` before publishing PR 3. + Validation: `npm test` passed 114 `cpx2` tests on macOS, including the packed declaration consumer test. After adding the startup-cleanup regression, all 16 focused tests, lint, and TypeScript passed. @@ -151,10 +156,10 @@ At the end of this PR, a conflict fails clearly; it does not delegate, stop a wa - Destination claims use shared ancestor locks and an exclusive destination lock via `fs-native-extensions`, without a coordinator file. - One-shot builds, the build phase of `serve`, and watch sessions now acquire claims before writing; watcher copy work drains through the upstream `close({ drain: true })` API before release. - Verified 79 targeted Node tests, TypeScript, and targeted lint on macOS with a temporary build of `cpx2` PR #199; the installed dependency was restored afterward and watch shutdown on this checkpoint requires the new API. -- This checkpoint stays local while the package releases are deferred; review the local macOS evidence now and run Linux and macOS CI once the published dependencies are available. + - Targeted macOS tests cover aliases, nested conflicts in both directions, siblings, a paused claimant, and release after a crash; Linux validation is still pending. - DOMStack-owned build fan-outs now wait for settled writes before surfacing errors; focused tests, TypeScript, and targeted lint passed. -- The installed `cpx2` release still lacks the drain guarantees; DOMStack's dependency must be bumped to the release containing PR 3a before publishing the ownership PR. + **Refactor first** @@ -173,7 +178,7 @@ At the end of this PR, a conflict fails clearly; it does not delegate, stop a wa - [x] Fail closed if an older `cpx2` silently ignores the drain option and does not return a promise. - [x] Update DOMStack-owned write fan-outs to wait for sibling writes on failure. - [x] Verify that failed one-shot static and extra-copy batches both retain the destination claim while a sibling write is active. -- [ ] Pin the released `cpx2` version and rerun validation against it; DOMStack ignores `package-lock.json`, so do not commit a generated lockfile. + **Exit criteria** @@ -190,23 +195,27 @@ Add a separate snapshot without changing that return value or the initial build **Refactor first** -- [ ] Separate `sessions` dispatch from the project CLI path in `bin.js`, and make positional parsing and required project paths depend on the command in `lib/cli/args.js`. -- [ ] Make the existing watch session the single source of truth for lifecycle and bound addresses, and derive both the public snapshot and registry updates from it instead of maintaining parallel state. +- [x] Separate `sessions` dispatch from the project CLI path in `bin.js`, and make positional parsing and required project paths depend on the command in `lib/cli/args.js`. +- [x] Make the existing watch session the single source of truth for lifecycle and bound addresses, and derive both the public snapshot and registry updates from it instead of maintaining parallel state. **Implementation** -- [ ] Develop and validate with the linked `@domstack/sync` build; adopt the released version in `package.json` during the release phase. -- [ ] Add `watch({ port })` and `domstack watch --port` through `lib/cli/options.js`, `lib/cli/args.js`, help, and `bin.js`; pass the preference to Sync only when serving. -- [ ] Expose a typed `watchInfo` snapshot in `index.js` and publish one `domstack-watch` record per session from `lib/watch/index.js`, with absolute source/destination paths, lifecycle state, and nullable bound URLs and ports. -- [ ] Update records on lifecycle transitions and dispose them on normal stop, cancellation, and startup failure; registry write failures warn without stopping a build or hiding in-process `watchInfo`. -- [ ] Add `domstack sessions [id] [--json]` before builder construction and source/destination validation; filter to DOMStack watch records and allow the optional positional ID only for `sessions`. -- [ ] Print actual bound URLs and a session ID at startup; make an empty list successful, missing IDs nonzero, and JSON output free of logs or decoration. +- [x] Develop and validate with the linked `@domstack/sync` build. + +- [x] Add `watch({ port })` and `domstack watch --port` through `lib/cli/options.js`, `lib/cli/args.js`, help, and `bin.js`; pass the preference to Sync only when serving. +- [x] Expose a typed `watchInfo` snapshot in `index.js` and publish one `domstack-watch` record per session from `lib/watch/index.js`, with absolute source/destination paths, lifecycle state, and nullable bound URLs and ports. +- [x] Update records on lifecycle transitions and dispose them on normal stop, cancellation, and startup failure; registry write failures warn without stopping a build or hiding in-process `watchInfo`. +- [x] Add `domstack sessions [id] [--json]` before builder construction and source/destination validation; filter to DOMStack watch records and allow the optional positional ID only for `sessions`. +- [x] Print actual bound URLs and a session ID at startup; make an empty list successful, missing IDs nonzero, and JSON output free of logs or decoration. **Exit criteria** -- [ ] Extend `lib/watch/lifecycle-tests/` and `lib/cli/tests/commands.test.js`: run two temporary sites with separate destinations on the same preferred port, discover them from another directory, edit each, and stop one without affecting the other. -- [ ] Cover `--no-serve`, signal cleanup, startup cancellation or failure, registry failure, unchanged `watch()` returns and callback, stable JSON, and strict positional parsing for other commands. -- [ ] Document port fallback, `watchInfo`, and discovery in `docs/cli/README.md` and `docs/api/README.md`. +- [x] Extend `lib/watch/lifecycle-tests/` and `lib/cli/tests/commands.test.js`: run two temporary sites with separate destinations on the same preferred port, discover them from another directory, edit each, and stop one without affecting the other. +- [x] Cover `--no-serve`, signal cleanup, startup cancellation or failure, registry failure, unchanged `watch()` returns and callback, stable JSON, and strict positional parsing for other commands. +- [x] Document port fallback, `watchInfo`, and discovery in `docs/cli/README.md` and `docs/api/README.md`. + +Validation: The full Node suite, TypeScript, and targeted lint passed with both upstream links active. +Focused subprocess and lifecycle tests covered requested-port fallback, cross-project discovery and ID lookup, `--no-serve`, signal cleanup, startup cancellation and failure, and a failed registry write. ## PR 5 — DOMStack: Delegated rebuilds @@ -244,7 +253,7 @@ Add `stop` to the control protocol and make replacement opt-in through `domstack - [ ] Route CLI signals and accepted control stops through the existing shared watch shutdown; keep process exit a CLI decision and keep the control connection available long enough to return the shutdown result. - [ ] Reuse the existing one-shot execution path for replacement by adding a guarded cleanup step under the same destination claim, not a separate build implementation. -- [ ] Delete temporary delegation guidance or transitional code only where PR 6 replaces it, and rerun the prior PRs' overlap and lifecycle regressions before merging. +- [ ] Delete temporary delegation guidance or transitional code only where PR 6 replaces it, and rerun the prior branches' overlap and lifecycle regressions as part of local sign-off. **Implementation** @@ -261,3 +270,40 @@ Add `stop` to the control protocol and make replacement opt-in through `domstack - [ ] Verify the matching watch CLI exits while an embedded host and its other sessions stay alive. - [ ] Test repeated stop, startup cancellation, stop during an active rebuild, caller disconnect and timeout, unsafe cleanup targets, different sources and nested conflicts, and a competing ownership claim. - [ ] Document the flag and its destructive cleanup behavior, and update the delegation error to point to `--replace-watch`. + +## Phase 2 — Open, merge, and publish after local sign-off + +Do not start this phase until the Phase 1 checklist is complete and the local feature set has been reviewed. +**The human maintainer performs all merges and publishes all releases.** +The agent may prepare branches and dependency updates, open or update PRs with `gh stack`, and report validation, but must not merge PRs, enable auto-merge, or trigger release workflows. +Use native GitHub stacks via `gh stack`, not just PRs that target one another's branches. + +### PR and release dependencies + +Arrows show dependencies, not the order of independent tasks; follow the numbered rollout below. + +```mermaid +flowchart TD + Local[Local npm link sign-off] --> Sync42[Sync PR 42: port fallback] + Local --> Cpx199[cpx2 PR 199: drain writes] + Sync42 --> Sync43[Sync PR 43: session discovery] + Sync43 --> SyncRelease[Sync npm release] + Cpx199 --> CpxRelease[cpx2 npm release] + CpxRelease --> Ownership[DOMStack PR 3: destination ownership] + SyncRelease --> Introspection[DOMStack PR 4: watch introspection] + Ownership --> Introspection + Introspection --> Delegation[DOMStack PR 5: delegated rebuilds] + Delegation --> Replacement[DOMStack PR 6: watcher replacement] + Replacement --> DomstackRelease[DOMStack npm release] +``` + +### Rollout order + +1. [ ] **Sync:** Land [#42](https://github.com/bcomnes/domstack-sync/pull/42) (port fallback), then [#43](https://github.com/bcomnes/domstack-sync/pull/43) (discovery) from native stack `#44`. +2. [ ] **Sync:** Publish a version that contains both changes and record the npm version in the plan. +3. [ ] **cpx2:** Land [#199](https://github.com/bcomnes/cpx2/pull/199) (opt-in watcher drain and one-shot copy draining), then publish a compatible version and record the npm version. +4. [ ] **DOMStack:** Update `package.json` to use released `cpx2` on PR 3 (ownership) and released `@domstack/sync` on PR 4 (introspection), then propagate the changes up the local stack. +5. [ ] **DOMStack:** Remove the `npm link` overrides and reinstall from the registry; rerun end-to-end tests with the published dependencies and do not commit a generated lockfile or any link reference. +6. [ ] **DOMStack:** Use `gh stack submit` to open the native stack in order: PR 3 (ownership) → PR 4 (introspection) → PR 5 (delegation) → PR 6 (replacement). +7. [ ] **DOMStack:** Verify Linux and macOS CI and review each layer; the human maintainer merges bottom-up in the same order, keeping the remaining PRs based on the correct branches as each lands. +8. [ ] **DOMStack:** The human maintainer publishes only after the entire stack lands and the release is approved. diff --git a/types.ts b/types.ts index 28d3cf9e..9e612c92 100644 --- a/types.ts +++ b/types.ts @@ -19,6 +19,7 @@ export type { GlobalDataResetChanges, } from './lib/build-pages/global-data/global-data-state.js' export type { WatchEvent } from './lib/watch/plan.js' +export type { WatchInfo, WatchOptions } from './lib/watch/index.js' export type { PageOutput, PageOutputProvenance,