@soroush.design/cli 0.2.0-alpha.1 → 0.2.0-alpha.2

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
@@ -7,33 +7,44 @@ an existing React app.
7
7
  ## Start a new app: `create`
8
8
 
9
9
  ```sh
10
- npx @soroush.tech/design-system create my-app
10
+ npx @soroush.design/cli create my-app
11
11
  ```
12
12
 
13
13
  It makes the app in a new folder, `my-app`, or in an empty one, and never writes in a folder that
14
- holds anything. It asks for what you did not give it - the name, TypeScript or JavaScript, the
15
- default color scheme, whether to add sample data pages - then shows every file and the install, and writes nothing before a yes.
16
- It installs with the package manager you ran it with (`npx`, `pnpm dlx`, `yarn dlx`, `bunx`), with
14
+ holds anything. It asks for what you did not give it - the name and the title typed, then the
15
+ language, the package manager, the default color scheme and the sample data pages picked with the
16
+ arrow keys - then shows every file and the install, and writes nothing before a yes. The package
17
+ manager starts on the one you ran it with (`npx`, `pnpm dlx`, `yarn dlx`, `bunx`). It installs with
17
18
  no scripts, and runs `git init` with no commit, unless the folder is already in a repository. When
18
19
  a write or the install fails, it takes the new app away.
19
20
 
20
- | Option | What it does |
21
- | -------------------- | --------------------------------------------------------- |
22
- | `-y`, `--yes` | Create without asking: TypeScript and light, unless given |
23
- | `--dry-run` | Show the files and exit |
24
- | `--title <text>` | What the app's pages call it: the name when not given |
25
- | `--framework <name>` | The app's framework: `vike`, the default and only one yet |
26
- | `--ts`, `--js` | TypeScript (the default) or JavaScript |
27
- | `--scheme <name>` | The default color scheme: `light` or `dark` |
28
- | `--sample-data` | Add the sample data pages |
29
- | `--no-git` | Do not run `git init` |
30
- | `-h`, `--help` | Show the options of `create` |
21
+ | Option | What it does |
22
+ | -------------------- | ----------------------------------------------------------------- |
23
+ | `-y`, `--yes` | Create without asking: TypeScript and light, unless given |
24
+ | `--dry-run` | Show the files and exit |
25
+ | `--title <text>` | What the app's pages call it: the name when not given |
26
+ | `--framework <name>` | The app's framework: `vike`, the default and only one yet |
27
+ | `--ts`, `--js` | TypeScript (the default) or JavaScript |
28
+ | `--pm <name>` | `npm`, `pnpm`, `yarn` or `bun`: the one that ran it, if not given |
29
+ | `--render <name>` | `isomorphic` (the default), `spa` or `ssg` |
30
+ | `--scheme <name>` | The default color scheme: `light` or `dark` |
31
+ | `--sample-data` | Add the sample data pages |
32
+ | `--no-git` | Do not run `git init` |
33
+ | `-h`, `--help` | Show the options of `create` |
31
34
 
32
35
  ### The Vike app
33
36
 
