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
28 changes: 14 additions & 14 deletions docs/reference/exit-codes.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ StellarForge CLI uses predictable process exit codes so humans, scripts, and CI
## Stable Baseline

| Exit code | Category | Meaning |
|---:|---------|---------|
| `0` x Success | The requested CLI operation completed successfully. |
| `1` x Unexpected failure | An unclassified exception reached the top-level CLI boundary. |
| `2` x Validation / usage failure | User input, command syntax, options, arguments, or other validated input was invalid. |
| `3` x Subprocess failure | A required external process or tool failed. |
| `4` x Internal failure | StellarForge detected a known internal failure condition that should not expose implementation details to the user. |
| `5` x Diagnostic failure | A diagnostic command completed normally but one or more required checks failed; used by `doctor` (environment health) and `stellarforge validate` (local project requirements). |
| `130` x Cancellation | The operation was interrupted by the user (SIGINT or equivalent) and stopped before completion. |
|---:|---|---|
| `0` | Success | The requested CLI operation completed successfully. |
| `1` | Unexpected failure | An unclassified exception reached the top-level CLI boundary. |
| `2` | Validation / usage failure | User input, command syntax, options, arguments, or other validated input was invalid. |
| `3` | Subprocess failure | A required external process or tool failed. |
| `4` | Internal failure | StellarForge detected a known internal failure condition that should not expose implementation details to the user. |
| `5` | Diagnostic failure | A diagnostic command completed normally but one or more required checks failed; used by `doctor` (environment health) and `stellarforge validate` (local project requirements). |
| `130` | Cancellation | The operation was interrupted by the user (SIGINT or equivalent) and stopped before completion. |


These values are part of the CLI contract and should not be changed casually. New stable categories require deliberate review and documentation.
Expand All @@ -33,12 +33,12 @@ An incomplete/partial diagnostic set (for example, checks without remediation) i
## Troubleshooting by Exit Code

