From c129b332313d67dbcf9a6b6fb290cb0f8b2e0b27 Mon Sep 17 00:00:00 2001 From: Maryam Ibrahim Hamza Date: Fri, 20 Nov 2026 12:20:18 +0100 Subject: [PATCH] Improve full-stack startup and frontend resilience Closes #333 Closes #332 Closes #331 Closes #329 --- docs/reference/commands.md | 4 + docs/reference/troubleshooting.md | 4 + src/dev/project.ts | 69 ++++++- src/testing/project.ts | 6 +- templates/full-stack/README.md | 23 ++- templates/full-stack/backend/src/server.js | 112 +++++++++++- templates/full-stack/backend/src/start.js | 36 +++- .../full-stack/backend/test/server.test.js | 85 +++++++++ templates/full-stack/frontend/src/app.js | 130 +++++++++++++ templates/full-stack/frontend/src/index.html | 38 ++++ templates/full-stack/frontend/src/styles.css | 95 ++++++++++ .../full-stack/frontend/test/app.test.js | 171 +++++++++++++++++- tests/full-stack-template.test.ts | 17 ++ tests/nested-project-root.test.ts | 104 +++++++++++ 14 files changed, 877 insertions(+), 17 deletions(-) create mode 100644 templates/full-stack/frontend/src/index.html create mode 100644 templates/full-stack/frontend/src/styles.css create mode 100644 tests/nested-project-root.test.ts diff --git a/docs/reference/commands.md b/docs/reference/commands.md index 31b6e562..b521b002 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -133,6 +133,8 @@ The command requires a valid project `package.json` with a `scripts` object. Scr A candidate counts as present only when it is a string with a non-blank value; blank or whitespace-only entries are ignored in favour of the next candidate. If every supported candidate is blank or absent, the command fails with actionable guidance before any subprocess is spawned. +The supported invocation location is the generated project root or any nested directory inside it. Root discovery walks at most eight parent directories and stops at the filesystem root, a repository boundary (`.git`), or the generated `.stellarforge.json` marker. Exactly one project root must be discovered; nested workspaces and multiple project roots are rejected with actionable guidance before any subprocess is spawned. + StellarForge invokes npm as an executable with an argument array; it does not execute the package script text through a constructed shell command. Child stdout/stderr are streamed with process labels. @@ -167,6 +169,8 @@ Supported project forms are: A string-valued but empty or whitespace-only `scripts.test` is rejected with exit `2` before any subprocess is spawned, because npm treats an empty test script as a successful no-op and would report success without running any tests. +The supported invocation location is the generated project root or any nested directory inside it. Root discovery uses the same bounded policy as `stellarforge dev`: at most eight parent directories, stopping at the filesystem root, a `.git` boundary, or the generated `.stellarforge.json` marker. Multiple discovered roots are rejected instead of guessed. + When both are present, the Node.js project test workflow is selected first. StellarForge does not execute package script text directly. It delegates through npm or Cargo and preserves external-process failures. diff --git a/docs/reference/troubleshooting.md b/docs/reference/troubleshooting.md index 305839a4..a325509a 100644 --- a/docs/reference/troubleshooting.md +++ b/docs/reference/troubleshooting.md @@ -112,6 +112,8 @@ Selection follows that order, and a candidate only wins when its value is a non- If the selected npm process starts and then fails, StellarForge returns subprocess exit category `3`. +You may invoke `stellarforge dev` from the project root or a nested directory. Discovery stops at the filesystem root, a `.git` boundary, or the generated `.stellarforge.json` marker, and examines at most eight parent directories. If more than one project root is found, run the command from the single generated project root; nested workspaces are not supported. + See the [`dev` command reference](commands.md#stellarforge-dev). ## `stellarforge test` cannot find a workflow @@ -125,6 +127,8 @@ Node.js projects are run through `npm run test`; Cargo projects are run through A failing project test is preserved as a subprocess failure instead of being converted to success. +You may invoke `stellarforge test` from the project root or a nested directory. Discovery is bounded by the filesystem root, a `.git` boundary, or the generated `.stellarforge.json` marker, and examines at most eight parent directories. If more than one project root is found, run the command from the single generated project root. + See the [`test` command reference](commands.md#stellarforge-test). ## Configuration file is rejected diff --git a/src/dev/project.ts b/src/dev/project.ts index 9eccbb6c..ef13121e 100644 --- a/src/dev/project.ts +++ b/src/dev/project.ts @@ -1,8 +1,73 @@ import { existsSync, readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; +import { dirname, join, relative, resolve } from 'node:path'; import { ValidationCliError } from '../errors/errors.js'; +import { GENERATED_MARKER_FILENAME } from '../generator/template-generation.js'; import { createNpmInvocation } from '../process/npm.js'; +export const MAX_PROJECT_ROOT_SEARCH_DEPTH = 8; + +const PROJECT_MANIFEST_FILENAMES = ['package.json', 'Cargo.toml'] as const; +const PROJECT_BOUNDARY_FILENAMES = ['.git', GENERATED_MARKER_FILENAME] as const; + +function containsAny(directory: string, filenames: readonly string[]): boolean { + return filenames.some((filename) => existsSync(join(directory, filename))); +} + +export function discoverProjectRoots(cwd: string): readonly string[] { + const start = resolve(cwd); + const roots: string[] = []; + let current = start; + + for (let depth = 0; depth <= MAX_PROJECT_ROOT_SEARCH_DEPTH; depth += 1) { + if ( + containsAny(current, PROJECT_MANIFEST_FILENAMES) || + existsSync(join(current, GENERATED_MARKER_FILENAME)) + ) { + roots.push(current); + } + + if (containsAny(current, PROJECT_BOUNDARY_FILENAMES)) { + break; + } + + const parent = dirname(current); + if (parent === current) { + break; + } + current = parent; + } + + return roots; +} + +export function selectProjectRoot(cwd: string, commandName: string): string { + const start = resolve(cwd); + const roots = discoverProjectRoots(start); + + if (roots.length === 0) { + throw new ValidationCliError( + `No supported StellarForge project root was found for \`stellarforge ${commandName}\`. ` + + `Run the command from the generated project root or a nested directory inside it. ` + + `Expected a package.json, Cargo.toml, or ${GENERATED_MARKER_FILENAME} marker.`, + ); + } + + if (roots.length > 1) { + const descriptions = roots.map((root) => { + const fromStart = relative(start, root); + return fromStart.length === 0 ? '.' : fromStart; + }); + + throw new ValidationCliError( + `Multiple supported StellarForge project roots were found for \`stellarforge ${commandName}\`: ` + + `${descriptions.join(', ')}. Run the command from a single generated project root; ` + + `nested workspaces are not supported.`, + ); + } + + return roots[0] as string; +} + export interface DevProcessSpec { readonly label: string; readonly command: string; @@ -52,7 +117,7 @@ function selectDevelopmentScript(scripts: Record): string { } export function resolveDevProcessPlan(cwd: string): readonly DevProcessSpec[] { - const projectRoot = resolve(cwd); + const projectRoot = selectProjectRoot(cwd, 'dev'); const projectPackage = readProjectPackage(projectRoot); if ( diff --git a/src/testing/project.ts b/src/testing/project.ts index 5c61722c..0c12b296 100644 --- a/src/testing/project.ts +++ b/src/testing/project.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync } from 'node:fs'; import { resolve } from 'node:path'; -import type { DevProcessSpec } from '../dev/project.js'; +import { selectProjectRoot, type DevProcessSpec } from '../dev/project.js'; import { ValidationCliError } from '../errors/errors.js'; import { createNpmInvocation } from '../process/npm.js'; @@ -79,7 +79,7 @@ function resolveCargoTestPlan(projectRoot: string): DevProcessSpec | undefined { } export function resolveTestProcessPlan(cwd: string): readonly DevProcessSpec[] { - const projectRoot = resolve(cwd); + const projectRoot = selectProjectRoot(cwd, 'test'); const nodePlan = resolveNodeTestPlan(projectRoot); if (nodePlan !== undefined) { @@ -92,6 +92,6 @@ export function resolveTestProcessPlan(cwd: string): readonly DevProcessSpec[] { } throw new ValidationCliError( - 'No supported StellarForge test workflow was found. Expected a package.json test script or a Cargo.toml workspace.', + 'No supported StellarForge test workflow was found. Run `stellarforge test` from the generated project root or a nested directory inside it. Expected a package.json test script or a Cargo.toml workspace.', ); } diff --git a/templates/full-stack/README.md b/templates/full-stack/README.md index 3c92665d..1dd36334 100644 --- a/templates/full-stack/README.md +++ b/templates/full-stack/README.md @@ -5,7 +5,7 @@ Generated with the StellarForge `full-stack` template. ## Structure ```text -frontend/ Browser-facing application boundary and tests +frontend/ Browser-facing application boundary, starter page, styles, and tests backend/ Node.js API/runtime boundary and tests contracts/ Soroban contract workspace boundary ``` @@ -41,7 +41,9 @@ The starter has no build step and no runtime dependencies; `frontend/src/app.js` npm run start:backend ``` -The backend exposes `GET /health` and static frontend assets (such as `GET /app.js`) on `127.0.0.1:3000` by default. Set `BACKEND_PORT` to override the port. The frontend has no server and no port variable at all. +The backend exposes `GET /health` and static frontend assets on `127.0.0.1:3000` by default. Open `http://127.0.0.1:3000/index.html` for the generated starter UI, or import `frontend/src/app.js` from your own page. Set `BACKEND_PORT` to override the port. The frontend has no server and no port variable at all. + +The starter page checks `GET /health` once on load. Its live status region announces `checking backend`, `backend healthy`, or `backend unavailable` as text, so status is not conveyed by color alone. If the backend is unavailable, activate the **Retry backend status** button to try again; the button is disabled while a request is in flight, and the page never polls automatically. If the configured port is already in use, startup fails with a raw Node error such as: @@ -92,8 +94,25 @@ Production deployments must implement deployment-specific security controls: Copy `.env.example` into your preferred local environment-management flow. The example contains public Stellar Testnet endpoints only and no credentials. +Backend startup validates configuration before opening a socket: + +- `BACKEND_PORT` is an integer from `1` to `65535` (default `3000`); +- `STELLAR_NETWORK` must be `TESTNET` (the default); +- `STELLAR_HORIZON_URL` and `STELLAR_RPC_URL` must be absolute `http`/`https` URLs without embedded credentials (defaults are the public Testnet endpoints) and must not point to a non-Testnet network. + +Missing values use the documented Testnet defaults. Missing, malformed, or conflicting values fail with field-specific guidance before any bind, so an invalid configuration never partially starts the server. Error messages do not echo environment values or credentials. + Never commit wallet seeds, secret keys, signing credentials, production tokens, or private infrastructure credentials. +## Accessibility checklist + +The generated starter page is dependency-free and intended to be usable with a keyboard and assistive technology: + +1. Tab from the beginning of the page; the skip link, status button, and controls receive a visible focus outline. +2. Activate **Retry backend status** with `Enter` or `Space`; it is disabled while a status request is in flight. +3. Confirm the screen reader announces heading levels in order (`h1` then `h2`) and announces status changes through the `role="status"` live region. +4. Confirm the status word (`checking backend`, `backend healthy`, or `backend unavailable`) is visible and not indicated only by color. + ## Contracts `contracts/` is intentionally a boundary rather than a fake production contract. Add reviewed Soroban code when the application domain is defined, or generate a dedicated StellarForge `smart-contract` starter for contract-focused work. diff --git a/templates/full-stack/backend/src/server.js b/templates/full-stack/backend/src/server.js index ceed741a..5265a879 100644 --- a/templates/full-stack/backend/src/server.js +++ b/templates/full-stack/backend/src/server.js @@ -27,13 +27,115 @@ export const STATIC_MIME_TYPES = Object.freeze({ '.ico': 'image/x-icon', }); +export const BACKEND_DEFAULTS = Object.freeze({ + network: 'TESTNET', + horizonUrl: 'https://horizon-testnet.stellar.org', + rpcUrl: 'https://soroban-testnet.stellar.org', + port: 3000, +}); + +const SUPPORTED_NETWORK = 'TESTNET'; +const NON_TESTNET_HOST_PATTERN = /(?:^|[.-])(mainnet|pubnet|public)(?:[.-]|$)/i; + +export class BackendConfigurationError extends Error { + constructor(message) { + super(message); + this.name = 'BackendConfigurationError'; + } +} + +function parsePort(value) { + if (typeof value !== 'string' && typeof value !== 'number') { + return Number.NaN; + } + + const text = String(value).trim(); + if (!/^\d+$/.test(text)) { + return Number.NaN; + } + + const port = Number(text); + return port >= 1 && port <= 65535 ? port : Number.NaN; +} + +function parseEndpoint(name, value, errors) { + if (typeof value !== 'string' || value.trim().length === 0) { + errors.push(`${name} must be an absolute http(s) URL.`); + return undefined; + } + + let parsed; + try { + parsed = new URL(value); + } catch { + errors.push(`${name} must be an absolute http(s) URL.`); + return undefined; + } + + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + errors.push(`${name} must use http or https.`); + } + if (parsed.username.length > 0 || parsed.password.length > 0) { + errors.push(`${name} must not contain embedded credentials.`); + } + if (parsed.hostname.length === 0) { + errors.push(`${name} must include a host.`); + } + + return parsed; +} + +export function validateBackendConfig(config) { + const errors = []; + const network = + typeof config?.network === 'string' + ? config.network.trim().toUpperCase() + : ''; + + if ( + !Number.isInteger(config?.port) || + config.port < 1 || + config.port > 65535 + ) { + errors.push('BACKEND_PORT must be a decimal integer from 1 to 65535.'); + } + if (network !== SUPPORTED_NETWORK) { + errors.push('STELLAR_NETWORK must be TESTNET for this starter.'); + } + + const endpoints = [ + ['STELLAR_HORIZON_URL', config?.horizonUrl], + ['STELLAR_RPC_URL', config?.rpcUrl], + ]; + + for (const [name, value] of endpoints) { + const parsed = parseEndpoint(name, value, errors); + if ( + parsed && + network === SUPPORTED_NETWORK && + NON_TESTNET_HOST_PATTERN.test(parsed.hostname) + ) { + errors.push( + `${name} points to a non-Testnet Stellar endpoint; this starter supports TESTNET only.`, + ); + } + } + + if (errors.length > 0) { + throw new BackendConfigurationError( + `Invalid Full Stack backend configuration:\n- ${errors.join('\n- ')}`, + ); + } + + return config; +} + export function getBackendConfig(env = globalThis.process.env) { return { - network: env.STELLAR_NETWORK ?? 'TESTNET', - horizonUrl: - env.STELLAR_HORIZON_URL ?? 'https://horizon-testnet.stellar.org', - rpcUrl: env.STELLAR_RPC_URL ?? 'https://soroban-testnet.stellar.org', - port: Number.parseInt(env.BACKEND_PORT ?? '3000', 10), + network: env.STELLAR_NETWORK ?? BACKEND_DEFAULTS.network, + horizonUrl: env.STELLAR_HORIZON_URL ?? BACKEND_DEFAULTS.horizonUrl, + rpcUrl: env.STELLAR_RPC_URL ?? BACKEND_DEFAULTS.rpcUrl, + port: parsePort(env.BACKEND_PORT ?? BACKEND_DEFAULTS.port), }; } diff --git a/templates/full-stack/backend/src/start.js b/templates/full-stack/backend/src/start.js index 46966a2c..8d8c0730 100644 --- a/templates/full-stack/backend/src/start.js +++ b/templates/full-stack/backend/src/start.js @@ -1,6 +1,34 @@ -import { createBackendServer, getBackendConfig } from './server.js'; +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + createBackendServer, + getBackendConfig, + validateBackendConfig, +} from './server.js'; -const config = getBackendConfig(); -const server = createBackendServer(); +export function startBackend( + env = globalThis.process.env, + listen = (server, port) => server.listen(port, '127.0.0.1'), +) { + const config = getBackendConfig(env); + validateBackendConfig(config); + const server = createBackendServer(env); + const listener = listen(server, config.port); -server.listen(config.port, '127.0.0.1'); + return { config, listener, server }; +} + +const invokedDirectly = + process.argv[1] !== undefined && + resolve(process.argv[1]) === fileURLToPath(import.meta.url); + +if (invokedDirectly) { + try { + startBackend(); + } catch (error) { + console.error( + error instanceof Error ? error.message : 'Backend startup failed.', + ); + process.exitCode = 1; + } +} diff --git a/templates/full-stack/backend/test/server.test.js b/templates/full-stack/backend/test/server.test.js index 71e7fbf3..a285e61a 100644 --- a/templates/full-stack/backend/test/server.test.js +++ b/templates/full-stack/backend/test/server.test.js @@ -3,12 +3,15 @@ import { Buffer } from 'node:buffer'; import { once } from 'node:events'; import http from 'node:http'; import test from 'node:test'; +import { startBackend } from '../src/start.js'; import { BASELINE_SECURITY_HEADERS, + BackendConfigurationError, createBackendServer, createHealthPayload, getBackendConfig, MAX_REQUEST_BODY_BYTES, + validateBackendConfig, } from '../src/server.js'; test('uses safe Testnet defaults without secrets', () => { @@ -426,3 +429,85 @@ test('HTTP server applies baseline security headers on error and traversal respo server.close(); } }); + +test('validates the documented Testnet defaults', () => { + const config = getBackendConfig({}); + + assert.deepEqual(validateBackendConfig(config), config); +}); + +test('rejects missing or malformed port values before startup', () => { + for (const value of ['', ' ', 'abc', '3000abc', '0', '-1', '65536', '3.5']) { + const config = getBackendConfig({ BACKEND_PORT: value }); + assert.throws( + () => validateBackendConfig(config), + (error) => + error instanceof BackendConfigurationError && + /BACKEND_PORT/.test(error.message), + ); + } + + assert.equal(getBackendConfig({ BACKEND_PORT: '3100' }).port, 3100); +}); + +test('rejects malformed Stellar endpoints without echoing secret-like values', () => { + const secretEndpoint = 'https://user:token@example.test/health'; + const config = getBackendConfig({ + STELLAR_HORIZON_URL: secretEndpoint, + STELLAR_RPC_URL: 'not-a-url', + }); + + assert.throws( + () => validateBackendConfig(config), + (error) => { + assert.ok(error instanceof BackendConfigurationError); + assert.match(error.message, /STELLAR_HORIZON_URL/); + assert.match(error.message, /STELLAR_RPC_URL/); + assert.doesNotMatch(error.message, /token|user|example\.test|not-a-url/); + return true; + }, + ); +}); + +test('rejects conflicting network mode and endpoint values', () => { + assert.throws( + () => validateBackendConfig(getBackendConfig({ STELLAR_NETWORK: 'MAINNET' })), + (error) => + error instanceof BackendConfigurationError && + /STELLAR_NETWORK must be TESTNET/.test(error.message), + ); + + assert.throws( + () => + validateBackendConfig( + getBackendConfig({ + STELLAR_HORIZON_URL: 'https://horizon-mainnet.stellar.org', + }), + ), + (error) => + error instanceof BackendConfigurationError && + /non-Testnet Stellar endpoint/.test(error.message), + ); +}); + +test('startup validation runs before any listener is opened', () => { + const listened = []; + const listen = (server, port) => { + listened.push({ server, port }); + return 'listener'; + }; + + assert.throws( + () => startBackend({ BACKEND_PORT: 'not-a-port' }, listen), + BackendConfigurationError, + ); + assert.deepEqual(listened, []); + + const started = startBackend({ BACKEND_PORT: '3100' }, listen); + assert.equal(started.config.port, 3100); + assert.equal(started.listener, 'listener'); + assert.deepEqual( + listened.map((entry) => entry.port), + [3100], + ); +}); diff --git a/templates/full-stack/frontend/src/app.js b/templates/full-stack/frontend/src/app.js index a2089d9e..888750da 100644 --- a/templates/full-stack/frontend/src/app.js +++ b/templates/full-stack/frontend/src/app.js @@ -1,3 +1,21 @@ +export const BACKEND_STATUS = Object.freeze({ + LOADING: 'loading', + HEALTHY: 'healthy', + UNAVAILABLE: 'unavailable', +}); + +export const STATUS_ELEMENT_ID = 'backend-status'; +export const RETRY_BUTTON_ID = 'retry-backend'; + +const STATUS_MESSAGES = Object.freeze({ + [BACKEND_STATUS.LOADING]: 'Status: checking backend...', + [BACKEND_STATUS.HEALTHY]: 'Status: backend healthy', + [BACKEND_STATUS.UNAVAILABLE]: + 'Status: backend unavailable. Use Retry backend status to try again.', +}); + +const RETRY_LABEL = 'Retry backend status'; + export function createAppModel() { return { name: '{{projectName}}', @@ -5,3 +23,115 @@ export function createAppModel() { backendHealthPath: '/health', }; } + +export function createStatusView(state, attempt = 0) { + const message = STATUS_MESSAGES[state]; + if (message === undefined) { + throw new Error(`Unknown backend status: ${state}`); + } + + return Object.freeze({ + state, + message, + retryLabel: RETRY_LABEL, + isLoading: state === BACKEND_STATUS.LOADING, + attempt, + }); +} + +export function createBackendStatusClient({ + fetchImpl = globalThis.fetch, + healthPath = '/health', + onStatusChange = () => {}, +} = {}) { + let state = BACKEND_STATUS.LOADING; + let attempt = 0; + let inFlight = false; + + const getState = () => createStatusView(state, attempt); + + const notify = () => { + onStatusChange(getState()); + }; + + const refresh = async () => { + if (inFlight) { + return getState(); + } + + inFlight = true; + attempt += 1; + state = BACKEND_STATUS.LOADING; + notify(); + + try { + if (typeof fetchImpl !== 'function') { + throw new Error('fetch is unavailable'); + } + + const response = await fetchImpl(healthPath, { + headers: { accept: 'application/json' }, + }); + if (!response.ok) { + throw new Error('backend returned an error'); + } + + const payload = await response.json(); + if (payload?.status !== 'ok') { + throw new Error('backend returned an unexpected payload'); + } + + state = BACKEND_STATUS.HEALTHY; + } catch { + state = BACKEND_STATUS.UNAVAILABLE; + } finally { + inFlight = false; + notify(); + } + + return getState(); + }; + + return Object.freeze({ getState, refresh }); +} + +export function renderBackendStatus(view, elements) { + const { statusElement, retryButton } = elements; + + statusElement.textContent = view.message; + statusElement.setAttribute('data-state', view.state); + statusElement.setAttribute('aria-busy', String(view.isLoading)); + statusElement.className = `status status--${view.state}`; + retryButton.disabled = view.isLoading; + retryButton.textContent = view.retryLabel; + + return { statusElement, retryButton }; +} + +export function mountApp(document = globalThis.document, options = {}) { + const statusElement = document.getElementById(STATUS_ELEMENT_ID); + const retryButton = document.getElementById(RETRY_BUTTON_ID); + + if (!statusElement || !retryButton) { + throw new Error( + 'Full Stack starter markup is missing the backend status elements.', + ); + } + + const controller = createBackendStatusClient({ + ...options, + onStatusChange: (view) => { + renderBackendStatus(view, { statusElement, retryButton }); + options.onStatusChange?.(view); + }, + }); + + retryButton.addEventListener('click', () => { + void controller.refresh(); + }); + + renderBackendStatus(controller.getState(), { statusElement, retryButton }); + void controller.refresh(); + + return controller; +} diff --git a/templates/full-stack/frontend/src/index.html b/templates/full-stack/frontend/src/index.html new file mode 100644 index 00000000..e083dd14 --- /dev/null +++ b/templates/full-stack/frontend/src/index.html @@ -0,0 +1,38 @@ + + + + + + {{projectName}} — Full Stack Starter + + + + +
+