34
- A [Vike](https://vike.dev) app, isomorphic: every page is prerendered to HTML at build time, with
35
- the styles it uses, so it is drawn styled before any script runs. Then the app takes over in the
36
- browser and moves between pages without a reload.
37
+ A [Vike](https://vike.dev) app, rendered the way you pick:
38
+
39
+ - **Isomorphic** (the default): every page is prerendered to HTML at build time, with the styles
40
+ it uses, so it is drawn styled before any script runs. Then the app takes over in the browser
41
+ and moves between pages without a reload.
42
+ - **SPA**: every page is an empty HTML shell from the build, and the browser renders it, with its
43
+ styles. It moves between pages without a reload.
44
+ - **SSG**: every page is prerendered to HTML with its styles, and ships no JavaScript: a link loads
45
+ the next page. It has no light and dark switch, since that needs JavaScript.
46
+
47
+ All three build to static files that any static host serves.
37
48
 
38
49
  - `src/pages/` holds the pages - a home page, a second page and a 404 page - built from the design
39
50
  system's components and theme tokens only.
package/dist/bin.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { n as main, r as version$1, t as createNodeIo } from "./io-2De2zuH0.mjs";
2
+ import { n as main, r as version$1, t as createNodeIo } from "./io-uDtjQuG6.mjs";
3
3
  // ../design-system/package.json
4
4
  var name = "@soroush.tech/design-system";
5
- var version = "2.3.0";
5
+ var version = "2.2.0";
6
6
  var peerDependencies = {
7
7
  "react": "^18.0.0 || ^19.0.0",
8
8
  "react-dom": "^18.0.0 || ^19.0.0"
package/dist/index.d.mts CHANGED
@@ -1,4 +1,11 @@
1
1
  import { Readable, Writable } from "node:stream";
2
+ /** One answer a choice offers. */
3
+ interface Choice {
4
+ /** What the command gets back. */
5
+ value: string;
6
+ /** What the person reads. */
7
+ label: string;
8
+ }
2
9
  interface RunOptions {
3
10
  cwd: string;
4
11
  env?: Record<string, string>;
@@ -17,12 +24,22 @@ interface Io {
17
24
  isInteractive: boolean;
18
25
  write: (text: string) => void;
19
26
  ask: (question: string) => Promise<string>;
27
+ /**
28
+ * Asks for one of `choices`, picked with the arrow keys, starting on `initial`. Rejects with a
29
+ * `CancelledError` on Ctrl+C or Escape.
30
+ */
31
+ select: (question: string, choices: readonly Choice[], initial?: number) => Promise<string>;
32
+ /** Asks for any of `choices`, toggled with space, starting with `initial` picked. */
33
+ selectMany: (question: string, choices: readonly Choice[], initial?: readonly string[]) => Promise<string[]>;
20
34
  run: (command: string, args: readonly string[], options: RunOptions) => RunResult;
21
35
  }
36
+ type Terminal = Readable & {
37
+ isTTY?: boolean;
38
+ isRaw?: boolean;
39
+ setRawMode?: (mode: boolean) => unknown;
40
+ };
22
41
  interface NodeIoOptions {
23
- stdin?: Readable & {
24
- isTTY?: boolean;
25
- };
42
+ stdin?: Terminal;
26
43
  stdout?: Writable & {
27
44
  isTTY?: boolean;
28
45
  };
@@ -31,6 +48,7 @@ interface NodeIoOptions {
31
48
  }
32
49
  export declare function createNodeIo({ stdin, stdout, platform, cwd }?: NodeIoOptions): Io;
33
50
  type Scheme = 'light' | 'dark';
51
+ type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun';
34
52
  interface PackageJson {
35
53
  name?: string;
36
54
  version?: string;
@@ -52,9 +70,16 @@ interface PackageJson {
52
70
  export declare function readDesignSystemPackage(fromFile: string): PackageJson;
53
71
  /**
54
72
  * Reads the command line and runs the command, for `designSystem`: the package of
55
- * `@soroush.tech/design-system` the command installs. Returns the exit code.
73
+ * `@soroush.tech/design-system` the command installs. Returns the exit code: 130 when the person
74
+ * stops it at a question, which is before anything is written.
56
75
  */
57
76
  declare function main(argv: readonly string[], io: Io, designSystem: PackageJson): Promise<number>;
77
+ /**
78
+ * How the app's pages are rendered: `isomorphic`, prerendered to HTML at build time and then
79
+ * moving between pages in the browser; `spa`, rendered in the browser only; `ssg`, HTML only, with
80
+ * no JavaScript in the browser.
81
+ */
82
+ type Rendering = 'isomorphic' | 'spa' | 'ssg';
58
83
  interface CreateOptions {
59
84
  /** The app's folder: asked for, or `my-app`, when missing. */
60
85
  name: string | undefined;
@@ -64,6 +89,10 @@ interface CreateOptions {
64
89
  framework: string | undefined;
65
90
  /** TypeScript or JavaScript: asked for, or TypeScript, when missing. */
66
91
  isTypeScript: boolean | undefined;
92
+ /** The package manager to install with: asked for, or the one that ran create, when missing. */
93
+ packageManager: PackageManagerName | undefined;
94
+ /** How the pages are rendered: asked for, or isomorphic, when missing. */
95
+ rendering: Rendering | undefined;
67
96
  scheme: Scheme | undefined;
68
97
  /** Adds the pages that read sample data: asked for, or not, when missing. */
69
98
  hasSampleData: boolean | undefined;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { t as createNodeIo, n as default, i as readDesignSystemPackage } from "./io-2De2zuH0.mjs";
1
+ export { t as createNodeIo, n as default, i as readDesignSystemPackage } from "./io-uDtjQuG6.mjs";
@@ -2,6 +2,7 @@ import { parseArgs } from "node:util";
2
2
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
3
3
  import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
+ import { emitKeypressEvents } from "node:readline";
5
6
  import { createInterface } from "node:readline/promises";
6
7
  // src/apply/fileSystem.ts
7
8
  const nodeFileSystem = {
@@ -727,10 +728,15 @@ function findApp(cwd) {
727
728
  folder
728
729
  };
729
730
  }
730
- /** Asks for the default color scheme: light, unless the answer is dark. */
731
+ /** Asks for the default color scheme, starting on light. */
731
732
  async function askScheme(io) {
732
- const answer = await io.ask("Default color scheme, light or dark? (light) ");
733
- return /^d(ark)?$/i.test(answer.trim()) ? "dark" : "light";
733
+ return await io.select("Default color scheme", [{
734
+ value: "light",
735
+ label: "light"
736
+ }, {
737
+ value: "dark",
738
+ label: "dark"
739
+ }]);
734
740
  }
735
741
  function collectFacts(app, scheme, designSystem) {
736
742
  const { root, packageJson, rootCandidates } = app;
@@ -836,6 +842,13 @@ async function runInit(options, io, designSystem, fileSystem = nodeFileSystem) {
836
842
  return applyAndInstall(plan, root, io, fileSystem);
837
843
  }
838
844
  // src/create/packageManager.ts
845
+ /** The package managers create installs with, in the order it offers them. */
846
+ const PACKAGE_MANAGERS = [
847
+ "npm",
848
+ "pnpm",
849
+ "yarn",
850
+ "bun"
851
+ ];
839
852
  /**
840
853
  * The package manager that ran `create`, from the user agent it gives the commands it starts
841
854
  * (`pnpm/10.4.1 npm/? node/v24.1.0 ...`), else npm. A new app has no lockfile to read it from.
@@ -870,7 +883,7 @@ function formatRunScript({ name }, script) {
870
883
  return name === "npm" || name === "bun" ? `${name} run ${script}` : `${name} ${script}`;
871
884
  }
872
885
  // package.json
873
- var version = "0.2.0-alpha.1";
886
+ var version = "0.2.0-alpha.2";
874
887
  // src/create/vike/vike.ts
875
888
  /** The versions the starter installs: the ones this package is tested with. */
876
889
  const VERSIONS = {
@@ -893,7 +906,8 @@ const VERSIONS = {
893
906
  /** A version from this package's own manifest, as a range an app takes. */
894
907
  const toRange = (version) => /^\d/.test(version) ? `^${version}` : version;
895
908
  const pickVersions = (names) => Object.fromEntries(names.map((name) => [name, toRange(VERSIONS[name])]));
896
- function createPackageJson({ packageName, isTypeScript, version }) {
909
+ function createPackageJson({ packageName, isTypeScript, rendering, version }) {
910
+ const renderer = rendering === "spa" ? [] : ["@emotion/server"];
897
911
  const packageJson = {
898
912
  name: packageName,
899
913
  private: true,
@@ -908,7 +922,7 @@ function createPackageJson({ packageName, isTypeScript, version }) {
908
922
  dependencies: {
909
923
  "@soroush.tech/design-system": toRange(version),
910
924
  ...pickVersions([
911
- "@emotion/server",
925
+ ...renderer,
912
926
  "react",
913
927
  "react-dom",
914
928
  "vike"
@@ -984,13 +998,14 @@ const ITEMS_LINK = ` <Link href="/items" underline="hover">
984
998
  Items
985
999
  </Link>
986
1000
  `;
987
- function createSources({ title, isTypeScript, scheme, hasSampleData }) {
988
- const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
989
- const x = isTypeScript ? "ts" : "js";
990
- return {
991
- config: `${t("import type { Config } from 'vike/types'\n\n")}// The settings of every page: https://vike.dev/config
992
- export default {
993
- // Isomorphic: every page is HTML at build time, then the app moves between pages in the
1001
+ /** The layout's light and dark switch, in a page that has JavaScript. */
1002
+ const SCHEME_SWITCH = ` <Button size="sm" variant="outlined" onClick={() => setScheme(otherScheme)}>
1003
+ {otherScheme}
1004
+ </Button>
1005
+ `;
1006
+ /** The settings of each rendering, in +config. */
1007
+ const CONFIG_SETTINGS = {
1008
+ isomorphic: ` // Isomorphic: every page is HTML at build time, then the app moves between pages in the
994
1009
  // browser, with no reload.
995
1010
  prerender: true,
996
1011
  clientRouting: true,
@@ -998,7 +1013,40 @@ export default {
998
1013
  // +Layout is a setting of this app's own: the component every page renders inside.
999
1014
  meta: {
1000
1015
  Layout: { env: { server: true, client: true } },
1001
- },
1016
+ },`,
1017
+ spa: ` // SPA: every page is an empty HTML shell from the build, which the browser renders; the app
1018
+ // moves between pages with no reload.
1019
+ prerender: true,
1020
+ clientRouting: true,
1021
+ // The page and +Layout, a setting of this app's own, load in the browser only.
1022
+ meta: {
1023
+ Page: { env: { server: false, client: true } },
1024
+ Layout: { env: { server: false, client: true } },
1025
+ },`,
1026
+ ssg: ` // SSG: every page is HTML at build time, with no JavaScript in the browser: a link loads the
1027
+ // next page.
1028
+ prerender: true,
1029
+ // The page and +Layout, a setting of this app's own, load at build time only.
1030
+ meta: {
1031
+ Page: { env: { server: true, client: false } },
1032
+ Layout: { env: { server: true, client: false } },
1033
+ },`
1034
+ };
1035
+ /** What the second page says of how it got there. */
1036
+ const ABOUT_TEXT = {
1037
+ isomorphic: `A second page: it is HTML with its styles from the build, and the app moves to it without a
1038
+ reload.`,
1039
+ spa: `A second page: the browser renders it, with its styles, and the app moves to it without a
1040
+ reload.`,
1041
+ ssg: "A second page: it is HTML with its styles from the build, and a link loads it as a new page."
1042
+ };
1043
+ function createSources({ title, isTypeScript, rendering, scheme, hasSampleData }) {
1044
+ const t = (typeScriptOnly) => isTypeScript ? typeScriptOnly : "";
1045
+ const x = isTypeScript ? "ts" : "js";
1046
+ return {
1047
+ config: `${t("import type { Config } from 'vike/types'\n\n")}// The settings of every page: https://vike.dev/config
1048
+ export default {
1049
+ ${CONFIG_SETTINGS[rendering]}
1002
1050
  }${t(" satisfies Config")}
1003
1051
  `,
1004
1052
  PageShell: `import { StrictMode } from 'react'
@@ -1006,9 +1054,8 @@ import { CacheProvider, styleCache } from '@soroush.tech/design-system/engine'
1006
1054
  ${t("import type { PageContext } from 'vike/types'\n")}import { PageContextProvider } from './usePageContext'
1007
1055
 
1008
1056
  /**
1009
- * The page inside its +Layout, the same on the server and in the browser. The Emotion cache is the
1010
- * design system's, so the server can find the styles the page used, and every component of the
1011
- * page can read its pageContext.
1057
+ * The page inside its +Layout. The Emotion cache is the design system's, so the styles the page
1058
+ * uses are found where it is drawn, and every component of the page can read its pageContext.
1012
1059
  */
1013
1060
  export function PageShell({ pageContext }${t(": { readonly pageContext: PageContext }")}) {
1014
1061
  const { Page, config } = pageContext
@@ -1029,6 +1076,34 @@ export function PageShell({ pageContext }${t(": { readonly pageContext: PageCont
1029
1076
  </StrictMode>
1030
1077
  )
1031
1078
  }
1079
+ `,
1080
+ spaOnRenderHtml: `import { escapeInject } from 'vike/server'
1081
+ ${t("import type { OnRenderHtmlSync } from 'vike/types'\n")}
1082
+ /** The page's HTML shell, from the build: the browser renders the page in #root. */
1083
+ export const onRenderHtml${t(": OnRenderHtmlSync")} = () => {
1084
+ return escapeInject\`<!doctype html>
1085
+ <html lang="en">
1086
+ <head>
1087
+ <meta charset="UTF-8" />
1088
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1089
+ <title>${title}</title>
1090
+ </head>
1091
+ <body>
1092
+ <div id="root"></div>
1093
+ </body>
1094
+ </html>\`
1095
+ }
1096
+ `,
1097
+ spaOnRenderClient: `import { createRoot${t(", type Root")} } from 'react-dom/client'
1098
+ ${t("import type { OnRenderClientSync } from 'vike/types'\n")}import { PageShell } from './PageShell'
1099
+
1100
+ let root${t(": Root | undefined")}
1101
+
1102
+ /** Draws the page in the browser, and each page the app moves to. */
1103
+ export const onRenderClient${t(": OnRenderClientSync")} = (pageContext) => {
1104
+ root ??= createRoot(document.getElementById('root')${t("!")})
1105
+ root.render(<PageShell pageContext={pageContext} />)
1106
+ }
1032
1107
  `,
1033
1108
  onRenderHtml: `import createEmotionServer from '@emotion/server/create-instance'
1034
1109
  import { renderToString } from 'react-dom/server'
@@ -1075,7 +1150,19 @@ export const onRenderClient${t(": OnRenderClientSync")} = (pageContext) => {
1075
1150
  }
1076
1151
  }
1077
1152
  `,
1078
- Layout: `import { useState${t(", type ReactNode")} } from 'react'
1153
+ Layout: `${rendering === "ssg" ? `${t("import type { ReactNode } from 'react'\n")}import { Flex } from '@soroush.tech/design-system/Flex'
1154
+ import { Link } from '@soroush.tech/design-system/Link'
1155
+ import { Typography } from '@soroush.tech/design-system/Typography'
1156
+ import { View } from '@soroush.tech/design-system/View'
1157
+ import { Providers } from '../theme/Providers'
1158
+
1159
+ /**
1160
+ * The frame every page renders in, inside the app's providers. A page has no JavaScript in the
1161
+ * browser, so it is drawn in the default scheme, which src/theme/Providers.${x} sets.
1162
+ */
1163
+ export default function Layout({ children }${t(": { readonly children: ReactNode }")}) {
1164
+ return (
1165
+ <Providers>` : `import { useState${t(", type ReactNode")} } from 'react'
1079
1166
  import { Button } from '@soroush.tech/design-system/Button'
1080
1167
  import { Flex } from '@soroush.tech/design-system/Flex'
1081
1168
  import { Link } from '@soroush.tech/design-system/Link'
@@ -1091,7 +1178,7 @@ export default function Layout({ children }${t(": { readonly children: ReactNode
1091
1178
  const [scheme, setScheme] = useState${t("<'light' | 'dark'>")}('${scheme}')
1092
1179
  const otherScheme = scheme === 'light' ? 'dark' : 'light'
1093
1180
  return (
1094
- <Providers scheme={scheme}>
1181
+ <Providers scheme={scheme}>`}
1095
1182
  <Flex
1096
1183
  as="header"
1097
1184
  flexDirection="row"
@@ -1112,10 +1199,7 @@ export default function Layout({ children }${t(": { readonly children: ReactNode
1112
1199
  <Link href="/about" underline="hover">
1113
1200
  About
1114
1201
  </Link>
1115
- ${hasSampleData ? ITEMS_LINK : ""} <Button size="sm" variant="outlined" onClick={() => setScheme(otherScheme)}>
1116
- {otherScheme}
1117
- </Button>
1118
- </Flex>
1202
+ ${hasSampleData ? ITEMS_LINK : ""}${rendering === "ssg" ? "" : SCHEME_SWITCH} </Flex>
1119
1203
  </Flex>
1120
1204
  <View as="main" px={3} py={4}>
1121
1205
  {children}
@@ -1154,8 +1238,7 @@ export default function Page() {
1154
1238
  <Flex gap={2}>
1155
1239
  <Typography variant="h2">About</Typography>
1156
1240
  <Typography color="secondary">
1157
- A second page: it is HTML with its styles from the build, and the app moves to it without a
1158
- reload.
1241
+ ${ABOUT_TEXT[rendering]}
1159
1242
  </Typography>
1160
1243
  </Flex>
1161
1244
  )
@@ -1378,19 +1461,34 @@ export default function Page() {
1378
1461
  }
1379
1462
  ];
1380
1463
  }
1381
- function createReadme({ title, isTypeScript, hasSampleData }) {
1464
+ /** How the README says each rendering works, and which files render the pages. */
1465
+ const README_RENDERING = {
1466
+ isomorphic: {
1467
+ summary: "prerendered at build time with its styles in the HTML, then moving between pages with no reload.",
1468
+ renderers: "`+onRenderHtml` and `+onRenderClient` render the pages, with the styles each page uses in its HTML."
1469
+ },
1470
+ spa: {
1471
+ summary: "a single-page app: each page is an HTML shell from the build, rendered in the browser, which moves between pages with no reload.",
1472
+ renderers: "`+onRenderHtml` writes the HTML shell of each page, and `+onRenderClient` renders the page in it."
1473
+ },
1474
+ ssg: {
1475
+ summary: "every page prerendered to HTML at build time, with its styles, and no JavaScript in the browser.",
1476
+ renderers: "`+onRenderHtml` renders the pages to HTML, with the styles each page uses."
1477
+ }
1478
+ };
1479
+ function createReadme({ title, isTypeScript, rendering, hasSampleData }) {
1382
1480
  const x = isTypeScript ? "ts" : "js";
1481
+ const { summary, renderers } = README_RENDERING[rendering];
1383
1482
  return `# ${title}
1384
1483
 
1385
- A [Vike](https://vike.dev) app on the [@soroush.tech design system](https://docs.soroush.tech),
1386
- prerendered at build time with its styles in the HTML, then moving between pages with no reload.
1484
+ A [Vike](https://vike.dev) app on the [@soroush.tech design system](https://docs.soroush.tech):
1485
+ ${summary}
1387
1486
 
1388
1487
  - \`npm run dev\` starts it, \`npm run build\` builds it, and \`npm run preview\` serves the build.
1389
1488
  - \`src/pages/\` holds the pages: a folder per route, each with its \`+Page\`.
1390
1489
  - \`src/pages/+Layout.${x}x\` is the frame every page renders in, inside the app's providers.
1391
1490
  - \`src/theme/themes.${x}\` holds the light and the dark theme: make them your own.
1392
- - \`src/pages/+onRenderHtml.${x}x\` and \`+onRenderClient.${x}x\` render the pages, with the styles each
1393
- page uses in its HTML.
1491
+ - In \`src/pages/\`, ${renderers}
1394
1492
  ${hasSampleData ? `- \`src/pages/items/\` lists the sample items of \`src/data/items.${x}\`, with a page for each.
1395
1493
  Their \`+data\` hooks read the data at build time: make them fetch your own.
1396
1494
  ` : ""}
@@ -1400,9 +1498,11 @@ https://docs.soroush.tech/design-system/getting-started/installation/#fonts
1400
1498
  }
1401
1499
  /** The files of the Vike app `facts` describe. */
1402
1500
  function createFiles(facts) {
1403
- const { isTypeScript, scheme } = facts;
1501
+ const { isTypeScript, rendering, scheme } = facts;
1404
1502
  const x = isTypeScript ? "ts" : "js";
1405
1503
  const sources = createSources(facts);
1504
+ const isSpa = rendering === "spa";
1505
+ const onRenderClient = rendering === "ssg" ? void 0 : isSpa ? sources.spaOnRenderClient : sources.onRenderClient;
1406
1506
  return [
1407
1507
  {
1408
1508
  path: "package.json",
@@ -1454,12 +1554,12 @@ function createFiles(facts) {
1454
1554
  },
1455
1555
  {
1456
1556
  path: `src/pages/+onRenderHtml.${x}x`,
1457
- content: sources.onRenderHtml
1557
+ content: isSpa ? sources.spaOnRenderHtml : sources.onRenderHtml
1458
1558
  },
1459
- {
1559
+ ...onRenderClient ? [{
1460
1560
  path: `src/pages/+onRenderClient.${x}x`,
1461
- content: sources.onRenderClient
1462
- },
1561
+ content: onRenderClient
1562
+ }] : [],
1463
1563
  {
1464
1564
  path: `src/pages/+Layout.${x}x`,
1465
1565
  content: sources.Layout
@@ -1479,12 +1579,19 @@ function createFiles(facts) {
1479
1579
  ...facts.hasSampleData ? createSampleDataFiles(facts) : []
1480
1580
  ];
1481
1581
  }
1482
- // src/create/starters.ts
1483
- /** The starters, by the name `--framework` takes. The first is the default. */
1484
- const STARTERS = { vike: {
1582
+ const vikeStarter = {
1485
1583
  title: "Vike",
1486
1584
  createFiles
1487
- } };
1585
+ };
1586
+ // src/create/starters.ts
1587
+ /** The renderings, in the order create offers them. The first is the default. */
1588
+ const RENDERINGS = [
1589
+ "isomorphic",
1590
+ "spa",
1591
+ "ssg"
1592
+ ];
1593
+ /** The starters, by the name `--framework` takes. The first is the default. */
1594
+ const STARTERS = { vike: vikeStarter };
1488
1595
  // src/create/create.ts
1489
1596
  const DEFAULT_NAME = "my-app";
1490
1597
  const APP_NAME = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
@@ -1537,9 +1644,42 @@ function isInsideRepository(folder, io) {
1537
1644
  const { status, stdout } = io.run("git", ["rev-parse", "--is-inside-work-tree"], { cwd: folder });
1538
1645
  return status === 0 && stdout.trim() === "true";
1539
1646
  }
1647
+ const YES_OR_NO = [{
1648
+ value: "yes",
1649
+ label: "Yes"
1650
+ }, {
1651
+ value: "no",
1652
+ label: "No"
1653
+ }];
1540
1654
  async function askLanguage(io) {
1541
- const answer = await io.ask("TypeScript or JavaScript? (TypeScript) ");
1542
- return !/^j(s|avascript)?$/i.test(answer.trim());
1655
+ return await io.select("Language", [{
1656
+ value: "ts",
1657
+ label: "TypeScript (recommended)"
1658
+ }, {
1659
+ value: "js",
1660
+ label: "JavaScript"
1661
+ }]) === "ts";
1662
+ }
1663
+ /** Asks for the package manager, starting on the one that ran create. */
1664
+ async function askPackageManager(io, detected) {
1665
+ const choices = PACKAGE_MANAGERS.map((name) => ({
1666
+ value: name,
1667
+ label: name === detected ? `${name} (the one that ran create)` : name
1668
+ }));
1669
+ return await io.select("Package manager", choices, PACKAGE_MANAGERS.indexOf(detected));
1670
+ }
1671
+ /**
1672
+ * The package manager to install with, or why it cannot be used: one other than the one that ran
1673
+ * create must answer `--version`, which also says whether a yarn is Berry.
1674
+ */
1675
+ function resolvePackageManager(name, detected, io) {
1676
+ if (name === detected.name) return detected;
1677
+ const { status, stdout } = io.run(name, ["--version"], { cwd: io.cwd });
1678
+ if (status !== 0) return { refusal: `${name} is not installed: install it, or pick another package manager.` };
1679
+ return {
1680
+ name,
1681
+ isYarnBerry: name === "yarn" && Number.parseInt(stdout, 10) >= 2
1682
+ };
1543
1683
  }
1544
1684
  async function askTitle(io, name) {
1545
1685
  return (await io.ask(`App title? (${name}) `)).trim() || name;
@@ -1547,9 +1687,21 @@ async function askTitle(io, name) {
1547
1687
  async function askName(io) {
1548
1688
  return (await io.ask(`App name? (${DEFAULT_NAME}) `)).trim() || DEFAULT_NAME;
1549
1689
  }
1690
+ /** What the rendering question says of each one. */
1691
+ const RENDERING_LABELS = {
1692
+ isomorphic: "Isomorphic (recommended): HTML from the build, then no reload",
1693
+ spa: "SPA: rendered in the browser",
1694
+ ssg: "SSG: HTML only, no JavaScript"
1695
+ };
1696
+ async function askRendering(io) {
1697
+ const choices = RENDERINGS.map((value) => ({
1698
+ value,
1699
+ label: RENDERING_LABELS[value]
1700
+ }));
1701
+ return await io.select("Rendering", choices);
1702
+ }
1550
1703
  async function askSampleData(io) {
1551
- const answer = await io.ask("Add sample data pages? (y/N) ");
1552
- return /^y(es)?$/i.test(answer.trim());
1704
+ return await io.select("Add sample data pages?", YES_OR_NO, 1) === "yes";
1553
1705
  }
1554
1706
  /** Whether to create the app: never on a dry run or with no terminal, else on --yes or a yes. */
1555
1707
  async function isApproved(options, isPreviewOnly, io) {
@@ -1562,8 +1714,7 @@ async function isApproved(options, isPreviewOnly, io) {
1562
1714
  return false;
1563
1715
  }
1564
1716
  if (options.isConfirmed) return true;
1565
- const answer = (await io.ask("Create it? (Y/n) ")).trim();
1566
- const isYes = answer === "" || /^y(es)?$/i.test(answer);
1717
+ const isYes = await io.select("Create it?", YES_OR_NO) === "yes";
1567
1718
  if (!isYes) io.write("Nothing was written.\n");
1568
1719
  return isYes;
1569
1720
  }
@@ -1627,28 +1778,35 @@ async function runCreate(options, io, designSystem, { starters = STARTERS, fileS
1627
1778
  io.write(`${nameRefusal}\n`);
1628
1779
  return 1;
1629
1780
  }
1781
+ const target = join(realpathSync(io.cwd), name);
1782
+ const folder = getFolderState(target, name);
1783
+ if (typeof folder === "object") {
1784
+ io.write(`${folder.refusal}\n`);
1785
+ return 1;
1786
+ }
1630
1787
  const title = (options.title ?? (canAsk ? await askTitle(io, name) : name)).trim() || name;
1631
1788
  if (isRefusedTitle(title)) {
1632
1789
  io.write(`${title} is not a title create can use: it cannot hold \` $ { } < > or \\.\n`);
1633
1790
  return 1;
1634
1791
  }
1635
1792
  const packageName = toPackageName(name);
1636
- const target = join(realpathSync(io.cwd), name);
1637
- const folder = getFolderState(target, name);
1638
- if (typeof folder === "object") {
1639
- io.write(`${folder.refusal}\n`);
1793
+ const isTypeScript = options.isTypeScript ?? (canAsk ? await askLanguage(io) : true);
1794
+ const detected = readPackageManager(userAgent);
1795
+ const packageManager = resolvePackageManager(options.packageManager ?? (canAsk ? await askPackageManager(io, detected.name) : detected.name), detected, io);
1796
+ if ("refusal" in packageManager) {
1797
+ io.write(`${packageManager.refusal}\n`);
1640
1798
  return 1;
1641
1799
  }
1642
- const isTypeScript = options.isTypeScript ?? (canAsk ? await askLanguage(io) : true);
1800
+ const rendering = options.rendering ?? (canAsk ? await askRendering(io) : RENDERINGS[0]);
1643
1801
  const scheme = options.scheme ?? (canAsk ? await askScheme(io) : "light");
1644
1802
  const hasSampleData = options.hasSampleData ?? (canAsk ? await askSampleData(io) : false);
1645
- const packageManager = readPackageManager(userAgent);
1646
1803
  const plan = {
1647
1804
  creates: starter.createFiles({
1648
1805
  name,
1649
1806
  packageName,
1650
1807
  title,
1651
1808
  isTypeScript,
1809
+ rendering,
1652
1810
  scheme,
1653
1811
  hasSampleData,
1654
1812
  version: designSystem.version
@@ -1660,7 +1818,8 @@ async function runCreate(options, io, designSystem, { starters = STARTERS, fileS
1660
1818
  };
1661
1819
  const language = isTypeScript ? "TypeScript" : "JavaScript";
1662
1820
  const packageNote = packageName === name ? "" : ` (package ${packageName})`;
1663
- io.write(`create will make ${name}${packageNote}, a ${starter.title} app in ${language}, in ./${name}:\n\n`);
1821
+ const renderingName = rendering === "isomorphic" ? rendering : rendering.toUpperCase();
1822
+ io.write(`create will make ${name}${packageNote}, a ${starter.title} app in ${language} (${renderingName}), in ./${name}:\n\n`);
1664
1823
  io.write(`${formatPlan(plan)}\n`);
1665
1824
  if (!await isApproved(options, isPreviewOnly, io)) return 0;
1666
1825
  return writeAndInstall({
@@ -1671,8 +1830,57 @@ async function runCreate(options, io, designSystem, { starters = STARTERS, fileS
1671
1830
  packageManager
1672
1831
  }, options, io, fileSystem);
1673
1832
  }
1833
+ // src/prompt.ts
1834
+ /** Stopped with Ctrl+C or Escape, before an answer. */
1835
+ var CancelledError = class extends Error {
1836
+ constructor() {
1837
+ super("Stopped before an answer.");
1838
+ this.name = "CancelledError";
1839
+ }
1840
+ };
1841
+ /** Reads a key as Node's `keypress` event names it. */
1842
+ function readChoiceKey(key) {
1843
+ if (!key) return "none";
1844
+ if (key.ctrl && key.name === "c" || key.name === "escape") return "cancel";
1845
+ if (key.name === "up" || key.name === "k") return "up";
1846
+ if (key.name === "down" || key.name === "j") return "down";
1847
+ if (key.name === "space") return "toggle";
1848
+ if (key.name === "return" || key.name === "enter") return "submit";
1849
+ return "none";
1850
+ }
1851
+ /** The state after `key`: the pointer wraps around the ends, and space picks or unpicks. */
1852
+ function updateChoice(state, key, choices) {
1853
+ const { cursor, picked } = state;
1854
+ if (key === "up") return {
1855
+ cursor: (cursor + choices.length - 1) % choices.length,
1856
+ picked
1857
+ };
1858
+ if (key === "down") return {
1859
+ cursor: (cursor + 1) % choices.length,
1860
+ picked
1861
+ };
1862
+ if (!picked) return state;
1863
+ const { value } = choices[cursor];
1864
+ const isPicked = picked.includes(value);
1865
+ return {
1866
+ cursor,
1867
+ picked: choices.map((choice) => choice.value).filter((candidate) => candidate === value ? !isPicked : picked.includes(candidate))
1868
+ };
1869
+ }
1870
+ /** The values a submitted choice answers with. */
1871
+ const getAnswer = ({ cursor, picked }, choices) => picked ? [...picked] : [choices[cursor].value];
1872
+ /** The question and its choices, as drawn while the person picks. Ends with a line break. */
1873
+ function formatChoice(question, { cursor, picked }, choices) {
1874
+ return `? ${question} (${picked ? "space to pick, enter when done" : "arrows to move, enter to pick"})\n${choices.map(({ value, label }, index) => {
1875
+ return `${index === cursor ? ">" : " "} ${picked ? picked.includes(value) ? "[x] " : "[ ] " : ""}${label}`;
1876
+ }).join("\n")}\n`;
1877
+ }
1878
+ /** The question with its answer, as it stays once picked. Ends with a line break. */
1879
+ function formatAnswer(question, values, choices) {
1880
+ return `? ${question}: ${choices.filter(({ value }) => values.includes(value)).map(({ label }) => label).join(", ") || "none"}\n`;
1881
+ }
1674
1882
  // src/main.ts
1675
- const BIN = "npx @soroush.tech/design-system";
1883
+ const BIN = "npx @soroush.design/cli";
1676
1884
  /** The help with no command: the commands, and how to get each one's own help. */
1677
1885
  const USAGE = `Usage: ${BIN} <command> [options]
1678
1886
 
@@ -1713,6 +1921,9 @@ Options:
1713
1921
  --title <text> what the app's pages call it: the name when not given
1714
1922
  --framework <name> the app's framework: ${[`${defaultFramework} (the default)`, ...otherFrameworks].join(", ")}
1715
1923
  --ts, --js TypeScript (the default) or JavaScript
1924
+ --pm <name> the package manager: npm, pnpm, yarn or bun; the one that ran create
1925
+ when not given
1926
+ --render <name> how pages render: isomorphic (the default), spa or ssg
1716
1927
  --scheme <name> the default color scheme: light (the default) or dark
1717
1928
  --sample-data add a list of sample items, and a page for each
1718
1929
  --no-git do not run git init
@@ -1741,6 +1952,8 @@ const OPTIONS = {
1741
1952
  title: { type: "string" },
1742
1953
  ts: { type: "boolean" },
1743
1954
  js: { type: "boolean" },
1955
+ pm: { type: "string" },
1956
+ render: { type: "string" },
1744
1957
  "sample-data": { type: "boolean" },
1745
1958
  "no-git": { type: "boolean" }
1746
1959
  };
@@ -1752,6 +1965,8 @@ const OWN_OPTIONS = {
1752
1965
  "title",
1753
1966
  "ts",
1754
1967
  "js",
1968
+ "pm",
1969
+ "render",
1755
1970
  "sample-data",
1756
1971
  "no-git"
1757
1972
  ]
@@ -1768,9 +1983,19 @@ function findMisuse(command, extra, used) {
1768
1983
  }
1769
1984
  /**
1770
1985
  * Reads the command line and runs the command, for `designSystem`: the package of
1771
- * `@soroush.tech/design-system` the command installs. Returns the exit code.
1986
+ * `@soroush.tech/design-system` the command installs. Returns the exit code: 130 when the person
1987
+ * stops it at a question, which is before anything is written.
1772
1988
  */
1773
1989
  async function main(argv, io, designSystem) {
1990
+ try {
1991
+ return await runCommandLine(argv, io, designSystem);
1992
+ } catch (error) {
1993
+ if (!(error instanceof CancelledError)) throw error;
1994
+ io.write("Stopped: nothing was written.\n");
1995
+ return 130;
1996
+ }
1997
+ }
1998
+ async function runCommandLine(argv, io, designSystem) {
1774
1999
  let parsed;
1775
2000
  try {
1776
2001
  parsed = parseArgs({
@@ -1808,6 +2033,16 @@ async function main(argv, io, designSystem) {
1808
2033
  io.write("--ts and --js do not go together: give one.\n");
1809
2034
  return 1;
1810
2035
  }
2036
+ const { render } = values;
2037
+ if (render !== void 0 && !RENDERINGS.includes(render)) {
2038
+ io.write(`--render is ${RENDERINGS.join(", ")}, not ${render}.\n`);
2039
+ return 1;
2040
+ }
2041
+ const { pm } = values;
2042
+ if (pm !== void 0 && !PACKAGE_MANAGERS.includes(pm)) {
2043
+ io.write(`--pm is ${PACKAGE_MANAGERS.join(", ")}, not ${pm}.\n`);
2044
+ return 1;
2045
+ }
1811
2046
  const isConfirmed = Boolean(values.yes);
1812
2047
  const isDryRun = Boolean(values["dry-run"]);
1813
2048
  if (command === "create") {
@@ -1817,6 +2052,8 @@ async function main(argv, io, designSystem) {
1817
2052
  title: values.title,
1818
2053
  framework: values.framework,
1819
2054
  isTypeScript,
2055
+ packageManager: pm,
2056
+ rendering: render,
1820
2057
  scheme,
1821
2058
  hasSampleData: values["sample-data"],
1822
2059
  isConfirmed,
@@ -1841,6 +2078,52 @@ function toWindowsCommandLine(command, args) {
1841
2078
  for (const part of [command, ...args]) if (!PLAIN_ARGUMENT.test(part)) throw new Error(`init does not run the argument ${part}`);
1842
2079
  return [command, ...args.map((arg) => `"${arg}"`)].join(" ");
1843
2080
  }
2081
+ const HIDE_CURSOR = "\x1B[?25l";
2082
+ const SHOW_CURSOR = "\x1B[?25h";
2083
+ const eraseLines = (count) => count > 0 ? `\u001B[${count}A\r\u001B[J` : "";
2084
+ /**
2085
+ * Draws a choice on the terminal and redraws it on each key, until Enter answers it or Ctrl+C or
2086
+ * Escape stops it. The terminal is in raw mode only while the choice is open.
2087
+ */
2088
+ function runChoice(stdin, stdout, question, choices, start) {
2089
+ return new Promise((resolve, reject) => {
2090
+ let state = start;
2091
+ let drawnLines = 0;
2092
+ const draw = (text) => {
2093
+ stdout.write(eraseLines(drawnLines) + text);
2094
+ drawnLines = text.split("\n").length - 1;
2095
+ };
2096
+ const wasRaw = Boolean(stdin.isRaw);
2097
+ const close = (text) => {
2098
+ stdin.off("keypress", onKeypress);
2099
+ stdin.setRawMode?.(wasRaw);
2100
+ stdin.pause();
2101
+ draw(text);
2102
+ stdout.write(SHOW_CURSOR);
2103
+ };
2104
+ function onKeypress(_text, key) {
2105
+ const action = readChoiceKey(key);
2106
+ if (action === "none") return;
2107
+ if (action === "cancel") {
2108
+ close(`? ${question}\n`);
2109
+ reject(new CancelledError());
2110
+ } else if (action === "submit") {
2111
+ const answer = getAnswer(state, choices);
2112
+ close(formatAnswer(question, answer, choices));
2113
+ resolve(answer);
2114
+ } else {
2115
+ state = updateChoice(state, action, choices);
2116
+ draw(formatChoice(question, state, choices));
2117
+ }
2118
+ }
2119
+ emitKeypressEvents(stdin);
2120
+ stdin.setRawMode?.(true);
2121
+ stdin.on("keypress", onKeypress);
2122
+ stdin.resume();
2123
+ stdout.write(HIDE_CURSOR);
2124
+ draw(formatChoice(question, state, choices));
2125
+ });
2126
+ }
1844
2127
  function createNodeIo({ stdin = process.stdin, stdout = process.stdout, platform = process.platform, cwd = process.cwd() } = {}) {
1845
2128
  return {
1846
2129
  cwd,
@@ -1859,6 +2142,17 @@ function createNodeIo({ stdin = process.stdin, stdout = process.stdout, platform
1859
2142
  prompt.close();
1860
2143
  }
1861
2144
  },
2145
+ select: async (question, choices, initial = 0) => {
2146
+ const [value] = await runChoice(stdin, stdout, question, choices, {
2147
+ cursor: initial,
2148
+ picked: void 0
2149
+ });
2150
+ return value;
2151
+ },
2152
+ selectMany: (question, choices, initial = []) => runChoice(stdin, stdout, question, choices, {
2153
+ cursor: 0,
2154
+ picked: initial
2155
+ }),
1862
2156
  run: (command, args, { cwd: directory, env = {}, showOutput = false }) => {
1863
2157
  const options = {
1864
2158
  cwd: directory,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soroush.design/cli",
3
- "version": "0.2.0-alpha.1",
3
+ "version": "0.2.0-alpha.2",
4
4
  "description": "The command line of the @soroush.tech design system: init sets it up in an existing React app, and create starts a new one, each showing every change first.",
5
5
  "keywords": [
6
6
  "cli",
@@ -61,7 +61,7 @@
61
61
  "typecheck": "tsc --noEmit",
62
62
  "test": "vitest run",
63
63
  "test:coverage": "vitest run --coverage",
64
- "test:types": "pnpm --filter @soroush.tech/design-system build && tsc -p type-tests/init/tsconfig.json && tsc -p type-tests/tsconfig.create-vike.json"
64
+ "test:types": "pnpm --filter @soroush.tech/design-system build && tsc -p type-tests/init/tsconfig.json && tsc -p type-tests/tsconfig.create-vike.json && tsc -p type-tests/tsconfig.create-vike-spa.json && tsc -p type-tests/tsconfig.create-vike-ssg.json"
65
65
  },
66
66
  "module": "./dist/index.mjs"
67
67
  }