ts-vibe 2.2.0 → 2.4.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.
@@ -0,0 +1,185 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { exec } from "../cmd.mjs";
5
+
6
+ async function exists(filePath) {
7
+ try {
8
+ await fs.lstat(filePath);
9
+ return true;
10
+ } catch (error) {
11
+ if (error.code === "ENOENT") return false;
12
+ throw error;
13
+ }
14
+ }
15
+
16
+ async function writeProjectFiles(root, files) {
17
+ for (const [relativePath, content] of Object.entries(files)) {
18
+ const destination = path.join(root, relativePath);
19
+ await fs.mkdir(path.dirname(destination), { recursive: true });
20
+ await fs.writeFile(destination, content, "utf8");
21
+ }
22
+ }
23
+
24
+ async function initializeGit(root) {
25
+ await exec("git", ["init"], { cwd: root });
26
+ await exec("git", ["add", "--all"], { cwd: root });
27
+ await exec("git", ["commit", "-m", "init project with ts-vibe"], {
28
+ cwd: root,
29
+ });
30
+ }
31
+
32
+ async function prepareStage(stagePath, project, onStep) {
33
+ onStep(project.language?.step_generate ?? "Generate project files");
34
+ await writeProjectFiles(stagePath, project.files);
35
+
36
+ if (project.install) {
37
+ onStep(project.language?.step_install ?? "Install dependencies");
38
+ await exec("npm", ["install"], { cwd: stagePath });
39
+ }
40
+
41
+ if (project.selectedFeatures.includes("git") && project.gitMode === "new") {
42
+ onStep(project.language?.step_git ?? "Initialize Git repository");
43
+ await initializeGit(stagePath);
44
+ }
45
+ }
46
+
47
+ async function moveEntry(source, destination, backup, journal) {
48
+ const sourceStat = await fs.lstat(source);
49
+ const destinationExists = await exists(destination);
50
+
51
+ if (!destinationExists) {
52
+ await fs.mkdir(path.dirname(destination), { recursive: true });
53
+ await fs.rename(source, destination);
54
+ journal.push({ type: "added", destination });
55
+ return;
56
+ }
57
+
58
+ const destinationStat = await fs.lstat(destination);
59
+ if (sourceStat.isDirectory() && destinationStat.isDirectory()) {
60
+ for (const entry of await fs.readdir(source)) {
61
+ await moveEntry(
62
+ path.join(source, entry),
63
+ path.join(destination, entry),
64
+ path.join(backup, entry),
65
+ journal,
66
+ );
67
+ }
68
+ await fs.rm(source, { recursive: true, force: true });
69
+ return;
70
+ }
71
+
72
+ await fs.mkdir(path.dirname(backup), { recursive: true });
73
+ await fs.rename(destination, backup);
74
+
75
+ try {
76
+ await fs.rename(source, destination);
77
+ journal.push({ type: "replaced", destination, backup });
78
+ } catch (error) {
79
+ await fs.rename(backup, destination);
80
+ throw error;
81
+ }
82
+ }
83
+
84
+ async function rollbackMerge(journal) {
85
+ for (const operation of [...journal].reverse()) {
86
+ await fs.rm(operation.destination, { recursive: true, force: true });
87
+ if (operation.type === "replaced") {
88
+ await fs.mkdir(path.dirname(operation.destination), { recursive: true });
89
+ await fs.rename(operation.backup, operation.destination);
90
+ }
91
+ }
92
+ }
93
+
94
+ async function publishIntoExisting(stagePath, project) {
95
+ const parent = path.dirname(project.targetPath);
96
+ const backupRoot = await fs.mkdtemp(
97
+ path.join(parent, `.ts-vibe-backup-${project.name}-`),
98
+ );
99
+ const clearedRoot = path.join(backupRoot, "cleared");
100
+ const mergeRoot = path.join(backupRoot, "merge");
101
+ const clearedEntries = [];
102
+ const journal = [];
103
+
104
+ try {
105
+ if (project.directoryPolicy === "clear") {
106
+ await fs.mkdir(clearedRoot, { recursive: true });
107
+ const stageName = path.basename(stagePath);
108
+ for (const entry of await fs.readdir(project.targetPath)) {
109
+ if (entry === ".git" || entry === stageName) continue;
110
+ await fs.rename(
111
+ path.join(project.targetPath, entry),
112
+ path.join(clearedRoot, entry),
113
+ );
114
+ clearedEntries.push(entry);
115
+ }
116
+ }
117
+
118
+ for (const entry of await fs.readdir(stagePath)) {
119
+ await moveEntry(
120
+ path.join(stagePath, entry),
121
+ path.join(project.targetPath, entry),
122
+ path.join(mergeRoot, entry),
123
+ journal,
124
+ );
125
+ }
126
+ } catch (error) {
127
+ await rollbackMerge(journal);
128
+
129
+ for (const entry of [...clearedEntries].reverse()) {
130
+ const original = path.join(project.targetPath, entry);
131
+ await fs.rm(original, { recursive: true, force: true });
132
+ await fs.rename(path.join(clearedRoot, entry), original);
133
+ }
134
+
135
+ throw error;
136
+ }
137
+
138
+ await fs.rm(backupRoot, { recursive: true, force: true });
139
+ }
140
+
141
+ export async function executeTransaction(project, { onStep = () => {} } = {}) {
142
+ const parent = path.dirname(project.targetPath);
143
+ await fs.mkdir(parent, { recursive: true });
144
+
145
+ const targetExists = await exists(project.targetPath);
146
+ if (targetExists && project.directoryPolicy === "create") {
147
+ throw new Error("The target directory appeared during generation");
148
+ }
149
+
150
+ const createdTarget = !targetExists;
151
+ if (createdTarget) {
152
+ await fs.mkdir(project.targetPath);
153
+ }
154
+
155
+ let stagePath;
156
+ let completed = false;
157
+
158
+ try {
159
+ stagePath = await fs.mkdtemp(
160
+ path.join(project.targetPath, ".ts-vibe-stage-"),
161
+ );
162
+ await prepareStage(stagePath, project, onStep);
163
+ onStep(project.language?.step_publish ?? "Publish project");
164
+
165
+ if (createdTarget) {
166
+ for (const entry of await fs.readdir(stagePath)) {
167
+ await fs.rename(
168
+ path.join(stagePath, entry),
169
+ path.join(project.targetPath, entry),
170
+ );
171
+ }
172
+ } else {
173
+ await publishIntoExisting(stagePath, project);
174
+ }
175
+
176
+ completed = true;
177
+ } finally {
178
+ if (stagePath) {
179
+ await fs.rm(stagePath, { recursive: true, force: true });
180
+ }
181
+ if (createdTarget && !completed) {
182
+ await fs.rm(project.targetPath, { recursive: true, force: true });
183
+ }
184
+ }
185
+ }
package/src/ts.mjs CHANGED
@@ -1,63 +1,100 @@
1
1
  import { read } from "./fs/json/json5.mjs";
