create-astro 0.9.0 → 0.11.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/dist/index.js CHANGED
@@ -1,31 +1,13 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
- var __hasOwnProp = Object.prototype.hasOwnProperty;
4
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __spreadValues = (a, b) => {
7
- for (var prop in b || (b = {}))
8
- if (__hasOwnProp.call(b, prop))
9
- __defNormalProp(a, prop, b[prop]);
10
- if (__getOwnPropSymbols)
11
- for (var prop of __getOwnPropSymbols(b)) {
12
- if (__propIsEnum.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- }
15
- return a;
16
- };
17
1
  import fs from "fs";
18
2
  import path from "path";
19
3
  import { bold, cyan, gray, green, red, yellow } from "kleur/colors";
20
- import fetch from "node-fetch";
21
4
  import prompts from "prompts";
22
5
  import degit from "degit";
23
6
  import yargs from "yargs-parser";
24
7
  import ora from "ora";
25
- import { FRAMEWORKS, COUNTER_COMPONENTS } from "./frameworks.js";
26
8
  import { TEMPLATES } from "./templates.js";
27
- import { createConfig } from "./config.js";
28
9
  import { logger, defaultLogLevel } from "./logger.js";
10
+ import { execa, execaCommand } from "execa";
29
11
  const cleanArgv = process.argv.filter((arg) => arg !== "--");
30
12
  const args = yargs(cleanArgv);
31
13
  prompts.override(args);
@@ -42,13 +24,12 @@ function isEmpty(dirPath) {
42
24
  return !fs.existsSync(dirPath) || fs.readdirSync(dirPath).length === 0;
43
25
  }
44
26
  const { version } = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
45
- const POSTPROCESS_FILES = ["package.json", "astro.config.mjs", "CHANGELOG.md"];
27
+ const FILES_TO_REMOVE = [".stackblitzrc", "sandbox.config.json", "CHANGELOG.md"];
46
28
  async function main() {
29
+ const pkgManager = pkgManagerFromUserAgent(process.env.npm_config_user_agent);
47
30
  logger.debug("Verbose logging turned on");
48
31
  console.log(`
49
32
  ${bold("Welcome to Astro!")} ${gray(`(create-astro v${version})`)}`);
50
- console.log(`If you encounter a problem, visit ${cyan("https://github.com/withastro/astro/issues")} to search or file a new issue.
51
- `);
52
33
  let spinner = ora({ color: "green", text: "Prepare for liftoff." });
53
34
  spinner.succeed();
54
35
  let cwd = args["_"][2];
@@ -60,7 +41,7 @@ ${bold("Welcome to Astro!")} ${gray(`(create-astro v${version})`)}`);
60
41
  acknowledgeProjectDir.succeed();
61
42
  }
62
43
  if (!cwd || !isEmpty(cwd)) {
63
- const notEmptyMsg = (dirPath) => `"${bold(dirPath)}" is not empty. Please clear contents or choose a different path.`;
44
+ const notEmptyMsg = (dirPath) => `"${bold(dirPath)}" is not empty!`;
64
45
  if (!isEmpty(cwd)) {
65
46
  let rejectProjectDir = ora({ color: "red", text: notEmptyMsg(cwd) });
66
47
  rejectProjectDir.fail();
@@ -94,7 +75,7 @@ ${bold("Welcome to Astro!")} ${gray(`(create-astro v${version})`)}`);
94
75
  process.exit(1);
95
76
  }
96
77
  const hash = args.commit ? `#${args.commit}` : "";
