nuxt-gin-tools 0.2.11 → 0.2.12

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,11 @@
1
+ /**
2
+ * 警告:本文件是API生成框架的一部分,请勿手动修改!
3
+ * 任何修改可能会被自动化流程覆盖。
4
+ * 如需调整生成逻辑,请修改相关配置文件或脚本。
5
+ */
6
+ /**
7
+ * 主函数
8
+ * 协调执行所有任务:生成代码、删除路径、配置Vue API
9
+ */
10
+ export declare function apiGenerate(): Promise<void>;
11
+ export default apiGenerate;
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ /**
3
+ * 警告:本文件是API生成框架的一部分,请勿手动修改!
4
+ * 任何修改可能会被自动化流程覆盖。
5
+ * 如需调整生成逻辑,请修改相关配置文件或脚本。
6
+ */
7
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
8
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9
+ return new (P || (P = Promise))(function (resolve, reject) {
10
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
12
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
13
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
14
+ });
15
+ };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.apiGenerate = apiGenerate;
21
+ const chalk_1 = __importDefault(require("chalk"));
22
+ const concurrently_1 = __importDefault(require("concurrently")); // 用于并发执行命令的工具
23
+ const fs_extra_1 = __importDefault(require("fs-extra")); // 文件系统操作工具,提供更便捷的API
24
+ const path_1 = __importDefault(require("path")); // 处理和转换文件路径的工具
25
+ const cwd = process.cwd(); // 获取当前工作目录
26
+ /**
27
+ * 要执行的命令列表
28
+ * 包含OpenAPI代码生成命令:
29
+ * 1. 生成Go Gin服务器代码
30
+ * 2. 生成TypeScript Axios客户端代码
31
+ */
32
+ let commands = [
33
+ {
34
+ command: "openapi-generator-cli generate -i openapi.yaml -g go-gin-server -c node_modules/nuxt-gin-tools/src/go-gin-server.json -o .",
35
+ name: "go",
36
+ prefixColor: "green",
37
+ },
38
+ {
39
+ command: "openapi-generator-cli generate -i openapi.yaml -g typescript-axios -o vue/composables/api ",
40
+ name: "vue",
41
+ prefixColor: "blue",
42
+ },
43
+ ];
44
+ /**
45
+ * 执行完成后需要删除的路径列表
46
+ */
47
+ const pathsToDelete = ["api"];
48
+ /**
49
+ * 设置Vue API客户端的基础URL
50
+ * 修改TypeScript axios生成的base.ts文件,将BASE_PATH设置为相对路径
51
+ * @returns {Promise<string>} 返回原始文件内容的Promise
52
+ */
53
+ function setVueBaseUrl() {
54
+ return __awaiter(this, void 0, void 0, function* () {
55
+ try {
56
+ // 构建Vue API运行时配置文件的完整路径
57
+ const VUE_API_RUNTIME_PATH = path_1.default.join(cwd, "vue/composables/api/base.ts");
58
+ // 读取原始文件内容
59
+ const originalContent = yield fs_extra_1.default.readFile(VUE_API_RUNTIME_PATH, "utf-8");
60
+ // 使用正则表达式替换BASE_PATH常量,移除协议和域名部分,使其成为相对路径
61
+ // 匹配类似 "export const BASE_PATH = "https://example.com"" 这样的行
62
+ const updatedContent = originalContent.replace(/export\s+const\s+BASE_PATH = "https?:\/\/[^/]+/, `export const BASE_PATH = "`);
63
+ // 将修改后的内容写回文件
64
+ yield fs_extra_1.default.outputFile(VUE_API_RUNTIME_PATH, updatedContent, "utf-8");
65
+ console.log("成功更新Vue API基础URL为相对路径");
66
+ return;
67
+ }
68
+ catch (error) {
69
+ console.error("更新Vue API基础URL失败:", error);
70
+ throw error; // 将错误继续抛出,以便上层处理
71
+ }
72
+ });
73
+ }
74
+ function setGoRoutes() {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ const GO_API_RUNTIME_PATH = path_1.default.join(cwd, "server/api/routers.go");
77
+ const originalContent = yield fs_extra_1.default.readFile(GO_API_RUNTIME_PATH, "utf-8");
78
+ const updatedContent = originalContent.replace(/getRoutes/g, "GetRoutes");
79
+ // overwrite
80
+ yield fs_extra_1.default.outputFile(GO_API_RUNTIME_PATH, updatedContent, "utf-8");
81
+ });
82
+ }
83
+ /**
84
+ * 删除指定的路径
85
+ * 用于清理生成过程中产生的临时或不需要的文件和目录
86
+ */
87
+ function removePaths() {
88
+ return __awaiter(this, void 0, void 0, function* () {
89
+ try {
90
+ // 遍历要删除的路径列表
91
+ for (const path of pathsToDelete) {
92
+ // 构建完整路径
93
+ const fullPath = path_1.default.join(cwd, path);
94
+ // 删除路径(文件或目录)
95
+ yield fs_extra_1.default.remove(fullPath);
96
+ console.log(`成功删除路径: ${fullPath}`);
97
+ }
98
+ }
99
+ catch (error) {
100
+ console.error("删除路径失败:", error);
101
+ throw error; // 将错误继续抛出
102
+ }
103
+ });
104
+ }
105
+ /**
106
+ * 主函数
107
+ * 协调执行所有任务:生成代码、删除路径、配置Vue API
108
+ */
109
+ function apiGenerate() {
110
+ return __awaiter(this, void 0, void 0, function* () {
111
+ try {
112
+ // 输出开始信息
113
+ console.log(chalk_1.default.bgGreen("开始生成API代码..."));
114
+ // 并发执行命令列表中的所有命令,等待所有命令完成
115
+ yield (0, concurrently_1.default)(commands).result;
116
+ // 按顺序执行清理和配置任务
117
+ let tasks = [];
118
+ tasks.push(removePaths());
119
+ tasks.push(setVueBaseUrl());
120
+ tasks.push(setGoRoutes());
121
+ yield Promise.all(tasks);
122
+ console.log(chalk_1.default.bgGreen("API代码生成和配置完成!"));
123
+ }
124
+ catch (error) {
125
+ // 捕获并处理任何阶段发生的错误
126
+ console.error(chalk_1.default.red("执行过程中发生错误:"), error);
127
+ // 以错误码1退出进程,表示执行失败
128
+ process.exit(1);
129
+ }
130
+ });
131
+ }
132
+ // 执行主函数
133
+ exports.default = apiGenerate;
@@ -0,0 +1,2 @@
1
+ export declare function build(): Promise<import("concurrently").CloseEvent[]>;
2
+ export default build;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.build = build;
7
+ const concurrently_1 = __importDefault(require("concurrently"));
8
+ const fs_extra_1 = require("fs-extra");
9
+ const path_1 = require("path");
10
+ const cwd = process.cwd();
11
+ function build() {
12
+ (0, fs_extra_1.ensureDirSync)((0, path_1.join)(cwd, "vue/.output"));
13
+ return (0, concurrently_1.default)([
14
+ {
15
+ command: "go build -o ./.build/.server/production.exe .",
16
+ name: "go",
17
+ prefixColor: "green",
18
+ },
19
+ {
20
+ command: "npx nuxt generate",
21
+ name: "nuxt",
22
+ prefixColor: "blue",
23
+ },
24
+ ]).result;
25
+ }
26
+ exports.default = build;
@@ -0,0 +1,8 @@
1
+ export declare function ifExistsRemove(relativePath: string): void;
2
+ export declare function cleanUpNuxt(): Promise<import("concurrently").CloseEvent[]>;
3
+ export declare function cleanUpBuild(): void;
4
+ /**
5
+ * 清理构建目录和临时文件
6
+ */
7
+ export declare function cleanUp(): Promise<void>;
8
+ export default cleanUp;
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.ifExistsRemove = ifExistsRemove;
49
+ exports.cleanUpNuxt = cleanUpNuxt;
50
+ exports.cleanUpBuild = cleanUpBuild;
51
+ exports.cleanUp = cleanUp;
52
+ const FS = __importStar(require("fs-extra"));
53
+ const Path = __importStar(require("path"));
54
+ const concurrently_1 = __importDefault(require("concurrently"));
55
+ const chalk_1 = __importDefault(require("chalk"));
56
+ const cwd = process.cwd();
57
+ function ifExistsRemove(relativePath) {
58
+ const absolutePath = Path.resolve(cwd, relativePath);
59
+ if (FS.existsSync(absolutePath)) {
60
+ FS.removeSync(absolutePath);
61
+ }
62
+ }
63
+ function cleanUpNuxt() {
64
+ return (0, concurrently_1.default)([
65
+ {
66
+ command: "npx nuxt cleanup",
67
+ },
68
+ ]).result;
69
+ }
70
+ function cleanUpBuild() {
71
+ // 清理构建目录
72
+ ifExistsRemove(".build/production");
73
+ // 清理原始 dist 目录
74
+ ifExistsRemove("dist");
75
+ // 清理临时文件
76
+ ifExistsRemove(".build");
77
+ // 清理临时文件
78
+ ifExistsRemove("tmp");
79
+ // 清理 Vue 应用构建输出目录
80
+ ifExistsRemove("vue/.output");
81
+ // 清理 OpenAPI 生成的文件
82
+ ifExistsRemove(".openapi-generator");
83
+ // 清理go.sum
84
+ // ifExistsRemove("go.sum");
85
+ }
86
+ /**
87
+ * 清理构建目录和临时文件
88
+ */
89
+ function cleanUp() {
90
+ return __awaiter(this, void 0, void 0, function* () {
91
+ const result = cleanUpNuxt();
92
+ cleanUpBuild();
93
+ yield result;
94
+ console.log(chalk_1.default.bgGreen("----- 清理完成!-----"));
95
+ });
96
+ }
97
+ exports.default = cleanUp;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * 启动 Go 开发监听流程:执行 `go run main.go`,并在文件变更后自动重启。
3
+ *
4
+ * 该函数通常由 `develop()` 调用;执行后会持续监听,直到收到退出信号。
5
+ *
6
+ * @returns {Promise<void>} 仅在监听流程被中断并完成清理后返回。
7
+ */
8
+ export declare function startGoDev(): Promise<void>;
@@ -0,0 +1,306 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.startGoDev = startGoDev;
16
+ const child_process_1 = require("child_process");
17
+ const chokidar_1 = __importDefault(require("chokidar"));
18
+ const chalk_1 = __importDefault(require("chalk"));
19
+ const fs_extra_1 = require("fs-extra");
20
+ const path_1 = require("path");
21
+ const utils_1 = require("../src/utils");
22
+ const cwd = process.cwd();
23
+ const RESTART_DEBOUNCE_MS = 150;
24
+ const SHUTDOWN_TIMEOUT_MS = 2000;
25
+ const LOG_TAG = "go-watch";
26
+ const GO_WATCH_PREFIX = chalk_1.default.bgMagenta.white(`[${LOG_TAG}]`);
27
+ const serverConfigPath = (0, path_1.join)(cwd, "server.config.json");
28
+ const ginPort = getGinPort();
29
+ function getGinPort() {
30
+ if (!(0, fs_extra_1.existsSync)(serverConfigPath)) {
31
+ return null;
32
+ }
33
+ try {
34
+ const serverConfig = (0, fs_extra_1.readJSONSync)(serverConfigPath);
35
+ if (Number.isInteger(serverConfig.ginPort) && serverConfig.ginPort > 0) {
36
+ return serverConfig.ginPort;
37
+ }
38
+ }
39
+ catch (_a) {
40
+ // best effort
41
+ }
42
+ return null;
43
+ }
44
+ function killGinPortIfNeeded() {
45
+ if (!ginPort) {
46
+ return;
47
+ }
48
+ (0, utils_1.killPort)(ginPort, { logPrefix: LOG_TAG, portLabel: "ginPort" });
49
+ }
50
+ function normalizePath(filePath) {
51
+ return filePath.replace(/\\/g, "/").replace(/^\.\//, "");
52
+ }
53
+ function toProjectRelative(filePath) {
54
+ const abs = (0, path_1.isAbsolute)(filePath) ? filePath : (0, path_1.resolve)(cwd, filePath);
55
+ return normalizePath((0, path_1.relative)(cwd, abs));
56
+ }
57
+ function toStringArray(value) {
58
+ if (!Array.isArray(value)) {
59
+ return [];
60
+ }
61
+ return value
62
+ .filter((item) => typeof item === "string")
63
+ .map((item) => item.trim())
64
+ .filter(Boolean);
65
+ }
66
+ function toStringValue(value) {
67
+ if (typeof value !== "string") {
68
+ return "";
69
+ }
70
+ return value.trim();
71
+ }
72
+ function loadWatchConfig() {
73
+ var _a, _b, _c, _d, _e, _f, _g, _h;
74
+ const defaultConfig = {
75
+ includeExt: new Set(["go"]),
76
+ includeDir: [],
77
+ includeFile: new Set(),
78
+ excludeDir: [".git", "node_modules", "vendor", "vue"],
79
+ excludeFile: new Set(),
80
+ excludeRegex: [/_test\.go$/],
81
+ tmpDir: ".build/.server",
82
+ testDataDir: "testdata",
83
+ };
84
+ const candidates = [
85
+ process.env.NUXT_GIN_WATCH_CONFIG,
86
+ (0, path_1.join)(cwd, "node_modules/nuxt-gin-tools/.go-watch.json"),
87
+ (0, path_1.join)(cwd, ".go-watch.json"),
88
+ (0, path_1.join)(__dirname, "..", ".go-watch.json"),
89
+ (0, path_1.join)(__dirname, "..", "..", ".go-watch.json"),
90
+ ].filter((item) => Boolean(item));
91
+ const configPath = candidates.find((item) => (0, fs_extra_1.existsSync)(item));
92
+ if (!configPath) {
93
+ return defaultConfig;
94
+ }
95
+ let parsedConfig = {};
96
+ try {
97
+ parsedConfig = JSON.parse((0, fs_extra_1.readFileSync)(configPath, "utf-8"));
98
+ }
99
+ catch (_j) {
100
+ console.warn(`${GO_WATCH_PREFIX} invalid watch config JSON, fallback to defaults: ${configPath}`);
101
+ return defaultConfig;
102
+ }
103
+ const includeExt = toStringArray((_a = parsedConfig.includeExt) !== null && _a !== void 0 ? _a : parsedConfig.include_ext)
104
+ .map((item) => item.replace(/^\./, ""))
105
+ .filter((item) => /^[a-zA-Z0-9]+$/.test(item));
106
+ const includeDir = toStringArray((_b = parsedConfig.includeDir) !== null && _b !== void 0 ? _b : parsedConfig.include_dir)
107
+ .map((item) => normalizePath(item))
108
+ .filter(Boolean);
109
+ const includeFile = toStringArray((_c = parsedConfig.includeFile) !== null && _c !== void 0 ? _c : parsedConfig.include_file)
110
+ .map((item) => normalizePath(item))
111
+ .filter(Boolean);
112
+ const excludeDir = toStringArray((_d = parsedConfig.excludeDir) !== null && _d !== void 0 ? _d : parsedConfig.exclude_dir)
113
+ .map((item) => normalizePath(item))
114
+ .filter(Boolean);
115
+ const excludeFile = toStringArray((_e = parsedConfig.excludeFile) !== null && _e !== void 0 ? _e : parsedConfig.exclude_file)
116
+ .map((item) => normalizePath(item))
117
+ .filter(Boolean);
118
+ const excludeRegex = toStringArray((_f = parsedConfig.excludeRegex) !== null && _f !== void 0 ? _f : parsedConfig.exclude_regex)
119
+ .map((item) => {
120
+ try {
121
+ return new RegExp(item);
122
+ }
123
+ catch (_a) {
124
+ return null;
125
+ }
126
+ })
127
+ .filter((item) => item instanceof RegExp);
128
+ const tmpDir = normalizePath(toStringValue((_g = parsedConfig.tmpDir) !== null && _g !== void 0 ? _g : parsedConfig.tmp_dir) || defaultConfig.tmpDir);
129
+ const testdataDir = normalizePath(toStringValue((_h = parsedConfig.testDataDir) !== null && _h !== void 0 ? _h : parsedConfig.testdata_dir) ||
130
+ defaultConfig.testDataDir);
131
+ return {
132
+ includeExt: new Set(includeExt.length ? includeExt : [...defaultConfig.includeExt]),
133
+ includeDir,
134
+ includeFile: new Set(includeFile),
135
+ excludeDir: [...new Set([...defaultConfig.excludeDir, ...excludeDir, tmpDir, testdataDir])],
136
+ excludeFile: new Set(excludeFile),
137
+ excludeRegex: excludeRegex.length ? excludeRegex : defaultConfig.excludeRegex,
138
+ tmpDir,
139
+ testDataDir: testdataDir,
140
+ };
141
+ }
142
+ function pathInDir(relPath, dir) {
143
+ const normalizedDir = normalizePath(dir).replace(/\/+$/, "");
144
+ return relPath === normalizedDir || relPath.startsWith(`${normalizedDir}/`);
145
+ }
146
+ function shouldIgnore(relPath, config) {
147
+ if (!relPath || relPath === ".") {
148
+ return false;
149
+ }
150
+ if (config.excludeFile.has(relPath)) {
151
+ return true;
152
+ }
153
+ if (config.excludeDir.some((dir) => pathInDir(relPath, dir))) {
154
+ return true;
155
+ }
156
+ return config.excludeRegex.some((reg) => reg.test(relPath));
157
+ }
158
+ function shouldTrigger(relPath, config) {
159
+ if (shouldIgnore(relPath, config)) {
160
+ return false;
161
+ }
162
+ const ext = (0, path_1.extname)(relPath).replace(/^\./, "");
163
+ const inIncludedFile = config.includeFile.has(relPath);
164
+ if (config.includeDir.length > 0) {
165
+ const inIncludedDir = config.includeDir.some((dir) => pathInDir(relPath, dir));
166
+ if (!inIncludedDir && !inIncludedFile) {
167
+ return false;
168
+ }
169
+ }
170
+ if (inIncludedFile) {
171
+ return true;
172
+ }
173
+ if (!ext) {
174
+ return false;
175
+ }
176
+ return config.includeExt.has(ext);
177
+ }
178
+ function quote(arg) {
179
+ if (/\s/.test(arg)) {
180
+ return `"${arg.replace(/"/g, '\\"')}"`;
181
+ }
182
+ return arg;
183
+ }
184
+ function runGoProcess() {
185
+ const command = `go run ${quote("main.go")}`;
186
+ killGinPortIfNeeded();
187
+ console.log(`${GO_WATCH_PREFIX} start: ${command}`);
188
+ return (0, child_process_1.spawn)(command, {
189
+ cwd,
190
+ shell: true,
191
+ stdio: "inherit",
192
+ });
193
+ }
194
+ function stopGoProcess(proc) {
195
+ return __awaiter(this, void 0, void 0, function* () {
196
+ if (!proc || proc.killed || proc.exitCode !== null) {
197
+ return;
198
+ }
199
+ yield new Promise((resolveStop) => {
200
+ let finished = false;
201
+ const done = () => {
202
+ if (finished) {
203
+ return;
204
+ }
205
+ finished = true;
206
+ resolveStop();
207
+ };
208
+ const timer = setTimeout(() => {
209
+ try {
210
+ proc.kill("SIGKILL");
211
+ }
212
+ catch (_a) {
213
+ // best effort
214
+ }
215
+ done();
216
+ }, SHUTDOWN_TIMEOUT_MS);
217
+ proc.once("exit", () => {
218
+ clearTimeout(timer);
219
+ done();
220
+ });
221
+ try {
222
+ proc.kill("SIGTERM");
223
+ }
224
+ catch (_a) {
225
+ clearTimeout(timer);
226
+ done();
227
+ }
228
+ });
229
+ });
230
+ }
231
+ /**
232
+ * 启动 Go 开发监听流程:执行 `go run main.go`,并在文件变更后自动重启。
233
+ *
234
+ * 该函数通常由 `develop()` 调用;执行后会持续监听,直到收到退出信号。
235
+ *
236
+ * @returns {Promise<void>} 仅在监听流程被中断并完成清理后返回。
237
+ */
238
+ function startGoDev() {
239
+ return __awaiter(this, void 0, void 0, function* () {
240
+ const watchConfig = loadWatchConfig();
241
+ const watchRoots = watchConfig.includeDir.length
242
+ ? watchConfig.includeDir.map((dir) => (0, path_1.join)(cwd, dir))
243
+ : [cwd];
244
+ console.log(`${GO_WATCH_PREFIX} watching: ${watchRoots.map((item) => toProjectRelative(item)).join(", ")}`);
245
+ let restarting = false;
246
+ let goProc = runGoProcess();
247
+ let restartTimer = null;
248
+ const watcher = chokidar_1.default.watch(watchRoots, {
249
+ ignoreInitial: true,
250
+ ignored: (pathName) => shouldIgnore(toProjectRelative(pathName), watchConfig),
251
+ awaitWriteFinish: {
252
+ stabilityThreshold: 120,
253
+ pollInterval: 20,
254
+ },
255
+ });
256
+ const triggerRestart = (eventName, changedPath) => {
257
+ const relPath = toProjectRelative(changedPath);
258
+ if (!shouldTrigger(relPath, watchConfig)) {
259
+ return;
260
+ }
261
+ if (restartTimer) {
262
+ clearTimeout(restartTimer);
263
+ }
264
+ restartTimer = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
265
+ if (restarting) {
266
+ return;
267
+ }
268
+ restarting = true;
269
+ console.log(`${GO_WATCH_PREFIX} ${eventName}: ${relPath}, restarting...`);
270
+ yield stopGoProcess(goProc);
271
+ goProc = runGoProcess();
272
+ restarting = false;
273
+ }), RESTART_DEBOUNCE_MS);
274
+ };
275
+ watcher
276
+ .on("add", (filePath) => triggerRestart("add", filePath))
277
+ .on("change", (filePath) => triggerRestart("change", filePath))
278
+ .on("unlink", (filePath) => triggerRestart("unlink", filePath))
279
+ .on("error", (error) => {
280
+ console.error(`${GO_WATCH_PREFIX} watcher error: ${String(error)}`);
281
+ });
282
+ const shutdown = () => __awaiter(this, void 0, void 0, function* () {
283
+ if (restartTimer) {
284
+ clearTimeout(restartTimer);
285
+ restartTimer = null;
286
+ }
287
+ yield watcher.close();
288
+ yield stopGoProcess(goProc);
289
+ });
290
+ process.on("SIGINT", () => __awaiter(this, void 0, void 0, function* () {
291
+ yield shutdown();
292
+ process.exit(0);
293
+ }));
294
+ process.on("SIGTERM", () => __awaiter(this, void 0, void 0, function* () {
295
+ yield shutdown();
296
+ process.exit(0);
297
+ }));
298
+ });
299
+ }
300
+ if (require.main === module) {
301
+ // 兼容直接执行该文件(例如 node src/dev-go.js)。
302
+ startGoDev().catch((error) => {
303
+ console.error(`${GO_WATCH_PREFIX} failed to start: ${String(error)}`);
304
+ process.exit(1);
305
+ });
306
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 启动本地开发环境。
3
+ *
4
+ * 行为包括:按配置执行预清理、释放开发端口、并行启动 Nuxt 与 Go 监听流程。
5
+ *
6
+ * @returns {Promise<void>} 仅在开发进程退出或出现异常时返回。
7
+ */
8
+ export declare function develop(): Promise<void>;
9
+ /**
10
+ * 仅启动 Nuxt 开发服务(带 nuxt 标签输出)。
11
+ *
12
+ * @returns {Promise<void>} 仅在开发进程退出或出现异常时返回。
13
+ */
14
+ export declare function developNuxt(): Promise<void>;
15
+ /**
16
+ * 仅启动 Go 开发监听流程。
17
+ *
18
+ * @returns {Promise<void>} 仅在开发进程退出或出现异常时返回。
19
+ */
20
+ export declare function developGo(): Promise<void>;
21
+ export default develop;