nuxt-gin-tools 0.2.16 → 0.2.18

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 (45) hide show
  1. package/commands/builder.d.ts +6 -1
  2. package/commands/builder.js +17 -8
  3. package/commands/develop.d.ts +8 -3
  4. package/commands/develop.js +23 -9
  5. package/commands/pack.d.ts +3 -1
  6. package/commands/pack.js +7 -6
  7. package/commands/update.d.ts +6 -1
  8. package/commands/update.js +16 -9
  9. package/index.js +68 -37
  10. package/package.json +1 -1
  11. package/src/cli-options.d.ts +8 -0
  12. package/src/cli-options.js +43 -0
  13. package/src/nuxt-config.js +8 -3
  14. package/src/api-generate.d.ts +0 -11
  15. package/src/api-generate.js +0 -133
  16. package/src/builder.d.ts +0 -2
  17. package/src/builder.js +0 -26
  18. package/src/cleanup.d.ts +0 -8
  19. package/src/cleanup.js +0 -97
  20. package/src/commands/api-generate.d.ts +0 -11
  21. package/src/commands/api-generate.js +0 -133
  22. package/src/commands/builder.d.ts +0 -2
  23. package/src/commands/builder.js +0 -26
  24. package/src/commands/cleanup.d.ts +0 -8
  25. package/src/commands/cleanup.js +0 -97
  26. package/src/commands/dev-go.d.ts +0 -8
  27. package/src/commands/dev-go.js +0 -306
  28. package/src/commands/develop.d.ts +0 -21
  29. package/src/commands/develop.js +0 -106
  30. package/src/commands/pack.d.ts +0 -82
  31. package/src/commands/pack.js +0 -230
  32. package/src/commands/postinstall.d.ts +0 -2
  33. package/src/commands/postinstall.js +0 -32
  34. package/src/commands/update.d.ts +0 -2
  35. package/src/commands/update.js +0 -22
  36. package/src/dev-go.d.ts +0 -8
  37. package/src/dev-go.js +0 -306
  38. package/src/develop.d.ts +0 -21
  39. package/src/develop.js +0 -106
  40. package/src/pack.d.ts +0 -82
  41. package/src/pack.js +0 -230
  42. package/src/postinstall.d.ts +0 -2
  43. package/src/postinstall.js +0 -32
  44. package/src/update.d.ts +0 -2
  45. package/src/update.js +0 -22
