@opentf/create-afw 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # @opentf/create-afw
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Create an [AFW](https://afw.opentechf.org) app on **Vite and Node**:
4
+
5
+ ```sh
6
+ npm create @opentf/afw my-app
7
+ ```
8
+
9
+ Answer the prompts, or pass the choices:
10
+
11
+ ```sh
12
+ npm create @opentf/afw my-app -- --template=fullstack --language=ts
13
+ ```
14
+
15
+ | Option | Values |
16
+ | --- | --- |
17
+ | `--template` | `spa` (default), `fullstack`, `ssr`, `ssg` |
18
+ | `--language` | `ts` (default), `js` (`--ts` / `--js` also work) |
19
+ | `--yes`, `-y` | Use the defaults instead of asking |
20
+
21
+ | Template | What you get |
22
+ | --- | --- |
23
+ | `spa` | Single-page app, rendered in the browser |
24
+ | `fullstack` | SPA plus API routes, middleware and loaders on a Node server |
25
+ | `ssr` | Server-rendered pages on a Node server, hydrated in the browser |
26
+ | `ssg` | Every page prerendered to static HTML at build time |
27
+
28
+ Every project comes with `dev`, `build` and `test` (Vitest) scripts, and either
29
+ `start` (the built Node server) or `preview`. TypeScript projects add `typecheck`.
30
+
31
+ For the esdev + ES-Runtime workflow, use `esdev create` instead.
32
+
33
+ ## License
34
+
35
+ MIT
package/index.js ADDED
@@ -0,0 +1,133 @@
1
+ #!/usr/bin/env node
2
+ // `npm create @opentf/afw` — scaffold an AFW app on Vite and Node.
3
+ //
4
+ // npm create @opentf/afw my-app
5
+ // npm create @opentf/afw my-app -- --template=fullstack --language=ts
6
+ //
7
+ // For the esdev + ES-Runtime workflow, use `esdev create` instead.
8
+
9
+ import { access, mkdir, readdir, writeFile } from "node:fs/promises";
10
+ import { basename, dirname, join, relative, resolve } from "node:path";
11
+ import { createInterface } from "node:readline/promises";
12
+ import { stdin, stdout } from "node:process";
13
+
14
+ import { TEMPLATES, projectFiles } from "./templates.js";
15
+ import { afwVersions } from "./versions.js";
16
+
17
+ const HELP = `Create an AFW app on Vite and Node.
18
+
19
+ Usage: npm create @opentf/afw [directory] -- [options]
20
+
21
+ Options:
22
+ --template=<name> ${Object.keys(TEMPLATES).join(" | ")} (default: spa)
23
+ ${Object.entries(TEMPLATES).map(([n, d]) => ` ${n.padEnd(10)} ${d}`).join("\n")}
24
+ --language=<lang> js | ts (default: ts)
25
+ --yes, -y Use the defaults instead of asking
26
+ --help, -h Show this help
27
+
28
+ For the esdev + ES-Runtime workflow, use \`esdev create\`.`;
29
+
30
+ const VALID_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
31
+
32
+ export function parseArgs(argv) {
33
+ const options = { directory: undefined, template: undefined, language: undefined, yes: false, help: false };
34
+ for (const arg of argv) {
35
+ if (arg === "--help" || arg === "-h") options.help = true;
36
+ else if (arg === "--yes" || arg === "-y") options.yes = true;
37
+ else if (arg.startsWith("--template=")) options.template = arg.slice(11);
38
+ else if (arg.startsWith("--language=")) options.language = arg.slice(11);
39
+ else if (arg === "--ts" || arg === "--typescript") options.language = "ts";
40
+ else if (arg === "--js") options.language = "js";
41
+ else if (arg.startsWith("-")) throw new Error(`Unknown option: ${arg}`);
42
+ else if (options.directory === undefined) options.directory = arg;
43
+ else throw new Error(`Unexpected argument: ${arg}`);
44
+ }
45
+ if (options.template !== undefined && !TEMPLATES[options.template]) {
46
+ throw new Error(`Unknown template "${options.template}". Choose one of: ${Object.keys(TEMPLATES).join(", ")}`);
47
+ }
48
+ if (options.language !== undefined && !["js", "ts"].includes(options.language)) {
49
+ throw new Error(`Unknown language "${options.language}". Choose js or ts.`);
50
+ }
51
+ return options;
52
+ }
53
+
54
+ /** The package manager that ran us (`npm create`, `pnpm create`, …). */
55
+ export function packageManager(userAgent = process.env.npm_config_user_agent ?? "") {
56
+ const name = userAgent.split("/")[0];
57
+ return ["pnpm", "yarn", "bun"].includes(name) ? name : "npm";
58
+ }
59
+
60
+ async function isEmptyDir(dir) {
61
+ try {
62
+ return (await readdir(dir)).filter((f) => f !== ".git").length === 0;
63
+ } catch {
64
+ return true;
65
+ }
66
+ }
67
+
68
+ async function ask(rl, question, fallback) {
69
+ const answer = (await rl.question(`${question} (${fallback}): `)).trim();
70
+ return answer || fallback;
71
+ }
72
+
73
+ async function choose(rl, question, choices, fallback) {
74
+ const keys = Object.keys(choices);
75
+ stdout.write(`${question}\n${keys.map((k, i) => ` ${i + 1}. ${k.padEnd(10)} ${choices[k]}`).join("\n")}\n`);
76
+ for (;;) {
77
+ const answer = (await rl.question(`Choose 1-${keys.length} (${fallback}): `)).trim();
78
+ if (!answer) return fallback;
79
+ const picked = keys[Number(answer) - 1] ?? (choices[answer] ? answer : undefined);
80
+ if (picked) return picked;
81
+ }
82
+ }
83
+
84
+ /** Scaffold a project. Returns the directory and the files written. */
85
+ export async function create({ directory, template = "spa", language = "ts", cwd = process.cwd() }) {
86
+ const target = resolve(cwd, directory);
87
+ const name = basename(target);
88
+ if (!VALID_NAME.test(name)) throw new Error(`"${name}" is not a valid package name: use lowercase letters, digits, "-", "_" or ".".`);
89
+ if (!(await isEmptyDir(target))) throw new Error(`${target} is not empty.`);
90
+ const files = projectFiles({ name, template, typescript: language === "ts", versions: await afwVersions() });
91
+ for (const [path, contents] of Object.entries(files)) {
92
+ const file = join(target, path);
93
+ await mkdir(dirname(file), { recursive: true });
94
+ await writeFile(file, contents);
95
+ }
96
+ return { target, files: Object.keys(files) };
97
+ }
98
+
99
+ async function main(argv) {
100
+ const options = parseArgs(argv);
101
+ if (options.help) {
102
+ console.log(HELP);
103
+ return;
104
+ }
105
+ const interactive = stdin.isTTY && stdout.isTTY && !options.yes;
106
+ if (interactive && (!options.directory || !options.template || !options.language)) {
107
+ const rl = createInterface({ input: stdin, output: stdout });
108
+ try {
109
+ options.directory ??= await ask(rl, "Project name", "afw-app");
110
+ options.template ??= await choose(rl, "Template:", TEMPLATES, "spa");
111
+ options.language ??= await choose(rl, "Language:", { ts: "TypeScript", js: "JavaScript" }, "ts");
112
+ } finally {
113
+ rl.close();
114
+ }
115
+ }
116
+ options.directory ??= "afw-app";
117
+ const { target } = await create(options);
118
+ const pm = packageManager();
119
+ const run = (script) => (pm === "npm" ? `npm run ${script}` : `${pm} ${script}`);
120
+ const dir = relative(process.cwd(), target) || ".";
121
+ console.log(`\nCreated ${options.template ?? "spa"} app in ${dir}\n\nNext:\n${dir === "." ? "" : ` cd ${dir}\n`} ${pm} install\n ${run("dev")}\n`);
122
+ }
123
+
124
+ // Run as a CLI (not when imported by the tests).
125
+ const invoked = process.argv[1] && (await access(process.argv[1]).then(() => true, () => false))
126
+ ? (await import("node:fs")).realpathSync(process.argv[1]) === (await import("node:url")).fileURLToPath(import.meta.url)
127
+ : false;
128
+ if (invoked) {
129
+ main(process.argv.slice(2)).catch((error) => {
130
+ console.error(`✗ ${error.message}`);
131
+ process.exit(1);
132
+ });
133
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@opentf/create-afw",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Create an AFW app on Vite and Node: npm create @opentf/afw.",
5
+ "type": "module",
6
+ "bin": {
7
+ "create-afw": "./index.js"
8
+ },
9
+ "scripts": {
10
+ "build": "cp ../../LICENSE LICENSE && node scripts/write-versions.mjs"
11
+ },
12
+ "exports": {
13
+ ".": "./index.js"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "templates.js",
18
+ "versions.js",
19
+ "versions.json"
20
+ ],
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "devDependencies": {
25
+ "@opentf/afw": "0.34.0",
26
+ "@opentf/afw-test": "1.29.0",
27
+ "@opentf/vite-plugin-afw": "0.1.0",
28
+ "happy-dom": "21.0.4",
29
+ "vite": "8.3.5",
30
+ "vitest": "5.0.5"
31
+ },
32
+ "keywords": [
33
+ "afw",
34
+ "opentf",
35
+ "create",
36
+ "scaffold",
37
+ "vite",
38
+ "starter"
39
+ ],
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/Open-Tech-Foundation/afw.git",
43
+ "directory": "packages/create-afw"
44
+ },
45
+ "homepage": "https://afw.opentechf.org/docs",
46
+ "bugs": "https://github.com/Open-Tech-Foundation/afw/issues",
47
+ "license": "MIT",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }
package/templates.js ADDED
@@ -0,0 +1,256 @@
1
+ // The Vite + Node project templates. Each template is generated from one source for
2
+ // both JavaScript and TypeScript, so the two never drift apart.
3
+
4
+ export const TEMPLATES = {
5
+ spa: "Single-page app, rendered in the browser",
6
+ fullstack: "SPA plus API routes, middleware and loaders on a Node server",
7
+ ssr: "Server-rendered pages on a Node server, hydrated in the browser",
8
+ ssg: "Every page prerendered to static HTML at build time",
9
+ };
10
+
11
+ // The third-party tools a new project starts on. AFW's own packages take the
12
+ // versions this scaffolder was released with (versions.js).
13
+ export const TOOL_VERSIONS = {
14
+ vite: "^8.3.5",
15
+ vitest: "^5.0.5",
16
+ "happy-dom": "^21.0.4",
17
+ typescript: "^6.0.3",
18
+ };
19
+
20
+ const MODE = { spa: "spa", fullstack: "spa", ssr: "ssr", ssg: "ssg" };
21
+ const hasServer = (template) => template === "fullstack" || template === "ssr";
22
+
23
+ /**
24
+ * The files of a new project, as `{ relativePath: contents }`.
25
+ *
26
+ * @param {{ name: string, template: keyof TEMPLATES, typescript: boolean, versions: Record<string, string> }} options
27
+ */
28
+ export function projectFiles({ name, template, typescript, versions }) {
29
+ if (!TEMPLATES[template]) throw new Error(`Unknown template "${template}". Choose one of: ${Object.keys(TEMPLATES).join(", ")}`);
30
+ const ts = typescript;
31
+ const js = ts ? "ts" : "js";
32
+ const jsx = ts ? "tsx" : "jsx";
33
+ const server = hasServer(template);
34
+ const mode = MODE[template];
35
+ const files = {};
36
+
37
+ const scripts = { dev: "vite", build: "vite build" };
38
+ if (server) scripts.start = "node dist/server/index.js";
39
+ else scripts.preview = "vite preview";
40
+ scripts.test = "vitest run";
41
+ if (ts) scripts.typecheck = "tsc";
42
+ const devDependencies = {
43
+ "@opentf/afw-test": versions["@opentf/afw-test"],
44
+ "@opentf/vite-plugin-afw": versions["@opentf/vite-plugin-afw"],
45
+ "happy-dom": TOOL_VERSIONS["happy-dom"],
46
+ ...(ts ? { typescript: TOOL_VERSIONS.typescript } : {}),
47
+ vite: TOOL_VERSIONS.vite,
48
+ vitest: TOOL_VERSIONS.vitest,
49
+ };
50
+ files["package.json"] = json({
51
+ name, private: true, type: "module", scripts,
52
+ dependencies: { "@opentf/afw": versions["@opentf/afw"] },
53
+ devDependencies,
54
+ });
55
+
56
+ files[`vite.config.${js}`] = `import afw from "@opentf/vite-plugin-afw";
57
+ ${ts ? 'import { defineConfig } from "vitest/config";\n' : ""}
58
+ ${ts ? "export default defineConfig(" : "export default "}{
59
+ plugins: [afw({ mode: "${mode}"${mode === "ssg" ? ', baseUrl: "" /* your site URL, e.g. "https://example.com", enables sitemap.xml */' : ""} })],
60
+ test: {
61
+ environment: "happy-dom",
62
+ setupFiles: ["@opentf/afw-test/vitest"],
63
+ },
64
+ }${ts ? ")" : ""};
65
+ `;
66
+
67
+ if (ts) {
68
+ files["tsconfig.json"] = json({
69
+ compilerOptions: {
70
+ target: "ESNext",
71
+ module: "ESNext",
72
+ moduleResolution: "bundler",
73
+ lib: ["ESNext", "DOM", "DOM.Iterable"],
74
+ jsx: "preserve",
75
+ jsxImportSource: "@opentf/afw",
76
+ types: ["@opentf/vite-plugin-afw/client"],
77
+ strict: true,
78
+ noEmit: true,
79
+ isolatedModules: true,
80
+ skipLibCheck: true,
81
+ allowImportingTsExtensions: true,
82
+ },
83
+ include: ["app", "tests", "entry.ts", "vite.config.ts"],
84
+ });
85
+ }
86
+
87
+ files["index.html"] = `<!doctype html>
88
+ <html lang="en">
89
+ <head>
90
+ <meta charset="utf-8" />
91
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
92
+ <title>${escapeHtml(name)}</title>
93
+ <link rel="stylesheet" href="/app/global.css" />
94
+ </head>
95
+ <body>
96
+ <div id="app"></div>
97
+ <script type="module" src="/entry.${js}"></script>
98
+ </body>
99
+ </html>
100
+ `;
101
+
102
+ files[`entry.${js}`] = `import { mountApp } from "@opentf/afw";
103
+ import { guard, loaderRoutes, pages } from "@afw/routes";
104
+
105
+ mountApp({ pages, guard, loaders: loaderRoutes, target: document.getElementById("app")${ts ? "!" : ""} });
106
+ `;
107
+
108
+ files["app/global.css"] = `:root {
109
+ font-family: system-ui, sans-serif;
110
+ color-scheme: light dark;
111
+ }
112
+
113
+ body {
114
+ margin: 0 auto;
115
+ max-width: 48rem;
116
+ padding: 2rem 1rem;
117
+ }
118
+
119
+ nav {
120
+ display: flex;
121
+ gap: 1rem;
122
+ margin-bottom: 2rem;
123
+ }
124
+ `;
125
+
126
+ const navLinks = [["/", "Home"], ["/about", "About"], ...(server ? [["/todos", "Todos"]] : [])];
127
+ files[`app/layout.${jsx}`] = `import { Link } from "@opentf/afw";
128
+
129
+ export default function Layout({ children }${ts ? ": { children: unknown }" : ""}) {
130
+ return (
131
+ <>
132
+ <nav>
133
+ ${navLinks.map(([href, label]) => ` <Link href="${href}">${label}</Link>`).join("\n")}
134
+ </nav>
135
+ <main>{children}</main>
136
+ </>
137
+ );
138
+ }
139
+ `;
140
+
141
+ files[`app/page.${jsx}`] = `import Counter from "./Counter.${jsx}";
142
+
143
+ export const metadata = { title: "${escapeJs(name)}" };
144
+
145
+ export default function Home() {
146
+ return (
147
+ <section>
148
+ <h1>${escapeHtml(name)}</h1>
149
+ <p>Edit <code>app/page.${jsx}</code> and save: the page updates in place.</p>
150
+ <Counter start={0} />
151
+ </section>
152
+ );
153
+ }
154
+ `;
155
+
156
+ files[`app/Counter.${jsx}`] = `export default function Counter({ start = 0 }${ts ? ": { start?: number }" : ""}) {
157
+ let count = $state(start);
158
+ const doubled = $derived(count * 2);
159
+
160
+ return (
161
+ <p>
162
+ <button onclick={() => count++}>Count: {count}</button> Doubled: {doubled}
163
+ </p>
164
+ );
165
+ }
166
+ `;
167
+
168
+ files["app/about/page.md"] = `---
169
+ title: About
170
+ ---
171
+
172
+ # About
173
+
174
+ This page is Markdown. The AFW compiler turns it into a page like any other.
175
+ `;
176
+
177
+ if (server) {
178
+ files[`app/api/hello/route.${js}`] = `// GET /api/hello?name=… — API routes run on Node, so any npm package works here.
179
+ export function GET(request${ts ? ": Request" : ""}, { query, locals }${ts ? ": { query: Record<string, string>; locals: Record<string, unknown> }" : ""}) {
180
+ return Response.json({ message: \`Hello, \${query.name ?? "world"}!\`, requestId: locals.requestId });
181
+ }
182
+ `;
183
+ files[`app/_middleware.${js}`] = `// Runs for every request: pages, API routes and loader data alike.
184
+ export default async function middleware(request${ts ? ": Request" : ""}, context${ts ? ": { locals: Record<string, unknown> }" : ""}, next${ts ? ": () => Promise<Response>" : ""}) {
185
+ context.locals.requestId = crypto.randomUUID();
186
+ const response = await next();
187
+ response.headers.set("x-request-id", String(context.locals.requestId));
188
+ return response;
189
+ }
190
+ `;
191
+ files[`app/todos/loader.${js}`] = `// Loaders run on the server and feed their page through \`router.data\`.
192
+ const todos = ["Try the dev server", "Add an API route", "Deploy with npm start"];
193
+
194
+ export default async function loader() {
195
+ return { todos };
196
+ }
197
+ `;
198
+ files[`app/todos/page.${jsx}`] = `import { router } from "@opentf/afw";
199
+
200
+ export const metadata = { title: "Todos" };
201
+
202
+ export default function Todos() {
203
+ return (
204
+ <section>
205
+ <h1>Todos</h1>
206
+ <ul>
207
+ {(${ts ? "(router.data as { todos?: string[] } | undefined)" : "router.data"}?.todos ?? []).map((todo${ts ? ": string" : ""}) => <li>{todo}</li>)}
208
+ </ul>
209
+ </section>
210
+ );
211
+ }
212
+ `;
213
+ }
214
+
215
+ files[`tests/Counter.test.${js}`] = `import { expect, test } from "vitest";
216
+ import { render, userEvent } from "@opentf/afw-test";
217
+ import Counter from "../app/Counter.${jsx}";
218
+
219
+ test("counts clicks", async () => {
220
+ const { getByRole, getByText } = render(Counter, { start: 1 });
221
+ await userEvent.setup().click(getByRole("button", { name: "Count: 1" }));
222
+ expect(getByRole("button").textContent).toBe("Count: 2");
223
+ expect(getByText(/Doubled: 4/)).toBeTruthy();
224
+ });
225
+ `;
226
+
227
+ files[".gitignore"] = "node_modules\ndist\n";
228
+
229
+ const run = (script) => `npm run ${script}`;
230
+ files["README.md"] = `# ${name}
231
+
232
+ An [AFW](https://afw.opentechf.org) app on Vite and Node (${TEMPLATES[template].toLowerCase()}).
233
+
234
+ | Command | What it does |
235
+ | --- | --- |
236
+ | \`${run("dev")}\` | Start the dev server |
237
+ | \`${run("build")}\` | Build for production |
238
+ | ${server ? `\`npm start\` | Run the built Node server (\`PORT\`, \`HOST\`)` : `\`${run("preview")}\` | Preview the production build`} |
239
+ | \`${run("test")}\` | Run the tests with Vitest |
240
+ ${ts ? `| \`${run("typecheck")}\` | Check types |\n` : ""}
241
+ Pages live in \`app/\`: \`app/about/page.md\` is served at \`/about\`.${server ? " API routes (`route." + js + "`), middleware (`_middleware." + js + "`) and loaders (`loader." + js + "`) run on Node." : ""}
242
+ `;
243
+ return files;
244
+ }
245
+
246
+ function json(value) {
247
+ return `${JSON.stringify(value, null, 2)}\n`;
248
+ }
249
+
250
+ function escapeHtml(text) {
251
+ return String(text).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
252
+ }
253
+
254
+ function escapeJs(text) {
255
+ return String(text).replace(/[\\"]/g, "\\$&");
256
+ }
package/versions.js ADDED
@@ -0,0 +1,20 @@
1
+ // The AFW package versions a new project depends on: the ones this scaffolder was
2
+ // released with (`versions.json`, written by `npm run build`), or — in the AFW
3
+ // repository itself — the workspace packages' current versions.
4
+
5
+ import { readFile } from "node:fs/promises";
6
+
7
+ export const AFW_PACKAGES = { "@opentf/afw": "afw", "@opentf/afw-test": "afw-test", "@opentf/vite-plugin-afw": "vite-plugin-afw" };
8
+
9
+ export async function afwVersions() {
10
+ try {
11
+ return JSON.parse(await readFile(new URL("./versions.json", import.meta.url), "utf8"));
12
+ } catch {
13
+ const versions = {};
14
+ for (const [name, folder] of Object.entries(AFW_PACKAGES)) {
15
+ const manifest = JSON.parse(await readFile(new URL(`../${folder}/package.json`, import.meta.url), "utf8"));
16
+ versions[name] = `^${manifest.version}`;
17
+ }
18
+ return versions;
19
+ }
20
+ }