{{projectName}}

+

Full Stack starter on Stellar Testnet

+
+
+
+

Backend status

+

Status: checking backend...

+ +
+
+
+

Local development only. No credentials are required.

+
+ + + diff --git a/templates/full-stack/frontend/src/styles.css b/templates/full-stack/frontend/src/styles.css new file mode 100644 index 00000000..b0677647 --- /dev/null +++ b/templates/full-stack/frontend/src/styles.css @@ -0,0 +1,95 @@ +:root { + color-scheme: light; + font-family: + system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + color: #202124; + background: #f8f9fa; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + line-height: 1.5; +} + +.skip-link { + position: absolute; + top: 0; + left: -9999px; + z-index: 10; + padding: 0.5rem 0.75rem; + color: #ffffff; + background: #174ea6; +} + +.skip-link:focus { + left: 1rem; + top: 1rem; +} + +:focus-visible { + outline: 3px solid #174ea6; + outline-offset: 3px; +} + +.app-header, +main, +footer { + margin: 0 auto; + max-width: 48rem; + padding: 1.5rem; +} + +.app-header h1 { + margin-bottom: 0.25rem; +} + +.status-panel { + padding: 1.25rem; + border: 1px solid #dadce0; + border-radius: 0.5rem; + background: #ffffff; +} + +.status { + margin: 1rem 0; + padding: 0.75rem 1rem; + border-left: 0.4rem solid #5f6368; + background: #f1f3f4; + font-weight: 600; +} + +.status[data-state="healthy"] { + border-left-color: #1b7f3a; +} + +.status[data-state="unavailable"] { + border-left-color: #b3261e; +} + +.status[data-state="loading"] { + border-left-color: #5f6368; +} + +button { + padding: 0.6rem 1rem; + border: 1px solid #174ea6; + border-radius: 0.25rem; + color: #ffffff; + background: #174ea6; + font: inherit; + cursor: pointer; +} + +button:hover:not(:disabled) { + background: #0b3b7a; +} + +button:disabled { + border-color: #9aa0a6; + background: #9aa0a6; + cursor: not-allowed; +} diff --git a/templates/full-stack/frontend/test/app.test.js b/templates/full-stack/frontend/test/app.test.js index 95b1c58e..a7de5fd0 100644 --- a/templates/full-stack/frontend/test/app.test.js +++ b/templates/full-stack/frontend/test/app.test.js @@ -1,6 +1,29 @@ import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; import test from 'node:test'; -import { createAppModel } from '../src/app.js'; +import { + BACKEND_STATUS, + createAppModel, + createBackendStatusClient, + createStatusView, + renderBackendStatus, +} from '../src/app.js'; + +function createHealthyResponse() { + return { + ok: true, + json: async () => ({ status: 'ok' }), + }; +} + +function createDeferred() { + let resolve; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + + return { promise, resolve }; +} test('exposes the generated app identity and Testnet boundary', () => { const model = createAppModel(); @@ -9,3 +32,149 @@ test('exposes the generated app identity and Testnet boundary', () => { assert.equal(model.network, 'Stellar Testnet'); assert.equal(model.backendHealthPath, '/health'); }); + +test('loading, healthy, and unavailable states are textually distinct', () => { + const loading = createStatusView(BACKEND_STATUS.LOADING); + const healthy = createStatusView(BACKEND_STATUS.HEALTHY); + const unavailable = createStatusView(BACKEND_STATUS.UNAVAILABLE); + + assert.equal(loading.state, 'loading'); + assert.equal(loading.isLoading, true); + assert.equal(healthy.state, 'healthy'); + assert.equal(healthy.isLoading, false); + assert.equal(unavailable.state, 'unavailable'); + assert.equal(unavailable.isLoading, false); + + const messages = [loading.message, healthy.message, unavailable.message]; + assert.equal(new Set(messages).size, 3); + for (const message of messages) { + assert.match(message, /^Status:/); + } + assert.match(unavailable.message, /backend unavailable/i); +}); + +test('an initial backend failure renders an understandable unavailable state', async () => { + const states = []; + const client = createBackendStatusClient({ + fetchImpl: async () => { + throw new Error('offline'); + }, + onStatusChange: (view) => states.push(view.state), + }); + + const result = await client.refresh(); + + assert.equal(result.state, BACKEND_STATUS.UNAVAILABLE); + assert.match(result.message, /backend unavailable/i); + assert.deepEqual(states, ['loading', 'unavailable']); +}); + +test('a user-triggered retry recovers when the backend returns', async () => { + let calls = 0; + const client = createBackendStatusClient({ + fetchImpl: async () => { + calls += 1; + if (calls === 1) { + throw new Error('offline'); + } + return createHealthyResponse(); + }, + }); + + assert.equal((await client.refresh()).state, BACKEND_STATUS.UNAVAILABLE); + const recovered = await client.refresh(); + + assert.equal(calls, 2); + assert.equal(recovered.state, BACKEND_STATUS.HEALTHY); + assert.match(recovered.message, /backend healthy/i); +}); + +test('repeated retry actions do not start unbounded concurrent requests', async () => { + let calls = 0; + const pending = createDeferred(); + const client = createBackendStatusClient({ + fetchImpl: async () => { + calls += 1; + return pending.promise; + }, + }); + + const first = client.refresh(); + const second = client.refresh(); + const third = client.refresh(); + + assert.equal(calls, 1); + + pending.resolve(createHealthyResponse()); + const results = await Promise.all([first, second, third]); + assert.equal(calls, 1); + assert.ok(results.every((result) => result.state === BACKEND_STATUS.HEALTHY)); + + await client.refresh(); + assert.equal(calls, 2); +}); + +test('rendering status updates text, live-region metadata, and retry control', () => { + const attributes = {}; + const statusElement = { + textContent: '', + className: '', + setAttribute(name, value) { + attributes[name] = value; + }, + }; + const retryButton = { disabled: false, textContent: '' }; + + renderBackendStatus(createStatusView(BACKEND_STATUS.LOADING, 1), { + statusElement, + retryButton, + }); + + assert.equal(statusElement.textContent, 'Status: checking backend...'); + assert.equal(statusElement.className, 'status status--loading'); + assert.deepEqual(attributes, { + 'data-state': 'loading', + 'aria-busy': 'true', + }); + assert.equal(retryButton.disabled, true); + assert.equal(retryButton.textContent, 'Retry backend status'); + + renderBackendStatus(createStatusView(BACKEND_STATUS.UNAVAILABLE, 2), { + statusElement, + retryButton, + }); + + assert.equal(statusElement.className, 'status status--unavailable'); + assert.equal(attributes['data-state'], 'unavailable'); + assert.equal(attributes['aria-busy'], 'false'); + assert.equal(retryButton.disabled, false); +}); + +test('starter markup and styles provide accessible structure without polling', () => { + const markup = readFileSync( + new URL('../src/index.html', import.meta.url), + 'utf8', + ); + const styles = readFileSync( + new URL('../src/styles.css', import.meta.url), + 'utf8', + ); + const source = readFileSync( + new URL('../src/app.js', import.meta.url), + 'utf8', + ); + + assert.match(markup, //); + assert.match(markup, //); + assert.match(markup, /
/); + assert.match(markup, /

/); + assert.ok(markup.indexOf('

') < markup.indexOf(' { expect(existsSync(join(projectRoot, 'frontend', 'src', 'app.js'))).toBe( true, ); + expect( + existsSync(join(projectRoot, 'frontend', 'src', 'index.html')), + ).toBe(true); + expect( + existsSync(join(projectRoot, 'frontend', 'src', 'styles.css')), + ).toBe(true); expect( existsSync(join(projectRoot, 'backend', 'src', 'server.js')), ).toBe(true); @@ -69,6 +75,14 @@ describe('Full Stack template', () => { const test = runNpmScript(projectRoot, 'test'); expect(test.status, test.stderr).toBe(0); + const starterMarkup = readFileSync( + join(projectRoot, 'frontend', 'src', 'index.html'), + 'utf8', + ); + expect(starterMarkup).toContain('role="status"'); + expect(starterMarkup).toContain('aria-live="polite"'); + expect(starterMarkup).toContain('Retry backend status'); + const generatedReadme = readFileSync( join(projectRoot, 'README.md'), 'utf8', @@ -77,6 +91,9 @@ describe('Full Stack template', () => { expect(generatedReadme).toContain('backend/'); expect(generatedReadme).toContain('contracts/'); expect(generatedReadme).toContain('no credentials'); + expect(generatedReadme).toContain('/index.html'); + expect(generatedReadme).toContain('Retry backend status'); + expect(generatedReadme).toContain('before opening a socket'); // Port-collision guidance (issue SW-196). expect(generatedReadme).toContain('EADDRINUSE'); expect(generatedReadme).toContain('BACKEND_PORT'); diff --git a/tests/nested-project-root.test.ts b/tests/nested-project-root.test.ts new file mode 100644 index 00000000..21aa534e --- /dev/null +++ b/tests/nested-project-root.test.ts @@ -0,0 +1,104 @@ +import { mkdirSync, writeFileSync } from 'node:fs'; +import { join, parse } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { resolveDevProcessPlan } from '../src/dev/project.js'; +import { ValidationCliError } from '../src/errors/errors.js'; +import { resolveTestProcessPlan } from '../src/testing/project.js'; +import { withTempDirectory } from './helpers/index.js'; + +const MAX_DEPTH = 8; + +function writePackage( + root: string, + scripts: Record = { + dev: 'node dev.js', + test: 'node --test', + }, +): void { + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ name: 'demo', scripts }), + ); +} + +describe('nested project root discovery', () => { + it('resolves a project root from nested folders for dev and test', () => + withTempDirectory((root) => { + writePackage(root); + const nested = join(root, 'frontend', 'src'); + mkdirSync(nested, { recursive: true }); + + expect(resolveDevProcessPlan(nested)[0]?.cwd).toBe(root); + expect(resolveTestProcessPlan(nested)[0]?.cwd).toBe(root); + })); + + it('uses the generated marker as a bounded root boundary', () => + withTempDirectory((root) => { + writePackage(root); + writeFileSync(join(root, '.stellarforge.json'), '{}'); + const nested = join(root, 'backend', 'src'); + mkdirSync(nested, { recursive: true }); + + expect(resolveDevProcessPlan(nested)[0]?.cwd).toBe(root); + expect(resolveTestProcessPlan(nested)[0]?.cwd).toBe(root); + })); + + it('rejects multiple supported project roots instead of guessing', () => + withTempDirectory((root) => { + writePackage(root); + const nested = join(root, 'frontend'); + mkdirSync(nested); + writePackage(nested); + + expect(() => resolveDevProcessPlan(nested)).toThrow(ValidationCliError); + expect(() => resolveDevProcessPlan(nested)).toThrow( + /Multiple supported StellarForge project roots/, + ); + expect(() => resolveTestProcessPlan(nested)).toThrow( + /Multiple supported StellarForge project roots/, + ); + })); + + it('stops discovery at a repository boundary', () => + withTempDirectory((root) => { + writePackage(root); + const boundary = join(root, 'repo'); + const nested = join(boundary, 'frontend', 'src'); + mkdirSync(join(boundary, '.git'), { recursive: true }); + mkdirSync(nested, { recursive: true }); + + expect(() => resolveDevProcessPlan(nested)).toThrow( + /No supported StellarForge project root/, + ); + expect(() => resolveTestProcessPlan(nested)).toThrow( + /No supported StellarForge project root/, + ); + })); + + it('stops discovery at the maximum search depth', () => + withTempDirectory((root) => { + writePackage(root); + const deep = join( + root, + ...Array.from({ length: MAX_DEPTH + 2 }, (_, index) => + `level-${index}`, + ), + ); + mkdirSync(deep, { recursive: true }); + + expect(() => resolveDevProcessPlan(deep)).toThrow( + /No supported StellarForge project root/, + ); + })); + + it('terminates at a filesystem root without finding a project', () => { + const filesystemRoot = parse(process.cwd()).root; + + expect(() => resolveDevProcessPlan(filesystemRoot)).toThrow( + ValidationCliError, + ); + expect(() => resolveTestProcessPlan(filesystemRoot)).toThrow( + ValidationCliError, + ); + }); +});