@dimina/compiler 1.0.12-beta.9 → 1.0.13

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,462 +1,2 @@
1
- import path from "node:path";
2
- import { fileURLToPath } from "node:url";
3
- import { Worker } from "node:worker_threads";
4
- import { Listr } from "listr2";
5
- import process from "node:process";
6
- import fs from "node:fs";
7
- import { g as getTargetPath, f as getAppId, k as getAppName, l as getPageConfigInfo, j as getAppConfigInfo, s as storeInfo, d as getWorkPath, m as getPages } from "./env-Csj3AHY4.js";
8
- import os from "node:os";
9
- const artCode = `
10
- ██████╗ ██╗███╗ ███╗██╗███╗ ██╗ █████╗
11
- ██╔══██╗██║████╗ ████║██║████╗ ██║██╔══██╗
12
- ██║ ██║██║██╔████╔██║██║██╔██╗ ██║███████║
13
- ██║ ██║██║██║╚██╔╝██║██║██║╚██╗██║██╔══██║
14
- ██████╔╝██║██║ ╚═╝ ██║██║██║ ╚████║██║ ██║
15
- ╚═════╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝
16
- `;
17
- function artCode$1() {
18
- console.log(artCode);
19
- }
20
- function createDist() {
21
- const distPath = getTargetPath();
22
- if (fs.existsSync(distPath)) {
23
- fs.rmSync(distPath, { recursive: true, force: true });
24
- }
25
- fs.mkdirSync(distPath, { recursive: true });
26
- }
27
- function publishToDist(dist, useAppIdDir = true) {
28
- const distPath = getTargetPath();
29
- const appId = getAppId();
30
- const absolutePath = useAppIdDir ? `${path.resolve(process.cwd(), dist)}${path.sep}${appId}` : `${path.resolve(process.cwd(), dist)}`;
31
- if (fs.existsSync(absolutePath)) {
32
- fs.rmSync(absolutePath, { recursive: true, force: true });
33
- }
34
- fs.mkdirSync(absolutePath, { recursive: true });
35
- function copyDir(src, dest) {
36
- fs.mkdirSync(dest, { recursive: true });
37
- const entries = fs.readdirSync(src, { withFileTypes: true });
38
- for (const entry of entries) {
39
- const srcPath = path.join(src, entry.name);
40
- const destPath = path.join(dest, entry.name);
41
- if (entry.isDirectory()) {
42
- copyDir(srcPath, destPath);
43
- } else {
44
- fs.copyFileSync(srcPath, destPath);
45
- }
46
- }
47
- }
48
- copyDir(distPath, absolutePath);
49
- }
50
- function getCGroupCPUCount() {
51
- try {
52
- const quotaPath = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us";
53
- const periodPath = "/sys/fs/cgroup/cpu/cpu.cfs_period_us";
54
- if (fs.existsSync(quotaPath) && fs.existsSync(periodPath)) {
55
- const quota = Number.parseInt(fs.readFileSync(quotaPath, "utf8"));
56
- const period = Number.parseInt(fs.readFileSync(periodPath, "utf8"));
57
- if (quota > 0) {
58
- return Math.max(1, Math.floor(quota / period));
59
- }
60
- }
61
- } catch (e) {
62
- console.warn("Failed to read CPU limits from cgroup:", e.message);
63
- }
64
- return os.cpus().length;
65
- }
66
- function getCGroupMemoryLimit() {
67
- try {
68
- const memLimitPath = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
69
- if (fs.existsSync(memLimitPath)) {
70
- const memLimit = Number.parseInt(fs.readFileSync(memLimitPath, "utf8"));
71
- if (memLimit < Number.Infinity && memLimit > 0) {
72
- return memLimit;
73
- }
74
- }
75
- } catch (e) {
76
- console.warn("Failed to read memory limits from cgroup:", e.message);
77
- }
78
- return os.totalmem();
79
- }
80
- const MAX_WORKERS = Math.max(1, Math.min(4, Math.floor(getCGroupCPUCount() / 4)));
81
- class WorkerPool {
82
- constructor(maxWorkers = MAX_WORKERS) {
83
- this.maxWorkers = maxWorkers;
84
- this.activeWorkers = 0;
85
- this.queue = [];
86
- this.memoryLimit = Math.floor(getCGroupMemoryLimit() * 0.6 / maxWorkers);
87
- }
88
- async runWorker(workerCreator) {
89
- if (this.activeWorkers >= this.maxWorkers) {
90
- await new Promise((resolve) => this.queue.push(resolve));
91
- }
92
- this.activeWorkers++;
93
- try {
94
- return await workerCreator();
95
- } finally {
96
- this.activeWorkers--;
97
- if (this.queue.length > 0) {
98
- const next = this.queue.shift();
99
- next();
100
- }
101
- }
102
- }
103
- getWorkerOptions() {
104
- const memoryMb = Math.floor(this.memoryLimit / (1024 * 1024));
105
- return {
106
- resourceLimits: {
107
- maxOldGenerationSizeMb: Math.max(256, memoryMb),
108
- // 最少 256MB
109
- maxYoungGenerationSizeMb: Math.max(64, Math.floor(memoryMb / 4)),
110
- // 最少 64MB
111
- codeRangeSizeMb: 64
112
- // 减少代码范围大小从 128MB 到 64MB
113
- }
114
- };
115
- }
116
- }
117
- const workerPool = new WorkerPool();
118
- class NpmBuilder {
119
- constructor(workPath, targetPath) {
120
- this.workPath = workPath;
121
- this.targetPath = targetPath;
122
- this.builtPackages = /* @__PURE__ */ new Set();
123
- this.packageDependencies = /* @__PURE__ */ new Map();
124
- }
125
- /**
126
- * 构建 npm 包
127
- * 扫描 miniprogram_npm 目录并构建相关包
128
- */
129
- async buildNpmPackages() {
130
- const miniprogramNpmPaths = this.findMiniprogramNpmDirs();
131
- for (const npmPath of miniprogramNpmPaths) {
132
- await this.buildNpmDir(npmPath);
133
- }
134
- }
135
- /**
136
- * 查找所有 miniprogram_npm 目录
137
- * @returns {string[]} miniprogram_npm 目录路径数组
138
- */
139
- findMiniprogramNpmDirs() {
140
- const npmDirs = [];
141
- const scanDir = (dir, relativePath = "") => {
142
- if (!fs.existsSync(dir)) {
143
- return;
144
- }
145
- const items = fs.readdirSync(dir, { withFileTypes: true });
146
- for (const item of items) {
147
- if (item.isDirectory()) {
148
- const itemPath = path.join(dir, item.name);
149
- const itemRelativePath = relativePath ? `${relativePath}/${item.name}` : item.name;
150
- if (item.name === "miniprogram_npm") {
151
- npmDirs.push(itemRelativePath);
152
- } else {
153
- scanDir(itemPath, itemRelativePath);
154
- }
155
- }
156
- }
157
- };
158
- scanDir(this.workPath);
159
- return npmDirs;
160
- }
161
- /**
162
- * 构建指定的 miniprogram_npm 目录
163
- * @param {string} npmDirPath miniprogram_npm 目录路径
164
- */
165
- async buildNpmDir(npmDirPath) {
166
- const fullNpmPath = path.join(this.workPath, npmDirPath);
167
- if (!fs.existsSync(fullNpmPath)) {
168
- return;
169
- }
170
- const packages = fs.readdirSync(fullNpmPath, { withFileTypes: true }).filter((item) => item.isDirectory()).map((item) => item.name);
171
- for (const packageName of packages) {
172
- await this.buildPackage(packageName, npmDirPath);
173
- }
174
- }
175
- /**
176
- * 构建单个 npm 包
177
- * @param {string} packageName 包名
178
- * @param {string} npmDirPath miniprogram_npm 目录路径
179
- */
180
- async buildPackage(packageName, npmDirPath) {
181
- const packageKey = `${npmDirPath}/${packageName}`;
182
- if (this.builtPackages.has(packageKey)) {
183
- return;
184
- }
185
- const packagePath = path.join(this.workPath, npmDirPath, packageName);
186
- const targetPackagePath = path.join(this.targetPath, npmDirPath, packageName);
187
- if (!fs.existsSync(path.dirname(targetPackagePath))) {
188
- fs.mkdirSync(path.dirname(targetPackagePath), { recursive: true });
189
- }
190
- await this.copyPackageFiles(packagePath, targetPackagePath);
191
- await this.processDependencies(packageName, packagePath, npmDirPath);
192
- this.builtPackages.add(packageKey);
193
- }
194
- /**
195
- * 复制包文件
196
- * @param {string} sourcePath 源路径
197
- * @param {string} targetPath 目标路径
198
- */
199
- async copyPackageFiles(sourcePath, targetPath) {
200
- if (!fs.existsSync(sourcePath)) {
201
- return;
202
- }
203
- if (!fs.existsSync(targetPath)) {
204
- fs.mkdirSync(targetPath, { recursive: true });
205
- }
206
- const items = fs.readdirSync(sourcePath, { withFileTypes: true });
207
- for (const item of items) {
208
- const sourceItemPath = path.join(sourcePath, item.name);
209
- const targetItemPath = path.join(targetPath, item.name);
210
- if (item.isDirectory()) {
211
- await this.copyPackageFiles(sourceItemPath, targetItemPath);
212
- } else {
213
- if (this.isMiniprogramFile(item.name)) {
214
- fs.copyFileSync(sourceItemPath, targetItemPath);
215
- }
216
- }
217
- }
218
- }
219
- /**
220
- * 检查是否为小程序相关文件
221
- * @param {string} filename 文件名
222
- * @returns {boolean} 是否为小程序文件
223
- */
224
- isMiniprogramFile(filename) {
225
- const miniprogramExts = [".js", ".json", ".wxml", ".wxss", ".wxs", ".ts", ".less", ".scss", ".styl"];
226
- const ext = path.extname(filename).toLowerCase();
227
- return miniprogramExts.includes(ext) || filename === "package.json" || filename === "README.md" || filename.startsWith(".");
228
- }
229
- /**
230
- * 处理包依赖
231
- * @param {string} packageName 包名
232
- * @param {string} packagePath 包路径
233
- * @param {string} npmDirPath npm 目录路径
234
- */
235
- async processDependencies(packageName, packagePath, npmDirPath) {
236
- const packageJsonPath = path.join(packagePath, "package.json");
237
- if (!fs.existsSync(packageJsonPath)) {
238
- return;
239
- }
240
- try {
241
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
242
- const dependencies = {
243
- ...packageJson.dependencies,
244
- ...packageJson.peerDependencies
245
- };
246
- if (dependencies && Object.keys(dependencies).length > 0) {
247
- this.packageDependencies.set(packageName, dependencies);
248
- for (const depName of Object.keys(dependencies)) {
249
- await this.buildPackage(depName, npmDirPath);
250
- }
251
- }
252
- } catch (e) {
253
- console.warn(`[npm-builder] 解析 package.json 失败: ${packageJsonPath}`, e.message);
254
- }
255
- }
256
- /**
257
- * 验证 npm 包的完整性
258
- * @param {string} packageName 包名
259
- * @param {string} packagePath 包路径
260
- * @returns {boolean} 是否有效
261
- */
262
- validatePackage(packageName, packagePath) {
263
- const requiredFiles = ["package.json"];
264
- for (const file of requiredFiles) {
265
- if (!fs.existsSync(path.join(packagePath, file))) {
266
- console.warn(`[npm-builder] 包 ${packageName} 缺少必要文件: ${file}`);
267
- return false;
268
- }
269
- }
270
- try {
271
- const packageJsonPath = path.join(packagePath, "package.json");
272
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
273
- if (!packageJson.name || !packageJson.version) {
274
- console.warn(`[npm-builder] 包 ${packageName} 的 package.json 格式不正确`);
275
- return false;
276
- }
277
- } catch (e) {
278
- console.warn(`[npm-builder] 包 ${packageName} 的 package.json 解析失败:`, e.message);
279
- return false;
280
- }
281
- return true;
282
- }
283
- /**
284
- * 获取已构建的包列表
285
- * @returns {string[]} 已构建的包列表
286
- */
287
- getBuiltPackages() {
288
- return Array.from(this.builtPackages);
289
- }
290
- /**
291
- * 获取包依赖关系
292
- * @returns {Map} 包依赖关系映射
293
- */
294
- getPackageDependencies() {
295
- return this.packageDependencies;
296
- }
297
- /**
298
- * 清理构建缓存
299
- */
300
- clearCache() {
301
- this.builtPackages.clear();
302
- this.packageDependencies.clear();
303
- }
304
- }
305
- function compileConfig() {
306
- const compileResInfo = {
307
- app: getAppConfigInfo(),
308
- modules: getPageConfigInfo(),
309
- projectName: getAppName()
310
- };
311
- const json = JSON.stringify(compileResInfo, null, 4);
312
- const mainDir = `${getTargetPath()}/main`;
313
- if (!fs.existsSync(mainDir)) {
314
- fs.mkdirSync(mainDir, { recursive: true });
315
- }
316
- fs.writeFileSync(`${mainDir}/app-config.json`, json);
317
- }
318
- let isPrinted = false;
319
- async function build(targetPath, workPath, useAppIdDir = true) {
320
- if (!isPrinted) {
321
- artCode$1();
322
- isPrinted = true;
323
- }
324
- const tasks = new Listr(
325
- [
326
- {
327
- title: "准备项目编译环境",
328
- task: (_, task) => task.newListr(
329
- [
330
- {
331
- title: "收集配置信息",
332
- task: (ctx) => {
333
- ctx.storeInfo = storeInfo(workPath);
334
- }
335
- },
336
- {
337
- title: "准备产物目录",
338
- task: () => {
339
- createDist();
340
- }
341
- },
342
- {
343
- title: "编译配置信息",
344
- task: () => {
345
- compileConfig();
346
- }
347
- },
348
- {
349
- title: "构建 npm 包",
350
- task: async () => {
351
- const npmBuilder = new NpmBuilder(getWorkPath(), getTargetPath());
352
- await npmBuilder.buildNpmPackages();
353
- }
354
- }
355
- ],
356
- { concurrent: false }
357
- )
358
- },
359
- {
360
- title: `开始编译:${workPath.split("/").pop()}`,
361
- task: (ctx, task) => {
362
- const pages = getPages();
363
- ctx.pages = pages;
364
- return task.newListr(
365
- [
366
- {
367
- title: "编译页面文件",
368
- task: async (ctx2, task2) => {
369
- return runCompileInWorker("view", ctx2, task2);
370
- }
371
- },
372
- {
373
- title: "编译页面逻辑",
374
- task: async (ctx2, task2) => {
375
- return runCompileInWorker("logic", ctx2, task2);
376
- }
377
- },
378
- {
379
- title: "编译样式文件",
380
- task: async (ctx2, task2) => {
381
- pages.mainPages.unshift({
382
- path: "app",
383
- id: ""
384
- });
385
- return runCompileInWorker("style", ctx2, task2);
386
- }
387
- }
388
- ],
389
- { concurrent: true }
390
- );
391
- }
392
- },
393
- {
394
- title: "输出编译产物",
395
- task: () => {
396
- publishToDist(targetPath, useAppIdDir);
397
- }
398
- }
399
- ],
400
- { concurrent: false }
401
- );
402
- try {
403
- const context = await tasks.run();
404
- return {
405
- appId: getAppId(),
406
- name: getAppName(),
407
- path: getAppConfigInfo().entryPagePath || context.pages.mainPages[1].path
408
- };
409
- } catch (e) {
410
- console.error(`${workPath} 编译出错: ${e.message}
411
- ${e.stack}`);
412
- }
413
- }
414
- function runCompileInWorker(script, ctx, task) {
415
- return workerPool.runWorker(() => new Promise((resolve, reject) => {
416
- const worker = new Worker(
417
- path.join(path.dirname(fileURLToPath(import.meta.url)), `core/${script}-compiler.js`),
418
- workerPool.getWorkerOptions()
419
- );
420
- const totalTasks = Object.keys(ctx.pages.mainPages).length + Object.values(ctx.pages.subPages).reduce((sum, item) => sum + item.info.length, 0);
421
- worker.postMessage({ pages: ctx.pages, storeInfo: ctx.storeInfo });
422
- worker.on("message", (message) => {
423
- try {
424
- if (message.completedTasks) {
425
- const progress = message.completedTasks / totalTasks;
426
- const percentage = progress * 100;
427
- const barLength = 30;
428
- const filledLength = Math.ceil(barLength * progress);
429
- const bar = "█".repeat(filledLength) + "░".repeat(barLength - filledLength);
430
- task.output = `[${bar}] ${percentage.toFixed(2)}%`;
431
- }
432
- if (message.success) {
433
- resolve();
434
- worker.terminate();
435
- } else if (message.error) {
436
- const error = new Error(message.error.message || message.error);
437
- if (message.error.stack)
438
- error.stack = message.error.stack;
439
- if (message.error.file)
440
- error.file = message.error.file;
441
- if (message.error.line)
442
- error.line = message.error.line;
443
- reject(error);
444
- worker.terminate();
445
- }
446
- } catch (err) {
447
- reject(new Error(`Error processing worker message: ${err.message}
448
- ${err.stack}`));
449
- worker.terminate();
450
- }
451
- });
452
- worker.on("error", reject);
453
- worker.on("exit", (code) => {
454
- if (code !== 0) {
455
- reject(new Error(`Worker stopped with exit code ${code}`));
456
- }
457
- });
458
- }));
459
- }
460
- export {
461
- build as default
462
- };
1
+ import { t as build } from "./src-D9P-SZeX.js";
2
+ export { build as default };