create-amytis 0.1.1 → 0.1.3

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.
Files changed (2) hide show
  1. package/dist/index.js +115 -28
  2. package/package.json +4 -7
package/dist/index.js CHANGED
@@ -7,33 +7,25 @@ import * as fs from "fs";
7
7
  import * as path from "path";
8
8
  import * as https from "https";
9
9
  import * as readline from "readline";
10
- import { execSync } from "child_process";
10
+ import { execFileSync, execSync } from "child_process";
11
11
  function prompt(question, defaultVal = "") {
12
12
  const rl = readline.createInterface({
13
13
  input: process.stdin,
14
14
  output: process.stdout
15
15
  });
16
16
  const display = defaultVal ? `${question} (${defaultVal}): ` : `${question}: `;
17
- return new Promise((resolve2) => {
17
+ return new Promise((resolve) => {
18
18
  rl.question(display, (answer) => {
19
19
  rl.close();
20
- resolve2(answer.trim() || defaultVal);
20
+ resolve(answer.trim() || defaultVal);
21
21
  });
22
22
  });
23
23
  }
24
24
  function fetchJson(url) {
25
- const headers = { "User-Agent": "create-amytis-cli" };
26
- if (process.env.GITHUB_TOKEN) {
27
- headers["Authorization"] = `Bearer ${process.env.GITHUB_TOKEN}`;
28
- }
29
- return new Promise((resolve2, reject) => {
30
- https.get(url, { headers }, (res) => {
25
+ return new Promise((resolve, reject) => {
26
+ https.get(url, { headers: { "User-Agent": "create-amytis-cli" } }, (res) => {
31
27
  if (res.statusCode === 301 || res.statusCode === 302) {
32
- fetchJson(res.headers.location).then(resolve2).catch(reject);
33
- return;
34
- }
35
- if (res.statusCode === 403) {
36
- reject(new Error("GitHub API rate limit exceeded. Set GITHUB_TOKEN env var to increase the limit."));
28
+ fetchJson(res.headers.location).then(resolve).catch(reject);
37
29
  return;
38
30
  }
39
31
  if (res.statusCode !== 200) {
@@ -44,7 +36,7 @@ function fetchJson(url) {
44
36
  res.on("data", (chunk) => data += chunk);
45
37
  res.on("end", () => {
46
38
  try {
47
- resolve2(JSON.parse(data));
39
+ resolve(JSON.parse(data));
48
40
  } catch {
49
41
  reject(new Error("Failed to parse GitHub API response"));
50
42
  }
@@ -53,7 +45,7 @@ function fetchJson(url) {
53
45
  });
54
46
  }
55
47
  function downloadFile(url, dest) {
56
- return new Promise((resolve2, reject) => {
48
+ return new Promise((resolve, reject) => {
57
49
  const doGet = (targetUrl) => {
58
50
  https.get(targetUrl, { headers: { "User-Agent": "create-amytis-cli" } }, (res) => {
59
51
  if (res.statusCode === 301 || res.statusCode === 302) {
@@ -66,7 +58,7 @@ function downloadFile(url, dest) {
66
58
  }
67
59
  const file = fs.createWriteStream(dest);
68
60
  res.pipe(file);
69
- file.on("finish", () => file.close(() => resolve2()));
61
+ file.on("finish", () => file.close(() => resolve()));
70
62
  file.on("error", (err) => {
71
63
  fs.unlink(dest, () => {});
72
64
  reject(err);
@@ -76,10 +68,52 @@ function downloadFile(url, dest) {
76
68
  doGet(url);
77
69
  });
78
70
  }
79
- function extractTarball(tarPath, outDir) {
71
+ function getArchiveMetadata(tag, platform = process.platform) {
72
+ if (platform === "win32") {
73
+ return {
74
+ url: `https://github.com/hutusi/amytis/archive/refs/tags/${tag}.zip`,
75
+ filename: `amytis-${tag}.zip`,
76
+ kind: "zip"
77
+ };
78
+ }
79
+ return {
80
+ url: `https://github.com/hutusi/amytis/archive/refs/tags/${tag}.tar.gz`,
81
+ filename: `amytis-${tag}.tar.gz`,
82
+ kind: "tar.gz"
83
+ };
84
+ }
85
+ function buildExtractCommand(archivePath, tmpDir, kind, platform = process.platform) {
86
+ if (kind === "zip") {
87
+ if (platform !== "win32") {
88
+ throw new Error("ZIP extraction is only supported on Windows in create-amytis");
89
+ }
90
+ return {
91
+ command: "powershell.exe",
92
+ args: [
93
+ "-NoProfile",
94
+ "-NonInteractive",
95
+ "-ExecutionPolicy",
96
+ "Bypass",
97
+ "-Command",
98
+ "Expand-Archive",
99
+ "-LiteralPath",
100
+ archivePath,
101
+ "-DestinationPath",
102
+ tmpDir,
103
+ "-Force"
104
+ ]
105
+ };
106
+ }
107
+ return {
108
+ command: "tar",
109
+ args: ["xzf", archivePath, "-C", tmpDir]
110
+ };
111
+ }
112
+ function extractArchive(archivePath, outDir, kind, platform = process.platform) {
80
113
  const tmpDir = `${outDir}.__tmp__`;
81
114
  fs.mkdirSync(tmpDir, { recursive: true });
82
- execSync(`tar xzf "${tarPath}" -C "${tmpDir}"`);
115
+ const { command, args } = buildExtractCommand(archivePath, tmpDir, kind, platform);
116
+ execFileSync(command, args, { stdio: "inherit" });
83
117
  const entries = fs.readdirSync(tmpDir);
84
118
  if (entries.length !== 1) {
85
119
  throw new Error(`Unexpected tarball structure: ${entries.join(", ")}`);
@@ -87,11 +121,39 @@ function extractTarball(tarPath, outDir) {
87
121
  const innerDir = path.join(tmpDir, entries[0]);
88
122
  fs.renameSync(innerDir, outDir);
89
123
  fs.rmdirSync(tmpDir);
90
- fs.unlinkSync(tarPath);
124
+ fs.unlinkSync(archivePath);
91
125
  }
92
126
  function escapeTemplateLiteral(str) {
93
127
  return str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
94
128
  }
129
+ function patchField(src, shapes, field) {
130
+ for (const [pattern, replacement] of shapes) {
131
+ if (pattern.test(src))
132
+ return src.replace(pattern, () => replacement);
133
+ }
134
+ throw new Error(`create-amytis is out of sync with the downloaded site.config.ts: ` + `could not find the "${field}" field to patch. Edit site.config.ts manually, ` + `and please report this at https://github.com/hutusi/amytis/issues`);
135
+ }
136
+ function applyStarterConfig(projectDir) {
137
+ const starterPath = path.join(projectDir, "site.config.example.ts");
138
+ if (!fs.existsSync(starterPath))
139
+ return false;
140
+ fs.copyFileSync(starterPath, path.join(projectDir, "site.config.ts"));
141
+ return true;
142
+ }
143
+ var LOCALE_DIR_SHAPE = /^[a-z]{2}(-[A-Z]{2})?$/;
144
+ function removeLocaleTrees(projectDir) {
145
+ const contentDir = path.join(projectDir, "content");
146
+ if (!fs.existsSync(contentDir))
147
+ return [];
148
+ const removed = [];
149
+ for (const entry of fs.readdirSync(contentDir, { withFileTypes: true })) {
150
+ if (!entry.isDirectory() || !LOCALE_DIR_SHAPE.test(entry.name))
151
+ continue;
152
+ fs.rmSync(path.join(contentDir, entry.name), { recursive: true, force: true });
153
+ removed.push(`content/${entry.name}/`);
154
+ }
155
+ return removed;
156
+ }
95
157
  function patchSiteConfig(projectDir, title, description) {
96
158
  const configPath = path.join(projectDir, "site.config.ts");
97
159
  if (!fs.existsSync(configPath)) {
@@ -99,10 +161,24 @@ function patchSiteConfig(projectDir, title, description) {
99
161
  return;
100
162
  }
101
163
  let src = fs.readFileSync(configPath, "utf8");
102
- src = src.replace(/title:\s*\{\s*en:\s*"[^"]*",\s*zh:\s*"[^"]*"\s*\}/, `title: { en: ${JSON.stringify(title)}, zh: ${JSON.stringify(title)} }`);
103
- src = src.replace(/description:\s*\{\s*en:\s*"[^"]*",\s*zh:\s*"[^"]*"\s*\}/, `description: { en: ${JSON.stringify(description)}, zh: ${JSON.stringify(description)} }`);
164
+ const quotedTitle = JSON.stringify(title);
165
+ const quotedDescription = JSON.stringify(description);
104
166
  const safeTitle = escapeTemplateLiteral(title);
105
- src = src.replace(/footerText:\s*\{\s*en:\s*`[^`]*`,\s*zh:\s*`[^`]*`\s*\}/, `footerText: { en: \`© \${new Date().getFullYear()} ${safeTitle}. All rights reserved.\`, zh: \`© \${new Date().getFullYear()} ${safeTitle}. 保留所有权利。\` }`);
167
+ src = patchField(src, [
168
+ [/^ {2}title:\s*\{\s*en:\s*"[^"]*",\s*zh:\s*"[^"]*"\s*\}/m, ` title: { en: ${quotedTitle}, zh: ${quotedTitle} }`],
169
+ [/^ {2}title:\s*"[^"]*"/m, ` title: ${quotedTitle}`]
170
+ ], "title");
171
+ src = patchField(src, [
172
+ [/^ {2}description:\s*\{\s*en:\s*"[^"]*",\s*zh:\s*"[^"]*"\s*\}/m, ` description: { en: ${quotedDescription}, zh: ${quotedDescription} }`],
173
+ [/^ {2}description:\s*"[^"]*"/m, ` description: ${quotedDescription}`]
174
+ ], "description");
175
+ src = patchField(src, [
176
+ [
177
+ /^ {2}footerText:\s*\{\s*en:\s*`[^`]*`,\s*zh:\s*`[^`]*`\s*\}/m,
178
+ ` footerText: { en: \`© \${new Date().getFullYear()} ${safeTitle}. All rights reserved.\`, zh: \`© \${new Date().getFullYear()} ${safeTitle}. 保留所有权利。\` }`
179
+ ],
180
+ [/^ {2}footerText:\s*`[^`]*`/m, ` footerText: \`© \${new Date().getFullYear()} ${safeTitle}. All rights reserved.\``]
181
+ ], "footerText");
106
182
  fs.writeFileSync(configPath, src, "utf8");
107
183
  }
108
184
  function patchPackageJson(projectDir, projectName) {
@@ -140,18 +216,25 @@ Fetching latest Amytis release...`);
140
216
  if (!tag)
141
217
  throw new Error("Could not determine latest release tag");
142
218
  console.log(` Found: ${tag}`);
143
- const tarUrl = `https://github.com/hutusi/amytis/archive/refs/tags/${tag}.tar.gz`;
144
- const tarDest = path.join(process.cwd(), `amytis-${tag}.tar.gz`);
219
+ const archive = getArchiveMetadata(tag);
220
+ const archiveDest = path.join(process.cwd(), archive.filename);
145
221
  console.log("Downloading tarball...");
146
- await downloadFile(tarUrl, tarDest);
222
+ await downloadFile(archive.url, archiveDest);
147
223
  console.log("Extracting...");
148
- extractTarball(tarDest, targetDir);
224
+ extractArchive(archiveDest, targetDir, archive.kind);
149
225
  console.log(` Scaffolded: ${targetDir}`);
150
226
  const siteTitle = await prompt(`
151
227
  Site title`, projectName);
152
228
  const siteDescription = await prompt("Site description", "My digital garden");
153
229
  console.log(`
154
230
  Patching site.config.ts...`);
231
+ if (applyStarterConfig(targetDir)) {
232
+ const removed = removeLocaleTrees(targetDir);
233
+ if (removed.length > 0)
234
+ console.log(` Removed the demo's translations: ${removed.join(", ")}`);
235
+ } else {
236
+ console.warn(" Warning: site.config.example.ts not found, keeping the release's site.config.ts");
237
+ }
155
238
  patchSiteConfig(targetDir, siteTitle, siteDescription);
156
239
  console.log("Patching package.json...");
157
240
  patchPackageJson(targetDir, projectName);
@@ -176,6 +259,10 @@ Error:`, err.message);
176
259
  });
177
260
  }
178
261
  export {
262
+ applyStarterConfig,
263
+ buildExtractCommand,
264
+ getArchiveMetadata,
265
+ patchPackageJson,
179
266
  patchSiteConfig,
180
- patchPackageJson
267
+ removeLocaleTrees
181
268
  };
package/package.json CHANGED
@@ -1,17 +1,14 @@
1
1
  {
2
2
  "name": "create-amytis",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Create a new Amytis digital garden",
5
5
  "license": "MIT",
6
- "bin": {
7
- "create-amytis": "dist/index.js"
8
- },
6
+ "type": "module",
7
+ "bin": { "create-amytis": "dist/index.js" },
9
8
  "scripts": {
10
9
  "build": "bun build src/index.ts --outfile dist/index.js --target node --sourcemap=none",
11
10
  "dev": "bun src/index.ts",
12
11
  "test": "bun test src"
13
12
  },
14
- "files": [
15
- "dist"
16
- ]
13
+ "files": ["dist"]
17
14
  }