2
2
  import { write } from "./fs/json/index.mjs";
3
3
 
4
- let config = null;
4
+ let tsConfig = null;
5
5
 
6
6
  export function readConfig() {
7
- config = read("tsconfig.json");
8
- return config;
7
+ tsConfig = read("tsconfig.json");
8
+ return tsConfig;
9
9
  }
10
10
 
11
- export function updateTsConfig() {
12
- if (!config) {
11
+ export function updateTsConfig(projectConfig) {
12
+ if (!tsConfig) {
13
13
  readConfig();
14
14
  }
15
15
 
16
- if (!config) {
16
+ if (!tsConfig) {
17
17
  throw new Error("tsconfig.json not found");
18
18
  }
19
19
 
20
- const options = (config.compilerOptions ??= {});
20
+ const options = (tsConfig.compilerOptions ??= {});
21
21
 
22
- options.rootDir = "./src"; // source code in src dir
23
- options.outDir = "./dist"; // code output in dist dir
24
- options.lib = ["ESNext"]; // adds modern JS API
25
- options.esModuleInterop = true; // more comfortable imports
22
+ // shared options
23
+ options.rootDir = "./src";
24
+ options.outDir = "./dist";
25
+
26
+ options.target = "ES2020";
27
+
28
+ if (projectConfig.options.includes("node")) {
29
+ options.types = ["node"];
30
+ }
31
+
32
+ options.sourceMap = true;
33
+
34
+ options.strict = true;
35
+ options.noUncheckedIndexedAccess = true;
36
+ options.exactOptionalPropertyTypes = true;
37
+
38
+ options.resolveJsonModule = true;
39
+ options.forceConsistentCasingInFileNames = true;
40
+
41
+ options.skipLibCheck = true;
42
+
43
+ options.esModuleInterop = true;
26
44
  options.allowSyntheticDefaultImports = true;
27
- options.resolveJsonModule = true; // allows to import JSON files
28
- options.forceConsistentCasingInFileNames = true; // strict file names in imports
29
- options.moduleResolution = "bundler"; // allows to use bundlers
30
- options.module = "esnext"; // ts generates modern ESM
31
45
 
32
- // @ in imports as src dir
33
- options.baseUrl = ".";
34
- options.paths ??= {};
35
- options.paths["@/*"] = ["src/*"];
46
+ // alias @ -> src
47
+ if (projectConfig.options.includes("src dir @ alias")) {
48
+ options.baseUrl = ".";
49
+ options.paths ??= {};
50
+ options.paths["@/*"] = ["src/*"];
51
+ }
36
52
 
53
+ // cleanup
37
54
  delete options.verbatimModuleSyntax;
38
55
  delete options.moduleDetection;
39
56
  delete options.noUncheckedSideEffectImports;
40
57
  delete options.declaration;
41
58
  delete options.declarationMap;
42
59
 
43
- write("tsconfig.json", config);
60
+ if (projectConfig.nodeType === "module") {
61
+ // ESM
62
+ options.lib = ["ESNext"];
63
+
64
+ options.module = "esnext";
65
+ options.moduleResolution = "bundler";
66
+ } else {
67
+ // CommonJS
68
+ options.lib = ["ES2020"];
69
+
70
+ options.module = "commonjs";
71
+ options.moduleResolution = "node";
72
+ }
73
+
74
+ write("tsconfig.json", tsConfig);
44
75
  }
45
76
 
46
77
  export function addType(typeName) {
47
- if (!config) {
78
+ if (!tsConfig) {
48
79
  readConfig();
49
80
  }
50
81
 
51
- if (!config) {
82
+ if (!tsConfig) {
52
83
  throw new Error("tsconfig.json not found");
53
84
  }
54
85
 
55
- if (!config.compilerOptions.types) {
56
- config.compilerOptions.types = [];
86
+ const options = (tsConfig.compilerOptions ??= {});
87
+ options.types ??= [];
88
+
89
+ if (!options.types.includes(typeName)) {
90
+ options.types.push(typeName);
57
91
  }
58
92
 
59
- config.compilerOptions.types.push(typeName);
60
- write("tsconfig.json", config);
93
+ write("tsconfig.json", tsConfig);
61
94
  }
62
95
 
63
- export default { readConfig, updateTsConfig, addType };
96
+ export default {
97
+ readConfig,
98
+ updateTsConfig,
99
+ addType,
100
+ };
package/src/utils/cmd.mjs CHANGED
@@ -1,58 +1,108 @@
1
- import chalk from "chalk";
2
- import { select } from "@inquirer/prompts";
3
- import checkboxPrompt from "@inquirer/checkbox";
4
- import ora from "ora";
1
+ import * as prompts from "@clack/prompts";
2
+ import colors from "picocolors";
3
+
4
+ const normalizeOptions = (options) =>
5
+ options.map((option) =>
6
+ typeof option === "string" ? { label: option, value: option } : option,
7
+ );
8
+
9
+ let defaultCancelMessage = "Operation cancelled";
10
+
11
+ function unwrap(value, message = defaultCancelMessage) {
12
+ if (prompts.isCancel(value)) {
13
+ prompts.cancel(message);
14
+ process.exit(0);
15
+ }
16
+
17
+ return value;
18
+ }
19
+
20
+ export function intro(title, cancelMessage) {
21
+ defaultCancelMessage = cancelMessage ?? defaultCancelMessage;
22
+ prompts.intro(colors.bgCyan(colors.black(` ${title} `)));
23
+ }
24
+
25
+ export function outro(message) {
26
+ prompts.outro(message);
27
+ }
28
+
29
+ export function cancel(message) {
30
+ prompts.cancel(message);
31
+ }
32
+
33
+ export function error(message) {
34
+ prompts.log.error(message);
35
+ }
36
+
37
+ export function note(message, title) {
38
+ prompts.note(message, title);
39
+ }
40
+
41
+ export async function input(message, options = {}) {
42
+ const { cancelMessage, ...promptOptions } = options;
43
+ const value = await prompts.text({ message, ...promptOptions });
44
+ return unwrap(value, cancelMessage);
45
+ }
46
+
47
+ export async function ask(message, options = {}) {
48
+ const { cancelMessage, ...promptOptions } = options;
49
+ const value = await prompts.confirm({ message, ...promptOptions });
50
+ return unwrap(value, cancelMessage);
51
+ }
5
52
 
6
53
  export async function confirm(
7
54
  fn,
8
55
  message,
9
56
  success = "Success",
10
- error = "Error",
57
+ errorMessage = "Error",
11
58
  ) {
12
- const spinner = ora({
13
- text: chalk.cyan(message),
14
- color: "cyan",
15
- }).start();
59
+ const spinner = prompts.spinner();
60
+ spinner.start(message);
16
61
 
17
62
  try {
18
- const res = await fn();
19
-
20
- spinner.succeed(`${chalk.bold.green(success)}: ${message}`);
21
-
22
- return res;
23
- } catch (e) {
24
- spinner.fail(`${chalk.bold.red(error)}: ${message}`);
25
-
26
- console.error(chalk.red(e instanceof Error ? e.message : String(e)));
27
-
28
- throw e;
63
+ const result = await fn({
64
+ message(text) {
65
+ spinner.message(text);
66
+ },
67
+ });
68
+ spinner.stop(`${colors.green(success)}: ${message}`);
69
+ return result;
70
+ } catch (error) {
71
+ spinner.error(`${colors.red(errorMessage)}: ${message}`);
72
+ prompts.log.error(error instanceof Error ? error.message : String(error));
73
+ throw error;
29
74
  }
30
75
  }
31
76
 
32
- export async function radio(prompt, options = []) {
77
+ export async function radio(message, options = [], initialValue) {
33
78
  if (!options.length) {
34
79
  throw new Error("radio: options is empty");
35
80
  }
36
81
 
37
- return select({
38
- message: chalk.bold(prompt),
39
- choices: options.map((option) => ({
40
- name: option,
41
- value: option,
42
- })),
82
+ const value = await prompts.select({
83
+ message,
84
+ options: normalizeOptions(options),
85
+ initialValue,
43
86
  });
87
+
88
+ return unwrap(value);
44
89
  }
45
90
 
46
- export async function checkbox(prompt, options = []) {
91
+ export async function checkbox(
92
+ message,
93
+ options = [],
94
+ initialValues = [],
95
+ ) {
47
96
  if (!options.length) {
48
97
  throw new Error("checkbox: options is empty");
49
98
  }
50
99
 
51
- return checkboxPrompt({
52
- message: chalk.bold(prompt),
53
- choices: options.map((option) => ({
54
- name: option,
55
- value: option,
56
- })),
100
+ const value = await prompts.multiselect({
101
+ message,
102
+ options: normalizeOptions(options),
103
+ initialValues,
104
+ required: false,
57
105
  });
106
+
107
+ return unwrap(value);
58
108
  }