@soroush.design/cli 0.0.0-stage → 0.1.0-alpha.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Masoud Soroush <https://soroush.tech>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # @soroush.design/cli
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
+ The command line of the [`@soroush.tech`](https://docs.soroush.tech) design system. Today it has
4
+ one command, `init`, which sets the design system up in an existing React app.
5
+
6
+ ## Use it
7
+
8
+ Run it in your app's folder, or in a workspace's root that holds one app:
9
+
10
+ ```sh
11
+ npx @soroush.tech/design-system init
12
+ ```
13
+
14
+ The design system ships this command line, so that installs the version you ask for. Run on its
15
+ own, `npx @soroush.design/cli init` does the same with the design system version it was released
16
+ next to.
17
+
18
+ In PowerShell, quote the package name: `@` starts a splat there.
19
+
20
+ ```powershell
21
+ npx '@soroush.tech/design-system' init
22
+ ```
23
+
24
+ ## Options
25
+
26
+ | Option | What it does |
27
+ | ----------------- | -------------------------------------------- |
28
+ | `-y`, `--yes` | Apply without asking |
29
+ | `--dry-run` | Show the changes and exit |
30
+ | `--force` | Run outside git, or with uncommitted changes |
31
+ | `--scheme <name>` | The default color scheme: `light` or `dark` |
32
+ | `-h`, `--help` | Show the help |
33
+
34
+ ## What `init` does
35
+
36
+ In a client-rendered React app, whatever builds it (Vite, webpack, Rspack, Parcel, Create React
37
+ App), in TypeScript or JavaScript:
38
+
39
+ - It writes `src/theme/themes` (a `light` and a `dark` theme, each a `createTheme(baseTheme,
40
+ {...})` call you edit) and `src/theme/Providers` (`ThemeProvider` with the base page styles).
41
+ - It wraps what your root renders in `<Providers>`.
42
+ - It installs `@soroush.tech/design-system` with your own package manager.
43
+
44
+ It is careful with your app:
45
+
46
+ - It shows every change first - the files, each edit as a diff, the install - and writes nothing
47
+ before a yes.
48
+ - It runs only in a git repository with no uncommitted change, unless `--force`.
49
+ - It never overwrites a file, and edits the root only when it has the standard shape: one
50
+ `createRoot(...).render(` or `ReactDOM.render(` call. Otherwise it prints the lines to add.
51
+ - When a write fails, it takes back every change it made. The install runs last, with no scripts.
52
+ - A second run finds its own files and changes nothing.
53
+ - It checks your React against the design system's peer range, and never upgrades React.
54
+ - It reaches no network but the install.
55
+
56
+ Next.js, Vike and React Router apps are refused for now, with a pointer to the
57
+ [setup guide](https://docs.soroush.tech/design-system/getting-started/installation/).
58
+
59
+ ## License
60
+
61
+ MIT
package/dist/bin.d.mts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/bin.mjs ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { n as main, t as createNodeIo } from "./io-BzBblzfn.mjs";
3
+ // ../design-system/package.json
4
+ var name = "@soroush.tech/design-system";
5
+ var version = "2.2.0";
6
+ var peerDependencies = {
7
+ "react": "^18.0.0 || ^19.0.0",
8
+ "react-dom": "^18.0.0 || ^19.0.0"
9
+ };
10
+ // src/bin.ts
11
+ process.exitCode = await main(process.argv.slice(2), createNodeIo(), {
12
+ name,
13
+ version,
14
+ peerDependencies
15
+ });
16
+ export {};
@@ -0,0 +1,67 @@
1
+ import { Readable, Writable } from "node:stream";
2
+ interface RunOptions {
3
+ cwd: string;
4
+ env?: Record<string, string>;
5
+ /** Shows the command's own output, as an install's progress, instead of capturing it. */
6
+ showOutput?: boolean;
7
+ }
8
+ interface RunResult {
9
+ /** The exit code, or `null` when the command could not start or was killed. */
10
+ status: number | null;
11
+ stdout: string;
12
+ }
13
+ /** Everything init reaches outside itself for, other than files: a seam for tests. */
14
+ interface Io {
15
+ cwd: string;
16
+ /** Whether a person can answer a question: both stdin and stdout are a terminal. */
17
+ isInteractive: boolean;
18
+ write: (text: string) => void;
19
+ ask: (question: string) => Promise<string>;
20
+ run: (command: string, args: readonly string[], options: RunOptions) => RunResult;
21
+ }
22
+ interface NodeIoOptions {
23
+ stdin?: Readable & {
24
+ isTTY?: boolean;
25
+ };
26
+ stdout?: Writable & {
27
+ isTTY?: boolean;
28
+ };
29
+ platform?: NodeJS.Platform;
30
+ cwd?: string;
31
+ }
32
+ export declare function createNodeIo({ stdin, stdout, platform, cwd }?: NodeIoOptions): Io;
33
+ type Scheme = 'light' | 'dark';
34
+ interface PackageJson {
35
+ name?: string;
36
+ version?: string;
37
+ packageManager?: string;
38
+ dependencies?: Record<string, string>;
39
+ devDependencies?: Record<string, string>;
40
+ peerDependencies?: Record<string, string>;
41
+ '@parcel/resolver-default'?: {
42
+ packageExports?: boolean;
43
+ };
44
+ workspaces?: string[] | {
45
+ packages?: string[];
46
+ };
47
+ }
48
+ /**
49
+ * The `package.json` of `@soroush.tech/design-system`: the nearest one above `fromFile` that is named
50
+ * for it. Its bin finds itself this way.
51
+ */
52
+ export declare function readDesignSystemPackage(fromFile: string): PackageJson;
53
+ /**
54
+ * Reads the command line and runs the command, for `designSystem`: the package of
55
+ * `@soroush.tech/design-system` that init installs. Returns the exit code.
56
+ */
57
+ declare function main(argv: readonly string[], io: Io, designSystem: PackageJson): Promise<number>;
58
+ interface InitOptions {
59
+ /** Applies without asking. */
60
+ isConfirmed: boolean;
61
+ /** Prints the plan and exits. */
62
+ isDryRun: boolean;
63
+ /** Runs outside git, or in a tree with uncommitted changes. */
64
+ isForced: boolean;
65
+ scheme: Scheme | undefined;
66
+ }
67
+ export { type InitOptions, type Io, type PackageJson, main as default };
package/dist/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import { n as main, r as readDesignSystemPackage, t as createNodeIo } from "./io-BzBblzfn.mjs";
2
+ // src/index.ts
3
+ var src_default = main;
4
+ export { createNodeIo, src_default as default, readDesignSystemPackage };
@@ -0,0 +1,933 @@
1
+ import { parseArgs } from "node:util";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { createInterface } from "node:readline/promises";
6
+ // src/apply/fileSystem.ts
7
+ const nodeFileSystem = {
8
+ readFile: (path) => readFileSync(path, "utf8"),
9
+ createFile: (path, content) => writeFileSync(path, content, { flag: "wx" }),
10
+ writeFile: (path, content) => writeFileSync(path, content),
11
+ removeFile: (path) => rmSync(path),
12
+ createDirectory: (path) => mkdirSync(path),
13
+ removeDirectory: (path) => rmdirSync(path),
14
+ isSymbolicLink: (path) => {
15
+ try {
16
+ return lstatSync(path).isSymbolicLink();
17
+ } catch {
18
+ return;
19
+ }
20
+ }
21
+ };
22
+ /**
23
+ * The absolute path of `path`, given from the app's root, when it stays inside the root and
24
+ * passes through no symbolic link. Anything else throws: init writes only inside the app.
25
+ */
26
+ function resolveInside(root, path, fileSystem) {
27
+ const absolute = resolve(root, path);
28
+ const fromRoot = relative(root, absolute);
29
+ if (!fromRoot || fromRoot.startsWith("..") || isAbsolute(fromRoot)) throw new Error(`${path} is outside the app's folder`);
30
+ let current = root;
31
+ for (const segment of fromRoot.split(sep)) {
32
+ current = join(current, segment);
33
+ const isLink = fileSystem.isSymbolicLink(current);
34
+ if (isLink === void 0) break;
35
+ if (isLink) throw new Error(`${path} goes through a symbolic link, which init does not follow`);
36
+ }
37
+ return absolute;
38
+ }
39
+ /** The folders between the root and `directory` that do not exist yet, outermost first. */
40
+ function findMissingDirectories(root, directory, fileSystem) {
41
+ const missing = [];
42
+ let current = directory;
43
+ while (current !== root && fileSystem.isSymbolicLink(current) === void 0) {
44
+ missing.unshift(current);
45
+ current = dirname(current);
46
+ }
47
+ return missing;
48
+ }
49
+ // src/apply/applyPlan.ts
50
+ /** A write failed. `isUndone` says whether every change made before it was taken back. */
51
+ var ApplyError = class extends Error {
52
+ isUndone;
53
+ constructor(message, isUndone) {
54
+ super(message);
55
+ this.name = "ApplyError";
56
+ this.isUndone = isUndone;
57
+ }
58
+ };
59
+ /**
60
+ * Writes the plan's files and edits. Each change keeps a step that takes it back, in memory: when
61
+ * one write fails, the steps run in reverse, so the app is left as it was. Each edit is checked
62
+ * against the file before it is written and read back after.
63
+ */
64
+ function applyPlan(plan, root, fileSystem = nodeFileSystem) {
65
+ const undoSteps = [];
66
+ try {
67
+ for (const file of plan.creates) {
68
+ const absolute = resolveInside(root, file.path, fileSystem);
69
+ for (const directory of findMissingDirectories(root, dirname(absolute), fileSystem)) {
70
+ fileSystem.createDirectory(directory);
71
+ undoSteps.push(() => fileSystem.removeDirectory(directory));
72
+ }
73
+ fileSystem.createFile(absolute, file.content);
74
+ undoSteps.push(() => fileSystem.removeFile(absolute));
75
+ }
76
+ for (const edit of plan.edits) {
77
+ const absolute = resolveInside(root, edit.path, fileSystem);
78
+ if (fileSystem.readFile(absolute) !== edit.before) throw new Error(`${edit.path} changed while init was running`);
79
+ undoSteps.push(() => fileSystem.writeFile(absolute, edit.before));
80
+ fileSystem.writeFile(absolute, edit.after);
81
+ if (fileSystem.readFile(absolute) !== edit.after) throw new Error(`${edit.path} did not read back as init wrote it`);
82
+ }
83
+ } catch (error) {
84
+ let isUndone = true;
85
+ for (const undo of undoSteps.reverse()) try {
86
+ undo();
87
+ } catch {
88
+ isUndone = false;
89
+ }
90
+ throw new ApplyError(error.message, isUndone);
91
+ }
92
+ }
93
+ // src/plan/rootEdit.ts
94
+ const RENDER_CALL = /\.render\s*\(/g;
95
+ const CLOSERS = {
96
+ ")": "(",
97
+ "]": "[",
98
+ "}": "{"
99
+ };
100
+ /** Whether a source starts a client-rendered React app: `createRoot(...).render(` or `ReactDOM.render(`. */
101
+ function isRootSource(source) {
102
+ return /\bcreateRoot\s*\(/.test(source) && /\.render\s*\(/.test(source) || /\bReactDOM\.render\s*\(/.test(source);
103
+ }
104
+ /** Skips a string or a comment starting at `index`, returning the index after it, or `index` if none starts there. */
105
+ function skipStringOrComment(source, index) {
106
+ const char = source[index];
107
+ if (char === "\"" || char === "'" || char === "`") {
108
+ let cursor = index + 1;
109
+ while (cursor < source.length && source[cursor] !== char) cursor += source[cursor] === "\\" ? 2 : 1;
110
+ return cursor + 1;
111
+ }
112
+ if (source.startsWith("//", index)) {
113
+ const end = source.indexOf("\n", index);
114
+ return end === -1 ? source.length : end;
115
+ }
116
+ if (source.startsWith("/*", index)) {
117
+ const end = source.indexOf("*/", index + 2);
118
+ return end === -1 ? source.length : end + 2;
119
+ }
120
+ return index;
121
+ }
122
+ /**
123
+ * The span of the first argument of the call whose `(` ends just before `from`: up to the first
124
+ * comma or the closing parenthesis at its own depth. `null` when the call never closes.
125
+ */
126
+ function readFirstArgument(source, from) {
127
+ const stack = [];
128
+ let cursor = from;
129
+ while (cursor < source.length) {
130
+ const skipped = skipStringOrComment(source, cursor);
131
+ if (skipped !== cursor) {
132
+ cursor = skipped;
133
+ continue;
134
+ }
135
+ const char = source[cursor];
136
+ if (char === "(" || char === "[" || char === "{") stack.push(char);
137
+ else if (char in CLOSERS) {
138
+ if (stack.length === 0) return trimSpan(source, from, cursor);
139
+ if (stack.pop() !== CLOSERS[char]) return null;
140
+ } else if (char === "," && stack.length === 0) return trimSpan(source, from, cursor);
141
+ cursor += 1;
142
+ }
143
+ return null;
144
+ }
145
+ function trimSpan(source, start, end) {
146
+ let from = start;
147
+ let to = end;
148
+ while (from < to && /\s/.test(source[from])) from += 1;
149
+ while (to > from && /\s/.test(source[to - 1])) to -= 1;
150
+ return {
151
+ start: from,
152
+ end: to
153
+ };
154
+ }
155
+ /** The indentation of the line `index` sits on. */
156
+ function indentationAt(source, index) {
157
+ const line = source.slice(source.lastIndexOf("\n", index - 1) + 1, index);
158
+ return line.slice(0, line.length - line.trimStart().length);
159
+ }
160
+ /** Wraps a JSX child in `<Providers>`, keeping a multi-line tree on its own lines, one step deeper. */
161
+ function wrapTree(tree, indentation) {
162
+ if (!tree.includes("\n")) return `<Providers>${tree}</Providers>`;
163
+ const step = indentation.includes(" ") ? " " : " ";
164
+ return `<Providers>\n${indentation}${step}${tree.replaceAll("\n", `\n${step}`)}\n${indentation}</Providers>`;
165
+ }
166
+ const IMPORT_DECLARATION = /^import(?=[\s{*'"])[\s\S]*?(['"])[^'"\n]*\1[^\S\n]*(;?)/gm;
167
+ /**
168
+ * Adds an import after the last import declaration, in the file's own quote and semicolon style:
169
+ * `statement` is written with single quotes and no semicolon.
170
+ */
171
+ function insertImport(source, statement) {
172
+ const last = [...source.matchAll(IMPORT_DECLARATION)].at(-1);
173
+ if (!last) return `${statement}\n${source}`;
174
+ const [text, quote, semicolon] = last;
175
+ const styled = (quote === "\"" ? statement.replaceAll("'", "\"") : statement) + semicolon;
176
+ const end = last.index + text.length;
177
+ return `${source.slice(0, end)}\n${styled}${source.slice(end)}`;
178
+ }
179
+ /**
180
+ * The root with what it renders wrapped in `<Providers>` and the import added, or `null` when it
181
+ * is not the standard shape: one render call. A JSX tree is wrapped as it is; any other argument -
182
+ * a call, a variable - is wrapped as `<Providers>{...}</Providers>`, but only in a file that may
183
+ * hold JSX (`canHoldJsx`, a `.jsx` or `.tsx` file).
184
+ */
185
+ function wrapRoot(source, importStatement, canHoldJsx) {
186
+ const calls = [...source.matchAll(RENDER_CALL)];
187
+ if (calls.length !== 1) return null;
188
+ const call = calls[0];
189
+ const argument = readFirstArgument(source, call.index + call[0].length);
190
+ if (!argument) return null;
191
+ const rendered = source.slice(argument.start, argument.end);
192
+ const isTree = rendered.startsWith("<") && rendered.endsWith(">");
193
+ if (!isTree && (!canHoldJsx || rendered === "")) return null;
194
+ const wrapped = wrapTree(isTree ? rendered : `{${rendered}}`, indentationAt(source, argument.start));
195
+ return insertImport(source.slice(0, argument.start) + wrapped + source.slice(argument.end), importStatement);
196
+ }
197
+ // src/detect/detect.ts
198
+ /** A file's text, or `undefined` when it cannot be read. */
199
+ function readText(path) {
200
+ try {
201
+ return readFileSync(path, "utf8");
202
+ } catch {
203
+ return;
204
+ }
205
+ }
206
+ function readPackageJson(directory) {
207
+ const text = readText(join(directory, "package.json"));
208
+ return text === void 0 ? void 0 : JSON.parse(text);
209
+ }
210
+ /** A dependency's declared range, from `dependencies` or `devDependencies`. */
211
+ function getDependency(packageJson, name) {
212
+ return packageJson.dependencies?.[name] ?? packageJson.devDependencies?.[name];
213
+ }
214
+ const LOCKFILES = [
215
+ ["pnpm-lock.yaml", "pnpm"],
216
+ ["yarn.lock", "yarn"],
217
+ ["bun.lock", "bun"],
218
+ ["bun.lockb", "bun"],
219
+ ["package-lock.json", "npm"],
220
+ ["npm-shrinkwrap.json", "npm"]
221
+ ];
222
+ /**
223
+ * The app's package manager: its `packageManager` field, else the lockfile in its folder or the
224
+ * nearest one above it inside the same repository (a workspace keeps one at its root), else npm.
225
+ */
226
+ function detectPackageManager(root, packageJson, fileExists = existsSync) {
227
+ const declared = /^(npm|pnpm|yarn|bun)@(\d+)/.exec(packageJson.packageManager ?? "");
228
+ if (declared) {
229
+ const name = declared[1];
230
+ return {
231
+ name,
232
+ isYarnBerry: name === "yarn" && Number(declared[2]) >= 2
233
+ };
234
+ }
235
+ for (let directory = root;; directory = dirname(directory)) {
236
+ const lockfile = LOCKFILES.find(([file]) => fileExists(join(directory, file)));
237
+ if (lockfile) {
238
+ const name = lockfile[1];
239
+ return {
240
+ name,
241
+ isYarnBerry: name === "yarn" && fileExists(join(directory, ".yarnrc.yml"))
242
+ };
243
+ }
244
+ if (fileExists(join(directory, ".git")) || dirname(directory) === directory) return {
245
+ name: "npm",
246
+ isYarnBerry: false
247
+ };
248
+ }
249
+ }
250
+ /**
251
+ * The React version the app has installed - in its own node_modules or a workspace's above it -
252
+ * else the lowest its declared range allows. Only node_modules folders are searched: a global
253
+ * folder or NODE_PATH says nothing about the app.
254
+ */
255
+ function findReactVersion(root, packageJson) {
256
+ for (let directory = root;; directory = dirname(directory)) {
257
+ const installed = readPackageJson(join(directory, "node_modules", "react"));
258
+ if (installed) return installed.version;
259
+ if (dirname(directory) === directory) break;
260
+ }
261
+ const match = /(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(getDependency(packageJson, "react") ?? "");
262
+ return match ? `${match[1]}.${match[2] ?? 0}.${match[3] ?? 0}` : void 0;
263
+ }
264
+ /**
265
+ * Whether `version` is in `range`. Only the shape the design system's peer ranges use is read:
266
+ * caret ranges joined by `||`, such as `^18.0.0 || ^19.0.0`. Any other shape throws.
267
+ */
268
+ function satisfiesRange(version, range) {
269
+ const [major, minor, patch] = version.split(/[.-]/).map(Number);
270
+ return range.split("||").some((part) => {
271
+ const match = /^\s*\^(\d+)\.(\d+)\.(\d+)\s*$/.exec(part);
272
+ if (!match) throw new Error(`init cannot read the range ${range}`);
273
+ const [low, lowMinor, lowPatch] = match.slice(1).map(Number);
274
+ return major === low && (minor > lowMinor || minor === lowMinor && patch >= lowPatch);
275
+ });
276
+ }
277
+ /** Whether the app is in a git repository with no uncommitted change. */
278
+ function getGitState(root, io) {
279
+ const { status, stdout } = io.run("git", ["status", "--porcelain"], { cwd: root });
280
+ if (status !== 0) return "not-a-repository";
281
+ return stdout.trim() === "" ? "clean" : "dirty";
282
+ }
283
+ const SKIPPED_FOLDERS = /* @__PURE__ */ new Set([
284
+ "node_modules",
285
+ "dist",
286
+ "build",
287
+ "out",
288
+ "coverage",
289
+ "public"
290
+ ]);
291
+ const MAX_DEPTH = 5;
292
+ /**
293
+ * Every file under the app's folder that starts a client-rendered app, by its path from the root.
294
+ * Tests, stories, folders that hold output or dependencies, hidden folders and symbolic links are
295
+ * not read.
296
+ */
297
+ function findRootFiles(root, folder = "", depth = 0) {
298
+ const found = [];
299
+ for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
300
+ const path = posix.join(folder, entry.name);
301
+ if (entry.name.startsWith(".")) continue;
302
+ if (entry.isDirectory() && !SKIPPED_FOLDERS.has(entry.name) && depth < MAX_DEPTH) found.push(...findRootFiles(root, path, depth + 1));
303
+ else if (entry.isFile() && /\.m?[jt]sx?$/.test(entry.name) && !/\.(test|spec|stories)\./.test(entry.name) && isRootSource(readFileSync(join(root, path), "utf8"))) found.push(path);
304
+ }
305
+ return found;
306
+ }
307
+ /** Whether the folder is a workspace's root: pnpm's `pnpm-workspace.yaml`, or a `workspaces` field. */
308
+ function isWorkspaceRoot(root, packageJson) {
309
+ return packageJson.workspaces !== void 0 || existsSync(join(root, "pnpm-workspace.yaml"));
310
+ }
311
+ /**
312
+ * The folder of the package a file belongs to: the nearest one above it, inside `root`, with a
313
+ * `package.json`, by its path from the root - `''` for the root itself.
314
+ */
315
+ function findPackageFolder(root, path) {
316
+ for (let folder = posix.dirname(path); folder !== "."; folder = posix.dirname(folder)) if (existsSync(join(root, folder, "package.json"))) return folder;
317
+ return "";
318
+ }
319
+ /**
320
+ * The `package.json` of `@soroush.tech/design-system`: the nearest one above `fromFile` that is named
321
+ * for it. Its bin finds itself this way.
322
+ */
323
+ function readDesignSystemPackage(fromFile) {
324
+ for (let directory = dirname(fromFile);; directory = dirname(directory)) {
325
+ const packageJson = readPackageJson(directory);
326
+ if (packageJson?.name === "@soroush.tech/design-system") return packageJson;
327
+ if (dirname(directory) === directory) throw new Error("init cannot find the package.json of @soroush.tech/design-system");
328
+ }
329
+ }
330
+ const UNSUPPORTED_FRAMEWORKS = [
331
+ ["next", "Next.js"],
332
+ ["vike", "Vike"],
333
+ ["@react-router/dev", "React Router in framework mode"],
334
+ ["@remix-run/react", "Remix"],
335
+ ["gatsby", "Gatsby"],
336
+ ["astro", "Astro"],
337
+ ["expo", "Expo"],
338
+ ["react-native", "React Native"]
339
+ ];
340
+ /** The framework an app is built on that init does not set up yet, if any. */
341
+ function findUnsupportedFramework(packageJson) {
342
+ return UNSUPPORTED_FRAMEWORKS.find(([name]) => getDependency(packageJson, name))?.[1];
343
+ }
344
+ /**
345
+ * Whether the app builds with Parcel and has not turned on its reading of package exports, which
346
+ * every subpath of the design system (`/theme`, `/engine`, `/Button`, ...) needs.
347
+ */
348
+ function needsParcelPackageExports(packageJson) {
349
+ return getDependency(packageJson, "parcel") !== void 0 && packageJson["@parcel/resolver-default"]?.packageExports !== true;
350
+ }
351
+ // src/plan/diff.ts
352
+ /**
353
+ * A line diff of two texts, as printed lines: `+ ` added, `- ` removed, and up to `context`
354
+ * unchanged lines around each change, with ` ...` where unchanged lines are left out. The files
355
+ * it compares are an app's root, a few dozen lines, so the plain longest-common-subsequence
356
+ * table is fast enough.
357
+ */
358
+ function diffLines(before, after, context = 2) {
359
+ const oldLines = before.split("\n");
360
+ const newLines = after.split("\n");
361
+ const common = Array.from({ length: oldLines.length + 1 }, () => new Array(newLines.length + 1).fill(0));
362
+ for (let i = oldLines.length - 1; i >= 0; i -= 1) for (let j = newLines.length - 1; j >= 0; j -= 1) common[i][j] = oldLines[i] === newLines[j] ? common[i + 1][j + 1] + 1 : Math.max(common[i + 1][j], common[i][j + 1]);
363
+ const lines = [];
364
+ let i = 0;
365
+ let j = 0;
366
+ while (i < oldLines.length || j < newLines.length) if (i < oldLines.length && j < newLines.length && oldLines[i] === newLines[j]) {
367
+ lines.push({
368
+ mark: " ",
369
+ text: oldLines[i]
370
+ });
371
+ i += 1;
372
+ j += 1;
373
+ } else if (i < oldLines.length && (j === newLines.length || common[i + 1][j] >= common[i][j + 1])) {
374
+ lines.push({
375
+ mark: "-",
376
+ text: oldLines[i]
377
+ });
378
+ i += 1;
379
+ } else {
380
+ lines.push({
381
+ mark: "+",
382
+ text: newLines[j]
383
+ });
384
+ j += 1;
385
+ }
386
+ const isNearChange = (index) => lines.slice(Math.max(0, index - context), index + context + 1).some((line) => line.mark !== " ");
387
+ const printed = [];
388
+ lines.forEach((line, index) => {
389
+ if (isNearChange(index)) printed.push(`${line.mark} ${line.text}`.trimEnd());
390
+ else if (printed.at(-1) !== " ...") printed.push(" ...");
391
+ });
392
+ return printed;
393
+ }
394
+ // src/plan/formatPlan.ts
395
+ /** The plan as the developer reads it before saying yes: every file, every edit and the install. */
396
+ function formatPlan(plan) {
397
+ const sections = [];
398
+ if (plan.creates.length > 0) sections.push(["Create:", ...plan.creates.map((file) => ` ${file.path}`)].join("\n"));
399
+ for (const edit of plan.edits) {
400
+ const diff = diffLines(edit.before, edit.after).map((line) => ` ${line}`.trimEnd());
401
+ sections.push([`Edit ${edit.path}:`, ...diff].join("\n"));
402
+ }
403
+ if (plan.install) {
404
+ const { command, args, env } = plan.install;
405
+ const prefix = Object.entries(env).map(([name, value]) => `${name}=${value} `);
406
+ sections.push(`Install:\n ${prefix.join("")}${[command, ...args].join(" ")}`);
407
+ }
408
+ if (plan.skips.length > 0) sections.push(["Skip:", ...plan.skips.map((skip) => ` ${skip.path}: ${skip.reason}`)].join("\n"));
409
+ if (plan.manual.length > 0) sections.push(["Left to you:", ...plan.manual.map((step) => ` - ${step}`)].join("\n"));
410
+ return `${sections.join("\n\n")}\n`;
411
+ }
412
+ // src/templates/templates.ts
413
+ /** The first line of every file init writes: a second run finds its own files by it. */
414
+ const MARKER = "// Set up by @soroush.tech/design-system init.";
415
+ const THEMING_DOCS = "https://docs.soroush.tech/design-system/customization/theming/";
416
+ const AUGMENTATION_STUB = `
417
+ // To add tokens of your own, declare them here, then give them values in each theme:
418
+ //
419
+ // import type { PaletteEntry } from '@soroush.tech/design-system/theme'
420
+ //
421
+ // declare module '@soroush.tech/design-system/theme' {
422
+ // interface ThemePalette {
423
+ // brand: PaletteEntry
424
+ // }
425
+ // }
426
+ `;
427
+ /**
428
+ * The app's themes. The default export is an object of named themes, each a `createTheme` call
429
+ * with a literal object last: the shape tools that edit a theme read and write.
430
+ */
431
+ function createThemesSource({ isTypeScript }) {
432
+ return `${MARKER} Your themes: change any value, or add a theme.
433
+ // Every token is listed at ${THEMING_DOCS}
434
+ import { baseTheme, createTheme } from '@soroush.tech/design-system/theme'
435
+ ${isTypeScript ? AUGMENTATION_STUB : ""}
436
+ const themes = {
437
+ light: createTheme(baseTheme, {
438
+ name: 'light',
439
+ colorScheme: 'light',
440
+ logoFilter: 'brightness(0)',
441
+ portraitBlend: 'multiply',
442
+ portraitOpacity: 1,
443
+ palette: {
444
+ default: { main: '#5E6065', light: '#8F9094', dark: '#111214', contrastText: '#FFFFFF' },
445
+ primary: { main: '#006E17', light: '#D4F9D2', dark: '#00530F', contrastText: '#FFFFFF' },
446
+ secondary: { main: '#5ACC57', light: '#D4F9D2', dark: '#3AAA37', contrastText: '#FFFFFF' },
447
+ success: { main: '#009928', light: '#E8FFE5', dark: '#006413', contrastText: '#FFFFFF' },
448
+ error: { main: '#BA1A1A', light: '#FFDAD6', dark: '#93000A', contrastText: '#FFFFFF' },
449
+ info: { main: '#0071A4', light: '#E0FAFF', dark: '#004D70', contrastText: '#FFFFFF' },
450
+ warning: { main: '#CCA800', light: '#FFF0A0', dark: '#8C6D00', contrastText: '#FFFFFF' },
451
+ },
452
+ background: {
453
+ backdrop: '#00000080',
454
+ appBar: '#FFFFFFD9',
455
+ glass: '#FFFFFF4D',
456
+ modal: '#FFFFFF',
457
+ default: '#EEEEEE',
458
+ primary: '#F9F9F9',
459
+ secondary: '#F3F3F3',
460
+ paper: '#FFFFFF',
461
+ terminal: '#EEEEEE',
462
+ grid: '#5ACC5733',
463
+ transparent: '#00000000',
464
+ scrollbar: '#0000004D',
465
+ scrollbarTrack: '#F3F3F380',
466
+ },
467
+ text: {
468
+ inherit: 'inherit',
469
+ initial: '#1A1C1C',
470
+ primary: '#006E17',
471
+ secondary: '#444748',
472
+ disabled: '#1A1C1C73',
473
+ error: '#BA1A1A',
474
+ success: '#009928',
475
+ info: '#0071A4',
476
+ warning: '#8C6D00',
477
+ },
478
+ border: {
479
+ default: '#1A1C1C24',
480
+ light: '#0073181A',
481
+ primary: '#006E17',
482
+ dark: '#003D0B',
483
+ },
484
+ skeleton: {
485
+ highlight: '#FFFFFFA6',
486
+ },
487
+ }),
488
+ dark: createTheme(baseTheme, {
489
+ name: 'dark',
490
+ colorScheme: 'dark',
491
+ }),
492
+ }
493
+
494
+ export default themes
495
+ `;
496
+ }
497
+ /**
498
+ * The providers the app's root renders inside: the theme, and the package's base page styles.
499
+ * It holds no JSX, so it needs none of the app's JSX settings.
500
+ */
501
+ function createProvidersSource({ isTypeScript, scheme, themesImport }) {
502
+ return `${MARKER} The app's root renders inside Providers.
503
+ import { createElement } from 'react'
504
+ ${isTypeScript ? `import type { ReactNode } from 'react'\n` : ""}import { Global, globalStyles } from '@soroush.tech/design-system/engine'
505
+ import { ThemeProvider } from '@soroush.tech/design-system/theme'
506
+ import themes from '${themesImport}'
507
+
508
+ /** Gives every component its theme, and draws the page's base styles. */
509
+ export function Providers(${isTypeScript ? "{ children }: { readonly children?: ReactNode }" : "{ children }"}) {
510
+ return createElement(
511
+ ThemeProvider,
512
+ { theme: themes.${scheme} },
513
+ createElement(Global, { styles: globalStyles }),
514
+ children
515
+ )
516
+ }
517
+ `;
518
+ }
519
+ // src/plan/importPath.ts
520
+ const RELATIVE_SPECIFIER = /\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g;
521
+ /**
522
+ * The extension style of a file's relative imports of code, so a new import matches its
523
+ * neighbours: `./App.tsx` means the app imports TypeScript files by their own extension, `./App.js`
524
+ * the Node style, and `./App` none.
525
+ */
526
+ function readExtensionStyle(source) {
527
+ for (const [, specifier] of source.matchAll(RELATIVE_SPECIFIER)) {
528
+ const extension = /\.(m?[jt]sx?)$/.exec(specifier)?.[1];
529
+ if (extension) return extension.includes("t") ? ".ts" : ".js";
530
+ }
531
+ return "";
532
+ }
533
+ /** The specifier `fromFile` imports `toFile` by, both relative to the app's root, in `style`. */
534
+ function toImportSpecifier(fromFile, toFile, style) {
535
+ const target = toFile.replace(/\.[^./]+$/, style);
536
+ const specifier = posix.relative(posix.dirname(fromFile), target);
537
+ return specifier.startsWith(".") ? specifier : `./${specifier}`;
538
+ }
539
+ // src/plan/planInit.ts
540
+ const SETUP_DOCS$1 = "https://docs.soroush.tech/design-system/getting-started/installation/";
541
+ /** The command that adds the design system with the app's own package manager, running no scripts. */
542
+ function createInstallCommand({ name, isYarnBerry }, version) {
543
+ const spec = `@soroush.tech/design-system@${version.includes("-") ? version : `^${version}`}`;
544
+ if (name === "yarn" && isYarnBerry) return {
545
+ command: "yarn",
546
+ args: ["add", spec],
547
+ env: { YARN_ENABLE_SCRIPTS: "false" }
548
+ };
549
+ return {
550
+ command: name,
551
+ args: [
552
+ name === "npm" ? "install" : "add",
553
+ spec,
554
+ "--ignore-scripts"
555
+ ],
556
+ env: {}
557
+ };
558
+ }
559
+ function describeRootProblem(facts) {
560
+ if (facts.rootCandidates.length === 0) return "init found no file that calls createRoot(...).render( or ReactDOM.render(.";
561
+ return `init found more than one root (${facts.rootCandidates.join(", ")}) and edits none.`;
562
+ }
563
+ /** Works out the changes, reading files through `facts.readFile` and writing nothing. */
564
+ function planInit(facts) {
565
+ const plan = {
566
+ creates: [],
567
+ edits: [],
568
+ skips: [],
569
+ manual: [],
570
+ install: void 0
571
+ };
572
+ const extension = facts.isTypeScript ? "ts" : "js";
573
+ const themeDir = facts.hasSrcFolder || !facts.root ? "src/theme" : posix.join(posix.dirname(facts.root.path), "theme");
574
+ const themesPath = `${themeDir}/themes.${extension}`;
575
+ const providersPath = `${themeDir}/Providers.${extension}`;
576
+ const style = facts.root ? readExtensionStyle(facts.root.source) : "";
577
+ if (planThemeFiles(plan, facts, {
578
+ themesPath,
579
+ providersPath,
580
+ style
581
+ })) planRootEdit(plan, facts, providersPath, style);
582
+ else plan.manual.push(`Set up the theme by hand: ${SETUP_DOCS$1}`);
583
+ if (facts.needsParcelPackageExports) plan.manual.push("Parcel finds @soroush.tech/design-system/theme and the other subpaths only once it reads package exports. Add to package.json: \"@parcel/resolver-default\": { \"packageExports\": true }");
584
+ if (!facts.hasDesignSystem) plan.install = createInstallCommand(facts.packageManager, facts.version);
585
+ return plan;
586
+ }
587
+ /** Whether a file is missing, was written by init, or by someone else. */
588
+ function getOwnership(facts, path) {
589
+ const content = facts.readFile(path);
590
+ if (content === void 0) return "missing";
591
+ return content.startsWith("// Set up by @soroush.tech/design-system init.") ? "ours" : "theirs";
592
+ }
593
+ /**
594
+ * Plans the themes and the providers, never over a file init did not write. Returns whether the
595
+ * app ends up with init's providers.
596
+ */
597
+ function planThemeFiles(plan, facts, { themesPath, providersPath, style }) {
598
+ const themes = getOwnership(facts, themesPath);
599
+ const providers = getOwnership(facts, providersPath);
600
+ if (themes === "missing") plan.creates.push({
601
+ path: themesPath,
602
+ content: createThemesSource(facts)
603
+ });
604
+ else if (themes === "theirs") plan.skips.push({
605
+ path: themesPath,
606
+ reason: "exists, and init did not write it"
607
+ });
608
+ if (providers === "theirs") plan.skips.push({
609
+ path: providersPath,
610
+ reason: "exists, and init did not write it"
611
+ });
612
+ else if (providers === "missing" && themes === "theirs") plan.skips.push({
613
+ path: providersPath,
614
+ reason: `would read ${themesPath}, which init did not write`
615
+ });
616
+ else if (providers === "missing") {
617
+ const themesImport = toImportSpecifier(providersPath, themesPath, style);
618
+ plan.creates.push({
619
+ path: providersPath,
620
+ content: createProvidersSource({
621
+ ...facts,
622
+ themesImport
623
+ })
624
+ });
625
+ }
626
+ return providers === "ours" || plan.creates.some((file) => file.path === providersPath);
627
+ }
628
+ /** Plans the root's edit, or the lines to add by hand when init cannot make it. */
629
+ function planRootEdit(plan, facts, providersPath, style) {
630
+ if (!facts.root) {
631
+ plan.manual.push(`${describeRootProblem(facts)} In the file that renders your app, import { Providers } from ${providersPath} and wrap the tree it renders: render(<Providers><App /></Providers>).`);
632
+ return;
633
+ }
634
+ const specifier = toImportSpecifier(facts.root.path, providersPath, style);
635
+ const statement = `import { Providers } from '${specifier}'`;
636
+ const { path, source } = facts.root;
637
+ const after = source.includes(`'${specifier}'`) || source.includes(`"${specifier}"`) ? source : wrapRoot(source, statement, /\.[jt]sx$/.test(path));
638
+ if (after === null) plan.manual.push(`${path} is not the standard shape, so init leaves it as it is. Add ${statement} to it, and wrap the tree it renders: render(<Providers><App /></Providers>).`);
639
+ else if (after !== source) plan.edits.push({
640
+ path,
641
+ before: source,
642
+ after
643
+ });
644
+ }
645
+ /** Whether the plan has nothing to write or install. */
646
+ function isPlanEmpty(plan) {
647
+ return plan.creates.length === 0 && plan.edits.length === 0 && !plan.install;
648
+ }
649
+ // src/init.ts
650
+ const SETUP_DOCS = "https://docs.soroush.tech/design-system/getting-started/installation/";
651
+ const FONTS_DOCS = `${SETUP_DOCS}#fonts`;
652
+ function formatClosing({ creates, manual }) {
653
+ const themes = creates.find((file) => /\/themes\.[jt]s$/.test(file.path));
654
+ const themesStep = themes ? `\n - Make the themes your own in ${themes.path}.` : "";
655
+ const steps = manual.map((step) => ` - ${step}`).join("\n");
656
+ return `Done: the design system is set up.
657
+ ${manual.length > 0 ? `\nStill left to you:\n${steps}\n` : ""}
658
+ Next:
659
+ - Use a component: import { Button } from '@soroush.tech/design-system/Button'${themesStep}
660
+ - Fonts: the theme names Space Grotesk and JetBrains Mono, and does not load them. To add them,
661
+ see ${FONTS_DOCS}
662
+
663
+ For a coding agent, if you use one (any agent):
664
+ - The house-style skill: npx skills add soroush-tech/design-system
665
+ - The MCP server, for any MCP client: https://mcp.soroush.design/mcp
666
+ `;
667
+ }
668
+ /** Why init refuses this app, or `undefined` when it can set it up. */
669
+ function findRefusal(root, packageJson, reactRange) {
670
+ const framework = findUnsupportedFramework(packageJson);
671
+ if (framework) return `This looks like a ${framework} app. init sets up client-rendered React apps for now, so it changes nothing here. To set it up by hand, see ${SETUP_DOCS}`;
672
+ const reactVersion = findReactVersion(root, packageJson);
673
+ if (!reactVersion) return "init found no React in this app. Add react and react-dom first.";
674
+ if (!satisfiesRange(reactVersion, reactRange)) return `This app has React ${reactVersion}, and the design system needs React ${reactRange}. init changes nothing, and never upgrades React.`;
675
+ }
676
+ function findGitRefusal(root, io) {
677
+ const state = getGitState(root, io);
678
+ if (state === "not-a-repository") return "This folder is not in a git repository, so init could not show you its changes afterwards. Run git init and commit first, or run again with --force.";
679
+ if (state === "dirty") return "This folder has uncommitted changes. Commit or stash them first, so init's changes stand on their own, or run again with --force.";
680
+ }
681
+ /**
682
+ * The app init sets up from `cwd`: the folder itself, or - in a workspace's root - the one package
683
+ * in it that starts an app. A string says why there is none. A file in a nested package is never
684
+ * taken for the app's own.
685
+ */
686
+ function findApp(cwd) {
687
+ const packageJson = readPackageJson(cwd);
688
+ if (!packageJson) return "There is no package.json in this folder. Run init in your app's folder.";
689
+ const rootFilesByFolder = /* @__PURE__ */ new Map();
690
+ for (const path of findRootFiles(cwd)) {
691
+ const folder = findPackageFolder(cwd, path);
692
+ rootFilesByFolder.set(folder, [...rootFilesByFolder.get(folder) ?? [], path]);
693
+ }
694
+ if (!isWorkspaceRoot(cwd, packageJson)) return {
695
+ root: cwd,
696
+ packageJson,
697
+ rootCandidates: rootFilesByFolder.get("") ?? [],
698
+ folder: ""
699
+ };
700
+ const folders = [...rootFilesByFolder.keys()];
701
+ if (folders.length === 0) return "This is a workspace's root, and init found no app in it that calls createRoot(...).render( or ReactDOM.render(. Run init in your app's folder.";
702
+ if (folders.length > 1) return `This is a workspace's root with more than one app (${folders.map((folder) => folder || ".").join(", ")}). Run init in the one to set up, for example: cd ${folders.find(Boolean)}`;
703
+ const [folder] = folders;
704
+ const root = join(cwd, folder);
705
+ const rootCandidates = rootFilesByFolder.get(folder).map((path) => folder ? path.slice(folder.length + 1) : path);
706
+ return {
707
+ root,
708
+ packageJson: readPackageJson(root),
709
+ rootCandidates,
710
+ folder
711
+ };
712
+ }
713
+ async function askScheme(io) {
714
+ const answer = await io.ask("Default color scheme, light or dark? (light) ");
715
+ return /^d(ark)?$/i.test(answer.trim()) ? "dark" : "light";
716
+ }
717
+ function collectFacts(app, scheme, designSystem) {
718
+ const { root, packageJson, rootCandidates } = app;
719
+ const rootPath = rootCandidates.length === 1 ? rootCandidates[0] : void 0;
720
+ return {
721
+ isTypeScript: rootPath ? /\.m?tsx?$/.test(rootPath) : existsSync(join(root, "tsconfig.json")),
722
+ hasSrcFolder: existsSync(join(root, "src")),
723
+ root: rootPath ? {
724
+ path: rootPath,
725
+ source: readText(join(root, rootPath))
726
+ } : void 0,
727
+ rootCandidates,
728
+ hasDesignSystem: Boolean(getDependency(packageJson, "@soroush.tech/design-system")),
729
+ needsParcelPackageExports: needsParcelPackageExports(packageJson),
730
+ packageManager: detectPackageManager(root, packageJson),
731
+ version: designSystem.version,
732
+ scheme: scheme ?? "light",
733
+ readFile: (path) => readText(join(root, path))
734
+ };
735
+ }
736
+ /** Plans, asking for the default scheme first when init creates the providers and may ask. */
737
+ async function planWithScheme(facts, canAsk, io) {
738
+ const plan = planInit(facts);
739
+ return plan.creates.some((file) => /\/Providers\.[jt]s$/.test(file.path)) && canAsk ? planInit({
740
+ ...facts,
741
+ scheme: await askScheme(io)
742
+ }) : plan;
743
+ }
744
+ /** Whether to apply the plan: never on a dry run or with no terminal, else on --yes or a yes. */
745
+ async function isApproved(options, isPreviewOnly, io) {
746
+ if (options.isDryRun) {
747
+ io.write("Dry run: nothing was changed.\n");
748
+ return false;
749
+ }
750
+ if (isPreviewOnly) {
751
+ io.write("Preview only: there is no terminal to answer in. Run again with --yes to apply.\n");
752
+ return false;
753
+ }
754
+ if (options.isConfirmed) return true;
755
+ const isYes = /^y(es)?$/i.test((await io.ask("Apply these changes? (y/N) ")).trim());
756
+ if (!isYes) io.write("Nothing was changed.\n");
757
+ return isYes;
758
+ }
759
+ /** Writes the plan, then installs the package. Returns the exit code. */
760
+ function applyAndInstall(plan, root, io, fileSystem) {
761
+ try {
762
+ applyPlan(plan, root, fileSystem);
763
+ } catch (error) {
764
+ const { message, isUndone } = error;
765
+ const outcome = isUndone ? "Every change it made was taken back." : "It could not take back every change: check git status.";
766
+ io.write(`init stopped: ${message}. ${outcome}\n`);
767
+ return 1;
768
+ }
769
+ if (plan.install) {
770
+ const { command, args, env } = plan.install;
771
+ io.write(`\nInstalling with ${command}:\n`);
772
+ if (io.run(command, args, {
773
+ cwd: root,
774
+ env,
775
+ showOutput: true
776
+ }).status !== 0) {
777
+ const commandLine = [command, ...args].join(" ");
778
+ io.write(`\nThe install failed. The files are written; install the package yourself:\n ${commandLine}\n`);
779
+ return 1;
780
+ }
781
+ }
782
+ io.write(formatClosing(plan));
783
+ return 0;
784
+ }
785
+ /**
786
+ * Sets up the design system in the app in `io.cwd`: checks, plans, shows the plan, and applies it
787
+ * only after a yes. `designSystem` is the package it installs: its version, and the React range it
788
+ * checks the app against. Returns the exit code.
789
+ */
790
+ async function runInit(options, io, designSystem, fileSystem = nodeFileSystem) {
791
+ const app = findApp(realpathSync(io.cwd));
792
+ if (typeof app === "string") {
793
+ io.write(`${app}\n`);
794
+ return 1;
795
+ }
796
+ const { root, packageJson, folder } = app;
797
+ if (folder) io.write(`This is a workspace's root: init sets up the app in ${folder}.\n\n`);
798
+ const refusal = findRefusal(root, packageJson, designSystem.peerDependencies.react);
799
+ if (refusal) {
800
+ io.write(`${refusal}\n`);
801
+ return 1;
802
+ }
803
+ const isPreviewOnly = options.isDryRun || !io.isInteractive && !options.isConfirmed;
804
+ const gitRefusal = isPreviewOnly || options.isForced ? void 0 : findGitRefusal(root, io);
805
+ if (gitRefusal) {
806
+ io.write(`${gitRefusal}\n`);
807
+ return 1;
808
+ }
809
+ const plan = await planWithScheme(collectFacts(app, options.scheme, designSystem), !options.scheme && !isPreviewOnly && !options.isConfirmed, io);
810
+ if (isPlanEmpty(plan)) {
811
+ const leftovers = plan.skips.length + plan.manual.length > 0 ? `\n${formatPlan(plan)}` : "";
812
+ io.write(`The design system is already set up here: init has nothing to change.\n${leftovers}`);
813
+ return 0;
814
+ }
815
+ const appName = packageJson.name ?? "this app";
816
+ io.write(`init will set up @soroush.tech/design-system in ${appName}:\n\n${formatPlan(plan)}\n`);
817
+ if (!await isApproved(options, isPreviewOnly, io)) return 0;
818
+ return applyAndInstall(plan, root, io, fileSystem);
819
+ }
820
+ // src/main.ts
821
+ const USAGE = `Usage: npx @soroush.tech/design-system init [options]
822
+
823
+ Sets up @soroush.tech/design-system in the React app in this folder. It shows every change
824
+ first, and writes nothing until you say yes.
825
+
826
+ Options:
827
+ -y, --yes apply without asking
828
+ --dry-run show the changes and exit
829
+ --force run outside git, or with uncommitted changes
830
+ --scheme <name> the default color scheme: light or dark
831
+ -h, --help show this help
832
+ `;
833
+ /**
834
+ * Reads the command line and runs the command, for `designSystem`: the package of
835
+ * `@soroush.tech/design-system` that init installs. Returns the exit code.
836
+ */
837
+ async function main(argv, io, designSystem) {
838
+ let parsed;
839
+ try {
840
+ parsed = parseArgs({
841
+ args: [...argv],
842
+ allowPositionals: true,
843
+ options: {
844
+ yes: {
845
+ type: "boolean",
846
+ short: "y"
847
+ },
848
+ "dry-run": { type: "boolean" },
849
+ force: { type: "boolean" },
850
+ scheme: { type: "string" },
851
+ help: {
852
+ type: "boolean",
853
+ short: "h"
854
+ }
855
+ }
856
+ });
857
+ } catch (error) {
858
+ io.write(`${error.message}\n\n${USAGE}`);
859
+ return 1;
860
+ }
861
+ const { values, positionals } = parsed;
862
+ if (values.help) {
863
+ io.write(USAGE);
864
+ return 0;
865
+ }
866
+ const [command, ...extra] = positionals;
867
+ if (command !== "init" || extra.length > 0) {
868
+ const unknown = command ? `Unknown command: ${positionals.join(" ")}\n\n` : "";
869
+ io.write(unknown + USAGE);
870
+ return 1;
871
+ }
872
+ const { scheme } = values;
873
+ if (scheme !== void 0 && scheme !== "light" && scheme !== "dark") {
874
+ io.write(`--scheme is light or dark, not ${scheme}.\n`);
875
+ return 1;
876
+ }
877
+ return runInit({
878
+ isConfirmed: Boolean(values.yes),
879
+ isDryRun: Boolean(values["dry-run"]),
880
+ isForced: Boolean(values.force),
881
+ scheme
882
+ }, io, designSystem);
883
+ }
884
+ // src/io.ts
885
+ const PLAIN_ARGUMENT = /^[\w@./:^=+-]+$/;
886
+ /**
887
+ * The command line for cmd.exe, which Windows needs to start a package manager's `.cmd` shim.
888
+ * Each argument is quoted: inside quotes, cmd.exe reads `^` as itself, not as its escape.
889
+ */
890
+ function toWindowsCommandLine(command, args) {
891
+ for (const part of [command, ...args]) if (!PLAIN_ARGUMENT.test(part)) throw new Error(`init does not run the argument ${part}`);
892
+ return [command, ...args.map((arg) => `"${arg}"`)].join(" ");
893
+ }
894
+ function createNodeIo({ stdin = process.stdin, stdout = process.stdout, platform = process.platform, cwd = process.cwd() } = {}) {
895
+ return {
896
+ cwd,
897
+ isInteractive: Boolean(stdin.isTTY && stdout.isTTY),
898
+ write: (text) => {
899
+ stdout.write(text);
900
+ },
901
+ ask: async (question) => {
902
+ const prompt = createInterface({
903
+ input: stdin,
904
+ output: stdout
905
+ });
906
+ try {
907
+ return await prompt.question(question);
908
+ } finally {
909
+ prompt.close();
910
+ }
911
+ },
912
+ run: (command, args, { cwd: directory, env = {}, showOutput = false }) => {
913
+ const options = {
914
+ cwd: directory,
915
+ env: {
916
+ ...process.env,
917
+ ...env
918
+ },
919
+ encoding: "utf8",
920
+ stdio: showOutput ? "inherit" : "pipe"
921
+ };
922
+ const result = platform === "win32" ? spawnSync(toWindowsCommandLine(command, args), {
923
+ ...options,
924
+ shell: true
925
+ }) : spawnSync(command, args, options);
926
+ return {
927
+ status: result.status,
928
+ stdout: result.stdout ?? ""
929
+ };
930
+ }
931
+ };
932
+ }
933
+ export { main as n, readDesignSystemPackage as r, createNodeIo as t };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@soroush.design/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "The command line of the @soroush.tech design system: init sets it up in an existing React app, showing every change first.",
5
+ "keywords": [
6
+ "cli",
7
+ "init",
8
+ "design-system",
9
+ "react",
10
+ "setup"
11
+ ],
12
+ "author": "Masoud Soroush <masoud@soroush.tech>",
13
+ "license": "MIT",
14
+ "homepage": "https://docs.soroush.tech",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/soroush-tech/design-system.git",
18
+ "directory": "packages/cli"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/soroush-tech/design-system/issues"
22
+ },
23
+ "type": "module",
24
+ "sideEffects": false,
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "bin": {
29
+ "soroush-design": "./dist/bin.mjs"
30
+ },
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.mts",
34
+ "default": "./dist/index.mjs"
35
+ }
36
+ },
37
+ "types": "./dist/index.d.mts",
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^26.6.6",
43
+ "@types/react": "^19.3.0",
44
+ "@types/react-dom": "^19.3.0",
45
+ "@vitest/coverage-v8": "^5.1.0",
46
+ "oxlint": "^1.93.0",
47
+ "tsdown": "^0.23.7",
48
+ "typescript": "~7.0.2",
49
+ "vitest": "^5.1.0",
50
+ "@soroush.tech/eslint-config": "0.0.0"
51
+ },
52
+ "scripts": {
53
+ "build": "tsdown",
54
+ "lint": "oxlint --deny-warnings",
55
+ "typecheck": "tsc --noEmit",
56
+ "test": "vitest run",
57
+ "test:coverage": "vitest run --coverage",
58
+ "test:types": "pnpm --filter @soroush.tech/design-system build && tsc -p type-tests/init/tsconfig.json"
59
+ },
60
+ "module": "./dist/index.mjs"
6
61
  }