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
4 changes: 4 additions & 0 deletions docs/reference/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions docs/reference/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
69 changes: 67 additions & 2 deletions src/dev/project.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -63,7 +128,7 @@ function selectDevelopmentScript(scripts: Record<string, unknown>): string {
}

export function resolveDevProcessPlan(cwd: string): readonly DevProcessSpec[] {
const projectRoot = resolveProjectRoot(cwd);
const projectRoot = selectProjectRoot(cwd, 'dev');
const projectPackage = readProjectPackage(projectRoot);

if (
Expand Down
4 changes: 2 additions & 2 deletions src/testing/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ function resolveCargoTestPlan(projectRoot: string): DevProcessSpec | undefined {
}

export function resolveTestProcessPlan(cwd: string): readonly DevProcessSpec[] {
const projectRoot = resolveProjectRoot(cwd);
const projectRoot = selectProjectRoot(cwd, 'test');
const nodePlan = resolveNodeTestPlan(projectRoot);

if (nodePlan !== undefined) {
Expand All @@ -97,6 +97,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.',
);
}
23 changes: 21 additions & 2 deletions templates/full-stack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
Expand Down Expand Up @@ -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.

On `SIGINT` or `SIGTERM`, the backend stops accepting new connections, drains active requests for up to five seconds, and then closes remaining connections so a stuck request cannot keep the process alive. Repeated signals do not start a second shutdown.

Expand Down Expand Up @@ -94,8 +96,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.
Expand Down
112 changes: 107 additions & 5 deletions templates/full-stack/backend/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
}

Expand Down
Loading
Loading