@@ -1,230 +0,0 @@
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.FILES_TO_COPY = exports.PACKAGE_JSON_CONTENT = exports.SERVER_EXECUTABLE = exports.PACK_CONFIG_PATH = exports.ORIGINAL_DIST_PATH = exports.SERVER_PATH = exports.ZIP_PATH = void 0;
49
- exports.builtPath = builtPath;
50
- exports.buildAndPack = buildAndPack;
51
- // 导入项目构建工具,用于执行 Nuxt 项目的构建流程
52
- const builder_1 = __importDefault(require("./builder"));
53
- // 导入 7zip 压缩工具库,用于将构建后的文件打包为 7z 格式
54
- const Zip = __importStar(require("7zip-min"));
55
- // 导入增强版的文件系统模块,提供更丰富的文件操作 API
56
- const FS = __importStar(require("fs-extra"));
57
- // 导入路径处理模块,用于规范化和解析文件路径
58
- const Path = __importStar(require("path"));
59
- const os = __importStar(require("os"));
60
- const fast_glob_1 = __importDefault(require("fast-glob"));
61
- /**
62
- * 生成相对于服务器构建目录的绝对路径
63
- * @param relativePath - 相对路径
64
- * @returns 解析后的绝对路径
65
- */
66
- function builtPath(relativePath) {
67
- return Path.resolve(exports.SERVER_PATH, relativePath);
68
- }
69
- // 定义打包后的 7z 文件输出路径
70
- exports.ZIP_PATH = Path.resolve(process.cwd(), ".build/production/server.7z");
71
- // 定义服务器构建文件的输出目录
72
- exports.SERVER_PATH = Path.resolve(process.cwd(), ".build/production/server");
73
- // 定义原始 dist 目录路径,用于清理操作
74
- exports.ORIGINAL_DIST_PATH = Path.resolve(process.cwd(), "dist");
75
- exports.PACK_CONFIG_PATH = Path.resolve(process.cwd(), "pack.config.json");
76
- exports.SERVER_EXECUTABLE = os.platform() === "win32" ? "server-production.exe" : "server-production"; // 根据操作系统选择可执行文件名
77
- // 定义打包后项目的 package.json 内容
78
- exports.PACKAGE_JSON_CONTENT = {
79
- private: true,
80
- scripts: {
81
- start: "./server-production.exe", // 定义启动命令
82
- },
83
- };
84
- // 定义需要复制到构建目录的文件映射关系(目标为构建目录下的相对路径)
85
- const DEFAULT_FILES_TO_COPY = {
86
- "vue/.output": "vue/.output", // Vue 应用构建输出
87
- [`.build/.server/production.exe`]: "server-production.exe", // 生产环境可执行文件
88
- "server.config.json": "server.config.json", // 服务器配置文件
89
- };
90
- // 兼容旧导出:默认构建目录下的绝对目标路径
91
- exports.FILES_TO_COPY = Object.fromEntries(Object.entries(DEFAULT_FILES_TO_COPY).map(([src, dest]) => [src, builtPath(dest)]));
92
- /**
93
- * 写入启动脚本和 package.json 文件到构建目录
94
- */
95
- function writeScriptFiles(serverPath, config) {
96
- // 写入 Windows 批处理启动脚本
97
- FS.outputFileSync(Path.resolve(serverPath, "start.bat"), `powershell -ExecutionPolicy ByPass -File ./start.ps1`);
98
- // 写入 PowerShell 启动脚本
99
- FS.outputFileSync(Path.resolve(serverPath, "start.ps1"), `./server-production.exe`);
100
- // 写入 Linux/macOS 启动脚本
101
- FS.outputFileSync(Path.resolve(serverPath, "start.sh"), `./server-production.exe`);
102
- // 写入 package.json 文件,使用 2 个空格缩进
103
- const mergedPackageJson = mergePackageJson(exports.PACKAGE_JSON_CONTENT, config === null || config === void 0 ? void 0 : config.packageJson);
104
- FS.outputJSONSync(Path.resolve(serverPath, "package.json"), mergedPackageJson, { spaces: 2 });
105
- }
106
- /**
107
- * 将配置的源文件复制到构建目录
108
- */
109
- function copyGeneratedFiles(serverPath, config) {
110
- var _a;
111
- const copyOptions = {
112
- overwrite: (config === null || config === void 0 ? void 0 : config.overwrite) !== false,
113
- errorOnExist: (config === null || config === void 0 ? void 0 : config.overwrite) === false,
114
- };
115
- // 遍历文件映射,将每个源文件复制到目标位置
116
- for (const [src, dest] of Object.entries(DEFAULT_FILES_TO_COPY)) {
117
- const resolvedDest = Path.resolve(serverPath, dest);
118
- FS.copySync(Path.resolve(process.cwd(), src), resolvedDest, copyOptions);
119
- }
120
- if (config === null || config === void 0 ? void 0 : config.extraFiles) {
121
- for (const [src, dest] of Object.entries(config.extraFiles)) {
122
- const resolvedSrc = Path.resolve(process.cwd(), src);
123
- const resolvedDest = Path.isAbsolute(dest) ? dest : Path.resolve(serverPath, dest);
124
- FS.copySync(resolvedSrc, resolvedDest, copyOptions);
125
- }
126
- }
127
- if ((_a = config === null || config === void 0 ? void 0 : config.extraFilesGlobs) === null || _a === void 0 ? void 0 : _a.length) {
128
- const matchedFiles = fast_glob_1.default.sync(config.extraFilesGlobs, {
129
- cwd: process.cwd(),
130
- onlyFiles: true,
131
- dot: true,
132
- ignore: config.exclude,
133
- });
134
- for (const file of matchedFiles) {
135
- const resolvedSrc = Path.resolve(process.cwd(), file);
136
- const resolvedDest = Path.resolve(serverPath, file);
137
- FS.copySync(resolvedSrc, resolvedDest, copyOptions);
138
- }
139
- }
140
- }
141
- function mergePackageJson(base, override) {
142
- if (!override) {
143
- return base;
144
- }
145
- const baseScripts = typeof base.scripts === "object" && base.scripts ? base.scripts : {};
146
- const overrideScripts = typeof override.scripts === "object" && override.scripts ? override.scripts : {};
147
- return Object.assign(Object.assign(Object.assign({}, base), override), { scripts: Object.assign(Object.assign({}, baseScripts), overrideScripts) });
148
- }
149
- function readPackConfigFromCwd() {
150
- if (!FS.existsSync(exports.PACK_CONFIG_PATH)) {
151
- return undefined;
152
- }
153
- return FS.readJSONSync(exports.PACK_CONFIG_PATH);
154
- }
155
- function resolveServerPath(config) {
156
- if (!(config === null || config === void 0 ? void 0 : config.serverPath)) {
157
- return exports.SERVER_PATH;
158
- }
159
- return Path.isAbsolute(config.serverPath)
160
- ? config.serverPath
161
- : Path.resolve(process.cwd(), config.serverPath);
162
- }
163
- function resolveZipPath(config) {
164
- if (config === null || config === void 0 ? void 0 : config.zipPath) {
165
- return Path.isAbsolute(config.zipPath)
166
- ? config.zipPath
167
- : Path.resolve(process.cwd(), config.zipPath);
168
- }
169
- if (config === null || config === void 0 ? void 0 : config.zipName) {
170
- return Path.resolve(Path.dirname(exports.ZIP_PATH), config.zipName);
171
- }
172
- return exports.ZIP_PATH;
173
- }
174
- /**
175
- * 打包文件为7z格式
176
- */
177
- function makeZip(serverPath, zipPath) {
178
- return new Promise((resolve, reject) => {
179
- // 使用 7zip 将服务器构建目录打包为 7z 文件
180
- Zip.pack(serverPath, zipPath, (error) => {
181
- if (error) {
182
- console.error("打包失败:", error);
183
- reject(error);
184
- }
185
- console.log("打包成功:", zipPath);
186
- resolve(zipPath);
187
- });
188
- });
189
- }
190
- /**
191
- * 清理原始 dist 目录
192
- */
193
- function cleanUp(config) {
194
- if ((config === null || config === void 0 ? void 0 : config.cleanDist) === false) {
195
- return;
196
- }
197
- // 检查原始 dist 目录是否存在,存在则删除
198
- if (FS.existsSync(exports.ORIGINAL_DIST_PATH)) {
199
- FS.removeSync(exports.ORIGINAL_DIST_PATH);
200
- }
201
- }
202
- /**
203
- * 构建并打包项目的主函数
204
- * 1. 执行项目构建
205
- * 2. 复制生成的文件
206
- * 3. 写入启动脚本
207
- * 4. 打包文件为 7z 格式
208
- * 5. 清理原始 dist 目录
209
- */
210
- function buildAndPack(config) {
211
- return __awaiter(this, void 0, void 0, function* () {
212
- const resolvedConfig = config !== null && config !== void 0 ? config : readPackConfigFromCwd();
213
- const serverPath = resolveServerPath(resolvedConfig);
214
- const zipPath = resolveZipPath(resolvedConfig);
215
- yield (0, builder_1.default)(); // 执行项目构建
216
- if (resolvedConfig === null || resolvedConfig === void 0 ? void 0 : resolvedConfig.beforePack) {
217
- yield resolvedConfig.beforePack();
218
- }
219
- copyGeneratedFiles(serverPath, resolvedConfig); // 复制相关文件
220
- if ((resolvedConfig === null || resolvedConfig === void 0 ? void 0 : resolvedConfig.writeScripts) !== false) {
221
- writeScriptFiles(serverPath, resolvedConfig); // 写入脚本文件
222
- }
223
- yield makeZip(serverPath, zipPath); // 打包文件
224
- if (resolvedConfig === null || resolvedConfig === void 0 ? void 0 : resolvedConfig.afterPack) {
225
- yield resolvedConfig.afterPack(zipPath);
226
- }
227
- cleanUp(resolvedConfig); // 清理临时文件
228
- });
229
- }
230
- exports.default = buildAndPack;
@@ -1,2 +0,0 @@
1
- export declare function postInstall(): Promise<import("concurrently").CloseEvent[]>;
2
- export default postInstall;
@@ -1,32 +0,0 @@
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.postInstall = postInstall;
7
- const concurrently_1 = __importDefault(require("concurrently"));
8
- const node_child_process_1 = require("node:child_process");
9
- function postInstall() {
10
- const hasGo = (0, node_child_process_1.spawnSync)("go", ["version"], { stdio: "ignore", shell: true }).status ===
11
- 0;
12
- const commands = [
13
- {
14
- command: "npx nuxt prepare",
15
- name: "nuxt",
16
- prefixColor: "blue",
17
- },
18
- ];
19
- if (hasGo) {
20
- commands.unshift({
21
- command: "go mod download && go mod tidy",
22
- name: "go",
23
- prefixColor: "green",
24
- });
25
- }
26
- else {
27
- console.warn("[nuxt-gin-tools] 未检测到 Go,已跳过 Go 相关安装。请先安装 Go 后再重新运行相关命令。");
28
- }
29
- // 执行并发命令
30
- return (0, concurrently_1.default)(commands).result;
31
- }
32
- exports.default = postInstall;
@@ -1,2 +0,0 @@
1
- export declare function update(): void;
2
- export default update;
@@ -1,22 +0,0 @@
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.update = update;
7
- const concurrently_1 = __importDefault(require("concurrently"));
8
- function update() {
9
- (0, concurrently_1.default)([
10
- {
11
- command: "pnpm update --latest",
12
- name: "pnpm",
13
- prefixColor: "magenta",
14
- },
15
- {
16
- command: "go get -u && go mod tidy",
17
- name: "go",
18
- prefixColor: "green",
19
- },
20
- ]);
21
- }
22
- exports.default = update;
package/src/dev-go.d.ts DELETED
@@ -1,8 +0,0 @@
1
- /**
2
- * 启动 Go 开发监听流程:执行 `go run main.go`,并在文件变更后自动重启。
3
- *
4
- * 该函数通常由 `develop()` 调用;执行后会持续监听,直到收到退出信号。
5
- *
6
- * @returns {Promise<void>} 仅在监听流程被中断并完成清理后返回。
7
- */
8
- export declare function startGoDev(): Promise<void>;
package/src/dev-go.js DELETED
@@ -1,306 +0,0 @@
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("./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
- }
package/src/develop.d.ts DELETED
@@ -1,21 +0,0 @@
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;