/* eslint-disable no-console */
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import path from 'node:path';
const ROCKET_CONFIG_PATH = 'rocket-config.js';
const INDEX_PAGE_PATH = 'docs/pages/index.rocket.md';
const SHARED_DATA_PATH = 'docs/pages/sharedData.js';
const THEME_CSS_PATH = 'public/rocket-theme.css';
const DOCS_PAGE_PATH = 'docs/pages/docs.rocket.md';
const JAVASCRIPT_DEMO_PAGE_PATH = 'docs/pages/javascript-demo.rocket.md';
const REQUEST_DEMO_PAGE_PATH = 'docs/pages/request-demo.rocket.md';
const SITE_STATUS_PAGE_PATH = 'docs/pages/site-status.rocket.js';
const ROCKET_AGENT_SKILL_PATH = '.agents/skills/rocket/SKILL.md';
const EXISTING_ROCKET_PAGE_NOISE_THRESHOLD = 3;
const STARTER_PAGE_FILES = [
SHARED_DATA_PATH,
THEME_CSS_PATH,
INDEX_PAGE_PATH,
DOCS_PAGE_PATH,
JAVASCRIPT_DEMO_PAGE_PATH,
REQUEST_DEMO_PAGE_PATH,
SITE_STATUS_PAGE_PATH,
];
const rocketConfigSource = `/** @type {import('@rocket/js/types.js').RocketConfig} */
export default {
includeGlobs: ['docs/pages/**/*.rocket.{md,js}', 'src/**/*.rocket.{md,js}'],
};
`;
const sharedDataSource = `import { resolve } from '@rocket/js/resolve.js';
const themeStylesheets = ['/rocket-theme.css'];
export const headerData = {
logo: [
resolve('@rocket/js/docs/assets/rocket-logo-light.svg', import.meta),
resolve('@rocket/js/docs/assets/rocket-text-no-logo.svg', import.meta),
],
homeLink: '/',
navLinks: [
{ text: 'Docs', href: '/docs' },
{ text: 'Demos', href: '/javascript-demo' },
],
socials: [],
};
/** @type {import('@rocket/js/types.js').FooterSection[]} */
export const footerData = [];
export const heroData = {
headerData,
footerData,
stylesheets: themeStylesheets,
heroMainData: {
logoNoText: resolve('@rocket/js/docs/assets/rocket-logo-light.svg', import.meta),
eyebrow: 'ROCKET STARTER',
title: 'Rocket Site',
body: 'A static documentation site built with Rocket Pages and Atlas layouts.',
documentationLink: '/docs',
documentationText: 'Read the docs',
setupLink: '/javascript-demo',
setupText: 'View demos',
installLabel: 'Build',
installCommand: 'npm run build',
},
whyRocketData: [
{
icon: 'file-earmark-text',
title: 'Plain Pages',
description: 'Author durable content in Markdown and keep routes explicit.',
},
{
icon: 'play-btn',
title: 'Live Demos',
description: 'Use JavaScript Demos for browser examples with standalone URLs.',
},
{
icon: 'arrow-left-right',
title: 'Request Demos',
description: 'Show concrete same-site responses without leaving the docs.',
},
],
quickStartData: {
title: 'Quick start',
subtitle: 'From this project:',
command: ['npm start', 'npm run build'],
description: 'Edit docs/pages, then run the build before publishing.',
},
workflowData: {
title: 'Starter workflow',
steps: [
{
icon: 'pencil-square',
title: 'Edit Pages',
description: 'Update the Markdown and JavaScript Pages under docs/pages.',
},
{
icon: 'terminal',
title: 'Build',
description: 'Run npm run build and fix any errors before publishing.',
},
],
},
};
export const docData = {
headerData,
footerData,
stylesheets: themeStylesheets,
navigationIconServerBudget: 35,
};
`;
const themeCssSource = `:root {
--rocket-theme-primary: #e10d14;
--rocket-theme-primary-dark: #b90f12;
--rocket-theme-link: #0366d6;
}
.atlas-page,
.atlas-header,
.atlas-navigation,
.atlas-toc,
.home-main,
rocket-header {
--primary-color: var(--rocket-theme-primary);
--primary-color-dark: var(--rocket-theme-primary-dark);
--link-color: var(--rocket-theme-link);
}
`;
const indexPageSource = `\`\`\`js server
export const config = {
path: '/',
metadata: {
title: 'Rocket Site',
description: 'Documentation built with Rocket.',
},
menu: {
iconName: 'house',
order: 0,
},
};
import { atlasHeroLayout, atlasHeroComponents } from '@rocket/js/layouts/atlasHero.js';
import { heroData } from './sharedData.js';
export const components = atlasHeroComponents;
export const layout = pageData => atlasHeroLayout(pageData, heroData);
\`\`\`
# Rocket Site
This starter is rendered with Rocket's Atlas hero layout.
## Next steps
- Edit this Page in \`docs/pages/index.rocket.md\`.
- Edit the shared Atlas data in \`docs/pages/sharedData.js\`.
- Add general documentation Pages under \`docs/pages\` with the Atlas docs layout.
- Add component reference Pages next to the components they document under \`src\`.
- Run \`npm run build\` to verify the site.
`;
const docsPageSource = `\`\`\`js server
export const config = {
path: '/docs',
metadata: {
title: 'Docs',
description: 'A first Atlas docs Page generated by rocket init.',
},
menu: {
iconName: 'book',
order: 10,
},
};
import { atlasDocLayout, atlasDocComponents } from '@rocket/js/layouts/atlasDoc.js';
import { docData } from './sharedData.js';
export const components = atlasDocComponents;
export const layout = pageData => atlasDocLayout(pageData, docData);
\`\`\`
# Docs
This Page uses Rocket's package-provided Atlas docs layout.
## Authoring Pages
Every Page owns its URL with \`config.path\`. General documentation Pages belong under
\`docs/pages\`, and component reference Pages can live next to the source files they document.
## Navigation Icons
Atlas docs navigation reads \`menu.iconName\` from Page config. Use Bootstrap Icon names for Pages
that appear in the left navigation.
`;
const javascriptDemoPageSource = `\`\`\`js server
export const config = {
path: '/javascript-demo',
metadata: {
title: 'JavaScript Demo',
description: 'A starter JavaScript Demo with a generated Standalone Demo URL.',
},
menu: {
iconName: 'window',
order: 20,
},
};
import { atlasDocLayout, atlasDocComponents } from '@rocket/js/layouts/atlasDoc.js';
import { docData } from './sharedData.js';
export const components = atlasDocComponents;
export const layout = pageData => atlasDocLayout(pageData, docData);
\`\`\`
# JavaScript Demo
Use a \`js demo\` block for browser-rendered examples. Rocket also generates a Standalone Demo URL
at \`/javascript-demo/_demo/starterButton/\`.
\`\`\`js demo label="docs/pages/javascript-demo.rocket.md"
import { html } from 'lit';
export const starterButton = () => html\`\`;
\`\`\`
`;
const requestDemoPageSource = `\`\`\`js server
export const config = {
path: '/request-demo',
metadata: {
title: 'Request Demo',
description: 'A starter Request Demo pointed at a concrete static JSON Page.',
},
menu: {
iconName: 'arrow-left-right',
order: 30,
},
};
import { atlasDocLayout, atlasDocComponents } from '@rocket/js/layouts/atlasDoc.js';
import { docData } from './sharedData.js';
export const components = atlasDocComponents;
export const layout = pageData => atlasDocLayout(pageData, docData);
\`\`\`
# Request Demo
Use a Request Demo when readers need to inspect a same-site \`GET\` response. Static Request Demo
examples should point at concrete paths and avoid query-dependent output.
\`\`\`js request-demo url="/api/site-status.json" label="docs/pages/site-status.rocket.js" height=220
export const config = {
path: '/api/site-status.json',
metadata: { title: 'Site Status' },
menu: false,
};
export default function siteStatusPage() {
return {
status: 'ready',
generatedBy: 'Rocket',
pages: ['/docs', '/javascript-demo', '/request-demo'],
};
}
\`\`\`
`;
const siteStatusPageSource = `export const config = {
path: '/api/site-status.json',
metadata: { title: 'Site Status' },
menu: false,
};
export default function siteStatusPage() {
return {
status: 'ready',
generatedBy: 'Rocket',
pages: ['/docs', '/javascript-demo', '/request-demo'],
};
}
`;
const STARTER_PAGE_SOURCES = new Map([
[SHARED_DATA_PATH, sharedDataSource],
[THEME_CSS_PATH, themeCssSource],
[INDEX_PAGE_PATH, indexPageSource],
[DOCS_PAGE_PATH, docsPageSource],
[JAVASCRIPT_DEMO_PAGE_PATH, javascriptDemoPageSource],
[REQUEST_DEMO_PAGE_PATH, requestDemoPageSource],
[SITE_STATUS_PAGE_PATH, siteStatusPageSource],
]);
const rocketAgentSkillSource = `---
name: rocket
description: Use when editing Rocket Pages, config, layouts, component reference Pages, or build behavior in this project.
---
# Rocket
## Rules
- Read \`rocket-config.js\` first; Page discovery follows \`includeGlobs\`.
- Every Page owns its URL through \`config.path\`; put general docs in \`docs/pages\` and component docs next to the component.
- Prefer Markdown for durable content; use JavaScript Pages for request-time or programmatic output.
- Prefer interactive examples for component and behavior docs; use \`js demo\` when readers benefit from trying the UI.
- Prefer Atlas docs layouts: \`atlasDocLayout\` for docs, \`atlasHeroLayout\` for a standalone docs home, with matching \`components\` exports.
- Markdown using Rocket custom elements needs a \`components\` export; use Atlas component maps or \`rocketDemoComponents\`.
- Add \`menu.iconName\` to Atlas docs navigation Pages so the left navigation has icons.
- Direct layout re-exports are supported when no local wrapper function is needed.
- For Atlas theming, use shared layout data with \`stylesheets\` and centralized CSS variables instead of per-Page style injection.
- To add a general Page, create \`docs/pages/name.rocket.md\`, set \`config.path\`, \`metadata\`, \`menu.iconName\`, and use the shared docs layout.
- Custom layouts rendering \`rocket-icon\` need \`addBootstrapIconLibrary(pageData)\` before \`document()\`.
- Static JavaScript Pages render once per concrete path; query/header/cookie/live-data output needs \`render: 'server'\`.
- Static Request Demos should target concrete non-query URLs.
- After adding a \`js demo\`, verify the parent Page and Standalone Demo URL \`/page/_demo/demoName/\`.
- If \`rocket init\` fails because package.json has \`"type": "commonjs"\`, change it to \`"type": "module"\` or rerun \`npx rocket init --yes\`.
- If dev server watchers fail with \`EMFILE\`, run \`npm start -- --no-watch --no-open\` and use \`Ctrl+R\` for manual restarts.
- When smoke-testing Pages with curl, send \`Accept: text/html\`: \`curl -H 'Accept: text/html' http://localhost:8888/path\`.
- Keep \`npm run build\` passing; record Rocket package issues separately from local workarounds.
`;
export class RocketInit {
/**
* @param {import('commander').Command} program
*/
async setupCommand(program) {
program
.command('init')
.description('create a Rocket docs starter')
.option('-y, --yes', 'update an explicit CommonJS package.json type to module')
.action(options => {
const result = this.init({ yes: options.yes });
reportInitResult(result);
});
}
/**
* @param {RocketInitOptions} [options]
* @returns {RocketInitResult}
*/
init(options = {}) {
const packageJsonUpdate = preparePackageJsonUpdate('package.json', options);
/** @type {RocketInitResult} */
const result = {
created: [],
skipped: [],
packageJson: packageJsonUpdate?.summary,
missingRocketDependency: Boolean(packageJsonUpdate?.missingRocketDependency),
nextSteps: packageJsonUpdate?.nextSteps || ['npx rocket start', 'npx rocket build'],
};
if (packageJsonUpdate?.changed) {
writeJsonFile('package.json', packageJsonUpdate.packageJson);
}
const shouldCreateStarterPages =
existingRocketPageFileCount(process.cwd()) < EXISTING_ROCKET_PAGE_NOISE_THRESHOLD;
writeFileIfMissing(ROCKET_CONFIG_PATH, rocketConfigSource, result);
if (shouldCreateStarterPages) {
for (const filePath of STARTER_PAGE_FILES) {
writeFileIfMissing(filePath, STARTER_PAGE_SOURCES.get(filePath) || '', result);
}
}
writeFileIfMissing(ROCKET_AGENT_SKILL_PATH, rocketAgentSkillSource, result);
return result;
}
}
/**
* @typedef {{
* yes?: boolean;
* }} RocketInitOptions
*/
/**
* @typedef {{
* created: string[];
* skipped: string[];
* packageJson?: {
* path: string;
* updated: string[];
* skipped: string[];
* };
* missingRocketDependency: boolean;
* nextSteps: string[];
* }} RocketInitResult
*/
/**
* @param {string} filePath
* @param {RocketInitOptions} options
* @returns {{
* changed: boolean;
* packageJson: Record;
* summary: NonNullable;
* missingRocketDependency: boolean;
* nextSteps: string[];
* } | undefined}
*/
function preparePackageJsonUpdate(filePath, options) {
if (!existsSync(filePath)) {
return undefined;
}
if (!statSync(filePath).isFile()) {
throw new Error('package.json exists but is not a file');
}
const packageJson = JSON.parse(readFileSync(filePath, 'utf8'));
if (!isPlainRecord(packageJson)) {
throw new Error('package.json must contain a JSON object');
}
/** @type {string[]} */
const updated = [];
/** @type {string[]} */
const skipped = [];
if (packageJson.type === 'commonjs') {
if (!options.yes) {
throw commonJsProjectError();
}
packageJson.type = 'module';
updated.push('type');
} else if (!hasOwn(packageJson, 'type')) {
packageJson.type = 'module';
updated.push('type');
} else if (packageJson.type === 'module') {
skipped.push('type');
}
if (!hasOwn(packageJson, 'scripts')) {
packageJson.scripts = {};
updated.push('scripts');
}
if (isPlainRecord(packageJson.scripts)) {
addRocketScript(packageJson.scripts, {
genericName: 'start',
fallbackName: 'rocket:start',
command: 'rocket start',
updated,
skipped,
});
addRocketScript(packageJson.scripts, {
genericName: 'build',
fallbackName: 'rocket:build',
command: 'rocket build',
updated,
skipped,
});
} else {
skipped.push('scripts');
}
return {
changed: updated.length > 0,
packageJson,
summary: {
path: filePath,
updated,
skipped,
},
missingRocketDependency: !hasPackageDependency(packageJson, '@rocket/js'),
nextSteps: rocketNextSteps(packageJson),
};
}
function commonJsProjectError() {
return new Error(
`Rocket init expects an ESM project. Found package.json type "commonjs".\n\n` +
`Update package.json before running rocket init:\n` +
`- "type": "commonjs",\n` +
`+ "type": "module",\n\n` +
`Then rerun:\n` +
` npx rocket init\n\n` +
`Or let Rocket apply that package.json change:\n` +
` npx rocket init --yes`,
);
}
/**
* @param {Record} scripts
* @param {{
* genericName: string;
* fallbackName: string;
* command: string;
* updated: string[];
* skipped: string[];
* }} options
*/
function addRocketScript(scripts, { genericName, fallbackName, command, updated, skipped }) {
if (!hasOwn(scripts, genericName)) {
scripts[genericName] = command;
updated.push(`scripts.${genericName}`);
return;
}
if (scriptRunsRocketCommand(scripts[genericName], genericName)) {
skipped.push(`scripts.${genericName}`);
return;
}
if (!hasOwn(scripts, fallbackName)) {
scripts[fallbackName] = command;
updated.push(`scripts.${fallbackName}`);
return;
}
skipped.push(`scripts.${genericName}`);
skipped.push(`scripts.${fallbackName}`);
}
/**
* @param {Record} packageJson
* @param {string} dependencyName
* @returns {boolean}
*/
function hasPackageDependency(packageJson, dependencyName) {
return ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].some(
field => isPlainRecord(packageJson[field]) && hasOwn(packageJson[field], dependencyName),
);
}
/**
* @param {Record} packageJson
* @returns {string[]}
*/
function rocketNextSteps(packageJson) {
if (!isPlainRecord(packageJson.scripts)) {
return ['npx rocket start', 'npx rocket build'];
}
return [
npmScriptCommand(packageJson.scripts, 'start', 'rocket:start'),
npmScriptCommand(packageJson.scripts, 'build', 'rocket:build'),
];
}
/**
* @param {Record} scripts
* @param {string} genericName
* @param {string} fallbackName
*/
function npmScriptCommand(scripts, genericName, fallbackName) {
if (scriptRunsRocketCommand(scripts[genericName], genericName)) {
return genericName === 'start' ? 'npm start' : `npm run ${genericName}`;
}
if (scriptRunsRocketCommand(scripts[fallbackName], genericName)) {
return `npm run ${fallbackName}`;
}
return `npx rocket ${genericName}`;
}
/**
* @param {unknown} script
* @param {string} commandName
* @returns {boolean}
*/
function scriptRunsRocketCommand(script, commandName) {
if (typeof script !== 'string') {
return false;
}
const shellBoundary = '[\\s"\\\'`;&|()]';
return new RegExp(
`(^|${shellBoundary})(?:npx\\s+)?rocket\\s+${commandName}(?=$|${shellBoundary})`,
).test(script);
}
/**
* @param {string} directory
* @returns {number}
*/
function existingRocketPageFileCount(directory) {
if (!existsSync(directory)) {
return 0;
}
return countRocketPageFiles(directory, { count: 0 });
}
/**
* @param {string} directory
* @param {{ count: number }} state
* @returns {number}
*/
function countRocketPageFiles(directory, state) {
if (state.count >= EXISTING_ROCKET_PAGE_NOISE_THRESHOLD) {
return state.count;
}
for (const entry of readdirSync(directory, { withFileTypes: true })) {
if (shouldIgnoreRocketPageScanEntry(entry.name)) {
continue;
}
const entryPath = path.join(directory, entry.name);
if (entry.isDirectory()) {
countRocketPageFiles(entryPath, state);
} else if (isRocketPageFile(entry.name)) {
state.count += 1;
}
if (state.count >= EXISTING_ROCKET_PAGE_NOISE_THRESHOLD) {
return state.count;
}
}
return state.count;
}
/**
* @param {string} name
* @returns {boolean}
*/
function shouldIgnoreRocketPageScanEntry(name) {
return ['.git', '.netlify', 'coverage', 'dist', 'node_modules', 'temp'].includes(name);
}
/**
* @param {string} fileName
* @returns {boolean}
*/
function isRocketPageFile(fileName) {
return fileName.endsWith('.rocket.md') || fileName.endsWith('.rocket.js');
}
/**
* @param {string} filePath
* @param {string} contents
* @param {RocketInitResult} result
*/
function writeFileIfMissing(filePath, contents, result) {
if (existsSync(filePath)) {
result.skipped.push(filePath);
return;
}
mkdirSync(path.dirname(filePath), { recursive: true });
writeFileSync(filePath, contents);
result.created.push(filePath);
}
/**
* @param {string} filePath
* @param {Record} value
*/
function writeJsonFile(filePath, value) {
writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`);
}
/**
* @param {RocketInitResult} result
*/
function reportInitResult(result) {
for (const filePath of result.created) {
console.log(`Created ${filePath}`);
}
for (const filePath of result.skipped) {
console.log(`Skipped ${filePath} (already exists)`);
}
if (result.packageJson?.updated.length) {
console.log(`Updated ${result.packageJson.path}: ${result.packageJson.updated.join(', ')}`);
} else if (result.packageJson) {
console.log(`Skipped ${result.packageJson.path} (already configured)`);
}
if (result.missingRocketDependency) {
console.log('Note: package.json does not list @rocket/js. Add it with: npm install @rocket/js');
}
console.log('');
console.log('Next steps:');
for (const step of result.nextSteps) {
console.log(` ${step}`);
}
}
/**
* @param {unknown} value
* @returns {value is Record}
*/
function isPlainRecord(value) {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
/**
* @param {Record} record
* @param {string} field
*/
function hasOwn(record, field) {
return Object.prototype.hasOwnProperty.call(record, field);
}