97
- const templateTarget = options.template.includes("/") ? options.template : `withastro/astro/examples/${options.template}#latest`;
78
+ const templateTarget = `withastro/astro/examples/${options.template}#latest`;
98
79
  const emitter = degit(`${templateTarget}${hash}`, {
99
80
  cache: false,
100
81
  force: true,
@@ -105,111 +86,113 @@ ${bold("Welcome to Astro!")} ${gray(`(create-astro v${version})`)}`);
105
86
  force: true,
106
87
  verbose: defaultLogLevel === "debug" ? true : false
107
88
  });
108
- const selectedTemplate = TEMPLATES.find((template) => template.value === options.template);
109
- let integrations = [];
110
- if ((selectedTemplate == null ? void 0 : selectedTemplate.integrations) === true) {
111
- const result = await prompts([
112
- {
113
- type: "multiselect",
114
- name: "integrations",
115
- message: "Which frameworks would you like to use?",
116
- choices: FRAMEWORKS
117
- }
118
- ]);
119
- integrations = result.integrations;
120
- }
121
89
  spinner = ora({ color: "green", text: "Copying project files..." }).start();
122
- try {
123
- emitter.on("info", (info) => {
124
- logger.debug(info.message);
125
- });
126
- await emitter.clone(cwd);
127
- } catch (err) {
128
- logger.debug(err);
129
- console.error(red(err.message));
130
- if (err.message === "zlib: unexpected end of file") {
131
- console.log(yellow("This seems to be a cache related problem. Remove the folder '~/.degit/github/withastro' to fix this error."));
132
- console.log(yellow("For more information check out this issue: https://github.com/withastro/astro/issues/655"));
133
- }
134
- if (err.code === "MISSING_REF") {
135
- console.log(yellow("This seems to be an issue with degit. Please check if you have 'git' installed on your system, and install it if you don't have (https://git-scm.com)."));
136
- console.log(yellow("If you do have 'git' installed, please run this command with the --verbose flag and file a new issue with the command output here: https://github.com/withastro/astro/issues"));
137
- }
138
- spinner.fail();
139
- process.exit(1);
140
- }
141
- await Promise.all(POSTPROCESS_FILES.map(async (file) => {
142
- const fileLoc = path.resolve(path.join(cwd, file));
143
- switch (file) {
144
- case "CHANGELOG.md": {
145
- if (fs.existsSync(fileLoc)) {
146
- await fs.promises.unlink(fileLoc);
147
- }
148
- break;
90
+ if (!args.dryrun) {
91
+ try {
92
+ emitter.on("info", (info) => {
93
+ logger.debug(info.message);
94
+ });
95
+ await emitter.clone(cwd);
96
+ } catch (err) {
97
+ logger.debug(err);
98
+ console.error(red(err.message));
99
+ if (err.message === "zlib: unexpected end of file") {
100
+ console.log(yellow("This seems to be a cache related problem. Remove the folder '~/.degit/github/withastro' to fix this error."));
101
+ console.log(yellow("For more information check out this issue: https://github.com/withastro/astro/issues/655"));
149
102
  }
150
- case "astro.config.mjs": {
151
- if ((selectedTemplate == null ? void 0 : selectedTemplate.integrations) !== true) {
152
- break;
153
- }
154
- await fs.promises.writeFile(fileLoc, createConfig({ integrations }));
155
- break;
156
- }
157
- case "package.json": {
158
- const packageJSON = JSON.parse(await fs.promises.readFile(fileLoc, "utf8"));
159
- delete packageJSON.snowpack;
160
- const integrationEntries = (await Promise.all(integrations.map((integration) => fetch(`https://registry.npmjs.org/${integration.packageName}/latest`).then((res) => res.json()).then((res) => {
161
- let dependencies = [[res["name"], `^${res["version"]}`]];
162
- if (res["peerDependencies"]) {
163
- for (const peer in res["peerDependencies"]) {
164
- dependencies.push([peer, res["peerDependencies"][peer]]);
165
- }
166
- }
167
- return dependencies;
168
- })))).flat(1);
169
- packageJSON.devDependencies = __spreadValues(__spreadValues({}, packageJSON.devDependencies ?? {}), Object.fromEntries(integrationEntries));
170
- packageJSON.devDependencies = Object.fromEntries(Object.entries(packageJSON.devDependencies).sort((a, b) => a[0].localeCompare(b[0])));
171
- await fs.promises.writeFile(fileLoc, JSON.stringify(packageJSON, void 0, 2));
172
- break;
103
+ if (err.code === "MISSING_REF") {
104
+ console.log(yellow("This seems to be an issue with degit. Please check if you have 'git' installed on your system, and install it if you don't have (https://git-scm.com)."));
105
+ console.log(yellow("If you do have 'git' installed, please run this command with the --verbose flag and file a new issue with the command output here: https://github.com/withastro/astro/issues"));
173
106
  }
107
+ spinner.fail();
108
+ process.exit(1);
174
109
  }
