@auis/cli 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 ADDED
@@ -0,0 +1,87 @@
1
+ # @auis/cli
2
+
3
+ The CLI for [**Auis**](https://github.com/gregoriombp/AuisDesign) — a code-native
4
+ design builder. One command, no clone, no config:
5
+
6
+ ```bash
7
+ npx @auis/cli my-product
8
+ ```
9
+
10
+ ```
11
+ auis 0.1.0
12
+ code-native design builder
13
+
14
+ ✓ Template main · tarball
15
+ ✓ Project my-product → my-product
16
+ ✓ Git initialized · first commit
17
+ ✓ Install npm · 41s
18
+
19
+ Ready.
20
+
21
+ cd my-product
22
+ npm run dev
23
+ → http://127.0.0.1:3000/auis
24
+
25
+ Then, in Claude Code / Codex / Cursor:
26
+ /auis-setup brand → tokens → voice
27
+ ```
28
+
29
+ ## What you get
30
+
31
+ A Next.js (App Router) + Tailwind v4 + shadcn/ui project where the design
32
+ system, the screens, the UX flows and the review process all live in the
33
+ codebase, and AI agents build against them under enforced rules:
34
+
35
+ - **Living styleguide** (`/auis/styleguide`) — tokens, foundations, components rendered from real code.
36
+ - **Review Mode** — visual comments on any screen become a local work queue agents resolve.
37
+ - **Edit Mode** — non-destructive visual edits that agents materialize into code.
38
+ - **UX Flows as code** (`/auis/ux-flow`) — navigable flow diagrams that are React pages.
39
+ - **State Mode** (`/auis/states`) — every registered screen in every state, side by side.
40
+ - **37 agent skills** — execution contracts for Claude Code, Codex and Cursor.
41
+
42
+ ## Usage
43
+
44
+ ```
45
+ npx @auis/cli [directory] [options]
46
+ npx @auis/cli new [directory] [options] same thing
47
+
48
+ -r, --ref <ref> branch, tag or commit of the template (default: main)
49
+ --pm <manager> npm | pnpm | yarn | bun (default: detected)
50
+ --no-install skip dependency installation
51
+ --no-git skip git init and the first commit
52
+ --force scaffold into a directory that is not empty
53
+ -y, --yes take the defaults, never prompt
54
+ -h, --help show usage
55
+ -v, --version print the CLI version
56
+ ```
57
+
58
+ Examples:
59
+
60
+ ```bash
61
+ npx @auis/cli my-product # new directory
62
+ npx @auis/cli . # current directory
63
+ npx @auis/cli my-product --pm pnpm --no-git
64
+ npx @auis/cli my-product --ref v1.0.0
65
+ ```
66
+
67
+ Requires **Node.js ≥ 20**. The template is fetched as a GitHub tarball (`tar`),
68
+ falling back to `git clone --depth 1`. The CLI itself has zero dependencies.
69
+
70
+ ## What the scaffold changes
71
+
72
+ Everything in the repository, minus the parts that only concern contributing to
73
+ Auis (`.github/ISSUE_TEMPLATE`, `PULL_REQUEST_TEMPLATE.md`, `CONTRIBUTING.md`,
74
+ `CODE_OF_CONDUCT.md`, the extraction/cleanup notes, and the `packages/`
75
+ directory this CLI lives in), plus:
76
+
77
+ - `package.json` renamed to your project, `0.1.0`, `private: true`, with an
78
+ `auis` field recording the template ref it came from;
79
+ - a project `README.md` in place of the Auis one;
80
+ - `.env.local` seeded from `.env.example`;
81
+ - `git init` and a first commit (unless `--no-git`);
82
+ - dependencies installed, which runs `skills:sync` and generates
83
+ `.claude/skills` + `.agents/skills` (unless `--no-install`).
84
+
85
+ `LICENSE` stays: Auis is MIT and the notice travels with the code.
86
+
87
+ MIT © Gregório Pinheiro
package/bin/auis.mjs ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "../src/cli.mjs";
3
+ import { fail, restoreCursorOnExit } from "../src/ui.mjs";
4
+
5
+ restoreCursorOnExit();
6
+
7
+ run(process.argv.slice(2))
8
+ .then((code) => {
9
+ process.exitCode = code ?? 0;
10
+ })
11
+ .catch((error) => {
12
+ fail(error?.stack ?? String(error));
13
+ process.exitCode = 1;
14
+ });
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@auis/cli",
3
+ "version": "0.1.0",
4
+ "description": "The Auis CLI — scaffold a code-native design builder: Next.js + Tailwind + shadcn/ui, with agent skills built in.",
5
+ "type": "module",
6
+ "bin": {
7
+ "auis": "bin/auis.mjs"
8
+ },
9
+ "exports": {
10
+ ".": "./src/cli.mjs",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "src",
16
+ "README.md"
17
+ ],
18
+ "engines": {
19
+ "node": ">=20"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "scripts": {
25
+ "test": "node --test test/*.test.mjs"
26
+ },
27
+ "keywords": [
28
+ "auis",
29
+ "design-system",
30
+ "design-builder",
31
+ "scaffold",
32
+ "starter",
33
+ "nextjs",
34
+ "shadcn-ui",
35
+ "tailwindcss",
36
+ "ai-agents",
37
+ "claude-code",
38
+ "styleguide",
39
+ "design-engineering"
40
+ ],
41
+ "author": "Gregório Pinheiro — Design Engineer UX/UI",
42
+ "license": "MIT",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/gregoriombp/AuisDesign.git",
46
+ "directory": "packages/cli"
47
+ },
48
+ "homepage": "https://github.com/gregoriombp/AuisDesign#readme",
49
+ "bugs": {
50
+ "url": "https://github.com/gregoriombp/AuisDesign/issues"
51
+ }
52
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Argument parsing and dispatch for the Auis CLI.
3
+ *
4
+ * `new` is the default command, so the bare form reads as the install line it
5
+ * is: `npx @auis/cli my-product`. Commands are dispatched by name to leave room
6
+ * for the ones that come next without changing how people invoke the CLI.
7
+ */
8
+
9
+ import fs from "node:fs";
10
+ import { color, banner, fail, write } from "./ui.mjs";
11
+ import { DEFAULT_REF, REPO_URL } from "./template.mjs";
12
+ import { PACKAGE_MANAGERS, create } from "./create.mjs";
13
+
14
+ const MIN_NODE_MAJOR = 20;
15
+ const COMMANDS = new Set(["new", "create", "init"]);
16
+
17
+ export const version = JSON.parse(
18
+ fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"),
19
+ ).version;
20
+
21
+ export function parseArgs(argv) {
22
+ const options = {
23
+ directory: undefined,
24
+ ref: DEFAULT_REF,
25
+ packageManager: undefined,
26
+ install: true,
27
+ git: true,
28
+ force: false,
29
+ yes: false,
30
+ help: false,
31
+ version: false,
32
+ };
33
+
34
+ // `auis my-app`, `auis new my-app`, `auis create my-app` and `auis init my-app`
35
+ // are the same call: scaffolding is the default command.
36
+ const rest = [...argv];
37
+ if (COMMANDS.has(rest[0])) rest.shift();
38
+
39
+ while (rest.length > 0) {
40
+ const arg = rest.shift();
41
+ switch (arg) {
42
+ case "-h":
43
+ case "--help":
44
+ options.help = true;
45
+ break;
46
+ case "-v":
47
+ case "-V":
48
+ case "--version":
49
+ options.version = true;
50
+ break;
51
+ case "-y":
52
+ case "--yes":
53
+ options.yes = true;
54
+ break;
55
+ case "--force":
56
+ options.force = true;
57
+ break;
58
+ case "--no-install":
59
+ case "--skip-install":
60
+ options.install = false;
61
+ break;
62
+ case "--no-git":
63
+ case "--skip-git":
64
+ options.git = false;
65
+ break;
66
+ case "-r":
67
+ case "--ref":
68
+ case "--branch":
69
+ options.ref = rest.shift();
70
+ if (!options.ref) throw new Error(`${arg} needs a branch, tag or commit`);
71
+ break;
72
+ case "--pm":
73
+ case "--use":
74
+ options.packageManager = rest.shift();
75
+ if (!PACKAGE_MANAGERS.includes(options.packageManager)) {
76
+ throw new Error(`--pm must be one of: ${PACKAGE_MANAGERS.join(", ")}`);
77
+ }
78
+ break;
79
+ default: {
80
+ if (arg.startsWith("--ref=") || arg.startsWith("--branch=")) {
81
+ options.ref = arg.slice(arg.indexOf("=") + 1);
82
+ break;
83
+ }
84
+ if (arg.startsWith("--pm=")) {
85
+ options.packageManager = arg.slice(5);
86
+ if (!PACKAGE_MANAGERS.includes(options.packageManager)) {
87
+ throw new Error(`--pm must be one of: ${PACKAGE_MANAGERS.join(", ")}`);
88
+ }
89
+ break;
90
+ }
91
+ if (arg.startsWith("-")) throw new Error(`unknown option: ${arg}`);
92
+ if (options.directory !== undefined) {
93
+ throw new Error(`unexpected argument: ${arg}`);
94
+ }
95
+ options.directory = arg;
96
+ }
97
+ }
98
+ }
99
+
100
+ return options;
101
+ }
102
+
103
+ export function help() {
104
+ const c = color;
105
+ write();
106
+ write(` ${c.bold("auis")} — scaffold a code-native design builder`);
107
+ write();
108
+ write(` ${c.bold("Usage")}`);
109
+ write(` npx @auis/cli ${c.dim("[directory] [options]")}`);
110
+ write(` npx @auis/cli new ${c.dim("[directory] [options]")} ${c.dim("(same thing)")}`);
111
+ write();
112
+ write(` ${c.bold("Options")}`);
113
+ write(` -r, --ref ${c.dim("<ref>")} branch, tag or commit of the template ${c.dim(`(default: ${DEFAULT_REF})`)}`);
114
+ write(` --pm ${c.dim("<manager>")} ${PACKAGE_MANAGERS.join(" | ")} ${c.dim("(default: detected)")}`);
115
+ write(` --no-install skip dependency installation`);
116
+ write(` --no-git skip git init and the first commit`);
117
+ write(` --force scaffold into a directory that is not empty`);
118
+ write(` -y, --yes take the defaults, never prompt`);
119
+ write(` -h, --help show this`);
120
+ write(` -v, --version print the CLI version`);
121
+ write();
122
+ write(` ${c.bold("Examples")}`);
123
+ write(` npx @auis/cli my-product`);
124
+ write(` npx @auis/cli . --no-install`);
125
+ write(` npx @auis/cli my-product --pm pnpm --ref v1.0.0`);
126
+ write();
127
+ write(` ${c.dim(REPO_URL)}`);
128
+ write();
129
+ }
130
+
131
+ export async function run(argv = []) {
132
+ const major = Number(process.versions.node.split(".")[0]);
133
+ if (major < MIN_NODE_MAJOR) {
134
+ fail(`Auis needs Node.js ${MIN_NODE_MAJOR} or newer — you are on ${process.versions.node}.`);
135
+ return 1;
136
+ }
137
+
138
+ let options;
139
+ try {
140
+ options = parseArgs(argv);
141
+ } catch (error) {
142
+ fail(`${error.message}\n Run ${color.bold("npx @auis/cli --help")} for usage.`);
143
+ return 1;
144
+ }
145
+
146
+ if (options.version) {
147
+ write(version);
148
+ return 0;
149
+ }
150
+ if (options.help) {
151
+ help();
152
+ return 0;
153
+ }
154
+
155
+ banner(version);
156
+ return create({ ...options, cliVersion: version });
157
+ }
package/src/create.mjs ADDED
@@ -0,0 +1,302 @@
1
+ /**
2
+ * `auis [directory]` — the `new` command: scaffold a project from the Auis
3
+ * template.
4
+ *
5
+ * The template is the AuisDesign repository itself: it is not a library you
6
+ * install into an app, it *is* the app (Next.js + Tailwind v4 + shadcn/ui plus
7
+ * the builder surfaces and the agent skills). Scaffolding therefore means
8
+ * "unpack the repo, drop the parts that only make sense for contributors to
9
+ * Auis, and make the result look like the user's own project".
10
+ */
11
+
12
+ import fs from "node:fs/promises";
13
+ import path from "node:path";
14
+ import { ask, color, fail, spinner, step, warn, write } from "./ui.mjs";
15
+ import { DEFAULT_REF, REPO_URL, exec, fetchTemplate, hasCommand } from "./template.mjs";
16
+
17
+ /** Files that document contributing to Auis, not building with it. */
18
+ export const PRUNE = [
19
+ ".git",
20
+ ".github/ISSUE_TEMPLATE",
21
+ ".github/PULL_REQUEST_TEMPLATE.md",
22
+ "CONTRIBUTING.md",
23
+ "CODE_OF_CONDUCT.md",
24
+ "docs/EXTRACTION-AUDIT.md",
25
+ "docs/ds-cleanup-plan.md",
26
+ "packages",
27
+ ];
28
+
29
+ /** Entries that do not make a directory "non-empty" for our purposes. */
30
+ const IGNORABLE = new Set([
31
+ ".DS_Store",
32
+ ".git",
33
+ ".gitattributes",
34
+ ".gitignore",
35
+ ".idea",
36
+ ".vscode",
37
+ "Thumbs.db",
38
+ "LICENSE",
39
+ "README.md",
40
+ ]);
41
+
42
+ export const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
43
+
44
+ /** npm's name rules, applied to whatever the user typed as a directory. */
45
+ export function toPackageName(input) {
46
+ const name = String(input)
47
+ .trim()
48
+ .replace(/^.*[\\/]/, "")
49
+ .toLowerCase()
50
+ .replace(/[^a-z0-9._-]+/g, "-")
51
+ .replace(/^[._-]+/, "")
52
+ .replace(/[-._]+$/, "")
53
+ .slice(0, 214);
54
+ return name || "auis-app";
55
+ }
56
+
57
+ export function detectPackageManager(userAgent = process.env.npm_config_user_agent) {
58
+ const name = String(userAgent ?? "").split("/")[0];
59
+ return PACKAGE_MANAGERS.includes(name) ? name : "npm";
60
+ }
61
+
62
+ const installArgs = (pm) => (pm === "yarn" ? [] : ["install"]);
63
+
64
+ async function readDirSafe(dir) {
65
+ try {
66
+ return await fs.readdir(dir);
67
+ } catch (error) {
68
+ if (error.code === "ENOENT") return null;
69
+ throw error;
70
+ }
71
+ }
72
+
73
+ export async function conflictsIn(dir) {
74
+ const entries = await readDirSafe(dir);
75
+ if (entries === null) return [];
76
+ return entries.filter((entry) => !IGNORABLE.has(entry));
77
+ }
78
+
79
+ async function personalize(root, { name, ref, cliVersion }) {
80
+ const pkgPath = path.join(root, "package.json");
81
+ const pkg = JSON.parse(await fs.readFile(pkgPath, "utf8"));
82
+
83
+ // Keep the template's key order and its scripts/dependencies; replace only
84
+ // the identity fields, which describe Auis rather than the new project.
85
+ const next = { ...pkg };
86
+ delete next.author;
87
+ delete next.repository;
88
+ delete next.keywords;
89
+ next.name = name;
90
+ next.version = "0.1.0";
91
+ next.description = `${name} — a design system and product surface built with Auis.`;
92
+ next.private = true;
93
+ next.auis = { template: `${REPO_URL}#${ref}`, createdWith: `@auis/cli@${cliVersion}` };
94
+
95
+ await fs.writeFile(pkgPath, `${JSON.stringify(next, null, 2)}\n`);
96
+
97
+ await fs.writeFile(path.join(root, "README.md"), projectReadme(name));
98
+ }
99
+
100
+ /**
101
+ * Runs against the final destination, not the staging copy: under --force the
102
+ * directory may already hold a .env.local with real keys in it, and copying the
103
+ * example over it would be data loss.
104
+ */
105
+ async function seedEnv(root) {
106
+ const envLocal = path.join(root, ".env.local");
107
+ try {
108
+ await fs.access(envLocal);
109
+ return;
110
+ } catch {
111
+ /* not there yet — seed it below */
112
+ }
113
+ try {
114
+ await fs.copyFile(path.join(root, ".env.example"), envLocal);
115
+ } catch {
116
+ /* the template always ships an example, but never block a scaffold on it */
117
+ }
118
+ }
119
+
120
+ function projectReadme(name) {
121
+ return `# ${name}
122
+
123
+ Built with [Auis](${REPO_URL}) — a code-native design builder. The design
124
+ system, the screens, the UX flows and the review queue all live in this
125
+ repository, and AI agents (Claude Code, Codex, Cursor) build against them under
126
+ the rules in [\`AGENTS.md\`](AGENTS.md).
127
+
128
+ ## Run it
129
+
130
+ \`\`\`bash
131
+ npm install
132
+ npm run dev # http://127.0.0.1:3000
133
+ \`\`\`
134
+
135
+ ## First move
136
+
137
+ In your agent, run:
138
+
139
+ \`\`\`
140
+ /auis-setup
141
+ \`\`\`
142
+
143
+ It sequences the three things Auis will never invent for you: **brand** (name,
144
+ tagline, logo), **tokens** (from a visual reference you hand it) and **voice**
145
+ (from your product). Or open \`/auis/welcome\` and follow the card.
146
+
147
+ ## Surfaces
148
+
149
+ | Surface | Route |
150
+ |---|---|
151
+ | Hub | \`/auis\` |
152
+ | Welcome / first-run setup | \`/auis/welcome\` |
153
+ | Styleguide | \`/auis/styleguide\` |
154
+ | Review inbox | \`/auis/styleguide/review\` |
155
+ | Review Bridge dashboard | \`/auis/review-bridge\` |
156
+ | UX Flow hub | \`/auis/ux-flow\` |
157
+ | State Mode matrix | \`/auis/states\` |
158
+
159
+ ## Commands
160
+
161
+ | Command | What it does |
162
+ |---|---|
163
+ | \`npm run dev\` | Dev server (predev syncs the agent skill trees) |
164
+ | \`npm run build\` / \`typecheck\` / \`lint\` | Build / types / lint |
165
+ | \`npm test\` | Unit tests |
166
+ | \`npm run ds:check\` | Design-system lint (hardcode debt) |
167
+ | \`npm run skills:sync\` | Regenerate \`.claude/skills\` + \`.agents/skills\` |
168
+
169
+ Docs: [\`AUIS.md\`](AUIS.md) · [\`AGENTS.md\`](AGENTS.md) · [\`docs/GETTING-STARTED.md\`](docs/GETTING-STARTED.md)
170
+ `;
171
+ }
172
+
173
+ async function initGit(root) {
174
+ if (!(await hasCommand("git"))) return "git not found";
175
+
176
+ const inside = await exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd: root });
177
+ if (inside.ok) return "already inside a repository";
178
+
179
+ const init = await exec("git", ["init", "-b", "main"], { cwd: root });
180
+ if (!init.ok) return init.stderr || "git init failed";
181
+
182
+ const add = await exec("git", ["add", "-A"], { cwd: root });
183
+ if (!add.ok) return add.stderr || "git add failed";
184
+
185
+ const commit = await exec("git", ["commit", "-m", "chore: scaffold Auis"], { cwd: root });
186
+ if (!commit.ok) return "commit skipped — set user.name and user.email, then commit";
187
+
188
+ return null;
189
+ }
190
+
191
+ export async function create(options) {
192
+ const {
193
+ directory,
194
+ ref = DEFAULT_REF,
195
+ packageManager,
196
+ install = true,
197
+ git = true,
198
+ force = false,
199
+ yes = false,
200
+ cliVersion,
201
+ } = options;
202
+
203
+ const raw =
204
+ directory ?? (yes ? "auis-app" : await ask("Project directory", "auis-app"));
205
+ const root = path.resolve(process.cwd(), raw);
206
+ const name = toPackageName(path.basename(root));
207
+ const relative = path.relative(process.cwd(), root) || ".";
208
+ const pm = packageManager ?? detectPackageManager();
209
+
210
+ const existing = await fs.stat(root).catch(() => null);
211
+ if (existing && !existing.isDirectory()) {
212
+ fail(`${color.bold(relative)} already exists and is not a directory.`);
213
+ return 1;
214
+ }
215
+
216
+ if (!force) {
217
+ const conflicts = await conflictsIn(root);
218
+ if (conflicts.length > 0) {
219
+ fail(
220
+ `${color.bold(relative)} is not empty (${conflicts.slice(0, 4).join(", ")}${
221
+ conflicts.length > 4 ? ", …" : ""
222
+ }).\n Pick another directory or pass --force to scaffold into it anyway.`,
223
+ );
224
+ return 1;
225
+ }
226
+ }
227
+
228
+ let template;
229
+ const stopFetch = spinner(`Fetching the Auis template (${ref})…`);
230
+ try {
231
+ template = await fetchTemplate(ref);
232
+ } catch (error) {
233
+ stopFetch();
234
+ fail(error.message);
235
+ return 1;
236
+ }
237
+ stopFetch();
238
+ step("Template", `${ref} · ${template.source}`);
239
+
240
+ try {
241
+ await Promise.all(
242
+ PRUNE.map((entry) =>
243
+ fs.rm(path.join(template.contents, entry), { recursive: true, force: true }),
244
+ ),
245
+ );
246
+ await personalize(template.contents, { name, ref, cliVersion });
247
+ await fs.mkdir(root, { recursive: true });
248
+ await fs.cp(template.contents, root, { recursive: true, force: true });
249
+ await seedEnv(root);
250
+ } catch (error) {
251
+ fail(`could not write the project: ${error.message}`);
252
+ return 1;
253
+ } finally {
254
+ await fs.rm(template.dir, { recursive: true, force: true });
255
+ }
256
+ step("Project", `${name} → ${relative}`);
257
+
258
+ if (git) {
259
+ const problem = await initGit(root);
260
+ if (problem) warn(`Git: ${problem}`);
261
+ else step("Git", "initialized · first commit");
262
+ }
263
+
264
+ let installed = false;
265
+ let exitCode = 0;
266
+ if (install) {
267
+ const stopInstall = spinner(`Installing dependencies with ${pm}…`);
268
+ const started = Date.now();
269
+ const result = await exec(pm, installArgs(pm), { cwd: root });
270
+ stopInstall();
271
+ installed = result.ok;
272
+ if (result.ok) {
273
+ step("Install", `${pm} · ${Math.round((Date.now() - started) / 1000)}s`);
274
+ } else {
275
+ // The project is on disk and usable — say what broke, then let the next
276
+ // steps carry the install command, but report the failure in the exit code.
277
+ warn(`${pm} install failed — the project is there, the dependencies are not.`);
278
+ if (result.stderr) {
279
+ write(color.dim(` ${result.stderr.split("\n").slice(-3).join("\n ")}`));
280
+ }
281
+ exitCode = 1;
282
+ }
283
+ }
284
+
285
+ const commands = [];
286
+ if (relative !== ".") commands.push(`cd ${relative}`);
287
+ if (!installed) commands.push(`${pm} ${installArgs(pm).join(" ")}`.trim());
288
+ commands.push(`${pm === "npm" ? "npm run" : pm} dev`);
289
+
290
+ write();
291
+ write(` ${color.bold(exitCode === 0 ? "Ready." : "Almost there.")}`);
292
+ write();
293
+ for (const command of commands) write(` ${color.cyan(command)}`);
294
+ write(` ${color.dim("→ http://127.0.0.1:3000/auis")}`);
295
+ write();
296
+ write(` ${color.dim("Then, in Claude Code / Codex / Cursor:")}`);
297
+ write(` ${color.cyan("/auis-setup")} ${color.dim("brand → tokens → voice")}`);
298
+ write();
299
+ write(` ${color.dim(`Docs: ${REPO_URL}`)}`);
300
+ write();
301
+ return exitCode;
302
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Fetching the Auis template. Preferred path is the GitHub tarball (no git
3
+ * required, no history dragged along); `git clone --depth 1` is the fallback
4
+ * for environments without `tar` or without HTTPS access to codeload.
5
+ */
6
+
7
+ import { spawn } from "node:child_process";
8
+ import { createWriteStream } from "node:fs";
9
+ import fs from "node:fs/promises";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { Readable } from "node:stream";
13
+ import { pipeline } from "node:stream/promises";
14
+
15
+ export const REPO = "gregoriombp/AuisDesign";
16
+ export const REPO_URL = `https://github.com/${REPO}`;
17
+ export const DEFAULT_REF = "main";
18
+
19
+ /**
20
+ * A ref can be a branch, a tag or a commit SHA and codeload spells each one
21
+ * differently, so we try all three shapes in order.
22
+ */
23
+ export function tarballUrls(ref = DEFAULT_REF) {
24
+ const base = `https://codeload.github.com/${REPO}/tar.gz`;
25
+ return [`${base}/refs/heads/${ref}`, `${base}/refs/tags/${ref}`, `${base}/${ref}`];
26
+ }
27
+
28
+ /** Runs a command, resolving with its exit code and captured stderr. */
29
+ export function exec(command, args, options = {}) {
30
+ return new Promise((resolve) => {
31
+ const child = spawn(command, args, {
32
+ stdio: options.inherit ? "inherit" : ["ignore", "ignore", "pipe"],
33
+ cwd: options.cwd,
34
+ shell: false,
35
+ env: options.env ?? process.env,
36
+ });
37
+ let stderr = "";
38
+ child.stderr?.on("data", (chunk) => {
39
+ stderr += chunk.toString();
40
+ });
41
+ child.on("error", (error) => resolve({ ok: false, code: -1, stderr: error.message }));
42
+ child.on("close", (code) => resolve({ ok: code === 0, code, stderr: stderr.trim() }));
43
+ });
44
+ }
45
+
46
+ export async function hasCommand(command, args = ["--version"]) {
47
+ const { ok } = await exec(command, args);
48
+ return ok;
49
+ }
50
+
51
+ async function downloadTarball(ref, file) {
52
+ const errors = [];
53
+ for (const url of tarballUrls(ref)) {
54
+ let response;
55
+ try {
56
+ response = await fetch(url, { redirect: "follow" });
57
+ } catch (error) {
58
+ errors.push(`${url}: ${error.message}`);
59
+ continue;
60
+ }
61
+ if (!response.ok || !response.body) {
62
+ errors.push(`${url}: HTTP ${response.status}`);
63
+ continue;
64
+ }
65
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(file));
66
+ return;
67
+ }
68
+ throw new Error(
69
+ `could not download the template for ref "${ref}".\n ${errors.join("\n ")}`,
70
+ );
71
+ }
72
+
73
+ /**
74
+ * Downloads and unpacks the template into a fresh staging directory, returning
75
+ * its path. The caller owns the directory and is responsible for removing it.
76
+ */
77
+ export async function fetchTemplate(ref = DEFAULT_REF) {
78
+ const staging = await fs.mkdtemp(path.join(os.tmpdir(), "auis-"));
79
+ const contents = path.join(staging, "template");
80
+ await fs.mkdir(contents);
81
+
82
+ if (await hasCommand("tar")) {
83
+ try {
84
+ const archive = path.join(staging, "auis.tar.gz");
85
+ await downloadTarball(ref, archive);
86
+ const untar = await exec("tar", [
87
+ "-xzf",
88
+ archive,
89
+ "-C",
90
+ contents,
91
+ "--strip-components=1",
92
+ ]);
93
+ if (!untar.ok) throw new Error(untar.stderr || `tar exited with ${untar.code}`);
94
+ await fs.rm(archive, { force: true });
95
+ return { dir: staging, contents, source: "tarball" };
96
+ } catch (error) {
97
+ await fs.rm(contents, { recursive: true, force: true });
98
+ await fs.mkdir(contents);
99
+ if (!(await hasCommand("git"))) {
100
+ await fs.rm(staging, { recursive: true, force: true });
101
+ throw error;
102
+ }
103
+ }
104
+ }
105
+
106
+ const clone = await exec("git", [
107
+ "clone",
108
+ "--depth",
109
+ "1",
110
+ "--branch",
111
+ ref,
112
+ REPO_URL,
113
+ contents,
114
+ ]);
115
+ if (!clone.ok) {
116
+ await fs.rm(staging, { recursive: true, force: true });
117
+ throw new Error(
118
+ `could not fetch the template (tarball and git clone both failed).\n ${clone.stderr}`,
119
+ );
120
+ }
121
+ await fs.rm(path.join(contents, ".git"), { recursive: true, force: true });
122
+ return { dir: staging, contents, source: "git" };
123
+ }
package/src/ui.mjs ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Terminal output for the Auis CLI. No dependencies: colors degrade to plain
3
+ * text when the stream is not a TTY or NO_COLOR is set, and the spinner is a
4
+ * no-op outside a TTY so CI logs stay readable.
5
+ */
6
+
7
+ const ESC = String.fromCharCode(27);
8
+
9
+ const supportsColor =
10
+ Boolean(process.stdout.isTTY) && !process.env.NO_COLOR && process.env.TERM !== "dumb";
11
+
12
+ const wrap = (open, close) => (text) =>
13
+ supportsColor ? `${ESC}[${open}m${text}${ESC}[${close}m` : String(text);
14
+
15
+ export const color = {
16
+ bold: wrap(1, 22),
17
+ dim: wrap(2, 22),
18
+ red: wrap(31, 39),
19
+ green: wrap(32, 39),
20
+ yellow: wrap(33, 39),
21
+ cyan: wrap(36, 39),
22
+ };
23
+
24
+ export const write = (line = "") => process.stdout.write(`${line}\n`);
25
+
26
+ export const banner = (version) => {
27
+ write();
28
+ write(` ${color.bold("auis")} ${color.dim(version)}`);
29
+ write(` ${color.dim("code-native design builder")}`);
30
+ write();
31
+ };
32
+
33
+ export const step = (label, detail = "") =>
34
+ write(` ${color.green("✓")} ${label.padEnd(10)}${color.dim(detail)}`);
35
+
36
+ export const warn = (message) => write(` ${color.yellow("!")} ${message}`);
37
+
38
+ export const fail = (message) =>
39
+ process.stderr.write(`\n ${color.red("✗")} ${message}\n\n`);
40
+
41
+ const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
42
+
43
+ /** Returns a stop() that clears the line, so the caller can print the result. */
44
+ export function spinner(label) {
45
+ if (!process.stdout.isTTY) {
46
+ write(` ${color.dim("…")} ${label}`);
47
+ return () => {};
48
+ }
49
+ let i = 0;
50
+ process.stdout.write(`${ESC}[?25l`);
51
+ const timer = setInterval(() => {
52
+ process.stdout.write(`\r ${color.cyan(FRAMES[i++ % FRAMES.length])} ${label}`);
53
+ }, 90);
54
+ return () => {
55
+ clearInterval(timer);
56
+ process.stdout.write(`\r${ESC}[2K${ESC}[?25h`);
57
+ };
58
+ }
59
+
60
+ /** The spinner hides the cursor; Ctrl-C must not leave it hidden. */
61
+ export function restoreCursorOnExit() {
62
+ const restore = () => {
63
+ if (process.stdout.isTTY) process.stdout.write(`${ESC}[?25h`);
64
+ };
65
+ process.on("exit", restore);
66
+ process.on("SIGINT", () => {
67
+ restore();
68
+ write();
69
+ process.exit(130);
70
+ });
71
+ }
72
+
73
+ /** Single-question prompt. Falls back to the default when stdin is not a TTY. */
74
+ export async function ask(question, fallback) {
75
+ if (!process.stdin.isTTY) return fallback;
76
+ const { createInterface } = await import("node:readline/promises");
77
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
78
+ try {
79
+ const answer = await rl.question(` ${question} ${color.dim(`(${fallback})`)} `);
80
+ return answer.trim() || fallback;
81
+ } finally {
82
+ rl.close();
83
+ }
84
+ }