| Exit code | Start here |
|---:|---------|
| `2` if [Usage](troubleshooting.md#command-or-option-is-not-recognized), [`new`](troubleshooting.md#stellarforge-new-cannot-create-the-project), [project name](troubleshooting.md#project-name-is-rejected), [configuration](troubleshooting.md#configuration-file-is-rejected), [deployment network](troubleshooting.md#deployment-network-is-required), or [deployment identity](troubleshooting.md#deployment-identity-is-rejected) |
| `3` if [`dev`](troubleshooting.md#stellarforge-dev-says-no-supported-script-exists), [`test`](troubleshooting.md#stellarforge-test-cannot-find-a-workflow), or [Stellar CLI deployment](troubleshooting.md#stellar-cli-deployment-fails) |
| `5` if [`doctor`](troubleshooting.md#stellarforge-doctor-reports-failures), [`validate`](troubleshooting.md#stellarforge-validate-reports-required-project-failures) |
| `130` if [Cancellation](troubleshooting.md#cancelled-operation) |
| `1` or `<` if [Unexpected or internal failure](troubleshooting.md#unexpected-or-internal-failure) |
|---:|---|
| `2` | [Usage](troubleshooting.md#command-or-option-is-not-recognized), [`new`](troubleshooting.md#stellarforge-new-cannot-create-the-project), [project name](troubleshooting.md#project-name-is-rejected), [configuration](troubleshooting.md#configuration-file-is-rejected), [deployment network](troubleshooting.md#deployment-network-is-required), or [deployment identity](troubleshooting.md#deployment-identity-is-rejected) |
| `3` | [`dev`](troubleshooting.md#stellarforge-dev-says-no-supported-script-exists), [`test`](troubleshooting.md#stellarforge-test-cannot-find-a-workflow), or [Stellar CLI deployment](troubleshooting.md#stellar-cli-deployment-fails) |
| `5` | [`doctor`](troubleshooting.md#stellarforge-doctor-reports-failures), [`validate`](troubleshooting.md#stellarforge-validate-reports-required-project-failures) |
| `130` | [Cancellation](troubleshooting.md#cancelled-operation) |
| `1` or `4` | [Unexpected or internal failure](troubleshooting.md#unexpected-or-internal-failure) |

The full index is at [Troubleshooting](troubleshooting.md#find-your-problem).

Expand Down
25 changes: 25 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,31 @@ export default tseslint.config(
rules: {
'@typescript-eslint/consistent-type-imports': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
],
},
},
{
files: ['templates/**/*.js'],
languageOptions: {
globals: {
AbortController: 'readonly',
AbortSignal: 'readonly',
Buffer: 'readonly',
Headers: 'readonly',
URL: 'readonly',
URLSearchParams: 'readonly',
clearInterval: 'readonly',
clearTimeout: 'readonly',
console: 'readonly',
fetch: 'readonly',
globalThis: 'readonly',
process: 'readonly',
setInterval: 'readonly',
setTimeout: 'readonly',
},
},
},
);
8 changes: 0 additions & 8 deletions scripts/audit-workflow-permissions.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,6 @@
import fs from 'node:fs';
import path from 'node:path';

/** Explicit per-job exceptions for workflows that must write. */
const ARTIFACT_RETENTION_DAYS = {
test: 7,
coverage: 7,
security: 30,
release: 90,
};

/** Artifact path patterns that must never be uploaded. */
const FORBIDDEN_ARTIFACT_PATTERNS = [
/\.env(\b|$)/i,
Expand Down
3 changes: 1 addition & 2 deletions src/commands/new.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,7 @@ export function createNewCommand(options: NewCommandOptions = {}): Command {

if (cancelled) {
throw new ScaffoldingCancelledCliError();
},
);
}

if (signal.aborted) {
throw signal.reason;
Expand Down
3 changes: 2 additions & 1 deletion src/deployment/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ export function runDeploymentPreflight(
});

let identityOk = true;
let identityRemediation: string | undefined;
let identityRemediation =
'Pass `--source <identity>` with a valid named Stellar CLI identity alias.';
try {
validateIdentityAlias(input.source);
} catch (error) {
Expand Down
4 changes: 3 additions & 1 deletion src/generator/template-generation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
ScaffoldingCancelledCliError,
ValidationCliError,
} from '../errors/errors.js';
import { ValidationCliError } from '../errors/errors.js';
import { resolveCliVersion } from '../version.js';
import type {
GenerationContext,
Expand Down Expand Up @@ -120,6 +119,8 @@ function assertNotCancelled(isCancelled?: () => boolean): void {
if (isCancelled?.()) {
throw new ScaffoldingCancelledCliError();
}
}

/**
* Measures the template tree before any file is written. Exceeding a documented
* limit fails with a safe aggregate message that never embeds local paths or
Expand Down Expand Up @@ -507,6 +508,7 @@ export function generateProjectFromTemplate(
'utf8',
);

assertNotCancelled(options.isCancelled);
renameSync(stagingRoot, destination);
} catch (error) {
rmSync(stagingRoot, { recursive: true, force: true });
Expand Down
2 changes: 1 addition & 1 deletion src/output/redaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const URL_WITH_QUERY = /\b([a-z][a-z0-9+.-]*:\/\/[^\s"'<>?]*\?)([^\s"'<>]*)/gi;
* URL userinfo passwords, and token-bearing URL query parameters.
*/
function redactUrlQuery(query: string): string {
return query.replace(/([^?&#=]+)=([^&#]*)/g, (match, key, value) => {
return query.replace(/([^?&#=]+)=([^&#]*)/g, (match, key) => {
if (!TOKEN_QUERY_KEY.test(String(key))) {
return match;
}
Expand Down
2 changes: 1 addition & 1 deletion templates/api-service/test/server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,7 @@ test('malformed, oversized, and multi-value correlation ids are replaced', async
await response.json();
}

const headers = new Headers();
const headers = new globalThis.Headers();
headers.append('x-correlation-id', 'first');
headers.append('x-correlation-id', 'second');
const repeated = await globalThis.fetch(
Expand Down
9 changes: 6 additions & 3 deletions templates/basic-app/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,16 @@ try {
);
writeLine(process.stdout, `horizonUrl: ${horizonUrl}`);
writeLine(process.stdout, `rpcUrl: ${rpcUrl}`);

globalThis.console.log(
`{{projectName}} is configured for the ${network.network} Stellar network.`,
);
globalThis.console.log(`Horizon: ${network.horizonUrl}`);
globalThis.console.log(`RPC: ${network.rpcUrl}`);
} catch (error) {
const message =
error instanceof Error ? error.message : 'Unknown startup failure.';
writeLine(process.stderr, 'status: failed');
writeLine(process.stderr, `error: ${message}`);
process.exit(1);
}
globalThis.console.log(`{{projectName}} is configured for the ${network.network} Stellar network.`);
globalThis.console.log(`Horizon: ${network.horizonUrl}`);
globalThis.console.log(`RPC: ${network.rpcUrl}`);
4 changes: 2 additions & 2 deletions templates/basic-app/src/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const SUPPORTED_NETWORKS = Object.freeze({
testnet: Object.freeze({
horizonUrl: DEFAULT_HORIZON_URL,
rpcUrl: DEFAULT_RPC_URL,
networkPassphrase: DEFAULT_NETWORK_PASSPHRASE,
networkPassphrase: DEFAULT_NETWORK_PASSTHRASE,
}),
local: Object.freeze({
horizonUrl: 'http://127.0.0.1:8000',
Expand Down Expand Up @@ -62,7 +62,7 @@ function validateEndpoint(label, value) {

let parsed;
try {
parsed = new URL(trimmed);
parsed = new globalThis.URL(trimmed);
} catch {
// Do not echo the input: URLs may contain credentials.
throw new TypeError(`${label} is not a valid URL.`);
Expand Down
7 changes: 1 addition & 6 deletions templates/basic-app/test/lifecycle.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import assert from 'node:assert/strict';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { fileURLToPath } from 'node:url';
Expand Down Expand Up @@ -103,13 +103,8 @@ test('reports actionable startup failure and exits non-zero for invalid configur
stdio: ['ignore', 'pipe', 'pipe'],
});

let stdout = '';
let stderr = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk) => {
stdout += chunk;
});
child.stderr.on('data', (chunk) => {
stderr += chunk;
});
Expand Down
9 changes: 2 additions & 7 deletions tests/deploy-preflight-validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,7 @@ describe('SW-161: deploy validation before subprocess side effects', () => {
writeValidProject(root);
writeConfig(root, config);
expectZeroSubprocessSideEffects(
await runInvalidDeploy(root, [
'--network',
'testnet',
'--source',
'deployer',
]),
await runInvalidDeploy(root, ['--source', 'deployer']),
);
});
});
Expand Down Expand Up @@ -247,7 +242,7 @@ describe('SW-161: deploy validation before subprocess side effects', () => {
writeConfig(root, config);
const captured = createCapturedTerminalOutput();
const child = new FakeChildProcess();
const executor = vi.fn(() => child);
const executor = vi.fn((_spec: DevProcessSpec) => child);
const command = createDeployCommand({
cwd: () => root,
output: captured.output,
Expand Down
1 change: 1 addition & 0 deletions tests/exit-code-reference.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ describe('exit-code reference conformance', () => {
subprocess: 3,
internal: 4,
diagnostic: 5,
cancelled: 130,
});
});

Expand Down
142 changes: 142 additions & 0 deletions tests/package-metadata.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { basename, dirname, join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { repositoryRoot } from './helpers/index.js';

const CLI_PACKAGE_NAME = '@diginodes/stellarforge-cli';

// Documented support matrix (docs/guides/installation.md,
// docs/reference/platform-support.md). The CLI ships a bounded range; generated
// Node projects only pin the floor, which must stay inside that range.
const CLI_NODE_ENGINE = '>=22.13.0 <25';
const TEMPLATE_NODE_ENGINE = '>=22.13.0';

// Templates that ship a package.json. smart-contract is Rust-only and has no
// manifest. The scripts block is the only intentional per-template variation;
// every other field is covered by the common policy asserted below.
const NODE_TEMPLATES: readonly {
id: string;
scripts: Record<string, string>;
}[] = [
{
id: 'basic-app',
scripts: {
start: 'node src/index.js',
check: 'node --check src/index.js && node --check src/network.js',
test: 'node --test',
},
},
{
id: 'api-service',
scripts: {
start: 'node src/start.js',
check:
'node --check src/config.js && node --check src/stellar-client.js && node --check src/server.js && node --check src/start.js',
test: 'node --test test/*.test.js',
},
},
{
id: 'full-stack',
scripts: {
check:
'node --check frontend/src/app.js && node --check backend/src/server.js && node --check backend/src/start.js',
test: 'node --test frontend/test/app.test.js backend/test/server.test.js',
'start:backend': 'node backend/src/start.js',
},
},
];

function readManifest(path: string): Record<string, unknown> {
return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;
}

// Project-local files a script executes, e.g. the paths passed to `node --check`
// or `node --test`. A bare `node --test` (auto-discovery) yields nothing.
function referencedFiles(script: string): string[] {
return script.split(/\s+/).filter((token) => token.endsWith('.js'));
}

// Resolves a script reference against the template tree. Plain paths must exist
// verbatim; glob references (e.g. `test/*.test.js`) must match at least one file.
function resolvesToFile(root: string, reference: string): boolean {
const directory = join(root, dirname(reference));

if (!existsSync(directory)) {
return false;
}

const pattern = new RegExp(
`^${basename(reference)
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*')}$`,
);

return readdirSync(directory).some((name) => pattern.test(name));
}

describe('package metadata policy', () => {
describe('CLI manifest', () => {
const cli = readManifest(join(repositoryRoot, 'package.json'));

it('publishes under the scoped package name', () => {
expect(cli.name).toBe(CLI_PACKAGE_NAME);
});

it('declares a concrete version, MIT license, and an explicit engine range', () => {
expect(cli.version).toMatch(/^\d+\.\d+\.\d+$/);
expect(cli.license).toBe('MIT');
expect((cli.engines as { node?: string }).node).toBe(CLI_NODE_ENGINE);
});

it('is a public package', () => {
expect(cli.private).toBe(false);
});

it('keeps the declared engine range in sync with the documented matrix', () => {
const installation = readFileSync(
join(repositoryRoot, 'docs', 'guides', 'installation.md'),
'utf8',
);

expect(installation).toContain(CLI_NODE_ENGINE);
});
});

describe.each(NODE_TEMPLATES)('$id template', ({ id, scripts }) => {
const templateRoot = join(repositoryRoot, 'templates', id);
const manifest = readManifest(join(templateRoot, 'package.json'));

it('stays parameterised by the project name instead of the CLI package', () => {
expect(manifest.name).toBe('{{projectName}}');
expect(JSON.stringify(manifest)).not.toContain(CLI_PACKAGE_NAME);
});

it('declares a concrete version and the private flag, never the CLI publish flag', () => {
expect(manifest.version).toBe('0.1.0');
expect(manifest.private).toBe(true);
});

// Explicit exception: generated projects ship no license field.
it('ships no license field', () => {
expect(manifest.license).toBeUndefined();
});

it('pins the documented engine floor inside the CLI range', () => {
expect(manifest.engines).toEqual({ node: TEMPLATE_NODE_ENGINE });
expect(CLI_NODE_ENGINE).toContain(TEMPLATE_NODE_ENGINE);
});

it('declares only scripts that resolve to bundled template files', () => {
expect(manifest.scripts).toEqual(scripts);

for (const command of Object.values(scripts)) {
for (const file of referencedFiles(command)) {
expect(
resolvesToFile(templateRoot, file),
`${id}: missing ${file}`,
).toBe(true);
}
}
});
});
});
Loading