175
- }));
176
- if ((selectedTemplate == null ? void 0 : selectedTemplate.value) === "starter") {
177
- let importStatements = [];
178
- let components = [];
179
- await Promise.all(integrations.map(async (integration) => {
180
- const component = COUNTER_COMPONENTS[integration.id];
181
- const componentName = path.basename(component.filename, path.extname(component.filename));
182
- const absFileLoc = path.resolve(cwd, component.filename);
183
- importStatements.push(`import ${componentName} from '${component.filename.replace(/^src/, "..")}';`);
184
- components.push(`<${componentName} client:visible />`);
185
- await fs.promises.writeFile(absFileLoc, component.content);
110
+ await Promise.all(FILES_TO_REMOVE.map(async (file) => {
111
+ const fileLoc = path.resolve(path.join(cwd, file));
112
+ if (fs.existsSync(fileLoc)) {
113
+ return fs.promises.rm(fileLoc, {});
114
+ }
186
115
  }));
187
- const pageFileLoc = path.resolve(path.join(cwd, "src", "pages", "index.astro"));
188
- const content = (await fs.promises.readFile(pageFileLoc)).toString();
189
- const newContent = content.replace(/^(\s*)\/\* ASTRO\:COMPONENT_IMPORTS \*\//gm, (_, indent) => {
190
- return indent + importStatements.join("\n");
191
- }).replace(/^(\s*)<!-- ASTRO:COMPONENT_MARKUP -->/gm, (_, indent) => {
192
- return components.map((ln) => indent + ln).join("\n");
193
- });
194
- await fs.promises.writeFile(pageFileLoc, newContent);
195
116
  }
196
117
  spinner.succeed();
197
118
  console.log(bold(green("\u2714") + " Done!"));
119
+ const installResponse = await prompts({
120
+ type: "confirm",
121
+ name: "install",
122
+ message: `Would you like us to run "${pkgManager} install?"`,
123
+ initial: true
124
+ });
125
+ if (!installResponse) {
126
+ process.exit(0);
127
+ }
128
+ if (installResponse.install) {
129
+ const installExec = execa(pkgManager, ["install"], { cwd });
130
+ const installingPackagesMsg = `Installing packages${emojiWithFallback(" \u{1F4E6}", "...")}`;
131
+ spinner = ora({ color: "green", text: installingPackagesMsg }).start();
132
+ if (!args.dryrun) {
133
+ await new Promise((resolve, reject) => {
134
+ var _a;
135
+ (_a = installExec.stdout) == null ? void 0 : _a.on("data", function(data) {
136
+ spinner.text = `${installingPackagesMsg}
137
+ ${bold(`[${pkgManager}]`)} ${data}`;
138
+ });
139
+ installExec.on("error", (error) => reject(error));
140
+ installExec.on("close", () => resolve());
141
+ });
142
+ }
143
+ spinner.succeed();
144
+ }
145
+ const astroAddCommand = installResponse.install ? "astro add --yes" : `${pkgManagerExecCommand(pkgManager)} astro@latest add --yes`;
146
+ const astroAddResponse = await prompts({
147
+ type: "confirm",
148
+ name: "astroAdd",
149
+ message: `Run "${astroAddCommand}?" This lets you optionally add component frameworks (ex. React), CSS frameworks (ex. Tailwind), and more.`,
150
+ initial: true
151
+ });
152
+ if (!astroAddResponse) {
153
+ process.exit(0);
154
+ }
155
+ if (!astroAddResponse.astroAdd) {
156
+ ora().info(`No problem. You can always run "${pkgManagerExecCommand(pkgManager)} astro add" later!`);
157
+ }
158
+ if (astroAddResponse.astroAdd && !args.dryrun) {
159
+ await execaCommand(astroAddCommand, astroAddCommand === "astro add --yes" ? { cwd, stdio: "inherit", localDir: cwd, preferLocal: true } : { cwd, stdio: "inherit" });
160
+ }
198
161
  console.log("\nNext steps:");
199
162
  let i = 1;
200
163
  const relative = path.relative(process.cwd(), cwd);
201
164
  if (relative !== "") {
202
165
  console.log(` ${i++}: ${bold(cyan(`cd ${relative}`))}`);
203
166
  }
204
- console.log(` ${i++}: ${bold(cyan("npm install"))} (or pnpm install, yarn, etc)`);
167
+ if (!installResponse.install) {
168
+ console.log(` ${i++}: ${bold(cyan(`${pkgManager} install`))}`);
169
+ }
205
170
  console.log(` ${i++}: ${bold(cyan('git init && git add -A && git commit -m "Initial commit"'))} (optional step)`);
206
- console.log(` ${i++}: ${bold(cyan("npm run dev"))} (or pnpm, yarn, etc)`);
171
+ const runCommand = pkgManager === "npm" ? "npm run dev" : `${pkgManager} dev`;
172
+ console.log(` ${i++}: ${bold(cyan(runCommand))}`);
207
173
  console.log(`
208
174
  To close the dev server, hit ${bold(cyan("Ctrl-C"))}`);
209
175
  console.log(`
210
176
  Stuck? Visit us at ${cyan("https://astro.build/chat")}
211
177
  `);
212
178
  }
179
+ function emojiWithFallback(char, fallback) {
180
+ return process.platform !== "win32" ? char : fallback;
181
+ }
182
+ function pkgManagerFromUserAgent(userAgent) {
183
+ if (!userAgent)
184
+ return "npm";
185
+ const pkgSpec = userAgent.split(" ")[0];
186
+ const pkgSpecArr = pkgSpec.split("/");
187
+ return pkgSpecArr[0];
188
+ }
189
+ function pkgManagerExecCommand(pkgManager) {
190
+ if (pkgManager === "pnpm") {
191
+ return "pnpx";
192
+ } else {
193
+ return "npx";
194
+ }
195
+ }
213
196
  export {
214
197
  main,
215
198
  mkdirp
package/dist/templates.js CHANGED
@@ -1,8 +1,7 @@
1
1
  const TEMPLATES = [
2
2
  {
3
- title: "Starter Kit (Generic)",
4
- value: "starter",
5
- integrations: true
3
+ title: "Just the basics",
4
+ value: "basics"
6
5
  },
7
6
  {
8
7
  title: "Blog",
@@ -17,7 +16,7 @@ const TEMPLATES = [
17
16
  value: "portfolio"
18
17
  },
19
18
  {
20
- title: "Minimal",
19
+ title: "Completely empty",
21
20
  value: "minimal"
22
21
  }
23
22
  ];
@@ -1,9 +1,4 @@
1
- export declare const TEMPLATES: ({
1
+ export declare const TEMPLATES: {
2
2
  title: string;
3
3
  value: string;
4
- integrations: boolean;
5
- } | {
6
- title: string;
7
- value: string;
8
- integrations?: undefined;
9
- })[];
4
+ }[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-astro",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "author": "withastro",
6
6
  "license": "MIT",
@@ -31,15 +31,15 @@
31
31
  "@types/degit": "^2.8.3",
32
32
  "@types/prompts": "^2.0.14",
33
33
  "degit": "^2.8.4",
34
+ "execa": "^6.1.0",
34
35
  "kleur": "^4.1.4",
35
- "node-fetch": "^3.2.3",
36
36
  "ora": "^6.1.0",
37
37
  "prompts": "^2.4.2",
38
38
  "yargs-parser": "^21.0.1"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/chai": "^4.3.1",
42
- "@types/mocha": "^9.1.0",
42
+ "@types/mocha": "^9.1.1",
43
43
  "@types/yargs-parser": "^21.0.0",
44
44
  "astro-scripts": "workspace:*",
45
45
  "chai": "^4.3.6",
package/dist/config.js DELETED
@@ -1,23 +0,0 @@
1
- const createConfig = ({ integrations }) => {
2
- if (integrations.length === 0) {
3
- return `import { defineConfig } from 'astro/config';
4
- // https://astro.build/config
5
- export default defineConfig({});
6
- `;
7
- }
8
- const rendererImports = integrations.map((r) => ` import ${r.id} from '${r.packageName}';`);
9
- const rendererIntegrations = integrations.map((r) => ` ${r.id}(),`);
10
- return [
11
- `import { defineConfig } from 'astro/config';`,
12
- ...rendererImports,
13
- `// https://astro.build/config`,
14
- `export default defineConfig({`,
15
- ` integrations: [`,
16
- ...rendererIntegrations,
17
- ` ]`,
18
- `});`
19
- ].join("\n");
20
- };
21
- export {
22
- createConfig
23
- };
@@ -1,134 +0,0 @@
1
- const COUNTER_COMPONENTS = {
2
- preact: {
3
- filename: `src/components/PreactCounter.jsx`,
4
- content: `import { useState } from 'preact/hooks';
5
-
6
- export default function PreactCounter() {
7
- const [count, setCount] = useState(0);
8
- const add = () => setCount((i) => i + 1);
9
- const subtract = () => setCount((i) => i - 1);
10
-
11
- return (
12
- <div id="preact" class="counter">
13
- <button onClick={subtract}>-</button>
14
- <pre>{count}</pre>
15
- <button onClick={add}>+</button>
16
- </div>
17
- );
18
- }
19
- `
20
- },
21
- react: {
22
- filename: `src/components/ReactCounter.jsx`,
23
- content: `import { useState } from 'react';
24
-
25
- export default function ReactCounter() {
26
- const [count, setCount] = useState(0);
27
- const add = () => setCount((i) => i + 1);
28
- const subtract = () => setCount((i) => i - 1);
29
-
30
- return (
31
- <div id="react" className="counter">
32
- <button onClick={subtract}>-</button>
33
- <pre>{count}</pre>
34
- <button onClick={add}>+</button>
35
- </div>
36
- );
37
- }
38
- `
39
- },
40
- solid: {
41
- filename: `src/components/SolidCounter.jsx`,
42
- content: `import { createSignal } from "solid-js";
43
-
44
- export default function SolidCounter() {
45
- const [count, setCount] = createSignal(0);
46
- const add = () => setCount(count() + 1);
47
- const subtract = () => setCount(count() - 1);
48
-
49
- return (
50
- <div id="solid" class="counter">
51
- <button onClick={subtract}>-</button>
52
- <pre>{count()}</pre>
53
- <button onClick={add}>+</button>
54
- </div>
55
- );
56
- }
57
- `
58
- },
59
- svelte: {
60
- filename: `src/components/SvelteCounter.svelte`,
61
- content: `<script>
62
- let count = 0;
63
-
64
- function add() {
65
- count += 1;
66
- }
67
-
68
- function subtract() {
69
- count -= 1;
70
- }
71
- <\/script>
72
-
73
- <div id="svelte" class="counter">
74
- <button on:click={subtract}>-</button>
75
- <pre>{ count }</pre>
76
- <button on:click={add}>+</button>
77
- </div>
78
- `
79
- },
80
- vue: {
81
- filename: `src/components/VueCounter.vue`,
82
- content: `<template>
83
- <div id="vue" class="counter">
84
- <button @click="subtract()">-</button>
85
- <pre>{{ count }}</pre>
86
- <button @click="add()">+</button>
87
- </div>
88
- </template>
89
-
90
- <script>
91
- import { ref } from 'vue';
92
- export default {
93
- setup() {
94
- const count = ref(0)
95
- const add = () => count.value = count.value + 1;
96
- const subtract = () => count.value = count.value - 1;
97
-
98
- return {
99
- count,
100
- add,
101
- subtract
102
- }
103
- }
104
- }
105
- <\/script>
106
- `
107
- }
108
- };
109
- const FRAMEWORKS = [
110
- {
111
- title: "Preact",
112
- value: { id: "preact", packageName: "@astrojs/preact" }
113
- },
114
- {
115
- title: "React",
116
- value: { id: "react", packageName: "@astrojs/react" }
117
- },
118
- {
119
- title: "Solid.js",
120
- value: { id: "solid", packageName: "@astrojs/solid-js" }
121
- },
122
- {
123
- title: "Svelte",
124
- value: { id: "svelte", packageName: "@astrojs/svelte" }
125
- },
126
- {
127
- title: "Vue",
128
- value: { id: "vue", packageName: "@astrojs/vue" }
129
- }
130
- ];
131
- export {
132
- COUNTER_COMPONENTS,
133
- FRAMEWORKS
134
- };
@@ -1,4 +0,0 @@
1
- import type { Integration } from './frameworks';
2
- export declare const createConfig: ({ integrations }: {
3
- integrations: Integration[];
4
- }) => string;
@@ -1,30 +0,0 @@
1
- export declare const COUNTER_COMPONENTS: {
2
- preact: {
3
- filename: string;
4
- content: string;
5
- };
6
- react: {
7
- filename: string;
8
- content: string;
9
- };
10
- solid: {
11
- filename: string;
12
- content: string;
13
- };
14
- svelte: {
15
- filename: string;
16
- content: string;
17
- };
18
- vue: {
19
- filename: string;
20
- content: string;
21
- };
22
- };
23
- export interface Integration {
24
- id: string;
25
- packageName: string;
26
- }
27
- export declare const FRAMEWORKS: {
28
- title: string;
29
- value: Integration;
30
- }[];